Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
feat: MDX-backed Content Blocks (#6234)
Oleg Isonenf9681dc30f39
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsxindex 6ba4b93011..4a8553b124 100644--- a/apps/builder/app/builder/builder.tsx+++ b/apps/builder/app/builder/builder.tsx@@ -70,6 +70,7 @@ import { KeyboardShortcutsDialog } from "./features/keyboard-shortcuts-dialog";import { TokenConflictDialog } from "~/shared/token-conflict-dialog";import { RootStyleConflictDialog } from "~/shared/root-style-conflict-dialog";import { DesignTokenImportDialog } from "~/shared/design-token-import-dialog";+import { TemplateNameConfirmationDialog } from "./features/template-name-confirmation-dialog";import type { User } from "~/shared/db/user.server";import {@@ -529,6 +530,7 @@ export const Builder = (props: BuilderProps) => {<DesignTokenImportDialog /><TokenConflictDialog /><RootStyleConflictDialog />+ <TemplateNameConfirmationDialog /><RemoteDialog /><Toaster /></div>diff --git a/apps/builder/app/builder/features/command-panel/groups/wrap-group.test.tsx b/apps/builder/app/builder/features/command-panel/groups/wrap-group.test.tsxindex 8e62e639b9..c71bb140cd 100644--- a/apps/builder/app/builder/features/command-panel/groups/wrap-group.test.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/wrap-group.test.tsx@@ -94,7 +94,7 @@ describe("canWrapInstance for components", () => {expect(result).toBe(true);});- test("should allow wrapping text in a legacy CodeText", () => {+ test("should prevent wrapping an instance in CodeText", () => {$instances.set(renderData(<$.Body ws:id="body">@@ -114,7 +114,7 @@ describe("canWrapInstance for components", () => {$props.get(),$registeredComponentMetas.get());- expect(result).toBe(true);+ expect(result).toBe(false);});});diff --git a/apps/builder/app/builder/features/navigator/navigator-tree.test.ts b/apps/builder/app/builder/features/navigator/navigator-tree.test.tsindex d2e08fcd2c..27baf72001 100644--- a/apps/builder/app/builder/features/navigator/navigator-tree.test.ts+++ b/apps/builder/app/builder/features/navigator/navigator-tree.test.ts@@ -1,11 +1,18 @@-import { beforeEach, describe, expect, test } from "vitest";-import { blockComponent } from "@webstudio-is/sdk";-import { __testing__ } from "./navigator-tree";+import { afterEach, beforeEach, describe, expect, test } from "vitest";+import {+ blockBodyComponent,+ blockComponent,+ elementComponent,+} from "@webstudio-is/sdk";+import { $flatTree, __testing__ } from "./navigator-tree";import {$allSelectedInstanceSelectors,+ $builderMode,+ $selectedPageId,selectInstances,} from "~/shared/nano-states";-import { $instances } from "~/shared/sync/data-stores";+import { $instances, $pages } from "~/shared/sync/data-stores";+import { $externalContentRoots } from "~/shared/external-content-mutations";const {commitNavigatorDrop,@@ -87,6 +94,181 @@ const createTreeItem = ({};};+test("shows connected Content Block instances in Content mode", () => {+ $pages.set({+ homePageId: "home",+ rootFolderId: "root",+ pages: new Map([+ [+ "home",+ {+ id: "home",+ name: "Home",+ path: "",+ title: "Home",+ meta: {},+ rootInstanceId: "body",+ },+ ],+ ]),+ folders: new Map([+ ["root", { id: "root", name: "Root", slug: "", children: ["home"] }],+ ]),+ });+ $instances.set(+ new Map([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [{ type: "id", value: "block" }],+ },+ ],+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "heading" }],+ },+ ],+ [+ "heading",+ {+ type: "instance",+ id: "heading",+ component: elementComponent,+ tag: "h1",+ children: [{ type: "text", value: "MDX heading" }],+ },+ ],+ ])+ );+ $selectedPageId.set("home");+ $builderMode.set("content");+ expect($flatTree.get().map(({ instance }) => instance.id)).toEqual([+ "block",+ "heading",+ ]);+});++test("shows the scoped Content Block occurrence in Content mode", () => {+ $pages.set({+ homePageId: "home",+ rootFolderId: "root",+ pages: new Map([+ [+ "home",+ {+ id: "home",+ name: "Home",+ path: "",+ title: "Home",+ meta: {},+ rootInstanceId: "body",+ },+ ],+ ]),+ folders: new Map([+ ["root", { id: "root", name: "Root", slug: "", children: ["home"] }],+ ]),+ });+ $instances.set(+ new Map([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [{ type: "id", value: "block" }],+ },+ ],+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "content" }],+ },+ ],+ [+ "content",+ {+ type: "instance",+ id: "content",+ component: blockBodyComponent,+ children: [],+ },+ ],+ [+ "scoped-block",+ {+ type: "instance",+ id: "scoped-block",+ component: blockComponent,+ children: [{ type: "id", value: "content" }],+ },+ ],+ [+ "scoped-content",+ {+ type: "instance",+ id: "scoped-content",+ component: blockBodyComponent,+ children: [{ type: "id", value: "scoped-heading" }],+ },+ ],+ [+ "scoped-heading",+ {+ type: "instance",+ id: "scoped-heading",+ component: elementComponent,+ tag: "h1",+ children: [{ type: "text", value: "Scoped MDX heading" }],+ },+ ],+ ])+ );+ $selectedPageId.set("home");+ $builderMode.set("content");+ $externalContentRoots.set(+ new Map([+ [+ "root",+ {+ sourceBlockInstanceId: "block",+ sourceRenderScope: '["block","body"]',+ blockInstanceId: "scoped-block",+ sourceContentInstanceId: "content",+ contentInstanceId: "scoped-content",+ renderScope: '["scoped-block","body"]',+ instanceIds: new Set(["scoped-heading"]),+ mutationRevision: 0,+ },+ ],+ ])+ );++ expect($flatTree.get().map(({ instance }) => instance.id)).toEqual([+ "scoped-block",+ "scoped-content",+ ]);+});++afterEach(() => {+ $builderMode.set("design");+ $selectedPageId.set(undefined);+ $pages.set(undefined);+ $instances.set(new Map());+ $externalContentRoots.set(new Map());+});+describe("getNavigatorSelectionUpdate", () => {beforeEach(() => {selectInstances([]);diff --git a/apps/builder/app/builder/features/navigator/navigator-tree.tsx b/apps/builder/app/builder/features/navigator/navigator-tree.tsxindex fed26bb58a..3ff1bb7169 100644--- a/apps/builder/app/builder/features/navigator/navigator-tree.tsx+++ b/apps/builder/app/builder/features/navigator/navigator-tree.tsx@@ -2,7 +2,7 @@ import {reparentInstance,toggleInstanceShow,} from "~/shared/instance-utils/mutation";-import { useEffect, useMemo, useRef } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import { atom, computed } from "nanostores";import { mergeRefs } from "@react-aria/utils";import { useStore } from "@nanostores/react";@@ -27,6 +27,7 @@ import { showAttribute, getCollectionEntries } from "@webstudio-is/react-sdk";import {ROOT_INSTANCE_ID,collectionComponent,+ blockBodyComponent,blockComponent,rootComponent,blockTemplateComponent,@@ -74,8 +75,17 @@ import {} from "@webstudio-is/project-build/runtime";import { emitCommand } from "~/builder/shared/commands";import { useContentEditable } from "~/shared/dom-hooks";-import { executeRuntimeMutation } from "~/shared/instance-utils/data";+import {+ executeRuntimeMutation,+ getDuplicateTemplateNameMessage,+} from "~/shared/instance-utils/data";import { isRichTextContent } from "@webstudio-is/project-build/runtime";+import {+ $externalContentRoots,+ externalContentInstanceNameMessage,+ isExternalContentInstance,+ resolveExternalContentOccurrence,+} from "~/shared/external-content-mutations";import {getInstanceLabel,InstanceIcon,@@ -224,6 +234,7 @@ export const $flatTree = computed($propValuesByInstanceSelector,$dropTarget,$isContentMode,+ $externalContentRoots,],(page,@@ -231,7 +242,8 @@ export const $flatTree = computed(expandedItems,propValuesByInstanceSelector,dropTarget,- isContentMode+ isContentMode,+ externalContentRoots) => {const flatTree: TreeItem[] = [];if (page === undefined) {@@ -246,12 +258,28 @@ export const $flatTree = computed(isLastChild = false,indexWithinChildren = 0) => {- const instance = instances.get(instanceId);+ let instance = instances.get(instanceId);if (instance === undefined) {// log instead of failing navigator treeconsole.error(`Unknown instance ${instanceId}`);return;}+ if (+ isContentMode &&+ (instance.component === blockComponent ||+ instance.component === blockBodyComponent)+ ) {+ const occurrence = resolveExternalContentOccurrence({+ sourceInstance: instance,+ sourceSelector: selector,+ instances,+ roots: externalContentRoots,+ });+ if (occurrence !== undefined) {+ instance = occurrence.instance;+ selector = occurrence.selector;+ }+ }const propValues = propValuesByInstanceSelector.get(getInstanceKey(selector));@@ -502,44 +530,73 @@ const EditableTreeNodeLabel = styled("div", {userSelect: "text",},},+ hasError: {+ true: {+ outline: `1px solid ${theme.colors.borderDestructiveMain}`,+ },+ },},});const TreeNodeContent = ({instance,isEditing,+ isNameEditable,onIsEditingChange,}: {instance: Instance;isEditing: boolean;+ isNameEditable: boolean;onIsEditingChange: (isEditing: boolean) => void;}) => {const editableRef = useRef<HTMLDivElement | null>(null);+ const [error, setError] = useState<string>();const label = getInstanceLabel(instance);const { ref, handlers } = useContentEditable({value: label,- isEditable: true,- isEditing,+ isEditable: isNameEditable,+ isEditing: isNameEditable && isEditing,onChangeValue: (value: string) => {- executeRuntimeMutation({- id: "instances.setLabel",- input: { instanceId: instance.id, label: value },- });- editableRef.current?.closest("button")?.focus();+ if (isExternalContentInstance($externalContentRoots.get(), instance.id)) {+ return;+ }+ try {+ executeRuntimeMutation({+ id: "instances.setLabel",+ input: { instanceId: instance.id, label: value },+ });+ setError(undefined);+ editableRef.current?.closest("button")?.focus();+ } catch (error) {+ const message = getDuplicateTemplateNameMessage(error);+ if (message === undefined) {+ throw error;+ }+ setError(message);+ onIsEditingChange(true);+ }},onChangeEditing: onIsEditingChange,});return (<TreeNodeLabel prefix={<InstanceIcon instance={instance} />}>- <EditableTreeNodeLabel- ref={mergeRefs(editableRef, ref)}- {...handlers}- isEditing={isEditing}+ <Tooltip+ content={isNameEditable ? error : externalContentInstanceNameMessage}+ delayDuration={0}>- {label}- </EditableTreeNodeLabel>+ <EditableTreeNodeLabel+ ref={mergeRefs(editableRef, ref)}+ {...handlers}+ isEditing={isEditing}+ hasError={error !== undefined}+ aria-invalid={error === undefined ? undefined : true}+ onInput={() => setError(undefined)}+ >+ {label}+ </EditableTreeNodeLabel>+ </Tooltip></TreeNodeLabel>);};@@ -704,6 +761,7 @@ const commitNavigatorDrop = ({export const NavigatorTree = () => {const isContentMode = useStore($isContentMode);const flatTree = useStore($flatTree);+ const externalContentRoots = useStore($externalContentRoots);const selectedInstanceSelectors = useStore($allSelectedInstanceSelectors);const selectedInstanceSelector = useStore($selectedInstanceSelector);const selectedKeys = useMemo(@@ -1111,6 +1169,12 @@ export const NavigatorTree = () => {><TreeNodeContentinstance={item.instance}+ isNameEditable={+ isExternalContentInstance(+ externalContentRoots,+ item.instance.id+ ) === false+ }isEditing={areInstanceSelectorsEqual(item.selector,editingItemSelectordiff --git a/apps/builder/app/builder/features/publish/publish.tsx b/apps/builder/app/builder/features/publish/publish.tsxindex 97508b4685..594370b2f7 100644--- a/apps/builder/app/builder/features/publish/publish.tsx+++ b/apps/builder/app/builder/features/publish/publish.tsx@@ -55,7 +55,7 @@ import {$stagingUsername,$stagingPassword,} from "~/shared/nano-states";-import { $publisherHost } from "~/shared/sync/data-stores";+import { $assets, $publisherHost } from "~/shared/sync/data-stores";import {$publishDialog,setActiveSidebarPanel,@@ -104,6 +104,7 @@ import {} from "@webstudio-is/project-build/runtime";import { showContentDatabasePublishWarning } from "./content-database-publish-warning";import { showPublishWarning } from "./publish-warning";+import { flushExternalContentProject } from "~/shared/external-content-roots";const PrePublishAuditMessage = ({finding,@@ -173,6 +174,7 @@ const getPrePublishAuditMessages = () => {props: $props.get(),dataSources: $dataSources.get(),resources: $resources.get(),+ assets: $assets.get(),metas: $registeredComponentMetas.get(),});const getMessage = (severity: PrePublishAuditFinding["severity"]) => {@@ -629,20 +631,6 @@ const Publish = ({setPublishError(undefined);setPublishWarning(undefined);- const { error: auditError, warning: auditWarning } =- getPrePublishAuditMessages();- if (auditError !== undefined) {- toast.error(auditError);- setPublishError(auditError);- return;- }- if (auditWarning !== undefined) {- showPublishWarning({- message: auditWarning,- setWarning: setPublishWarning,- });- }-// Custom domain checkboxes are disabled on free plan so they are never// submitted — only the staging (wstd.io) domain can appear in formData.const domains = formData@@ -658,6 +646,20 @@ const Publish = ({setIsPublishing(true);try {+ await flushExternalContentProject({ projectId: project.id });+ const { error: auditError, warning: auditWarning } =+ getPrePublishAuditMessages();+ if (auditError !== undefined) {+ toast.error(auditError);+ setPublishError(auditError);+ return;+ }+ if (auditWarning !== undefined) {+ showPublishWarning({+ message: auditWarning,+ setWarning: setPublishWarning,+ });+ }await showContentDatabasePublishWarning({projectId: project.id,setWarning: setPublishWarning,diff --git a/apps/builder/app/builder/features/settings-panel/controls/boolean.tsx b/apps/builder/app/builder/features/settings-panel/controls/boolean.tsxindex 31abe5bd52..1b5ef96782 100644--- a/apps/builder/app/builder/features/settings-panel/controls/boolean.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/boolean.tsx@@ -14,7 +14,7 @@ export const BooleanControl = ({}: ControlProps<"boolean">) => {const label = humanizeAttribute(meta.label || propName);const binding = useBindableControl({- boundExpression: prop?.type === "expression" ? prop.value : undefined,+ boundExpression: prop?.type === "expression" ? prop : undefined,fallbackExpression: JSON.stringify(computedValue),});diff --git a/apps/builder/app/builder/features/settings-panel/controls/check.tsx b/apps/builder/app/builder/features/settings-panel/controls/check.tsxindex c71ed2e85a..b945570e34 100644--- a/apps/builder/app/builder/features/settings-panel/controls/check.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/check.tsx@@ -41,7 +41,7 @@ export const CheckControl = ({const id = useId();const label = humanizeAttribute(meta.label || propName);const binding = useBindableControl({- boundExpression: prop?.type === "expression" ? prop.value : undefined,+ boundExpression: prop?.type === "expression" ? prop : undefined,fallbackExpression: JSON.stringify(computedValue),});diff --git a/apps/builder/app/builder/features/settings-panel/controls/code.tsx b/apps/builder/app/builder/features/settings-panel/controls/code.tsxindex 2efea1cb0f..6a83436a41 100644--- a/apps/builder/app/builder/features/settings-panel/controls/code.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/code.tsx@@ -63,7 +63,7 @@ export const matchCodeTextEditorLanguage = (selectedLanguage: unknown) => {);};-const useCodeTextLanguageSupport = (selectedLanguage: unknown) => {+export const useCodeTextLanguageSupport = (selectedLanguage: unknown) => {const [languageSupport, setLanguageSupport] = useState<LanguageSupport>();useEffect(() => {@@ -163,10 +163,14 @@ export const CodeControl = ({const editorValue = behavior? behavior.formatValue(computedValue): String(computedValue ?? "");+ const binding = useBindableControl({+ boundExpression: prop?.type === "expression" ? prop : undefined,+ fallbackExpression: JSON.stringify(computedValue),+ });const localValue = useDraftValue(editorValue,(value) => {- if (prop?.type === "expression") {+ if (binding.bindingState.overwritable === false) {return;}let storedValue = value;@@ -198,11 +202,6 @@ export const CodeControl = ({{ autoSave: behavior?.autoSave ?? true });- const binding = useBindableControl({- boundExpression: prop?.type === "expression" ? prop.value : undefined,- fallbackExpression: JSON.stringify(computedValue),- });-const errorInfo = (<ErrorInfoerror={error}diff --git a/apps/builder/app/builder/features/settings-panel/controls/content-block-source-controller.test.ts b/apps/builder/app/builder/features/settings-panel/controls/content-block-source-controller.test.tsnew file mode 100644index 0000000000..dbe1333d6c--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/controls/content-block-source-controller.test.ts@@ -0,0 +1,168 @@+import { expect, test, vi } from "vitest";+import { createDefaultPages } from "@webstudio-is/project-build";+import {+ blockComponent,+ blockTemplateComponent,+ elementComponent,+} from "@webstudio-is/sdk";+import { applyBuilderPatchTransactions } from "@webstudio-is/project-build/state";+import { createContentBlockSourceController } from "./content-block-source-controller";++const createState = () => ({+ pages: createDefaultPages({ rootInstanceId: "block" }),+ instances: new Map([+ [+ "block",+ {+ type: "instance" as const,+ id: "block",+ component: blockComponent,+ children: [+ { type: "id" as const, value: "templates" },+ { type: "id" as const, value: "body" },+ ],+ },+ ],+ [+ "templates",+ {+ type: "instance" as const,+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ [+ "body",+ {+ type: "instance" as const,+ id: "body",+ component: elementComponent,+ tag: "p",+ children: [{ type: "text" as const, value: "Existing" }],+ },+ ],+ ]),+ props: new Map(),+ dataSources: new Map(),+ resources: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ breakpoints: new Map(),+ assets: new Map(),+});++test("validates before confirmation and revalidates before replacing existing content", async () => {+ let state = createState();+ let currentName = "article_v1.mdx";+ const openAsset = vi.fn(async () => ({+ asset: {+ id: "asset",+ projectId: "project",+ name: currentName,+ type: "file" as const,+ format: "mdx",+ size: 0,+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ source: "",+ status: "saved" as const,+ }));+ const reloadAsset = vi.fn(async (_assetId: string, expectedName: string) => {+ if (expectedName !== currentName) {+ throw new Error("Revision conflict");+ }+ return openAsset();+ });+ const controller = createContentBlockSourceController({+ blockInstanceId: "block",+ renderScope: '["block"]',+ projectId: "project",+ getState: () => state,+ openAsset,+ reloadAsset,+ resolveExpressionAssetId: () => undefined,+ flushAsset: vi.fn(),+ updateAssetSource: vi.fn(),+ commitProjectPayload: (payload) => {+ state = applyBuilderPatchTransactions(state, [+ { id: "test", payload: [...payload] },+ ]).state as typeof state;+ },+ });++ await expect(+ controller.requestSource({+ source: { type: "asset", assetId: "asset" },+ })+ ).resolves.toEqual({ status: "requires-confirmation", diagnostics: [] });+ expect(openAsset).toHaveBeenCalledOnce();+ expect(state.instances.get("body")).toBeDefined();++ await expect(+ controller.requestSource({+ source: { type: "asset", assetId: "asset" },+ confirmed: true,+ })+ ).resolves.toMatchObject({ status: "applied" });+ expect(reloadAsset).toHaveBeenCalledWith("asset", "article_v1.mdx");+ expect(state.instances.has("body")).toBe(false);+ expect(+ Array.from(state.props.values()).find(+ (prop) => prop.instanceId === "block" && prop.name === "src"+ )+ ).toMatchObject({+ type: "asset",+ value: "asset",+ });+});++test("disconnects without loading or copying the Asset source", async () => {+ let state = createState();+ state.props.set("src", {+ id: "src",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "asset",+ });+ const source = "# From MDX";+ const openAsset = vi.fn(async () => ({+ asset: {+ id: "asset",+ projectId: "project",+ name: "article.mdx",+ type: "file" as const,+ format: "mdx",+ size: new TextEncoder().encode(source).byteLength,+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ source,+ status: "saved" as const,+ }));+ const controller = createContentBlockSourceController({+ blockInstanceId: "block",+ renderScope: '["block"]',+ projectId: "project",+ getState: () => state,+ openAsset,+ reloadAsset: vi.fn(),+ resolveExpressionAssetId: () => undefined,+ flushAsset: vi.fn(),+ updateAssetSource: vi.fn(),+ commitProjectPayload: (payload) => {+ state = applyBuilderPatchTransactions(state, [+ { id: "test", payload: [...payload] },+ ]).state as typeof state;+ },+ });++ await expect(controller.disconnect()).resolves.toEqual({ status: "applied" });+ expect(openAsset).not.toHaveBeenCalled();+ expect(state.props.has("src")).toBe(false);+ expect(state.instances.get("block")?.children).toEqual([+ { type: "id", value: "templates" },+ { type: "id", value: "body" },+ ]);+});diff --git a/apps/builder/app/builder/features/settings-panel/controls/content-block-source-controller.ts b/apps/builder/app/builder/features/settings-panel/controls/content-block-source-controller.tsnew file mode 100644index 0000000000..aa2e978041--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/controls/content-block-source-controller.ts@@ -0,0 +1,273 @@+import type { AssetContentSessionState } from "@webstudio-is/content-engine/asset-content-session";+import type { BuilderPatchChange } from "@webstudio-is/project-build/contracts";+import type { BuilderState } from "@webstudio-is/project-build/state";+import { createContentBlockApplication } from "@webstudio-is/project-build/runtime";+import {+ getContentBlockSource,+ isEqualContentBlockSource,+ type ContentBlockDiagnostic,+ type ContentBlockSource,+} from "@webstudio-is/sdk";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";+import { $variableValuesByInstanceSelector } from "~/shared/nano-states";+import { getWebstudioData } from "~/shared/instance-utils/data";+import { createTransactionFromBuilderPatchPayload } from "~/shared/sync/builder-patch";+import { readBuilderStateStores } from "~/shared/sync/data-stores";+import {+ flushExternalContentAsset,+ openExternalContentAsset,+ reloadExternalContentAsset,+ updateExternalContentAssetSource,+} from "~/shared/external-content-roots";+import {+ parseContentBlockRenderScope,+ resolveContentBlockOccurrenceAssetId,+} from "~/shared/content-block-source-utils";++type MutationResult =+ | Readonly<{ status: "applied"; state?: AssetContentSessionState }>+ | Readonly<{ status: "blocked"; message: string }>;++export type ContentBlockSourceControllerResult =+ | MutationResult+ | Readonly<{+ status: "requires-confirmation";+ diagnostics: readonly ContentBlockDiagnostic[];+ }>;++export const createContentBlockSourceController = ({+ blockInstanceId,+ renderScope,+ projectId,+ getState,+ openAsset,+ reloadAsset,+ resolveExpressionAssetId,+ flushAsset,+ updateAssetSource,+ commitProjectPayload,+}: {+ blockInstanceId: string;+ renderScope: string;+ projectId: string;+ getState: () => BuilderState;+ openAsset: (assetId: string) => Promise<AssetContentSessionState>;+ reloadAsset: (+ assetId: string,+ expectedName: string+ ) => Promise<AssetContentSessionState>;+ resolveExpressionAssetId: (+ expression: string,+ renderScope: string+ ) => string | undefined;+ flushAsset: (assetId: string) => Promise<unknown>;+ updateAssetSource: (+ assetId: string,+ update: (source: string) => string | Promise<string>+ ) => Promise<unknown>;+ commitProjectPayload: (payload: readonly BuilderPatchChange[]) => void;+}) => {+ const stagedSources = new Map<string, string>();+ const application = createContentBlockApplication({+ projectId,+ metas: componentMetas,+ resolveSourceAssetId: ({ source }) =>+ source.type === "asset"+ ? source.assetId+ : resolveExpressionAssetId(source.value, renderScope),+ session: {+ open: openAsset,+ reload: (assetId, options) => {+ if (options?.expectedName === undefined) {+ throw new Error("The expected Asset name is required for reload");+ }+ return reloadAsset(assetId, options.expectedName);+ },+ save: (assetId, source) => {+ stagedSources.set(assetId, source);+ },+ flush: async (assetId) => {+ const source = stagedSources.get(assetId);+ if (source !== undefined) {+ await updateAssetSource(assetId, () => source);+ stagedSources.delete(assetId);+ }+ await flushAsset(assetId);+ return openAsset(assetId);+ },+ },+ });+ let pending:+ | Readonly<{+ source: ContentBlockSource;+ assetId: string;+ expectedName: string;+ instances: BuilderState["instances"];+ props: BuilderState["props"];+ }>+ | undefined;++ const requestSource = async ({+ source,+ confirmed = false,+ }: {+ source: ContentBlockSource;+ confirmed?: boolean;+ }): Promise<ContentBlockSourceControllerResult> => {+ const state = getState();+ const configured = getContentBlockSource({+ blockInstanceId,+ props: state.props?.values() ?? [],+ });+ if (configured !== undefined) {+ pending = undefined;+ if (isEqualContentBlockSource(configured, source)) {+ const inspection = await application.inspect({+ state,+ blockInstanceId,+ renderScope,+ source,+ });+ return { status: "applied", state: inspection.sessionState };+ }+ const prepared = await application.switchSource({+ state,+ blockInstanceId,+ renderScope,+ source,+ });+ const current = getState();+ if (+ current.instances !== state.instances ||+ current.props !== state.props+ ) {+ return {+ status: "blocked",+ message: "The Content Block changed while the source was loading.",+ };+ }+ commitProjectPayload(prepared.projectPayload);+ return { status: "applied", state: prepared.inspection.sessionState };+ }+ if (confirmed) {+ if (+ pending === undefined ||+ isEqualContentBlockSource(pending.source, source) === false ||+ pending.instances !== state.instances ||+ pending.props !== state.props+ ) {+ pending = undefined;+ return {+ status: "blocked",+ message: "The Content Block changed before connection was confirmed.",+ };+ }+ await reloadAsset(pending.assetId, pending.expectedName);+ }+ const prepared = await application.connect({+ state,+ blockInstanceId,+ renderScope,+ source,+ });+ const current = getState();+ if (+ current.instances !== state.instances ||+ current.props !== state.props+ ) {+ pending = undefined;+ return {+ status: "blocked",+ message: "The Content Block changed while the source was loading.",+ };+ }+ if (prepared.requiresConfirmation && confirmed === false) {+ pending = {+ source,+ assetId: prepared.inspection.identity.assetId,+ expectedName: prepared.inspection.sessionState.asset.name,+ instances: state.instances,+ props: state.props,+ };+ return {+ status: "requires-confirmation",+ diagnostics: prepared.inspection.diagnostics,+ };+ }+ pending = undefined;+ commitProjectPayload(prepared.projectPayload);+ return { status: "applied", state: prepared.inspection.sessionState };+ };++ const disconnect = async (): Promise<MutationResult> => {+ const state = getState();+ const prepared = await application.disconnect({+ state,+ blockInstanceId,+ });+ const current = getState();+ if (+ current.instances !== state.instances ||+ current.props !== state.props+ ) {+ return {+ status: "blocked",+ message: "The Content Block changed while it was disconnecting.",+ };+ }+ commitProjectPayload(prepared.projectPayload);+ return { status: "applied" };+ };++ return {+ requestSource,+ disconnect,+ open: async (source: ContentBlockSource) =>+ (+ await application.inspect({+ state: getState(),+ blockInstanceId,+ renderScope,+ source,+ })+ ).sessionState,+ };+};++export const createBuilderContentBlockSourceController = ({+ blockInstanceId,+ renderScope,+ projectId,+}: {+ blockInstanceId: string;+ renderScope: string;+ projectId: string;+}) =>+ createContentBlockSourceController({+ blockInstanceId,+ renderScope,+ projectId,+ getState: readBuilderStateStores,+ openAsset: (assetId) => openExternalContentAsset({ projectId, assetId }),+ reloadAsset: (assetId, expectedName) =>+ reloadExternalContentAsset({ projectId, assetId, expectedName }),+ resolveExpressionAssetId: (expression, scope) => {+ const instanceSelector = parseContentBlockRenderScope(scope);+ return instanceSelector === undefined+ ? undefined+ : resolveContentBlockOccurrenceAssetId({+ source: { type: "expression", value: expression },+ instanceSelector,+ variableValuesByRenderScope:+ $variableValuesByInstanceSelector.get(),+ });+ },+ flushAsset: (assetId) => flushExternalContentAsset({ projectId, assetId }),+ updateAssetSource: (assetId, update) =>+ updateExternalContentAssetSource({ projectId, assetId, update }),+ commitProjectPayload: (payload) =>+ createTransactionFromBuilderPatchPayload({+ data: getWebstudioData(),+ payload: [...payload],+ }),+ });diff --git a/apps/builder/app/builder/features/settings-panel/controls/content-block-source-section.tsx b/apps/builder/app/builder/features/settings-panel/controls/content-block-source-section.tsxnew file mode 100644index 0000000000..60428c6b12--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/controls/content-block-source-section.tsx@@ -0,0 +1,196 @@+import { useEffect, useMemo, useState } from "react";+import { useStore } from "@nanostores/react";+import {+ contentBlockSourceProp,+ getContentBlockSource,+} from "@webstudio-is/sdk";+import { TextFileEditor } from "~/builder/features/text-file-editor/text-file-editor";+import {+ $authPermit,+ $isContentMode,+ $variableValuesByInstanceSelector,+} from "~/shared/nano-states";+import type { AssetContentSessionState } from "@webstudio-is/content-engine/asset-content-session";+import { $assets, $project, $props } from "~/shared/sync/data-stores";+import {+ retryExternalContentAsset,+ subscribeExternalContentAsset,+} from "~/shared/external-content-roots";+import {+ $externalContentRoots,+ findExternalContentRoot,+} from "~/shared/external-content-mutations";+import { ContentBlockSourceControl } from "./content-block-source";+import { createBuilderContentBlockSourceController } from "./content-block-source-controller";+import {+ parseContentBlockRenderScope,+ resolveContentBlockOccurrenceAssetId,+} from "~/shared/content-block-source-utils";+import { PropertyLabel } from "../property-label";+import { VerticalLayout } from "../shared";++export const ContentBlockSourceSection = ({+ blockInstanceId,+ renderScope,+}: {+ blockInstanceId: string;+ renderScope: string;+}) => {+ const project = useStore($project);+ const props = useStore($props);+ const assets = useStore($assets);+ const authPermit = useStore($authPermit);+ const isContentMode = useStore($isContentMode);+ const variableValues = useStore($variableValuesByInstanceSelector);+ const externalContentRoots = useStore($externalContentRoots);+ const source = useMemo(+ () => getContentBlockSource({ blockInstanceId, props: props.values() }),+ [blockInstanceId, props]+ );+ const instanceSelector = useMemo(+ () => parseContentBlockRenderScope(renderScope),+ [renderScope]+ );+ const resolvedAssetId = useMemo(() => {+ if (source === undefined || instanceSelector === undefined) {+ return;+ }+ return resolveContentBlockOccurrenceAssetId({+ source,+ instanceSelector,+ variableValuesByRenderScope: variableValues,+ });+ }, [instanceSelector, source, variableValues]);+ const resolvedAsset =+ resolvedAssetId === undefined ? undefined : assets.get(resolvedAssetId);+ const [loading, setLoading] = useState(source !== undefined);+ const [error, setError] = useState<string>();+ const [openedAssetId, setOpenedAssetId] = useState<string>();+ const [disconnecting, setDisconnecting] = useState(false);+ const [contentState, setContentState] = useState<AssetContentSessionState>();+ const controller = useMemo(+ () =>+ project === undefined+ ? undefined+ : createBuilderContentBlockSourceController({+ blockInstanceId,+ renderScope,+ projectId: project.id,+ }),+ [blockInstanceId, project, renderScope]+ );+ useEffect(() => {+ let active = true;+ if (source === undefined || controller === undefined) {+ setLoading(false);+ setError(undefined);+ return;+ }+ setLoading(true);+ void controller+ .open(source)+ .then(() => {+ if (active === false) {+ return;+ }+ setError(undefined);+ })+ .catch(+ (error) =>+ active &&+ setError(+ error instanceof Error ? error.message : "Unable to load MDX"+ )+ )+ .finally(() => active && setLoading(false));+ return () => {+ active = false;+ };+ }, [controller, resolvedAsset?.name, resolvedAsset?.size, source]);++ useEffect(() => {+ if (project === undefined || resolvedAssetId === undefined) {+ setContentState(undefined);+ return;+ }+ return subscribeExternalContentAsset({+ projectId: project.id,+ assetId: resolvedAssetId,+ listener: setContentState,+ });+ }, [project, resolvedAssetId]);++ if (project === undefined || controller === undefined) {+ return;+ }+ const externalContentRoot = findExternalContentRoot(+ externalContentRoots,+ blockInstanceId,+ renderScope+ );++ return (+ <VerticalLayout+ label={+ <PropertyLabel+ name={contentBlockSourceProp}+ readOnly={isContentMode}+ deletable={isContentMode === false && authPermit !== "view"}+ onDelete={() => {+ if (disconnecting) {+ return;+ }+ setDisconnecting(true);+ setError(undefined);+ void controller+ .disconnect()+ .then((result) => {+ if (result.status === "blocked") {+ setError(result.message);+ }+ })+ .catch((error) =>+ setError(+ error instanceof Error+ ? error.message+ : "Unable to disconnect source"+ )+ )+ .finally(() => setDisconnecting(false));+ }}+ />+ }+ >+ <ContentBlockSourceControl+ source={source}+ resolvedAsset={resolvedAsset}+ readOnly={isContentMode}+ disabled={authPermit === "view" || disconnecting}+ loading={loading}+ error={error}+ diagnostics={externalContentRoot?.diagnostics}+ persistenceStatus={contentState?.status}+ persistenceError={contentState?.error?.message}+ onRetry={+ resolvedAssetId === undefined+ ? undefined+ : async () => {+ await retryExternalContentAsset({+ projectId: project.id,+ assetId: resolvedAssetId,+ });+ }+ }+ onRequestSource={controller.requestSource}+ onOpen={setOpenedAssetId}+ />+ {openedAssetId !== undefined && (+ <TextFileEditor+ key={openedAssetId}+ assetId={openedAssetId}+ onOpenChange={(open) => open === false && setOpenedAssetId(undefined)}+ />+ )}+ </VerticalLayout>+ );+};diff --git a/apps/builder/app/builder/features/settings-panel/controls/content-block-source.test.tsx b/apps/builder/app/builder/features/settings-panel/controls/content-block-source.test.tsxnew file mode 100644index 0000000000..f61aa7e509--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/controls/content-block-source.test.tsx@@ -0,0 +1,349 @@+/**+ * @vitest-environment jsdom+ */+import { act } from "react-dom/test-utils";+import { createRoot, type Root } from "react-dom/client";+import type { ComponentProps } from "react";+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import { TooltipProvider } from "@webstudio-is/design-system";+import type { Asset } from "@webstudio-is/sdk";+import { $assets } from "~/shared/sync/data-stores";+import { ContentBlockSourceControl } from "./content-block-source";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const asset: Asset = {+ id: "post",+ projectId: "project",+ name: "post.mdx",+ format: "mdx",+ size: 10,+ type: "file",+ meta: {},+ createdAt: "2026-01-01T00:00:00.000Z",+};+const targetAsset: Asset = { ...asset, id: "other", name: "other.mdx" };+let container: HTMLDivElement;+let root: Root;+const scrollIntoView = Object.getOwnPropertyDescriptor(+ HTMLElement.prototype,+ "scrollIntoView"+);++beforeEach(() => {+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+ Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {+ configurable: true,+ value: vi.fn(),+ });+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ $assets.set(new Map([asset, targetAsset].map((item) => [item.id, item])));+});++afterEach(() => {+ act(() => root.unmount());+ document.body.innerHTML = "";+ vi.unstubAllGlobals();+ $assets.set(new Map());+ if (scrollIntoView === undefined) {+ delete (HTMLElement.prototype as { scrollIntoView?: unknown })+ .scrollIntoView;+ } else {+ Object.defineProperty(+ HTMLElement.prototype,+ "scrollIntoView",+ scrollIntoView+ );+ }+});++const findButton = (label: string) => {+ const button = Array.from(+ document.body.querySelectorAll<HTMLButtonElement>("button")+ ).find((candidate) => candidate.textContent?.trim() === label);+ if (button === undefined) {+ throw new Error(`Expected button "${label}"`);+ }+ return button;+};++const chooseAsset = async (triggerLabel: string, assetName: string) => {+ await act(async () => {+ findButton(triggerLabel).click();+ await new Promise<void>((resolve) =>+ requestAnimationFrame(() => resolve())+ );+ });+ const option = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="option"]')+ ).find((element) => element.textContent?.includes(assetName));+ const target = option?.querySelector<HTMLElement>(+ "[data-asset-thumbnail] > div"+ );+ if (target === undefined || target === null) {+ throw new Error(`Expected compatible Asset "${assetName}"`);+ }+ await act(async () => {+ target.click();+ await Promise.resolve();+ });+};++const renderControl = ({+ onRequestSource = async () => ({ status: "applied" as const }),+ onOpen = () => {},+ source = { type: "asset" as const, assetId: asset.id },+ resolvedAsset = asset,+ loading = false,+ readOnly = false,+ diagnostics,+ persistenceStatus,+ persistenceError,+ onRetry,+}: {+ onRequestSource?: ComponentProps<+ typeof ContentBlockSourceControl+ >["onRequestSource"];+ onOpen?: ComponentProps<typeof ContentBlockSourceControl>["onOpen"];+ source?:+ | { type: "asset"; assetId: string }+ | { type: "expression"; value: string };+ resolvedAsset?: Asset;+ loading?: boolean;+ readOnly?: boolean;+ diagnostics?: ComponentProps<typeof ContentBlockSourceControl>["diagnostics"];+ persistenceStatus?: ComponentProps<+ typeof ContentBlockSourceControl+ >["persistenceStatus"];+ persistenceError?: string;+ onRetry?: () => Promise<void>;+} = {}) => {+ act(() => {+ root.render(+ <TooltipProvider>+ <ContentBlockSourceControl+ source={source}+ resolvedAsset={resolvedAsset}+ loading={loading}+ readOnly={readOnly}+ diagnostics={diagnostics}+ persistenceStatus={persistenceStatus}+ persistenceError={persistenceError}+ onRetry={onRetry}+ onRequestSource={onRequestSource}+ onOpen={onOpen}+ />+ </TooltipProvider>+ );+ });+};++test("shows a warning indicator for source diagnostics", () => {+ const diagnostic = {+ code: "ignored-template-prop" as const,+ severity: "warning" as const,+ blockInstanceId: "block",+ assetId: "post",+ contentRef: "post.mdx",+ renderScope: "collection:item-2",+ templateName: "Hero",+ propName: "tone",+ reason: "design-only" as const,+ sourceRange: {+ start: { line: 7, column: 4 },+ end: { line: 7, column: 12 },+ },+ };+ renderControl({+ diagnostics: [diagnostic, diagnostic],+ });++ expect(+ container.querySelector('[aria-label^="MDX source warning:"]')+ ).not.toBeNull();+ expect(container.textContent).not.toContain("Render scope:");+});++test("keeps the resolved filename visible while refreshed content loads", () => {+ renderControl({ loading: true });++ expect(findButton("post.mdx")).not.toBeNull();+ expect(findButton("Open").matches(":disabled")).toBe(true);+});++test("shows equal filename and Open actions for a connected source", () => {+ renderControl();++ const actions = document.querySelector(+ '[aria-label="Content source actions"]'+ );+ expect(+ Array.from(actions?.querySelectorAll("button") ?? []).map((button) =>+ button.textContent?.trim()+ )+ ).toEqual(["post.mdx", "Open"]);+});++test("opens the resolved Asset for a bound source", () => {+ const onOpen = vi.fn();+ renderControl({+ source: { type: "expression", value: "post.body" },+ resolvedAsset: targetAsset,+ onOpen,+ });++ act(() => findButton("Open").click());++ expect(onOpen).toHaveBeenCalledWith(targetAsset.id);+});++test("keeps a connected source visible and openable when read-only", () => {+ const onOpen = vi.fn();+ const onRequestSource = vi.fn(async () => ({ status: "applied" as const }));+ renderControl({ readOnly: true, onOpen, onRequestSource });++ expect(findButton("post.mdx")).not.toBeNull();+ expect(findButton("post.mdx").matches(":disabled")).toBe(true);+ expect(container.querySelector('[data-variant="bound"]')).toBeNull();++ act(() => findButton("Open").click());++ expect(onOpen).toHaveBeenCalledWith(asset.id);+ expect(onRequestSource).not.toHaveBeenCalled();+});++test("switches a connected source from the filename button", async () => {+ const onRequestSource = vi.fn(async () => ({ status: "applied" as const }));+ renderControl({ onRequestSource });++ await chooseAsset("post.mdx", "other.mdx");++ expect(onRequestSource).toHaveBeenCalledWith({+ source: { type: "asset", assetId: targetAsset.id },+ confirmed: undefined,+ });+});++test("shows the resolved filename while retaining a dynamic binding", () => {+ renderControl({ source: { type: "expression", value: "post.body" } });++ expect(findButton("post.mdx")).not.toBeNull();+ expect(container.querySelector('[data-variant="bound"]')).not.toBeNull();+});++test("shows only a full-width bindable connect button without a source", () => {+ act(() => {+ root.render(+ <TooltipProvider>+ <ContentBlockSourceControl+ onRequestSource={async () => ({ status: "applied" })}+ onOpen={() => {}}+ />+ </TooltipProvider>+ );+ });++ expect(document.querySelector("input")).toBeNull();+ expect(findButton("Connect .mdx file")).not.toBeNull();+ expect(document.body.textContent).not.toContain("Create MDX file");+});++test("asks for confirmation before connecting over existing content", async () => {+ const onRequestSource = vi+ .fn()+ .mockResolvedValueOnce({+ status: "requires-confirmation",+ diagnostics: [+ {+ code: "invalid-mdx",+ severity: "error",+ blockInstanceId: "block",+ assetId: "other",+ renderScope: "scope",+ message: "Unexpected closing tag.",+ sourceRange: {+ start: { line: 3, column: 2 },+ end: { line: 3, column: 4 },+ },+ },+ ],+ })+ .mockResolvedValueOnce({ status: "applied" });+ act(() => {+ root.render(+ <TooltipProvider>+ <ContentBlockSourceControl+ onRequestSource={onRequestSource}+ onOpen={() => {}}+ />+ </TooltipProvider>+ );+ });++ await chooseAsset("Connect .mdx file", "other.mdx");++ expect(document.body.textContent).toContain("Connect content source");+ expect(document.body.textContent).toContain(+ "The MDX file will not be changed."+ );+ expect(document.body.textContent).toContain(+ "Unexpected closing tag. Line 3, column 2."+ );+ const dialogButtons = Array.from(+ document.body.querySelectorAll<HTMLButtonElement>("button")+ )+ .map((button) => button.textContent?.trim())+ .filter((label) => label === "Connect" || label === "Abort");+ // DialogActions reverses DOM order so Abort is left and Connect is right.+ expect(dialogButtons).toEqual(["Connect", "Abort"]);+ expect(onRequestSource).toHaveBeenNthCalledWith(1, {+ source: { type: "asset", assetId: targetAsset.id },+ confirmed: undefined,+ });++ await act(async () => findButton("Connect").click());+ expect(onRequestSource).toHaveBeenNthCalledWith(2, {+ source: { type: "asset", assetId: targetAsset.id },+ confirmed: true,+ });+});++test("keeps a failed Asset write visible and retryable", async () => {+ const onRetry = vi.fn(async () => {});+ renderControl({+ persistenceStatus: "failed",+ persistenceError: "Temporary storage failure",+ onRetry,+ });++ expect(document.querySelector('[role="alert"]')?.textContent).toBe(+ "Temporary storage failure"+ );+ await act(async () => findButton("Retry").click());+ expect(onRetry).toHaveBeenCalledOnce();+});++test("allows retrying a failed Asset write when the source is read-only", async () => {+ const onRetry = vi.fn(async () => {});+ renderControl({+ readOnly: true,+ persistenceStatus: "failed",+ persistenceError: "Temporary storage failure",+ onRetry,+ });++ await act(async () => findButton("Retry").click());++ expect(onRetry).toHaveBeenCalledOnce();+});diff --git a/apps/builder/app/builder/features/settings-panel/controls/content-block-source.tsx b/apps/builder/app/builder/features/settings-panel/controls/content-block-source.tsxnew file mode 100644index 0000000000..912c0b3c1e--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/controls/content-block-source.tsx@@ -0,0 +1,375 @@+import { useRef, useState } from "react";+import {+ Button,+ Box,+ Dialog,+ DialogActions,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogTitle,+ Flex,+ Grid,+ Text,+ Tooltip,+ rawTheme,+ theme,+} from "@webstudio-is/design-system";+import { AlertIcon } from "@webstudio-is/icons";+import {+ formatAssetName,+ type Asset,+ type ContentBlockDiagnostic,+ type ContentBlockSource,+} from "@webstudio-is/sdk";+import { BindableExpressionControl } from "~/builder/shared/bindable-expression";+import { useBindableControl } from "./use-bindable-control";+import { SelectAsset } from "./select-asset";+import {+ deduplicateContentBlockDiagnostics,+ formatContentBlockDiagnostic,+} from "~/shared/content-block-diagnostics";++type ContentBlockSourceMutationResult =+ | Readonly<{ status: "applied" }>+ | Readonly<{ status: "partial"; message: string }>+ | Readonly<{ status: "blocked"; message: string }>;++type ContentBlockSourceActionResult =+ | ContentBlockSourceMutationResult+ | Readonly<{+ status: "requires-confirmation";+ diagnostics?: readonly ContentBlockDiagnostic[];+ }>;++type PendingSource = Readonly<{+ source: ContentBlockSource;+ diagnostics: readonly ContentBlockDiagnostic[];+}>;++const getErrorMessage = (error: unknown, fallback: string) =>+ error instanceof Error ? error.message : fallback;++const ConnectSourceDialog = ({+ disabled,+ error,+ diagnostics,+ onClose,+ onConfirm,+}: {+ disabled: boolean;+ error?: string;+ diagnostics: readonly ContentBlockDiagnostic[];+ onClose: () => void;+ onConfirm: () => void;+}) => (+ <Dialog open onOpenChange={(open) => open === false && onClose()}>+ <DialogContent>+ <DialogTitle>Connect content source</DialogTitle>+ <DialogDescription asChild>+ <Text css={{ padding: theme.panel.padding }}>+ Connecting this file will replace the existing Content Block content.+ The MDX file will not be changed.+ </Text>+ </DialogDescription>+ {error !== undefined && (+ <Text+ role="alert"+ color="destructive"+ variant="tiny"+ css={{+ paddingInline: theme.panel.paddingInline,+ paddingBottom: theme.panel.paddingBlock,+ }}+ >+ {error}+ </Text>+ )}+ {diagnostics.map((diagnostic) => (+ <Text+ key={JSON.stringify(diagnostic)}+ role="status"+ color="subtle"+ variant="tiny"+ css={{ paddingInline: theme.panel.paddingInline }}+ >+ {formatContentBlockDiagnostic(diagnostic)}+ </Text>+ ))}+ <DialogActions>+ <Button disabled={disabled} onClick={onConfirm}>+ Connect+ </Button>+ <DialogClose>+ <Button autoFocus color="ghost" disabled={disabled}>+ Abort+ </Button>+ </DialogClose>+ </DialogActions>+ </DialogContent>+ </Dialog>+);++/**+ * Presentation and interaction boundary for Content Block source lifecycle.+ * The caller owns loading, exact-Asset authorization, lifecycle preparation,+ * and persistence. This component never updates the src prop directly.+ */+export const ContentBlockSourceControl = ({+ source,+ resolvedAsset,+ readOnly = false,+ disabled = false,+ loading = false,+ error,+ diagnostics = [],+ persistenceStatus,+ persistenceError,+ onRetry,+ onRequestSource,+ onOpen,+}: {+ source?: ContentBlockSource;+ resolvedAsset?: Asset;+ readOnly?: boolean;+ disabled?: boolean;+ loading?: boolean;+ error?: string;+ diagnostics?: readonly ContentBlockDiagnostic[];+ persistenceStatus?: "saved" | "pending" | "saving" | "failed" | "conflicting";+ persistenceError?: string;+ onRetry?: () => Promise<void>;+ onRequestSource: (input: {+ source: ContentBlockSource;+ confirmed?: boolean;+ }) => Promise<ContentBlockSourceActionResult>;+ onOpen: (assetId: string) => void;+}) => {+ const [pendingSource, setPendingSource] = useState<PendingSource>();+ const [busy, setBusy] = useState(false);+ const busyRef = useRef(false);+ const [localError, setLocalError] = useState<string>();+ const isDisabled = disabled || loading || busy;+ const isSourceMutationDisabled = readOnly || isDisabled;+ const connected = source !== undefined;+ const binding = useBindableControl({+ boundExpression: source?.type === "expression" ? source : undefined,+ fallbackExpression: JSON.stringify(resolvedAsset?.id ?? ""),+ });+ const uniqueDiagnostics = deduplicateContentBlockDiagnostics(diagnostics);+ const sourceLabel = resolvedAsset+ ? formatAssetName(resolvedAsset)+ : loading+ ? "Loading content source…"+ : source?.type === "expression"+ ? "Dynamic content source"+ : source?.type === "asset"+ ? "Missing MDX Asset"+ : "No content source";++ const beginOperation = () => {+ if (disabled || loading || busyRef.current) {+ return false;+ }+ busyRef.current = true;+ setBusy(true);+ setLocalError(undefined);+ return true;+ };++ const finishOperation = () => {+ busyRef.current = false;+ setBusy(false);+ };++ const requestSource = async (+ requestedSource: ContentBlockSource,+ confirmed?: boolean+ ) => {+ if (readOnly || beginOperation() === false) {+ return;+ }+ try {+ const result = await onRequestSource({+ source: requestedSource,+ confirmed,+ });+ if (result.status === "requires-confirmation") {+ setPendingSource({+ source: requestedSource,+ diagnostics: result.diagnostics ?? [],+ });+ return;+ }+ if (result.status === "blocked" || result.status === "partial") {+ setLocalError(result.message);+ return;+ }+ setPendingSource(undefined);+ } catch (error) {+ setLocalError(getErrorMessage(error, "Unable to change source"));+ } finally {+ finishOperation();+ }+ };++ return (+ <fieldset disabled={isDisabled} style={{ display: "contents" }}>+ <Grid gap="2">+ <BindableExpressionControl+ {...binding}+ showBinding={readOnly === false}+ value={resolvedAsset?.id}+ validate={(value) =>+ typeof value === "string" && value !== ""+ ? undefined+ : "Content source must resolve to an Asset ID"+ }+ onChangeValue={(value) => {+ if (typeof value === "string" && value !== "") {+ void requestSource({ type: "asset", assetId: value });+ }+ }}+ onChangeExpression={(value) => {+ void requestSource({ type: "expression", value });+ }}+ onRemove={(value) => {+ if (typeof value === "string" && value !== "") {+ void requestSource({ type: "asset", assetId: value });+ }+ }}+ renderControl={() =>+ connected ? (+ <Grid columns={2} gap="2" aria-label="Content source actions">+ <Flex align="center" gap="1">+ <Box css={{ flex: 1, minWidth: 0 }}>+ <SelectAsset+ assetId={resolvedAsset?.id}+ title="Switch MDX file"+ accept=".mdx"+ disabled={isSourceMutationDisabled}+ triggerLabel={sourceLabel}+ onChange={(assetId) =>+ void requestSource({ type: "asset", assetId })+ }+ />+ </Box>+ {uniqueDiagnostics.length > 0 && (+ <Tooltip+ content={+ <Grid gap="1">+ <Text>+ {formatContentBlockDiagnostic(uniqueDiagnostics[0])}+ </Text>+ {uniqueDiagnostics.length > 1 && (+ <Text>+ {uniqueDiagnostics.length - 1} more diagnostic+ {uniqueDiagnostics.length === 2 ? "" : "s"}+ </Text>+ )}+ </Grid>+ }+ >+ <Flex+ as="span"+ align="center"+ role="img"+ tabIndex={0}+ aria-label={`MDX source warning: ${formatContentBlockDiagnostic(uniqueDiagnostics[0])}${uniqueDiagnostics.length > 1 ? ` ${uniqueDiagnostics.length - 1} more diagnostic${uniqueDiagnostics.length === 2 ? "" : "s"}.` : ""}`}+ css={{+ color: rawTheme.colors.backgroundAlertMain,+ flexShrink: 0,+ }}+ >+ <AlertIcon size={14} />+ </Flex>+ </Tooltip>+ )}+ </Flex>+ <Button+ color="neutral"+ disabled={isDisabled || resolvedAsset === undefined}+ css={{ width: "100%" }}+ onClick={() => {+ if (resolvedAsset !== undefined) {+ onOpen(resolvedAsset.id);+ }+ }}+ >+ Open+ </Button>+ </Grid>+ ) : readOnly ? null : (+ <SelectAsset+ title="Choose MDX file"+ accept=".mdx"+ disabled={isDisabled}+ triggerLabel="Connect .mdx file"+ onChange={(assetId) =>+ void requestSource({ type: "asset", assetId })+ }+ />+ )+ }+ />++ {(localError ?? error) !== undefined && pendingSource === undefined && (+ <Text role="alert" color="destructive" variant="tiny">+ {localError ?? error}+ </Text>+ )}++ {(persistenceStatus === "pending" ||+ persistenceStatus === "saving") && (+ <Text role="status" variant="tiny">+ Saving content source…+ </Text>+ )}++ {persistenceStatus === "failed" && (+ <Flex gap="2" align="center" wrap="wrap">+ <Text role="alert" color="destructive" variant="tiny">+ {persistenceError ?? "Unable to save content source."}+ </Text>+ {onRetry !== undefined && (+ <Button+ color="ghost"+ disabled={isDisabled}+ onClick={() => {+ if (beginOperation() === false) {+ return;+ }+ void onRetry()+ .catch((error) =>+ setLocalError(+ getErrorMessage(error, "Unable to retry save")+ )+ )+ .finally(finishOperation);+ }}+ >+ Retry+ </Button>+ )}+ </Flex>+ )}++ {busy && (+ <Text role="status" variant="tiny">+ Updating content source…+ </Text>+ )}++ {pendingSource !== undefined && (+ <ConnectSourceDialog+ disabled={isSourceMutationDisabled}+ error={localError ?? error}+ diagnostics={pendingSource.diagnostics}+ onClose={() => setPendingSource(undefined)}+ onConfirm={() => void requestSource(pendingSource.source, true)}+ />+ )}+ </Grid>+ </fieldset>+ );+};diff --git a/apps/builder/app/builder/features/settings-panel/controls/file.tsx b/apps/builder/app/builder/features/settings-panel/controls/file.tsxindex 54ebe45b70..138b96e497 100644--- a/apps/builder/app/builder/features/settings-panel/controls/file.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/file.tsx@@ -45,6 +45,10 @@ export const FileControl = ({onChange,}: ControlProps<"file">) => {const id = useId();+ const binding = useBindableControl({+ boundExpression: prop?.type === "expression" ? prop : undefined,+ fallbackExpression: JSON.stringify(computedValue),+ });const localStringValue = useDraftValue(// use undefined for asset type to not delete@@ -53,7 +57,7 @@ export const FileControl = ({? String(computedValue): undefined,(value) => {- if (value === undefined || prop?.type === "expression") {+ if (value === undefined || binding.bindingState.overwritable === false) {return;}onChange({ type: "string", value });@@ -61,10 +65,6 @@ export const FileControl = ({);const label = humanizeAttribute(meta.label || propName);- const binding = useBindableControl({- boundExpression: prop?.type === "expression" ? prop.value : undefined,- fallbackExpression: JSON.stringify(computedValue),- });return (<VerticalLayout label={<PropertyLabel name={propName} />}><Flex css={{ gap: theme.spacing[3] }} direction="column" justify="center">@@ -90,9 +90,9 @@ export const FileControl = ({)}/><SelectAsset- prop={prop?.type === "asset" ? prop : undefined}+ assetId={prop?.type === "asset" ? prop.value : undefined}accept={meta.accept}- onChange={onChange}+ onChange={(assetId) => onChange({ type: "asset", value: assetId })}/></Flex></VerticalLayout>diff --git a/apps/builder/app/builder/features/settings-panel/controls/json.tsx b/apps/builder/app/builder/features/settings-panel/controls/json.tsxindex 423f38281d..7c621f5a68 100644--- a/apps/builder/app/builder/features/settings-panel/controls/json.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/json.tsx@@ -18,8 +18,12 @@ export const JsonControl = ({}: ControlProps<"json">) => {const [error, setError] = useState<boolean>(false);const valueString = formatValue(computedValue ?? "");+ const binding = useBindableControl({+ boundExpression: prop?.type === "expression" ? prop : undefined,+ fallbackExpression: valueString,+ });const localValue = useDraftValue(valueString, (value) => {- if (prop?.type === "expression") {+ if (binding.bindingState.overwritable === false) {return;}const isLiteral = isLiteralExpression(value);@@ -37,11 +41,6 @@ export const JsonControl = ({}});- const binding = useBindableControl({- boundExpression: prop?.type === "expression" ? prop.value : undefined,- fallbackExpression: valueString,- });-return (<VerticalLayoutlabel={diff --git a/apps/builder/app/builder/features/settings-panel/controls/number.tsx b/apps/builder/app/builder/features/settings-panel/controls/number.tsxindex 50c5cdff94..501b74fd57 100644--- a/apps/builder/app/builder/features/settings-panel/controls/number.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/number.tsx@@ -21,10 +21,14 @@ export const NumberControl = ({const [isInvalid, setIsInvalid] = useState(false);const number = Number(computedValue);+ const binding = useBindableControl({+ boundExpression: prop?.type === "expression" ? prop : undefined,+ fallbackExpression: JSON.stringify(computedValue),+ });const localValue = useDraftValue(Number.isNaN(number) ? "" : number,(value) => {- if (prop?.type === "expression") {+ if (binding.bindingState.overwritable === false) {return;}if (typeof value === "number") {@@ -37,11 +41,6 @@ export const NumberControl = ({);const label = humanizeAttribute(meta.label || propName);- const binding = useBindableControl({- boundExpression: prop?.type === "expression" ? prop.value : undefined,- fallbackExpression: JSON.stringify(computedValue),- });-return (<ResponsiveLayoutlabel={diff --git a/apps/builder/app/builder/features/settings-panel/controls/select-asset.tsx b/apps/builder/app/builder/features/settings-panel/controls/select-asset.tsxindex a9106259d8..9f0d94eae6 100644--- a/apps/builder/app/builder/features/settings-panel/controls/select-asset.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/select-asset.tsx@@ -1,16 +1,17 @@-import { useMemo } from "react";+import { useMemo, useState } from "react";import { computed } from "nanostores";import { useStore } from "@nanostores/react";-import { Button, Flex, Text, FloatingPanel } from "@webstudio-is/design-system";-import { acceptToMimeCategories } from "@webstudio-is/sdk";+import { Button, Flex, FloatingPanel } from "@webstudio-is/design-system";+import {+ acceptToMimeCategories,+ formatAssetName,+ type Asset,+} from "@webstudio-is/sdk";import { $assets } from "~/shared/sync/data-stores";import { AssetManager } from "~/builder/shared/asset-manager";-import { type PropValue } from "../shared";-import { formatAssetName } from "@webstudio-is/project-build/runtime";import { AssetUpload } from "~/builder/shared/assets";-// tests whether we can use AssetManager for the given "accept" value-const isImageAccept = (accept?: string) => {+const acceptsImageUpload = (accept?: string) => {const acceptCategories = acceptToMimeCategories(accept || "");return (acceptCategories === "*" ||@@ -20,39 +21,56 @@ const isImageAccept = (accept?: string) => {type Props = {accept?: string;- prop?: Extract<PropValue, { type: "asset" }>;- onChange: (value: Extract<PropValue, { type: "asset" }>) => void;+ assetId?: Asset["id"];+ title?: string;+ triggerLabel?: string;+ disabled?: boolean;+ onChange: (assetId: Asset["id"]) => void;};-export const SelectAsset = ({ prop, onChange, accept }: Props) => {+export const SelectAsset = ({+ accept,+ assetId,+ title,+ triggerLabel,+ disabled,+ onChange,+}: Props) => {+ const [open, setOpen] = useState(false);const $asset = useMemo(() =>computed($assets, (assets) =>- prop ? assets.get(prop.value) : undefined+ assetId === undefined ? undefined : assets.get(assetId)),- [prop]+ [assetId]);const asset = useStore($asset);-- if (isImageAccept(accept) === false) {- return <Text color="destructive">Unsupported accept value: {accept}</Text>;- }+ const acceptsImages = acceptsImageUpload(accept);return (<Flex gap={2} css={{ flex: 1 }} align="center"><FloatingPanel- title="Images"- titleSuffix={<AssetUpload type="image" accept={accept} />}+ open={open}+ onOpenChange={setOpen}+ title={title ?? (acceptsImages ? "Images" : "Assets")}+ titleSuffix={+ acceptsImages ? (+ <AssetUpload type="image" accept={accept} />+ ) : undefined+ }content={<AssetManager- onChange={(assetId) => onChange({ type: "asset", value: assetId })}+ onChange={(assetId) => {+ setOpen(false);+ onChange(assetId);+ }}accept={accept}/>}>- <Button color="neutral" css={{ flex: 1 }}>- {asset ? formatAssetName(asset) : "Choose source"}+ <Button color="neutral" css={{ flex: 1 }} disabled={disabled}>+ {triggerLabel ?? (asset ? formatAssetName(asset) : "Choose source")}</Button></FloatingPanel></Flex>diff --git a/apps/builder/app/builder/features/settings-panel/controls/text-content-utils.test.ts b/apps/builder/app/builder/features/settings-panel/controls/text-content-utils.test.tsindex 28d9bd3aaa..11763991e7 100644--- a/apps/builder/app/builder/features/settings-panel/controls/text-content-utils.test.ts+++ b/apps/builder/app/builder/features/settings-panel/controls/text-content-utils.test.ts@@ -19,6 +19,7 @@ test("updates the targeted expression without replacing its siblings", () => {]),type: "expression",value: "2 + 2",+ expressionBindingMode: "readwrite",})).toEqual({id: "instances.updateText",@@ -27,6 +28,7 @@ test("updates the targeted expression without replacing its siblings", () => {childIndex: 1,mode: "expression",text: "2 + 2",+ expressionBindingMode: "readwrite",},});});diff --git a/apps/builder/app/builder/features/settings-panel/controls/text-content-utils.ts b/apps/builder/app/builder/features/settings-panel/controls/text-content-utils.tsindex 026ad24f97..6e2bbef3eb 100644--- a/apps/builder/app/builder/features/settings-panel/controls/text-content-utils.ts+++ b/apps/builder/app/builder/features/settings-panel/controls/text-content-utils.ts@@ -1,14 +1,16 @@-import type { Instance } from "@webstudio-is/sdk";+import type { ExpressionBindingMode, Instance } from "@webstudio-is/sdk";import { getEditableTextTarget } from "@webstudio-is/project-build/runtime";export const getTextContentUpdateOperation = ({instance,type,value,+ expressionBindingMode,}: {instance: Instance | undefined;type: "text" | "expression";value: string;+ expressionBindingMode?: ExpressionBindingMode;}) => {if (instance === undefined) {return;@@ -22,6 +24,9 @@ export const getTextContentUpdateOperation = ({childIndex,mode: type,text: value,+ ...(expressionBindingMode === undefined+ ? {}+ : { expressionBindingMode }),},};}@@ -35,6 +40,7 @@ export const getTextContentUpdateOperation = ({instanceId: instance.id,mode: type,text: value,+ ...(expressionBindingMode === undefined ? {} : { expressionBindingMode }),},};};diff --git a/apps/builder/app/builder/features/settings-panel/controls/text-content.test.tsx b/apps/builder/app/builder/features/settings-panel/controls/text-content.test.tsxindex b191c65899..c0f2d6279a 100644--- a/apps/builder/app/builder/features/settings-panel/controls/text-content.test.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/text-content.test.tsx@@ -168,7 +168,7 @@ test("updates only the targeted expression child through the binding editor", asexpect($instances.get().get("reading-time")?.children).toEqual([{ type: "text", value: " · " },- { type: "expression", value: "2 + 2" },+ { type: "expression", value: "2 + 2", mode: "read" },]);});diff --git a/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx b/apps/builder/app/builder/features/settings-panel/controls/text-content.tsxindex c3f516670d..40e544a0f7 100644--- a/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx@@ -9,11 +9,15 @@ import {Flex,rawTheme,Text,+ toast,} from "@webstudio-is/design-system";-import type { Instance } from "@webstudio-is/sdk";+import type { ExpressionBindingMode, Instance } from "@webstudio-is/sdk";import { AlertIcon } from "@webstudio-is/icons";import { $instances } from "~/shared/sync/data-stores";-import { validatePrimitiveValue } from "@webstudio-is/project-build/runtime";+import {+ getEditableTextTarget,+ validatePrimitiveValue,+} from "@webstudio-is/project-build/runtime";import { useDraftValue } from "~/builder/shared/use-draft-value";import { BindableExpressionControl } from "~/builder/shared/bindable-expression";import { executeRuntimeMutation } from "~/shared/instance-utils/data";@@ -22,8 +26,8 @@ import { type ControlProps, VerticalLayout } from "../shared";import { FieldLabel, useIsBindingResetForbidden } from "../property-label";import { useBindableControl } from "./use-bindable-control";import { evaluateExpressionWithinScope } from "~/builder/shared/binding-popover";-import { getEditableTextTarget } from "@webstudio-is/project-build/runtime";import { getTextContentUpdateOperation } from "./text-content-utils";+import { useCodeTextLanguageSupport } from "./code";const useInstance = (instanceId: Instance["id"]) => {const $store = useMemo(() => {@@ -34,16 +38,31 @@ const useInstance = (instanceId: Instance["id"]) => {export const TextContent = ({instanceId,+ meta,computedValue,+ computedProps,}: ControlProps<"textContent">) => {const instance = useInstance(instanceId);+ const languageProp = meta.editor?.languageProp;+ const languageSupport = useCodeTextLanguageSupport(+ languageProp === undefined ? undefined : computedProps?.get(languageProp)+ );const childrenCount = instance?.children.length ?? 0;const hasChildren = childrenCount > 0;const hasMixedContent = childrenCount > 1;const target = instance && getEditableTextTarget(instance);const child = target?.child ?? { type: "text" as const, value: "" };- const updateChild = (type: "text" | "expression", value: string) => {- const operation = getTextContentUpdateOperation({ instance, type, value });+ const updateChild = (+ type: "text" | "expression",+ value: string,+ expressionBindingMode?: ExpressionBindingMode+ ) => {+ const operation = getTextContentUpdateOperation({+ instance,+ type,+ value,+ expressionBindingMode,+ });if (operation !== undefined) {executeRuntimeMutation(operation);}@@ -82,7 +101,7 @@ export const TextContent = ({child.type === "text" ? JSON.stringify(child.value) : child.value;const binding = useBindableControl({- boundExpression: child.type === "expression" ? expression : undefined,+ boundExpression: child.type === "expression" ? child : undefined,fallbackExpression: expression,});let displayedValue = computedValue;@@ -98,6 +117,13 @@ export const TextContent = ({}const localValue = useDraftValue(String(displayedValue ?? ""), (value) => {if (child.type === "expression") {+ void binding.writeBoundValue?.(value).catch((error) => {+ toast.error(+ error instanceof Error+ ? error.message+ : "Unable to update MDX frontmatter"+ );+ });return;}updateChild("text", value);@@ -150,7 +176,9 @@ export const TextContent = ({value={localValue.value}validate={(value) => validatePrimitiveValue(value, "Text Content")}onChangeValue={(value) => updateChild("text", value)}- onChangeExpression={(value) => updateChild("expression", value)}+ onChangeExpression={(value) =>+ updateChild("expression", value, binding.getExpressionMode(value))+ }onRemove={resetBindings}renderControl={({ readOnly }) => (<CodeEditor@@ -168,6 +196,7 @@ export const TextContent = ({</DialogTitle>}size="small"+ languageSupport={languageSupport}readOnly={readOnly}value={localValue.value}onChange={localValue.set}diff --git a/apps/builder/app/builder/features/settings-panel/controls/text.test.tsx b/apps/builder/app/builder/features/settings-panel/controls/text.test.tsxnew file mode 100644index 0000000000..4047726c91--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/controls/text.test.tsx@@ -0,0 +1,148 @@+/**+ * @vitest-environment jsdom+ */+import { act } from "react-dom/test-utils";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import { TooltipProvider } from "@webstudio-is/design-system";+import {+ blockComponent,+ contentBlockDocumentProp,+ encodeDataSourceVariable,+ type Instance,+ type Prop,+} from "@webstudio-is/sdk";+import { $builderMode, selectInstance } from "~/shared/nano-states";+import { $instances, $props } from "~/shared/sync/data-stores";+import { $externalContentRoots } from "~/shared/external-content-mutations";+import { TextControl } from "./text";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ const block: Instance = {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "heading" }],+ };+ const heading: Instance = {+ type: "instance",+ id: "heading",+ component: "Heading",+ children: [],+ };+ const documentProp: Prop = {+ id: "document",+ instanceId: block.id,+ name: contentBlockDocumentProp,+ type: "parameter",+ value: "document-data-source",+ };+ const titleProp: Prop = {+ id: "title",+ instanceId: heading.id,+ name: "title",+ type: "expression",+ value: `${encodeDataSourceVariable("document-data-source")}.frontmatter.title`,+ mode: "readwrite",+ };+ const sourceProp: Prop = {+ id: "source",+ instanceId: block.id,+ name: "src",+ type: "asset",+ value: "article",+ };+ $instances.set(+ new Map([+ [block.id, block],+ [heading.id, heading],+ ])+ );+ $props.set(+ new Map<string, Prop>([+ [documentProp.id, documentProp],+ [sourceProp.id, sourceProp],+ [titleProp.id, titleProp],+ ])+ );+ $externalContentRoots.set(+ new Map([+ [+ "root",+ {+ blockInstanceId: block.id,+ instanceIds: new Set([heading.id]),+ mutationRevision: 0,+ document: {+ frontmatter: { properties: { title: "Before" } },+ children: [],+ },+ },+ ],+ ])+ );+ $builderMode.set("content");+ selectInstance([heading.id, block.id]);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ selectInstance(undefined);+ $instances.set(new Map());+ $props.set(new Map());+ $externalContentRoots.set(new Map());+ $builderMode.set("design");+});++test("saves an edited direct frontmatter binding without exposing the binding", () => {+ const onChange = vi.fn();+ const prop = $props.get().get("title");+ if (prop === undefined) {+ throw new Error("Expected title prop");+ }+ act(() => {+ root.render(+ <TooltipProvider>+ <TextControl+ instanceId="heading"+ meta={{ type: "string", control: "text", required: false }}+ prop={prop}+ propName="title"+ computedValue="Before"+ onChange={onChange}+ />+ </TooltipProvider>+ );+ });+ const input = container.querySelector<HTMLTextAreaElement>("textarea");+ if (input === null) {+ throw new Error("Expected text control");+ }++ expect(input.disabled).toBe(false);+ expect(container.querySelector('[data-variant="bound"]')).toBeNull();+ act(() => {+ input.focus();+ Object.getOwnPropertyDescriptor(+ HTMLTextAreaElement.prototype,+ "value"+ )?.set?.call(input, "After");+ input.dispatchEvent(new Event("input", { bubbles: true }));+ });+ act(() => {+ input.blur();+ });++ expect(onChange).toHaveBeenCalledWith({ type: "string", value: "After" });+});diff --git a/apps/builder/app/builder/features/settings-panel/controls/text.tsx b/apps/builder/app/builder/features/settings-panel/controls/text.tsxindex 7a9ca4f23a..0ec8da6678 100644--- a/apps/builder/app/builder/features/settings-panel/controls/text.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/text.tsx@@ -18,19 +18,18 @@ export const TextControl = ({computedValue,onChange,}: ControlProps<"text">) => {+ const binding = useBindableControl({+ boundExpression: prop?.type === "expression" ? prop : undefined,+ fallbackExpression: JSON.stringify(computedValue),+ });const localValue = useDraftValue(String(computedValue ?? ""), (value) => {- if (prop?.type === "expression") {+ if (binding.bindingState.overwritable === false) {return;}onChange({ type: "string", value });});const id = useId();const label = humanizeAttribute(meta.label || propName);- const binding = useBindableControl({- boundExpression: prop?.type === "expression" ? prop.value : undefined,- fallbackExpression: JSON.stringify(computedValue),- });-const input = (<BindableExpressionControl{...binding}diff --git a/apps/builder/app/builder/features/settings-panel/controls/time-zone.tsx b/apps/builder/app/builder/features/settings-panel/controls/time-zone.tsxindex b04bbaa60f..49bb8ec0ac 100644--- a/apps/builder/app/builder/features/settings-panel/controls/time-zone.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/time-zone.tsx@@ -192,8 +192,12 @@ export const TimeZoneControl = ({const savedValue = String(computedValue ?? meta.defaultValue ?? defaultTimeZone);+ const binding = useBindableControl({+ boundExpression: prop?.type === "expression" ? prop : undefined,+ fallbackExpression: JSON.stringify(computedValue),+ });const localValue = useDraftValue(savedValue, (value) => {- if (prop?.type === "expression") {+ if (binding.bindingState.overwritable === false) {return;}onChange({ type: "string", value });@@ -202,11 +206,6 @@ export const TimeZoneControl = ({const selectedItem = getTimeZoneItem(savedValue);const currentItem = getTimeZoneItem(localValue.value);const label = humanizeAttribute(meta.label || propName);- const binding = useBindableControl({- boundExpression: prop?.type === "expression" ? prop.value : undefined,- fallbackExpression: JSON.stringify(computedValue),- });-const datetime = getStringProp(props,instanceId,diff --git a/apps/builder/app/builder/features/settings-panel/controls/url.tsx b/apps/builder/app/builder/features/settings-panel/controls/url.tsxindex 5e2740512b..765be787e3 100644--- a/apps/builder/app/builder/features/settings-panel/controls/url.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/url.tsx@@ -103,9 +103,9 @@ const addHttpsIfMissing = (url: string) => {return url;};-const BaseUrl = ({ readOnly, prop, value, onChange, id }: BaseControlProps) => {+const BaseUrl = ({ readOnly, value, onChange, id }: BaseControlProps) => {const localValue = useDraftValue(value, (value) => {- if (prop?.type === "expression") {+ if (readOnly) {return;}onChange({ type: "string", value });@@ -140,17 +140,11 @@ const BaseUrl = ({ readOnly, prop, value, onChange, id }: BaseControlProps) => {);};-const BasePhone = ({- readOnly,- prop,- value,- onChange,- id,-}: BaseControlProps) => {+const BasePhone = ({ readOnly, value, onChange, id }: BaseControlProps) => {const localValue = useDraftValue(value.startsWith("tel:") ? value.slice(4) : "",(value) => {- if (prop?.type === "expression") {+ if (readOnly) {return;}const nextValue = `tel:${value}`;@@ -219,15 +213,9 @@ export const __testing__ = {propToEmail,};-const BaseEmail = ({- readOnly,- prop,- value,- onChange,- id,-}: BaseControlProps) => {+const BaseEmail = ({ readOnly, value, onChange, id }: BaseControlProps) => {const localValue = useDraftValue(propToEmail(value), ({ email, subject }) => {- if (prop?.type === "expression") {+ if (readOnly) {return;}const value = emailToProp({ email, subject });@@ -426,8 +414,8 @@ const BasePage = ({ prop, onChange }: BaseControlProps) => {const BaseAttachment = ({ prop, onChange }: BaseControlProps) => (<Row><SelectAsset- prop={prop?.type === "asset" ? prop : undefined}- onChange={onChange}+ assetId={prop?.type === "asset" ? prop.value : undefined}+ onChange={(assetId) => onChange({ type: "asset", value: assetId })}/></Row>);@@ -546,7 +534,7 @@ export const UrlControl = ({const value = String(computedValue ?? "");const label = humanizeAttribute(meta.label || propName);const binding = useBindableControl({- boundExpression: prop?.type === "expression" ? prop.value : undefined,+ boundExpression: prop?.type === "expression" ? prop : undefined,fallbackExpression: JSON.stringify(computedValue),});diff --git a/apps/builder/app/builder/features/settings-panel/controls/use-bindable-control.test.ts b/apps/builder/app/builder/features/settings-panel/controls/use-bindable-control.test.tsnew file mode 100644index 0000000000..0cd48f2343--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/controls/use-bindable-control.test.ts@@ -0,0 +1,41 @@+import { expect, test } from "vitest";+import { getBindableControlPresentation } from "./use-bindable-control";++test("edits a frontmatter value without exposing its binding", () => {+ expect(+ getBindableControlPresentation({+ bindingState: { overwritable: false, variant: "bound" },+ isFrontmatterBinding: true,+ isEditableFrontmatterBinding: true,+ })+ ).toEqual({+ bindingState: { overwritable: true, variant: "bound" },+ showBinding: false,+ });+});++test("keeps ordinary expression bindings read-only and visible", () => {+ expect(+ getBindableControlPresentation({+ bindingState: { overwritable: false, variant: "bound" },+ isFrontmatterBinding: false,+ isEditableFrontmatterBinding: false,+ })+ ).toEqual({+ bindingState: { overwritable: false, variant: "bound" },+ showBinding: true,+ });+});++test("keeps an unavailable frontmatter value read-only without exposing its binding", () => {+ expect(+ getBindableControlPresentation({+ bindingState: { overwritable: false, variant: "bound" },+ isFrontmatterBinding: true,+ isEditableFrontmatterBinding: false,+ })+ ).toEqual({+ bindingState: { overwritable: false, variant: "bound" },+ showBinding: false,+ });+});diff --git a/apps/builder/app/builder/features/settings-panel/controls/use-bindable-control.ts b/apps/builder/app/builder/features/settings-panel/controls/use-bindable-control.tsindex 20d9b5406c..c78f51b172 100644--- a/apps/builder/app/builder/features/settings-panel/controls/use-bindable-control.ts+++ b/apps/builder/app/builder/features/settings-panel/controls/use-bindable-control.ts@@ -1,17 +1,126 @@import { useStore } from "@nanostores/react";-import { useBindingState } from "~/builder/shared/bindable-expression";+import {+ useBindingState,+ type BindingState,+} from "~/builder/shared/bindable-expression";+import {+ $isContentMode,+ $selectedInstanceSelector,+} from "~/shared/nano-states";+import { $instances, $props } from "~/shared/sync/data-stores";+import {+ $externalContentRoots,+ findExternalContentRootEntryBySelector,+} from "~/shared/external-content-mutations";+import { updateExternalContentFrontmatter } from "~/shared/external-content-roots";+import {+ getSelectedContentBlockDocumentBindingPath,+ getSelectedContentBlockExpressionMode,+ isObjectPathWritable,+} from "~/shared/content-block-document";import { $selectedInstanceScope } from "../shared";+import type {+ ExpressionBinding,+ ExpressionBindingMode,+} from "@webstudio-is/sdk";++export const getBindableControlPresentation = ({+ bindingState,+ isFrontmatterBinding,+ isEditableFrontmatterBinding,+}: {+ bindingState: BindingState;+ isFrontmatterBinding: boolean;+ isEditableFrontmatterBinding: boolean;+}) => ({+ bindingState: {+ ...bindingState,+ overwritable:+ isEditableFrontmatterBinding || bindingState.overwritable === true,+ },+ showBinding: isFrontmatterBinding === false,+});export const useBindableControl = ({boundExpression,fallbackExpression,}: {- boundExpression?: string;+ boundExpression?: Pick<ExpressionBinding, "value" | "mode">;fallbackExpression: string;}) => {const { scope, aliases } = useStore($selectedInstanceScope);- const bindingState = useBindingState(boundExpression);+ const selectedInstanceSelector = useStore($selectedInstanceSelector);+ const externalContentRoots = useStore($externalContentRoots);+ const isContentMode = useStore($isContentMode);+ const bindingState = useBindingState(boundExpression?.value);+ const externalEntry =+ selectedInstanceSelector === undefined+ ? undefined+ : findExternalContentRootEntryBySelector(+ externalContentRoots,+ selectedInstanceSelector+ );+ const externalRoot = externalEntry?.[1];+ const frontmatterPath =+ isContentMode &&+ boundExpression !== undefined &&+ selectedInstanceSelector !== undefined+ ? getSelectedContentBlockDocumentBindingPath({+ binding: {+ type: "expression",+ ...boundExpression,+ },+ instanceSelector: selectedInstanceSelector,+ instances: $instances.get(),+ props: $props.get(),+ sourceBlockInstanceId: externalRoot?.sourceBlockInstanceId,+ renderedBlockInstanceId: externalRoot?.blockInstanceId,+ })+ : undefined;+ const isEditableFrontmatterBinding =+ frontmatterPath !== undefined &&+ externalRoot?.document !== undefined &&+ isObjectPathWritable({+ value: externalRoot.document.frontmatter.properties,+ path: frontmatterPath,+ });const bound = boundExpression !== undefined;- const expression = boundExpression ?? fallbackExpression;- return { expression, bound, scope, aliases, bindingState };+ const expression = boundExpression?.value ?? fallbackExpression;+ const writeBoundValue =+ frontmatterPath !== undefined &&+ externalEntry !== undefined &&+ isEditableFrontmatterBinding+ ? (value: unknown) =>+ updateExternalContentFrontmatter({+ rootKey: externalEntry[0],+ path: frontmatterPath,+ value,+ })+ : undefined;+ const getExpressionMode = (value: string): ExpressionBindingMode => {+ if (selectedInstanceSelector === undefined) {+ return "read";+ }+ return getSelectedContentBlockExpressionMode({+ expression: value,+ instanceSelector: selectedInstanceSelector,+ instances: $instances.get(),+ props: $props.get(),+ sourceBlockInstanceId: externalRoot?.sourceBlockInstanceId,+ renderedBlockInstanceId: externalRoot?.blockInstanceId,+ });+ };+ return {+ expression,+ bound,+ scope,+ aliases,+ getExpressionMode,+ writeBoundValue,+ ...getBindableControlPresentation({+ bindingState,+ isFrontmatterBinding: frontmatterPath !== undefined,+ isEditableFrontmatterBinding,+ }),+ };};diff --git a/apps/builder/app/builder/features/settings-panel/controls/use-string-options.ts b/apps/builder/app/builder/features/settings-panel/controls/use-string-options.tsindex 31bdcbdd71..052c6a93ef 100644--- a/apps/builder/app/builder/features/settings-panel/controls/use-string-options.ts+++ b/apps/builder/app/builder/features/settings-panel/controls/use-string-options.ts@@ -20,7 +20,7 @@ export const useStringOptions = ({: [value, ...meta.options];const label = humanizeAttribute(meta.label || propName);const binding = useBindableControl({- boundExpression: prop?.type === "expression" ? prop.value : undefined,+ boundExpression: prop?.type === "expression" ? prop : undefined,fallbackExpression: JSON.stringify(computedValue),});diff --git a/apps/builder/app/builder/features/settings-panel/property-label.test.tsx b/apps/builder/app/builder/features/settings-panel/property-label.test.tsxnew file mode 100644index 0000000000..f852dc0061--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/property-label.test.tsx@@ -0,0 +1,107 @@+/**+ * @vitest-environment jsdom+ */+import { act } from "react-dom/test-utils";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import { TooltipProvider } from "@webstudio-is/design-system";+import {+ blockComponent,+ contentBlockSourceProp,+ coreMetas,+ type Instance,+ type Prop,+} from "@webstudio-is/sdk";+import {+ $authPermit,+ $registeredComponentMetas,+ selectInstance,+} from "~/shared/nano-states";+import { $instances, $props } from "~/shared/sync/data-stores";+import { PropertyLabel } from "./property-label";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const block: Instance = {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [],+};+const source: Prop = {+ id: "source",+ instanceId: block.id,+ name: contentBlockSourceProp,+ type: "asset",+ value: "asset",+};++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ $instances.set(new Map([[block.id, block]]));+ $props.set(new Map([[source.id, source]]));+ $registeredComponentMetas.set(new Map(Object.entries(coreMetas)));+ $authPermit.set("build");+ selectInstance([block.id]);+});++afterEach(() => {+ act(() => root.unmount());+ document.body.innerHTML = "";+ selectInstance(undefined);+ $instances.set(new Map());+ $props.set(new Map());+ $registeredComponentMetas.set(new Map());+ $authPermit.set("view");+ vi.unstubAllGlobals();+});++test("uses the deletion override for tooltip reset and Alt-click", () => {+ const onDelete = vi.fn();+ act(() => {+ root.render(+ <TooltipProvider>+ <PropertyLabel name={contentBlockSourceProp} onDelete={onDelete} />+ </TooltipProvider>+ );+ });++ const label = Array.from(+ container.querySelectorAll<HTMLButtonElement>("button")+ ).find((element) => element.textContent === "Source");+ if (label === undefined) {+ throw new Error("Expected Source property label");+ }++ act(() => label.click());+ const reset = Array.from(+ document.body.querySelectorAll<HTMLButtonElement>("button")+ ).find((button) => button.textContent?.includes("Reset value"));+ if (reset === undefined) {+ throw new Error("Expected Reset value action");+ }+ act(() => reset.click());+ expect(onDelete).toHaveBeenCalledOnce();++ act(() =>+ label.dispatchEvent(+ new MouseEvent("click", { altKey: true, bubbles: true })+ )+ );+ expect(onDelete).toHaveBeenCalledTimes(2);+});diff --git a/apps/builder/app/builder/features/settings-panel/property-label.tsx b/apps/builder/app/builder/features/settings-panel/property-label.tsxindex fb89f95769..c11822cb75 100644--- a/apps/builder/app/builder/features/settings-panel/property-label.tsx+++ b/apps/builder/app/builder/features/settings-panel/property-label.tsx@@ -96,9 +96,13 @@ const useIsResettable = (name: string) => {export const PropertyLabel = ({name,readOnly,+ deletable = true,+ onDelete,}: {name: string;readOnly?: boolean;+ deletable?: boolean;+ onDelete?: () => void;}) => {const [isOpen, setIsOpen] = useState(false);const propMeta = usePropMeta(name);@@ -109,7 +113,16 @@ export const PropertyLabel = ({const isResettable = useIsResettable(name);const isBindingResetForbidden = useIsBindingResetForbidden();const canDelete =- isDeletable && !(prop?.type === "expression" && isBindingResetForbidden);+ deletable &&+ isDeletable &&+ !(prop?.type === "expression" && isBindingResetForbidden);+ const handleDelete = () => {+ if (onDelete === undefined) {+ deleteProp(name);+ return;+ }+ onDelete();+ };return (<Flex align="center" css={{ gap: theme.spacing[3] }}>{/* prevent label growing */}@@ -122,7 +135,7 @@ export const PropertyLabel = ({if (event.altKey) {event.preventDefault();if (canDelete) {- deleteProp(name);+ handleDelete();}return;}@@ -159,7 +172,7 @@ export const PropertyLabel = ({suffix={<Kbd value={["alt", "click"]} color="moreSubtle" />}css={{ gridTemplateColumns: "1fr max-content 1fr" }}onClick={() => {- deleteProp(name);+ handleDelete();setIsOpen(false);}}>diff --git a/apps/builder/app/builder/features/settings-panel/props-section/props-section.test.ts b/apps/builder/app/builder/features/settings-panel/props-section/props-section.test.tsindex bc1e011414..d5e65d2e68 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/props-section.test.ts+++ b/apps/builder/app/builder/features/settings-panel/props-section/props-section.test.ts@@ -1,13 +1,49 @@import { describe, expect, test } from "vitest";-import { rootComponent } from "@webstudio-is/sdk";+import { blockComponent, rootComponent, type Prop } from "@webstudio-is/sdk";import { __testing__ } from "./props-section";const {shouldShowPropertiesSection,shouldRenderPropsSectionContainer,shouldSyncMediaAssetProps,+ findExpressionPropByStandardName,+ shouldWriteBoundValue,} = __testing__;+test("finds a legacy React-named expression by its standard attribute name", () => {+ const className: Prop = {+ id: "class-name",+ instanceId: "heading",+ name: "className",+ type: "expression",+ value: "$ws$dataSource$document.frontmatter.className",+ };++ expect(+ findExpressionPropByStandardName({+ props: [className],+ instanceId: "heading",+ propName: "class",+ })+ ).toBe(className);+});++test("writes bound values only in Content mode", () => {+ expect(+ shouldWriteBoundValue(true, { type: "string", value: "New title" })+ ).toBe(true);+ expect(+ shouldWriteBoundValue(false, { type: "string", value: "New title" })+ ).toBe(false);+ expect(+ shouldWriteBoundValue(true, {+ type: "expression",+ value: "$ws$dataSource$document.frontmatter.subtitle",+ mode: "readwrite",+ })+ ).toBe(false);+});+describe("shouldShowPropertiesSection", () => {test("shows properties in design mode even when empty", () => {expect(@@ -55,6 +91,7 @@ describe("shouldRenderPropsSectionContainer", () => {propsMetasSize: 1,hasVisibleProps: false,isContentMode: false,+ isDesignMode: true,})).toBe(true);});@@ -66,6 +103,7 @@ describe("shouldRenderPropsSectionContainer", () => {propsMetasSize: 0,hasVisibleProps: true,isContentMode: true,+ isDesignMode: false,})).toBe(true);});@@ -77,6 +115,7 @@ describe("shouldRenderPropsSectionContainer", () => {propsMetasSize: 1,hasVisibleProps: true,isContentMode: true,+ isDesignMode: true,})).toBe(false);expect(@@ -85,6 +124,7 @@ describe("shouldRenderPropsSectionContainer", () => {propsMetasSize: 0,hasVisibleProps: true,isContentMode: false,+ isDesignMode: false,})).toBe(false);expect(@@ -93,6 +133,28 @@ describe("shouldRenderPropsSectionContainer", () => {propsMetasSize: 0,hasVisibleProps: false,isContentMode: true,+ isDesignMode: false,+ })+ ).toBe(false);+ });++ test("renders an empty Content Block settings container only in Design mode", () => {+ expect(+ shouldRenderPropsSectionContainer({+ component: blockComponent,+ propsMetasSize: 0,+ hasVisibleProps: false,+ isContentMode: false,+ isDesignMode: true,+ })+ ).toBe(true);+ expect(+ shouldRenderPropsSectionContainer({+ component: blockComponent,+ propsMetasSize: 0,+ hasVisibleProps: false,+ isContentMode: true,+ isDesignMode: false,})).toBe(false);});@@ -132,4 +194,15 @@ describe("shouldSyncMediaAssetProps", () => {})).toBe(false);});++ test("does not copy an Asset into related frontmatter bindings", () => {+ expect(+ shouldSyncMediaAssetProps({+ component: "Image",+ propName: "src",+ propValue: { type: "asset" },+ propType: "expression",+ })+ ).toBe(false);+ });});diff --git a/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx b/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsxindex f70c76c452..b69ddd6e69 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx+++ b/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx@@ -5,7 +5,11 @@ import { useStore } from "@nanostores/react";import { matchSorter } from "match-sorter";import {type Instance,+ type Prop,type Props,+ blockComponent,+ contentBlockSourceProp,+ toAssetReferenceRuntimeData,descendantComponent,rootComponent,} from "@webstudio-is/sdk";@@ -16,6 +20,7 @@ import {Flex,Box,Grid,+ toast,} from "@webstudio-is/design-system";import {isAttributeNameSafe,@@ -31,11 +36,17 @@ import {$memoryProps,$selectedBreakpoint,} from "~/shared/nano-states";-import { $props } from "~/shared/sync/data-stores";+import {+ $assetFolders,+ $assets,+ $instances,+ $props,+} from "~/shared/sync/data-stores";import { CollapsibleSectionWithAddButton } from "~/builder/shared/collapsible-section";import {$selectedInstance,$selectedInstanceKey,+ $selectedInstanceSelector,getInstanceKey,} from "~/shared/nano-states";import { renderControl } from "../controls/combined";@@ -48,6 +59,23 @@ import {$selectedInstancePropsMetas,} from "../shared";import { executeRuntimeMutation } from "~/shared/instance-utils/data";+import { ContentBlockSourceSection } from "../controls/content-block-source-section";+import {+ $externalContentRoots,+ findExternalContentRootEntryBySelector,+} from "~/shared/external-content-mutations";+import { updateExternalContentFrontmatter } from "~/shared/external-content-roots";+import {+ getSelectedContentBlockDocumentBindingPath,+ getSelectedContentBlockExpressionMode,+ isObjectPathWritable,+} from "~/shared/content-block-document";+import {+ createMdxAssetReferenceValues,+ findProp,+} from "@webstudio-is/project-build/runtime";+import { resolveAssetValueReferences } from "@webstudio-is/content-engine";+import type { PropValue } from "../shared";type Item = {name: string;@@ -97,15 +125,20 @@ const shouldRenderPropsSectionContainer = ({propsMetasSize,hasVisibleProps,isContentMode,+ isDesignMode,}: {component: Instance["component"];propsMetasSize: number;hasVisibleProps: boolean;isContentMode: boolean;+ isDesignMode: boolean;}) => {if (component === rootComponent) {return false;}+ if (component === blockComponent) {+ return isDesignMode || (isContentMode && hasVisibleProps);+ }return propsMetasSize > 0 || (isContentMode && hasVisibleProps);};@@ -113,14 +146,43 @@ const shouldSyncMediaAssetProps = ({component,propName,propValue,+ propType,}: {component: Instance["component"];propName: string;propValue: { type: string };+ propType?: Prop["type"];}) =>(component === "Image" || component === "Video") &&propName === "src" &&- propValue.type === "asset";+ propValue.type === "asset" &&+ propType !== "expression";++const findExpressionPropByStandardName = ({+ props,+ instanceId,+ propName,+}: {+ props: readonly Prop[];+ instanceId: Instance["id"];+ propName: Prop["name"];+}) => {+ const findExpression = (name: string) => {+ const prop = findProp(props, instanceId, name);+ return prop?.type === "expression" ? prop : undefined;+ };+ const reactPropName = standardAttributesToReactProps[propName];+ return (+ findExpression(propName) ??+ (reactPropName === undefined ? undefined : findExpression(reactPropName))+ );+};++const shouldWriteBoundValue = (+ isContentMode: boolean,+ update: PropValue+): update is Exclude<PropValue, { type: "expression" }> =>+ isContentMode && update.type !== "expression";const renderProperty = ({@@ -129,10 +191,20 @@ const renderProperty = (propValuesByInstanceSelector,component,instanceId,+ selectedInstanceKey,}: PropsSectionProps,item: PropAndMeta) => {const { prop, propName, meta } = item;+ if (component === blockComponent && propName === contentBlockSourceProp) {+ return (+ <ContentBlockSourceSection+ key={propName}+ blockInstanceId={instanceId}+ renderScope={selectedInstanceKey}+ />+ );+ }const targetInstanceId = item.instanceId ?? instanceId;const targetPropValues =item.instanceSelector === undefined@@ -161,6 +233,7 @@ const renderProperty = (component,propName,propValue,+ propType: prop?.type,})) {logic.handleChangeByPropName("width", propValue);@@ -274,8 +347,9 @@ export const PropsSection = (props: PropsSectionProps) => {const matchMediaValue = matchMediaBreakpoints(matchingBreakpoints);- const hasProperties =- logic.addedProps.length > 0 || logic.initialProps.length > 0;+ const addedProps = logic.addedProps;+ const initialProps = logic.initialProps;+ const hasProperties = addedProps.length > 0 || initialProps.length > 0;const hasItems = hasProperties || (isDesignMode && addingProp);const animationAction = logic.initialProps.find(@@ -368,8 +442,8 @@ export const PropsSection = (props: PropsSectionProps) => {}}/>)}- {logic.addedProps.map((item) => renderProperty(props, item))}- {logic.initialProps.map((item) => renderProperty(props, item))}+ {addedProps.map((item) => renderProperty(props, item))}+ {initialProps.map((item) => renderProperty(props, item))}</Flex></CollapsibleSectionWithAddButton>)}@@ -381,6 +455,8 @@ export const __testing__ = {shouldShowPropertiesSection,shouldRenderPropsSectionContainer,shouldSyncMediaAssetProps,+ findExpressionPropByStandardName,+ shouldWriteBoundValue,};const $propValues = computed(@@ -399,16 +475,149 @@ export const PropsSectionContainer = ({const { propsByInstanceId } = useStore($propsIndex);const propValues = useStore($propValues);const propValuesByInstanceSelector = useStore($propValuesByInstanceSelector);+ const selectedInstanceSelector = useStore($selectedInstanceSelector);+ const externalContentRoots = useStore($externalContentRoots);+ const assets = useStore($assets);+ const assetFolders = useStore($assetFolders);const logic = usePropsLogic({instance,props: propsByInstanceId.get(instance.id) ?? [],updateProp: (update) => {+ const originalProp = findExpressionPropByStandardName({+ props: propsByInstanceId.get(instance.id) ?? [],+ instanceId: instance.id,+ propName: update.name,+ });+ const externalEntry =+ selectedInstanceSelector === undefined+ ? undefined+ : findExternalContentRootEntryBySelector(+ externalContentRoots,+ selectedInstanceSelector+ );+ const candidateRoot = externalEntry?.[1];+ const persistedUpdate =+ update.type === "expression"+ ? {+ ...update,+ mode:+ selectedInstanceSelector === undefined+ ? "read"+ : getSelectedContentBlockExpressionMode({+ expression: update.value,+ instanceSelector: selectedInstanceSelector,+ instances: $instances.get(),+ props: $props.get(),+ sourceBlockInstanceId:+ candidateRoot?.sourceBlockInstanceId,+ renderedBlockInstanceId: candidateRoot?.blockInstanceId,+ }),+ }+ : update;+ if (+ originalProp?.type === "expression" &&+ shouldWriteBoundValue($isContentMode.get(), persistedUpdate)+ ) {+ const path =+ selectedInstanceSelector === undefined+ ? undefined+ : getSelectedContentBlockDocumentBindingPath({+ binding: originalProp,+ instanceSelector: selectedInstanceSelector,+ instances: $instances.get(),+ props: $props.get(),+ sourceBlockInstanceId: candidateRoot?.sourceBlockInstanceId,+ renderedBlockInstanceId: candidateRoot?.blockInstanceId,+ });+ if (path !== undefined && externalEntry === undefined) {+ toast.error("The MDX content source is not ready for editing.");+ return;+ }+ if (path === undefined || externalEntry === undefined) {+ executeRuntimeMutation({+ id: "instances.updateProps",+ input: { updates: [persistedUpdate] },+ });+ return;+ }+ const [rootKey, externalRoot] = externalEntry;+ let targetPath: readonly string[] = path;+ let nextValue: unknown = update.value;+ let nextResolvedValue: unknown = update.value;+ if (update.type === "asset" && externalRoot.identity !== undefined) {+ const sourceAsset = assets.get(externalRoot.identity.assetId);+ const targetAsset = assets.get(update.value);+ const reference =+ sourceAsset === undefined || targetAsset === undefined+ ? undefined+ : createMdxAssetReferenceValues({+ source: sourceAsset,+ assets: assets.values(),+ assetFolders,+ }).get(targetAsset.id);+ if (reference !== undefined && targetAsset !== undefined) {+ targetPath =+ path.length > 1 && path.at(-1) === "src"+ ? path.slice(0, -1)+ : path;+ nextValue = { $ref: reference };+ nextResolvedValue = resolveAssetValueReferences({+ value: nextValue,+ references: [+ {+ path: [],+ assetId: targetAsset.id,+ structured: true,+ },+ ],+ runtimeAssets: {+ [targetAsset.id]: toAssetReferenceRuntimeData(+ targetAsset,+ window.location.origin+ ),+ },+ });+ }+ }+ if (externalRoot.document === undefined) {+ toast.error("The MDX content source is not ready for editing.");+ return;+ }+ if (+ isObjectPathWritable({+ value: externalRoot.document.frontmatter.properties,+ path: targetPath,+ }) === false+ ) {+ toast.error("Open the referenced file to edit this value.");+ return;+ }+ if (update.type === "asset" && typeof nextValue !== "object") {+ toast.error(+ "The selected Asset cannot be referenced from this file."+ );+ return;+ }+ void updateExternalContentFrontmatter({+ rootKey,+ path: targetPath,+ value: nextValue,+ resolvedValue: nextResolvedValue,+ }).catch((error) => {+ toast.error(+ error instanceof Error+ ? error.message+ : "Unable to update MDX frontmatter"+ );+ });+ return;+ }executeRuntimeMutation({id: "instances.updateProps",input: {- updates: [update],+ updates: [persistedUpdate],},});},@@ -416,6 +625,7 @@ export const PropsSectionContainer = ({const propsMetas = useStore($selectedInstancePropsMetas);const isContentMode = useStore($isContentMode);+ const isDesignMode = useStore($isDesignMode);const hasVisibleProps =logic.systemProps.length > 0 ||logic.initialProps.length > 0 ||@@ -426,6 +636,7 @@ export const PropsSectionContainer = ({propsMetasSize: propsMetas.size,hasVisibleProps,isContentMode,+ isDesignMode,}) === false) {return;diff --git a/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.test.ts b/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.test.tsindex ce487a644c..8a79d888d9 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.test.ts+++ b/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.test.ts@@ -5,6 +5,7 @@ import type {PropMeta,WsComponentMeta,} from "@webstudio-is/sdk";+import { blockComponent, contentBlockSourceProp } from "@webstudio-is/sdk";import { textContentAttribute } from "@webstudio-is/react-sdk";import { __testing__ } from "./use-props-logic";import type { ContentModeCapabilities } from "@webstudio-is/project-build/runtime";@@ -15,6 +16,7 @@ const { isPropVisibleInContentMode, getAndDelete, canShowTextContent } =const getInput = (input: Partial<Parameters<typeof isPropVisibleInContentMode>[0]> = {}): Parameters<typeof isPropVisibleInContentMode>[0] => ({+ component: "Box",propName: "title",props: [],propsMetas: new Map(),@@ -66,6 +68,52 @@ describe("isPropVisibleInContentMode", () => {).toBe(true);});+ test("shows only the exact frontmatter-bound shell property", () => {+ const title: Prop = {+ id: "title-prop",+ instanceId: "editable-instance",+ name: "title",+ type: "expression",+ value: "$ws$dataSource$document.frontmatter.title",+ };+ const description: Prop = {+ id: "description-prop",+ instanceId: "editable-instance",+ name: "description",+ type: "string",+ value: "Designed description",+ };+ const capabilities = {+ ...getInput().capabilities,+ editableInstanceIds: new Set<string>(),+ frontmatterBoundPropIds: new Set([title.id]),+ };++ expect(+ isPropVisibleInContentMode(+ getInput({ props: [title, description], capabilities })+ )+ ).toBe(true);+ expect(+ isPropVisibleInContentMode(+ getInput({+ propName: "description",+ props: [title, description],+ capabilities,+ })+ )+ ).toBe(false);+ expect(+ isPropVisibleInContentMode(+ getInput({+ propName: textContentAttribute,+ props: [title, description],+ capabilities,+ })+ )+ ).toBe(false);+ });+test("shows existing asset props as content", () => {const prop: Prop = {id: "image-prop",@@ -106,6 +154,64 @@ describe("isPropVisibleInContentMode", () => {).toBe(true);});+ test("keeps explicitly Design-mode file controls out of Content mode", () => {+ const fileMeta: PropMeta = {+ type: "string",+ control: "file",+ required: false,+ contentMode: false,+ };++ expect(+ isPropVisibleInContentMode(+ getInput({+ propName: "src",+ propsMetas: new Map([["src", fileMeta]]),+ })+ )+ ).toBe(false);+ });++ test("shows an existing Content Block source without making it editable", () => {+ const source: Prop = {+ id: "source-prop",+ instanceId: "editable-instance",+ name: contentBlockSourceProp,+ type: "asset",+ value: "post",+ };+ const sourceMeta: PropMeta = {+ type: "string",+ control: "file",+ required: false,+ contentMode: false,+ };++ expect(+ isPropVisibleInContentMode(+ getInput({+ component: blockComponent,+ propName: contentBlockSourceProp,+ props: [source],+ propsMetas: new Map([[contentBlockSourceProp, sourceMeta]]),+ capabilities: {+ ...getInput().capabilities,+ editableInstanceIds: new Set(),+ },+ })+ )+ ).toBe(true);+ expect(+ isPropVisibleInContentMode(+ getInput({+ component: blockComponent,+ propName: contentBlockSourceProp,+ propsMetas: new Map([[contentBlockSourceProp, sourceMeta]]),+ })+ )+ ).toBe(false);+ });+test("shows only props marked as content mode in metadata", () => {const contentModeMeta: PropMeta = {type: "string",diff --git a/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts b/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.tsindex 43f4c561bf..acb2c302fa 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts+++ b/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts@@ -6,7 +6,11 @@ import type {Props,WsComponentMeta,} from "@webstudio-is/sdk";-import { descendantComponent } from "@webstudio-is/sdk";+import {+ blockComponent,+ contentBlockSourceProp,+ descendantComponent,+} from "@webstudio-is/sdk";import {canHaveTextContent,createStartingPropValueFromMeta,@@ -49,27 +53,50 @@ export type PropAndMeta = {};const isPropVisibleInContentMode = ({+ component,propName,props,propsMetas,selectedInstanceSelector,capabilities,}: {+ component: Instance["component"];propName: string;props: Prop[];propsMetas: Map<string, PropMeta>;selectedInstanceSelector: undefined | Instance["id"][];capabilities: ContentModeCapabilities;}) => {- if (- selectedInstanceSelector === undefined ||- capabilities.editableInstanceIds.has(selectedInstanceSelector[0]) === false- ) {+ if (selectedInstanceSelector === undefined) {return false;}+ if (component === blockComponent && propName === contentBlockSourceProp) {+ return props.some(+ (prop) =>+ prop.name === contentBlockSourceProp &&+ (prop.type === "asset" || prop.type === "expression")+ );+ }+ const instanceId = selectedInstanceSelector[0];+ if (capabilities.editableInstanceIds.has(instanceId) === false) {+ if (propName === textContentAttribute) {+ return (+ capabilities.frontmatterBoundTextInstanceIds?.has(instanceId) === true+ );+ }+ return props.some(+ (prop) =>+ prop.name === propName &&+ capabilities.frontmatterBoundPropIds?.has(prop.id) === true+ );+ }if (propName === textContentAttribute) {return true;}+ const propMeta = propsMetas.get(propName);+ if (propMeta?.contentMode === false) {+ return false;+ }if (props.some((prop) =>@@ -78,7 +105,6 @@ const isPropVisibleInContentMode = ({) {return true;}- const propMeta = propsMetas.get(propName);if (propMeta?.type === "string" && propMeta.control === "file") {return true;}@@ -181,6 +207,7 @@ export const usePropsLogic = ({return false;}return isPropVisibleInContentMode({+ component: instance.component,propName,props,propsMetas,@@ -256,7 +283,7 @@ export const usePropsLogic = ({propName: textContentAttribute,instanceId: textContentTarget.instanceId,instanceSelector: textContentTarget.instanceSelector,- meta: {+ meta: metas.get(instance.component)?.textContent ?? {required: false,control: "textContent",type: "string",diff --git a/apps/builder/app/builder/features/settings-panel/settings-section.tsx b/apps/builder/app/builder/features/settings-panel/settings-section.tsxindex 6cc8670510..d2ffb9e463 100644--- a/apps/builder/app/builder/features/settings-panel/settings-section.tsx+++ b/apps/builder/app/builder/features/settings-panel/settings-section.tsx@@ -1,25 +1,54 @@-import { useId } from "react";+import { useEffect, useId, useState } from "react";import { useStore } from "@nanostores/react";-import { InputField } from "@webstudio-is/design-system";+import { InputField, Tooltip } from "@webstudio-is/design-system";import { useDraftValue } from "~/builder/shared/use-draft-value";import { HorizontalLayout, Label, Row } from "./shared";import { $selectedInstance } from "~/shared/nano-states";import { getInstanceLabel } from "~/builder/shared/instance-label";-import { executeRuntimeMutation } from "~/shared/instance-utils/data";--const saveLabel = (label: string, instanceId: string) => {- executeRuntimeMutation({- id: "instances.setLabel",- input: { instanceId, label },- });-};+import {+ executeRuntimeMutation,+ getDuplicateTemplateNameMessage,+} from "~/shared/instance-utils/data";+import {+ $externalContentRoots,+ externalContentInstanceNameMessage,+ isExternalContentInstance,+} from "~/shared/external-content-mutations";export const SettingsSection = () => {const selectedInstance = useStore($selectedInstance);+ const externalContentRoots = useStore($externalContentRoots);const id = useId();+ const [error, setError] = useState<string>();+ useEffect(() => setError(undefined), [selectedInstance?.id]);const localValue = useDraftValue(selectedInstance?.label ?? "",- (value) => selectedInstance && saveLabel(value, selectedInstance.id),+ (value) => {+ if (selectedInstance === undefined) {+ return;+ }+ if (+ isExternalContentInstance(+ $externalContentRoots.get(),+ selectedInstance.id+ )+ ) {+ return;+ }+ try {+ executeRuntimeMutation({+ id: "instances.setLabel",+ input: { instanceId: selectedInstance.id, label: value },+ });+ setError(undefined);+ } catch (error) {+ const message = getDuplicateTemplateNameMessage(error);+ if (message === undefined) {+ throw error;+ }+ setError(message);+ }+ },{ autoSave: false });@@ -28,19 +57,33 @@ export const SettingsSection = () => {}const placeholder = getInstanceLabel(selectedInstance);+ const isNameEditable =+ isExternalContentInstance(externalContentRoots, selectedInstance.id) ===+ false;return (<Row><HorizontalLayout label={<Label htmlFor={id}>Name</Label>}>- <InputField- id={id}- /* Key is required, otherwise when label is undefined, previous value stayed */- key={selectedInstance.id}- placeholder={placeholder}- value={localValue.value}- onChange={(event) => localValue.set(event.target.value)}- onBlur={localValue.save}- />+ <Tooltip+ content={isNameEditable ? error : externalContentInstanceNameMessage}+ delayDuration={0}+ >+ <InputField+ id={id}+ /* Key is required, otherwise when label is undefined, previous value stayed */+ key={selectedInstance.id}+ placeholder={placeholder}+ value={localValue.value}+ color={error === undefined ? undefined : "error"}+ aria-invalid={error === undefined ? undefined : true}+ disabled={isNameEditable === false}+ onChange={(event) => {+ setError(undefined);+ localValue.set(event.target.value);+ }}+ onBlur={localValue.save}+ />+ </Tooltip></HorizontalLayout></Row>);diff --git a/apps/builder/app/builder/features/settings-panel/shared.tsx b/apps/builder/app/builder/features/settings-panel/shared.tsxindex 43beac8ca1..2b47b0e6ac 100644--- a/apps/builder/app/builder/features/settings-panel/shared.tsx+++ b/apps/builder/app/builder/features/settings-panel/shared.tsx@@ -54,7 +54,7 @@ export type PropValue =| { type: "boolean"; value: boolean }| { type: "json"; value: unknown }| { type: "string[]"; value: string[] }- | { type: "expression"; value: string }+ | Pick<Extract<Prop, { type: "expression" }>, "type" | "value" | "mode">| { type: "asset"; value: Asset["id"] }| { type: "page"; value: Extract<Prop, { type: "page" }>["value"] }| { type: "action"; value: Extract<Prop, { type: "action" }>["value"] }diff --git a/apps/builder/app/builder/features/template-name-confirmation-dialog.test.tsx b/apps/builder/app/builder/features/template-name-confirmation-dialog.test.tsxnew file mode 100644index 0000000000..15a66e17cc--- /dev/null+++ b/apps/builder/app/builder/features/template-name-confirmation-dialog.test.tsx@@ -0,0 +1,74 @@+/**+ * @vitest-environment jsdom+ */+import { act } from "react-dom/test-utils";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import { $pendingTemplateNameConfirmation } from "~/shared/instance-utils/data";+import { TemplateNameConfirmationDialog } from "./template-name-confirmation-dialog";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ document.body.innerHTML = "";+ $pendingTemplateNameConfirmation.set(undefined);+ vi.unstubAllGlobals();+});++test.each([+ { action: "rename" as const, title: "Rename template", confirm: "Rename" },+ { action: "delete" as const, title: "Delete template", confirm: "Delete" },+])("shows exact $action actions and aborts accessibly", (expected) => {+ act(() => {+ $pendingTemplateNameConfirmation.set({+ operation:+ expected.action === "rename"+ ? {+ id: "instances.setLabel",+ input: { instanceId: "card", label: "Hero Card" },+ }+ : { id: "instances.delete", input: { instanceIds: ["card"] } },+ confirmation: {+ action: expected.action,+ templates: [{ instanceId: "card", oldName: "Card" }],+ },+ });+ root.render(<TemplateNameConfirmationDialog />);+ });++ const dialog = document.body.querySelector('[role="dialog"]');+ expect(dialog?.getAttribute("aria-labelledby")).toBeTruthy();+ expect(dialog?.textContent).toContain(expected.title);+ expect(+ Array.from(dialog?.querySelectorAll("button") ?? [], (button) =>+ button.textContent?.trim()+ ).filter(Boolean)+ ).toEqual(["Abort", expected.confirm]);++ act(() => {+ Array.from(dialog?.querySelectorAll("button") ?? [])+ .find((button) => button.textContent === "Abort")+ ?.click();+ });+ expect($pendingTemplateNameConfirmation.get()).toBeUndefined();+});diff --git a/apps/builder/app/builder/features/template-name-confirmation-dialog.tsx b/apps/builder/app/builder/features/template-name-confirmation-dialog.tsxnew file mode 100644index 0000000000..6843183711--- /dev/null+++ b/apps/builder/app/builder/features/template-name-confirmation-dialog.tsx@@ -0,0 +1,59 @@+import { useStore } from "@nanostores/react";+import {+ Button,+ Dialog,+ DialogActions,+ DialogContent,+ DialogDescription,+ DialogTitle,+ Text,+ theme,+} from "@webstudio-is/design-system";+import {+ $pendingTemplateNameConfirmation,+ abortPendingTemplateNameConfirmation,+ confirmPendingTemplateNameChange,+} from "~/shared/instance-utils/data";++export const TemplateNameConfirmationDialog = () => {+ const pending = useStore($pendingTemplateNameConfirmation);+ const action = pending?.confirmation.action;+ return (+ <Dialog+ open={pending !== undefined}+ onOpenChange={(open) => {+ if (open === false) {+ abortPendingTemplateNameConfirmation();+ }+ }}+ >+ <DialogContent>+ <DialogTitle suffix={false}>+ {action === "delete" ? "Delete template" : "Rename template"}+ </DialogTitle>+ <DialogDescription asChild>+ <Text css={{ padding: theme.spacing[5] }}>+ {action === "delete"+ ? "Deleting this template may disconnect references in connected MDX files. The files will not be changed."+ : "Renaming this template may disconnect references in connected MDX files. The files will not be changed."}+ </Text>+ </DialogDescription>+ <DialogActions>+ <Button+ autoFocus+ color="neutral"+ onClick={abortPendingTemplateNameConfirmation}+ >+ Abort+ </Button>+ <Button+ color={action === "delete" ? "destructive" : "primary"}+ onClick={confirmPendingTemplateNameChange}+ >+ {action === "delete" ? "Delete" : "Rename"}+ </Button>+ </DialogActions>+ </DialogContent>+ </Dialog>+ );+};diff --git a/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.test.ts b/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.test.tsindex 12e8d04022..00165ec365 100644--- a/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.test.ts+++ b/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.test.ts@@ -1,7 +1,8 @@-import { expect, test } from "vitest";+import { expect, test, vi } from "vitest";import type { Asset } from "@webstudio-is/sdk";import {createTextFileData,+ createTextFile,getTextFileNameError,} from "./create-text-file-dialog";@@ -29,6 +30,9 @@ test("accepts supported text names and rejects invalid or duplicate names", () =expect(getTextFileNameError({ name: "data.json", assets: [existing] })).toBeUndefined();+ expect(+ getTextFileNameError({ name: "component.mdx", assets: [] })+ ).toBeUndefined();expect(getTextFileNameError({ name: "image.png", assets: [] })).toBe("Use a supported editable text extension.");@@ -54,6 +58,38 @@ test("compares global complete display names after an asset is renamed", () => {})).toBe("A file with this name already exists.");});++test("can restrict creation to the requested text format", () => {+ expect(+ getTextFileNameError({+ name: "post.mdx",+ assets: [],+ allowedExtensions: ["mdx"],+ })+ ).toBeUndefined();+ expect(+ getTextFileNameError({+ name: "post.md",+ assets: [],+ allowedExtensions: ["mdx"],+ })+ ).toBe("Use a supported editable text extension.");+ expect(+ getTextFileNameError({+ name: "post.MDX",+ assets: [],+ allowedExtensions: ["MDX"],+ })+ ).toBeUndefined();+ expect(+ getTextFileNameError({+ name: "post.mdx.txt",+ assets: [],+ allowedExtensions: ["mdx"],+ })+ ).toBe("Use a supported editable text extension.");+});+test("creates valid initial content for editable file types", async () => {const jsonFile = createTextFileData("data.json");if (jsonFile === undefined) {@@ -72,3 +108,23 @@ test("creates valid initial content for editable file types", async () => {expect(createTextFileData("image.png")).toBeUndefined();});++test("creates an independent asset instead of deduplicating empty files", async () => {+ const asset = {+ ...existing,+ id: "new",+ name: "post_hash.mdx",+ format: "mdx",+ };+ const upload = vi.fn(async () => asset);++ await expect(createTextFile({ name: "post.mdx", upload })).resolves.toEqual(+ asset+ );+ expect(upload).toHaveBeenCalledOnce();+ expect(upload).toHaveBeenCalledWith(+ "file",+ expect.objectContaining({ name: "post.mdx" }),+ { folderId: undefined, deduplicate: false }+ );+});diff --git a/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.tsx b/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.tsxindex b60b7bf697..c2a87ab687 100644--- a/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.tsx+++ b/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.tsx@@ -1,4 +1,4 @@-import { useLayoutEffect, useState, type KeyboardEvent } from "react";+import { useLayoutEffect, useRef, useState, type KeyboardEvent } from "react";import isValidFilename from "valid-filename";import {Button,@@ -25,16 +25,22 @@ import { uploadSingleAsset } from "~/builder/shared/assets/upload-assets";export const getTextFileNameError = ({name,assets,+ allowedExtensions,}: {name: string;assets: Iterable<Asset>;+ allowedExtensions?: readonly string[];}) => {if (isValidFilename(name) === false) {return "Enter a valid file name.";}+ const extension = getFileExtension(name)?.toLowerCase() ?? "";if (- isTextFileAsset({ format: getFileExtension(name)?.toLowerCase() ?? "" }) ===- false+ isTextFileAsset({ format: extension }) === false ||+ (allowedExtensions !== undefined &&+ allowedExtensions.some(+ (allowedExtension) => allowedExtension.toLowerCase() === extension+ ) === false)) {return "Use a supported editable text extension.";}@@ -55,18 +61,20 @@ export const createTextFileData = (name: string): File | undefined => {});};-const createTextFile = async ({+export const createTextFile = async ({name,folderId,+ upload = uploadSingleAsset,}: {name: string;folderId?: string;+ upload?: typeof uploadSingleAsset;}): Promise<Asset | undefined> => {const file = createTextFileData(name);if (file === undefined) {return;}- return uploadSingleAsset("file", file, { folderId });+ return upload("file", file, { folderId, deduplicate: false });};const stopEscapePropagation = (event: KeyboardEvent) => {@@ -78,34 +86,45 @@ const stopEscapePropagation = (event: KeyboardEvent) => {export const CreateTextFileDialog = ({open,folderId,+ defaultName = "untitled.md",+ allowedExtensions,+ title = "New text file",+ disabled = false,onOpenChange,onCreated,}: {open: boolean;folderId?: string;+ defaultName?: string;+ allowedExtensions?: readonly string[];+ title?: string;+ disabled?: boolean;onOpenChange: (open: boolean) => void;onCreated: (assetId: string) => void;}) => {- const [name, setName] = useState("untitled.md");+ const [name, setName] = useState(defaultName);const [error, setError] = useState<string>();const [creating, setCreating] = useState(false);+ const nameInputRef = useRef<HTMLInputElement>(null);+ const dialogContentRef = useRef<HTMLDivElement>(null);useLayoutEffect(() => {if (open) {- setName("untitled.md");+ setName(defaultName);setError(undefined);setCreating(false);}- }, [open]);+ }, [defaultName, open]);const normalizedName = name.trim();const submit = async () => {- if (creating) {+ if (creating || disabled) {return;}const validationError = getTextFileNameError({name: normalizedName,assets: $assets.get().values(),+ allowedExtensions,});setError(validationError);if (validationError !== undefined) {@@ -134,18 +153,29 @@ export const CreateTextFileDialog = ({return (<Dialog open={open} onOpenChange={onOpenChange}><DialogContent+ ref={dialogContentRef}minWidth={360}aria-describedby={undefined}onKeyDown={stopEscapePropagation}+ onOpenAutoFocus={(event) => {+ event.preventDefault();+ if (disabled) {+ dialogContentRef.current?.focus();+ return;+ }+ const focusName = () => nameInputRef.current?.focus();+ focusName();+ requestAnimationFrame(focusName);+ }}>- <DialogTitle>New text file</DialogTitle>+ <DialogTitle>{title}</DialogTitle><Grid gap={3} css={{ padding: theme.panel.padding }}><Grid gap={1}><Label htmlFor="asset-text-file-name">File name</Label><InputFieldid="asset-text-file-name"- autoFocus- disabled={creating}+ inputRef={nameInputRef}+ disabled={creating || disabled}value={name}color={error === undefined ? undefined : "error"}onChange={(event) => {@@ -165,7 +195,10 @@ export const CreateTextFileDialog = ({)}</Grid><Flex justify="end">- <Button disabled={creating} onClick={() => void submit()}>+ <Button+ disabled={creating || disabled}+ onClick={() => void submit()}+ >{creating ? "Creating…" : "Create file"}</Button></Flex>diff --git a/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.ui.test.tsx b/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.ui.test.tsxnew file mode 100644index 0000000000..4de080f83e--- /dev/null+++ b/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.ui.test.tsx@@ -0,0 +1,87 @@+/**+ * @vitest-environment jsdom+ */+import { act } from "react-dom/test-utils";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import { CreateTextFileDialog } from "./create-text-file-dialog";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let container: HTMLDivElement;+let root: Root;+let animationFrames: FrameRequestCallback[];++beforeEach(() => {+ animationFrames = [];+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {+ animationFrames.push(callback);+ return animationFrames.length;+ });+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ document.body.innerHTML = "";+ vi.unstubAllGlobals();+});++test("focuses the file name after the opening control restores focus", () => {+ act(() => {+ root.render(+ <CreateTextFileDialog open onOpenChange={vi.fn()} onCreated={vi.fn()} />+ );+ });++ const input = document.querySelector<HTMLInputElement>(+ "#asset-text-file-name"+ );+ const close = document.querySelector<HTMLButtonElement>(+ 'button[aria-label="Close"]'+ );+ if (input === null || close === null) {+ throw new Error("Expected the text file dialog controls");+ }++ close.focus();+ expect(document.activeElement).toBe(close);++ act(() => {+ for (const callback of animationFrames.splice(0)) {+ callback(0);+ }+ });++ expect(document.activeElement).toBe(input);+});++test("focuses the dialog itself when creation is disabled", () => {+ act(() => {+ root.render(+ <CreateTextFileDialog+ open+ disabled+ onOpenChange={vi.fn()}+ onCreated={vi.fn()}+ />+ );+ });++ expect(document.activeElement).toBe(+ document.querySelector<HTMLElement>('[role="dialog"]')+ );+ expect(animationFrames).toHaveLength(0);+});diff --git a/apps/builder/app/builder/features/text-file-editor/mdx-editor-lint.test.ts b/apps/builder/app/builder/features/text-file-editor/mdx-editor-lint.test.tsnew file mode 100644index 0000000000..ef2a53852d--- /dev/null+++ b/apps/builder/app/builder/features/text-file-editor/mdx-editor-lint.test.ts@@ -0,0 +1,37 @@+/**+ * @vitest-environment jsdom+ */+import { EditorState } from "@codemirror/state";+import { EditorView } from "@codemirror/view";+import { forceLinting, forEachDiagnostic } from "@codemirror/lint";+import { expect, test } from "vitest";+import { getTextFileEditorExtensions } from "./text-file-utils";++test("decorates the exact unsupported MDX source range", async () => {+ const parent = document.createElement("div");+ document.body.appendChild(parent);+ const view = new EditorView({+ parent,+ state: EditorState.create({+ doc: "# Kept\n\n{danger()}\n",+ extensions: getTextFileEditorExtensions({ format: "mdx" }),+ }),+ });++ forceLinting(view);+ await new Promise((resolve) => setTimeout(resolve, 20));+ const diagnostics: unknown[] = [];+ forEachDiagnostic(view.state, (diagnostic, from, to) => {+ diagnostics.push({ ...diagnostic, from, to });+ });++ expect(diagnostics).toEqual([+ {+ from: 8,+ to: 18,+ severity: "warning",+ message: "Executable MDX expressions are not supported",+ },+ ]);+ view.destroy();+});diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx b/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsxindex e48739e395..507c52fe03 100644--- a/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx+++ b/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx@@ -1,5 +1,6 @@import {useEffect,+ useMemo,useRef,useState,type ReactNode,@@ -38,8 +39,16 @@ import {TextItalicIcon,TextStrikethroughIcon,} from "@webstudio-is/icons";-import { formatAssetName } from "@webstudio-is/project-build/runtime";-import { getAssetUrl, getPagePath, type Asset } from "@webstudio-is/sdk";+import {+ formatAssetName,+ MdxAuthoredContentConflictError,+} from "@webstudio-is/project-build/runtime";+import {+ getAssetUrl,+ getPagePath,+ isMdxFileAsset,+ type Asset,+} from "@webstudio-is/sdk";import { CodeEditor } from "~/shared/code-editor";import { EditorDialog, type EditorApi } from "~/shared/code-editor-base";import {@@ -61,10 +70,19 @@ import {} from "~/builder/features/settings-panel/controls/url";import {getTextFileEditorExtensions,+ getMdxPersistenceFeedback,isMarkdownAsset,+ type MdxPersistenceFeedback,normalizeTextFileContent,} from "./text-file-utils";import { MarkdownSplitView } from "./markdown-preview";+import { getAssetContentBridge } from "~/shared/asset-content-bridge.client";+import { $externalContentRoots } from "~/shared/external-content-mutations";+import type { AssetContentSessionState } from "@webstudio-is/content-engine/asset-content-session";+import {+ replaceExternalContentAssetSource,+ retryExternalContentAsset,+} from "~/shared/external-content-roots";type TextFileState =| { status: "loading" }@@ -429,16 +447,44 @@ export const TextFileEditor = ({}) => {const assets = useStore($assets);const assetFolders = useStore($assetFolders);+ const externalContentRoots = useStore($externalContentRoots);const asset = assets.get(assetId);const { assetContainers } = useAssets();const canEdit = useStore($authPermit) !== "view";const [state, setState] = useState<TextFileState>({ status: "loading" });- const [previewOpen, setPreviewOpen] = useState(false);+ const [persistenceFeedback, setPersistenceFeedback] =+ useState<MdxPersistenceFeedback>();+ const [previewOpen, setPreviewOpen] = useState(true);const currentAssetRef = useRef<Asset>();const persistedContentRef = useRef<string>();const requestedContentRef = useRef<string>();+ const pendingMdxSavesRef = useRef(0);const saveQueueRef = useRef(Promise.resolve());const editorApiRef = useRef<EditorApi>();+ const reportedConflictRef = useRef<string>();+ const mdxSession =+ asset !== undefined &&+ isMdxFileAsset(asset) &&+ asset.projectId !== undefined+ ? getAssetContentBridge().getContentSession?.(asset.projectId)+ : undefined;+ const semanticDiagnostics = useMemo(+ () =>+ Array.from(externalContentRoots.values()).flatMap((root) =>+ root.identity?.assetId === assetId &&+ (root.projectId === undefined || root.projectId === asset?.projectId)+ ? (root.diagnostics ?? [])+ : []+ ),+ [asset?.projectId, assetId, externalContentRoots]+ );+ const languageExtensions = useMemo(+ () =>+ asset === undefined+ ? []+ : getTextFileEditorExtensions(asset, semanticDiagnostics),+ [asset, semanticDiagnostics]+ );useEffect(() => {const assetToLoad = $assets.get().get(assetId);@@ -450,9 +496,44 @@ export const TextFileEditor = ({const controller = new AbortController();setState({ status: "loading" });+ setPersistenceFeedback(undefined);+ reportedConflictRef.current = undefined;++ const applySessionState = (sessionState: AssetContentSessionState) => {+ const feedback = getMdxPersistenceFeedback(sessionState);+ setPersistenceFeedback(feedback);+ if (+ feedback?.kind === "conflicting" &&+ reportedConflictRef.current !== feedback.message+ ) {+ reportedConflictRef.current = feedback.message;+ getAssetContentBridge().requireReload(feedback.message);+ }+ if (feedback?.kind !== "conflicting") {+ reportedConflictRef.current = undefined;+ }+ };const load = async () => {try {+ if (isMdxFileAsset(assetToLoad)) {+ const session = getAssetContentBridge().getContentSession?.(+ assetToLoad.projectId+ );+ if (session === undefined) {+ throw new Error("MDX content session is not available");+ }+ const opened = await session.open(assetId);+ if (controller.signal.aborted) {+ return;+ }+ currentAssetRef.current = assetToLoad;+ persistedContentRef.current = opened.source;+ requestedContentRef.current = opened.source;+ applySessionState(opened);+ setState({ status: "loaded", content: opened.source });+ return;+ }const response = await fetch(getAssetUrl(assetToLoad, window.location.origin),{ signal: controller.signal }@@ -475,7 +556,30 @@ export const TextFileEditor = ({};void load();- return () => controller.abort();+ const unsubscribe = isMdxFileAsset(assetToLoad)+ ? getAssetContentBridge()+ .getContentSession?.(assetToLoad.projectId)+ .subscribe((changedAssetId, sessionState) => {+ if (changedAssetId !== assetId || controller.signal.aborted) {+ return;+ }+ currentAssetRef.current = sessionState.asset as Asset;+ persistedContentRef.current = sessionState.source;+ applySessionState(sessionState);+ if (requestedContentRef.current === sessionState.source) {+ return;+ }+ if (pendingMdxSavesRef.current > 0) {+ return;+ }+ requestedContentRef.current = sessionState.source;+ setState({ status: "loaded", content: sessionState.source });+ })+ : undefined;+ return () => {+ controller.abort();+ unsubscribe?.();+ };}, [assetId]);const save = (content: string) => {@@ -496,7 +600,42 @@ export const TextFileEditor = ({if (normalizedContent !== content) {setState({ status: "loaded", content: normalizedContent });}+ const expectedContent = requestedContentRef.current;requestedContentRef.current = normalizedContent;+ if (isMdxFileAsset(currentAsset) && mdxSession !== undefined) {+ if (+ expectedContent === undefined ||+ currentAsset.projectId === undefined+ ) {+ toast.error("Unable to save: MDX content is not loaded");+ return;+ }+ pendingMdxSavesRef.current += 1;+ void replaceExternalContentAssetSource({+ projectId: currentAsset.projectId,+ assetId,+ expectedSource: expectedContent,+ source: normalizedContent,+ })+ .catch((error) => {+ const message =+ error instanceof Error+ ? error.message+ : "Unable to save this file.";+ const feedback: MdxPersistenceFeedback = {+ kind:+ error instanceof MdxAuthoredContentConflictError+ ? "conflicting"+ : "failed",+ message,+ };+ setPersistenceFeedback(feedback);+ })+ .finally(() => {+ pendingMdxSavesRef.current -= 1;+ });+ return;+ }saveQueueRef.current = saveQueueRef.current.then(async () => {const requestedContent = requestedContentRef.current;if (@@ -534,13 +673,16 @@ export const TextFileEditor = ({<CodeEditoreditorApiRef={editorApiRef}value={state.content}- languageExtensions={getTextFileEditorExtensions(asset)}+ languageExtensions={languageExtensions}size="full"expandable={false}chromelessreadOnly={canEdit === false}onChange={(content) => {setState({ status: "loaded", content });+ if (isMdxFileAsset(asset)) {+ save(content);+ }}}onChangeComplete={save}/>@@ -551,6 +693,8 @@ export const TextFileEditor = ({<EditorDialogtitle={title}contentPadding={false}+ width={isMarkdown ? 1280 : undefined}+ height={isMarkdown ? 960 : undefined}openonOpenChange={(open) => {if (open === false && state.status === "loaded") {@@ -578,11 +722,46 @@ export const TextFileEditor = ({css={{display: "grid",gridTemplateRows: isMarkdown- ? "auto minmax(0, 1fr)"+ ? persistenceFeedback === undefined+ ? "auto minmax(0, 1fr)"+ : "auto auto minmax(0, 1fr)": "minmax(0, 1fr)",height: "100%",}}>+ {persistenceFeedback !== undefined && (+ <Flex+ gap="2"+ align="center"+ css={{ padding: rawTheme.spacing[5] }}+ >+ <Text role="alert" color="destructive" variant="tiny">+ {persistenceFeedback.message}+ </Text>+ {persistenceFeedback.kind === "failed" &&+ mdxSession !== undefined && (+ <Button+ color="ghost"+ onClick={() => {+ void retryExternalContentAsset({+ projectId: asset.projectId!,+ assetId,+ }).catch((error) => {+ setPersistenceFeedback({+ kind: "failed",+ message:+ error instanceof Error+ ? error.message+ : "Unable to save this file.",+ });+ });+ }}+ >+ Retry+ </Button>+ )}+ </Flex>+ )}{isMarkdown && (<MarkdownToolbareditorApiRef={editorApiRef}diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts b/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.tsindex 354e485fe4..f0764bf367 100644--- a/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts+++ b/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts@@ -6,6 +6,8 @@ import {} from "@webstudio-is/sdk";import {getTextFileEditorExtensions,+ getMdxEditorDiagnostics,+ getMdxPersistenceFeedback,isMarkdownAsset,normalizeTextFileContent,normalizeTextFileConversion,@@ -38,7 +40,11 @@ describe("text file assets", () => {const language = getAssetTextEditorLanguage({ format });expect(isTextFileAsset({ format })).toBe(language !== undefined);expect(getTextFileEditorExtensions({ format })).toHaveLength(- language === undefined || language === "plain" ? 0 : 1+ language === undefined || language === "plain"+ ? 0+ : format === "mdx"+ ? 4+ : 1);});@@ -78,6 +84,103 @@ describe("text file assets", () => {});});+ test("reports MDX diagnostics at parser source ranges", async () => {+ await expect(+ getMdxEditorDiagnostics("# Kept\n\n{danger()}\n")+ ).resolves.toEqual([+ {+ from: 8,+ to: 18,+ severity: "warning",+ message: "Executable MDX expressions are not supported",+ },+ ]);+ });++ test("reports unrecoverable MDX without blocking the source", async () => {+ const source = "# Kept\n\n<ws.element";+ const diagnostics = await getMdxEditorDiagnostics(source);+ expect(diagnostics).toHaveLength(1);+ expect(diagnostics[0]).toMatchObject({+ severity: "error",+ from: source.length,+ to: source.length,+ });+ });++ test("reports connected Content Block warnings at property ranges", async () => {+ const source = '<ws.element ws:name="Card" class="legacy" />';+ await expect(+ getMdxEditorDiagnostics(source, [+ {+ code: "ignored-template-prop",+ severity: "warning",+ blockInstanceId: "block",+ assetId: "asset",+ templateName: "Card",+ propName: "class",+ reason: "incompatible",+ sourceRange: {+ start: { line: 1, column: 28, offset: 27 },+ end: { line: 1, column: 42, offset: 41 },+ },+ },+ ])+ ).resolves.toEqual([+ {+ from: 27,+ to: 41,+ severity: "warning",+ message:+ 'Property "class" on template "Card" was ignored because it is incompatible. Line 1, column 28.',+ },+ ]);+ });++ test("reports connected Content Block content-model errors", async () => {+ const source = '<ws.element ws:tag="li">nested item</ws.element>';+ await expect(+ getMdxEditorDiagnostics(source, [+ {+ code: "invalid-mdx",+ severity: "error",+ blockInstanceId: "block",+ assetId: "asset",+ message: "Placing <li> element inside a <li> violates HTML spec.",+ sourceRange: {+ start: { line: 1, column: 1, offset: 0 },+ end: { line: 1, column: source.length + 1, offset: source.length },+ },+ },+ ])+ ).resolves.toEqual([+ {+ from: 0,+ to: source.length,+ severity: "error",+ message: "Placing <li> element inside a <li> violates HTML spec.",+ },+ ]);+ });++ test("keeps failed and conflicting MDX saves visible", () => {+ expect(+ getMdxPersistenceFeedback({+ status: "failed",+ error: new Error("Network unavailable"),+ })+ ).toEqual({ kind: "failed", message: "Network unavailable" });+ expect(+ getMdxPersistenceFeedback({+ status: "conflicting",+ })+ ).toEqual({+ kind: "conflicting",+ message: "This file changed elsewhere. Reload before continuing.",+ });+ expect(getMdxPersistenceFeedback({ status: "saved" })).toBeUndefined();+ });+test("rejects incomplete object syntax", () => {expect(normalizeTextFileContent({ format: "json" }, "{ title:")).toEqual({error: "Enter a JSON-compatible value.",diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts b/apps/builder/app/builder/features/text-file-editor/text-file-utils.tsindex f5111e62c0..daecfa7e93 100644--- a/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts+++ b/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts@@ -1,14 +1,121 @@import type { Extension } from "@codemirror/state";+import { keymap } from "@codemirror/view";+import {+ linter,+ lintGutter,+ lintKeymap,+ type Diagnostic,+} from "@codemirror/lint";import { css } from "@codemirror/lang-css";import { html } from "@codemirror/lang-html";import { javascript } from "@codemirror/lang-javascript";import { markdown } from "@codemirror/lang-markdown";import { parseJsonExpression } from "@webstudio-is/expression";+import {+ createMdxSourceDiagnostics,+ parseMdxDocumentRecovering,+ type MdxSourcePoint,+} from "@webstudio-is/content-engine/mdx";import {getAssetTextEditorLanguage,type Asset,type AssetTextEditorLanguage,+ type ContentBlockDiagnostic,} from "@webstudio-is/sdk";+import type { AssetContentSessionState } from "@webstudio-is/content-engine/asset-content-session";+import { formatContentBlockDiagnostic } from "~/shared/content-block-diagnostics";++export type MdxPersistenceFeedback = Readonly<{+ kind: "failed" | "conflicting";+ message: string;+}>;++export const getMdxPersistenceFeedback = (+ state: Pick<AssetContentSessionState, "status" | "error">+): MdxPersistenceFeedback | undefined => {+ if (state.status === "failed") {+ return {+ kind: "failed",+ message: state.error?.message ?? "Unable to save this file.",+ };+ }+ if (state.status === "conflicting") {+ return {+ kind: "conflicting",+ message:+ state.error?.message ??+ "This file changed elsewhere. Reload before continuing.",+ };+ }+};++const getPointOffset = (source: string, point: MdxSourcePoint) => {+ if (point.offset !== undefined) {+ return Math.min(point.offset, source.length);+ }+ const lines = source.split("\n");+ let offset = 0;+ for (let index = 0; index < point.line - 1 && index < lines.length; index++) {+ offset += lines[index].length + 1;+ }+ return Math.min(offset + point.column - 1, source.length);+};++export const getMdxEditorDiagnostics = async (+ source: string,+ semanticDiagnostics: readonly ContentBlockDiagnostic[] = []+): Promise<Diagnostic[]> => {+ const result = await parseMdxDocumentRecovering({ source });+ const diagnostics = [+ ...createMdxSourceDiagnostics(result.diagnostics).map((diagnostic) => ({+ sourceRange: diagnostic.sourceRange,+ severity: diagnostic.severity,+ message: diagnostic.message,+ })),+ ...semanticDiagnostics.map((diagnostic) => ({+ sourceRange: diagnostic.sourceRange,+ severity: diagnostic.severity,+ message:+ diagnostic.code === "invalid-mdx"+ ? diagnostic.message+ : diagnostic.code === "unsafe-mdx"+ ? diagnostic.reason+ : formatContentBlockDiagnostic(diagnostic),+ })),+ ].map((diagnostic) => {+ const from =+ diagnostic.sourceRange === undefined+ ? 0+ : getPointOffset(source, diagnostic.sourceRange.start);+ const to =+ diagnostic.sourceRange === undefined+ ? Math.min(1, source.length)+ : Math.max(from, getPointOffset(source, diagnostic.sourceRange.end));+ return {+ from,+ to,+ severity: diagnostic.severity,+ message: diagnostic.message,+ };+ });+ return Array.from(+ new Map(+ diagnostics.map((diagnostic) => [JSON.stringify(diagnostic), diagnostic])+ ).values()+ );+};++const getMdxExtensions = (+ semanticDiagnostics: readonly ContentBlockDiagnostic[]+): Extension[] => [+ linter(+ (view) =>+ getMdxEditorDiagnostics(view.state.doc.toString(), semanticDiagnostics),+ { delay: 300 }+ ),+ lintGutter(),+ keymap.of(lintKeymap),+];const languageExtensions = {plain: [],@@ -21,13 +128,17 @@ const languageExtensions = {} satisfies Record<AssetTextEditorLanguage, Extension[]>;export const getTextFileEditorExtensions = (- asset: Pick<Asset, "format">+ asset: Pick<Asset, "format">,+ semanticDiagnostics: readonly ContentBlockDiagnostic[] = []): Extension[] => {const language = getAssetTextEditorLanguage(asset);if (language === undefined) {return [];}- return languageExtensions[language];+ const extensions = languageExtensions[language];+ return asset.format.toLowerCase() === "mdx"+ ? [...extensions, ...getMdxExtensions(semanticDiagnostics)]+ : extensions;};export const isMarkdownAsset = (asset: Pick<Asset, "format">) =>diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/block-editor-context-menu.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/block-editor-context-menu.tsxindex 98de45896d..b2df6edcfa 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/block-editor-context-menu.tsx+++ b/apps/builder/app/builder/features/workspace/canvas-tools/block-editor-context-menu.tsx@@ -6,6 +6,7 @@ import {$textEditingInstanceSelector,$textEditorContextMenu,$textEditorContextMenuCommand,+ execTextEditorContextMenuCommand,} from "~/shared/nano-states";import { $instances } from "~/shared/sync/data-stores";import { applyScale } from "./outline";@@ -82,7 +83,21 @@ const Menu = ({const handleValueChangeComplete = useCallback((templateSelector: InstanceSelector) => {const insertBefore = modifierKeys.altKey;- insertTemplateAt(templateSelector, anchor, insertBefore);+ execTextEditorContextMenuCommand({ type: "templateInsertionStarted" });+ void insertTemplateAt(templateSelector, anchor, insertBefore).then(+ (didInsert) => {+ if (didInsert === false) {+ execTextEditorContextMenuCommand({+ type: "templateInsertionCancelled",+ });+ }+ },+ () => {+ execTextEditorContextMenuCommand({+ type: "templateInsertionCancelled",+ });+ }+ );},[anchor, modifierKeys.altKey]);@@ -142,6 +157,11 @@ const Menu = ({break;}+ case "templateInsertionStarted":+ case "templateInsertionCancelled": {+ break;+ }+default:(type) satisfies never;}diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsxindex 12197f8916..b5ed327455 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsx+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsx@@ -46,6 +46,7 @@ import {getInstanceLabel,InstanceIcon,} from "~/builder/shared/instance-label";+import { useOutlineControlPosition } from "./use-outline-control-position";export const TemplatesMenu = ({onOpenChange,@@ -76,10 +77,12 @@ export const TemplatesMenu = ({}) => {const instances = useStore($instances);const modifierKeys = useStore($modifierKeys);+ const preventCloseAutoFocusRef = useRef(false);const blockInstanceSelector = findBlockSelector({ anchor, instances });const handleValueChangeComplete = useEffectEvent((value: string) => {+ preventCloseAutoFocusRef.current = true;const templateSelector = JSON.parse(value) as InstanceSelector;onValueChangeComplete(templateSelector);});@@ -125,6 +128,13 @@ export const TemplatesMenu = ({collisionPadding={16}side="bottom"loop+ onCloseAutoFocus={(event) => {+ if (preventCloseAutoFocusRef.current === false) {+ return;+ }+ preventCloseAutoFocusRef.current = false;+ event.preventDefault();+ }}// @todo remove inert after creation{...(inert ? { inert: "" } : {})}>@@ -239,6 +249,9 @@ export const BlockChildHoveredInstanceOutline = () => {>(undefined);const outline = blockChildOutline ?? buttonOutline;+ const rect =+ outline === undefined ? undefined : applyScale(outline.rect, scale);+ const [controlRef, controlPosition] = useOutlineControlPosition(rect);const [isMenuOpen, setIsMenuOpen] = useState(false);@@ -250,6 +263,10 @@ export const BlockChildHoveredInstanceOutline = () => {return;}+ if (rect === undefined) {+ return;+ }+if (clampingRect === undefined) {return;}@@ -282,11 +299,6 @@ export const BlockChildHoveredInstanceOutline = () => {// 1 child is Templates instanceconst hasChildren = blockInstance.children.length > 1;- const rect = applyScale(outline.rect, scale);-- // Check if the top edge of the component is hidden (clipped by viewport/clamping)- const isTopEdgeHidden = rect.top < clampingRect.top;-const canDeleteHoveredInstance =shallowEqual(outline.selector, outline.hoveredSelector) &&canDeleteInstanceInContentMode({@@ -318,18 +330,21 @@ export const BlockChildHoveredInstanceOutline = () => {return (<Outline rect={rect} clampingRect={clampingRect}><Flex+ ref={controlRef}css={{position: "absolute",left: 0,paddingRight: theme.sizes.controlHeight,- ...(isTopEdgeHidden+ ...(controlPosition === "top"? {- bottom: `calc(-${theme.sizes.controlHeight} )`,- clipPath: `polygon(0% 0%, 100% 0%, ${theme.sizes.controlHeight} 100%, 0% 100%)`,- }- : {top: `calc(-${theme.sizes.controlHeight})`,clipPath: `polygon(0% 0%, ${theme.sizes.controlHeight} 0%, 100% 100%, 0% 100%)`,+ }+ : {+ ...(controlPosition === "bottom"+ ? { bottom: `calc(-${theme.sizes.controlHeight})` }+ : { top: 0 }),+ clipPath: `polygon(0% 0%, 100% 0%, ${theme.sizes.controlHeight} 100%, 0% 100%)`,}),// Define grace area for the buttonpointerEvents: isMenuOpen ? "none" : "all",@@ -399,14 +414,14 @@ export const BlockChildHoveredInstanceOutline = () => {? `oklch(from ${theme.colors.backgroundPrimary} l c h / 0.7)`: undefined,borderRadius: theme.borderRadius[4],- ...(isTopEdgeHidden+ ...(controlPosition === "top"? {- borderTopLeftRadius: 0,- borderTopRightRadius: 0,- }- : {borderBottomLeftRadius: 0,borderBottomRightRadius: 0,+ }+ : {+ borderTopLeftRadius: 0,+ borderTopRightRadius: 0,}),// Define grace area for the buttonpointerEvents: isMenuOpen ? "none" : "all",diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.test.ts b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.test.tsindex d20dec9979..0cc14cb76f 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.test.ts+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.test.ts@@ -1,8 +1,16 @@-import { beforeEach, describe, expect, test, vi } from "vitest";-import type { Instance, WebstudioFragment } from "@webstudio-is/sdk";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import {+ blockComponent,+ blockTemplateComponent,+ coreMetas,+ elementComponent,+ type Instance,+ type WebstudioFragment,+} from "@webstudio-is/sdk";+import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";import type { Project } from "@webstudio-is/project";import { createDefaultPages } from "@webstudio-is/project-build";-import { __testing__, insertListItemAt } from "./block-utils";+import { __testing__, insertListItemAt, insertTemplateAt } from "./block-utils";import { registerContainers } from "~/shared/sync/sync-stores";import {$instances,@@ -12,7 +20,10 @@ import {} from "~/shared/sync/data-stores";import {$selectedInstanceSelector,+ $builderMode,+ $registeredComponentMetas,$textEditingInstanceSelector,+ selectPage,selectInstance,} from "~/shared/nano-states";@@ -119,3 +130,74 @@ describe("insertListItemAt", () => {});});});++describe("insertTemplateAt", () => {+ beforeEach(() => {+ $project.set({ id: "projectId" } as Project);+ $pages.set(+ createDefaultPages({ homePageId: "home", rootInstanceId: "body" })+ );+ selectPage("home");+ $props.set(new Map());+ $builderMode.set("content");+ $registeredComponentMetas.set(+ new Map(Object.entries({ ...defaultMetas, ...coreMetas }))+ );+ selectInstance(["current", "block", "body"]);+ $textEditingInstanceSelector.set(undefined);+ });++ afterEach(() => {+ $builderMode.set("design");+ });++ test("inserts synchronously when content mode has no token conflicts", async () => {+ $instances.set(+ new Map<Instance["id"], Instance>([+ [+ "body",+ createInstance("body", "Body", [{ type: "id", value: "block" }]),+ ],+ [+ "block",+ createInstance("block", blockComponent, [+ { type: "id", value: "templates" },+ { type: "id", value: "current" },+ ]),+ ],+ [+ "templates",+ createInstance("templates", blockTemplateComponent, [+ { type: "id", value: "template" },+ ]),+ ],+ [+ "template",+ {+ ...createInstance("template", elementComponent),+ tag: "p",+ },+ ],+ [+ "current",+ {+ ...createInstance("current", elementComponent),+ tag: "p",+ },+ ],+ ])+ );++ const insertion = insertTemplateAt(+ ["template", "templates", "block", "body"],+ ["current", "block", "body"],+ false+ );++ const insertedSelector = $selectedInstanceSelector.get();+ expect(insertedSelector?.[0]).not.toBe("current");+ expect(insertedSelector?.slice(1)).toEqual(["block", "body"]);++ await expect(insertion).resolves.toBe(true);+ });+});diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.tsindex f2a254699e..ca2823211c 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts@@ -26,7 +26,7 @@ import type {InstanceSelector,} from "@webstudio-is/project-build/runtime";import {- findBlockSelector,+ findBlockContentSelector,getBlockTemplateInsertionIndex,} from "@webstudio-is/project-build/runtime";@@ -130,10 +130,10 @@ export const insertTemplateAt = async (templateSelector[0]);- const parentSelector = findBlockSelector({ anchor, instances });+ const parentSelector = findBlockContentSelector({ anchor, instances });if (parentSelector === undefined) {- return;+ return false;}const position = getBlockTemplateInsertionIndex({@@ -143,7 +143,7 @@ export const insertTemplateAt = async (});if (position === undefined) {- return;+ return false;}const target: DroppableTarget = {@@ -158,23 +158,26 @@ export const insertTemplateAt = async (targetData: getWebstudioData(),contentMode,});- const conflictResolution = await resolveTokenConflicts(conflicts);+ const conflictResolution =+ conflicts.length === 0+ ? "theirs"+ : await resolveTokenConflicts(conflicts);if (conflictResolution === "cancel") {- return;+ return false;}- const didInsert = await insertWebstudioFragmentAt(+ const didInsert = insertWebstudioFragmentAt(fragment,target,conflictResolution,{ contentMode });if (didInsert === false) {- return;+ return false;}const selectedInstanceSelector = $selectedInstanceSelector.get();if (selectedInstanceSelector === undefined) {- return;+ return false;}const data = getWebstudioData();const editableInstanceSelector = findTextEditorTarget({@@ -188,8 +191,9 @@ export const insertTemplateAt = async (? { selector: editableInstanceSelector, reason: "new" }: undefined);+ return true;} catch {// User cancelled the operation- return;+ return false;}};diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/label.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/outline/label.tsxindex c68eea3bb1..d81adaa308 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/label.tsx+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/label.tsx@@ -1,4 +1,3 @@-import { useCallback, useState } from "react";import { styled, type Rect } from "@webstudio-is/design-system";import type { Instance } from "@webstudio-is/sdk";import { theme } from "@webstudio-is/design-system";@@ -6,39 +5,7 @@ import {InstanceIcon,getInstanceLabel,} from "~/builder/shared/instance-label";--type LabelPosition = "top" | "inside" | "bottom";-type LabelRefCallback = (element: HTMLElement | null) => void;--/**- * Detects if there is no space on top and for the label and tells to show it inside.- * - if there is enough space for the label on top of the instance - top- * - else if instance height is more than 250px - bottom- * - else inside-top - last resort because it covers a bit of the instance content- */-const useLabelPosition = (- instanceRect: Rect-): [LabelRefCallback, LabelPosition] => {- const [position, setPosition] = useState<LabelPosition>("top");-- const ref = useCallback(- (element: null | HTMLElement) => {- if (element === null || instanceRect === undefined) {- return;- }- const labelRect = element.getBoundingClientRect();- let nextPosition: LabelPosition = "top";- // Label won't fit above the instance outline- if (labelRect.height > instanceRect.top) {- nextPosition = instanceRect.height < 250 ? "bottom" : "inside";- }- setPosition(nextPosition);- },- [instanceRect]- );-- return [ref, position];-};+import { useOutlineControlPosition } from "./use-outline-control-position";const LabelContainer = styled("div",@@ -98,7 +65,7 @@ type LabelProps = {};export const Label = ({ instance, instanceRect, variant }: LabelProps) => {- const [labelRef, position] = useLabelPosition(instanceRect);+ const [labelRef, position] = useOutlineControlPosition(instanceRect);return (<LabelContainer position={position} variant={variant} ref={labelRef}><InstanceIcon size="1em" instance={instance} />diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/use-outline-control-position.test.ts b/apps/builder/app/builder/features/workspace/canvas-tools/outline/use-outline-control-position.test.tsnew file mode 100644index 0000000000..786ca03824--- /dev/null+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/use-outline-control-position.test.ts@@ -0,0 +1,31 @@+import { describe, expect, test } from "vitest";+import { getOutlineControlPosition } from "./use-outline-control-position";++describe("getOutlineControlPosition", () => {+ test("positions above when the control fits", () => {+ expect(+ getOutlineControlPosition({+ controlHeight: 20,+ instanceRect: { top: 20, height: 100, left: 0, width: 100 },+ })+ ).toBe("top");+ });++ test("positions below a short instance when the control does not fit", () => {+ expect(+ getOutlineControlPosition({+ controlHeight: 20,+ instanceRect: { top: 19, height: 100, left: 0, width: 100 },+ })+ ).toBe("bottom");+ });++ test("positions inside a tall instance when the control does not fit", () => {+ expect(+ getOutlineControlPosition({+ controlHeight: 20,+ instanceRect: { top: 19, height: 250, left: 0, width: 100 },+ })+ ).toBe("inside");+ });+});diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/use-outline-control-position.ts b/apps/builder/app/builder/features/workspace/canvas-tools/outline/use-outline-control-position.tsnew file mode 100644index 0000000000..1877ccdf70--- /dev/null+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/use-outline-control-position.ts@@ -0,0 +1,42 @@+import { useCallback, useState } from "react";+import type { Rect } from "@webstudio-is/design-system";++export type OutlineControlPosition = "top" | "inside" | "bottom";++// Prefer placing controls outside the instance. For tall instances, keep the+// control visible inside the outline instead of moving it far below the fold.+export const getOutlineControlPosition = ({+ controlHeight,+ instanceRect,+}: {+ controlHeight: number;+ instanceRect: Rect;+}): OutlineControlPosition => {+ if (controlHeight <= instanceRect.top) {+ return "top";+ }+ return instanceRect.height < 250 ? "bottom" : "inside";+};++type ControlRefCallback = (element: HTMLElement | null) => void;++export const useOutlineControlPosition = (+ instanceRect: Rect | undefined+): [ControlRefCallback, OutlineControlPosition] => {+ const [position, setPosition] = useState<OutlineControlPosition>("top");+ const ref = useCallback(+ (element: HTMLElement | null) => {+ if (element === null || instanceRect === undefined) {+ return;+ }+ setPosition(+ getOutlineControlPosition({+ controlHeight: element.getBoundingClientRect().height,+ instanceRect,+ })+ );+ },+ [instanceRect]+ );+ return [ref, position];+};diff --git a/apps/builder/app/builder/shared/asset-manager/asset-filters.tsx b/apps/builder/app/builder/shared/asset-manager/asset-filters.tsxindex 84c08d5a96..a763b921a5 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-filters.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-filters.tsx@@ -49,6 +49,7 @@ const EXTENSION_TO_DISPLAY_CATEGORY: Record<// Codetxt: "Code",md: "Code",+ mdx: "Code",js: "Code",css: "Code",json: "Code",diff --git a/apps/builder/app/builder/shared/assets/builder-mdx-content-repository.client.ts b/apps/builder/app/builder/shared/assets/builder-mdx-content-repository.client.tsnew file mode 100644index 0000000000..64dca5a4bd--- /dev/null+++ b/apps/builder/app/builder/shared/assets/builder-mdx-content-repository.client.ts@@ -0,0 +1,35 @@+import type { AssetContentRepository } from "@webstudio-is/content-engine/asset-content-repository";+import { getAssetContentBridge } from "~/shared/asset-content-bridge.client";+import { $authToken } from "~/shared/nano-states";+import { createHttpAssetContentRepository } from "./mdx-content-repository";++export const createBuilderHttpAssetContentRepository = ({+ projectId,+ origin,+}: {+ projectId: string;+ origin?: string;+}): AssetContentRepository => {+ let repository: AssetContentRepository | undefined;+ const getRepository = () => {+ if (repository !== undefined) {+ return repository;+ }+ const requestOrigin = origin ?? globalThis.location?.origin;+ if (requestOrigin === undefined) {+ throw new Error("Asset content requests require a browser origin");+ }+ repository = createHttpAssetContentRepository({+ projectId,+ origin: requestOrigin,+ authToken: () => $authToken.get(),+ request: (input, init) =>+ getAssetContentBridge().request(String(input), init),+ });+ return repository;+ };+ return {+ readContent: (input) => getRepository().readContent(input),+ updateContent: (input) => getRepository().updateContent(input),+ };+};diff --git a/apps/builder/app/builder/shared/assets/mdx-content-repository.test.ts b/apps/builder/app/builder/shared/assets/mdx-content-repository.test.tsnew file mode 100644index 0000000000..71a6552c75--- /dev/null+++ b/apps/builder/app/builder/shared/assets/mdx-content-repository.test.ts@@ -0,0 +1,259 @@+import { describe, expect, test, vi } from "vitest";+import {+ AssetContentAuthorizationError,+ AssetRevisionConflictError,+} from "@webstudio-is/content-engine/asset-content-repository";+import {+ assetContentDescriptorHeader,+ serializeAssetContentDescriptor,+} from "@webstudio-is/protocol/asset-resource-api";+import { contentEngineLimits } from "@webstudio-is/content-engine/limits";+import { createHttpAssetContentRepository } from "./mdx-content-repository";+import { createBuilderHttpAssetContentRepository } from "./builder-mdx-content-repository.client";++const asset = {+ id: "asset-1",+ projectId: "project-1",+ name: "article_revision.mdx",+ type: "file" as const,+ format: "mdx",+ size: 7,+ createdAt: "2026-08-15T00:00:00.000Z",+};++const collect = async (data: AsyncIterable<Uint8Array>) => {+ const chunks: Uint8Array[] = [];+ for await (const chunk of data) {+ chunks.push(chunk);+ }+ return new Uint8Array(chunks.flatMap((chunk) => Array.from(chunk.values())));+};++describe("HTTP MDX content repository", () => {+ test("can be created during server rendering without reading browser globals", () => {+ const browserWindow = globalThis.window;+ vi.stubGlobal("window", undefined);+ try {+ expect(() =>+ createBuilderHttpAssetContentRepository({ projectId: asset.projectId })+ ).not.toThrow();+ } finally {+ vi.stubGlobal("window", browserWindow);+ }+ });++ test("returns content and exact revision identity from one response", async () => {+ const request = vi.fn<typeof fetch>(async () =>+ Promise.resolve(+ new Response("# Hello", {+ headers: {+ "content-length": "7",+ [assetContentDescriptorHeader]:+ serializeAssetContentDescriptor(asset),+ },+ })+ )+ );+ const repository = createHttpAssetContentRepository({+ projectId: asset.projectId,+ origin: "https://webstudio.is",+ authToken: () => "token",+ request,+ });++ const content = await repository.readContent({ assetId: asset.id });++ expect(content.asset).toEqual(asset);+ expect(content.contentLength).toBe(7);+ expect(new TextDecoder().decode(await collect(content.data))).toBe(+ "# Hello"+ );+ expect(request).toHaveBeenCalledTimes(1);+ expect(+ new Headers(request.mock.calls[0]?.[1]?.headers).get("x-auth-token")+ ).toBe("token");+ });++ test("rejects content without the identity of the streamed revision", async () => {+ const repository = createHttpAssetContentRepository({+ projectId: asset.projectId,+ origin: "https://webstudio.is",+ request: async () => new Response("# Hello"),+ });++ await expect(repository.readContent({ assetId: asset.id })).rejects.toThrow(+ "missing its revision identity"+ );+ });++ test.each([+ [{ ...asset, id: "other" }, "requested Asset"],+ [{ ...asset, projectId: "other" }, "requested Asset"],+ ])("rejects substituted content identity %#", async (descriptor, message) => {+ const repository = createHttpAssetContentRepository({+ projectId: asset.projectId,+ origin: "https://webstudio.is",+ request: async () =>+ new Response("# Hello", {+ headers: {+ [assetContentDescriptorHeader]:+ serializeAssetContentDescriptor(descriptor),+ },+ }),+ });++ await expect(repository.readContent({ assetId: asset.id })).rejects.toThrow(+ message+ );+ });++ test("requires a partial response for a ranged read", async () => {+ const repository = createHttpAssetContentRepository({+ projectId: asset.projectId,+ origin: "https://webstudio.is",+ request: async () =>+ new Response("Hell", {+ headers: {+ [assetContentDescriptorHeader]:+ serializeAssetContentDescriptor(asset),+ },+ }),+ });++ await expect(+ repository.readContent({+ assetId: asset.id,+ range: { offset: 2, length: 4 },+ })+ ).rejects.toThrow("unexpected status 200");+ });++ test("rejects an oversized full-file descriptor before exposing its body", async () => {+ const repository = createHttpAssetContentRepository({+ projectId: asset.projectId,+ origin: "https://webstudio.is",+ request: async () =>+ new Response("body", {+ headers: {+ [assetContentDescriptorHeader]: serializeAssetContentDescriptor({+ ...asset,+ size: contentEngineLimits.hydratedFileBytes + 1,+ }),+ },+ }),+ });++ await expect(repository.readContent({ assetId: asset.id })).rejects.toThrow(+ "exceeds the MDX editing limit"+ );+ });++ test.each([+ [403, AssetContentAuthorizationError],+ [409, AssetRevisionConflictError],+ ])(+ "maps HTTP %s to the shared repository error",+ async (status, ErrorType) => {+ const repository = createHttpAssetContentRepository({+ projectId: asset.projectId,+ origin: "https://webstudio.is",+ request: async () =>+ new Response(JSON.stringify({ errors: "Denied" }), {+ status,+ headers: { "content-type": "application/json" },+ }),+ });++ await expect(+ repository.readContent({ assetId: asset.id })+ ).rejects.toThrow(ErrorType);+ }+ );++ test("updates with the pinned storage name and returns the next identity", async () => {+ const next = { ...asset, name: "article_next.mdx", size: 4 };+ const request = vi.fn<typeof fetch>(async (_url, init) => {+ expect(init?.method).toBe("PUT");+ expect(await new Response(init?.body).text()).toBe("next");+ return new Response(JSON.stringify({ asset: next }), {+ headers: { "content-type": "application/json" },+ });+ });+ const repository = createHttpAssetContentRepository({+ projectId: asset.projectId,+ origin: "https://webstudio.is",+ request,+ });++ await expect(+ repository.updateContent({+ assetId: asset.id,+ expectedName: asset.name,+ data: new ReadableStream({+ start(controller) {+ controller.enqueue(new TextEncoder().encode("next"));+ controller.close();+ },+ }),+ })+ ).resolves.toEqual(next);++ const url = request.mock.calls[0]?.[0];+ expect(new URL(String(url)).searchParams.get("expectedName")).toBe(+ asset.name+ );+ });++ test("bounds update buffering before making a request", async () => {+ const request = vi.fn<typeof fetch>();+ let cancelled = false;+ const repository = createHttpAssetContentRepository({+ projectId: asset.projectId,+ origin: "https://webstudio.is",+ request,+ });++ await expect(+ repository.updateContent({+ assetId: asset.id,+ expectedName: asset.name,+ data: new ReadableStream({+ start(controller) {+ controller.enqueue(+ new Uint8Array(contentEngineLimits.hydratedFileBytes + 1)+ );+ },+ cancel() {+ cancelled = true;+ },+ }),+ })+ ).rejects.toThrow();+ expect(request).not.toHaveBeenCalled();+ expect(cancelled).toBe(true);+ });++ test("rejects a substituted identity after update", async () => {+ const repository = createHttpAssetContentRepository({+ projectId: asset.projectId,+ origin: "https://webstudio.is",+ request: async () =>+ new Response(JSON.stringify({ asset: { ...asset, id: "other" } }), {+ headers: { "content-type": "application/json" },+ }),+ });++ await expect(+ repository.updateContent({+ assetId: asset.id,+ expectedName: asset.name,+ data: new ReadableStream({+ start(controller) {+ controller.enqueue(new TextEncoder().encode("next"));+ controller.close();+ },+ }),+ })+ ).rejects.toThrow("requested Asset");+ });+});diff --git a/apps/builder/app/builder/shared/assets/mdx-content-repository.ts b/apps/builder/app/builder/shared/assets/mdx-content-repository.tsnew file mode 100644index 0000000000..30419b8693--- /dev/null+++ b/apps/builder/app/builder/shared/assets/mdx-content-repository.ts@@ -0,0 +1,28 @@+import {+ createHttpAssetContentRepository as createSharedRepository,+ type AssetContentRepository,+} from "@webstudio-is/content-engine/asset-content-repository";+import { createProjectAssetContentTransport } from "@webstudio-is/http-client";++type HttpAssetContentRepositoryDependencies = Readonly<{+ projectId: string;+ origin: string;+ authToken?: () => string | undefined;+ request?: typeof fetch;+}>;++export const createHttpAssetContentRepository = ({+ projectId,+ origin,+ authToken = () => undefined,+ request = fetch,+}: HttpAssetContentRepositoryDependencies): AssetContentRepository =>+ createSharedRepository({+ projectId,+ ...createProjectAssetContentTransport({+ projectId,+ origin,+ authToken,+ request,+ }),+ });diff --git a/apps/builder/app/builder/shared/assets/upload-assets.test.ts b/apps/builder/app/builder/shared/assets/upload-assets.test.tsindex bf9ea90ab2..ec27c21e54 100644--- a/apps/builder/app/builder/shared/assets/upload-assets.test.ts+++ b/apps/builder/app/builder/shared/assets/upload-assets.test.ts@@ -247,6 +247,44 @@ describe("upload-assets", () => {expect(waitForUpload).toHaveBeenCalledWith(importedAsset.id);});+ test.each(["md", "mdx", "json"])(+ "imports mutable %s documents without deduplicating them",+ async (format) => {+ $project.set({ id: "target-project" } as Project);+ const sourceAsset = {+ id: "article",+ projectId: "source-project",+ name: `article.${format}`,+ type: "file",+ format,+ size: 1,+ createdAt: "2026-01-01",+ description: null,+ meta: {},+ } satisfies Asset;+ const importedAsset = {+ ...sourceAsset,+ id: "article-copy",+ projectId: "target-project",+ } satisfies Asset;+ const upload = vi.fn(async (_type, [url]: URL[]) => {+ return new Map([[url, importedAsset.id]]);+ });+ const waitForUpload = vi.fn(async () => importedAsset);+ const url = new URL(`https://source.example.com/article.${format}`);++ await importAssets(+ "target-project",+ [{ asset: sourceAsset, url: url.href }],+ { upload, waitForUpload }+ );++ expect(upload).toHaveBeenCalledWith("file", [url], {+ deduplicate: false,+ });+ }+ );+test("reuses matching assets from the current deployment", async () => {$project.set({ id: "target-project" } as Project);const existingAsset = {@@ -313,6 +351,29 @@ describe("upload-assets", () => {expect(init.body.get("contentHash")).toBe("a".repeat(64));});+ test("can reserve an independent asset with identical content", async () => {+ request.mockResolvedValue(+ Response.json({+ assetId: "new-asset-id",+ name: "new-name",+ deduplicated: false,+ })+ );++ await createUploadTicket({+ authToken: "token",+ projectId: "project-id",+ fileOrUrl: new File([], "empty.mdx", { type: "text/mdx" }),+ contentHash: "a".repeat(64),+ deduplicate: false,+ assetType: "file",+ request,+ });++ const [, init] = request.mock.calls[0] as [string, { body: FormData }];+ expect(init.body.get("contentHash")).toBeNull();+ });+test("reports non-error upload failures", async () => {request.mockRejectedValue("network down");const onCompleted = vi.fn();diff --git a/apps/builder/app/builder/shared/assets/upload-assets.tsx b/apps/builder/app/builder/shared/assets/upload-assets.tsxindex 64f1611d03..a4dfed5f87 100644--- a/apps/builder/app/builder/shared/assets/upload-assets.tsx+++ b/apps/builder/app/builder/shared/assets/upload-assets.tsx@@ -36,6 +36,7 @@ type AssetActionResponse = AssetUploadResult | { errors: string };type UploadAssetsOptions = {folderId?: string;dimensions?: { width: number; height: number };+ deduplicate?: boolean;};const safeDeleteAssets = (assetIds: Asset["id"][], projectId: string) => {@@ -301,6 +302,7 @@ const createUploadTicket = async ({projectId,fileOrUrl,contentHash,+ deduplicate = true,assetType,request = fetch,}: {@@ -308,6 +310,7 @@ const createUploadTicket = async ({projectId: string;fileOrUrl: File | URL;contentHash?: string;+ deduplicate?: boolean;assetType: AssetType;request?: typeof fetch;}): Promise<UploadTicket> => {@@ -315,7 +318,7 @@ const createUploadTicket = async ({const metaFormData = new FormData();metaFormData.append("projectId", projectId);metaFormData.append("type", assetType);- if (contentHash !== undefined) {+ if (contentHash !== undefined && deduplicate) {metaFormData.append("contentHash", contentHash);}const existingNames = new Set<string>();@@ -525,6 +528,7 @@ export const uploadAssets = async <T extends File | URL>(fileData.source === "file" ? fileData.file : new URL(fileData.url),contentHash:fileData.source === "file" ? fileData.contentHash : undefined,+ deduplicate: options.deduplicate,assetType: fileData.type,});fileData.assetId = ticket.assetId;@@ -615,15 +619,23 @@ export const importAssets = async (if (url === undefined) {throw new Error("Asset source URL is missing");}- const options =- source.asset.type === "video"- ? {- dimensions: {- width: source.asset.meta.width,- height: source.asset.meta.height,- },- }- : {};+ let options: UploadAssetsOptions = {};+ if (source.asset.type === "video") {+ options = {+ dimensions: {+ width: source.asset.meta.width,+ height: source.asset.meta.height,+ },+ };+ }+ if (+ source.asset.type === "file" &&+ ["md", "mdx", "json"].includes(source.asset.format.toLowerCase())+ ) {+ // Copy mutable documents independently because reference rewriting must+ // never modify an existing target Asset that upload deduplication reused.+ options = { deduplicate: false };+ }const assetId = (await upload(source.asset.type, [url], options)).get(url);if (assetId === undefined) {throw new Error("Failed to import asset");@@ -641,7 +653,7 @@ export const importAssets = async (export const uploadSingleAsset = async (type: AssetType,file: File,- options: { folderId?: string } = {}+ options: { folderId?: string; deduplicate?: boolean } = {}): Promise<Asset | undefined> => {const assetId = (await uploadAssets(type, [file], options)).get(file);return assetId === undefined ? undefined : waitForAssetUpload(assetId);diff --git a/apps/builder/app/builder/shared/commands.test.ts b/apps/builder/app/builder/shared/commands.test.tsindex b6b1b43426..7e72372d0e 100644--- a/apps/builder/app/builder/shared/commands.test.ts+++ b/apps/builder/app/builder/shared/commands.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, test, vi } from "vitest";import { createDefaultPages } from "@webstudio-is/project-build";import {+ blockComponent,blockTemplateComponent,type DataSource,type Instance,@@ -1616,6 +1617,65 @@ describe("move instance commands", () => {]);});+ test("moves direct Content Block children in content mode", () => {+ setupMoveInstanceProject();+ $instances.set(+ new Map($instances.get()).set("body", {+ ...$instances.get().get("body")!,+ component: blockComponent,+ })+ );+ $builderMode.set("content");+ selectInstance(["heading", "body"]);++ emitCommand("moveInstanceUp");++ expect($instances.get().get("body")?.children).toEqual([+ { type: "id", value: "heading" },+ { type: "id", value: "box" },+ { type: "id", value: "paragraph" },+ ]);+ });++ test("does not move Content Block children outside it in content mode", () => {+ setupMoveInstanceProject();+ $instances.set(+ new Map($instances.get()).set("body", {+ ...$instances.get().get("body")!,+ component: blockComponent,+ })+ );+ $builderMode.set("content");+ selectInstance(["box", "body"]);++ emitCommand("moveInstanceUp");++ expect($instances.get().get("body")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ { type: "id", value: "paragraph" },+ ]);+ });++ test("moves Content Block descendants into siblings in content mode", () => {+ setupMoveInstanceProject();+ $instances.set(+ new Map($instances.get()).set("body", {+ ...$instances.get().get("body")!,+ component: blockComponent,+ })+ );+ $builderMode.set("content");+ selectInstance(["heading", "body"]);++ emitCommand("moveInstanceIntoPreviousSibling");++ expect($instances.get().get("box")?.children).toEqual([+ { type: "id", value: "nested" },+ { type: "id", value: "heading" },+ ]);+ });+test("moves the first child above its parent", () => {setupMoveInstanceProject();selectInstance(["nested", "box", "body"]);diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.tsindex 1e7a41faa2..b80152bd9a 100644--- a/apps/builder/app/builder/shared/commands.ts+++ b/apps/builder/app/builder/shared/commands.ts@@ -3,7 +3,10 @@ import {deleteSelectedInstance,reparentInstance,} from "~/shared/instance-utils/mutation";-import { sortInstancePathsForChildMutation } from "@webstudio-is/project-build/runtime";+import {+ canMoveInstanceInContentMode,+ sortInstancePathsForChildMutation,+} from "@webstudio-is/project-build/runtime";import { toggleInstanceShow } from "~/shared/instance-utils/mutation";import { insertWebstudioFragmentAt } from "~/shared/instance-utils/insert";import { toast } from "@webstudio-is/design-system";@@ -30,6 +33,11 @@ import {toggleBuilderMode,} from "~/shared/nano-states";import { $instances } from "~/shared/sync/data-stores";+import {+ externalContentInstanceNameMessage,+ getExternalContentRoots,+ isExternalContentInstance,+} from "~/shared/external-content-mutations";// Declare command for type safetydeclare module "~/shared/pubsub" {@@ -596,10 +604,12 @@ const getInstanceMoveTarget = (direction: InstanceMoveDirection) => {};const moveSelectedInstance = (direction: InstanceMoveDirection) => {+ const isContentMode = $isContentMode.get();if (- guardDesignModeCommand({+ guardDesignOrContentModeCommand({+ isContentMode,isDesignMode: $isDesignMode.get(),- message: "Moving is only allowed in design mode.",+ message: "Moving is only allowed in design or content mode.",}) === false) {return;@@ -613,6 +623,17 @@ const moveSelectedInstance = (direction: InstanceMoveDirection) => {if (target === undefined) {return;}+ if (isContentMode) {+ if (+ canMoveInstanceInContentMode({+ instanceSelector: selectedItem.instanceSelector,+ parentSelector: target.parentSelector,+ instances: $instances.get(),+ }) === false+ ) {+ return;+ }+ }reparentInstance(selectedItem.instanceSelector, target);};@@ -1019,6 +1040,15 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({return;}const [selectedItem] = instancePath;+ if (+ isExternalContentInstance(+ getExternalContentRoots(),+ selectedItem.instance.id+ )+ ) {+ toast.info(externalContentInstanceNameMessage);+ return;+ }$editingItemSelector.set(selectedItem.instanceSelector);},},diff --git a/apps/builder/app/builder/shared/expression-editor.tsx b/apps/builder/app/builder/shared/expression-editor.tsxindex 03d539dc37..7bc2c26bed 100644--- a/apps/builder/app/builder/shared/expression-editor.tsx+++ b/apps/builder/app/builder/shared/expression-editor.tsx@@ -27,7 +27,7 @@ import {pickedCompletion,} from "@codemirror/autocomplete";import { javascript } from "@codemirror/lang-javascript";-import { textVariants, css, rawTheme } from "@webstudio-is/design-system";+import { css } from "@webstudio-is/design-system";import {lintExpression,allowedStringMethods,@@ -43,6 +43,7 @@ import {type EditorApi,foldGutterExtension,getCodeEditorCssVars,+ linterTooltipTheme,normalizeEditorValue,} from "~/shared/code-editor-base";import {@@ -540,28 +541,6 @@ const wrapperStyle = css({defaultVariants: { size: "default" },});-const linterTooltipTheme = EditorView.theme({- ".cm-tooltip:has(.cm-tooltip-lint)": {- backgroundColor: "transparent",- borderWidth: 0,- paddingTop: rawTheme.spacing[5],- paddingBottom: rawTheme.spacing[5],- pointerEvents: "none",- },- ".cm-tooltip-lint": {- backgroundColor: rawTheme.colors.backgroundTooltipMain,- color: rawTheme.colors.foregroundContrastMain,- borderRadius: rawTheme.borderRadius[7],- padding: rawTheme.spacing[5],- },- ".cm-tooltip-lint .cm-diagnostic": {- borderWidth: 0,- padding: 0,- margin: 0,- ...textVariants.regular,- },-});-const fullSizeEditorTheme = EditorView.theme({".cm-scroller": {minHeight: 0,diff --git a/apps/builder/app/canvas/features/build-mode/block-body.tsx b/apps/builder/app/canvas/features/build-mode/block-body.tsxnew file mode 100644index 0000000000..669b36a576--- /dev/null+++ b/apps/builder/app/canvas/features/build-mode/block-body.tsx@@ -0,0 +1,29 @@+import type {+ AnyComponent,+ WebstudioComponentSystemProps,+} from "@webstudio-is/react-sdk";+import * as React from "react";+import { useStore } from "@nanostores/react";+import { $isPreviewMode } from "~/shared/nano-states";++export const BlockBody = React.forwardRef<+ HTMLDivElement,+ { children: React.ReactNode } & WebstudioComponentSystemProps+>(({ children, ...props }, ref) => {+ const isPreviewMode = useStore($isPreviewMode);+ const isEmpty = React.Children.count(children) === 0;+ if (isPreviewMode && isEmpty) {+ return <></>;+ }+ return (+ <div+ ref={ref}+ style={+ isEmpty ? { minHeight: "1lh", width: "100%" } : { display: "contents" }+ }+ {...props}+ >+ {children}+ </div>+ );+}) as AnyComponent;diff --git a/apps/builder/app/canvas/features/build-mode/block.tsx b/apps/builder/app/canvas/features/build-mode/block.tsxindex af7085ce11..2c4f0a655d 100644--- a/apps/builder/app/canvas/features/build-mode/block.tsx+++ b/apps/builder/app/canvas/features/build-mode/block.tsx@@ -1,5 +1,5 @@import { useStore } from "@nanostores/react";-import { blockTemplateComponent } from "@webstudio-is/sdk";+import { findContentBlockTemplateContainers } from "@webstudio-is/sdk";import {idAttribute,selectorIdAttribute,@@ -31,21 +31,14 @@ export const Block = React.forwardRef<return <div>Content Block instance is undefined</div>;}- const templateInstanceId = instance.children.find(- (child) =>- child.type === "id" &&- instances.get(child.value)?.component === blockTemplateComponent- )?.value;-- if (templateInstanceId === undefined) {- return <div>Content Block template child is not found</div>;- }-- const templateInstance = instances.get(templateInstanceId);-+ const templateInstance = findContentBlockTemplateContainers({+ blockInstance: instance,+ instances,+ })[0];if (templateInstance === undefined) {- return <div>Content Block template instance is not found</div>;+ return <div>Content Block template child is not found</div>;}+ const templateInstanceId = templateInstance.id;if (isDesignMode) {if (selectedInstanceSelector !== undefined) {diff --git a/apps/builder/app/canvas/features/text-editor/interop.test.tsx b/apps/builder/app/canvas/features/text-editor/interop.test.tsxindex 8574169b7b..52ff11da04 100644--- a/apps/builder/app/canvas/features/text-editor/interop.test.tsx+++ b/apps/builder/app/canvas/features/text-editor/interop.test.tsx@@ -3,7 +3,12 @@ import { createHeadlessEditor } from "@lexical/headless";import { LinkNode } from "@lexical/link";import { $createParagraphNode, $createTextNode, $getRoot } from "lexical";import { $, renderData, renderTemplate, ws } from "@webstudio-is/template";-import { $convertToLexical, $convertToUpdates, type Refs } from "./interop";+import {+ $convertToLexical,+ $convertToPlainTextUpdate,+ $convertToUpdates,+ type Refs,+} from "./interop";const { instances } = renderData(<$.Body ws:id="bodyId">@@ -222,3 +227,34 @@ test("convert lexical to instances uses supplied id generator for new formatting).instances);});++test("convert lexical formatting to plain text content", async () => {+ const editor = createHeadlessEditor({ nodes: [LinkNode] });+ await new Promise<void>((resolve) => {+ editor.update(+ () => {+ const paragraph = $createParagraphNode();+ const text = $createTextNode("const answer = 42;");+ text.toggleFormat("bold");+ paragraph.append(text);+ $getRoot().append(paragraph);+ },+ { onUpdate: resolve }+ );+ });+ const treeRootInstance = instances.get("emptyBoxId");+ if (treeRootInstance === undefined) {+ throw Error("Tree root instance should be in test data");+ }++ expect(+ editor+ .getEditorState()+ .read(() => $convertToPlainTextUpdate(treeRootInstance))+ ).toEqual([+ {+ ...treeRootInstance,+ children: [{ type: "text", value: "const answer = 42;" }],+ },+ ]);+});diff --git a/apps/builder/app/canvas/features/text-editor/interop.ts b/apps/builder/app/canvas/features/text-editor/interop.tsindex a7cd862927..9a10295c62 100644--- a/apps/builder/app/canvas/features/text-editor/interop.ts+++ b/apps/builder/app/canvas/features/text-editor/interop.ts@@ -154,6 +154,13 @@ export const $convertToUpdates = (return instancesList;};+export const $convertToPlainTextUpdate = (treeRootInstance: Instance) => [+ {+ ...treeRootInstance,+ children: [{ type: "text" as const, value: $getRoot().getTextContent() }],+ },+];+const $writeLexical = (parent: ElementNode | TextNode,children: Instance["children"],diff --git a/apps/builder/app/canvas/features/text-editor/text-editor.test.tsx b/apps/builder/app/canvas/features/text-editor/text-editor.test.tsxnew file mode 100644index 0000000000..6b0101881f--- /dev/null+++ b/apps/builder/app/canvas/features/text-editor/text-editor.test.tsx@@ -0,0 +1,63 @@+import { act } from "react-dom/test-utils";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, describe, expect, test } from "vitest";+import { ContentEditable } from "@lexical/react/LexicalContentEditable";+import { elementComponent, type Instance } from "@webstudio-is/sdk";+import { $textEditingInstanceSelector } from "~/shared/nano-states";+import { TextEditor } from "./text-editor";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let root: Root | undefined;++afterEach(() => {+ act(() => {+ root?.unmount();+ });+ root = undefined;+ document.body.innerHTML = "";+ $textEditingInstanceSelector.set(undefined);+});++describe("TextEditor", () => {+ test("focuses the editable element when initializing a new empty instance", async () => {+ const instance: Instance = {+ type: "instance",+ id: "list-item",+ component: elementComponent,+ tag: "li",+ children: [],+ };+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ $textEditingInstanceSelector.set({+ selector: [instance.id],+ reason: "new",+ });++ await act(async () => {+ root?.render(+ <TextEditor+ rootInstanceSelector={[instance.id]}+ instances={new Map([[instance.id, instance]])}+ props={new Map()}+ contentEditable={<ContentEditable />}+ onChange={() => {}}+ onSelectInstance={() => {}}+ />+ );+ });++ const editable = container.querySelector<HTMLElement>(+ "[data-lexical-editor]"+ );+ expect(editable).not.toBeNull();+ expect(document.activeElement).toBe(editable);+ expect(editable?.contains(window.getSelection()?.anchorNode ?? null)).toBe(+ true+ );+ });+});diff --git a/apps/builder/app/canvas/features/text-editor/text-editor.tsx b/apps/builder/app/canvas/features/text-editor/text-editor.tsxindex 9e251c5879..544137345c 100644--- a/apps/builder/app/canvas/features/text-editor/text-editor.tsx+++ b/apps/builder/app/canvas/features/text-editor/text-editor.tsx@@ -64,7 +64,12 @@ import {} from "@webstudio-is/project-build/runtime";import { builderRuntimeContext } from "@webstudio-is/project-build/runtime";import { ToolbarConnectorPlugin } from "./toolbar-connector";-import { type Refs, $convertToLexical, $convertToUpdates } from "./interop";+import {+ type Refs,+ $convertToLexical,+ $convertToPlainTextUpdate,+ $convertToUpdates,+} from "./interop";import { useEffectEvent } from "~/shared/hook-utils/effect-event";import { deleteInstanceBySelector } from "~/shared/instance-utils/mutation";import {@@ -74,6 +79,7 @@ import {$registeredComponentMetas,$textEditingInstanceSelector,$textEditorContextMenu,+ $textEditorContextMenuCommand,execTextEditorContextMenuCommand,} from "~/shared/nano-states";import { $instances } from "~/shared/sync/data-stores";@@ -790,6 +796,9 @@ const InitCursorPlugin = () => {// We are controlling scroll ourself in instance-selected.ts see updateScroll.// Without skipping we are getting side effects of composition in scrollBy, scrollIntoView callstag: "skip-scroll-into-view",+ onUpdate: () => {+ editor.focus();+ },});}, [editor]);@@ -1070,15 +1079,18 @@ const RichTextContentPluginInternal = ({let menuState: "closed" | "opening" | "opened" = "closed";let slashNodeKey: NodeKey | undefined = undefined;+ let removeSlashWhenSelectionChanges = false;const closeMenu = () => {- if (menuState === "closed") {+ if (menuState === "closed" && removeSlashWhenSelectionChanges === false) {return;}- menuState = "closed";+ if (menuState !== "closed") {+ menuState = "closed";- handleOpen(editor.getEditorState(), undefined);+ handleOpen(editor.getEditorState(), undefined);+ }if (slashNodeKey === undefined) {return;@@ -1098,6 +1110,8 @@ const RichTextContentPluginInternal = ({if (!isSelectionInSameComponent) {node?.remove();+ slashNodeKey = undefined;+ removeSlashWhenSelectionChanges = false;// Delete currentif ($getRoot().getTextContentSize() === 0) {@@ -1123,6 +1137,17 @@ const RichTextContentPluginInternal = ({selection.setStyle("");};+ const unsubscribeContextMenuCommand = $textEditorContextMenuCommand.listen(+ (command) => {+ if (command?.type === "templateInsertionStarted") {+ removeSlashWhenSelectionChanges = true;+ }+ if (command?.type === "templateInsertionCancelled") {+ removeSlashWhenSelectionChanges = false;+ }+ }+ );+const unsubscibeSelectionChange = editor.registerCommand(SELECTION_CHANGE_COMMAND,() => {@@ -1335,7 +1360,7 @@ const RichTextContentPluginInternal = ({);const closeMenuWithUpdate = () => {- if (menuState === "closed") {+ if (menuState === "closed" && removeSlashWhenSelectionChanges === false) {return;}@@ -1407,6 +1432,7 @@ const RichTextContentPluginInternal = ({unsubscribeUpdateListener();unsubscibeSelectionChange();unsubscribeBlurListener();+ unsubscribeContextMenuCommand();// Safari and FF support as no blur event is triggered in some casescloseMenuWithUpdate();};@@ -1425,6 +1451,7 @@ type TextEditorProps = {props: Props;contentEditable: JSX.Element;editable?: boolean;+ plainText?: boolean;onChange: (instancesList: Instance[]) => void | Record<string, string>;onSelectInstance: (instanceId: Instance["id"]) => void;};@@ -1506,6 +1533,7 @@ export const TextEditor = ({props,contentEditable,editable,+ plainText = false,onChange,onSelectInstance,}: TextEditorProps) => {@@ -1527,14 +1555,15 @@ export const TextEditor = ({return;}- const idMap = onChange(- $convertToUpdates(- treeRootInstance,- refs,- newLinkKeyToInstanceId,- builderRuntimeContext.createId- )- );+ const updates = plainText+ ? $convertToPlainTextUpdate(treeRootInstance)+ : $convertToUpdates(+ treeRootInstance,+ refs,+ newLinkKeyToInstanceId,+ builderRuntimeContext.createId+ );+ const idMap = onChange(updates);if (idMap !== undefined) {for (const [key, instanceId] of refs) {refs.set(key, idMap[instanceId] ?? instanceId);@@ -1724,14 +1753,16 @@ export const TextEditor = ({<LexicalComposer initialConfig={initialConfig}><RemoveParagaphsPlugin /><CaretColorPlugin />- <ToolbarConnectorPlugin- onSelectNode={(nodeKey) => {- const instanceId = refs.get(`${nodeKey}:span`);- if (instanceId !== undefined) {- onSelectInstance(instanceId);- }- }}- />+ {plainText === false && (+ <ToolbarConnectorPlugin+ onSelectNode={(nodeKey) => {+ const instanceId = refs.get(`${nodeKey}:span`);+ if (instanceId !== undefined) {+ onSelectInstance(instanceId);+ }+ }}+ />+ )}<BindInstanceToNodePluginrefs={refs}rootInstanceSelector={rootInstanceSelector}@@ -1740,26 +1771,30 @@ export const TextEditor = ({ErrorBoundary={LexicalErrorBoundary}contentEditable={contentEditable}/>- <LinkPlugin />+ {plainText === false && <LinkPlugin />}- <LinkSanitizePlugin />+ {plainText === false && <LinkSanitizePlugin />}<HistoryPlugin />{/* oxlint-disable-next-line react-hooks/rules-of-hooks -- our useEffectEvent is a stable callback */}<SwitchBlockPlugin onNext={handleNext} />- <RichTextContentPlugin- onOpen={handleContextMenuOpen}- rootInstanceSelector={rootInstanceSelector}- // oxlint-disable-next-line react-hooks/rules-of-hooks -- our useEffectEvent is a stable callback- onNext={handleNext}- />+ {plainText === false && (+ <RichTextContentPlugin+ onOpen={handleContextMenuOpen}+ rootInstanceSelector={rootInstanceSelector}+ // oxlint-disable-next-line react-hooks/rules-of-hooks -- our useEffectEvent is a stable callback+ onNext={handleNext}+ />+ )}{/* oxlint-disable-next-line react-hooks/rules-of-hooks -- our useEffectEvent is a stable callback */}<OnChangeOnBlurPlugin onChange={handleChange} /><InitCursorPlugin />- <LinkSelectionPlugin- rootInstanceSelector={rootInstanceSelector}- registerNewLink={registerNewLink}- />+ {plainText === false && (+ <LinkSelectionPlugin+ rootInstanceSelector={rootInstanceSelector}+ registerNewLink={registerNewLink}+ />+ )}<AnyKeyDownPlugin onKeyDown={handleAnyKeydown} /><InitialJSONStatePluginonInitialState={(json) => {diff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsxindex c1e1f46a28..fb347292f1 100644--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx@@ -24,8 +24,10 @@ import {collectionComponent,descendantComponent,blockComponent,+ blockBodyComponent,blockTemplateComponent,getIndexesWithinAncestors,+ getContentBlockSource,elementComponent,} from "@webstudio-is/sdk";import { indexProperty, tagProperty } from "@webstudio-is/sdk/runtime";@@ -39,7 +41,7 @@ import {standardAttributesToReactProps,getCollectionEntries,} from "@webstudio-is/react-sdk";-import { rawTheme } from "@webstudio-is/design-system";+import { rawTheme, toast } from "@webstudio-is/design-system";import {Input,Link,@@ -51,10 +53,12 @@ import {$propValuesByInstanceSelectorWithMemoryProps,getIndexedInstanceId,$registeredComponentMetas,+ $variableValuesByInstanceSelector,+ $isDesignMode,$selectedInstanceRenderState,$selectedPageHash,} from "~/shared/nano-states";-import { $props } from "~/shared/sync/data-stores";+import { $project, $props } from "~/shared/sync/data-stores";import { $textEditingInstanceSelector } from "~/shared/nano-states";import { $instances } from "~/shared/sync/data-stores";import {@@ -74,12 +78,33 @@ import {type WebstudioComponentProps,} from "~/canvas/elements";import { Block } from "../build-mode/block";+import { BlockBody } from "../build-mode/block-body";import { BlockTemplate } from "../build-mode/block-template";import {editablePlaceholderAttribute,editingPlaceholderVariable,} from "~/canvas/shared/styles";import { richTextPlaceholders } from "@webstudio-is/project-build/runtime";+import {+ acquireExternalContentRoot,+ updateExternalContentFrontmatter,+} from "~/shared/external-content-roots";+import {+ $externalContentRoots,+ findExternalContentRoot,+ findExternalContentRootEntryBySelector,+ getExternalContentRoots,+ resolveExternalContentOccurrence,+} from "~/shared/external-content-mutations";+import {+ getSelectedContentBlockDocumentBindingPath,+ isObjectPathWritable,+} from "~/shared/content-block-document";+import {+ formatContentBlockDiagnostic,+ takeNewContentBlockDiagnostics,+} from "~/shared/content-block-diagnostics";+import { resolveContentBlockOccurrenceAssetId } from "~/shared/content-block-source-utils";const computeComponentKey = (props: Record<string, unknown>) => {const assetId = props.$webstudio$canvasOnly$assetId;@@ -476,13 +501,167 @@ const getEditableComponentPlaceholder = (return placeholder;};-export const WebstudioComponentCanvas = forwardRef<+const ExternalContentRootLoader = ({+ instance,+ instanceSelector,+ includeUnresolvedTemplatePlaceholders,+ showDiagnostics,+}: {+ instance: Instance;+ instanceSelector: InstanceSelector;+ includeUnresolvedTemplatePlaceholders: boolean;+ showDiagnostics: boolean;+}) => {+ const allProps = useStore($props);+ const project = useStore($project);+ const variableValues = useStore($variableValuesByInstanceSelector);+ const externalContentRoots = useStore($externalContentRoots);+ const renderScope = getInstanceKey(instanceSelector);+ const source = useMemo(+ () =>+ getContentBlockSource({+ blockInstanceId: instance.id,+ props: allProps.values(),+ }),+ [allProps, instance.id]+ );+ const sourceAssetId = useMemo(() => {+ if (source === undefined) {+ return;+ }+ return resolveContentBlockOccurrenceAssetId({+ source,+ instanceSelector,+ variableValuesByRenderScope: variableValues,+ });+ }, [instanceSelector, source, variableValues]);++ const diagnosticsSnapshot = findExternalContentRoot(+ externalContentRoots,+ instance.id,+ renderScope+ );++ useEffect(() => {+ if (showDiagnostics === false) {+ return;+ }+ for (const diagnostic of takeNewContentBlockDiagnostics(+ diagnosticsSnapshot?.diagnostics ?? [],+ diagnosticsSnapshot?.identity?.revision+ )) {+ toast.warn(formatContentBlockDiagnostic(diagnostic));+ }+ }, [+ diagnosticsSnapshot?.diagnostics,+ diagnosticsSnapshot?.identity?.revision,+ showDiagnostics,+ ]);++ useLayoutEffect(() => {+ if (project === undefined || sourceAssetId === undefined) {+ return;+ }+ let active = true;+ const controller = new AbortController();+ let release: (() => void) | undefined;+ void acquireExternalContentRoot({+ projectId: project.id,+ assetId: sourceAssetId,+ blockInstanceId: instance.id,+ renderScope,+ includeUnresolvedTemplatePlaceholders,+ signal: controller.signal,+ })+ .then((nextRelease) => {+ if (active === false) {+ nextRelease();+ return;+ }+ release = nextRelease;+ })+ .catch((error) => {+ if (active) {+ toast.error(+ error instanceof Error+ ? error.message+ : "Unable to load MDX content"+ );+ }+ });+ return () => {+ active = false;+ controller.abort();+ release?.();+ };+ }, [+ includeUnresolvedTemplatePlaceholders,+ instance.id,+ project,+ renderScope,+ sourceAssetId,+ ]);+ return null;+};++const getExternalContentInstance = ({+ sourceInstance,+ sourceInstanceSelector,+ instances,+}: {+ sourceInstance: Instance;+ sourceInstanceSelector: InstanceSelector;+ instances: Instances;+}) => {+ const occurrence = resolveExternalContentOccurrence({+ sourceInstance,+ sourceSelector: sourceInstanceSelector,+ instances,+ roots: getExternalContentRoots(),+ });+ return occurrence === undefined+ ? undefined+ : { instance: occurrence.instance, instanceSelector: occurrence.selector };+};++const getUpdatedText = (+ rootInstanceId: Instance["id"],+ updates: readonly Instance[]+) => {+ const byId = new Map(updates.map((instance) => [instance.id, instance]));+ const visit = (instanceId: Instance["id"]): string | undefined => {+ const instance = byId.get(instanceId);+ if (instance === undefined) {+ return;+ }+ let value = "";+ for (const child of instance.children) {+ if (child.type === "expression") {+ return;+ }+ if (child.type === "text") {+ value += child.value;+ continue;+ }+ const nested = visit(child.value);+ if (nested === undefined) {+ return;+ }+ value += nested;+ }+ return value;+ };+ return visit(rootInstanceId);+};++const WebstudioComponentCanvasInner = forwardRef<HTMLElement,WebstudioComponentProps>(({ instance, instanceSelector, components, ...restProps }, ref) => {const instanceId = instance.id;const instances = useStore($instances);const allProps = useStore($props);+ const externalContentRoots = useStore($externalContentRoots);const metas = useStore($registeredComponentMetas);const textEditingInstanceSelector = useStore($textEditingInstanceSelector);@@ -576,6 +755,10 @@ export const WebstudioComponentCanvas = forwardRef<Component = Block;}+ if (instance.component === blockBodyComponent) {+ Component = BlockBody;+ }+if (instance.component === blockTemplateComponent) {Component = BlockTemplate;}@@ -627,11 +810,37 @@ export const WebstudioComponentCanvas = forwardRef<return instanceElement;}+ const contentModel = metas.get(instance.component)?.contentModel;+ const expressionChild =+ instance.children.length === 1 && instance.children[0].type === "expression"+ ? instance.children[0]+ : undefined;+ const externalEntry = findExternalContentRootEntryBySelector(+ externalContentRoots,+ instanceSelector+ );+ const candidateRoot = externalEntry?.[1];+ const frontmatterPath =+ expressionChild === undefined+ ? undefined+ : getSelectedContentBlockDocumentBindingPath({+ binding: expressionChild,+ instanceSelector,+ instances,+ props: allProps,+ sourceBlockInstanceId: candidateRoot?.sourceBlockInstanceId,+ renderedBlockInstanceId: candidateRoot?.blockInstanceId,+ });return (<TextEditorrootInstanceSelector={instanceSelector}instances={instances}props={allProps}+ plainText={+ frontmatterPath !== undefined ||+ (contentModel?.children.length === 1 &&+ contentModel.children[0] === "text")+ }contentEditable={<ContentEditableplaceholder={getEditableComponentPlaceholder(@@ -642,13 +851,54 @@ export const WebstudioComponentCanvas = forwardRef<"editing")}renderComponentWithRef={(elementRef) => (- <Component {...props} ref={mergeRefs(ref, elementRef)}>+ <Component+ {...props}+ data-ws-text-editing=""+ ref={mergeRefs(ref, elementRef)}+ >{initialContentEditableContent.current}</Component>)}/>}onChange={(instancesList) => {+ if (frontmatterPath !== undefined) {+ const value = getUpdatedText(instance.id, instancesList);+ if (externalEntry === undefined) {+ toast.error("The MDX content source is not ready for editing.");+ return;+ }+ const [rootKey, externalRoot] = externalEntry;+ if (externalRoot.document === undefined) {+ toast.error("The MDX content source is not ready for editing.");+ return;+ }+ if (+ isObjectPathWritable({+ value: externalRoot.document.frontmatter.properties,+ path: frontmatterPath,+ }) === false+ ) {+ toast.error("Open the referenced file to edit this value.");+ return;+ }+ if (value === undefined) {+ toast.error("This frontmatter value must remain plain text.");+ return;+ }+ void updateExternalContentFrontmatter({+ rootKey,+ path: frontmatterPath,+ value,+ }).catch((error) => {+ toast.error(+ error instanceof Error+ ? error.message+ : "Unable to update MDX frontmatter"+ );+ });+ return;+ }const result = executeRuntimeMutation({id: "instances.updateTextTree",input: {@@ -672,7 +922,43 @@ export const WebstudioComponentCanvas = forwardRef<);});-export const WebstudioComponentPreview = forwardRef<+export const WebstudioComponentCanvas = forwardRef<+ HTMLElement,+ WebstudioComponentProps+>(({ instance, instanceSelector, ...props }, ref) => {+ const instances = useStore($instances);+ const isDesignMode = useStore($isDesignMode);+ const externalContent = isDesignMode+ ? undefined+ : getExternalContentInstance({+ sourceInstance: instance,+ sourceInstanceSelector: instanceSelector,+ instances,+ });+ const renderedInstance = externalContent?.instance ?? instance;+ const renderedInstanceSelector =+ externalContent?.instanceSelector ?? instanceSelector;+ return (+ <>+ {instance.component === blockComponent ? (+ <ExternalContentRootLoader+ instance={instance}+ instanceSelector={instanceSelector}+ includeUnresolvedTemplatePlaceholders={true}+ showDiagnostics={true}+ />+ ) : null}+ <WebstudioComponentCanvasInner+ {...props}+ ref={ref}+ instance={renderedInstance}+ instanceSelector={renderedInstanceSelector}+ />+ </>+ );+});++const WebstudioComponentPreviewInner = forwardRef<HTMLElement,WebstudioComponentProps>(({ instance, instanceSelector, components, ...restProps }, ref) => {@@ -745,6 +1031,10 @@ export const WebstudioComponentPreview = forwardRef<Component = Block;}+ if (instance.component === blockBodyComponent) {+ Component = BlockBody;+ }+if (instance.component === blockTemplateComponent) {Component = BlockTemplate;}@@ -778,3 +1068,36 @@ export const WebstudioComponentPreview = forwardRef<return element;});++export const WebstudioComponentPreview = forwardRef<+ HTMLElement,+ WebstudioComponentProps+>(({ instance, instanceSelector, ...props }, ref) => {+ const instances = useStore($instances);+ const externalContent = getExternalContentInstance({+ sourceInstance: instance,+ sourceInstanceSelector: instanceSelector,+ instances,+ });+ const renderedInstance = externalContent?.instance ?? instance;+ const renderedInstanceSelector =+ externalContent?.instanceSelector ?? instanceSelector;+ return (+ <>+ {instance.component === blockComponent ? (+ <ExternalContentRootLoader+ instance={instance}+ instanceSelector={instanceSelector}+ includeUnresolvedTemplatePlaceholders={false}+ showDiagnostics={false}+ />+ ) : null}+ <WebstudioComponentPreviewInner+ {...props}+ ref={ref}+ instance={renderedInstance}+ instanceSelector={renderedInstanceSelector}+ />+ </>+ );+});diff --git a/apps/builder/app/canvas/instance-selection-events.ts b/apps/builder/app/canvas/instance-selection-events.tsindex 8f549c1094..7e26253cdc 100644--- a/apps/builder/app/canvas/instance-selection-events.ts+++ b/apps/builder/app/canvas/instance-selection-events.ts@@ -142,6 +142,7 @@ const handleEdit = (isContentMode: true,instanceSelector: editableInstanceSelector,instances,+ props: $props.get(),}) === false) {editableInstanceSelector = undefined;diff --git a/apps/builder/app/canvas/shared/commands.ts b/apps/builder/app/canvas/shared/commands.tsindex 345051d3bc..2293057442 100644--- a/apps/builder/app/canvas/shared/commands.ts+++ b/apps/builder/app/canvas/shared/commands.ts@@ -101,6 +101,7 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({isContentMode: $isContentMode.get(),instanceSelector: editableInstanceSelector,instances: $instances.get(),+ props: $props.get(),}) === false) {return;diff --git a/apps/builder/app/canvas/shared/content-mode.test.ts b/apps/builder/app/canvas/shared/content-mode.test.tsindex db12c3e620..d74ce7efb2 100644--- a/apps/builder/app/canvas/shared/content-mode.test.ts+++ b/apps/builder/app/canvas/shared/content-mode.test.ts@@ -1,8 +1,14 @@import { describe, expect, test } from "vitest";import {+ blockBodyComponent,blockComponent,blockTemplateComponent,+ contentBlockDocumentProp,+ contentBlockSourceProp,+ encodeDataSourceVariable,elementComponent,+ type Instance,+ type Prop,} from "@webstudio-is/sdk";import { isTextEditableInContentMode } from "./content-mode";@@ -29,6 +35,7 @@ describe("isTextEditableInContentMode", () => {isContentMode: true,instanceSelector: ["inside", "block", "body"],instances,+ props: new Map(),})).toBe(true);expect(@@ -36,6 +43,7 @@ describe("isTextEditableInContentMode", () => {isContentMode: true,instanceSelector: ["outside", "body"],instances,+ props: new Map(),})).toBe(false);expect(@@ -43,6 +51,7 @@ describe("isTextEditableInContentMode", () => {isContentMode: true,instanceSelector: ["source", "templates", "block", "body"],instances,+ props: new Map(),})).toBe(false);});@@ -53,7 +62,70 @@ describe("isTextEditableInContentMode", () => {isContentMode: false,instanceSelector: ["outside", "body"],instances,+ props: new Map(),})).toBe(true);});++ test("permits a direct frontmatter text binding outside the Body", () => {+ const document = encodeDataSourceVariable("document-source");+ const explicitInstances = new Map<string, Instance>([+ ["block", instance("block", blockComponent, ["title", "content"])],+ [+ "title",+ {+ ...instance("title", elementComponent),+ children: [+ {+ type: "expression" as const,+ value: `${document}.frontmatter.title`,+ mode: "readwrite" as const,+ },+ ],+ },+ ],+ ["content", instance("content", blockBodyComponent)],+ ]);+ const props = new Map<string, Prop>([+ [+ "source",+ {+ id: "source",+ instanceId: "block",+ name: contentBlockSourceProp,+ type: "asset",+ value: "article",+ },+ ],+ [+ "document",+ {+ id: "document",+ instanceId: "block",+ name: contentBlockDocumentProp,+ type: "parameter",+ value: "document-source",+ },+ ],+ ]);++ expect(+ isTextEditableInContentMode({+ isContentMode: true,+ instanceSelector: ["title", "block"],+ instances: explicitInstances,+ props,+ })+ ).toBe(true);++ props.delete("source");+ expect(+ isTextEditableInContentMode({+ isContentMode: true,+ instanceSelector: ["title", "block"],+ instances: explicitInstances,+ props,+ })+ ).toBe(false);+ });});diff --git a/apps/builder/app/canvas/shared/content-mode.ts b/apps/builder/app/canvas/shared/content-mode.tsindex ced62d01a0..e97cb698d5 100644--- a/apps/builder/app/canvas/shared/content-mode.ts+++ b/apps/builder/app/canvas/shared/content-mode.ts@@ -1,20 +1,30 @@-import { getContentModeEditableInstanceIds } from "@webstudio-is/project-build/runtime";+import {+ getContentModeEditableInstanceIds,+ getContentModeFrontmatterBoundTargets,+} from "@webstudio-is/project-build/runtime";import type { InstanceSelector } from "@webstudio-is/project-build/runtime";-import type { Instances } from "@webstudio-is/sdk";+import type { Instances, Props } from "@webstudio-is/sdk";export const isTextEditableInContentMode = ({isContentMode,instanceSelector,instances,+ props,}: {isContentMode: boolean;instanceSelector: InstanceSelector;instances: Instances;+ props: Props;}) => {if (isContentMode === false) {return true;}- return getContentModeEditableInstanceIds({ instances }).has(- instanceSelector[0]+ const instanceId = instanceSelector[0];+ return (+ getContentModeEditableInstanceIds({ instances }).has(instanceId) ||+ getContentModeFrontmatterBoundTargets({+ instances,+ props,+ }).textInstanceIds.has(instanceId));};diff --git a/apps/builder/app/services/api-router.server.ts b/apps/builder/app/services/api-router.server.tsindex 601ad9391c..aa655425d3 100644--- a/apps/builder/app/services/api-router.server.ts+++ b/apps/builder/app/services/api-router.server.ts@@ -40,7 +40,9 @@ import {loadBuilderAssetFieldCatalog,loadAssetDataByProject,loadAssetFoldersByProject,+ PostgresAssetRepository,} from "@webstudio-is/asset-uploader/server";+import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session";import { buildPatchTransaction } from "@webstudio-is/protocol/schema";import {publicApiContractVersion,@@ -54,10 +56,12 @@ import {loadApiToken,} from "./api-permits.server";import { componentMetas } from "~/shared/component-metas.server";-import { type Asset, type AssetFolder } from "@webstudio-is/sdk";+import type { Asset, AssetFolder } from "@webstudio-is/sdk";import {applyContentModeTransaction,+ createContentBlockApplication,getContentModeCapabilities,+ type BuilderRuntimeContext,} from "@webstudio-is/project-build/runtime";import type { CompactBuild } from "@webstudio-is/project-build";import {@@ -340,6 +344,7 @@ const commitRuntimeMutation = async <assetFolders,input,commit,+ context,}: {id: RuntimeOperationId;build: Awaited<ReturnType<typeof loadDevBuildByProjectId>>;@@ -347,6 +352,7 @@ const commitRuntimeMutation = async <assetFolders?: AssetFolder[];input: unknown;commit: BuildCommit;+ context?: Partial<BuilderRuntimeContext>;}) => {const mutation = await executeApiRuntimeMutation<Result>({id,@@ -354,6 +360,7 @@ const commitRuntimeMutation = async <assets,assetFolders,input,+ context,});if (mutation.noop || mutation.payload.length === 0) {return {@@ -464,18 +471,58 @@ const loadRuntimeAssetData = async (ctx: AppContext, projectId: string) => {});};+const createServerContentBlockApplication = ({+ ctx,+ projectId,+ build,+ assets,+ assetFolders,+}: {+ ctx: AppContext;+ projectId: string;+ build: CompactBuild;+ assets: Asset[];+ assetFolders: AssetFolder[];+}) => {+ const state = createBuilderRuntimeState(build, assets, assetFolders);+ const repository = new PostgresAssetRepository({+ projectId,+ context: ctx,+ assetStore: createAssetClient(),+ });+ const session = createAssetContentSession({+ repository,+ authorize: ({ assetId }) => state.assets?.has(assetId) === true,+ });+ return createContentBlockApplication({+ projectId,+ session,+ metas: componentMetas,+ });+};+const runtimeAssetsQuery = <Result = unknown>(id: RuntimeOperationId) =>projectQuery(runtimeProjectInput(id), "view", async ({ ctx, input }) => {const [{ assets, assetFolders }, build] = await Promise.all([loadRuntimeAssetData(ctx, input.projectId),loadDevBuildByProjectId(ctx, input.projectId),]);+ const contentBlockApplication = id.startsWith("contentBlocks.")+ ? createServerContentBlockApplication({+ ctx,+ projectId: input.projectId,+ build,+ assets,+ assetFolders,+ })+ : undefined;return executeApiRuntimeOperation<Result>({id,build,assets,assetFolders,input,+ context: { contentBlockApplication },});});@@ -500,6 +547,38 @@ const runtimeAssetsMutation = <Result extends Record<string, unknown> = {}>(});+const runtimeContentBlockMutation = <+ Result extends Record<string, unknown> = {},+>(+ id: RuntimeOperationId+) =>+ contentOrBuildMutation(+ runtimeMutationInput(id, false),+ async ({ ctx, input, build, commit }) => {+ const { assets, assetFolders } = await loadRuntimeAssetData(+ ctx,+ input.projectId+ );+ return await commitRuntimeMutation<Result>({+ id,+ build,+ assets,+ assetFolders,+ input,+ commit,+ context: {+ contentBlockApplication: createServerContentBlockApplication({+ ctx,+ projectId: input.projectId,+ build,+ assets,+ assetFolders,+ }),+ },+ });+ }+ );+type RuntimeOperationRouteTree = Record<string, unknown>;type RouterRecord = Parameters<typeof router>[0];type RuntimeOperation = (typeof runtimeOperationContracts)[number];@@ -532,7 +611,9 @@ const createRuntimeOperationProcedure = (operation: RuntimeOperation) => {if (operation.requiresAssets) {return operation.kind === "read"? runtimeAssetsQuery(id)- : runtimeAssetsMutation(id);+ : id.startsWith("contentBlocks.")+ ? runtimeContentBlockMutation(id)+ : runtimeAssetsMutation(id);}if (operation.kind === "read") {return runtimeBuildQuery(id);diff --git a/apps/builder/app/services/api-runtime.server.ts b/apps/builder/app/services/api-runtime.server.tsindex 9c6602a185..5736266197 100644--- a/apps/builder/app/services/api-runtime.server.ts+++ b/apps/builder/app/services/api-runtime.server.ts@@ -1,9 +1,12 @@import type { CompactBuild } from "@webstudio-is/project-build";import type { RuntimeOperationId } from "@webstudio-is/project-build/contracts";-import { executeBuilderRuntimeOperation } from "@webstudio-is/project-build/runtime";-import { BuilderRuntimeError } from "@webstudio-is/project-build/runtime";-import { builderRuntimeContext } from "@webstudio-is/project-build/runtime";-import { type BuilderRuntimeMutation } from "@webstudio-is/project-build/runtime";+import {+ BuilderRuntimeError,+ builderRuntimeContext,+ executeBuilderRuntimeOperation,+ type BuilderRuntimeContext,+ type BuilderRuntimeMutation,+} from "@webstudio-is/project-build/runtime";import type { BuilderState } from "@webstudio-is/project-build/state";import { createBuilderStateFromCompactBuild } from "@webstudio-is/project-build/state";import { type Asset, type AssetFolder } from "@webstudio-is/sdk";@@ -26,12 +29,14 @@ export const executeApiRuntimeOperation = async <Result>({assets,assetFolders,input,+ context,}: {id: RuntimeOperationId;build: CompactBuild;assets?: Asset[];assetFolders?: AssetFolder[];input: unknown;+ context?: Partial<BuilderRuntimeContext>;}): Promise<Result> => {try {return await executeBuilderRuntimeOperation<Result>({@@ -42,6 +47,7 @@ export const executeApiRuntimeOperation = async <Result>({createId: builderRuntimeContext.createId,projectId: build.projectId,projectVersion: build.version,+ ...context,},});} catch (error) {@@ -67,4 +73,5 @@ export const executeApiRuntimeMutation = <assets?: Asset[];assetFolders?: AssetFolder[];input: unknown;+ context?: Partial<BuilderRuntimeContext>;}) => executeApiRuntimeOperation<BuilderRuntimeMutation<Result>>(args);diff --git a/apps/builder/app/services/asset-rest-route-handlers.server.ts b/apps/builder/app/services/asset-rest-route-handlers.server.tsindex 8b0f98031d..863d7a07ab 100644--- a/apps/builder/app/services/asset-rest-route-handlers.server.ts+++ b/apps/builder/app/services/asset-rest-route-handlers.server.ts@@ -7,8 +7,10 @@ import { Readable } from "node:stream";import parseRange from "range-parser";import { getAssetMime } from "@webstudio-is/sdk";import {+ assetContentDescriptorHeader,assetMetadataUpdate,assetResourceApiOperations,+ serializeAssetContentDescriptor,} from "@webstudio-is/protocol/asset-resource-api";import { privateNoStoreResponseHeaders } from "./cache-control.server";import { ensureApiCsrf } from "./api-auth.server";@@ -69,9 +71,13 @@ export const createAssetContentLoader =const range = parseRequestRange(request.headers.get("range"), asset.size);const content = await repository.readContent({ assetId, range, asset });const headers = new Headers(privateNoStoreResponseHeaders);+ headers.set(+ assetContentDescriptorHeader,+ serializeAssetContentDescriptor(content.asset)+ );headers.set("content-type",- getAssetMime(asset) ?? "application/octet-stream"+ getAssetMime(content.asset) ?? "application/octet-stream");headers.set("accept-ranges", "bytes");headers.set(diff --git a/apps/builder/app/shared/asset-content-bridge.client.test.ts b/apps/builder/app/shared/asset-content-bridge.client.test.tsnew file mode 100644index 0000000000..b738c430b7--- /dev/null+++ b/apps/builder/app/shared/asset-content-bridge.client.test.ts@@ -0,0 +1,118 @@+import { expect, test, vi } from "vitest";+import { contentEngineLimits } from "@webstudio-is/content-engine/limits";+import { createAssetContentBridge } from "./asset-content-bridge.client";++const origin = "https://builder.example";+const contentUrl = `${origin}/rest/assets/asset-1/content?projectId=project-1`;++const createBridge = ({+ authorized = true,+}: {+ authorized?: boolean;+} = {}) => {+ const request = vi.fn(async () => new Response("ok"));+ const authorize = vi.fn(() => authorized);+ const requireReload = vi.fn();+ return {+ bridge: createAssetContentBridge({+ origin,+ request,+ authorize,+ requireReload,+ }),+ request,+ authorize,+ requireReload,+ };+};++test("delegates stale revision handling to the bridge owner", () => {+ const { bridge, requireReload } = createBridge();++ bridge.requireReload("The file changed.");++ expect(requireReload).toHaveBeenCalledWith("The file changed.");+});++test("forwards only an authorized Asset content request", async () => {+ const { bridge, request, authorize } = createBridge();++ await expect(bridge.request(contentUrl)).resolves.toBeInstanceOf(Response);++ expect(authorize).toHaveBeenCalledWith({+ projectId: "project-1",+ assetId: "asset-1",+ operation: "read",+ });+ expect(request).toHaveBeenCalledTimes(1);+});++test("forwards a bounded authorized write", async () => {+ const { bridge, request, authorize } = createBridge();++ await expect(+ bridge.request(`${contentUrl}&expectedName=article.mdx`, {+ method: "PUT",+ headers: { "content-type": "application/octet-stream" },+ body: new TextEncoder().encode("# Updated"),+ })+ ).resolves.toBeInstanceOf(Response);++ expect(authorize).toHaveBeenCalledWith({+ projectId: "project-1",+ assetId: "asset-1",+ operation: "write",+ });+ expect(request).toHaveBeenCalledTimes(1);+});++const rejectedRequests: ReadonlyArray<{+ name: string;+ url: string;+ init?: RequestInit;+}> = [+ {+ name: "another origin",+ url: "https://attacker.example/rest/assets/asset-1/content?projectId=project-1",+ },+ {+ name: "another route",+ url: `${origin}/rest/assets/asset-1?projectId=project-1`,+ },+ {+ name: "an unsupported method",+ url: contentUrl,+ init: { method: "DELETE" },+ },+ {+ name: "an unknown query",+ url: `${contentUrl}&redirect=https://attacker.example`,+ },+];++test.each(rejectedRequests)("rejects $name", async ({ url, init }) => {+ const { bridge, request } = createBridge();++ await expect(bridge.request(url, init)).rejects.toThrow();+ expect(request).not.toHaveBeenCalled();+});++test("enforces project and Asset authorization inside the request path", async () => {+ const { bridge, request } = createBridge({ authorized: false });++ await expect(bridge.request(contentUrl)).rejects.toThrow("not authorized");+ expect(request).not.toHaveBeenCalled();+});++test("bounds Asset content writes before forwarding them", async () => {+ const { bridge, request } = createBridge();++ await expect(+ bridge.request(`${contentUrl}&expectedName=article.mdx`, {+ method: "PUT",+ headers: { "content-type": "application/octet-stream" },+ body: new Uint8Array(contentEngineLimits.hydratedFileBytes + 1),+ })+ ).rejects.toThrow("exceeds");+ expect(request).not.toHaveBeenCalled();+});diff --git a/apps/builder/app/shared/asset-content-bridge.client.ts b/apps/builder/app/shared/asset-content-bridge.client.tsnew file mode 100644index 0000000000..2d41c69d23--- /dev/null+++ b/apps/builder/app/shared/asset-content-bridge.client.ts@@ -0,0 +1,133 @@+import { contentEngineLimits } from "@webstudio-is/content-engine/limits";+import type { AssetContentSession } from "@webstudio-is/content-engine/asset-content-session";++type AssetContentAuthorization = Readonly<{+ projectId: string;+ assetId: string;+ operation: "read" | "write";+}>;++export type AssetContentBridge = Readonly<{+ request: (input: string, init?: RequestInit) => Promise<Response>;+ authorize: (input: AssetContentAuthorization) => boolean;+ requireReload: (error: string) => void;+ getContentSession?: (projectId: string) => AssetContentSession;+}>;++const namespace = "__webstudio__$__assetContentBridge";++export const createAssetContentBridge = ({+ origin,+ request,+ authorize,+ requireReload,+ getContentSession,+}: {+ origin: string;+ request: (input: string, init?: RequestInit) => Promise<Response>;+ authorize: (input: AssetContentAuthorization) => boolean;+ requireReload: (error: string) => void;+ getContentSession?: (projectId: string) => AssetContentSession;+}): AssetContentBridge => ({+ authorize,+ requireReload,+ getContentSession,+ request: async (input, init) => {+ const url = new URL(input, origin);+ const method = init?.method?.toUpperCase() ?? "GET";+ const [, rest, assets, encodedAssetId, content, ...extraPath] =+ url.pathname.split("/");+ if (+ url.origin !== origin ||+ rest !== "rest" ||+ assets !== "assets" ||+ encodedAssetId === undefined ||+ encodedAssetId === "" ||+ content !== "content" ||+ extraPath.length !== 0 ||+ (method !== "GET" && method !== "PUT")+ ) {+ throw new Error("Only same-origin Asset content requests are allowed");+ }+ let assetId: string;+ try {+ assetId = decodeURIComponent(encodedAssetId);+ } catch {+ throw new Error("Asset content request has an invalid Asset id");+ }+ const projectIds = url.searchParams.getAll("projectId");+ const expectedNames = url.searchParams.getAll("expectedName");+ const allowedQueryNames =+ method === "GET"+ ? new Set(["projectId"])+ : new Set(["projectId", "expectedName"]);+ if (+ projectIds.length !== 1 ||+ projectIds[0] === "" ||+ expectedNames.length !== (method === "PUT" ? 1 : 0) ||+ (method === "PUT" && expectedNames[0] === "") ||+ [...url.searchParams.keys()].some(+ (name) => allowedQueryNames.has(name) === false+ )+ ) {+ throw new Error("Asset content request has invalid parameters");+ }+ const operation = method === "PUT" ? "write" : "read";+ if (+ authorize({+ projectId: projectIds[0],+ assetId,+ operation,+ }) === false+ ) {+ throw new Error("Asset content request is not authorized");+ }+ if (method === "GET") {+ if (init?.body != null) {+ throw new Error("Asset content reads cannot include a body");+ }+ return await request(url.href, init);+ }+ const headers = new Headers(init?.headers);+ if (headers.get("content-type") !== "application/octet-stream") {+ throw new Error("Asset content writes require binary content");+ }+ const body = init?.body;+ const byteLength =+ typeof body === "string"+ ? new TextEncoder().encode(body).byteLength+ : body instanceof Blob+ ? body.size+ : body instanceof ArrayBuffer+ ? body.byteLength+ : ArrayBuffer.isView(body)+ ? body.byteLength+ : undefined;+ if (byteLength === undefined) {+ throw new Error("Asset content writes require a bounded body");+ }+ if (byteLength > contentEngineLimits.hydratedFileBytes) {+ throw new Error("Asset content write exceeds the MDX editing limit");+ }+ return await request(url.href, init);+ },+});++declare global {+ interface Window {+ [namespace]?: AssetContentBridge;+ }+}++export const initAssetContentBridge = (bridge: AssetContentBridge) => {+ window[namespace] = bridge;+};++export const getAssetContentBridge = () => {+ const owner = window.self === window.top ? window : window.top;+ const bridge = owner?.[namespace];+ if (bridge === undefined) {+ throw new Error("Builder Asset content bridge is not available");+ }+ return bridge;+};diff --git a/apps/builder/app/shared/builder-api.test.ts b/apps/builder/app/shared/builder-api.test.tsnew file mode 100644index 0000000000..ef5ae1594a--- /dev/null+++ b/apps/builder/app/shared/builder-api.test.ts@@ -0,0 +1,48 @@+import { expect, test } from "vitest";+import type { Asset } from "@webstudio-is/sdk";+import { __testing__ } from "./builder-api";++const file = (format: string) =>+ ({ type: "file", format }) satisfies Pick<Asset, "type" | "format">;++test("allows graph documents to be read but only MDX roots to be written", () => {+ for (const format of ["md", "mdx", "json"]) {+ expect(+ __testing__.canAccessAssetContent({+ asset: file(format),+ operation: "read",+ canWrite: false,+ })+ ).toBe(true);+ }+ expect(+ __testing__.canAccessAssetContent({+ asset: file("png"),+ operation: "read",+ canWrite: true,+ })+ ).toBe(false);+ expect(+ __testing__.canAccessAssetContent({+ asset: file("mdx"),+ operation: "write",+ canWrite: true,+ })+ ).toBe(true);+ for (const format of ["md", "json"]) {+ expect(+ __testing__.canAccessAssetContent({+ asset: file(format),+ operation: "write",+ canWrite: true,+ })+ ).toBe(false);+ }+ expect(+ __testing__.canAccessAssetContent({+ asset: file("mdx"),+ operation: "write",+ canWrite: false,+ })+ ).toBe(false);+});diff --git a/apps/builder/app/shared/builder-api.ts b/apps/builder/app/shared/builder-api.tsindex 5486c529e6..f96c6d1c32 100644--- a/apps/builder/app/shared/builder-api.ts+++ b/apps/builder/app/shared/builder-api.ts@@ -8,9 +8,43 @@ import {import { showTokenConflictDialog } from "./token-conflict-dialog";import { showRootStyleConflictDialog } from "./root-style-conflict-dialog";import { showDesignTokenImportDialog } from "./design-token-import-dialog";+import { fetch as builderFetch } from "./fetch.client";+import { $assets, $project } from "./sync/data-stores";+import { $authPermit } from "./nano-states";+import {+ createAssetContentBridge,+ initAssetContentBridge,+} from "./asset-content-bridge.client";+import { requireBuilderReload } from "./sync/reload-required";+import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session";+import { createHttpAssetContentRepository } from "~/builder/shared/assets/mdx-content-repository";+import { $authToken } from "./nano-states";+import { isMdxFileAsset, type Asset } from "@webstudio-is/sdk";+import { createTransactionFromBuilderPatchPayload } from "./sync/builder-patch";+import { getWebstudioData } from "./instance-utils/data";+import { invalidateAssets } from "./resources";+import { onNextTransactionComplete } from "./sync/project-queue";+import { disposeExternalContentProject } from "./external-content-roots";const apiWindowNamespace = "__webstudio__$__builderApi";+const isContentDocumentAsset = (asset: Pick<Asset, "type" | "format">) =>+ asset.type === "file" &&+ ["md", "mdx", "json"].includes(asset.format.toLowerCase());++const canAccessAssetContent = ({+ asset,+ operation,+ canWrite,+}: {+ asset: Pick<Asset, "type" | "format">;+ operation: "read" | "write";+ canWrite: boolean;+}) =>+ operation === "read"+ ? isContentDocumentAsset(asset)+ : canWrite && isMdxFileAsset(asset);+type ToastHandler = (message: string) => void;const isSafeMode = (() => {@@ -20,6 +54,28 @@ const isSafeMode = (() => {return new URLSearchParams(window.location.search).get("safemode") === "true";})();+const authorizeAssetContent = ({+ projectId,+ assetId,+ operation,+}: {+ projectId: string;+ assetId: string;+ operation: "read" | "write";+}) => {+ const asset = $assets.get().get(assetId);+ return (+ $project.get()?.id === projectId &&+ asset?.projectId === projectId &&+ asset !== undefined &&+ canAccessAssetContent({+ asset,+ operation,+ canWrite: $authPermit.get() !== "view",+ })+ );+};+const _builderApi = {isInitialized: () => true,isSafeMode: () => isSafeMode,@@ -121,6 +177,197 @@ export const builderApi = createRecursiveProxy((options) => {export const initBuilderApi = () => {if (isInTop()) {window[apiWindowNamespace] = _builderApi;+ type ContentSessionEntry = {+ projectId: string;+ session: ReturnType<typeof createAssetContentSession>;+ active: boolean;+ retiring?: Promise<void>;+ };+ const contentSessions = new Map<string, ContentSessionEntry>();+ let activeContentSession: ContentSessionEntry | undefined;+ const retireContentSession = (contentSession: ContentSessionEntry) => {+ contentSession.active = false;+ if (activeContentSession === contentSession) {+ activeContentSession = undefined;+ }+ if (contentSession.retiring !== undefined) {+ return;+ }+ const retiring = disposeExternalContentProject({+ projectId: contentSession.projectId,+ session: contentSession.session,+ shouldCleanup: () => contentSession.active === false,+ })+ .then((cleanedUp) => {+ if (cleanedUp === false || contentSession.active) {+ return;+ }+ if (+ contentSessions.get(contentSession.projectId) === contentSession+ ) {+ contentSessions.delete(contentSession.projectId);+ }+ contentSession.session.dispose();+ })+ .catch(() => {+ toast.error(+ "Some MDX changes could not be saved. Return to this project to retry."+ );+ })+ .finally(() => {+ if (contentSession.retiring === retiring) {+ contentSession.retiring = undefined;+ }+ });+ contentSession.retiring = retiring;+ };+ const unlistenProject = $project.listen((project) => {+ if (+ activeContentSession !== undefined &&+ activeContentSession.projectId !== project?.id+ ) {+ retireContentSession(activeContentSession);+ }+ });+ initAssetContentBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: (input, init) => builderFetch(input, init),+ authorize: authorizeAssetContent,+ requireReload: (error) => requireBuilderReload({ error }),+ getContentSession: (projectId) => {+ if ($project.get()?.id !== projectId) {+ throw new Error("Asset content session belongs to another project");+ }+ const existing = contentSessions.get(projectId);+ if (existing !== undefined) {+ existing.active = true;+ activeContentSession = existing;+ return existing.session;+ }+ if (activeContentSession !== undefined) {+ retireContentSession(activeContentSession);+ }+ let sessionAuthToken = $authToken.get();+ let canWrite = $authPermit.get() !== "view";+ const authorizedReadAssetIds = new Set(+ Array.from($assets.get().values())+ .filter(+ (asset) =>+ asset.projectId === projectId &&+ canAccessAssetContent({+ asset,+ operation: "read",+ canWrite: true,+ })+ )+ .map((asset) => asset.id)+ );+ const authorizedWriteAssetIds = new Set(+ Array.from($assets.get().values())+ .filter(+ (asset) =>+ asset.projectId === projectId &&+ canAccessAssetContent({+ asset,+ operation: "write",+ canWrite: true,+ })+ )+ .map((asset) => asset.id)+ );+ const session = createAssetContentSession({+ repository: createHttpAssetContentRepository({+ projectId,+ origin: window.location.origin,+ authToken: () => {+ if ($project.get()?.id === projectId) {+ sessionAuthToken = $authToken.get();+ }+ return sessionAuthToken;+ },+ request: (input, init) => builderFetch(input, init),+ }),+ authorize: ({ assetId, operation }) => {+ if ($project.get()?.id === projectId) {+ canWrite = $authPermit.get() !== "view";+ const asset = $assets.get().get(assetId);+ if (+ asset?.projectId === projectId &&+ canAccessAssetContent({+ asset,+ operation: "read",+ canWrite: true,+ })+ ) {+ authorizedReadAssetIds.add(assetId);+ }+ if (+ asset?.projectId === projectId &&+ canAccessAssetContent({+ asset,+ operation: "write",+ canWrite: true,+ })+ ) {+ authorizedWriteAssetIds.add(assetId);+ }+ }+ return (+ (operation === "read"+ ? authorizedReadAssetIds+ : authorizedWriteAssetIds+ ).has(assetId) &&+ (operation === "read" || canWrite)+ );+ },+ });+ session.subscribe((_assetId, state) => {+ if (state.status !== "saved" || $project.get()?.id !== projectId) {+ return;+ }+ const current = $assets.get().get(state.asset.id);+ if (current === undefined) {+ return;+ }+ if (+ current.name === state.asset.name &&+ current.size === state.asset.size &&+ current.updatedAt === state.asset.updatedAt+ ) {+ return;+ }+ createTransactionFromBuilderPatchPayload({+ data: getWebstudioData(),+ payload: [+ {+ namespace: "assets",+ patches: [+ {+ op: "replace",+ path: [current.id],+ value: { ...current, ...state.asset },+ },+ ],+ },+ ],+ });+ onNextTransactionComplete(invalidateAssets);+ });+ activeContentSession = { projectId, session, active: true };+ contentSessions.set(projectId, activeContentSession);+ return session;+ },+ })+ );+ return () => {+ unlistenProject();+ for (const contentSession of contentSessions.values()) {+ retireContentSession(contentSession);+ }+ };}return () => {};};++export const __testing__ = { canAccessAssetContent };diff --git a/apps/builder/app/shared/code-editor-base.tsx b/apps/builder/app/shared/code-editor-base.tsxindex 0235d1f3b6..2e4b5dbf05 100644--- a/apps/builder/app/shared/code-editor-base.tsx+++ b/apps/builder/app/shared/code-editor-base.tsx@@ -236,6 +236,28 @@ export const foldGutterExtension = foldGutter({},});+export const linterTooltipTheme = EditorView.theme({+ ".cm-tooltip:has(.cm-tooltip-lint)": {+ backgroundColor: "transparent",+ borderWidth: 0,+ paddingTop: rawTheme.spacing[5],+ paddingBottom: rawTheme.spacing[5],+ pointerEvents: "none",+ },+ ".cm-tooltip-lint": {+ backgroundColor: rawTheme.colors.backgroundTooltipMain,+ color: rawTheme.colors.foregroundContrastMain,+ borderRadius: rawTheme.borderRadius[7],+ padding: rawTheme.spacing[5],+ },+ ".cm-tooltip-lint .cm-diagnostic": {+ borderWidth: 0,+ padding: 0,+ margin: 0,+ ...textVariants.regular,+ },+});+export type EditorApi = {replaceSelection: (string: string) => void;insertTemplate: (template: {diff --git a/apps/builder/app/shared/code-editor.tsx b/apps/builder/app/shared/code-editor.tsxindex 2f7aa06382..4be866f945 100644--- a/apps/builder/app/shared/code-editor.tsx+++ b/apps/builder/app/shared/code-editor.tsx@@ -38,6 +38,7 @@ import {EditorDialogControl,foldGutterExtension,getCodeEditorCssVars,+ linterTooltipTheme,} from "~/shared/code-editor-base";const wrapperStyle = css({@@ -216,6 +217,7 @@ export const CodeEditor = forwardRef<...builtInExtensions,...dynamicLanguageExtensions,...languageExtensions,+ linterTooltipTheme,],[builtInExtensions, dynamicLanguageExtensions, languageExtensions]);diff --git a/apps/builder/app/shared/content-block-diagnostics.test.ts b/apps/builder/app/shared/content-block-diagnostics.test.tsnew file mode 100644index 0000000000..a73522d200--- /dev/null+++ b/apps/builder/app/shared/content-block-diagnostics.test.ts@@ -0,0 +1,39 @@+import { expect, test } from "vitest";+import type { ContentBlockDiagnostic } from "@webstudio-is/sdk";+import {+ deduplicateContentBlockDiagnostics,+ formatContentBlockDiagnostic,+ takeNewContentBlockDiagnostics,+} from "./content-block-diagnostics";++const diagnostic: ContentBlockDiagnostic = {+ code: "ignored-template-prop",+ severity: "warning",+ blockInstanceId: "block",+ assetId: "article",+ contentRef: "article.mdx",+ renderScope: "scope",+ templateName: "Hero",+ propName: "tone",+ reason: "design-only",+ sourceRange: {+ start: { line: 2, column: 3 },+ end: { line: 2, column: 12 },+ },+};++test("formats and deduplicates diagnostics by revision without losing detail", () => {+ expect(formatContentBlockDiagnostic(diagnostic)).toBe(+ 'Property "tone" on template "Hero" was ignored because it is design only. Line 2, column 3.'+ );+ expect(deduplicateContentBlockDiagnostics([diagnostic, diagnostic])).toEqual([+ diagnostic,+ ]);+ expect(takeNewContentBlockDiagnostics([diagnostic], "one")).toEqual([+ diagnostic,+ ]);+ expect(takeNewContentBlockDiagnostics([diagnostic], "one")).toEqual([]);+ expect(takeNewContentBlockDiagnostics([diagnostic], "two")).toEqual([+ diagnostic,+ ]);+});diff --git a/apps/builder/app/shared/content-block-diagnostics.ts b/apps/builder/app/shared/content-block-diagnostics.tsnew file mode 100644index 0000000000..bbea4f1697--- /dev/null+++ b/apps/builder/app/shared/content-block-diagnostics.ts@@ -0,0 +1,65 @@+import type { ContentBlockDiagnostic } from "@webstudio-is/sdk";++const formatSourceLocation = (diagnostic: ContentBlockDiagnostic) => {+ const point = diagnostic.sourceRange?.start;+ return point === undefined+ ? ""+ : ` Line ${point.line}, column ${point.column}.`;+};++export const formatContentBlockDiagnostic = (+ diagnostic: ContentBlockDiagnostic+) => {+ let message = "Invalid MDX content.";+ if (diagnostic.code === "invalid-mdx") {+ message = diagnostic.message;+ } else if (diagnostic.code === "unsafe-mdx") {+ message = diagnostic.reason;+ } else if (diagnostic.code === "unresolved-template") {+ message = `Template "${diagnostic.templateName}" is not available and was skipped.`;+ } else if (diagnostic.code === "ignored-template-prop") {+ message = `Property "${diagnostic.propName}" on template "${+ diagnostic.templateName+ }" was ignored because it is ${diagnostic.reason.replace("-", " ")}.`;+ }+ return `${message}${formatSourceLocation(diagnostic)}`;+};++export const deduplicateContentBlockDiagnostics = (+ diagnostics: readonly ContentBlockDiagnostic[]+) => {+ const keys = new Set<string>();+ return diagnostics.filter((diagnostic) => {+ const key = JSON.stringify(diagnostic);+ if (keys.has(key)) {+ return false;+ }+ keys.add(key);+ return true;+ });+};++const notifiedDiagnosticKeys = new Set<string>();+const maxNotifiedDiagnosticKeys = 1000;++export const takeNewContentBlockDiagnostics = (+ diagnostics: readonly ContentBlockDiagnostic[],+ revision?: string+) => {+ const fresh: ContentBlockDiagnostic[] = [];+ for (const diagnostic of deduplicateContentBlockDiagnostics(diagnostics)) {+ const key = JSON.stringify([revision, diagnostic]);+ if (notifiedDiagnosticKeys.has(key)) {+ continue;+ }+ notifiedDiagnosticKeys.add(key);+ if (notifiedDiagnosticKeys.size > maxNotifiedDiagnosticKeys) {+ const oldestKey = notifiedDiagnosticKeys.values().next().value;+ if (oldestKey !== undefined) {+ notifiedDiagnosticKeys.delete(oldestKey);+ }+ }+ fresh.push(diagnostic);+ }+ return fresh;+};diff --git a/apps/builder/app/shared/content-block-document.test.ts b/apps/builder/app/shared/content-block-document.test.tsnew file mode 100644index 0000000000..d86c11b823--- /dev/null+++ b/apps/builder/app/shared/content-block-document.test.ts@@ -0,0 +1,411 @@+import { describe, expect, test } from "vitest";+import {+ getSelectedContentBlockDocumentBindingPath,+ getSelectedContentBlockExpressionMode,+ isObjectPathWritable,+ setObjectPathValue,+} from "./content-block-document";+import {+ blockComponent,+ blockTemplateComponent,+ contentBlockDocumentProp,+ encodeDataSourceVariable,+ type Instance,+ type Prop,+} from "@webstudio-is/sdk";++describe("Content Block document bindings", () => {+ test("uses the selected external root instead of an enclosing Content Block", () => {+ const instances = new Map<string, Instance>([+ [+ "inner",+ {+ type: "instance",+ id: "inner",+ component: blockComponent,+ children: [],+ },+ ],+ [+ "outer",+ {+ type: "instance",+ id: "outer",+ component: blockComponent,+ children: [],+ },+ ],+ ]);+ const props = new Map<string, Prop>([+ [+ "outer-source",+ {+ id: "outer-source",+ instanceId: "outer",+ name: "src",+ type: "asset",+ value: "outer-article",+ },+ ],+ [+ "inner-source",+ {+ id: "inner-source",+ instanceId: "inner",+ name: "src",+ type: "asset",+ value: "inner-article",+ },+ ],+ [+ "outer-document",+ {+ id: "outer-document",+ instanceId: "outer",+ name: contentBlockDocumentProp,+ type: "parameter",+ value: "outerDocument",+ },+ ],+ [+ "inner-document",+ {+ id: "inner-document",+ instanceId: "inner",+ name: contentBlockDocumentProp,+ type: "parameter",+ value: "innerDocument",+ },+ ],+ ]);++ expect(+ getSelectedContentBlockDocumentBindingPath({+ binding: {+ type: "expression",+ value: `${encodeDataSourceVariable("innerDocument")}.frontmatter.title`,+ mode: "readwrite",+ },+ instanceSelector: ["heading", "outer"],+ instances,+ props,+ sourceBlockInstanceId: "inner",+ renderedBlockInstanceId: "outer",+ })+ ).toEqual(["title"]);+ });++ test("does not infer write access from a direct expression alone", () => {+ expect(+ getSelectedContentBlockDocumentBindingPath({+ binding: {+ type: "expression",+ value: `${encodeDataSourceVariable("innerDocument")}.frontmatter.title`,+ },+ instanceSelector: ["heading", "inner"],+ instances: new Map([+ [+ "inner",+ {+ type: "instance",+ id: "inner",+ component: blockComponent,+ children: [],+ },+ ],+ ]),+ props: new Map<string, Prop>([+ [+ "inner-source",+ {+ id: "inner-source",+ instanceId: "inner",+ name: "src",+ type: "asset",+ value: "article",+ },+ ],+ [+ "inner-document",+ {+ id: "inner-document",+ instanceId: "inner",+ name: contentBlockDocumentProp,+ type: "parameter",+ value: "innerDocument",+ },+ ],+ ]),+ })+ ).toBeUndefined();+ });++ test("does not expose a writable document target after disconnect", () => {+ expect(+ getSelectedContentBlockDocumentBindingPath({+ binding: {+ type: "expression",+ value: `${encodeDataSourceVariable("document")}.frontmatter.title`,+ mode: "readwrite",+ },+ instanceSelector: ["heading", "block"],+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [],+ },+ ],+ ]),+ props: new Map([+ [+ "document",+ {+ id: "document",+ instanceId: "block",+ name: contentBlockDocumentProp,+ type: "parameter",+ value: "document",+ },+ ],+ ]),+ })+ ).toBeUndefined();+ });++ test("classifies only connected direct document paths as readwrite", () => {+ const document = encodeDataSourceVariable("document");+ const block: Instance = {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [],+ };+ const instances = new Map([[block.id, block]]);+ const props = new Map<string, Prop>([+ [+ "source",+ {+ id: "source",+ instanceId: block.id,+ name: "src",+ type: "asset",+ value: "article",+ },+ ],+ [+ "document",+ {+ id: "document",+ instanceId: block.id,+ name: contentBlockDocumentProp,+ type: "parameter",+ value: "document",+ },+ ],+ ]);+ const context = {+ instanceSelector: ["heading", block.id],+ instances,+ props,+ };++ expect(+ getSelectedContentBlockExpressionMode({+ ...context,+ expression: `${document}.frontmatter.title`,+ })+ ).toBe("readwrite");+ expect(+ getSelectedContentBlockExpressionMode({+ ...context,+ expression: `${document}.frontmatter.title + "!"`,+ })+ ).toBe("read");+ });++ test("keeps bindings inside Templates read-only", () => {+ const document = encodeDataSourceVariable("document");+ const instances = new Map<string, Instance>([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "templates" }],+ },+ ],+ [+ "templates",+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [{ type: "id", value: "heading" }],+ },+ ],+ ]);+ const props = new Map<string, Prop>([+ [+ "source",+ {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "article",+ },+ ],+ [+ "document",+ {+ id: "document",+ instanceId: "block",+ name: contentBlockDocumentProp,+ type: "parameter",+ value: "document",+ },+ ],+ ]);++ expect(+ getSelectedContentBlockExpressionMode({+ expression: `${document}.frontmatter.title`,+ instanceSelector: ["heading", "templates", "block"],+ instances,+ props,+ })+ ).toBe("read");+ });++ test("does not write an outer document through a nested Content Block", () => {+ const outerDocument = encodeDataSourceVariable("outerDocument");+ const instances = new Map<string, Instance>([+ [+ "inner",+ {+ type: "instance",+ id: "inner",+ component: blockComponent,+ children: [{ type: "id", value: "heading" }],+ },+ ],+ [+ "outer",+ {+ type: "instance",+ id: "outer",+ component: blockComponent,+ children: [{ type: "id", value: "inner" }],+ },+ ],+ ]);+ const props = new Map<string, Prop>([+ [+ "outer-source",+ {+ id: "outer-source",+ instanceId: "outer",+ name: "src",+ type: "asset",+ value: "outer-article",+ },+ ],+ [+ "outer-document",+ {+ id: "outer-document",+ instanceId: "outer",+ name: contentBlockDocumentProp,+ type: "parameter",+ value: "outerDocument",+ },+ ],+ ]);++ expect(+ getSelectedContentBlockExpressionMode({+ expression: `${outerDocument}.frontmatter.title`,+ instanceSelector: ["heading", "inner", "outer"],+ instances,+ props,+ sourceBlockInstanceId: "outer",+ renderedBlockInstanceId: "outer",+ })+ ).toBe("read");+ });++ test("does not write through a referenced frontmatter value", () => {+ expect(+ isObjectPathWritable({+ value: { author: { $ref: "./author.mdx#frontmatter" } },+ path: ["author", "name"],+ })+ ).toBe(false);+ expect(+ isObjectPathWritable({+ value: { featureImage: { $ref: "./hero.png" } },+ path: ["featureImage"],+ })+ ).toBe(true);+ });++ test("updates a nested property without mutating its source", () => {+ const source = { author: { name: "Before", role: "Writer" } };+ expect(+ setObjectPathValue({+ value: source,+ path: ["author", "name"],+ nextValue: "After",+ })+ ).toEqual({ author: { name: "After", role: "Writer" } });+ expect(source.author.name).toBe("Before");+ });++ test("does not replace an existing scalar while traversing a nested path", () => {+ const source = { author: "Oleg" };++ expect(+ isObjectPathWritable({ value: source, path: ["author", "name"] })+ ).toBe(false);+ expect(() =>+ setObjectPathValue({+ value: source,+ path: ["author", "name"],+ nextValue: "Ada",+ })+ ).toThrow("Frontmatter object path is invalid");+ expect(source).toEqual({ author: "Oleg" });+ });++ test("updates an array item without changing the array shape", () => {+ const source = { authors: [{ name: "Before" }, { name: "Other" }] };+ const path = ["authors", "0", "name"];++ expect(isObjectPathWritable({ value: source, path })).toBe(true);+ expect(+ setObjectPathValue({ value: source, path, nextValue: "After" })+ ).toEqual({ authors: [{ name: "After" }, { name: "Other" }] });+ expect(source.authors[0].name).toBe("Before");+ });++ test("rejects invalid array indexes and unsafe object paths", () => {+ expect(+ isObjectPathWritable({ value: { authors: [] }, path: ["authors", "0"] })+ ).toBe(false);+ expect(+ isObjectPathWritable({ value: {}, path: ["__proto__", "polluted"] })+ ).toBe(false);+ expect(() =>+ setObjectPathValue({+ value: {},+ path: ["__proto__", "polluted"],+ nextValue: true,+ })+ ).toThrow("Frontmatter object path is invalid");+ });+});diff --git a/apps/builder/app/shared/content-block-document.ts b/apps/builder/app/shared/content-block-document.tsnew file mode 100644index 0000000000..9aa26029ac--- /dev/null+++ b/apps/builder/app/shared/content-block-document.ts@@ -0,0 +1,198 @@+import {+ blockComponent,+ blockTemplateComponent,+ contentBlockDocumentProp,+ getWritableContentBlockDocumentBinding,+ getContentBlockSource,+ isSafeContentBlockDocumentPath,+ type ExpressionBinding,+ type ExpressionBindingMode,+ type Instance,+ type Instances,+ type Props,+} from "@webstudio-is/sdk";+import type { InstanceSelector } from "@webstudio-is/project-build/runtime";++export const getSelectedContentBlockDocumentBindingPath = ({+ binding,+ instanceSelector,+ instances,+ props,+ sourceBlockInstanceId,+ renderedBlockInstanceId,+}: {+ binding: ExpressionBinding;+ instanceSelector: InstanceSelector;+ instances: Pick<Instances, "get">;+ props: Props;+ sourceBlockInstanceId?: Instance["id"];+ renderedBlockInstanceId?: Instance["id"];+}) => {+ if (+ instanceSelector.some(+ (instanceId) =>+ instances.get(instanceId)?.component === blockTemplateComponent+ )+ ) {+ return;+ }+ const selectedBlockInstanceId = instanceSelector.find(+ (instanceId) => instances.get(instanceId)?.component === blockComponent+ );+ const owningBlockInstanceIds = [+ sourceBlockInstanceId,+ renderedBlockInstanceId,+ ].filter((instanceId) => instanceId !== undefined);+ if (+ selectedBlockInstanceId !== undefined &&+ owningBlockInstanceIds.length > 0 &&+ owningBlockInstanceIds.includes(selectedBlockInstanceId) === false+ ) {+ return;+ }+ const blockInstanceIds =+ owningBlockInstanceIds.length > 0+ ? owningBlockInstanceIds+ : selectedBlockInstanceId === undefined+ ? []+ : [selectedBlockInstanceId];+ const allProps = Array.from(props.values());+ for (const [index, blockInstanceId] of blockInstanceIds.entries()) {+ if (blockInstanceIds.indexOf(blockInstanceId) !== index) {+ continue;+ }+ const blockProps = allProps.filter(+ (prop) => prop.instanceId === blockInstanceId+ );+ if (+ getContentBlockSource({+ blockInstanceId,+ props: blockProps,+ }) === undefined+ ) {+ continue;+ }+ const documentProp = blockProps.find(+ (prop) =>+ prop.name === contentBlockDocumentProp && prop.type === "parameter"+ );+ if (documentProp?.type !== "parameter") {+ continue;+ }+ const target = getWritableContentBlockDocumentBinding({+ binding,+ documentDataSourceId: documentProp.value,+ });+ if (target !== undefined) {+ return target.frontmatterPath;+ }+ }+};++export const getSelectedContentBlockExpressionMode = ({+ expression,+ ...context+}: Omit<+ Parameters<typeof getSelectedContentBlockDocumentBindingPath>[0],+ "binding"+> & { expression: string }): ExpressionBindingMode =>+ getSelectedContentBlockDocumentBindingPath({+ ...context,+ binding: { type: "expression", value: expression, mode: "readwrite" },+ }) === undefined+ ? "read"+ : "readwrite";++export const setObjectPathValue = ({+ value,+ path,+ nextValue,+}: {+ value: Readonly<Record<string, unknown>>;+ path: readonly string[];+ nextValue: unknown;+}) => {+ if (path.length === 0) {+ return value;+ }+ if (isSafeContentBlockDocumentPath(path) === false) {+ throw new Error("Frontmatter object path is invalid");+ }+ const update = (current: unknown, index: number): unknown => {+ const segment = path[index];+ const isLast = index === path.length - 1;+ if (Array.isArray(current)) {+ const arrayIndex = getArrayIndex(segment);+ if (arrayIndex === undefined || arrayIndex >= current.length) {+ throw new Error("Frontmatter array path is invalid");+ }+ const result = [...current];+ result[arrayIndex] = isLast+ ? nextValue+ : update(current[arrayIndex], index + 1);+ return result;+ }+ if (+ current !== undefined &&+ (typeof current !== "object" || current === null)+ ) {+ throw new Error("Frontmatter object path is invalid");+ }+ const record =+ current === undefined+ ? {}+ : (current as Readonly<Record<string, unknown>>);+ const result = { ...record };+ result[segment] = isLast ? nextValue : update(record[segment], index + 1);+ return result;+ };+ return update(value, 0) as Readonly<Record<string, unknown>>;+};++const getArrayIndex = (segment: string) => {+ const index = Number(segment);+ return Number.isSafeInteger(index) && index >= 0 && String(index) === segment+ ? index+ : undefined;+};++export const isObjectPathWritable = ({+ value,+ path,+}: {+ value: Readonly<Record<string, unknown>>;+ path: readonly string[];+}) => {+ if (isSafeContentBlockDocumentPath(path) === false) {+ return false;+ }+ let current: unknown = value;+ for (const [index, segment] of path.entries()) {+ const isLast = index === path.length - 1;+ if (Array.isArray(current)) {+ const arrayIndex = getArrayIndex(segment);+ if (arrayIndex === undefined || arrayIndex >= current.length) {+ return false;+ }+ if (isLast) {+ return true;+ }+ current = current[arrayIndex];+ continue;+ }+ if (current === undefined) {+ return true;+ }+ if (typeof current !== "object" || current === null) {+ return false;+ }+ if ("$ref" in current) {+ return false;+ }+ if (isLast) {+ return true;+ }+ current = (current as Record<string, unknown>)[segment];+ }+ return true;+};diff --git a/apps/builder/app/shared/content-block-source-utils.test.ts b/apps/builder/app/shared/content-block-source-utils.test.tsnew file mode 100644index 0000000000..f2fd3e61b8--- /dev/null+++ b/apps/builder/app/shared/content-block-source-utils.test.ts@@ -0,0 +1,86 @@+import { describe, expect, test } from "vitest";+import { ROOT_INSTANCE_ID, type Instances } from "@webstudio-is/sdk";+import {+ getContentBlockOccurrenceVariableValues,+ isRepeatedContentBlockOccurrence,+ parseContentBlockRenderScope,+ resolveContentBlockOccurrenceAssetId,+} from "./content-block-source-utils";++const selector = ["block", "collection[item]", "collection", "body"];++describe("Content Block occurrence source", () => {+ test("parses only instance selectors", () => {+ expect(parseContentBlockRenderScope(JSON.stringify(selector))).toEqual(+ selector+ );+ expect(parseContentBlockRenderScope("{}")).toBeUndefined();+ expect(parseContentBlockRenderScope('["block",1]')).toBeUndefined();+ });++ test("resolves the same direct and root-qualified variable scopes", () => {+ const values = new Map([["asset", "article"]]);+ const direct = new Map([[JSON.stringify(selector), values]]);+ const rootQualified = new Map([+ [JSON.stringify([...selector, ROOT_INSTANCE_ID]), values],+ ]);+ expect(+ getContentBlockOccurrenceVariableValues({+ instanceSelector: selector,+ variableValuesByRenderScope: direct,+ })+ ).toBe(values);+ expect(+ resolveContentBlockOccurrenceAssetId({+ source: { type: "expression", value: "asset" },+ instanceSelector: selector,+ variableValuesByRenderScope: rootQualified,+ })+ ).toBe("article");+ });++ test("resolves each bound Collection occurrence independently", () => {+ const first = ["block", "collection[first]", "collection", "body"];+ const second = ["block", "collection[second]", "collection", "body"];+ const values = new Map([+ [JSON.stringify(first), new Map([["asset", "a.mdx"]])],+ [JSON.stringify(second), new Map([["asset", "b.mdx"]])],+ ]);++ expect(+ [first, second].map((instanceSelector) =>+ resolveContentBlockOccurrenceAssetId({+ source: { type: "expression", value: "asset" },+ instanceSelector,+ variableValuesByRenderScope: values,+ })+ )+ ).toEqual(["a.mdx", "b.mdx"]);+ });++ test("detects repeated selectors consistently", () => {+ const instances = new Map(+ ["block", "collection", "body"].map((id) => [+ id,+ {+ type: "instance" as const,+ id,+ component: "Box",+ children: [],+ },+ ])+ ) as Instances;+ expect(+ isRepeatedContentBlockOccurrence({+ instanceSelector: selector,+ instances,+ })+ ).toBe(true);+ expect(+ isRepeatedContentBlockOccurrence({+ instanceSelector: ["block", "collection", "body"],+ instances,+ })+ ).toBe(false);+ });+});diff --git a/apps/builder/app/shared/content-block-source-utils.ts b/apps/builder/app/shared/content-block-source-utils.tsnew file mode 100644index 0000000000..a853fb41cb--- /dev/null+++ b/apps/builder/app/shared/content-block-source-utils.ts@@ -0,0 +1,68 @@+import { resolveContentBlockSourceAssetId } from "@webstudio-is/project-build/runtime";+import {+ ROOT_INSTANCE_ID,+ type ContentBlockSource,+ type Instances,+} from "@webstudio-is/sdk";+import type { InstanceSelector } from "@webstudio-is/project-build/runtime";++type VariableValuesByRenderScope = ReadonlyMap<+ string,+ ReadonlyMap<string, unknown>+>;++export const parseContentBlockRenderScope = (renderScope: string) => {+ try {+ const value: unknown = JSON.parse(renderScope);+ if (+ Array.isArray(value) &&+ value.length > 0 &&+ value.every((instanceId) => typeof instanceId === "string")+ ) {+ return value as InstanceSelector;+ }+ } catch {+ return;+ }+};++export const getContentBlockOccurrenceVariableValues = ({+ instanceSelector,+ variableValuesByRenderScope,+}: {+ instanceSelector: InstanceSelector;+ variableValuesByRenderScope: VariableValuesByRenderScope;+}) =>+ variableValuesByRenderScope.get(JSON.stringify(instanceSelector)) ??+ variableValuesByRenderScope.get(+ JSON.stringify([...instanceSelector, ROOT_INSTANCE_ID])+ );++export const resolveContentBlockOccurrenceAssetId = ({+ source,+ instanceSelector,+ variableValuesByRenderScope,+}: {+ source: ContentBlockSource;+ instanceSelector: InstanceSelector;+ variableValuesByRenderScope: VariableValuesByRenderScope;+}) =>+ resolveContentBlockSourceAssetId({+ source,+ values: getContentBlockOccurrenceVariableValues({+ instanceSelector,+ variableValuesByRenderScope,+ }),+ });++export const isRepeatedContentBlockOccurrence = ({+ instanceSelector,+ instances,+}: {+ instanceSelector: InstanceSelector;+ instances: Instances;+}) =>+ instanceSelector.some(+ (instanceId) =>+ instanceId !== ROOT_INSTANCE_ID && instances.has(instanceId) === false+ );diff --git a/apps/builder/app/shared/copy-paste/asset-transfer-utils.test.ts b/apps/builder/app/shared/copy-paste/asset-transfer-utils.test.tsindex 7c7d41c132..dfd60c4e74 100644--- a/apps/builder/app/shared/copy-paste/asset-transfer-utils.test.ts+++ b/apps/builder/app/shared/copy-paste/asset-transfer-utils.test.ts@@ -114,6 +114,12 @@ test("imports and remaps every fragment asset reference", async () => {if (result.success === false) {return;}+ expect(result.assets).toEqual(+ new Map<Asset["id"], Asset>([+ [imageAsset.id, importedImage],+ [fontAsset.id, importedFont],+ ])+ );expect(result.fragments.get(fragment)).toEqual({...fragment,assets: [],diff --git a/apps/builder/app/shared/copy-paste/asset-transfer-utils.ts b/apps/builder/app/shared/copy-paste/asset-transfer-utils.tsindex 3fdacf631f..a54f118cb9 100644--- a/apps/builder/app/shared/copy-paste/asset-transfer-utils.ts+++ b/apps/builder/app/shared/copy-paste/asset-transfer-utils.ts@@ -26,6 +26,7 @@ export const transferFragmentAssets = async ({success: true,fragments: new Map(fragments.map((fragment) => [fragment, fragment])),assetIds: new Map<Asset["id"], Asset["id"]>(),+ assets: new Map<Asset["id"], Asset>(),} as const;}@@ -87,5 +88,6 @@ export const transferFragmentAssets = async ({success: true,fragments: transferredFragments,assetIds,+ assets: importedAssets,} as const;};diff --git a/apps/builder/app/shared/copy-paste/content-block-fragment.test.ts b/apps/builder/app/shared/copy-paste/content-block-fragment.test.tsnew file mode 100644index 0000000000..38a28322d7--- /dev/null+++ b/apps/builder/app/shared/copy-paste/content-block-fragment.test.ts@@ -0,0 +1,398 @@+import { expect, test, vi } from "vitest";+import {+ blockBodyComponent,+ blockComponent,+ blockTemplateComponent,+ type Asset,+ type AssetFolder,+} from "@webstudio-is/sdk";+import {+ includeMdxAssetDependencies,+ prepareConnectedContentBlockFragment,+ resolveRepeatedContentBlockSourcesForCopy,+} from "./content-block-fragment";++const createFile = ({+ id,+ name,+ format,+ folderId,+}: {+ id: string;+ name: string;+ format: string;+ folderId?: string;+}) =>+ ({+ id,+ projectId: "project",+ name,+ type: "file",+ format,+ folderId,+ size: 1,+ createdAt: "2026-01-01T00:00:00.000Z",+ description: null,+ meta: {},+ }) satisfies Asset;++const source = createFile({+ id: "article",+ name: "article.mdx",+ format: "mdx",+ folderId: "articles",+});+const dependency = createFile({+ id: "hero",+ name: "hero.png",+ format: "png",+ folderId: "media",+});+const folders = new Map<string, AssetFolder>([+ [+ "articles",+ {+ id: "articles",+ projectId: "project",+ name: "articles",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ],+ [+ "media",+ {+ id: "media",+ projectId: "project",+ name: "media",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ],+]);+const fragment = {+ children: [],+ instances: [],+ props: [],+ assets: [source],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSources: [],+ styleSourceSelections: [],+ styles: [],+};++test("discovers dependencies for an unmounted MDX source", async () => {+ const readSource = vi.fn(async () => "");+ const discoveryCache = new Map<+ string,+ Promise<readonly string[] | undefined>+ >();++ const result = await includeMdxAssetDependencies({+ fragment,+ projectId: "project",+ assets: new Map([+ [source.id, source],+ [dependency.id, dependency],+ ]),+ assetFolders: folders,+ discoveryCache,+ readSource,+ });+ await includeMdxAssetDependencies({+ fragment,+ projectId: "project",+ assets: new Map([+ [source.id, source],+ [dependency.id, dependency],+ ]),+ assetFolders: folders,+ discoveryCache,+ readSource,+ });++ expect(readSource).toHaveBeenCalledOnce();+ expect(readSource).toHaveBeenCalledWith(source.id);+ expect(result.fragment.assets).toEqual([source, dependency]);+ expect(result.skippedAssetIds).toEqual([]);+});++test("preserves an invalid MDX source and reports skipped discovery", async () => {+ const result = await includeMdxAssetDependencies({+ fragment,+ projectId: "project",+ assets: new Map([[source.id, source]]),+ assetFolders: folders,+ readSource: async () => "<broken",+ });++ expect(result.fragment.assets).toEqual([source]);+ expect(result.skippedAssetIds).toEqual([source.id]);+});++test("discovers transitive dependencies through Markdown documents", async () => {+ const author = createFile({+ id: "author",+ name: "author.md",+ format: "md",+ folderId: "articles",+ });++ const result = await includeMdxAssetDependencies({+ fragment,+ projectId: "project",+ assets: new Map([+ [source.id, source],+ [author.id, author],+ [dependency.id, dependency],+ ]),+ assetFolders: folders,+ readSource: async (assetId) =>+ assetId === source.id+ ? "---\nauthor:\n $ref: ./author.md#frontmatter\n---\n"+ : "---\navatar: ../media/hero.png\n---\n",+ });++ expect(result.fragment.assets).toEqual([source, author, dependency]);+ expect(result.skippedAssetIds).toEqual([]);+});++test("discovers transitive dependencies through JSON documents", async () => {+ const author = createFile({+ id: "author",+ name: "author.json",+ format: "json",+ folderId: "articles",+ });++ const result = await includeMdxAssetDependencies({+ fragment,+ projectId: "project",+ assets: new Map([+ [source.id, source],+ [author.id, author],+ [dependency.id, dependency],+ ]),+ assetFolders: folders,+ readSource: async (assetId) =>+ assetId === source.id+ ? "---\nauthor:\n $ref: ./author.json#\n---\n"+ : '{"avatar":"../media/hero.png"}',+ });++ expect(result.fragment.assets).toEqual([source, author, dependency]);+ expect(result.skippedAssetIds).toEqual([]);+});++test("includes a static expression source without a mounted Content Block", () => {+ const prepared = prepareConnectedContentBlockFragment({+ fragment: {+ ...fragment,+ children: [{ type: "id", value: "block" }],+ instances: [+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [+ { type: "id", value: "templates" },+ { type: "id", value: "authored" },+ ],+ },+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ },+ {+ type: "instance",+ id: "authored",+ component: "Paragraph",+ children: [{ type: "text", value: "Loaded" }],+ },+ ],+ props: [+ {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "expression",+ value: JSON.stringify(source.id),+ },+ ],+ assets: [],+ },+ projectId: undefined,+ assets: new Map([[source.id, source]]),+ });++ expect(prepared.assets).toEqual([source]);+ expect(prepared.instances).not.toContainEqual(+ expect.objectContaining({ id: "authored" })+ );+});++test("preserves the designed shell and clears only an explicit Body", () => {+ const prepared = prepareConnectedContentBlockFragment({+ fragment: {+ ...fragment,+ children: [{ type: "id", value: "block" }],+ instances: [+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [+ { type: "id", value: "shell" },+ { type: "id", value: "templates" },+ ],+ },+ {+ type: "instance",+ id: "shell",+ component: "Box",+ children: [{ type: "id", value: "content" }],+ },+ {+ type: "instance",+ id: "content",+ component: blockBodyComponent,+ children: [{ type: "id", value: "authored" }],+ },+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ },+ {+ type: "instance",+ id: "authored",+ component: "Paragraph",+ children: [{ type: "text", value: "Loaded" }],+ },+ ],+ props: [+ {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: source.id,+ },+ ],+ },+ projectId: undefined,+ });++ expect(prepared.instances).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: "block",+ children: [+ { type: "id", value: "shell" },+ { type: "id", value: "templates" },+ ],+ }),+ expect.objectContaining({ id: "shell" }),+ expect.objectContaining({ id: "content", children: [] }),+ expect.objectContaining({ id: "templates" }),+ ])+ );+ expect(prepared.instances).not.toContainEqual(+ expect.objectContaining({ id: "authored" })+ );+});++test("makes a copied Collection item source independent from its Collection", () => {+ const dynamicFragment = {+ ...fragment,+ children: [{ type: "id" as const, value: "item" }],+ instances: [+ {+ type: "instance" as const,+ id: "item",+ component: "Box",+ children: [{ type: "id" as const, value: "block" }],+ },+ {+ type: "instance" as const,+ id: "block",+ component: blockComponent,+ children: [],+ },+ ],+ props: [+ {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "expression" as const,+ value: "$ws$dataSource$item.file",+ },+ ],+ };+ const firstScope = '["block","item","collection[first]","collection"]';+ const secondScope = '["block","item","collection[second]","collection"]';+ const result = resolveRepeatedContentBlockSourcesForCopy({+ fragment: dynamicFragment,+ selectedInstanceSelector: ["item", "collection[first]", "collection"],+ occurrences: [+ {+ sourceBlockInstanceId: "block",+ sourceRenderScope: firstScope,+ sourceInstanceSelector: JSON.parse(firstScope),+ assetId: "first-article",+ },+ {+ sourceBlockInstanceId: "block",+ sourceRenderScope: secondScope,+ sourceInstanceSelector: JSON.parse(secondScope),+ assetId: "second-article",+ },+ ],+ });++ expect(result.fragment.props).toEqual([+ expect.objectContaining({ type: "asset", value: "first-article" }),+ ]);+ expect(result.renderScopes).toEqual(new Set([firstScope]));+});++test("keeps a dynamic source when the copied item contains many occurrences", () => {+ const sourceProp = {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "expression" as const,+ value: "$ws$dataSource$item.file",+ };+ const result = resolveRepeatedContentBlockSourcesForCopy({+ fragment: { ...fragment, props: [sourceProp] },+ selectedInstanceSelector: ["item", "collection[first]", "collection"],+ occurrences: ["nested[first]", "nested[second]"].map(+ (nestedInstanceId) => ({+ sourceBlockInstanceId: "block",+ sourceRenderScope: JSON.stringify([+ "block",+ nestedInstanceId,+ "item",+ "collection[first]",+ "collection",+ ]),+ sourceInstanceSelector: [+ "block",+ nestedInstanceId,+ "item",+ "collection[first]",+ "collection",+ ],+ assetId: nestedInstanceId,+ })+ ),+ });++ expect(result.fragment.props).toEqual([sourceProp]);+ expect(result.renderScopes).toHaveLength(2);+});diff --git a/apps/builder/app/shared/copy-paste/content-block-fragment.ts b/apps/builder/app/shared/copy-paste/content-block-fragment.tsnew file mode 100644index 0000000000..c1e66799a9--- /dev/null+++ b/apps/builder/app/shared/copy-paste/content-block-fragment.ts@@ -0,0 +1,314 @@+import {+ createCanonicalAssetPath,+ discoverNamedMdxAssetReferences,+ parseMdxDocumentRecovering,+} from "@webstudio-is/content-engine/mdx";+import { discoverNamedMarkdownDocumentAssetReferences } from "@webstudio-is/content-engine/markdown-assets";+import { discoverNamedJsonAssetReferences } from "@webstudio-is/content-engine";+import {+ createWebstudioDataFromFragment,+ extractWebstudioFragment,+ isDescendantOrSelf,+ mergeWebstudioFragments,+} from "@webstudio-is/project-build/runtime";+import {+ blockComponent,+ blockTemplateComponent,+ contentBlockSourceProp,+ createAssetFolderHierarchy,+ formatAssetName,+ findContentBlockBodyContainers,+ getContentBlockSource,+ getStaticContentBlockSourceAssetId,+ isMdxFileAsset,+ type Asset,+ type AssetFolders,+ type WebstudioFragment,+} from "@webstudio-is/sdk";+import {+ getExternalContentRootAssets,+ openExternalContentAsset,+} from "../external-content-roots";++export const resolveRepeatedContentBlockSourcesForCopy = ({+ fragment,+ selectedInstanceSelector,+ occurrences,+}: {+ fragment: WebstudioFragment;+ selectedInstanceSelector: readonly string[];+ occurrences: ReadonlyArray<+ Readonly<{+ sourceBlockInstanceId: string;+ sourceRenderScope: string;+ sourceInstanceSelector: readonly string[];+ assetId: string;+ }>+ >;+}) => {+ const selectedOccurrences = occurrences.filter(({ sourceInstanceSelector }) =>+ isDescendantOrSelf(+ [...sourceInstanceSelector],+ [...selectedInstanceSelector]+ )+ );+ const occurrencesByBlockId = new Map<string, typeof selectedOccurrences>();+ for (const occurrence of selectedOccurrences) {+ const blockOccurrences =+ occurrencesByBlockId.get(occurrence.sourceBlockInstanceId) ?? [];+ blockOccurrences.push(occurrence);+ occurrencesByBlockId.set(+ occurrence.sourceBlockInstanceId,+ blockOccurrences+ );+ }+ return {+ fragment: {+ ...fragment,+ props: fragment.props.map((prop) => {+ const blockOccurrences = occurrencesByBlockId.get(prop.instanceId);+ if (+ prop.name !== contentBlockSourceProp ||+ prop.type !== "expression" ||+ blockOccurrences?.length !== 1+ ) {+ return prop;+ }+ return {+ ...prop,+ type: "asset" as const,+ value: blockOccurrences[0].assetId,+ };+ }),+ },+ renderScopes: new Set(+ selectedOccurrences.map(({ sourceRenderScope }) => sourceRenderScope)+ ),+ };+};++export const prepareConnectedContentBlockFragment = ({+ fragment,+ projectId,+ assets,+ renderScopes,+}: {+ fragment: WebstudioFragment;+ projectId: string | undefined;+ assets?: ReadonlyMap<Asset["id"], Asset>;+ renderScopes?: ReadonlySet<string>;+}) => {+ const data = createWebstudioDataFromFragment(fragment);+ let changed = false;+ const staticSourceAssetIds = new Set<string>();+ for (const instance of data.instances.values()) {+ if (instance.component !== blockComponent) {+ continue;+ }+ const source = getContentBlockSource({+ blockInstanceId: instance.id,+ props: data.props.values(),+ });+ if (source === undefined) {+ continue;+ }+ const staticAssetId = getStaticContentBlockSourceAssetId(source);+ if (staticAssetId !== undefined) {+ staticSourceAssetIds.add(staticAssetId);+ }+ const bodyContainers = findContentBlockBodyContainers({+ blockInstance: instance,+ instances: data.instances,+ });+ if (bodyContainers.length === 0) {+ data.instances.set(instance.id, {+ ...instance,+ children: instance.children.filter(+ (child) =>+ child.type === "id" &&+ data.instances.get(child.value)?.component ===+ blockTemplateComponent+ ),+ });+ } else {+ for (const body of bodyContainers) {+ data.instances.set(body.id, { ...body, children: [] });+ }+ }+ changed = true;+ }+ const prepared =+ changed === false+ ? fragment+ : mergeWebstudioFragments(+ fragment.children.flatMap((child) =>+ child.type === "id" ? [child.value] : []+ ),+ fragment.children.flatMap((child) =>+ child.type === "id"+ ? [extractWebstudioFragment(data, child.value)]+ : []+ )+ );+ const assetIds = new Set(prepared.assets.map(({ id }) => id));+ for (const assetId of staticSourceAssetIds) {+ const asset = assets?.get(assetId);+ if (asset !== undefined && assetIds.has(asset.id) === false) {+ assetIds.add(asset.id);+ prepared.assets.push(asset);+ }+ }+ if (projectId === undefined) {+ return prepared;+ }+ const blockInstanceIds = new Set(+ prepared.instances+ .filter(({ component }) => component === blockComponent)+ .map(({ id }) => id)+ );+ for (const asset of getExternalContentRootAssets({+ projectId,+ blockInstanceIds,+ renderScopes,+ })) {+ if (assetIds.has(asset.id) === false) {+ assetIds.add(asset.id);+ prepared.assets.push(asset);+ }+ }+ return prepared;+};++export const hasDynamicContentBlockSource = (fragment: WebstudioFragment) => {+ const data = createWebstudioDataFromFragment(fragment);+ return Array.from(data.instances.values()).some((instance) => {+ if (instance.component !== blockComponent) {+ return false;+ }+ const source = getContentBlockSource({+ blockInstanceId: instance.id,+ props: data.props.values(),+ });+ return (+ source?.type === "expression" &&+ getStaticContentBlockSourceAssetId(source) === undefined+ );+ });+};++export const createClipboardAssetPaths = (+ assets: readonly Asset[],+ assetFolders: AssetFolders+) => {+ const folderHierarchy = createAssetFolderHierarchy(assetFolders);+ return Object.fromEntries(+ assets.map((asset) => [+ asset.id,+ createCanonicalAssetPath({+ folderNames: folderHierarchy+ .getPath(asset.folderId)+ .map(({ name }) => name),+ name: formatAssetName(asset),+ }),+ ])+ );+};++export const includeMdxAssetDependencies = async ({+ fragment,+ projectId,+ assets,+ assetFolders,+ discoveryCache = new Map(),+ readSource = async (assetId: string) =>+ (await openExternalContentAsset({ projectId, assetId })).source,+}: {+ fragment: WebstudioFragment;+ projectId: string;+ assets: ReadonlyMap<Asset["id"], Asset>;+ assetFolders: AssetFolders;+ discoveryCache?: Map<string, Promise<readonly string[] | undefined>>;+ readSource?: (assetId: string) => Promise<string>;+}) => {+ const isContentDocument = (asset: Asset) =>+ isMdxFileAsset(asset) ||+ (asset.type === "file" &&+ ["md", "json"].includes(asset.format.toLowerCase()));+ const included = new Map(fragment.assets.map((asset) => [asset.id, asset]));+ const pending = fragment.assets.filter(isContentDocument);+ const inspected = new Set<string>();+ const skippedAssetIds: string[] = [];+ const folderHierarchy = createAssetFolderHierarchy(assetFolders);+ const getNamedAsset = (asset: Asset) => ({+ id: asset.id,+ name: formatAssetName(asset),+ folderNames: folderHierarchy+ .getPath(asset.folderId)+ .map(({ name }) => name),+ });+ while (pending.length > 0) {+ const sourceAsset = pending.shift()!;+ if (inspected.has(sourceAsset.id)) {+ continue;+ }+ inspected.add(sourceAsset.id);+ let discovery = discoveryCache.get(sourceAsset.id);+ if (discovery === undefined) {+ discovery = (async () => {+ try {+ const source = await readSource(sourceAsset.id);+ const namedAssets = Array.from(assets.values(), getNamedAsset);+ if (sourceAsset.format.toLowerCase() === "json") {+ return (+ await discoverNamedJsonAssetReferences({+ source,+ asset: getNamedAsset(sourceAsset),+ assets: namedAssets,+ })+ ).map(({ assetId }) => assetId);+ }+ if (isMdxFileAsset(sourceAsset) === false) {+ return (+ await discoverNamedMarkdownDocumentAssetReferences({+ markdown: source,+ source: getNamedAsset(sourceAsset),+ assets: namedAssets,+ })+ ).map(({ assetId }) => assetId);+ }+ const parsed = await parseMdxDocumentRecovering({ source });+ if (parsed.status === "unrecoverable") {+ return;+ }+ return discoverNamedMdxAssetReferences({+ document: parsed.document,+ source: getNamedAsset(sourceAsset),+ assets: namedAssets,+ }).map(({ assetId }) => assetId);+ } catch {+ return;+ }+ })();+ discoveryCache.set(sourceAsset.id, discovery);+ }+ const dependencyIds = await discovery;+ if (dependencyIds === undefined) {+ skippedAssetIds.push(sourceAsset.id);+ continue;+ }+ for (const assetId of dependencyIds) {+ const dependency = assets.get(assetId);+ if (dependency === undefined || included.has(assetId)) {+ continue;+ }+ included.set(assetId, dependency);+ if (isContentDocument(dependency)) {+ pending.push(dependency);+ }+ }+ }+ return {+ fragment: { ...fragment, assets: Array.from(included.values()) },+ skippedAssetIds,+ };+};diff --git a/apps/builder/app/shared/copy-paste/copy-paste.test.ts b/apps/builder/app/shared/copy-paste/copy-paste.test.tsindex ff322c36bd..b28892bb1f 100644--- a/apps/builder/app/shared/copy-paste/copy-paste.test.ts+++ b/apps/builder/app/shared/copy-paste/copy-paste.test.ts@@ -221,6 +221,30 @@ test("does not copy page to clipboard when copy permission is disabled", async (expect(writeText).not.toHaveBeenCalled();});+test("writes asynchronously prepared page data from a clipboard event", async () => {+ resetStores();+ setupPage();+ $project.set({ id: "project" } as Project);+ selectInstance(["body-id"]);+ const writeText = vi.fn().mockResolvedValue(undefined);+ vi.stubGlobal("navigator", {+ ...navigator,+ clipboard: { writeText },+ });+ const abortController = new AbortController();+ initCopyPaste({ signal: abortController.signal });+ const { event } = createClipboardEvent("copy");++ document.dispatchEvent(event);+ await waitForClipboardEvent();++ expect(event.defaultPrevented).toBe(true);+ expect(writeText).toHaveBeenCalledWith(+ expect.stringContaining('"@webstudio/page/v0.1"')+ );+ abortController.abort();+});+test("does not copy instance to clipboard when no instance is selected", async () => {resetStores();const writeText = vi.fn().mockResolvedValue(undefined);diff --git a/apps/builder/app/shared/copy-paste/copy-paste.ts b/apps/builder/app/shared/copy-paste/copy-paste.tsindex ae30783661..9e965dbf69 100644--- a/apps/builder/app/shared/copy-paste/copy-paste.ts+++ b/apps/builder/app/shared/copy-paste/copy-paste.ts@@ -80,7 +80,7 @@ const validateCopyPermission = () => {export type Plugin = {name: string;mimeType: string;- onCopy?: () => undefined | string;+ onCopy?: () => undefined | string | Promise<undefined | string>;onCut?: () => undefined | string;onPaste?: (data: string) => PasteResult | Promise<PasteResult>;};@@ -124,6 +124,17 @@ const initPlugins = ({for (const { mimeType, onCopy } of plugins) {const data = onCopy?.();+ if (data instanceof Promise) {+ event.preventDefault();+ void data+ .then((value) => writeClipboardText(value))+ .catch(() =>+ builderApi.toast.error(+ "Could not prepare the selected content for copying."+ )+ );+ break;+ }if (data) {// must prevent default, otherwise setData() will not workevent.preventDefault();@@ -269,11 +280,13 @@ export const initCopyPasteForContentEditMode = ({});};-const writeClipboardText = (data: string | undefined) => {+const writeClipboardText = async (+ data: string | undefined | Promise<string | undefined>+) => {+ data = await data;if (data && validateCopyPermission()) {- return navigator.clipboard.writeText(data);+ await navigator.clipboard.writeText(data);}- return Promise.resolve();};// Public API for programmatic copy/paste/cut operationsdiff --git a/apps/builder/app/shared/copy-paste/mdx-asset-transfer.test.ts b/apps/builder/app/shared/copy-paste/mdx-asset-transfer.test.tsnew file mode 100644index 0000000000..f8f112a215--- /dev/null+++ b/apps/builder/app/shared/copy-paste/mdx-asset-transfer.test.ts@@ -0,0 +1,202 @@+import { expect, test, vi } from "vitest";+import type { Asset } from "@webstudio-is/sdk";+import { rewriteTransferredDocumentAssetReferences } from "./mdx-asset-transfer";++const sourceMdx = {+ id: "article",+ projectId: "source",+ name: "article.mdx",+ type: "file",+ format: "mdx",+ size: 20,+ createdAt: "2026-01-01T00:00:00.000Z",+ description: null,+ meta: {},+} satisfies Asset;+const sourceImage = {+ id: "hero",+ projectId: "source",+ name: "hero.png",+ type: "image",+ format: "png",+ size: 20,+ createdAt: "2026-01-01T00:00:00.000Z",+ description: null,+ meta: { width: 100, height: 100 },+} satisfies Asset;+const sourceMarkdown = {+ id: "author",+ projectId: "source",+ name: "oleg.md",+ type: "file",+ format: "md",+ size: 20,+ createdAt: "2026-01-01T00:00:00.000Z",+ description: null,+ meta: {},+} satisfies Asset;+const sourceJson = {+ ...sourceMarkdown,+ id: "author-json",+ name: "oleg.json",+ format: "json",+} satisfies Asset;++test("rewrites copied MDX to the imported Asset paths", async () => {+ const readSource = vi.fn(async () => "");+ const writeSource = vi.fn(async () => {});++ await rewriteTransferredDocumentAssetReferences({+ sourceOrigin: "https://source.example.com",+ projectId: "target",+ sourceAssets: [sourceMdx, sourceImage],+ sourceAssetPaths: {+ article: "articles/article.mdx",+ hero: "media/hero.png",+ },+ importedAssets: new Map([+ [sourceMdx.id, { ...sourceMdx, id: "article-copy", projectId: "target" }],+ [+ sourceImage.id,+ {+ ...sourceImage,+ id: "hero-copy",+ projectId: "target",+ filename: "hero_1",+ },+ ],+ ]),+ readSource,+ writeSource,+ });++ expect(writeSource).toHaveBeenCalledWith(+ expect.objectContaining({ id: "article-copy" }),+ "\n"+ );+});++test("preserves invalid copied MDX for destination diagnostics", async () => {+ const writeSource = vi.fn(async () => {});+ const result = await rewriteTransferredDocumentAssetReferences({+ sourceOrigin: "https://source.example.com",+ projectId: "target",+ sourceAssets: [sourceMdx],+ importedAssets: new Map([+ [sourceMdx.id, { ...sourceMdx, id: "article-copy", projectId: "target" }],+ ]),+ readSource: async () => "<broken",+ writeSource,+ });++ expect(result.skippedInvalidAssetIds).toEqual([sourceMdx.id]);+ expect(writeSource).not.toHaveBeenCalled();+});++test("rewrites structured document references in copied MDX", async () => {+ const writeSource = vi.fn(async () => {});++ await rewriteTransferredDocumentAssetReferences({+ sourceOrigin: "https://source.example.com",+ projectId: "target",+ sourceAssets: [sourceMdx, sourceMarkdown],+ sourceAssetPaths: {+ article: "posts/article.mdx",+ author: "authors/oleg.md",+ },+ importedAssets: new Map([+ [sourceMdx.id, { ...sourceMdx, id: "article-copy", projectId: "target" }],+ [+ sourceMarkdown.id,+ {+ ...sourceMarkdown,+ id: "author-copy",+ projectId: "target",+ filename: "oleg_1",+ },+ ],+ ]),+ readSource: async () =>+ "---\nauthor:\n $ref: ../authors/oleg.md#frontmatter\n---\n",+ writeSource,+ });++ expect(writeSource).toHaveBeenCalledWith(+ expect.objectContaining({ id: "article-copy" }),+ "---\nauthor:\n $ref: oleg_1.md#frontmatter\n---\n\n"+ );+});++test("rewrites references in copied Markdown dependencies", async () => {+ const writeSource = vi.fn(async () => {});++ await rewriteTransferredDocumentAssetReferences({+ sourceOrigin: "https://source.example.com",+ projectId: "target",+ sourceAssets: [sourceMarkdown, sourceImage],+ sourceAssetPaths: {+ author: "authors/oleg.md",+ hero: "media/hero.png",+ },+ importedAssets: new Map([+ [+ sourceMarkdown.id,+ { ...sourceMarkdown, id: "author-copy", projectId: "target" },+ ],+ [+ sourceImage.id,+ {+ ...sourceImage,+ id: "hero-copy",+ projectId: "target",+ filename: "hero_1",+ },+ ],+ ]),+ readSource: async () =>+ "---\navatar: ../media/hero.png#profile\n---\n\n<!-- HTML remains valid Markdown -->\n\n",+ writeSource,+ });++ expect(writeSource).toHaveBeenCalledWith(+ expect.objectContaining({ id: "author-copy" }),+ "---\navatar: hero_1.png#profile\n---\n\n<!-- HTML remains valid Markdown -->\n\n"+ );+});++test("rewrites references in copied JSON dependencies", async () => {+ const writeSource = vi.fn(async () => {});++ await rewriteTransferredDocumentAssetReferences({+ sourceOrigin: "https://source.example.com",+ projectId: "target",+ sourceAssets: [sourceJson, sourceImage],+ sourceAssetPaths: {+ "author-json": "authors/oleg.json",+ hero: "media/hero.png",+ },+ importedAssets: new Map([+ [+ sourceJson.id,+ { ...sourceJson, id: "author-copy", projectId: "target" },+ ],+ [+ sourceImage.id,+ {+ ...sourceImage,+ id: "hero-copy",+ projectId: "target",+ filename: "hero_1",+ },+ ],+ ]),+ readSource: async () =>+ JSON.stringify({ avatar: "../media/hero.png#profile" }),+ writeSource,+ });++ expect(writeSource).toHaveBeenCalledWith(+ expect.objectContaining({ id: "author-copy" }),+ '{\n "avatar": "hero_1.png#profile"\n}\n'+ );+});diff --git a/apps/builder/app/shared/copy-paste/mdx-asset-transfer.ts b/apps/builder/app/shared/copy-paste/mdx-asset-transfer.tsnew file mode 100644index 0000000000..c054ecf000--- /dev/null+++ b/apps/builder/app/shared/copy-paste/mdx-asset-transfer.ts@@ -0,0 +1,129 @@+import {+ createCanonicalAssetPath,+ MdxDocumentError,+ rewriteMdxAssetReferences,+} from "@webstudio-is/content-engine/mdx";+import {+ MarkdownAssetReferenceError,+ rewriteMarkdownAssetReferences,+} from "@webstudio-is/content-engine/markdown-assets";+import {+ JsonAssetReferenceError,+ rewriteJsonAssetReferences,+} from "@webstudio-is/content-engine";+import {+ formatAssetName,+ getAssetUrl,+ isMdxFileAsset,+ type Asset,+} from "@webstudio-is/sdk";+import { fetch as builderFetch } from "../fetch.client";+import {+ flushExternalContentAsset,+ openExternalContentAsset,+ updateExternalContentAssetSource,+} from "../external-content-roots";+import { updateAssetContent } from "~/builder/shared/assets/update-asset-content";++const getRootAssetPath = (asset: Asset) =>+ createCanonicalAssetPath({+ folderNames: [],+ name: formatAssetName(asset),+ });++export const rewriteTransferredDocumentAssetReferences = async ({+ sourceOrigin,+ projectId,+ sourceAssets,+ sourceAssetPaths = {},+ importedAssets,+ readSource = async (asset: Asset) => {+ const response = await builderFetch(getAssetUrl(asset, sourceOrigin));+ if (response.ok === false) {+ throw new Error(+ `Unable to read copied content Asset "${formatAssetName(asset)}"`+ );+ }+ return response.text();+ },+ writeSource = async (asset: Asset, source: string) => {+ if (isMdxFileAsset(asset) === false) {+ await updateAssetContent({ asset, content: source });+ return;+ }+ await openExternalContentAsset({ projectId, assetId: asset.id });+ await updateExternalContentAssetSource({+ projectId,+ assetId: asset.id,+ update: () => source,+ });+ await flushExternalContentAsset({ projectId, assetId: asset.id });+ },+}: {+ sourceOrigin: string;+ projectId: string;+ sourceAssets: readonly Asset[];+ sourceAssetPaths?: Readonly<Record<string, string>>;+ importedAssets: ReadonlyMap<Asset["id"], Asset>;+ readSource?: (asset: Asset) => Promise<string>;+ writeSource?: (asset: Asset, source: string) => Promise<void>;+}) => {+ const assetPaths = new Map(+ sourceAssets.map((asset) => [+ asset.id,+ sourceAssetPaths[asset.id] ?? getRootAssetPath(asset),+ ])+ );+ const replacementPaths = new Map(+ sourceAssets.flatMap((asset) => {+ const imported = importedAssets.get(asset.id);+ return imported === undefined+ ? []+ : ([[asset.id, getRootAssetPath(imported)]] as const);+ })+ );+ const skippedInvalidAssetIds: string[] = [];+ for (const sourceAsset of sourceAssets) {+ const imported = importedAssets.get(sourceAsset.id);+ const format = sourceAsset.format.toLowerCase();+ if (+ (isMdxFileAsset(sourceAsset) === false &&+ (sourceAsset.type !== "file" ||+ (format !== "md" && format !== "json"))) ||+ imported === undefined ||+ imported.id === sourceAsset.id+ ) {+ continue;+ }+ const source = await readSource(sourceAsset);+ let rewritten: string;+ try {+ const rewrite =+ format === "mdx"+ ? rewriteMdxAssetReferences+ : format === "md"+ ? rewriteMarkdownAssetReferences+ : rewriteJsonAssetReferences;+ rewritten = await rewrite({+ source,+ sourcePath: assetPaths.get(sourceAsset.id)!,+ assetPaths,+ replacementPaths,+ });+ } catch (error) {+ if (+ error instanceof MdxDocumentError ||+ error instanceof MarkdownAssetReferenceError ||+ error instanceof JsonAssetReferenceError+ ) {+ skippedInvalidAssetIds.push(sourceAsset.id);+ continue;+ }+ throw error;+ }+ if (rewritten !== source) {+ await writeSource(imported, rewritten);+ }+ }+ return { skippedInvalidAssetIds };+};diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts b/apps/builder/app/shared/copy-paste/plugin-instance.test.tsindex 0f0d3923ee..93058f80bd 100644--- a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts+++ b/apps/builder/app/shared/copy-paste/plugin-instance.test.ts@@ -18,6 +18,7 @@ import {coreMetas,elementComponent,blockTemplateComponent,+ blockComponent,portalComponent,} from "@webstudio-is/sdk";import type { Project } from "@webstudio-is/project";@@ -25,9 +26,10 @@ import * as baseComponentMetas from "@webstudio-is/sdk-components-react/metas";import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";import { registerContainers } from "../sync/sync-stores";import { $registeredComponentMetas } from "../nano-states";-import { $assets, $instances } from "~/shared/sync/data-stores";import {$dataSources,+ $assets,+ $instances,$pages,$project,$props,@@ -45,6 +47,7 @@ import {} from "../slot-test-utils";import { pasteHandled } from "./copy-paste";import { initBuilderApi } from "../builder-api";+import { $externalContentRoots } from "../external-content-mutations";const expectString = expect.any(String) as unknown as string;@@ -169,6 +172,163 @@ describe("copy and cut guards", () => {});});+ test("copies and pastes one rendered Collection Content Block with its resolved direct MDX source", async () => {+ setPageRoot("body");+ $instances.set(+ toMap([+ createInstance("body", "Body", [{ type: "id", value: "collection" }]),+ createInstance("collection", collectionComponent, [+ { type: "id", value: "item" },+ ]),+ createInstance("item", "Box", [{ type: "id", value: "block" }]),+ createInstance("block", blockComponent, [+ { type: "id", value: "templates" },+ { type: "id", value: "mdx-heading" },+ ]),+ createInstance("templates", blockTemplateComponent, []),+ createInstance("mdx-heading", elementComponent, [+ { type: "text", value: "Loaded from MDX" },+ ]),+ ])+ );+ $dataSources.set(+ toMap([+ {+ id: "item-source",+ scopeInstanceId: "collection",+ type: "parameter",+ name: "item",+ },+ ])+ );+ $props.set(+ toMap([+ {+ id: "collection-data",+ instanceId: "collection",+ name: "data",+ type: "json",+ value: [{ mdx: "post" }],+ },+ {+ id: "collection-item",+ instanceId: "collection",+ name: "item",+ type: "parameter",+ value: "item-source",+ },+ {+ id: "block-source",+ instanceId: "block",+ name: "src",+ type: "expression",+ value: `${encodeDataSourceVariable("item-source")}.mdx`,+ },+ ] satisfies Prop[])+ );+ $assets.set(+ toMap([+ {+ id: "post",+ projectId: "my-project",+ type: "file",+ format: "mdx",+ name: "post.mdx",+ size: 0,+ createdAt: "2026-01-01T00:00:00.000Z",+ meta: {},+ },+ ])+ );+ const renderScope = '["block","item","collection[0]","collection","body"]';+ $externalContentRoots.set(+ new Map([+ [+ "post-root",+ {+ sourceBlockInstanceId: "block",+ sourceRenderScope: renderScope,+ blockInstanceId: "runtime-block",+ renderScope,+ instanceIds: new Set<string>(),+ mutationRevision: 0,+ identity: {+ blockInstanceId: "block",+ assetId: "post",+ revision: "revision",+ contentRef: "post.mdx",+ format: "mdx",+ renderScope,+ },+ },+ ],+ ])+ );+ selectInstance(["item", "collection[0]", "collection", "body"]);++ const clipboardData = instanceText.onCopy?.();+ const fragment = JSON.parse(clipboardData ?? "")[+ "@webstudio/instance/v0.1"+ ];++ expect(fragment.props).toContainEqual({+ id: "block-source",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "post",+ });+ expect(fragment.assets).toContainEqual(+ expect.objectContaining({ id: "post", format: "mdx" })+ );+ expect(fragment.assetPaths).toEqual({ post: "post.mdx" });+ expect(fragment.instances).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ id: "block" }),+ expect.objectContaining({ id: "item" }),+ expect.objectContaining({ id: "templates" }),+ ])+ );+ expect(fragment.instances).not.toEqual(+ expect.arrayContaining([expect.objectContaining({ id: "mdx-heading" })])+ );+ initBuilderApi();+ const importAssets = vi+ .spyOn(window.__webstudio__$__builderApi, "importAssets")+ .mockResolvedValue(new Map([["post", $assets.get().get("post")!]]));+ $instances.set(+ toMap([createInstance("target-body", "Body", [])] satisfies Instance[])+ );+ $props.set(new Map());+ $dataSources.set(new Map());+ setPageRoot("target-body");+ selectInstance(["target-body"]);++ expect(await instanceText.onPaste?.(clipboardData ?? "")).toEqual(+ pasteHandled+ );+ const pastedBlock = Array.from($instances.get().values()).find(+ (instance) => instance.component === blockComponent+ );+ expect(pastedBlock).toBeDefined();+ expect(+ Array.from($props.get().values()).find(+ (prop) => prop.instanceId === pastedBlock?.id && prop.name === "src"+ )+ ).toEqual(expect.objectContaining({ type: "asset", value: "post" }));+ expect(+ Array.from($instances.get().values()).some(+ (instance) => instance.id === "mdx-heading"+ )+ ).toBe(false);++ importAssets.mockRestore();+ $externalContentRoots.set(new Map());+ $props.set(new Map());+ $assets.set(new Map());+ setPageRoot("body0");+ });+test("pastes multiple copied roots in order and selects pasted roots", async () => {$instances.set(toMap([diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.tsindex c101eb96a3..acd9014565 100644--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts@@ -1,10 +1,15 @@import {+ breakpointPasteLimitWarning,extractWebstudioFragment,+ findChildReferenceIndex,findSafeFragmentPasteTarget,getCommonAncestorSelector,+ getInstancePath,getPasteRootInstanceIds,getFragmentContentModelWarnings,mergeWebstudioFragments,+ type InstanceSelector,+ sortInstancePathsForChildMutation,} from "@webstudio-is/project-build/runtime";import {instanceTransferDataVersion,@@ -22,16 +27,15 @@ import { type Insertable } from "../instance-utils/insert";import { shallowEqual } from "shallow-equal";import { toast } from "@webstudio-is/design-system";import {+ blockComponent,+ contentBlockSourceProp,+ getContentBlockSource,+ isMdxFileAsset,type Instance,type WebstudioFragment,isComponentDetachable,} from "@webstudio-is/sdk";-import { $instances, $project } from "~/shared/sync/data-stores";-import {- type InstanceSelector,- sortInstancePathsForChildMutation,-} from "@webstudio-is/project-build/runtime";-import { findChildReferenceIndex } from "@webstudio-is/project-build/runtime";+import { $assetFolders, $instances, $project } from "~/shared/sync/data-stores";import { deleteInstanceBySelector } from "../instance-utils/mutation";import {$allSelectedInstanceSelectors,@@ -39,15 +43,30 @@ import {$selectedInstancePath,$selectedInstanceSelector,$registeredComponentMetas,+ $variableValuesByInstanceSelector,selectInstances,} from "~/shared/nano-states";-import { getInstancePath } from "@webstudio-is/project-build/runtime";import { builderApi } from "../builder-api";import { pasteHandled, pasteIgnored, type Plugin } from "./copy-paste";-import { breakpointPasteLimitWarning } from "@webstudio-is/project-build/runtime";import { resolveFragmentTokenConflicts } from "../resolve-token-conflicts";import { reportFragmentContentModelWarnings } from "./fragment-utils";import { transferFragmentAssets } from "./asset-transfer-utils";+import {+ isRepeatedContentBlockOccurrence,+ parseContentBlockRenderScope,+ resolveContentBlockOccurrenceAssetId,+} from "../content-block-source-utils";+import { rewriteTransferredDocumentAssetReferences } from "./mdx-asset-transfer";+import {+ createClipboardAssetPaths,+ hasDynamicContentBlockSource,+ prepareConnectedContentBlockFragment,+ resolveRepeatedContentBlockSourcesForCopy,+} from "./content-block-fragment";+import {+ $externalContentRoots,+ getExternalContentSourceSelector,+} from "../external-content-mutations";const invalidPasteDataMessage ="Could not paste Webstudio instance data. The clipboard data appears to be incomplete or invalid.";@@ -73,10 +92,102 @@ const getTreeData = (return;}+ const data = getWebstudioData();+ const project = $project.get();+ const sourceInstanceSelector =+ instance?.component === blockComponent+ ? getExternalContentSourceSelector({+ selector: instanceSelector,+ roots: $externalContentRoots.get(),+ })?.sourceSelector+ : undefined;+ const copyInstanceSelector = sourceInstanceSelector ?? instanceSelector;+ let fragment = extractWebstudioFragment(data, copyInstanceSelector[0]);+ let renderScopes: ReadonlySet<string> | undefined;+ const isRepeatedOccurrence = isRepeatedContentBlockOccurrence({+ instanceSelector,+ instances,+ });+ if (isRepeatedOccurrence) {+ const resolved = resolveRepeatedContentBlockSourcesForCopy({+ fragment,+ selectedInstanceSelector: copyInstanceSelector,+ occurrences: Array.from($externalContentRoots.get().values()).flatMap(+ (root) => {+ const sourceInstanceSelector = parseContentBlockRenderScope(+ root.sourceRenderScope ?? root.renderScope ?? ""+ );+ const sourceBlockInstanceId =+ root.sourceBlockInstanceId ?? root.blockInstanceId;+ return root.identity === undefined ||+ sourceInstanceSelector === undefined+ ? []+ : [+ {+ sourceBlockInstanceId,+ sourceRenderScope:+ root.sourceRenderScope ?? root.renderScope ?? "",+ sourceInstanceSelector,+ assetId: root.identity.assetId,+ },+ ];+ }+ ),+ });+ fragment = resolved.fragment;+ renderScopes = resolved.renderScopes;+ }+ if (instance?.component === blockComponent) {+ const source = getContentBlockSource({+ blockInstanceId: copyInstanceSelector[0],+ props: data.props.values(),+ });+ const resolvedAssetId =+ source?.type === "expression"+ ? resolveContentBlockOccurrenceAssetId({+ source,+ instanceSelector,+ variableValuesByRenderScope:+ $variableValuesByInstanceSelector.get(),+ })+ : undefined;+ const resolvedAsset =+ resolvedAssetId === undefined+ ? undefined+ : data.assets.get(resolvedAssetId);+ if (resolvedAsset !== undefined && isMdxFileAsset(resolvedAsset)) {+ fragment = {+ ...fragment,+ props: fragment.props.map((prop) =>+ prop.instanceId === copyInstanceSelector[0] &&+ prop.name === contentBlockSourceProp+ ? { ...prop, type: "asset" as const, value: resolvedAsset.id }+ : prop+ ),+ };+ }+ }+ fragment = prepareConnectedContentBlockFragment({+ fragment,+ projectId: project?.id,+ assets: data.assets,+ renderScopes,+ });+ const hasDynamicContentSource = hasDynamicContentBlockSource(fragment);+ if (+ showToast &&+ instance?.component !== blockComponent &&+ hasDynamicContentSource+ ) {+ toast.warn(+ "Dynamic MDX sources are copied from the Collection items currently rendered on the canvas."+ );+ }return {sourceOrigin: window.location.origin,- instanceSelector,- ...extractWebstudioFragment(getWebstudioData(), targetInstanceId),+ assetPaths: createClipboardAssetPaths(fragment.assets, $assetFolders.get()),+ instanceSelector: copyInstanceSelector,+ ...fragment,};};@@ -96,6 +207,10 @@ const stringifyMultiRootSelection = (selectedData: InstanceTransferData[]) => {const rootInstanceIds = selectedData.map((data) => data.instanceSelector[0]);return stringifyMultiRoot({sourceOrigin: firstData.sourceOrigin,+ assetPaths: Object.assign(+ {},+ ...selectedData.map(({ assetPaths }) => assetPaths ?? {})+ ),rootInstanceIds,fragment: mergeWebstudioFragments(rootInstanceIds, selectedData),});@@ -185,11 +300,21 @@ const findPasteTarget = (const instances = $instances.get();const instanceSelector = $selectedInstanceSelector.get();+ const selectedSourceSelector =+ instanceSelector === undefined+ ? undefined+ : getExternalContentSourceSelector({+ selector: instanceSelector,+ roots: $externalContentRoots.get(),+ })?.sourceSelector;// paste after selected instanceif (instanceSelector &&- shallowEqual(instanceSelector, data.instanceSelector)+ shallowEqual(+ selectedSourceSelector ?? instanceSelector,+ data.instanceSelector+ )) {// body is not allowed to copy// so clipboard always have at least two level instance selector@@ -215,12 +340,14 @@ const insertPastedFragment = async ({pasteTarget,selectRootInstances,sourceOrigin,+ assetPaths,projectId,}: {fragment: WebstudioFragment;pasteTarget: Insertable;selectRootInstances: (rootInstanceIds: Instance["id"][]) => void;sourceOrigin: string | undefined;+ assetPaths?: Readonly<Record<string, string>>;projectId: string;}) => {try {@@ -246,6 +373,35 @@ const insertPastedFragment = async ({error: "Project changed while pasting.",} as const;}+ if (sourceOrigin !== undefined) {+ try {+ const { skippedInvalidAssetIds } =+ await rewriteTransferredDocumentAssetReferences({+ sourceOrigin,+ projectId,+ sourceAssets: fragment.assets,+ sourceAssetPaths: assetPaths,+ importedAssets: transferred.assets,+ });+ if (skippedInvalidAssetIds.length > 0) {+ toast.warn(+ "Some invalid content files were copied unchanged. Open them to review their diagnostics."+ );+ }+ } catch {+ return {+ success: false,+ error:+ "Could not update Asset references in the copied content files.",+ } as const;+ }+ }+ if ($project.get()?.id !== projectId) {+ return {+ success: false,+ error: "Project changed while pasting.",+ } as const;+ }const transferredFragment = transferred.fragments.get(fragment);if (transferredFragment === undefined) {return pasteHandled;@@ -310,6 +466,7 @@ const handlePasteInstance = async (clipboardData: string) => {fragment,pasteTarget,sourceOrigin: transferData.data.sourceOrigin ?? window.location.origin,+ assetPaths: transferData.data.assetPaths,projectId,selectRootInstances: (rootInstanceIds) => {selectInstances(@@ -331,6 +488,7 @@ const handlePasteInstance = async (clipboardData: string) => {fragment,pasteTarget,sourceOrigin: transferData.data.sourceOrigin ?? window.location.origin,+ assetPaths: transferData.data.assetPaths,projectId,selectRootInstances: (rootInstanceIds) => {const newRootInstanceId = rootInstanceIds[0];diff --git a/apps/builder/app/shared/copy-paste/plugin-page.test.ts b/apps/builder/app/shared/copy-paste/plugin-page.test.tsindex 5429cf36cd..8b3365b407 100644--- a/apps/builder/app/shared/copy-paste/plugin-page.test.ts+++ b/apps/builder/app/shared/copy-paste/plugin-page.test.ts@@ -1,7 +1,10 @@import { afterEach, expect, test, vi } from "vitest";import { enableMapSet } from "immer";import { createDefaultPages } from "@webstudio-is/project-build";+import type { PageTransferItem } from "@webstudio-is/project-build/transfer";import {+ blockComponent,+ blockTemplateComponent,encodeDataSourceVariable,ROOT_FOLDER_ID,ROOT_INSTANCE_ID,@@ -36,6 +39,7 @@ import {copyTemplateData,handlePastePage,pageText,+ __testing__,} from "./plugin-page";import { pasteHandled, pasteIgnored } from "./copy-paste";import { initBuilderApi } from "../builder-api";@@ -43,6 +47,7 @@ import { initBuilderApi } from "../builder-api";enableMapSet();registerContainers();initBuilderApi();+const { preparePageTransferItem } = __testing__;afterEach(() => {vi.restoreAllMocks();@@ -196,7 +201,7 @@ const setupProjectWithRootStyle = ({return pages;};-test("copies the selected page root from the copy plugin", () => {+test("copies the selected page root from the copy plugin", async () => {$project.set({ id: "source-project" } as Project);resetBuildStores();@@ -226,11 +231,11 @@ test("copies the selected page root from the copy plugin", () => {]));- expect(pageText.onCopy?.()).toContain('"type":"page"');- expect(pageText.onCopy?.()).toContain('"name":"Selected Page"');+ expect(await pageText.onCopy?.()).toContain('"type":"page"');+ expect(await pageText.onCopy?.()).toContain('"name":"Selected Page"');});-test("copies the edited folder from the copy plugin", () => {+test("copies the edited folder from the copy plugin", async () => {$project.set({ id: "source-project" } as Project);resetBuildStores();@@ -260,8 +265,8 @@ test("copies the edited folder from the copy plugin", () => {]));- expect(pageText.onCopy?.()).toContain('"type":"folder"');- expect(pageText.onCopy?.()).toContain('"name":"Edited Folder"');+ expect(await pageText.onCopy?.()).toContain('"type":"folder"');+ expect(await pageText.onCopy?.()).toContain('"name":"Edited Folder"');});test("copies page data across projects", async () => {@@ -306,7 +311,7 @@ test("copies page data across projects", async () => {);$dataSources.set(new Map([[variable.id, variable]]));- const clipboardData = copyPageData("source-page");+ const clipboardData = await copyPageData("source-page");expect(clipboardData).toBeDefined();$project.set({ id: "target-project" } as Project);@@ -396,10 +401,13 @@ test("transfers assets copied from another deployment before inserting the page"]));$assets.set(new Map([[sourceAsset.id, sourceAsset]]));- const clipboardData = JSON.parse(copyPageData("source-page") ?? "");+ const clipboardData = JSON.parse((await copyPageData("source-page")) ?? "");expect(clipboardData["@webstudio/page/v0.1"].sourceOrigin).toBe(window.location.origin);+ expect(clipboardData["@webstudio/page/v0.1"].assetPaths).toEqual({+ "source-asset": "hero.png",+ });clipboardData["@webstudio/page/v0.1"].sourceOrigin ="https://source.example.com";@@ -503,7 +511,7 @@ test("preserves legacy page metadata assets that exist in the destination", asyn]));$assets.set(new Map([[sourceAsset.id, sourceAsset]]));- const currentData = JSON.parse(copyPageData("source-page") ?? "")[+ const currentData = JSON.parse((await copyPageData("source-page")) ?? "")["@webstudio/page/v0.1"];delete currentData.sourceOrigin;@@ -571,7 +579,7 @@ test.each([property: "fontSize",value: { type: "keyword", value: "medium" },});- const clipboardData = copyPageData("source-page");+ const clipboardData = await copyPageData("source-page");setupProjectWithRootStyle({projectId: "target-project",@@ -630,7 +638,7 @@ test("cancels page paste when global root style resolution is cancelled", async}sourcePage.meta.socialImageAssetId = sourceAsset.id;$assets.set(new Map([[sourceAsset.id, sourceAsset]]));- const clipboardData = copyPageData("source-page");+ const clipboardData = await copyPageData("source-page");const targetPages = setupProjectWithRootStyle({projectId: "target-project",@@ -668,7 +676,7 @@ test("checks current root styles after resolving token conflicts", async () => {color: "red",});addRootTokenStyle({ styleSourceId: "source-token", value: "red" });- const clipboardData = copyPageData("source-page");+ const clipboardData = await copyPageData("source-page");setupProjectWithRootStyle({projectId: "target-project",@@ -722,7 +730,7 @@ test("handles page paste data without falling through when insertion cannot comp]));- const clipboardData = copyPageData("source-page");+ const clipboardData = await copyPageData("source-page");expect(clipboardData).toBeDefined();resetBuildStores();@@ -819,7 +827,7 @@ test("copies folder data with nested pages across projects", async () => {);setRootLocalStyle({ styleSourceId: "source-local", value: "red" });- const clipboardData = copyFolderData("source-folder");+ const clipboardData = await copyFolderData("source-folder");expect(clipboardData).toBeDefined();$project.set({ id: "target-project" } as Project);@@ -906,7 +914,7 @@ test("preserves empty folder slugs when pasting folder data", async () => {]));- const clipboardData = copyFolderData("source-folder");+ const clipboardData = await copyFolderData("source-folder");expect(clipboardData).toBeDefined();$project.set({ id: "target-project" } as Project);@@ -985,7 +993,7 @@ test("copies template data as a template", async () => {);setRootLocalStyle({ styleSourceId: "source-local", value: "red" });- const clipboardData = copyTemplateData("template-id");+ const clipboardData = await copyTemplateData("template-id");expect(clipboardData).toBeDefined();$project.set({ id: "target-project" } as Project);@@ -1038,3 +1046,152 @@ test("copies template data as a template", async () => {);expect(pastedPage).toBeUndefined();});++test.each(["page", "template", "folder"] as const)(+ "prepares connected MDX dependencies when copying a %s",+ async (type) => {+ const sourceAsset = {+ id: "article",+ projectId: "source-project",+ name: "article.mdx",+ type: "file",+ format: "mdx",+ size: 1,+ createdAt: "2026-01-01T00:00:00.000Z",+ description: null,+ meta: {},+ } satisfies Asset;+ const dependency = {+ ...sourceAsset,+ id: "hero",+ name: "hero.png",+ format: "png",+ } satisfies Asset;+ $assets.set(+ new Map([+ [sourceAsset.id, sourceAsset],+ [dependency.id, dependency],+ ])+ );+ const emptyFragment = {+ children: [],+ instances: [],+ props: [],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSources: [],+ styleSourceSelections: [],+ styles: [],+ };+ const bodyFragment = {+ ...emptyFragment,+ children: [{ type: "id" as const, value: "body" }],+ instances: [+ {+ type: "instance" as const,+ id: "body",+ component: "Body",+ children: [{ type: "id" as const, value: "block" }],+ },+ {+ type: "instance" as const,+ id: "block",+ component: blockComponent,+ children: [+ { type: "id" as const, value: "templates" },+ { type: "id" as const, value: "authored" },+ ],+ },+ {+ type: "instance" as const,+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ },+ {+ type: "instance" as const,+ id: "authored",+ component: "Paragraph",+ children: [{ type: "text" as const, value: "Loaded" }],+ },+ ],+ props: [+ {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "asset" as const,+ value: sourceAsset.id,+ },+ ],+ assets: [sourceAsset],+ };+ const page = {+ type: "page" as const,+ page: {+ id: "page",+ name: "Page",+ path: "/page",+ title: "Page",+ rootInstanceId: "body",+ meta: {},+ },+ rootFragment: emptyFragment,+ bodyFragment,+ };+ const template = {+ type: "template" as const,+ template: {+ id: "template",+ name: "Template",+ title: "Template",+ rootInstanceId: "body",+ meta: {},+ },+ rootFragment: emptyFragment,+ bodyFragment,+ };+ const item: PageTransferItem =+ type === "page"+ ? page+ : type === "template"+ ? template+ : {+ type: "folder",+ folder: {+ id: "folder",+ name: "Folder",+ slug: "folder",+ children: ["page"],+ },+ children: [page],+ };+ const includeDependencies = vi.fn(async ({ fragment }) => ({+ fragment:+ fragment.assets.length === 0+ ? fragment+ : { ...fragment, assets: [...fragment.assets, dependency] },+ skippedAssetIds: [],+ }));++ const prepared = await preparePageTransferItem({+ item,+ projectId: "source-project",+ assets: $assets.get(),+ assetFolders: new Map(),+ includeDependencies,+ });+ const preparedItem =+ prepared.type === "folder" ? prepared.children[0] : prepared;+ if (preparedItem === undefined || preparedItem.type === "folder") {+ throw new Error("Expected a prepared page-like item");+ }++ expect(preparedItem.bodyFragment.assets).toEqual([sourceAsset, dependency]);+ expect(preparedItem.bodyFragment.instances).not.toContainEqual(+ expect.objectContaining({ id: "authored" })+ );+ }+);diff --git a/apps/builder/app/shared/copy-paste/plugin-page.ts b/apps/builder/app/shared/copy-paste/plugin-page.tsindex 7d8da88fe9..7cb1bbe9bf 100644--- a/apps/builder/app/shared/copy-paste/plugin-page.ts+++ b/apps/builder/app/shared/copy-paste/plugin-page.ts@@ -11,7 +11,12 @@ import {type Page,type PageTemplate,} from "@webstudio-is/sdk";-import { $pages, $project } from "~/shared/sync/data-stores";+import {+ $assetFolders,+ $assets,+ $pages,+ $project,+} from "~/shared/sync/data-stores";import { detectFragmentTokenConflicts } from "@webstudio-is/project-build/runtime";import { resolveTokenConflicts } from "../resolve-token-conflicts";import { resolveRootStyleConflicts } from "../resolve-root-style-conflicts";@@ -34,19 +39,152 @@ import { getPageActionTarget } from "../page-action-target";import { pasteHandled, pasteIgnored, type Plugin } from "./copy-paste";import { breakpointPasteLimitWarning } from "@webstudio-is/project-build/runtime";import { transferFragmentAssets } from "./asset-transfer-utils";+import { rewriteTransferredDocumentAssetReferences } from "./mdx-asset-transfer";+import {+ createClipboardAssetPaths,+ hasDynamicContentBlockSource,+ includeMdxAssetDependencies,+ prepareConnectedContentBlockFragment,+} from "./content-block-fragment";const invalidPasteDataMessage ="Could not paste Webstudio page data. The clipboard data appears to be incomplete or invalid.";-const stringify = (data: PageTransferItem) => {+const stringify = (+ data: PageTransferItem,+ assetFolders: ReturnType<typeof $assetFolders.get>+) => {+ const assets = new Map(+ collectPageTransferItems(data).flatMap((item) =>+ [item.rootFragment, item.bodyFragment].flatMap((fragment) =>+ fragment.assets.map((asset) => [asset.id, asset] as const)+ )+ )+ );return JSON.stringify({[pageTransferDataVersion]: {...data,sourceOrigin: window.location.origin,+ assetPaths: createClipboardAssetPaths(+ Array.from(assets.values()),+ assetFolders+ ),},});};+const preparePageTransferItemRecursive = async ({+ item,+ projectId,+ assets,+ assetFolders,+ includeDependencies,+ discoveryCache,+ warnings,+}: {+ item: PageTransferItem;+ projectId: string | undefined;+ assets: ReturnType<typeof $assets.get>;+ assetFolders: ReturnType<typeof $assetFolders.get>;+ includeDependencies: typeof includeMdxAssetDependencies;+ discoveryCache: Map<string, Promise<readonly string[] | undefined>>;+ warnings: { skippedDependencies: boolean };+}): Promise<PageTransferItem> => {+ if (item.type === "folder") {+ return {+ ...item,+ children: (await Promise.all(+ item.children.map((child) =>+ preparePageTransferItemRecursive({+ item: child,+ projectId,+ assets,+ assetFolders,+ includeDependencies,+ discoveryCache,+ warnings,+ })+ )+ )) as FolderTransferData["children"],+ };+ }+ const prepared = {+ ...item,+ rootFragment: prepareConnectedContentBlockFragment({+ fragment: item.rootFragment,+ projectId,+ assets,+ }),+ bodyFragment: prepareConnectedContentBlockFragment({+ fragment: item.bodyFragment,+ projectId,+ assets,+ }),+ };+ if (projectId === undefined) {+ return prepared;+ }+ const [root, body] = await Promise.all(+ [prepared.rootFragment, prepared.bodyFragment].map((fragment) =>+ includeDependencies({+ fragment,+ projectId,+ assets,+ assetFolders,+ discoveryCache,+ })+ )+ );+ if (root.skippedAssetIds.length > 0 || body.skippedAssetIds.length > 0) {+ warnings.skippedDependencies = true;+ }+ return {+ ...prepared,+ rootFragment: root.fragment,+ bodyFragment: body.fragment,+ };+};++const preparePageTransferItem = async ({+ item,+ projectId,+ assets,+ assetFolders,+ includeDependencies = includeMdxAssetDependencies,+}: {+ item: PageTransferItem;+ projectId: string | undefined;+ assets: ReturnType<typeof $assets.get>;+ assetFolders: ReturnType<typeof $assetFolders.get>;+ includeDependencies?: typeof includeMdxAssetDependencies;+}) => {+ if (+ collectPageTransferItems(item).some(({ rootFragment, bodyFragment }) =>+ [rootFragment, bodyFragment].some(hasDynamicContentBlockSource)+ )+ ) {+ toast.warn(+ "Dynamic MDX sources are copied from the Collection items currently rendered on the canvas."+ );+ }+ const warnings = { skippedDependencies: false };+ const prepared = await preparePageTransferItemRecursive({+ item,+ projectId,+ assets,+ assetFolders,+ includeDependencies,+ discoveryCache: new Map(),+ warnings,+ });+ if (warnings.skippedDependencies) {+ toast.warn(+ "Some MDX dependencies could not be inspected and were skipped while copying."+ );+ }+ return prepared;+};+const getDefaultTargetFolderId = () => {const pages = $pages.get();if (pages === undefined) {@@ -220,33 +358,58 @@ const handleCopyPage = () => {}};-export const copyPageData = (pageId: Page["id"]) => {+export const copyPageData = async (pageId: Page["id"]) => {const data = getWebstudioData();const pageData = getPageCopyData(data, pageId);if (pageData === undefined) {return;}- return stringify(pageData);+ return stringify(+ await preparePageTransferItem({+ item: pageData,+ projectId: $project.get()?.id,+ assets: data.assets,+ assetFolders: data.assetFolders,+ }),+ data.assetFolders+ );};-export const copyTemplateData = (templateId: PageTemplate["id"]) => {+export const copyTemplateData = async (templateId: PageTemplate["id"]) => {const data = getWebstudioData();const template = data.pages.pageTemplates?.get(templateId);if (template === undefined) {return;}return stringify(- addTemplateType(createTemplateCopyData({ data, template }), data.assets)+ await preparePageTransferItem({+ item: addTemplateType(+ createTemplateCopyData({ data, template }),+ data.assets+ ),+ projectId: $project.get()?.id,+ assets: data.assets,+ assetFolders: data.assetFolders,+ }),+ data.assetFolders);};-export const copyFolderData = (folderId: Folder["id"]) => {+export const copyFolderData = async (folderId: Folder["id"]) => {const data = getWebstudioData();const folderData = createFolderCopyData({ data, folderId });if (folderData === undefined) {return;}- return stringify(addFolderType(folderData, data.assets));+ return stringify(+ await preparePageTransferItem({+ item: addFolderType(folderData, data.assets),+ projectId: $project.get()?.id,+ assets: data.assets,+ assetFolders: data.assetFolders,+ }),+ data.assetFolders+ );};export const handlePastePage = async (@@ -260,7 +423,7 @@ export const handlePastePage = async (if (transferData.valid === false) {return { success: false, error: invalidPasteDataMessage } as const;}- const { sourceOrigin, ...transferItem } = transferData.data;+ const { sourceOrigin, assetPaths, ...transferItem } = transferData.data;let item: PageTransferItem = transferItem;const pages = $pages.get();@@ -342,6 +505,42 @@ export const handlePastePage = async (error: "Project changed while pasting.",} as const;}+ if (sourceOrigin !== undefined) {+ const sourceAssets = new Map(+ sourcePageItems.flatMap((item) =>+ [item.rootFragment, item.bodyFragment].flatMap((fragment) =>+ fragment.assets.map((asset) => [asset.id, asset] as const)+ )+ )+ );+ try {+ const { skippedInvalidAssetIds } =+ await rewriteTransferredDocumentAssetReferences({+ sourceOrigin,+ projectId,+ sourceAssets: Array.from(sourceAssets.values()),+ sourceAssetPaths: assetPaths,+ importedAssets: transferred.assets,+ });+ if (skippedInvalidAssetIds.length > 0) {+ toast.warn(+ "Some invalid content files were copied unchanged. Open them to review their diagnostics."+ );+ }+ } catch {+ return {+ success: false,+ error:+ "Could not update Asset references in the copied content files.",+ } as const;+ }+ }+ if ($project.get()?.id !== projectId) {+ return {+ success: false,+ error: "Project changed while pasting.",+ } as const;+ }item = remapPageTransferAssets(item,transferred.fragments,@@ -384,3 +583,5 @@ export const pageText: Plugin = {onCopy: handleCopyPage,onPaste: (clipboardData) => handlePastePage(clipboardData),};++export const __testing__ = { preparePageTransferItem };diff --git a/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsxindex eda8e33b45..67fe604dc5 100644--- a/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx+++ b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx@@ -1103,7 +1103,7 @@ test("CodeBlock", async () => {},});- equalFragment(fragment, <$.CodeText lang="javascript" code="test" />);+ equalFragment(fragment, <$.CodeText lang="javascript">test</$.CodeText>);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {w-code-block {@@ -1988,7 +1988,10 @@ test("FormBlockLabel", async () => {},});- equalFragment(fragment, <$.Label htmlFor="email">Email Address</$.Label>);+ equalFragment(+ fragment,+ <$.Label {...{ for: "email" }}>Email Address</$.Label>+ );expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {label {@@ -2122,7 +2125,10 @@ test("FormBlockLabel", async () => {},});- equalFragment(fragment, <$.Label htmlFor="email">Email Address</$.Label>);+ equalFragment(+ fragment,+ <$.Label {...{ for: "email" }}>Email Address</$.Label>+ );expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {label {diff --git a/apps/builder/app/shared/db/canvas.server.ts b/apps/builder/app/shared/db/canvas.server.tsindex 7da2d41da8..13e1ac5cdc 100644--- a/apps/builder/app/shared/db/canvas.server.ts+++ b/apps/builder/app/shared/db/canvas.server.ts@@ -7,7 +7,14 @@ import {loadBuildById,loadDevBuildByProjectId,} from "@webstudio-is/project-build/server";-import { createBuildContentCompilationPlan } from "@webstudio-is/project-build";+import {+ createBuildContentCompilationPlan,+ createPublishedBuildContentCompilationPlan,+ getDynamicPublishedMdxSourceBlockIds,+ getPublishedMdxContentDatabaseMaxBytes,+ resolvePublishedMdxDependencyClosure,+ resolvePublishedMdxAssetCandidates,+} from "@webstudio-is/project-build";import { collectFontFamiliesFromStyleDecls } from "@webstudio-is/project-build/runtime";import {loadAssetDataByProject,@@ -21,7 +28,10 @@ import {type Asset,type AssetFolder,} from "@webstudio-is/sdk";-import { serializePages } from "@webstudio-is/project-migrations/pages";+import {+ migratePages,+ serializePages,+} from "@webstudio-is/project-migrations/pages";import { loadById } from "@webstudio-is/project/index.server";import { getUserById } from "./user.server";import { createAssetClient } from "../asset-client";@@ -160,7 +170,28 @@ const addProjectMetadata = async (? undefined: await getUserById(context, project.userId);- const assetRequirements = createBuildContentCompilationPlan(data.build);+ const publicationBuild = {+ ...data.build,+ pages: migratePages(data.build.pages),+ };+ const dynamicBlockIds =+ getDynamicPublishedMdxSourceBlockIds(publicationBuild);+ const projectCandidates = resolvePublishedMdxAssetCandidates({+ build: publicationBuild,+ allowUnresolved: true,+ });+ const needsCandidateDiscovery = dynamicBlockIds.some(+ (blockId) => projectCandidates.has(blockId) === false+ );+ const candidateDiscoveryPlan = needsCandidateDiscovery+ ? createBuildContentCompilationPlan(data.build)+ : undefined;+ const assetRequirements =+ candidateDiscoveryPlan ??+ createPublishedBuildContentCompilationPlan(+ publicationBuild,+ projectCandidates+ );let assetIndex: PublishedProjectBundle["assetIndex"];let publishedAssets = data.assets;let publishedAssetFolders = data.assetFolders;@@ -169,11 +200,27 @@ const addProjectMetadata = async (projectId: project.id,context,assetStore: createAssetClient(),- contentDatabaseMaxBytes: getContentDatabaseMaxBytes(),+ contentDatabaseMaxBytes: getPublishedMdxContentDatabaseMaxBytes({+ baseBytes: getContentDatabaseMaxBytes(),+ assets: data.assets,+ }),plan: assetRequirements,retainedAssetIds: data.assets.filter((asset) => asset.type === "font").map((asset) => asset.id),+ ...(assetRequirements.queries.some(({ id }) =>+ id.startsWith("__content-block-mdx__:")+ ) || candidateDiscoveryPlan !== undefined+ ? {+ resolvePlan: async (+ artifact: NonNullable<PublishedProjectBundle["assetIndex"]>+ ) =>+ (await resolvePublishedMdxDependencyClosure({+ build: publicationBuild,+ artifact,+ }))!,+ }+ : {}),});assetIndex = publishedAssetData.artifact;publishedAssets = publishedAssetData.assets;diff --git a/apps/builder/app/shared/external-content-mutations.test.ts b/apps/builder/app/shared/external-content-mutations.test.tsnew file mode 100644index 0000000000..93157fb7cd--- /dev/null+++ b/apps/builder/app/shared/external-content-mutations.test.ts@@ -0,0 +1,170 @@+import { describe, expect, test } from "vitest";+import type { BuilderPatchChange } from "@webstudio-is/project-build/contracts";+import { elementComponent, type Instance, type Prop } from "@webstudio-is/sdk";+import {+ isExternalContentInstance,+ isExternalContentMutation,+} from "./external-content-mutations";++const instance = (+ id: string,+ children: Instance["children"] = []+): Instance => ({+ type: "instance",+ id,+ component: elementComponent,+ tag: "div",+ children,+});++const state = {+ instances: new Map([+ ["block", instance("block", [{ type: "id", value: "external" }])],+ ["external", instance("external")],+ ["ordinary", instance("ordinary")],+ ]),+ props: new Map<string, Prop>([+ [+ "external-prop",+ {+ id: "external-prop",+ instanceId: "external",+ name: "title",+ type: "string",+ value: "Before",+ },+ ],+ ]),+};++const change = (+ namespace: BuilderPatchChange["namespace"],+ patches: BuilderPatchChange["patches"]+): BuilderPatchChange => ({ namespace, patches });++describe("external content mutation detection", () => {+ const roots = new Map([+ [+ "scope",+ {+ blockInstanceId: "block",+ instanceIds: new Set(["external"]),+ ownership: {+ instances: new Set(["external"]),+ props: new Set(["external-prop"]),+ styles: new Set(["external:base:color"]),+ },+ mutationRevision: 0,+ },+ ],+ ]);++ test("detects edits to existing external instances and props", () => {+ expect(+ isExternalContentMutation({+ state,+ roots,+ payload: [+ change("instances", [+ {+ op: "replace",+ path: ["external", "children"],+ value: [{ type: "text", value: "After" }],+ },+ ]),+ ],+ })+ ).toBe(true);+ expect(+ isExternalContentMutation({+ state,+ roots,+ payload: [+ change("props", [+ {+ op: "replace",+ path: ["external-prop", "value"],+ value: "After",+ },+ ]),+ ],+ })+ ).toBe(true);+ });++ test("detects insertion into an empty connected block", () => {+ expect(+ isExternalContentMutation({+ state,+ roots,+ payload: [+ change("instances", [+ {+ op: "replace",+ path: ["block", "children"],+ value: [{ type: "id", value: "inserted" }],+ },+ {+ op: "add",+ path: ["inserted"],+ value: instance("inserted"),+ },+ ]),+ ],+ })+ ).toBe(true);+ });++ test("detects edits to every registered external namespace", () => {+ expect(+ isExternalContentMutation({+ state,+ roots,+ payload: [+ change("styles", [+ {+ op: "replace",+ path: ["external:base:color", "value"],+ value: { type: "keyword", value: "red" },+ },+ ]),+ ],+ })+ ).toBe(true);+ });++ test("does not reroute unrelated project mutations", () => {+ expect(+ isExternalContentMutation({+ state,+ roots,+ payload: [+ change("instances", [+ {+ op: "replace",+ path: ["ordinary", "children"],+ value: [{ type: "text", value: "After" }],+ },+ ]),+ ],+ })+ ).toBe(false);+ });+});++test("identifies only instances authored by external content", () => {+ const roots = new Map([+ [+ "scope",+ {+ blockInstanceId: "block",+ instanceIds: new Set(["external"]),+ mutationRevision: 0,+ },+ ],+ ]);++ expect(isExternalContentInstance(roots, "external")).toBe(true);+ expect(isExternalContentInstance(roots, "block")).toBe(false);+ expect(isExternalContentInstance(roots, "ordinary")).toBe(false);+});diff --git a/apps/builder/app/shared/external-content-mutations.ts b/apps/builder/app/shared/external-content-mutations.tsnew file mode 100644index 0000000000..1257509e7f--- /dev/null+++ b/apps/builder/app/shared/external-content-mutations.ts@@ -0,0 +1,364 @@+import type { BuilderPatchChange } from "@webstudio-is/project-build/contracts";+import type { BuilderState } from "@webstudio-is/project-build/state";+import type {+ ContentBlockExternalContentIdentity,+ ContentBlockDiagnostic,+ Instance,+ Instances,+ Prop,+} from "@webstudio-is/sdk";+import { blockBodyComponent, blockComponent } from "@webstudio-is/sdk";+import type { InstanceSelector } from "@webstudio-is/project-build/runtime";+import type { MdxDocument } from "@webstudio-is/content-engine/mdx";+import { atom } from "nanostores";+import type { ExternalContentOwnership } from "./external-content-persistence";++export type ExternalContentRoot = {+ sourceBlockInstanceId?: Instance["id"];+ sourceRenderScope?: string;+ blockInstanceId: Instance["id"];+ sourceContentInstanceId?: Instance["id"];+ /** Instance whose children are persisted as document.body. */+ contentInstanceId?: Instance["id"];+ renderScope?: string;+ instanceIds: ReadonlySet<Instance["id"]>;+ propIds?: ReadonlySet<Prop["id"]>;+ ownership?: ExternalContentOwnership;+ mutationRevision: number;+ projectId?: string;+ identity?: ContentBlockExternalContentIdentity;+ diagnostics?: readonly ContentBlockDiagnostic[];+ document?: MdxDocument;+ frontmatter?: Readonly<Record<string, unknown>>;+ transientInstanceIds?: ReadonlySet<Instance["id"]>;+};++export const findExternalContentRoot = (+ roots: ReadonlyMap<string, ExternalContentRoot>,+ sourceBlockInstanceId: Instance["id"],+ renderScope: string+) => {+ for (const root of roots.values()) {+ if (+ (root.sourceBlockInstanceId ?? root.blockInstanceId) ===+ sourceBlockInstanceId &&+ (root.sourceRenderScope ?? root.renderScope) === renderScope+ ) {+ return root;+ }+ }+};++export const findExternalContentRootEntryBySelector = (+ roots: ReadonlyMap<string, ExternalContentRoot>,+ selector: InstanceSelector+) => {+ let closest:+ | readonly [key: string, root: ExternalContentRoot, blockIndex: number]+ | undefined;+ for (const [key, root] of roots) {+ let blockIndex = selector.indexOf(root.blockInstanceId);+ if (blockIndex === -1 && root.sourceBlockInstanceId !== undefined) {+ blockIndex = selector.indexOf(root.sourceBlockInstanceId);+ }+ if (+ blockIndex !== -1 &&+ (closest === undefined || blockIndex < closest[2])+ ) {+ closest = [key, root, blockIndex];+ }+ }+ return closest === undefined+ ? undefined+ : ([closest[0], closest[1]] as const);+};++export const resolveExternalContentOccurrence = ({+ sourceInstance,+ sourceSelector,+ instances,+ roots,+}: {+ sourceInstance: Instance;+ sourceSelector: InstanceSelector;+ instances: Instances;+ roots: ReadonlyMap<string, ExternalContentRoot>;+}) => {+ if (+ sourceInstance.component !== blockComponent &&+ sourceInstance.component !== blockBodyComponent+ ) {+ return;+ }+ const root =+ sourceInstance.component === blockComponent+ ? findExternalContentRoot(+ roots,+ sourceInstance.id,+ JSON.stringify(sourceSelector)+ )+ : Array.from(roots.values()).find(+ (root) =>+ root.sourceContentInstanceId === sourceInstance.id &&+ sourceSelector.includes(root.blockInstanceId)+ );+ const occurrenceInstanceId =+ sourceInstance.component === blockBodyComponent+ ? root?.contentInstanceId+ : root?.blockInstanceId;+ const instance =+ occurrenceInstanceId === undefined+ ? undefined+ : instances.get(occurrenceInstanceId);+ if (instance === undefined) {+ return;+ }+ return {+ instance,+ selector: [instance.id, ...sourceSelector.slice(1)] as InstanceSelector,+ };+};++export const getExternalContentSourceSelector = ({+ selector,+ roots,+}: {+ selector: InstanceSelector;+ roots: ReadonlyMap<string, ExternalContentRoot>;+}) => {+ for (const root of roots.values()) {+ const sourceId = root.sourceBlockInstanceId;+ if (sourceId === undefined || sourceId === root.blockInstanceId) {+ continue;+ }+ const blockIndex = selector.indexOf(root.blockInstanceId);+ if (blockIndex !== -1) {+ return {+ contentSelector: selector.slice(0, blockIndex + 1),+ sourceSelector: [sourceId, ...selector.slice(blockIndex + 1)],+ };+ }+ }+};++export const $externalContentRoots = atom(+ new Map<string, ExternalContentRoot>()+);+const mutationListeners = new Set<(rootKeys: readonly string[]) => void>();+const observedMutationRevisions = new Map<string, number>();++$externalContentRoots.listen((roots) => {+ const changedRootKeys: string[] = [];+ for (const [key, root] of roots) {+ const previousRevision = observedMutationRevisions.get(key);+ observedMutationRevisions.set(key, root.mutationRevision);+ if (+ previousRevision !== undefined &&+ root.mutationRevision > previousRevision+ ) {+ changedRootKeys.push(key);+ }+ }+ for (const key of observedMutationRevisions.keys()) {+ if (roots.has(key) === false) {+ observedMutationRevisions.delete(key);+ }+ }+ if (changedRootKeys.length > 0) {+ for (const listener of mutationListeners) {+ listener(changedRootKeys);+ }+ }+});++export const registerExternalContentRoot = (+ key: string,+ root: ExternalContentRoot+) => {+ const current = $externalContentRoots.get();+ const registeredRoot = {+ ...root,+ mutationRevision: current.get(key)?.mutationRevision ?? 0,+ };+ $externalContentRoots.set(new Map(current).set(key, registeredRoot));+ return () => {+ const roots = $externalContentRoots.get();+ if (roots.get(key) === registeredRoot) {+ const nextRoots = new Map(roots);+ nextRoots.delete(key);+ $externalContentRoots.set(nextRoots);+ }+ };+};++export const getExternalContentRoots = () => $externalContentRoots.get();++export const isExternalContentInstance = (+ roots: ReadonlyMap<string, ExternalContentRoot>,+ instanceId: Instance["id"]+) => {+ for (const { instanceIds } of roots.values()) {+ if (instanceIds.has(instanceId)) {+ return true;+ }+ }+ return false;+};++export const externalContentInstanceNameMessage =+ "Names cannot be edited for MDX content.";++export const subscribeExternalContentMutations = (+ listener: (rootKeys: readonly string[]) => void+) => {+ mutationListeners.add(listener);+ return () => mutationListeners.delete(listener);+};++export const publishExternalContentMutation = (rootKeys: readonly string[]) => {+ if (rootKeys.length === 0) {+ return;+ }+ const roots = $externalContentRoots.get();+ const nextRoots = new Map(roots);+ let changed = false;+ for (const key of rootKeys) {+ const root = roots.get(key);+ if (root !== undefined) {+ root.mutationRevision += 1;+ changed = true;+ }+ }+ if (changed) {+ $externalContentRoots.set(nextRoots);+ }+};++export const getAffectedExternalContentRootKeys = ({+ state,+ roots,+ payload,+}: {+ state: ExternalContentMutationState;+ roots: ReadonlyMap<string, ExternalContentRoot>;+ payload: readonly BuilderPatchChange[];+}) =>+ Array.from(roots)+ .filter(([, root]) => doesMutationAffectRoot({ state, root, payload }))+ .map(([key]) => key);++type ExternalContentMutationState = {+ instances: NonNullable<BuilderState["instances"]>;+ props?: BuilderState["props"];+};++const getPatchId = (patch: BuilderPatchChange["patches"][number]) => {+ const [id] = patch.path;+ return typeof id === "string" ? id : undefined;+};++const affectsRootInstances = ({+ root,+ change,+}: {+ root: ExternalContentRoot;+ change: BuilderPatchChange;+}) => {+ for (const patch of change.patches) {+ const id = getPatchId(patch);+ if (id === undefined) {+ continue;+ }+ if (root.instanceIds.has(id)) {+ return true;+ }+ if (+ id === (root.contentInstanceId ?? root.blockInstanceId) &&+ patch.path[1] === "children"+ ) {+ return true;+ }+ if (+ patch.op !== "remove" &&+ patch.path.length === 1 &&+ typeof patch.value === "object" &&+ patch.value !== null &&+ "instanceId" in patch.value &&+ root.instanceIds.has(String(patch.value.instanceId))+ ) {+ return true;+ }+ }+ return false;+};++const affectsRootProps = ({+ state,+ root,+ change,+}: {+ state: ExternalContentMutationState;+ root: ExternalContentRoot;+ change: BuilderPatchChange;+}) => {+ for (const patch of change.patches) {+ const id = getPatchId(patch);+ if (id === undefined) {+ continue;+ }+ const existing = state.props?.get(id);+ const added =+ patch.op !== "remove" &&+ patch.path.length === 1 &&+ typeof patch.value === "object" &&+ patch.value !== null &&+ "instanceId" in patch.value+ ? patch.value+ : undefined;+ if (+ root.propIds?.has(id) ||+ (existing !== undefined && root.instanceIds.has(existing.instanceId)) ||+ (added !== undefined && root.instanceIds.has(String(added.instanceId)))+ ) {+ return true;+ }+ }+ return false;+};++const doesMutationAffectRoot = ({+ state,+ root,+ payload,+}: {+ state: ExternalContentMutationState;+ root: ExternalContentRoot;+ payload: readonly BuilderPatchChange[];+}) =>+ payload.some((change) => {+ if (change.namespace === "instances") {+ return affectsRootInstances({ root, change });+ }+ if (change.namespace === "props") {+ return affectsRootProps({ state, root, change });+ }+ const ownedIds =+ root.ownership?.[change.namespace as keyof ExternalContentOwnership];+ return change.patches.some((patch) => {+ const id = getPatchId(patch);+ return id !== undefined && ownedIds?.has(id) === true;+ });+ });++export const isExternalContentMutation = ({+ state,+ roots,+ payload,+}: {+ state: ExternalContentMutationState;+ roots: ReadonlyMap<string, ExternalContentRoot>;+ payload: readonly BuilderPatchChange[];+}) =>+ Array.from(roots.values()).some((root) =>+ doesMutationAffectRoot({ state, root, payload })+ );diff --git a/apps/builder/app/shared/external-content-persistence.test.ts b/apps/builder/app/shared/external-content-persistence.test.tsnew file mode 100644index 0000000000..735341f235--- /dev/null+++ b/apps/builder/app/shared/external-content-persistence.test.ts@@ -0,0 +1,106 @@+import { expect, test } from "vitest";+import type { BuilderPatchChange } from "@webstudio-is/project-build/contracts";+import type { BuilderState } from "@webstudio-is/project-build/state";+import { createExternalContentPersistencePlan } from "./external-content-persistence";++const instance = (id: string) => ({+ type: "instance" as const,+ id,+ component: "ws:element",+ tag: "div",+ children: [],+});++const state = (ids: string[]): BuilderState => ({+ instances: new Map(ids.map((id) => [id, instance(id)])),+ props: new Map(),+});++const change = (+ patches: BuilderPatchChange["patches"]+): BuilderPatchChange => ({ namespace: "instances", patches });++test("moves an external instance into project persistence", () => {+ const before = state(["external", "ordinary-parent"]);+ const after = state(["external", "ordinary-parent"]);+ const plan = createExternalContentPersistencePlan({+ beforeData: before,+ afterData: after,+ beforeOwnership: { instances: new Set(["external"]) },+ afterOwnership: { instances: new Set() },+ payload: [+ change([+ {+ op: "add",+ path: ["ordinary-parent", "children", 0],+ value: { type: "id", value: "external" },+ },+ ]),+ ],+ });++ expect(plan.preliminaryExternalPayload).toEqual([+ change([{ op: "remove", path: ["external"] }]),+ ]);+ expect(plan.projectPayload).toEqual([+ change([+ { op: "add", path: ["external"], value: instance("external") },+ {+ op: "add",+ path: ["ordinary-parent", "children", 0],+ value: { type: "id", value: "external" },+ },+ ]),+ ]);+ expect(plan.externalPayload).toEqual([]);+});++test("removes an ordinary instance from project persistence when it enters an external root", () => {+ const before = state(["ordinary"]);+ const after = state(["ordinary"]);+ const plan = createExternalContentPersistencePlan({+ beforeData: before,+ afterData: after,+ beforeOwnership: { instances: new Set() },+ afterOwnership: { instances: new Set(["ordinary"]) },+ payload: [],+ });++ expect(plan.projectPayload).toEqual([+ change([{ op: "remove", path: ["ordinary"] }]),+ ]);+ expect(plan.externalPayload).toEqual([+ change([{ op: "add", path: ["ordinary"], value: instance("ordinary") }]),+ ]);+});++test("keeps connected Content Block children in memory-only persistence", () => {+ const before = state(["block"]);+ const after = state(["block", "paragraph"]);+ const childrenPatch = {+ op: "replace" as const,+ path: ["block", "children"],+ value: [{ type: "id", value: "paragraph" }],+ };+ const plan = createExternalContentPersistencePlan({+ beforeData: before,+ afterData: after,+ beforeOwnership: { instances: new Set() },+ afterOwnership: { instances: new Set(["paragraph"]) },+ externalBlockInstanceIds: new Set(["block"]),+ payload: [+ change([+ childrenPatch,+ { op: "add", path: ["paragraph"], value: instance("paragraph") },+ ]),+ ],+ });++ expect(plan.projectPayload).toEqual([]);+ expect(plan.externalPayload).toEqual([+ change([+ childrenPatch,+ { op: "add", path: ["paragraph"], value: instance("paragraph") },+ ]),+ ]);+});diff --git a/apps/builder/app/shared/external-content-persistence.ts b/apps/builder/app/shared/external-content-persistence.tsnew file mode 100644index 0000000000..60ed4d4614--- /dev/null+++ b/apps/builder/app/shared/external-content-persistence.ts@@ -0,0 +1,253 @@+import type { BuilderPatchChange } from "@webstudio-is/project-build/contracts";+import type { BuilderState } from "@webstudio-is/project-build/state";+import {+ createWebstudioDataFromFragment,+ extractWebstudioFragment,+ mergeWebstudioFragments,+} from "@webstudio-is/project-build/runtime";+import {+ blockTemplateComponent,+ type WebstudioData,+ type WebstudioFragment,+} from "@webstudio-is/sdk";+import type { ExternalContentRoot } from "./external-content-mutations";++export const externalContentNamespaces = [+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+] as const;++type ExternalNamespace = (typeof externalContentNamespaces)[number];+export type ExternalContentOwnership = Partial<+ Record<ExternalNamespace, ReadonlySet<string>>+>;+type CompleteExternalContentOwnership = Record<+ ExternalNamespace,+ ReadonlySet<string>+>;++export const getExternalContentFragmentRecords = (+ fragment: WebstudioFragment+): ReadonlyArray<+ readonly [+ ExternalNamespace,+ readonly Readonly<{ key: string; value: unknown }>[],+ ]+> => {+ const data = createWebstudioDataFromFragment(fragment);+ return externalContentNamespaces.map((namespace) => [+ namespace,+ Array.from(+ data[namespace] as ReadonlyMap<string, unknown>,+ ([key, value]) => ({ key, value })+ ),+ ]);+};++export const getExternalContentFragmentOwnership = (+ fragment: WebstudioFragment+): CompleteExternalContentOwnership => {+ const ownership = {} as CompleteExternalContentOwnership;+ for (const [namespace, records] of getExternalContentFragmentRecords(+ fragment+ )) {+ ownership[namespace] = new Set(records.map(({ key }) => key));+ }+ return ownership;+};++const mergeExternalContentOwnership = (+ ownershipValues: Iterable<ExternalContentOwnership>+): ExternalContentOwnership => {+ const merged: Record<string, Set<string>> = {};+ for (const ownership of ownershipValues) {+ for (const namespace of externalContentNamespaces) {+ const ids = ownership[namespace];+ if (ids === undefined) {+ continue;+ }+ const mergedIds = merged[namespace] ?? new Set<string>();+ for (const id of ids) {+ mergedIds.add(id);+ }+ merged[namespace] = mergedIds;+ }+ }+ return merged as ExternalContentOwnership;+};++const getRegisteredRootOwnership = (+ root: ExternalContentRoot+): ExternalContentOwnership =>+ root.ownership ?? {+ instances: root.instanceIds,+ ...(root.propIds === undefined ? {} : { props: root.propIds }),+ };++export const getExternalContentOwnership = (+ roots: ReadonlyMap<string, ExternalContentRoot>+): ExternalContentOwnership =>+ mergeExternalContentOwnership(+ Array.from(roots.values(), getRegisteredRootOwnership)+ );++export const getExternalContentOwnershipFromState = ({+ state,+ roots,+ rootKeys,+}: {+ state: Omit<WebstudioData, "pages">;+ roots: ReadonlyMap<string, ExternalContentRoot>;+ rootKeys?: ReadonlySet<string>;+}): ExternalContentOwnership => {+ const selectedRoots = Array.from(roots).filter(+ ([key]) => rootKeys === undefined || rootKeys.has(key)+ );+ const rootIds = selectedRoots.flatMap(([, root]) =>+ (+ state.instances.get(root.contentInstanceId ?? root.blockInstanceId)+ ?.children ?? []+ ).flatMap((child) =>+ child.type === "id" &&+ state.instances.get(child.value)?.component !== blockTemplateComponent+ ? [child.value]+ : []+ )+ );+ const fragment = mergeWebstudioFragments(+ rootIds,+ rootIds.map((id) => extractWebstudioFragment(state, id))+ );+ const selectedOwnership = getExternalContentFragmentOwnership(fragment);+ if (rootKeys === undefined) {+ return selectedOwnership;+ }+ const retainedOwnership = mergeExternalContentOwnership(+ Array.from(roots)+ .filter(([key]) => rootKeys.has(key) === false)+ .map(([, root]) => getRegisteredRootOwnership(root))+ );+ return mergeExternalContentOwnership([retainedOwnership, selectedOwnership]);+};++const getRecords = (state: BuilderState, namespace: ExternalNamespace) =>+ state[namespace] as ReadonlyMap<string, unknown> | undefined;++const addPatch = (+ changes: Map<BuilderPatchChange["namespace"], BuilderPatchChange>,+ namespace: BuilderPatchChange["namespace"],+ patch: BuilderPatchChange["patches"][number]+) => {+ const change = changes.get(namespace) ?? { namespace, patches: [] };+ change.patches.push(patch);+ changes.set(namespace, change);+};++const toPayload = (+ changes: Map<BuilderPatchChange["namespace"], BuilderPatchChange>+) => Array.from(changes.values()).filter(({ patches }) => patches.length > 0);++export const createExternalContentPersistencePlan = ({+ beforeData,+ afterData,+ beforeOwnership,+ afterOwnership,+ externalBlockInstanceIds = new Set(),+ payload,+}: {+ beforeData: BuilderState;+ afterData: BuilderState;+ beforeOwnership: ExternalContentOwnership;+ afterOwnership: ExternalContentOwnership;+ externalBlockInstanceIds?: ReadonlySet<string>;+ payload: readonly BuilderPatchChange[];+}) => {+ const preliminaryExternal = new Map<+ BuilderPatchChange["namespace"],+ BuilderPatchChange+ >();+ const project = new Map<+ BuilderPatchChange["namespace"],+ BuilderPatchChange+ >();+ const external = new Map<+ BuilderPatchChange["namespace"],+ BuilderPatchChange+ >();++ for (const namespace of externalContentNamespaces) {+ const beforeIds = beforeOwnership[namespace] ?? new Set();+ const afterIds = afterOwnership[namespace] ?? new Set();+ const beforeRecords = getRecords(beforeData, namespace);+ const afterRecords = getRecords(afterData, namespace);++ for (const id of beforeIds) {+ if (afterIds.has(id) || afterRecords?.has(id) === false) {+ continue;+ }+ const value = afterRecords?.get(id);+ if (value === undefined) {+ continue;+ }+ addPatch(preliminaryExternal, namespace, { op: "remove", path: [id] });+ addPatch(project, namespace, { op: "add", path: [id], value });+ }++ for (const id of afterIds) {+ if (beforeIds.has(id) || beforeRecords?.has(id) === false) {+ continue;+ }+ const value = afterRecords?.get(id);+ if (value === undefined) {+ continue;+ }+ addPatch(project, namespace, { op: "remove", path: [id] });+ addPatch(external, namespace, { op: "add", path: [id], value });+ }+ }++ for (const change of payload) {+ const namespace = change.namespace;+ const isExternalNamespace = externalContentNamespaces.some(+ (candidate) => candidate === namespace+ );+ for (const patch of change.patches) {+ const [id] = patch.path;+ if (isExternalNamespace === false || typeof id !== "string") {+ addPatch(project, namespace, patch);+ continue;+ }+ const externalNamespace = namespace as ExternalNamespace;+ if (+ namespace === "instances" &&+ externalBlockInstanceIds.has(id) &&+ patch.path[1] === "children"+ ) {+ addPatch(external, namespace, patch);+ continue;+ }+ const beforeIds = beforeOwnership[externalNamespace] ?? new Set();+ const afterIds = afterOwnership[externalNamespace] ?? new Set();+ const afterRecords = getRecords(afterData, externalNamespace);+ if (+ afterIds.has(id) ||+ (beforeIds.has(id) && afterRecords?.has(id) === false)+ ) {+ addPatch(external, namespace, patch);+ } else {+ addPatch(project, namespace, patch);+ }+ }+ }++ return {+ preliminaryExternalPayload: toPayload(preliminaryExternal),+ projectPayload: toPayload(project),+ externalPayload: toPayload(external),+ };+};diff --git a/apps/builder/app/shared/external-content-roots.test.ts b/apps/builder/app/shared/external-content-roots.test.tsnew file mode 100644index 0000000000..a94fb97c62--- /dev/null+++ b/apps/builder/app/shared/external-content-roots.test.ts@@ -0,0 +1,1539 @@+import { afterEach, expect, test, vi } from "vitest";+import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session";+import { createDefaultPages } from "@webstudio-is/project-build";+import {+ blockBodyComponent,+ blockComponent,+ blockTemplateComponent,+ type Asset,+ type Instance,+} from "@webstudio-is/sdk";+import {+ createAssetContentBridge,+ initAssetContentBridge,+} from "./asset-content-bridge.client";+import {+ acquireExternalContentRoot,+ disposeExternalContentProject,+ flushExternalContentAsset,+ flushExternalContentProject,+ getExternalContentRootAssets,+ getExternalContentRootSnapshot,+ getExternalContentRootChildren,+ replaceExternalContentAssetSource,+ retryExternalContentAsset,+ subscribeExternalContentAsset,+ updateExternalContentAssetSource,+ updateExternalContentFrontmatter,+} from "./external-content-roots";+import { executeRuntimeMutation } from "./instance-utils/data";+import { selectInstance } from "./nano-states";+import {+ findExternalContentRoot,+ getExternalContentRoots,+ resolveExternalContentOccurrence,+} from "./external-content-mutations";+import {+ $assets,+ $breakpoints,+ $dataSources,+ $instances,+ $pages,+ $project,+ $projectSettings,+ $props,+ $resources,+ $styleSourceSelections,+ $styleSources,+ $styles,+} from "./sync/data-stores";+import {+ externalContentSyncStore,+ registerContainers,+ serverSyncStore,+} from "./sync/sync-stores";++registerContainers();++test("places unresolved-template placeholders at their authored nesting point", async () => {+ const source =+ '<ws.element ws:tag="section">Before<ws.element ws:name="Missing" />After</ws.element>';+ const sourceAsset = {+ ...asset,+ size: new TextEncoder().encode(source).byteLength,+ };+ const session = createAssetContentSession({+ repository: {+ readContent: async () => ({+ asset: sourceAsset,+ data: (async function* () {+ yield new TextEncoder().encode(source);+ })(),+ }),+ updateContent: async () => sourceAsset,+ },+ authorize: () => true,+ });+ sessions.push(session);+ initAssetContentBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload: vi.fn(),+ getContentSession: () => session,+ })+ );+ $project.set({ id: "project", title: "Project", domain: "" } as never);+ $pages.set(createDefaultPages({ rootInstanceId: "block" }));+ $instances.set(new Map([["block", instance("block", blockComponent, [])]]));+ $props.set(new Map());+ $assets.set(new Map([[sourceAsset.id, sourceAsset]]));+ $breakpoints.set(new Map());+ $dataSources.set(new Map());+ $resources.set(new Map());+ $styleSources.set(new Map());+ $styleSourceSelections.set(new Map());+ $styles.set(new Map());+ $projectSettings.set({ meta: {}, compiler: {} });++ releases.push(+ await acquireExternalContentRoot({+ projectId: "project",+ assetId: sourceAsset.id,+ blockInstanceId: "block",+ renderScope: '["block"]',+ })+ );++ const section = Array.from($instances.get().values()).find(+ (candidate) => candidate.tag === "section"+ );+ const missing = Array.from($instances.get().values()).find(+ (candidate) => candidate.label === "Missing template: Missing"+ );+ expect(missing).toMatchObject({+ component: "ws:element",+ tag: "div",+ children: [{ type: "text", value: "Missing template: Missing" }],+ });+ if (section === undefined || missing === undefined) {+ throw new Error("Expected the section and missing-template placeholder");+ }+ expect(section.children).toEqual([+ { type: "text", value: "Before" },+ { type: "id", value: missing.id },+ { type: "text", value: "After" },+ ]);+ expect(+ getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })+ ).toEqual([{ type: "id", value: section.id }]);+});++const asset: Asset = {+ id: "asset",+ projectId: "project",+ name: "article_v1.mdx",+ type: "file",+ format: "mdx",+ size: 7,+ createdAt: "2026-01-01T00:00:00.000Z",+ description: null,+ meta: {},+};++const instance = (+ id: string,+ component: string,+ children: Instance["children"]+): Instance => ({ type: "instance", id, component, children });++const releases: Array<() => void> = [];+const sessions: Array<ReturnType<typeof createAssetContentSession>> = [];++afterEach(() => {+ for (const release of releases.splice(0)) {+ release();+ }+ for (const session of sessions.splice(0)) {+ session.dispose();+ }+});++test("rejects a stale raw editor replacement behind a newer queued edit", async () => {+ let continueCanvasEdit: (() => void) | undefined;+ const canvasEditGate = new Promise<void>((resolve) => {+ continueCanvasEdit = resolve;+ });+ const session = createAssetContentSession({+ repository: {+ readContent: async () => ({+ asset,+ data: (async function* () {+ yield new TextEncoder().encode("# Hello");+ })(),+ }),+ updateContent: async () => asset,+ },+ authorize: () => true,+ });+ sessions.push(session);+ const requireReload = vi.fn();+ initAssetContentBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload,+ getContentSession: () => session,+ })+ );+ await session.open(asset.id);++ const canvasEdit = updateExternalContentAssetSource({+ projectId: "project",+ assetId: asset.id,+ update: async () => {+ await canvasEditGate;+ return "# Canvas";+ },+ });+ const staleEditorEdit = replaceExternalContentAssetSource({+ projectId: "project",+ assetId: asset.id,+ expectedSource: "# Hello",+ source: "# Editor",+ });++ continueCanvasEdit?.();+ await canvasEdit;+ await expect(staleEditorEdit).rejects.toThrow(+ "The MDX content source changed before the file edit was saved."+ );+ expect(session.get(asset.id)?.source).toBe("# Canvas");+ expect(requireReload).toHaveBeenCalledOnce();+});++test("rebases frontmatter edits from Content Blocks sharing one Asset", async () => {+ const initialSource = "---\ntitle: Before\n---\n\n# Article\n";+ const initialAsset = {+ ...asset,+ size: new TextEncoder().encode(initialSource).byteLength,+ };+ const writes: string[] = [];+ const session = createAssetContentSession({+ repository: {+ readContent: async () => ({+ asset: initialAsset,+ data: (async function* () {+ yield new TextEncoder().encode(initialSource);+ })(),+ }),+ updateContent: async ({ data }) => {+ const source = await new Response(data).text();+ writes.push(source);+ return {+ ...initialAsset,+ size: new TextEncoder().encode(source).byteLength,+ };+ },+ },+ authorize: () => true,+ debounceMilliseconds: 0,+ });+ sessions.push(session);+ initAssetContentBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload: vi.fn(),+ getContentSession: () => session,+ })+ );+ $project.set({ id: "project", title: "Project", domain: "" } as never);+ $pages.set(createDefaultPages({ rootInstanceId: "block" }));+ $instances.set(+ new Map([+ ["block", instance("block", blockComponent, [])],+ ["block-2", instance("block-2", blockComponent, [])],+ ])+ );+ $props.set(new Map());+ $assets.set(new Map([[initialAsset.id, initialAsset]]));+ $breakpoints.set(new Map());+ $dataSources.set(new Map());+ $resources.set(new Map());+ $styleSources.set(new Map());+ $styleSourceSelections.set(new Map());+ $styles.set(new Map());+ $projectSettings.set({ meta: {}, compiler: {} });++ releases.push(+ await acquireExternalContentRoot({+ projectId: "project",+ assetId: initialAsset.id,+ blockInstanceId: "block",+ renderScope: '["block"]',+ }),+ await acquireExternalContentRoot({+ projectId: "project",+ assetId: initialAsset.id,+ blockInstanceId: "block-2",+ renderScope: '["block-2"]',+ })+ );+ const entries = Array.from(getExternalContentRoots());+ const firstKey = entries.find(+ ([, root]) => root.sourceBlockInstanceId === "block"+ )?.[0];+ const secondKey = entries.find(+ ([, root]) => root.sourceBlockInstanceId === "block-2"+ )?.[0];+ if (firstKey === undefined || secondKey === undefined) {+ throw new Error("Expected both shared Content Block roots");+ }++ await Promise.all([+ updateExternalContentFrontmatter({+ rootKey: firstKey,+ path: ["title"],+ value: "After",+ }),+ updateExternalContentFrontmatter({+ rootKey: secondKey,+ path: ["excerpt"],+ value: "Summary",+ }),+ ]);+ await flushExternalContentAsset({+ projectId: "project",+ assetId: initialAsset.id,+ });++ expect(writes.at(-1)).toBe(+ "---\nexcerpt: Summary\ntitle: After\n---\n\n# Article\n"+ );+});++test("does not install an Asset load after its Content Block unmounts", async () => {+ let finishRead: (() => void) | undefined;+ const waitForRead = new Promise<void>((resolve) => {+ finishRead = resolve;+ });+ const session = createAssetContentSession({+ repository: {+ readContent: async () => {+ await waitForRead;+ return {+ asset,+ data: (async function* () {+ yield new TextEncoder().encode("# Stale");+ })(),+ };+ },+ updateContent: async () => asset,+ },+ authorize: () => true,+ });+ sessions.push(session);+ initAssetContentBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload: vi.fn(),+ getContentSession: () => session,+ })+ );+ $project.set({ id: "project", title: "Project", domain: "" } as never);+ $pages.set(createDefaultPages({ rootInstanceId: "block" }));+ $instances.set(new Map([["block", instance("block", blockComponent, [])]]));+ $props.set(new Map());+ $dataSources.set(new Map());+ $resources.set(new Map());+ $styleSources.set(new Map());+ $styleSourceSelections.set(new Map());+ $styles.set(new Map());+ $breakpoints.set(new Map());+ const controller = new AbortController();+ const opening = acquireExternalContentRoot({+ projectId: "project",+ assetId: asset.id,+ blockInstanceId: "block",+ renderScope: '["block"]',+ signal: controller.signal,+ });++ controller.abort();+ finishRead?.();+ releases.push(await opening);++ expect(+ getExternalContentRootSnapshot({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })+ ).toBeUndefined();+});++test("replaces a mounted root when its source Asset changes", async () => {+ const secondAsset: Asset = {+ ...asset,+ id: "second-asset",+ name: "second.mdx",+ size: new TextEncoder().encode("# Second").byteLength,+ };+ const session = createAssetContentSession({+ repository: {+ readContent: async ({ assetId }) => ({+ asset: assetId === asset.id ? asset : secondAsset,+ data: (async function* () {+ yield new TextEncoder().encode(+ assetId === asset.id ? "# First" : "# Second"+ );+ })(),+ }),+ updateContent: async ({ assetId }) =>+ assetId === asset.id ? asset : secondAsset,+ },+ authorize: () => true,+ });+ sessions.push(session);+ initAssetContentBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload: vi.fn(),+ getContentSession: () => session,+ })+ );+ $project.set({ id: "project", title: "Project", domain: "" } as never);+ $pages.set(createDefaultPages({ rootInstanceId: "block" }));+ $instances.set(new Map([["block", instance("block", blockComponent, [])]]));+ $props.set(new Map());+ $assets.set(+ new Map<Asset["id"], Asset>([+ [asset.id, asset],+ [secondAsset.id, secondAsset],+ ])+ );+ $dataSources.set(new Map());+ $resources.set(new Map());+ $styleSources.set(new Map());+ $styleSourceSelections.set(new Map());+ $styles.set(new Map());+ $breakpoints.set(new Map());+ $projectSettings.set({ meta: {}, compiler: {} });+ serverSyncStore.popAll();+ externalContentSyncStore.popAll();+ const renderScope = '["block"]';++ const releaseFirst = await acquireExternalContentRoot({+ projectId: "project",+ assetId: asset.id,+ blockInstanceId: "block",+ renderScope,+ });+ releaseFirst();+ const releaseSecond = await acquireExternalContentRoot({+ projectId: "project",+ assetId: secondAsset.id,+ blockInstanceId: "block",+ renderScope,+ });++ const child = getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope,+ })?.[0];+ expect(child?.type).toBe("id");+ expect(+ child?.type === "id"+ ? $instances.get().get(child.value)?.children+ : undefined+ ).toEqual([{ type: "text", value: "Second" }]);++ $instances.set(+ new Map($instances.get())+ .set("ordinary", instance("ordinary", "ws:element", []))+ .set("block", {+ ...$instances.get().get("block")!,+ children: [child!, { type: "id", value: "ordinary" }],+ })+ );+ releaseSecond();++ expect($instances.get().get("block")?.children).toEqual([+ { type: "id", value: "ordinary" },+ ]);+ expect($instances.get().has("ordinary")).toBe(true);+});++test("installs MDX into the Body and recovers an invalid dependency", async () => {+ const source = `---+author:+ $ref: ./author.md#frontmatter+---++# Article body`;+ const authorSource = `---+name: Ada+avatar:+ $ref: ./avatar.jpg+---+`;+ const invalidAuthorSource = `---+name: [+---+`;+ const authorAsset: Asset = {+ ...asset,+ id: "author",+ name: "author_v1.md",+ format: "md",+ size: new TextEncoder().encode(invalidAuthorSource).byteLength,+ };+ const avatarAsset: Asset = {+ id: "avatar",+ projectId: "project",+ name: "avatar_v1.jpg",+ type: "image",+ format: "jpg",+ size: 100,+ createdAt: "2026-01-01T00:00:00.000Z",+ description: null,+ meta: { width: 100, height: 100 },+ };+ const session = createAssetContentSession({+ repository: {+ readContent: async ({ assetId }) => ({+ asset:+ assetId === authorAsset.id+ ? authorAsset+ : { ...asset, size: new TextEncoder().encode(source).byteLength },+ data: (async function* () {+ yield new TextEncoder().encode(+ assetId === authorAsset.id ? invalidAuthorSource : source+ );+ })(),+ }),+ updateContent: async ({ assetId, data }) => {+ const updatedSource = await new Response(data).text();+ const currentAsset = assetId === authorAsset.id ? authorAsset : asset;+ return {+ ...currentAsset,+ size: new TextEncoder().encode(updatedSource).byteLength,+ };+ },+ },+ authorize: () => true,+ });+ sessions.push(session);+ initAssetContentBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload: vi.fn(),+ getContentSession: () => session,+ })+ );+ $project.set({ id: "project", title: "Project", domain: "" } as never);+ $pages.set(createDefaultPages({ rootInstanceId: "block" }));+ $instances.set(+ new Map([+ [+ "block",+ instance("block", blockComponent, [+ { type: "id", value: "header" },+ { type: "id", value: "body-outlet" },+ { type: "id", value: "footer" },+ { type: "id", value: "templates" },+ ]),+ ],+ ["header", instance("header", "ws:element", [])],+ ["body-outlet", instance("body-outlet", blockBodyComponent, [])],+ ["footer", instance("footer", "ws:element", [])],+ ["templates", instance("templates", blockTemplateComponent, [])],+ ])+ );+ $props.set(new Map());+ $assets.set(+ new Map<Asset["id"], Asset>([+ [asset.id, asset],+ [authorAsset.id, authorAsset],+ [avatarAsset.id, avatarAsset],+ ])+ );+ $dataSources.set(new Map());+ $resources.set(new Map());+ $styleSources.set(new Map());+ $styleSourceSelections.set(new Map());+ $styles.set(new Map());+ $breakpoints.set(new Map());+ $projectSettings.set({ meta: {}, compiler: {} });+ serverSyncStore.popAll();+ externalContentSyncStore.popAll();++ const renderScope = '["block"]';+ const release = await acquireExternalContentRoot({+ projectId: "project",+ assetId: asset.id,+ blockInstanceId: "block",+ renderScope,+ });++ expect($instances.get().get("block")?.children).toEqual([+ { type: "id", value: "header" },+ { type: "id", value: "body-outlet" },+ { type: "id", value: "footer" },+ { type: "id", value: "templates" },+ ]);+ const [bodyChild] = $instances.get().get("body-outlet")?.children ?? [];+ expect(bodyChild?.type).toBe("id");+ expect(+ bodyChild?.type === "id"+ ? $instances.get().get(bodyChild.value)?.children+ : undefined+ ).toEqual([{ type: "text", value: "Article body" }]);+ expect(+ findExternalContentRoot(getExternalContentRoots(), "block", renderScope)+ ?.diagnostics+ ).toEqual([+ expect.objectContaining({+ severity: "error",+ message: expect.stringContaining("Unable to resolve frontmatter"),+ }),+ ]);++ session.save(authorAsset.id, authorSource);+ await flushExternalContentAsset({+ projectId: "project",+ assetId: authorAsset.id,+ });+ await vi.waitFor(() =>+ expect(+ findExternalContentRoot(getExternalContentRoots(), "block", renderScope)+ ?.frontmatter+ ).toEqual({+ author: {+ name: "Ada",+ avatar: expect.objectContaining({ id: avatarAsset.id }),+ },+ })+ );+ expect(+ getExternalContentRootAssets({+ projectId: "project",+ blockInstanceIds: new Set(["block"]),+ }).map(({ id }) => id)+ ).toEqual([asset.id, authorAsset.id, avatarAsset.id]);++ session.save(+ authorAsset.id,+ `---+name: Ada Lovelace+avatar:+ $ref: ./avatar.jpg+---+`+ );+ await flushExternalContentAsset({+ projectId: "project",+ assetId: authorAsset.id,+ });+ expect(+ findExternalContentRoot(getExternalContentRoots(), "block", renderScope)+ ?.frontmatter+ ).toEqual({+ author: {+ name: "Ada Lovelace",+ avatar: expect.objectContaining({ id: avatarAsset.id }),+ },+ });++ release();+ expect($instances.get().get("body-outlet")?.children).toEqual([]);+ expect($instances.get().has("header")).toBe(true);+ expect($instances.get().has("footer")).toBe(true);+});++test("keeps dynamic Collection occurrences isolated by render scope", async () => {+ const secondAsset: Asset = {+ ...asset,+ id: "second-asset",+ name: "second.mdx",+ size: new TextEncoder().encode("# Second").byteLength,+ };+ const sources = new Map([+ [asset.id, "# First"],+ [secondAsset.id, "# Second"],+ ]);+ const writes: Array<{ assetId: string; source: string }> = [];+ const session = createAssetContentSession({+ repository: {+ readContent: async ({ assetId }) => {+ const currentAsset = assetId === asset.id ? asset : secondAsset;+ const source = sources.get(assetId) ?? "";+ return {+ asset: currentAsset,+ data: (async function* () {+ yield new TextEncoder().encode(source);+ })(),+ };+ },+ updateContent: async ({ assetId, data }) => {+ const source = await new Response(data).text();+ sources.set(assetId, source);+ writes.push({ assetId, source });+ const currentAsset = assetId === asset.id ? asset : secondAsset;+ return {+ ...currentAsset,+ size: new TextEncoder().encode(source).byteLength,+ };+ },+ },+ authorize: () => true,+ debounceMilliseconds: 0,+ });+ sessions.push(session);+ initAssetContentBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload: vi.fn(),+ getContentSession: () => session,+ })+ );+ $project.set({ id: "project", title: "Project", domain: "" } as never);+ $pages.set(createDefaultPages({ rootInstanceId: "body" }));+ $instances.set(+ new Map([+ ["body", instance("body", "Body", [{ type: "id", value: "collection" }])],+ [+ "collection",+ instance("collection", "Collection", [{ type: "id", value: "block" }]),+ ],+ [+ "block",+ instance("block", blockComponent, [+ { type: "id", value: "shell" },+ { type: "id", value: "templates" },+ ]),+ ],+ [+ "shell",+ instance("shell", "ws:element", [{ type: "id", value: "body-outlet" }]),+ ],+ ["body-outlet", instance("body-outlet", blockBodyComponent, [])],+ ["templates", instance("templates", blockTemplateComponent, [])],+ ])+ );+ $props.set(new Map());+ $assets.set(+ new Map([+ [asset.id, asset],+ [secondAsset.id, secondAsset],+ ])+ );+ $dataSources.set(new Map());+ $resources.set(new Map());+ $styleSources.set(new Map());+ $styleSourceSelections.set(new Map());+ $styles.set(new Map());+ $breakpoints.set(new Map());+ $projectSettings.set({ meta: {}, compiler: {} });+ serverSyncStore.popAll();+ externalContentSyncStore.popAll();++ const firstScope = '["block","collection[first]","collection","body"]';+ const secondScope = '["block","collection[second]","collection","body"]';+ releases.push(+ await acquireExternalContentRoot({+ projectId: "project",+ assetId: asset.id,+ blockInstanceId: "block",+ renderScope: firstScope,+ })+ );+ releases.push(+ await acquireExternalContentRoot({+ projectId: "project",+ assetId: secondAsset.id,+ blockInstanceId: "block",+ renderScope: secondScope,+ })+ );+ const firstRoot = findExternalContentRoot(+ getExternalContentRoots(),+ "block",+ firstScope+ );+ const secondRoot = findExternalContentRoot(+ getExternalContentRoots(),+ "block",+ secondScope+ );+ if (firstRoot === undefined || secondRoot === undefined) {+ throw new Error("Expected both dynamic Content Block roots");+ }+ expect(+ resolveExternalContentOccurrence({+ sourceInstance: $instances.get().get("body-outlet")!,+ sourceSelector: [+ "body-outlet",+ "shell",+ firstRoot.blockInstanceId,+ "collection[first]",+ "collection",+ "body",+ ],+ instances: $instances.get(),+ roots: getExternalContentRoots(),+ })?.instance.id+ ).toBe(firstRoot.contentInstanceId);+ expect(+ getExternalContentRootAssets({+ projectId: "project",+ blockInstanceIds: new Set(["block"]),+ }).map(({ id }) => id)+ ).toEqual([asset.id, secondAsset.id]);+ const firstHeading = $instances+ .get()+ .get(firstRoot.contentInstanceId ?? firstRoot.blockInstanceId)+ ?.children.at(0);+ const secondHeading = $instances+ .get()+ .get(secondRoot.contentInstanceId ?? secondRoot.blockInstanceId)+ ?.children.at(0);+ if (firstHeading?.type !== "id" || secondHeading?.type !== "id") {+ throw new Error("Expected both dynamic MDX headings");+ }+ expect(+ getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: firstScope,+ })+ ).toEqual([firstHeading]);+ expect($instances.get().get(firstHeading.value)?.children).toEqual([+ { type: "text", value: "First" },+ ]);+ expect($instances.get().get(secondHeading.value)?.children).toEqual([+ { type: "text", value: "Second" },+ ]);++ selectInstance([+ firstHeading.value,+ firstRoot.contentInstanceId ?? "body-outlet",+ "shell",+ firstRoot.blockInstanceId,+ "collection[first]",+ "collection",+ "body",+ ]);+ executeRuntimeMutation({+ id: "instances.setTextContent",+ input: {+ operation: "set",+ instanceId: firstHeading.value,+ mode: "text",+ text: "Updated first",+ },+ });+ await flushExternalContentAsset({ projectId: "project", assetId: asset.id });++ expect(writes).toEqual([{ assetId: asset.id, source: "# Updated first\n" }]);+ expect($instances.get().get(secondHeading.value)?.children).toEqual([+ { type: "text", value: "Second" },+ ]);+});++test("finishes a queued canvas save after its external root is released", async () => {+ const writes: string[] = [];+ let continueUpdate: (() => void) | undefined;+ const updateGate = new Promise<void>((resolve) => {+ continueUpdate = resolve;+ });+ const session = createAssetContentSession({+ repository: {+ readContent: async () => ({+ asset,+ data: (async function* () {+ yield new TextEncoder().encode("# Hello");+ })(),+ }),+ updateContent: async ({ data }) => {+ const source = await new Response(data).text();+ writes.push(source);+ return { ...asset, size: new TextEncoder().encode(source).byteLength };+ },+ },+ authorize: () => true,+ debounceMilliseconds: 0,+ });+ sessions.push(session);+ initAssetContentBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload: vi.fn(),+ getContentSession: () => session,+ })+ );+ $project.set({ id: "project", title: "Project", domain: "" } as never);+ $pages.set(createDefaultPages({ rootInstanceId: "block" }));+ $instances.set(+ new Map([+ [+ "block",+ instance("block", blockComponent, [{ type: "id", value: "templates" }]),+ ],+ ["templates", instance("templates", blockTemplateComponent, [])],+ ])+ );+ $props.set(new Map());+ $assets.set(new Map([[asset.id, asset]]));+ $dataSources.set(new Map());+ $resources.set(new Map());+ $styleSources.set(new Map());+ $styleSourceSelections.set(new Map());+ $styles.set(new Map());+ $breakpoints.set(new Map());+ const release = await acquireExternalContentRoot({+ projectId: "project",+ assetId: asset.id,+ blockInstanceId: "block",+ renderScope: '["block"]',+ });+ const heading = getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })?.[0];+ if (heading?.type !== "id") {+ throw new Error("Expected a materialized heading");+ }+ const statuses: string[] = [];+ const unsubscribe = subscribeExternalContentAsset({+ projectId: "project",+ assetId: asset.id,+ listener: ({ status }) => statuses.push(status),+ });+ const blockingUpdate = updateExternalContentAssetSource({+ projectId: "project",+ assetId: asset.id,+ update: async (source) => {+ await updateGate;+ return source;+ },+ });+ selectInstance([heading.value, "block"]);+ executeRuntimeMutation({+ id: "instances.setTextContent",+ input: {+ operation: "set",+ instanceId: heading.value,+ mode: "text",+ text: "Stale update",+ },+ });++ release();+ continueUpdate?.();+ await blockingUpdate;+ await flushExternalContentAsset({ projectId: "project", assetId: asset.id });+ unsubscribe();++ expect(statuses).not.toContain("failed");+ expect(writes).toEqual(["# Stale update\n"]);+});++test("retains a failed queued update when project teardown cannot drain it", async () => {+ const teardownAsset: Asset = {+ ...asset,+ id: "teardown-asset",+ projectId: "teardown-project",+ size: new TextEncoder().encode("# Original").byteLength,+ };+ const writes: string[] = [];+ const session = createAssetContentSession({+ repository: {+ readContent: async () => ({+ asset: teardownAsset,+ data: (async function* () {+ yield new TextEncoder().encode("# Original");+ })(),+ }),+ updateContent: async ({ data }) => {+ const source = await new Response(data).text();+ writes.push(source);+ return {+ ...teardownAsset,+ size: new TextEncoder().encode(source).byteLength,+ };+ },+ },+ authorize: () => true,+ debounceMilliseconds: 0,+ });+ sessions.push(session);+ initAssetContentBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload: vi.fn(),+ getContentSession: () => session,+ })+ );+ await session.open(teardownAsset.id);+ let preparationFails = true;+ const update = () => {+ if (preparationFails) {+ throw new Error("Temporary serialization failure");+ }+ return "# Recovered";+ };++ await expect(+ updateExternalContentAssetSource({+ projectId: teardownAsset.projectId!,+ assetId: teardownAsset.id,+ update,+ })+ ).rejects.toThrow("Temporary serialization failure");+ await expect(+ disposeExternalContentProject({+ projectId: teardownAsset.projectId!,+ session,+ })+ ).rejects.toThrow("Temporary serialization failure");++ preparationFails = false;+ await retryExternalContentAsset({+ projectId: teardownAsset.projectId!,+ assetId: teardownAsset.id,+ });+ await flushExternalContentAsset({+ projectId: teardownAsset.projectId!,+ assetId: teardownAsset.id,+ });++ expect(writes).toEqual(["# Recovered"]);+ await disposeExternalContentProject({+ projectId: teardownAsset.projectId!,+ session,+ });+});++test("retains pending content when the repository write fails during teardown", async () => {+ const teardownAsset: Asset = {+ ...asset,+ id: "repository-failure-asset",+ projectId: "repository-failure-project",+ size: new TextEncoder().encode("# Original").byteLength,+ };+ const writes: string[] = [];+ let writeFails = true;+ const session = createAssetContentSession({+ repository: {+ readContent: async () => ({+ asset: teardownAsset,+ data: (async function* () {+ yield new TextEncoder().encode("# Original");+ })(),+ }),+ updateContent: async ({ data }) => {+ const source = await new Response(data).text();+ if (writeFails) {+ throw new Error("Temporary repository failure");+ }+ writes.push(source);+ return {+ ...teardownAsset,+ size: new TextEncoder().encode(source).byteLength,+ };+ },+ },+ authorize: () => true,+ debounceMilliseconds: 60_000,+ });+ sessions.push(session);+ initAssetContentBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload: vi.fn(),+ getContentSession: () => session,+ })+ );+ await session.open(teardownAsset.id);+ await updateExternalContentAssetSource({+ projectId: teardownAsset.projectId!,+ assetId: teardownAsset.id,+ update: () => "# Pending",+ });++ await expect(+ disposeExternalContentProject({+ projectId: teardownAsset.projectId!,+ session,+ })+ ).rejects.toThrow("Temporary repository failure");++ writeFails = false;+ await disposeExternalContentProject({+ projectId: teardownAsset.projectId!,+ session,+ });+ expect(writes).toEqual(["# Pending"]);+});++test("keeps drained queues when the project becomes active during teardown", async () => {+ const projectId = "reactivated-project";+ const source = "# Original";+ const reactivatedAsset = {+ ...asset,+ projectId,+ size: new TextEncoder().encode(source).byteLength,+ };+ const session = createAssetContentSession({+ repository: {+ readContent: async () => ({+ asset: reactivatedAsset,+ data: (async function* () {+ yield new TextEncoder().encode(source);+ })(),+ }),+ updateContent: async ({ data }) => ({+ ...reactivatedAsset,+ size: (await new Response(data).arrayBuffer()).byteLength,+ }),+ },+ authorize: () => true,+ });+ sessions.push(session);+ initAssetContentBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload: vi.fn(),+ getContentSession: () => session,+ })+ );+ await session.open(asset.id);+ await updateExternalContentAssetSource({+ projectId,+ assetId: asset.id,+ update: () => "# Active again",+ });++ await expect(+ disposeExternalContentProject({+ projectId,+ session,+ shouldCleanup: () => false,+ })+ ).resolves.toBe(false);+ await expect(+ disposeExternalContentProject({ projectId, session })+ ).resolves.toBe(true);+});++test("materializes into normal instances and saves their synchronous mutations only to the Asset", async () => {+ const writes: string[] = [];+ const requireReload = vi.fn();+ let revision = 1;+ const session = createAssetContentSession({+ repository: {+ readContent: async () => ({+ asset,+ data: (async function* () {+ yield new TextEncoder().encode("# Hello");+ })(),+ }),+ updateContent: async ({ data }) => {+ const source = await new Response(data).text();+ writes.push(source);+ revision += 1;+ return {+ ...asset,+ name: `article_v${revision}.mdx`,+ size: new TextEncoder().encode(source).byteLength,+ };+ },+ },+ authorize: () => true,+ debounceMilliseconds: 0,+ });+ sessions.push(session);+ initAssetContentBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload,+ getContentSession: () => session,+ })+ );++ const pages = createDefaultPages({ rootInstanceId: "block" });+ $pages.set(pages);+ $project.set({ id: "project", title: "Project", domain: "" } as never);+ $instances.set(+ new Map([+ [+ "block",+ instance("block", blockComponent, [{ type: "id", value: "templates" }]),+ ],+ ["templates", instance("templates", blockTemplateComponent, [])],+ [+ "block-2",+ instance("block-2", blockComponent, [+ { type: "id", value: "templates-2" },+ ]),+ ],+ ["templates-2", instance("templates-2", blockTemplateComponent, [])],+ ["ordinary", instance("ordinary", "ws:element", [])],+ ])+ );+ $props.set(new Map());+ $assets.set(new Map([[asset.id, asset]]));+ $breakpoints.set(new Map());+ $dataSources.set(new Map());+ $resources.set(new Map());+ $styleSources.set(new Map());+ $styleSourceSelections.set(new Map());+ $styles.set(new Map());+ $projectSettings.set({ meta: {}, compiler: {} });+ serverSyncStore.popAll();+ externalContentSyncStore.popAll();++ releases.push(+ await acquireExternalContentRoot({+ projectId: "project",+ assetId: asset.id,+ blockInstanceId: "block",+ renderScope: '["block"]',+ })+ );+ releases.push(+ await acquireExternalContentRoot({+ projectId: "project",+ assetId: asset.id,+ blockInstanceId: "block-2",+ renderScope: '["block-2"]',+ })+ );++ const repeatedRenderScope =+ '["block","collection[first]","collection","body"]';+ const releaseRepeatedRoot = await acquireExternalContentRoot({+ projectId: "project",+ assetId: asset.id,+ blockInstanceId: "block",+ renderScope: repeatedRenderScope,+ });+ const repeatedRoot = findExternalContentRoot(+ getExternalContentRoots(),+ "block",+ repeatedRenderScope+ );+ if (repeatedRoot === undefined) {+ throw new Error("Expected a scoped repeated Content Block root");+ }+ expect(repeatedRoot.blockInstanceId).not.toBe("block");+ expect($instances.get().get("block")?.children).toEqual([+ { type: "id", value: "templates" },+ expect.objectContaining({ type: "id" }),+ ]);+ expect($instances.get().get(repeatedRoot.blockInstanceId)?.children).toEqual([+ { type: "id", value: "templates" },+ expect.objectContaining({ type: "id" }),+ ]);+ releaseRepeatedRoot();+ expect($instances.get().has(repeatedRoot.blockInstanceId)).toBe(false);+ expect($instances.get().get("block")?.children).toEqual([+ { type: "id", value: "templates" },+ expect.objectContaining({ type: "id" }),+ ]);++ const headingId = getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })?.[0];+ if (headingId?.type !== "id") {+ throw new Error("Expected a materialized heading");+ }+ expect($instances.get().get("block")?.children).toEqual([+ { type: "id", value: "templates" },+ headingId,+ ]);+ const initialIdentity = getExternalContentRootSnapshot({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })?.identity;+ expect($instances.get().get(headingId.value)).toMatchObject({+ tag: "h1",+ children: [{ type: "text", value: "Hello" }],+ });++ executeRuntimeMutation({+ id: "instances.setTextContent",+ input: {+ operation: "set",+ instanceId: headingId.value,+ mode: "text",+ text: "Updated",+ },+ });++ expect($instances.get().get(headingId.value)?.children).toEqual([+ { type: "text", value: "Updated" },+ ]);++ selectInstance([headingId.value, "block"]);+ const insertion = executeRuntimeMutation({+ id: "instances.insertComponent",+ input: {+ parentInstanceId: "block",+ component: "ws:element",+ tag: "h2",+ },+ });+ const insertedId = insertion?.result.rootInstanceIds[0];+ if (insertion === undefined || insertedId === undefined) {+ throw new Error("Expected an inserted heading");+ }+ expect(insertion.result.parentInstanceId).toBe("block");+ executeRuntimeMutation({+ id: "instances.setTextContent",+ input: {+ operation: "set",+ instanceId: insertedId,+ mode: "text",+ text: "Second",+ },+ });+ expect(+ getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })+ ).toEqual([+ { type: "id", value: headingId.value },+ { type: "id", value: insertedId },+ ]);+ expect($instances.get().get("block")?.children).toEqual([+ { type: "id", value: "templates" },+ { type: "id", value: headingId.value },+ { type: "id", value: insertedId },+ ]);+ expect(serverSyncStore.popAll()).toEqual([]);+ await flushExternalContentAsset({ projectId: "project", assetId: asset.id });+ await vi.waitFor(() => expect(writes).toEqual(["# Updated\n\n## Second\n"]));+ const savedIdentity = getExternalContentRootSnapshot({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })?.identity;+ expect(savedIdentity?.contentRef).toBe("article_v2.mdx");+ expect(savedIdentity?.revision).not.toBe(initialIdentity?.revision);+ executeRuntimeMutation({+ id: "instances.setTextContent",+ input: {+ operation: "set",+ instanceId: insertedId,+ mode: "text",+ text: "Second after save",+ },+ });+ expect(serverSyncStore.popAll()).toEqual([]);+ await flushExternalContentAsset({ projectId: "project", assetId: asset.id });+ expect(writes.at(-1)).toBe("# Updated\n\n## Second after save\n");+ expect(+ getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })+ ).toEqual([+ { type: "id", value: headingId.value },+ { type: "id", value: insertedId },+ ]);++ const secondOccurrenceChildren = getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block-2",+ renderScope: '["block-2"]',+ });+ const secondOccurrenceHeading = secondOccurrenceChildren?.[0];+ const secondOccurrenceSubheading = secondOccurrenceChildren?.[1];+ if (+ secondOccurrenceHeading?.type !== "id" ||+ secondOccurrenceSubheading?.type !== "id"+ ) {+ throw new Error("Expected both shared Asset occurrences to rematerialize");+ }++ selectInstance([headingId.value, "block"]);+ executeRuntimeMutation({+ id: "instances.setTextContent",+ input: {+ operation: "set",+ instanceId: headingId.value,+ mode: "text",+ text: "First occurrence",+ },+ });+ expect($instances.get().get(headingId.value)?.children).toEqual([+ { type: "text", value: "First occurrence" },+ ]);+ selectInstance([secondOccurrenceSubheading.value, "block-2"]);+ executeRuntimeMutation({+ id: "instances.setTextContent",+ input: {+ operation: "set",+ instanceId: secondOccurrenceSubheading.value,+ mode: "text",+ text: "Second occurrence",+ },+ });+ expect(+ $instances.get().get(secondOccurrenceSubheading.value)?.children+ ).toEqual([{ type: "text", value: "Second occurrence" }]);++ await flushExternalContentAsset({ projectId: "project", assetId: asset.id });+ expect(writes.at(-1)).toBe("# First occurrence\n\n## Second occurrence\n");+ expect(requireReload).not.toHaveBeenCalled();++ const firstOccurrenceChildren = getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ });+ const moved = firstOccurrenceChildren?.[1];+ if (moved?.type !== "id") {+ throw new Error("Expected a movable external child");+ }+ selectInstance([moved.value, "block"]);+ executeRuntimeMutation({+ id: "instances.move",+ input: {+ moves: [{ instanceId: moved.value, parentInstanceId: "ordinary" }],+ },+ });+ expect($instances.get().get("ordinary")?.children).toEqual([moved]);+ expect(serverSyncStore.popAll()).not.toEqual([]);++ selectInstance([moved.value, "ordinary"]);+ executeRuntimeMutation({+ id: "instances.move",+ input: { moves: [{ instanceId: moved.value, parentInstanceId: "block" }] },+ });+ expect($instances.get().get("ordinary")?.children).toEqual([]);+ expect(serverSyncStore.popAll()).not.toEqual([]);+ await flushExternalContentAsset({ projectId: "project", assetId: asset.id });+ expect(writes.at(-1)).toBe("# First occurrence\n\n## Second occurrence\n");++ session.save(asset.id, "<broken");+ await session.flush(asset.id);+ await vi.waitFor(() =>+ expect(+ getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })+ ).toEqual([])+ );+ expect(+ getExternalContentRootSnapshot({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })?.diagnostics+ ).toEqual([+ expect.objectContaining({ code: "invalid-mdx", severity: "error" }),+ ]);+ selectInstance(["block"]);+ const localInsertion = executeRuntimeMutation({+ id: "instances.insertComponent",+ input: {+ parentInstanceId: "block",+ component: "ws:element",+ tag: "p",+ },+ });+ const localParagraphId = localInsertion?.result.rootInstanceIds[0];+ if (localParagraphId === undefined) {+ throw new Error("Expected a local paragraph");+ }+ executeRuntimeMutation({+ id: "instances.setTextContent",+ input: {+ operation: "set",+ instanceId: localParagraphId,+ mode: "text",+ text: "Local draft",+ },+ });+ await new Promise<void>((resolve) => setTimeout(resolve, 0));+ expect(+ getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })+ ).toEqual([{ type: "id", value: localParagraphId }]);+ expect($instances.get().has(localParagraphId)).toBe(true);++ await expect(+ flushExternalContentProject({ projectId: "project", session })+ ).rejects.toThrow(+ "The MDX content source must be structurally valid before canvas edits can be saved."+ );++ session.save(asset.id, "# Repaired");+ await session.flush(asset.id);+ await expect(+ retryExternalContentAsset({ projectId: "project", assetId: asset.id })+ ).rejects.toThrow(+ "The MDX content source changed before the edit was saved. Reload to continue."+ );+ expect(requireReload).toHaveBeenCalledWith(+ "The MDX content source changed before the edit was saved. Reload to continue."+ );+ expect(writes.at(-1)).toBe("# Repaired");+ expect($instances.get().get(localParagraphId)?.children).toEqual([+ { type: "text", value: "Local draft" },+ ]);+ await expect(+ disposeExternalContentProject({ projectId: "project", session })+ ).rejects.toThrow(+ "The MDX content source changed before the edit was saved. Reload to continue."+ );+ expect(+ getExternalContentRootSnapshot({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })+ ).toBeUndefined();+});diff --git a/apps/builder/app/shared/external-content-roots.ts b/apps/builder/app/shared/external-content-roots.tsnew file mode 100644index 0000000000..d6fbc30f4e--- /dev/null+++ b/apps/builder/app/shared/external-content-roots.ts@@ -0,0 +1,1575 @@+import {+ createCanonicalAssetPath,+ parseMdxDocumentRecovering,+ replaceMdxFrontmatter,+ serializeMdxDocument,+ type MdxDocument,+} from "@webstudio-is/content-engine/mdx";+import {+ compileDocumentSourceGraph,+ createDocumentSourceUrl,+ createUniqueAssetIdsByPath,+ discoverAssetValueReferences,+ DocumentGraphError,+ DocumentSourceCompilationError,+ getDocumentGraphClosure,+ resolveDocumentGraphProperties,+ type AssetValueReference,+ type DocumentFormat,+} from "@webstudio-is/content-engine";+import {+ extractWebstudioFragment,+ adoptMdxAuthoredContentFragment,+ createEmptyWebstudioFragment,+ materializeMdxSource,+ mergeWebstudioFragments,+ MdxAuthoredContentConflictError,+ omitTransientEmptyMarkdownDrafts,+ rebaseMdxAuthoredContent,+ createMdxScopeIdGenerator,+ type MaterializedMdxAuthoredContentRoot,+} from "@webstudio-is/project-build/runtime";+import {+ blockTemplateComponent,+ createAssetContentRevision,+ createAssetFolderHierarchy,+ formatAssetName,+ findContentBlockBodyContainerPaths,+ findContentBlockTemplateContainers,+ getInstanceName,+ createContentBlockExternalContentIdentity,+ toAssetReferenceRuntimeData,+ type ContentBlockDiagnostic,+ type WebstudioFragment,+} from "@webstudio-is/sdk";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";+import type {+ AssetContentSession,+ AssetContentSessionState,+} from "@webstudio-is/content-engine/asset-content-session";+import { getAssetContentBridge } from "./asset-content-bridge.client";+import {+ getExternalContentRoots,+ registerExternalContentRoot,+ subscribeExternalContentMutations,+} from "./external-content-mutations";+import {+ getExternalContentFragmentOwnership,+ getExternalContentFragmentRecords,+} from "./external-content-persistence";+import type { BuilderPatchChange } from "@webstudio-is/project-build/contracts";+import { getWebstudioData } from "./instance-utils/data";+import { externalContentSyncStore } from "./sync/sync-stores";+import { createSyncChangesFromBuilderPatchPayload } from "./sync/builder-patch";+import { $project } from "./sync/data-stores";+import {+ isRepeatedContentBlockOccurrence,+ parseContentBlockRenderScope,+} from "./content-block-source-utils";+import { setObjectPathValue } from "./content-block-document";++type RootEntry = {+ key: string;+ projectId: string;+ assetId: string;+ sourceBlockInstanceId: string;+ blockInstanceId: string;+ sourceContentInstanceId: string;+ contentInstanceId: string;+ renderScope: string;+ root: MaterializedMdxAuthoredContentRoot;+ installedFragment: WebstudioFragment;+ transientInstanceIds: ReadonlySet<string>;+ diagnostics: readonly ContentBlockDiagnostic[];+ includeUnresolvedTemplatePlaceholders: boolean;+ unregisterMutationRoot: () => void;+ references: number;+ openVersion: number;+ saveRevision: number;+ dependencyAssetIds: ReadonlySet<string>;+};++type AssetQueue = {+ projectId: string;+ pendingSnapshots: number;+ serialization: Promise<void>;+ failedUpdate?: AssetUpdate;+ failedPreservedRootKey?: string;+ latestDocument?: Readonly<{ source: string; document: MdxDocument }>;+ parsed?: Readonly<{+ source: string;+ result: ReturnType<typeof parseMdxDocumentRecovering>;+ }>;+ preservedRootKey?: string;+ error?: Error;+ listeners: Set<(error: Error | undefined) => void>;+};++type PreparedAssetUpdate =+ | string+ | Readonly<{ source: string; document: MdxDocument }>+ | undefined;+type AssetUpdate = (+ state: AssetContentSessionState,+ latestDocument: MdxDocument | undefined+) => PreparedAssetUpdate | Promise<PreparedAssetUpdate>;++const roots = new Map<string, RootEntry>();+const rootOpenGenerations = new Map<+ string,+ Readonly<{ projectId: string; value: number }>+>();+const assetQueues = new Map<string, AssetQueue>();+const subscribedSessions = new WeakSet<AssetContentSession>();+const getAssetQueueKey = (projectId: string, assetId: string) =>+ JSON.stringify([projectId, assetId]);+const getRootKey = (+ projectId: string,+ sourceBlockInstanceId: string,+ renderScope: string+) => JSON.stringify([projectId, sourceBlockInstanceId, renderScope]);++const settleProjectAssetQueues = async (projectId: string) => {+ while (true) {+ const queues = Array.from(assetQueues.values()).filter(+ (queue) => queue.projectId === projectId+ );+ const serializations = queues.map((queue) => queue.serialization);+ await Promise.all(serializations);+ const currentQueues = Array.from(assetQueues.values()).filter(+ (queue) => queue.projectId === projectId+ );+ if (+ currentQueues.length === queues.length &&+ currentQueues.every(+ (queue, index) =>+ queue === queues[index] &&+ queue.serialization === serializations[index]+ )+ ) {+ const failed = currentQueues.find((queue) => queue.error !== undefined);+ if (failed?.error !== undefined) {+ throw failed.error;+ }+ return currentQueues;+ }+ }+};++const getAssetQueue = (projectId: string, assetId: string) => {+ const key = getAssetQueueKey(projectId, assetId);+ let queue = assetQueues.get(key);+ if (queue === undefined) {+ queue = {+ projectId,+ pendingSnapshots: 0,+ serialization: Promise.resolve(),+ listeners: new Set(),+ };+ assetQueues.set(key, queue);+ }+ return queue;+};++const parseAssetSource = (+ projectId: string,+ assetId: string,+ source: string+) => {+ const queue = getAssetQueue(projectId, assetId);+ if (queue.parsed?.source === source) {+ return queue.parsed.result;+ }+ const result = parseMdxDocumentRecovering({ source });+ queue.parsed = { source, result };+ return result;+};++const publishAssetQueueError = (queue: AssetQueue) => {+ for (const listener of queue.listeners) {+ listener(queue.error);+ }+};++const getPreservedRootKey = (+ queue: AssetQueue | undefined,+ state: AssetContentSessionState+) => {+ if (+ queue?.latestDocument !== undefined &&+ queue.latestDocument.source === state.source+ ) {+ return queue.preservedRootKey;+ }+ if (queue !== undefined) {+ queue.preservedRootKey = undefined;+ queue.latestDocument = undefined;+ }+};++const getAuthoredChildren = (entry: RootEntry) => {+ const data = getWebstudioData();+ const content = data.instances.get(entry.contentInstanceId);+ if (entry.contentInstanceId !== entry.blockInstanceId) {+ return content?.children ?? [];+ }+ return (content?.children ?? []).filter(+ (child) =>+ child.type !== "id" ||+ data.instances.get(child.value)?.component !== blockTemplateComponent+ );+};++const getMutationRootChildren = (+ entry: RootEntry,+ authoredChildren = getAuthoredChildren(entry)+) => {+ if (entry.contentInstanceId !== entry.blockInstanceId) {+ return authoredChildren;+ }+ const data = getWebstudioData();+ const block =+ data.instances.get(entry.blockInstanceId) ??+ data.instances.get(entry.sourceBlockInstanceId);+ const templateChildren =+ block === undefined+ ? []+ : findContentBlockTemplateContainers({+ blockInstance: block,+ instances: data.instances,+ }).map(({ id }) => ({ type: "id" as const, value: id }));+ return [...templateChildren, ...authoredChildren];+};++const registerMutationRoot = (+ entry: RootEntry,+ fragment: WebstudioFragment+) => {+ const owned = getExternalContentFragmentOwnership(fragment);+ const instanceSelector = parseContentBlockRenderScope(entry.renderScope);+ entry.unregisterMutationRoot = registerExternalContentRoot(entry.key, {+ sourceBlockInstanceId: entry.sourceBlockInstanceId,+ sourceRenderScope: entry.renderScope,+ blockInstanceId: entry.blockInstanceId,+ sourceContentInstanceId: entry.sourceContentInstanceId,+ contentInstanceId: entry.contentInstanceId,+ renderScope:+ entry.blockInstanceId === entry.sourceBlockInstanceId ||+ instanceSelector === undefined+ ? entry.renderScope+ : JSON.stringify([entry.blockInstanceId, ...instanceSelector.slice(1)]),+ instanceIds: owned.instances,+ propIds: owned.props,+ ownership: owned,+ mutationRevision: 0,+ projectId: entry.projectId,+ identity: entry.root.identity,+ diagnostics: entry.diagnostics,+ document: entry.root.document,+ frontmatter:+ entry.root.resolvedFrontmatter ??+ entry.root.document.frontmatter.properties,+ transientInstanceIds: entry.transientInstanceIds,+ });+};++const installRoot = ({+ entry,+ root,+ diagnostics,+}: {+ entry: RootEntry;+ root: MaterializedMdxAuthoredContentRoot;+ diagnostics: readonly ContentBlockDiagnostic[];+}) => {+ const data = getWebstudioData();+ const sourceBlock = data.instances.get(entry.sourceBlockInstanceId);+ if (sourceBlock === undefined) {+ return;+ }+ const installedFragment = root.fragment;+ const transientInstanceIds = new Set(+ entry.includeUnresolvedTemplatePlaceholders+ ? root.provenance.unresolvedTemplates.map(({ markerId }) => markerId)+ : []+ );+ const nextOwned = getExternalContentFragmentOwnership(installedFragment);+ const payload: BuilderPatchChange[] = [];++ if (entry.blockInstanceId !== entry.sourceBlockInstanceId) {+ const scopedBlock = {+ ...sourceBlock,+ id: entry.blockInstanceId,+ children:+ entry.contentInstanceId === entry.blockInstanceId+ ? getMutationRootChildren(entry, [])+ : sourceBlock.children,+ };+ payload.push({+ namespace: "instances",+ patches: [+ {+ op: data.instances.has(entry.blockInstanceId) ? "replace" : "add",+ path: [entry.blockInstanceId],+ value: scopedBlock,+ },+ ],+ });+ if (entry.contentInstanceId !== entry.blockInstanceId) {+ const sourceContent = data.instances.get(entry.sourceContentInstanceId);+ if (sourceContent === undefined) {+ return;+ }+ payload.push({+ namespace: "instances",+ patches: [+ {+ op: data.instances.has(entry.contentInstanceId) ? "replace" : "add",+ path: [entry.contentInstanceId],+ value: {+ ...sourceContent,+ id: entry.contentInstanceId,+ children: [],+ },+ },+ ],+ });+ }+ }++ for (const [namespace, records] of getExternalContentFragmentRecords(+ entry.installedFragment+ )) {+ const nextIds = nextOwned[namespace] ?? new Set();+ const patches = records+ .filter(({ key }) => nextIds.has(key) === false)+ .map(({ key }) => ({ op: "remove" as const, path: [key] }));+ if (patches.length > 0) {+ payload.push({ namespace, patches });+ }+ }++ for (const [namespace, records] of getExternalContentFragmentRecords(+ installedFragment+ )) {+ const current = data[namespace] as ReadonlyMap<string, unknown>;+ const patches = records.map(({ key, value }) => ({+ op: current.has(key) ? ("replace" as const) : ("add" as const),+ path: [key],+ value,+ }));+ if (patches.length > 0) {+ payload.push({ namespace, patches });+ }+ }++ payload.push({+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: [entry.contentInstanceId, "children"],+ value: getMutationRootChildren(entry, installedFragment.children),+ },+ ],+ });++ externalContentSyncStore.createTransactionFromChanges(+ createSyncChangesFromBuilderPatchPayload({ data, payload })+ );+ entry.root = root;+ entry.installedFragment = installedFragment;+ entry.transientInstanceIds = transientInstanceIds;+ entry.diagnostics = diagnostics;+ registerMutationRoot(entry, installedFragment);+};++const uninstallRoot = (entry: RootEntry) => {+ const data = getWebstudioData();+ const payload: BuilderPatchChange[] = [];+ const content = data.instances.get(entry.contentInstanceId);+ const owned = getExternalContentFragmentOwnership(entry.installedFragment);+ if (+ content !== undefined &&+ entry.blockInstanceId === entry.sourceBlockInstanceId+ ) {+ const retainedChildren = content.children.filter(+ (child) =>+ child.type !== "id" || owned.instances.has(child.value) === false+ );+ if (retainedChildren.length !== content.children.length) {+ payload.push({+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: [entry.contentInstanceId, "children"],+ value: retainedChildren,+ },+ ],+ });+ }+ }+ for (const [namespace, records] of getExternalContentFragmentRecords(+ entry.installedFragment+ )) {+ const current = data[namespace] as ReadonlyMap<string, unknown>;+ const patches = records+ .filter(({ key }) => current.has(key))+ .map(({ key }) => ({ op: "remove" as const, path: [key] }));+ if (patches.length > 0) {+ payload.push({ namespace, patches });+ }+ }+ if (entry.blockInstanceId !== entry.sourceBlockInstanceId) {+ if (entry.contentInstanceId !== entry.blockInstanceId) {+ payload.push({+ namespace: "instances",+ patches: [{ op: "remove", path: [entry.contentInstanceId] }],+ });+ }+ payload.push({+ namespace: "instances",+ patches: [{ op: "remove", path: [entry.blockInstanceId] }],+ });+ }+ if (payload.length > 0) {+ externalContentSyncStore.createTransactionFromChanges(+ createSyncChangesFromBuilderPatchPayload({ data, payload })+ );+ }+};++const createExternalContentIdentity = (+ entry: RootEntry,+ sourceState: AssetContentSessionState+) =>+ createContentBlockExternalContentIdentity({+ blockInstanceId: entry.sourceBlockInstanceId,+ asset: sourceState.asset,+ renderScope: entry.renderScope,+ });++const getDocumentFormat = (format: string): DocumentFormat | undefined => {+ const normalized = format.toLowerCase();+ if (normalized === "md") {+ return "markdown";+ }+ if (normalized === "mdx" || normalized === "json") {+ return normalized;+ }+};++const resolveExternalContentFrontmatter = async (+ entry: RootEntry,+ sourceState: AssetContentSessionState+) => {+ const data = getWebstudioData();+ const hierarchy = createAssetFolderHierarchy(data.assetFolders ?? new Map());+ const assets = Array.from(data.assets.values());+ const getPath = (asset: (typeof assets)[number]) =>+ createCanonicalAssetPath({+ name: formatAssetName(asset),+ folderNames: hierarchy.getPath(asset.folderId).map(({ name }) => name),+ });+ const assetPaths = assets.map((asset) => ({+ id: asset.id,+ path: getPath(asset),+ }));+ const assetPathsById = new Map(+ assetPaths.map(({ id, path }) => [id, path] as const)+ );+ const assetIdsByPath = createUniqueAssetIdsByPath(assetPaths);+ const documentAssets = assets.flatMap((asset) => {+ const format = getDocumentFormat(asset.format);+ return asset.type === "file" && format !== undefined+ ? [{ asset, format, path: getPath(asset) }]+ : [];+ });+ if (+ documentAssets.some(({ asset }) => asset.id === entry.assetId) === false+ ) {+ return;+ }+ const documentAssetIds = new Set(documentAssets.map(({ asset }) => asset.id));+ const structuredAssetIds = new Set(+ assets+ .filter(({ id }) => documentAssetIds.has(id) === false)+ .map(({ id }) => id)+ );+ const session = getSession(entry.projectId);+ const referencesByDocumentId = new Map<string, AssetValueReference[]>();+ const getReferencedAssetIds = (documentIds: Iterable<string>) =>+ Array.from(documentIds).flatMap((id) =>+ (referencesByDocumentId.get(id) ?? []).map(({ assetId }) => assetId)+ );+ const encoder = new TextEncoder();+ let graph: Awaited<ReturnType<typeof compileDocumentSourceGraph>>;+ try {+ graph = await compileDocumentSourceGraph({+ documents: documentAssets.map(({ asset, format, path }) => ({+ id: asset.id,+ documentUrl: createDocumentSourceUrl(path),+ revision: createAssetContentRevision({+ storageName: asset.name,+ updatedAt: asset.updatedAt ?? asset.createdAt,+ size: asset.size,+ }),+ contentRef: asset.name,+ format,+ source: {+ async *[Symbol.asyncIterator]() {+ yield encoder.encode(+ asset.id === entry.assetId+ ? sourceState.source+ : (await session.open(asset.id)).source+ );+ },+ },+ })),+ rootIds: [entry.assetId],+ ignoredReferenceUrls: new Set(+ assets+ .filter(({ id }) => documentAssetIds.has(id) === false)+ .map((asset) => createDocumentSourceUrl(getPath(asset)))+ ),+ onDocumentProperties: ({ id, properties }) => {+ const sourcePath = assetPathsById.get(id);+ if (sourcePath !== undefined) {+ referencesByDocumentId.set(+ id,+ discoverAssetValueReferences({+ properties,+ sourcePath,+ assetIdsByPath,+ structuredAssetIds,+ })+ );+ }+ },+ });+ } catch (error) {+ let failedDocumentIds: readonly string[] = [];+ if (+ error instanceof DocumentSourceCompilationError &&+ error.documentId !== undefined+ ) {+ failedDocumentIds = [error.documentId];+ } else if (error instanceof DocumentGraphError) {+ failedDocumentIds = error.documentIds;+ }+ entry.dependencyAssetIds = new Set([+ entry.assetId,+ ...failedDocumentIds.filter((id) => documentAssetIds.has(id)),+ ...referencesByDocumentId.keys(),+ ...getReferencedAssetIds(referencesByDocumentId.keys()),+ ]);+ throw error;+ }+ const graphNodes = getDocumentGraphClosure({+ graph,+ rootIds: [entry.assetId],+ });+ entry.dependencyAssetIds = new Set([+ ...graphNodes.map(({ id }) => id),+ ...getReferencedAssetIds(graphNodes.map(({ id }) => id)),+ ]);+ const runtimeAssets = Object.fromEntries(+ assets.map((asset) => [+ asset.id,+ toAssetReferenceRuntimeData(asset, window.location.origin),+ ])+ );+ const properties = await resolveDocumentGraphProperties({+ graph,+ rootId: entry.assetId,+ assetValueReferences: Object.fromEntries(referencesByDocumentId),+ runtimeAssets,+ load: async (node) => {+ if (node.format === undefined) {+ throw new Error(`Document ${node.id} has no format`);+ }+ return {+ format: node.format,+ revision: node.revision,+ source:+ node.id === entry.assetId+ ? sourceState.source+ : (await session.open(node.id)).source,+ };+ },+ });+ return properties;+};++const createBuilderUnresolvedTemplateInstance = ({+ markerId,+ templateName,+}: {+ markerId: string;+ templateName: string;+}) => ({+ type: "instance" as const,+ id: markerId,+ component: "ws:element",+ tag: "div",+ label: `Missing template: ${templateName}`,+ children: [+ {+ type: "text" as const,+ value: `Missing template: ${templateName}`,+ },+ ],+});++const materialize = async ({+ entry,+ sourceState,+}: {+ entry: RootEntry;+ sourceState: AssetContentSessionState;+}) => {+ const data = getWebstudioData();+ const parsed = await parseAssetSource(+ entry.projectId,+ entry.assetId,+ sourceState.source+ );+ const result = await materializeMdxSource({+ source: sourceState.source,+ identity: createExternalContentIdentity(entry, sourceState),+ data,+ metas: componentMetas,+ projectId: entry.projectId,+ parsed: { source: sourceState.source, result: parsed },+ createUnresolvedTemplateInstance:+ entry.includeUnresolvedTemplatePlaceholders+ ? createBuilderUnresolvedTemplateInstance+ : undefined,+ });+ try {+ const resolved = await resolveExternalContentFrontmatter(+ entry,+ sourceState+ );+ if (resolved !== undefined) {+ return {+ ...result,+ root: { ...result.root, resolvedFrontmatter: resolved },+ };+ }+ } catch (error) {+ const diagnostic: ContentBlockDiagnostic = {+ code: "invalid-mdx",+ severity: "error",+ blockInstanceId: entry.sourceBlockInstanceId,+ assetId: entry.assetId,+ renderScope: entry.renderScope,+ message:+ error instanceof Error+ ? `Unable to resolve frontmatter references: ${error.message}`+ : "Unable to resolve frontmatter references",+ };+ return {+ ...result,+ diagnostics: [...result.diagnostics, diagnostic],+ };+ }+ return result;+};++const rematerializeAsset = async (+ projectId: string,+ assetId: string,+ sourceState: AssetContentSessionState,+ preservedRootKey?: string+) => {+ const preservedEntry =+ preservedRootKey === undefined ? undefined : roots.get(preservedRootKey);+ if (+ preservedEntry?.projectId === projectId &&+ preservedEntry.assetId === assetId+ ) {+ const result = await materialize({ entry: preservedEntry, sourceState });+ if (roots.get(preservedEntry.key) === preservedEntry) {+ // Preserve the synchronously edited fragment and refresh only the+ // source-owned state that does not participate in the current selection.+ preservedEntry.root = {+ ...preservedEntry.root,+ identity: createExternalContentIdentity(preservedEntry, sourceState),+ };+ preservedEntry.diagnostics = result.diagnostics;+ registerMutationRoot(preservedEntry, preservedEntry.installedFragment);+ }+ }+ await Promise.all(+ Array.from(roots.values())+ .filter(+ (entry) =>+ entry.projectId === projectId &&+ (entry.assetId === assetId ||+ entry.dependencyAssetIds.has(assetId)) &&+ entry.key !== preservedRootKey+ )+ .map(async (entry) => {+ const version = ++entry.openVersion;+ const entrySourceState =+ entry.assetId === assetId+ ? sourceState+ : await getSession(projectId).open(entry.assetId);+ const result = await materialize({+ entry,+ sourceState: entrySourceState,+ });+ if (roots.get(entry.key) === entry && entry.openVersion === version) {+ installRoot({ entry, ...result });+ }+ })+ );+};++const getSession = (projectId: string) => {+ const session = getAssetContentBridge().getContentSession?.(projectId);+ if (session === undefined) {+ throw new Error("Builder Asset content session is not available");+ }+ if (subscribedSessions.has(session) === false) {+ subscribedSessions.add(session);+ session.subscribe((assetId, state) => {+ const queueKey = getAssetQueueKey(projectId, assetId);+ if (state.status === "conflicting") {+ getAssetContentBridge().requireReload(+ state.error?.message ??+ "The MDX content source changed before the edit was saved."+ );+ return;+ }+ const queue = assetQueues.get(queueKey);+ if ((queue?.pendingSnapshots ?? 0) === 0 && queue?.error === undefined) {+ void rematerializeAsset(+ projectId,+ assetId,+ state,+ getPreservedRootKey(queue, state)+ );+ }+ });+ }+ return session;+};++const extractRootFragment = ({+ contentInstanceId,+ children: rootChildren,+ transientInstanceIds,+}: {+ contentInstanceId: string;+ children: WebstudioFragment["children"];+ transientInstanceIds: ReadonlySet<string>;+}) => {+ const data = getWebstudioData();+ if (data.instances.has(contentInstanceId) === false) {+ throw new Error("Connected Content Block no longer exists");+ }+ const isPersistentChild = (child: WebstudioFragment["children"][number]) =>+ child.type !== "id" || transientInstanceIds.has(child.value) === false;+ const children = rootChildren.filter(isPersistentChild);+ const rootIds = children.flatMap((child) =>+ child.type === "id" ? [child.value] : []+ );+ const fragment = mergeWebstudioFragments(+ rootIds,+ rootIds.map((id) => extractWebstudioFragment(data, id))+ );+ return {+ ...fragment,+ children,+ instances: fragment.instances+ .filter(({ id }) => transientInstanceIds.has(id) === false)+ .map((instance) => ({+ ...instance,+ children: instance.children.filter(isPersistentChild),+ })),+ };+};++const extractCurrentFragment = (entry: RootEntry) =>+ extractRootFragment({+ contentInstanceId: entry.contentInstanceId,+ children: getAuthoredChildren(entry),+ transientInstanceIds: entry.transientInstanceIds,+ });++const captureInstalledFragment = (+ entry: RootEntry,+ fragment: WebstudioFragment+): WebstudioFragment => {+ const data = getWebstudioData();+ const transientInstances = Array.from(entry.transientInstanceIds).flatMap(+ (id) => {+ const instance = data.instances.get(id);+ return instance === undefined ? [] : [instance];+ }+ );+ return {+ ...fragment,+ instances: [...fragment.instances, ...transientInstances],+ };+};++const getInsertedTemplateNames = (+ entry: RootEntry,+ fragment: WebstudioFragment+) => {+ const data = getWebstudioData();+ const block = data.instances.get(entry.blockInstanceId);+ const templates =+ block === undefined+ ? undefined+ : findContentBlockTemplateContainers({+ blockInstance: block,+ instances: data.instances,+ })[0];+ const availableNames = new Set(+ templates?.children.flatMap((child) => {+ const instance =+ child.type === "id" ? data.instances.get(child.value) : undefined;+ return instance === undefined+ ? []+ : [getInstanceName({ instance, metas: componentMetas })];+ }) ?? []+ );+ const authoredIds = new Set(+ entry.root.fragment.instances.map(({ id }) => id)+ );+ return new Map(+ fragment.children.flatMap((child) => {+ const instance =+ child.type === "id" && authoredIds.has(child.value) === false+ ? data.instances.get(child.value)+ : undefined;+ if (instance === undefined) {+ return [];+ }+ const name = getInstanceName({ instance, metas: componentMetas });+ return availableNames.has(name) ? [[instance.id, name] as const] : [];+ })+ );+};++const enqueueAssetUpdate = ({+ projectId,+ assetId,+ update,+ preservedRootKey,+}: {+ projectId: string;+ assetId: string;+ update: AssetUpdate;+ preservedRootKey?: string;+}) => {+ const queue = getAssetQueue(projectId, assetId);+ const session = getSession(projectId);+ queue.preservedRootKey = preservedRootKey;+ queue.pendingSnapshots += 1;+ queue.error = undefined;+ publishAssetQueueError(queue);+ const saving = queue.serialization.then(async () => {+ const state = session.get(assetId);+ if (state === undefined) {+ throw new Error(`Asset content session "${assetId}" is not open`);+ }+ const prepared = await update(+ state,+ queue.latestDocument?.source === state.source+ ? queue.latestDocument.document+ : undefined+ );+ if (prepared === undefined) {+ return;+ }+ const source = typeof prepared === "string" ? prepared : prepared.source;+ queue.latestDocument =+ typeof prepared === "string"+ ? undefined+ : { source, document: prepared.document };+ session.save(assetId, source);+ });+ let succeeded = false;+ const tracked = saving.then(+ () => {+ succeeded = true;+ queue.failedUpdate = undefined;+ queue.failedPreservedRootKey = undefined;+ queue.error = undefined;+ publishAssetQueueError(queue);+ },+ (error) => {+ queue.failedUpdate = update;+ queue.failedPreservedRootKey = preservedRootKey;+ queue.error =+ error instanceof Error+ ? error+ : new Error("Unable to prepare MDX save");+ if (queue.error instanceof MdxAuthoredContentConflictError) {+ getAssetContentBridge().requireReload(queue.error.message);+ }+ publishAssetQueueError(queue);+ throw queue.error;+ }+ );+ queue.serialization = tracked+ .catch(() => {})+ .then(async () => {+ queue.pendingSnapshots -= 1;+ if (queue.pendingSnapshots === 0 && succeeded) {+ const state = session.get(assetId);+ if (state !== undefined) {+ await rematerializeAsset(+ projectId,+ assetId,+ state,+ getPreservedRootKey(queue, state)+ );+ }+ }+ });+ return tracked;+};++subscribeExternalContentMutations((rootKeys) => {+ for (const key of rootKeys) {+ const entry = roots.get(key);+ if (entry === undefined) {+ continue;+ }+ // A local mutation supersedes any materialization that started from an+ // older session snapshot. The queued save will rematerialize the Asset+ // after the newest local document is installed in the session.+ entry.openVersion += 1;+ const fragment = extractCurrentFragment(entry);+ const persistedFragment = omitTransientEmptyMarkdownDrafts({+ root: entry.root,+ fragment,+ });+ const insertedTemplateNames = getInsertedTemplateNames(entry, fragment);+ const authoredRoot = entry.root;+ const saveRevision = ++entry.saveRevision;+ entry.installedFragment = captureInstalledFragment(entry, fragment);+ registerMutationRoot(entry, entry.installedFragment);+ void enqueueAssetUpdate({+ projectId: entry.projectId,+ assetId: entry.assetId,+ preservedRootKey: entry.key,+ update: async (state, queuedDocument) => {+ if (+ roots.get(entry.key) === entry &&+ entry.saveRevision !== saveRevision+ ) {+ return;+ }+ const latestIsLocal = queuedDocument !== undefined;+ let latestDocument = queuedDocument;+ if (latestDocument === undefined) {+ const latest = await parseAssetSource(+ entry.projectId,+ entry.assetId,+ state.source+ );+ if (latest.status !== "parsed") {+ throw new Error(+ "The MDX content source must be structurally valid before canvas edits can be saved."+ );+ }+ latestDocument = latest.document;+ }+ let saveRoot = authoredRoot;+ let saveFragment = persistedFragment;+ let saveInsertedTemplateNames = insertedTemplateNames;+ if (roots.get(entry.key) === entry) {+ const currentFragment = extractCurrentFragment(entry);+ saveRoot = entry.root;+ saveFragment = omitTransientEmptyMarkdownDrafts({+ root: saveRoot,+ fragment: currentFragment,+ });+ saveInsertedTemplateNames = getInsertedTemplateNames(+ entry,+ currentFragment+ );+ } else if (entry.saveRevision !== saveRevision) {+ return;+ }+ const document = await rebaseMdxAuthoredContent({+ root: saveRoot,+ fragment: saveFragment,+ latest: latestDocument,+ latestRevision: createExternalContentIdentity(entry, state).revision,+ latestIsLocal,+ insertedTemplateNames: saveInsertedTemplateNames,+ });+ const source = serializeMdxDocument(document);+ if (roots.get(entry.key) !== entry) {+ return { source, document };+ }+ const materialized = await materialize({+ entry,+ sourceState: { ...state, source },+ });+ if (roots.get(entry.key) !== entry) {+ return;+ }+ try {+ entry.root = adoptMdxAuthoredContentFragment({+ root: materialized.root,+ fragment: saveFragment,+ });+ } catch {+ // A concurrent file edit can add content that is absent from this+ // occurrence. Keep the live tree after saving the merged document so+ // a recovery write never replaces the user's local IDs or selection.+ // Other occurrences still rematerialize from the merged source.+ }+ return { source, document };+ },+ }).catch(() => {});+ }+});++export const updateExternalContentAssetSource = ({+ projectId,+ assetId,+ update,+}: {+ projectId: string;+ assetId: string;+ update: (source: string) => string | Promise<string>;+}) =>+ enqueueAssetUpdate({+ projectId,+ assetId,+ update: ({ source }) => update(source),+ });++export const updateExternalContentFrontmatter = ({+ rootKey,+ path,+ value,+ resolvedValue = value,+}: {+ rootKey: string;+ path: readonly string[];+ value: unknown;+ resolvedValue?: unknown;+}) => {+ const entry = roots.get(rootKey);+ if (entry === undefined) {+ return Promise.reject(new Error("Connected Content Block is not open"));+ }+ const properties = setObjectPathValue({+ value: entry.root.document.frontmatter.properties,+ path,+ nextValue: value,+ });+ entry.root = {+ ...entry.root,+ document: {+ ...entry.root.document,+ frontmatter: { properties },+ },+ resolvedFrontmatter: setObjectPathValue({+ value:+ entry.root.resolvedFrontmatter ??+ entry.root.document.frontmatter.properties,+ path,+ nextValue: resolvedValue,+ }),+ };+ registerMutationRoot(entry, entry.installedFragment);+ return enqueueAssetUpdate({+ projectId: entry.projectId,+ assetId: entry.assetId,+ preservedRootKey: entry.key,+ update: async (state, queuedDocument) => {+ if (queuedDocument !== undefined) {+ const latestProperties = setObjectPathValue({+ value: queuedDocument.frontmatter.properties,+ path,+ nextValue: value,+ });+ const document = {+ ...queuedDocument,+ frontmatter: { properties: latestProperties },+ };+ return { source: serializeMdxDocument(document), document };+ }+ const parsed = await parseAssetSource(+ entry.projectId,+ entry.assetId,+ state.source+ );+ if (parsed.status !== "parsed") {+ throw new Error(+ "The MDX content source must be structurally valid before frontmatter can be saved."+ );+ }+ const latestProperties = setObjectPathValue({+ value: parsed.document.frontmatter.properties,+ path,+ nextValue: value,+ });+ const source = await replaceMdxFrontmatter({+ source: state.source,+ properties: latestProperties,+ });+ const updated = await parseAssetSource(+ entry.projectId,+ entry.assetId,+ source+ );+ return updated.status === "parsed"+ ? { source, document: updated.document }+ : source;+ },+ });+};++export const replaceExternalContentAssetSource = ({+ projectId,+ assetId,+ expectedSource,+ source,+}: {+ projectId: string;+ assetId: string;+ expectedSource: string;+ source: string;+}) =>+ enqueueAssetUpdate({+ projectId,+ assetId,+ update: ({ source: currentSource }) => {+ if (currentSource !== expectedSource) {+ throw new MdxAuthoredContentConflictError(+ "The MDX content source changed before the file edit was saved."+ );+ }+ return source;+ },+ });++export const acquireExternalContentRoot = async ({+ projectId,+ assetId,+ blockInstanceId,+ renderScope,+ includeUnresolvedTemplatePlaceholders = true,+ signal,+}: {+ projectId: string;+ assetId: string;+ blockInstanceId: string;+ renderScope: string;+ includeUnresolvedTemplatePlaceholders?: boolean;+ signal?: AbortSignal;+}) => {+ const key = getRootKey(projectId, blockInstanceId, renderScope);+ const existing = roots.get(key);+ if (+ existing?.assetId === assetId &&+ existing.includeUnresolvedTemplatePlaceholders ===+ includeUnresolvedTemplatePlaceholders+ ) {+ existing.references += 1;+ return () => releaseExternalContentRoot(key, existing);+ }+ if (existing !== undefined) {+ roots.delete(key);+ existing.unregisterMutationRoot();+ uninstallRoot(existing);+ }+ const openGeneration = (rootOpenGenerations.get(key)?.value ?? 0) + 1;+ rootOpenGenerations.set(key, { projectId, value: openGeneration });+ const session = getSession(projectId);+ const sourceState = await session.open(assetId);+ if (+ signal?.aborted ||+ rootOpenGenerations.get(key)?.value !== openGeneration+ ) {+ return () => {};+ }+ const placeholderRoot: MaterializedMdxAuthoredContentRoot = {+ identity: {+ blockInstanceId,+ assetId,+ revision: "loading",+ contentRef: sourceState.asset.name,+ format: "mdx",+ renderScope,+ },+ fragment: createEmptyWebstudioFragment(),+ document: { frontmatter: { properties: {} }, children: [] },+ provenance: { nodes: [], unresolvedTemplates: [] },+ };+ const instanceSelector = parseContentBlockRenderScope(renderScope);+ const sourceBlock = getWebstudioData().instances.get(blockInstanceId);+ if (sourceBlock === undefined) {+ throw new Error("Connected Content Block no longer exists");+ }+ const bodyPaths = findContentBlockBodyContainerPaths({+ blockInstance: sourceBlock,+ instances: getWebstudioData().instances,+ });+ if (bodyPaths.length > 1) {+ throw new Error("Content Block must contain at most one Body outlet");+ }+ const sourceContentInstanceId = bodyPaths[0]?.at(-1)?.id ?? blockInstanceId;+ const runtimeBlockInstanceId =+ instanceSelector !== undefined &&+ isRepeatedContentBlockOccurrence({+ instanceSelector,+ instances: getWebstudioData().instances,+ })+ ? createMdxScopeIdGenerator({+ identity: placeholderRoot.identity,+ path: [-1],+ })()+ : blockInstanceId;+ const runtimeContentInstanceId =+ runtimeBlockInstanceId === blockInstanceId ||+ sourceContentInstanceId === blockInstanceId+ ? sourceContentInstanceId === blockInstanceId+ ? runtimeBlockInstanceId+ : sourceContentInstanceId+ : createMdxScopeIdGenerator({+ identity: placeholderRoot.identity,+ path: [-2],+ })();+ const entry: RootEntry = {+ key,+ projectId,+ assetId,+ sourceBlockInstanceId: blockInstanceId,+ blockInstanceId: runtimeBlockInstanceId,+ sourceContentInstanceId,+ contentInstanceId: runtimeContentInstanceId,+ renderScope,+ root: placeholderRoot,+ installedFragment: placeholderRoot.fragment,+ transientInstanceIds: new Set(),+ diagnostics: [],+ includeUnresolvedTemplatePlaceholders,+ unregisterMutationRoot: () => {},+ references: 1,+ openVersion: 0,+ saveRevision: 0,+ dependencyAssetIds: new Set([assetId]),+ };+ roots.set(key, entry);+ registerMutationRoot(entry, placeholderRoot.fragment);+ const result = await materialize({ entry, sourceState });+ if (roots.get(key) === entry) {+ installRoot({ entry, ...result });+ }+ return () => releaseExternalContentRoot(key, entry);+};++export const flushExternalContentAsset = async ({+ projectId,+ assetId,+}: {+ projectId: string;+ assetId: string;+}) => {+ await assetQueues.get(getAssetQueueKey(projectId, assetId))?.serialization;+ const state = await getSession(projectId).flush(assetId);+ await rematerializeAsset(+ projectId,+ assetId,+ state,+ getPreservedRootKey(+ assetQueues.get(getAssetQueueKey(projectId, assetId)),+ state+ )+ );+ return state;+};++export const flushExternalContentProject = async ({+ projectId,+ session = getSession(projectId),+}: {+ projectId: string;+ session?: AssetContentSession;+}) => {+ while (true) {+ const queues = await settleProjectAssetQueues(projectId);+ const serializations = queues.map((queue) => queue.serialization);+ await session.flushAll();+ const currentQueues = Array.from(assetQueues.values()).filter(+ (queue) => queue.projectId === projectId+ );+ if (+ currentQueues.length === queues.length &&+ currentQueues.every(+ (queue, index) =>+ queue === queues[index] &&+ queue.serialization === serializations[index]+ )+ ) {+ return;+ }+ }+};++export const openExternalContentAsset = ({+ projectId,+ assetId,+}: {+ projectId: string;+ assetId: string;+}) => getSession(projectId).open(assetId);++export const reloadExternalContentAsset = ({+ projectId,+ assetId,+ expectedName,+}: {+ projectId: string;+ assetId: string;+ expectedName: string;+}) => getSession(projectId).reload(assetId, { expectedName });++export const retryExternalContentAsset = ({+ projectId,+ assetId,+}: {+ projectId: string;+ assetId: string;+}) => {+ const queue = getAssetQueue(projectId, assetId);+ if (queue.failedUpdate !== undefined) {+ return enqueueAssetUpdate({+ projectId,+ assetId,+ update: queue.failedUpdate,+ preservedRootKey: queue.failedPreservedRootKey,+ }).then(() => getSession(projectId).get(assetId));+ }+ return getSession(projectId).retry(assetId);+};++export const subscribeExternalContentAsset = ({+ projectId,+ assetId,+ listener,+}: {+ projectId: string;+ assetId: string;+ listener: (state: AssetContentSessionState) => void;+}) => {+ const session = getSession(projectId);+ const queue = getAssetQueue(projectId, assetId);+ const publish = (state: AssetContentSessionState) =>+ listener(+ queue.error === undefined+ ? state+ : { ...state, status: "failed", error: queue.error }+ );+ const current = session.get(assetId);+ if (current !== undefined) {+ publish(current);+ }+ const unsubscribe = session.subscribe((changedAssetId, state) => {+ if (changedAssetId === assetId) {+ publish(state);+ }+ });+ const queueListener = () => {+ const state = session.get(assetId);+ if (state !== undefined) {+ publish(state);+ }+ };+ queue.listeners.add(queueListener);+ return () => {+ unsubscribe();+ queue.listeners.delete(queueListener);+ };+};++export const getExternalContentRootSnapshot = ({+ projectId,+ blockInstanceId,+ renderScope,+}: {+ projectId: string;+ blockInstanceId: string;+ renderScope: string;+}) => {+ const key = getRootKey(projectId, blockInstanceId, renderScope);+ const entry = roots.get(key);+ if (entry !== undefined) {+ return {+ assetId: entry.assetId,+ diagnostics: entry.diagnostics,+ fragment: extractCurrentFragment(entry),+ identity: entry.root.identity,+ };+ }+ const root = getExternalContentRoots().get(key);+ if (+ root?.projectId !== projectId ||+ root.identity === undefined ||+ root.identity.assetId === ""+ ) {+ return;+ }+ return {+ assetId: root.identity.assetId,+ diagnostics: root.diagnostics ?? [],+ fragment: extractRootFragment({+ contentInstanceId: root.contentInstanceId ?? root.blockInstanceId,+ children:+ getWebstudioData().instances.get(+ root.contentInstanceId ?? root.blockInstanceId+ )?.children ?? [],+ transientInstanceIds: root.transientInstanceIds ?? new Set(),+ }),+ identity: root.identity,+ };+};++export const getExternalContentRootChildren = ({+ projectId,+ blockInstanceId,+ renderScope,+}: {+ projectId: string;+ blockInstanceId: string;+ renderScope: string;+}) => {+ if (+ roots.has(getRootKey(projectId, blockInstanceId, renderScope)) === false+ ) {+ return;+ }+ const data = getWebstudioData();+ const root = getExternalContentRoots().get(+ getRootKey(projectId, blockInstanceId, renderScope)+ );+ if (root === undefined) {+ return;+ }+ const contentInstanceId = root.contentInstanceId ?? root.blockInstanceId;+ return (data.instances.get(contentInstanceId)?.children ?? []).filter(+ (child) =>+ child.type !== "id" ||+ data.instances.get(child.value)?.component !== blockTemplateComponent+ );+};++export const getExternalContentRootAssets = ({+ projectId,+ blockInstanceIds,+ renderScopes,+}: {+ projectId: string;+ blockInstanceIds: ReadonlySet<string>;+ renderScopes?: ReadonlySet<string>;+}) => {+ const assets = new Map<string, WebstudioFragment["assets"][number]>();+ const projectAssets = getWebstudioData().assets;+ for (const entry of roots.values()) {+ if (+ entry.projectId !== projectId ||+ blockInstanceIds.has(entry.sourceBlockInstanceId) === false ||+ (renderScopes !== undefined &&+ renderScopes.has(entry.renderScope) === false)+ ) {+ continue;+ }+ const sourceAsset = projectAssets.get(entry.assetId);+ if (sourceAsset !== undefined) {+ assets.set(sourceAsset.id, sourceAsset);+ }+ for (const assetId of entry.dependencyAssetIds) {+ const asset = projectAssets.get(assetId);+ if (asset !== undefined) {+ assets.set(asset.id, asset);+ }+ }+ for (const asset of entry.root.fragment.assets) {+ assets.set(asset.id, asset);+ }+ }+ return Array.from(assets.values());+};++export const disposeExternalContentProject = async ({+ projectId,+ session,+ shouldCleanup = () => true,+}: {+ projectId: string;+ session: AssetContentSession;+ shouldCleanup?: () => boolean;+}) => {+ const uninstall = $project.get()?.id === projectId;+ for (const [key, entry] of roots) {+ if (entry.projectId !== projectId) {+ continue;+ }+ roots.delete(key);+ rootOpenGenerations.set(key, {+ projectId,+ value: (rootOpenGenerations.get(key)?.value ?? 0) + 1,+ });+ entry.unregisterMutationRoot();+ if (uninstall) {+ uninstallRoot(entry);+ }+ }+ for (const [key, generation] of rootOpenGenerations) {+ if (generation.projectId === projectId) {+ rootOpenGenerations.set(key, {+ projectId,+ value: generation.value + 1,+ });+ }+ }+ const queues = Array.from(assetQueues.entries()).filter(+ ([, queue]) => queue.projectId === projectId+ );+ await settleProjectAssetQueues(projectId);+ await session.flushAll();+ if (shouldCleanup() === false) {+ return false;+ }+ for (const [key, queue] of queues) {+ if (assetQueues.get(key) === queue) {+ assetQueues.delete(key);+ }+ }+ for (const [key, generation] of rootOpenGenerations) {+ if (generation.projectId === projectId) {+ rootOpenGenerations.delete(key);+ }+ }+ subscribedSessions.delete(session);+ return true;+};++const releaseExternalContentRoot = (key: string, entry: RootEntry) => {+ entry.references -= 1;+ if (entry.references > 0 || roots.get(key) !== entry) {+ return;+ }+ roots.delete(key);+ rootOpenGenerations.set(key, {+ projectId: entry.projectId,+ value: (rootOpenGenerations.get(key)?.value ?? 0) + 1,+ });+ entry.unregisterMutationRoot();+ uninstallRoot(entry);+};diff --git a/apps/builder/app/shared/instance-utils/data.test.tsx b/apps/builder/app/shared/instance-utils/data.test.tsxindex 693a738e40..4dd43eda4a 100644--- a/apps/builder/app/shared/instance-utils/data.test.tsx+++ b/apps/builder/app/shared/instance-utils/data.test.tsx@@ -1,5 +1,12 @@import { describe, expect, expectTypeOf, test } from "vitest";-import type { Asset, Instance, PageTemplate } from "@webstudio-is/sdk";+import {+ blockComponent,+ blockTemplateComponent,+ elementComponent,+ type Asset,+ type Instance,+ type PageTemplate,+} from "@webstudio-is/sdk";import { createDefaultPages } from "@webstudio-is/project-build";import { findCycles } from "@webstudio-is/project-build/runtime";import type { BuilderRuntimeOperationInput } from "@webstudio-is/project-build/runtime";@@ -11,7 +18,11 @@ import {migrateLoadedWebstudioData,type RuntimeMutationOperation,} from "./data";-import { registerContainers, serverSyncStore } from "../sync/sync-stores";+import {+ externalContentSyncStore,+ registerContainers,+ serverSyncStore,+} from "../sync/sync-stores";import {$assets,$breakpoints,@@ -27,6 +38,8 @@ import {} from "../sync/data-stores";import { $selectedPageId } from "../nano-states/pages";import { $authPermit, $builderMode } from "../nano-states/misc";+import { selectInstance } from "../nano-states";+import { $externalContentRoots } from "../external-content-mutations";const createInstance = (id: Instance["id"],@@ -51,6 +64,11 @@ const setBaseStores = () => {serverSyncStore.transactionManager.currentStack = [];serverSyncStore.transactionManager.undoneStack = [];serverSyncStore.popAll();+ externalContentSyncStore.transactionManager.currentStack = [];+ externalContentSyncStore.transactionManager.undoneStack = [];+ externalContentSyncStore.popAll();+ $externalContentRoots.set(new Map());+ selectInstance(undefined);const pages = createDefaultPages({ rootInstanceId: "body" });$pages.set(pages);$selectedPageId.set(pages.homePageId);@@ -90,6 +108,347 @@ const createImageAsset = (id: string): Asset => ({});describe("data store helpers", () => {+ test("publishes external children only after their instances exist", () => {+ setBaseStores();+ $instances.set(+ new Map([+ [+ "body",+ createInstance("body", "Body", [{ type: "id", value: "block" }]),+ ],+ [+ "block",+ createInstance("block", blockComponent, [+ { type: "id", value: "templates" },+ ]),+ ],+ ["templates", createInstance("templates", blockTemplateComponent, [])],+ ])+ );+ $externalContentRoots.set(+ new Map([+ [+ "root",+ {+ blockInstanceId: "block",+ renderScope: JSON.stringify(["block", "body"]),+ instanceIds: new Set<string>(),+ mutationRevision: 0,+ },+ ],+ ])+ );+ selectInstance(["block", "body"]);+ const missingInstanceIds: string[] = [];+ const unsubscribe = $instances.listen((instances) => {+ for (const child of instances.get("block")?.children ?? []) {+ if (child.type === "id" && instances.has(child.value) === false) {+ missingInstanceIds.push(child.value);+ }+ }+ });++ executeRuntimeMutation({+ id: "instances.insertFragment",+ input: {+ parentInstanceId: "block",+ fragment: {+ children: [{ type: "id", value: "paragraph-template" }],+ instances: [+ {+ ...createInstance("paragraph-template", elementComponent, []),+ tag: "p",+ },+ ],+ styleSourceSelections: [],+ styleSources: [],+ breakpoints: [],+ styles: [],+ dataSources: [],+ resources: [],+ props: [],+ assets: [],+ },+ },+ });+ unsubscribe();++ expect($instances.get().get("block")?.children).toHaveLength(2);+ expect(missingInstanceIds).toEqual([]);+ });++ test("deletes only the selected external child and preserves the normal focus target", () => {+ setBaseStores();+ $instances.set(+ new Map([+ [+ "body",+ createInstance("body", "Body", [{ type: "id", value: "block" }]),+ ],+ [+ "block",+ createInstance("block", blockComponent, [+ { type: "id", value: "templates" },+ { type: "id", value: "previous-paragraph" },+ { type: "id", value: "paragraph" },+ { type: "id", value: "next-paragraph" },+ ]),+ ],+ ["templates", createInstance("templates", blockTemplateComponent, [])],+ [+ "previous-paragraph",+ {+ ...createInstance("previous-paragraph", elementComponent, []),+ tag: "p",+ },+ ],+ [+ "paragraph",+ {+ ...createInstance("paragraph", elementComponent, []),+ tag: "p",+ },+ ],+ [+ "next-paragraph",+ {+ ...createInstance("next-paragraph", elementComponent, []),+ tag: "p",+ },+ ],+ ])+ );+ $externalContentRoots.set(+ new Map([+ [+ "root",+ {+ blockInstanceId: "block",+ renderScope: JSON.stringify(["block", "body"]),+ instanceIds: new Set([+ "previous-paragraph",+ "paragraph",+ "next-paragraph",+ ]),+ mutationRevision: 0,+ },+ ],+ ])+ );+ selectInstance(["paragraph", "block", "body"]);+ const missingInstanceIds: string[] = [];+ const unsubscribeInstances = $instances.subscribe((instances) => {+ for (const child of instances.get("block")?.children ?? []) {+ if (child.type === "id" && instances.has(child.value) === false) {+ missingInstanceIds.push(child.value);+ }+ }+ });++ const result = executeRuntimeMutation({+ id: "instances.deleteBySelector",+ input: { instanceSelector: ["paragraph", "block", "body"] },+ });+ unsubscribeInstances();++ expect(result?.result.instanceSelector).toEqual([+ "next-paragraph",+ "block",+ "body",+ ]);+ expect($instances.get().get("block")?.children).toEqual([+ { type: "id", value: "templates" },+ { type: "id", value: "previous-paragraph" },+ { type: "id", value: "next-paragraph" },+ ]);+ expect($instances.get().has("previous-paragraph")).toBe(true);+ expect($instances.get().has("paragraph")).toBe(false);+ expect($instances.get().has("next-paragraph")).toBe(true);+ expect(missingInstanceIds).toEqual([]);+ });++ test("mutates only the selected scoped Content Block occurrence", () => {+ setBaseStores();+ $instances.set(+ new Map([+ [+ "body",+ createInstance("body", "Body", [{ type: "id", value: "collection" }]),+ ],+ [+ "collection",+ createInstance("collection", "Collection", [+ { type: "id", value: "block" },+ ]),+ ],+ [+ "block",+ createInstance("block", blockComponent, [+ { type: "id", value: "templates" },+ ]),+ ],+ ["templates", createInstance("templates", blockTemplateComponent, [])],+ [+ "scoped-block",+ createInstance("scoped-block", blockComponent, [+ { type: "id", value: "templates" },+ { type: "id", value: "previous-paragraph" },+ { type: "id", value: "paragraph" },+ ]),+ ],+ [+ "previous-paragraph",+ {+ ...createInstance("previous-paragraph", elementComponent, []),+ tag: "p",+ },+ ],+ [+ "paragraph",+ {+ ...createInstance("paragraph", elementComponent, []),+ tag: "p",+ },+ ],+ ])+ );+ const scopedSelector = [+ "scoped-block",+ "collection[first]",+ "collection",+ "body",+ ];+ $externalContentRoots.set(+ new Map([+ [+ "root",+ {+ sourceBlockInstanceId: "block",+ sourceRenderScope: JSON.stringify([+ "block",+ "collection[first]",+ "collection",+ "body",+ ]),+ blockInstanceId: "scoped-block",+ renderScope: JSON.stringify(scopedSelector),+ instanceIds: new Set(["previous-paragraph", "paragraph"]),+ mutationRevision: 0,+ },+ ],+ ])+ );+ selectInstance(["paragraph", ...scopedSelector]);+ serverSyncStore.popAll();++ const result = executeRuntimeMutation({+ id: "instances.deleteBySelector",+ input: { instanceSelector: ["paragraph", ...scopedSelector] },+ });++ expect(result?.result.instanceSelector).toEqual([+ "previous-paragraph",+ ...scopedSelector,+ ]);+ expect($instances.get().get("scoped-block")?.children).toEqual([+ { type: "id", value: "templates" },+ { type: "id", value: "previous-paragraph" },+ ]);+ expect($instances.get().get("block")?.children).toEqual([+ { type: "id", value: "templates" },+ ]);+ expect(serverSyncStore.popAll()).toEqual([]);+ expect($externalContentRoots.get().get("root")?.mutationRevision).toBe(1);+ });++ test("persists both external roots when content moves between them", () => {+ setBaseStores();+ $instances.set(+ new Map([+ [+ "body",+ createInstance("body", "Body", [+ { type: "id", value: "source-block" },+ { type: "id", value: "target-block" },+ ]),+ ],+ [+ "source-block",+ createInstance("source-block", blockComponent, [+ { type: "id", value: "source-templates" },+ { type: "id", value: "paragraph" },+ ]),+ ],+ [+ "target-block",+ createInstance("target-block", blockComponent, [+ { type: "id", value: "target-templates" },+ ]),+ ],+ [+ "source-templates",+ createInstance("source-templates", blockTemplateComponent, []),+ ],+ [+ "target-templates",+ createInstance("target-templates", blockTemplateComponent, []),+ ],+ [+ "paragraph",+ {+ ...createInstance("paragraph", elementComponent, []),+ tag: "p",+ },+ ],+ ])+ );+ $externalContentRoots.set(+ new Map([+ [+ "source-root",+ {+ blockInstanceId: "source-block",+ renderScope: JSON.stringify(["source-block", "body"]),+ instanceIds: new Set(["paragraph"]),+ mutationRevision: 0,+ },+ ],+ [+ "target-root",+ {+ blockInstanceId: "target-block",+ renderScope: JSON.stringify(["target-block", "body"]),+ instanceIds: new Set<string>(),+ mutationRevision: 0,+ },+ ],+ ])+ );+ serverSyncStore.popAll();++ executeRuntimeMutation({+ id: "instances.move",+ input: {+ moves: [{ instanceId: "paragraph", parentInstanceId: "target-block" }],+ },+ });++ expect($instances.get().get("source-block")?.children).toEqual([+ { type: "id", value: "source-templates" },+ ]);+ expect($instances.get().get("target-block")?.children).toEqual([+ { type: "id", value: "target-templates" },+ { type: "id", value: "paragraph" },+ ]);+ expect(serverSyncStore.popAll()).toEqual([]);+ expect(+ Array.from(+ $externalContentRoots.get().values(),+ ({ mutationRevision }) => mutationRevision+ )+ ).toEqual([1, 1]);+ });+test("getWebstudioData reads all instance-related stores", () => {const pages = createDefaultPages({ rootInstanceId: "body" });const instances = new Map([["body", createInstance("body", "Body", [])]]);diff --git a/apps/builder/app/shared/instance-utils/data.ts b/apps/builder/app/shared/instance-utils/data.tsindex eea941bb8a..8ad74920da 100644--- a/apps/builder/app/shared/instance-utils/data.ts+++ b/apps/builder/app/shared/instance-utils/data.ts@@ -4,20 +4,36 @@import { toast } from "@webstudio-is/design-system";import { type WebstudioData, isPageTemplate } from "@webstudio-is/sdk";import {+ BuilderRuntimeError,+ blockTemplateNameConfirmationInput,+ builderRuntimeContext,executeBuilderRuntimeOperation,createRuntimeMutationAccumulator,+ type BuilderRuntimeContext,+ type BuilderRuntimeMutation,type BuilderRuntimeOperationInput,type BuilderRuntimeMutationOperationId,type BuilderRuntimeOperationResult,} from "@webstudio-is/project-build/runtime";-import {- builderRuntimeContext,- type BuilderRuntimeContext,-} from "@webstudio-is/project-build/runtime";-import { type BuilderRuntimeMutation } from "@webstudio-is/project-build/runtime";+import { applyBuilderPatchTransactions } from "@webstudio-is/project-build/state";+import { atom } from "nanostores";import { $canOpenPageTemplates, $selectedPage } from "../nano-states";-import { createTransactionFromBuilderPatchPayload } from "../sync/builder-patch";+import {+ createSyncChangesFromBuilderPatchPayload,+ createTransactionFromBuilderPatchPayload,+} from "../sync/builder-patch";import { $project, readBuilderStateStores } from "../sync/data-stores";+import { externalContentSyncStore } from "../sync/sync-stores";+import {+ getAffectedExternalContentRootKeys,+ getExternalContentRoots,+ publishExternalContentMutation,+} from "../external-content-mutations";+import {+ createExternalContentPersistencePlan,+ getExternalContentOwnership,+ getExternalContentOwnershipFromState,+} from "../external-content-persistence";type RuntimeMutationResult<Id extends BuilderRuntimeMutationOperationId> =Extract<BuilderRuntimeOperationResult<Id>, BuilderRuntimeMutation>;@@ -29,6 +45,53 @@ export type RuntimeMutationOperation = {};}[BuilderRuntimeMutationOperationId];+type TemplateNameConfirmation = ReturnType<+ typeof blockTemplateNameConfirmationInput.parse+>;+type PendingTemplateNameConfirmation =+ | {+ operation: RuntimeMutationOperation;+ confirmation: TemplateNameConfirmation;+ asynchronous?: boolean;+ }+ | {+ operations: readonly RuntimeMutationOperation[];+ operationIndex: number;+ confirmation: TemplateNameConfirmation;+ };++export const $pendingTemplateNameConfirmation = atom<+ PendingTemplateNameConfirmation | undefined+>(undefined);++const getTemplateNameConfirmation = (error: unknown) => {+ if (error instanceof BuilderRuntimeError === false) {+ return;+ }+ const issue = error.issues?.find(+ ({ code }) => code === "template_name_change_requires_confirmation"+ );+ const parsed = blockTemplateNameConfirmationInput.safeParse(issue?.example);+ return parsed.success ? parsed.data : undefined;+};++const addTemplateNameConfirmation = (+ operation: RuntimeMutationOperation,+ confirmation: TemplateNameConfirmation+) =>+ ({+ ...operation,+ input: { ...operation.input, templateNameConfirmation: confirmation },+ }) as RuntimeMutationOperation;++export const getDuplicateTemplateNameMessage = (error: unknown) => {+ if (error instanceof BuilderRuntimeError === false) {+ return;+ }+ return error.issues?.find(({ code }) => code === "duplicate_template_name")+ ?.message;+};+export type WebstudioInstanceData = Pick<WebstudioData,| "instances"@@ -98,10 +161,62 @@ const createRuntimeMutationArgs = <const commitRuntimeMutation = <Mutation extends BuilderRuntimeMutation>(result: Mutation): Mutation => {- createTransactionFromBuilderPatchPayload({- data: getWebstudioData(),- payload: result.payload,+ const data = getWebstudioData();+ const roots = getExternalContentRoots();+ const payload = result.payload;+ const affectedRootKeys = new Set(+ getAffectedExternalContentRootKeys({ state: data, roots, payload })+ );+ if (affectedRootKeys.size === 0) {+ createTransactionFromBuilderPatchPayload({ data, payload });+ return result;+ }+ const beforeOwnership = getExternalContentOwnership(roots);+ const afterData = applyBuilderPatchTransactions(data, [+ { id: "external-content-persistence-plan", payload },+ ]).state as ReturnType<typeof getWebstudioData>;+ const afterOwnership = getExternalContentOwnershipFromState({+ state: afterData,+ roots,+ rootKeys: affectedRootKeys,});+ const plan = createExternalContentPersistencePlan({+ beforeData: data,+ afterData,+ beforeOwnership,+ afterOwnership,+ externalBlockInstanceIds: new Set(+ Array.from(+ roots.values(),+ ({ blockInstanceId, contentInstanceId }) =>+ contentInstanceId ?? blockInstanceId+ )+ ),+ payload,+ });+ if (plan.preliminaryExternalPayload.length > 0) {+ externalContentSyncStore.createTransactionFromChanges(+ createSyncChangesFromBuilderPatchPayload({+ data,+ payload: plan.preliminaryExternalPayload,+ })+ );+ }+ if (plan.projectPayload.length > 0) {+ createTransactionFromBuilderPatchPayload({+ data: getWebstudioData(),+ payload: plan.projectPayload,+ });+ }+ if (plan.externalPayload.length > 0) {+ externalContentSyncStore.createTransactionFromChanges(+ createSyncChangesFromBuilderPatchPayload({+ data: getWebstudioData(),+ payload: plan.externalPayload,+ })+ );+ }+ publishExternalContentMutation(Array.from(affectedRootKeys));return result;};@@ -119,14 +234,71 @@ export const executeRuntimeMutation = <if (canCommitWebstudioData() === false) {return;}- return commitRuntimeMutation(- requireSynchronousResult(- id,- executeBuilderRuntimeOperation<RuntimeMutationResult<Id>>(- createRuntimeMutationArgs({ id, input, context })+ try {+ return commitRuntimeMutation(+ requireSynchronousResult(+ id,+ executeBuilderRuntimeOperation<RuntimeMutationResult<Id>>(+ createRuntimeMutationArgs({ id, input, context })+ ))- )- );+ );+ } catch (error) {+ const confirmation = getTemplateNameConfirmation(error);+ if (confirmation === undefined) {+ throw error;+ }+ $pendingTemplateNameConfirmation.set({+ operation: { id, input } as RuntimeMutationOperation,+ confirmation,+ });+ return;+ }+};++export const abortPendingTemplateNameConfirmation = () => {+ $pendingTemplateNameConfirmation.set(undefined);+};++export const confirmPendingTemplateNameChange = () => {+ const pending = $pendingTemplateNameConfirmation.get();+ if (pending === undefined) {+ return;+ }+ $pendingTemplateNameConfirmation.set(undefined);+ try {+ if ("operations" in pending) {+ executeRuntimeMutationSequence(+ pending.operations.map((operation, index) =>+ index === pending.operationIndex+ ? addTemplateNameConfirmation(operation, pending.confirmation)+ : operation+ )+ );+ return;+ }+ const operation = addTemplateNameConfirmation(+ pending.operation,+ pending.confirmation+ );+ if (pending.asynchronous) {+ void executeRuntimeMutationAsync(operation).catch((error) => {+ toast.error(+ error instanceof Error+ ? error.message+ : "The template change could not be applied."+ );+ });+ } else {+ executeRuntimeMutation(operation);+ }+ } catch (error) {+ toast.error(+ error instanceof Error+ ? error.message+ : "The template change could not be applied."+ );+ }};export const executeRuntimeMutationSequence = (@@ -136,19 +308,35 @@ export const executeRuntimeMutationSequence = (return;}const accumulator = createRuntimeMutationAccumulator(getWebstudioData());- const results = operations.map(({ id, input }) => {- return accumulator.stage(- requireSynchronousResult(- id,- executeBuilderRuntimeOperation<BuilderRuntimeMutation>({- id,- state: accumulator.state,- input,- context: getRuntimeMutationContext(),- })- )- );- });+ const results: Record<string, unknown>[] = [];+ for (const [operationIndex, { id, input }] of operations.entries()) {+ try {+ results.push(+ accumulator.stage(+ requireSynchronousResult(+ id,+ executeBuilderRuntimeOperation<BuilderRuntimeMutation>({+ id,+ state: accumulator.state,+ input,+ context: getRuntimeMutationContext(),+ })+ )+ )+ );+ } catch (error) {+ const confirmation = getTemplateNameConfirmation(error);+ if (confirmation === undefined) {+ throw error;+ }+ $pendingTemplateNameConfirmation.set({+ operations,+ operationIndex,+ confirmation,+ });+ return;+ }+ }commitRuntimeMutation(accumulator.complete({ results }));};@@ -166,10 +354,23 @@ export const executeRuntimeMutationAsync = async <if (canCommitWebstudioData() === false) {return;}- const result = await executeBuilderRuntimeOperation<- RuntimeMutationResult<Id>- >(createRuntimeMutationArgs({ id, input, context }));- return commitRuntimeMutation(result);+ try {+ const result = await executeBuilderRuntimeOperation<+ RuntimeMutationResult<Id>+ >(createRuntimeMutationArgs({ id, input, context }));+ return commitRuntimeMutation(result);+ } catch (error) {+ const confirmation = getTemplateNameConfirmation(error);+ if (confirmation === undefined) {+ throw error;+ }+ $pendingTemplateNameConfirmation.set({+ operation: { id, input } as RuntimeMutationOperation,+ confirmation,+ asynchronous: true,+ });+ return;+ }};export const getWebstudioData = () => {diff --git a/apps/builder/app/shared/instance-utils/selection.ts b/apps/builder/app/shared/instance-utils/selection.tsindex 71e91eecf9..438685cc4e 100644--- a/apps/builder/app/shared/instance-utils/selection.ts+++ b/apps/builder/app/shared/instance-utils/selection.ts@@ -188,6 +188,18 @@ export const canResolveInstanceSelector = (continue;}+ const indexedParentId = getIndexedBaseInstanceId(parentId);+ if (+ indexedParentId !== undefined &&+ instances+ .get(indexedParentId)+ ?.children.some(+ (child) => child.type === "id" && child.value === instanceId+ ) === true+ ) {+ continue;+ }+const parentInstance = instances.get(parentId);if (parentInstance?.children.some(diff --git a/apps/builder/app/shared/nano-states/instance-selection.test.ts b/apps/builder/app/shared/nano-states/instance-selection.test.tsindex 91f5052395..ebb98a59e5 100644--- a/apps/builder/app/shared/nano-states/instance-selection.test.ts+++ b/apps/builder/app/shared/nano-states/instance-selection.test.ts@@ -13,6 +13,7 @@ import {toggleSelectedInstance,} from "./instances";import { $selectedPageId } from "./pages";+import { $externalContentRoots } from "../external-content-mutations";const createInstance = (id: Instance["id"],@@ -29,6 +30,7 @@ beforeEach(() => {$pages.set(undefined);$selectedPageId.set(undefined);selectInstance(undefined);+ $externalContentRoots.set(new Map());});describe("selectInstance", () => {@@ -224,6 +226,24 @@ describe("selection store invariants", () => {expect($allSelectedInstanceSelectors.get()).toEqual([]);});+ test("keeps selectors that resolve through canonical Content Block children", () => {+ const instances = new Map([+ ["body", createInstance("body", [{ type: "id", value: "block" }])],+ ["block", createInstance("block", [{ type: "id", value: "heading" }])],+ ["heading", createInstance("heading")],+ ]);+ $instances.set(instances);+ selectInstance(["heading", "block", "body"]);++ $instances.set(new Map(instances));++ expect($selectedInstanceSelector.get()).toEqual([+ "heading",+ "block",+ "body",+ ]);+ });+test("keeps virtual collection item selectors when their base instance still exists", () => {$instances.set(new Map([@@ -248,6 +268,87 @@ describe("selection store invariants", () => {expect($allSelectedInstanceSelectors.get()).toEqual([]);});++ test("keeps children selected inside a virtual collection item", () => {+ const instances = new Map([+ ["body", createInstance("body", [{ type: "id", value: "collection" }])],+ [+ "collection",+ createInstance("collection", [{ type: "id", value: "block" }]),+ ],+ ["block", createInstance("block")],+ ]);+ $instances.set(instances);+ selectInstance(["block", "collection[first]", "collection", "body"]);++ $instances.set(new Map(instances));++ expect($selectedInstanceSelector.get()).toEqual([+ "block",+ "collection[first]",+ "collection",+ "body",+ ]);+ });++ test("keeps selected external content inside a scoped Content Block", () => {+ const instances = new Map([+ ["body", createInstance("body", [{ type: "id", value: "collection" }])],+ [+ "collection",+ createInstance("collection", [{ type: "id", value: "block" }]),+ ],+ ["block", createInstance("block")],+ [+ "scoped-block",+ createInstance("scoped-block", [{ type: "id", value: "heading" }]),+ ],+ ["heading", createInstance("heading")],+ ]);+ $instances.set(instances);+ $externalContentRoots.set(+ new Map([+ [+ "root",+ {+ sourceBlockInstanceId: "block",+ sourceRenderScope: JSON.stringify([+ "block",+ "collection[first]",+ "collection",+ "body",+ ]),+ blockInstanceId: "scoped-block",+ renderScope: JSON.stringify([+ "scoped-block",+ "collection[first]",+ "collection",+ "body",+ ]),+ instanceIds: new Set(["heading"]),+ mutationRevision: 0,+ },+ ],+ ])+ );+ selectInstance([+ "heading",+ "scoped-block",+ "collection[first]",+ "collection",+ "body",+ ]);++ $instances.set(new Map(instances));++ expect($selectedInstanceSelector.get()).toEqual([+ "heading",+ "scoped-block",+ "collection[first]",+ "collection",+ "body",+ ]);+ });});describe("toggleSelectedInstance", () => {diff --git a/apps/builder/app/shared/nano-states/instance-selection.ts b/apps/builder/app/shared/nano-states/instance-selection.tsindex fca5ad7396..3c99ab5e3a 100644--- a/apps/builder/app/shared/nano-states/instance-selection.ts+++ b/apps/builder/app/shared/nano-states/instance-selection.ts@@ -9,6 +9,10 @@ import {normalizeInstanceSelectors,} from "../instance-utils/selection";import { $instances } from "../sync/data-stores";+import {+ getExternalContentRoots,+ getExternalContentSourceSelector,+} from "../external-content-mutations";export const $allSelectedInstanceSelectors = atom<InstanceSelector[]>([]);// Instance pruning is derived from tree updates and must not be synchronized@@ -81,9 +85,25 @@ $instances.listen((instances) => {return;}setSelectedInstances(- selectedSelectors.filter((instanceSelector) =>- canResolveInstanceSelector(instanceSelector, instances)- ),+ selectedSelectors.filter((instanceSelector) => {+ const externalSelectors = getExternalContentSourceSelector({+ selector: instanceSelector,+ roots: getExternalContentRoots(),+ });+ if (externalSelectors !== undefined) {+ return (+ canResolveInstanceSelector(+ externalSelectors.contentSelector,+ instances+ ) &&+ canResolveInstanceSelector(+ externalSelectors.sourceSelector,+ instances+ )+ );+ }+ return canResolveInstanceSelector(instanceSelector, instances);+ }),"instance-pruning");});diff --git a/apps/builder/app/shared/nano-states/instances.ts b/apps/builder/app/shared/nano-states/instances.tsindex 4f08447ef4..b042015220 100644--- a/apps/builder/app/shared/nano-states/instances.ts+++ b/apps/builder/app/shared/nano-states/instances.ts@@ -62,7 +62,9 @@ type ContextMenuCommand =}| { type: "selectNext" }| { type: "selectPrevious" }- | { type: "enter" };+ | { type: "enter" }+ | { type: "templateInsertionStarted" }+ | { type: "templateInsertionCancelled" };export const $textEditorContextMenuCommand = atom<undefined | ContextMenuCommanddiff --git a/apps/builder/app/shared/nano-states/props.test.tsx b/apps/builder/app/shared/nano-states/props.test.tsxindex 1a274b87b0..dc25a78b6e 100644--- a/apps/builder/app/shared/nano-states/props.test.tsx+++ b/apps/builder/app/shared/nano-states/props.test.tsx@@ -8,6 +8,8 @@ import {ROOT_INSTANCE_ID,type Resource,SYSTEM_VARIABLE_ID,+ blockComponent,+ contentBlockDocumentProp,collectionComponent,} from "@webstudio-is/sdk";import { showAttribute, textContentAttribute } from "@webstudio-is/react-sdk";@@ -39,6 +41,7 @@ import {import { $systemDataByPage, updateCurrentSystem } from "../system";import { registerContainers } from "../sync/sync-stores";import { $resourcesCache, getResourceKey } from "../resources";+import { $externalContentRoots } from "../external-content-mutations";const { $computedResourceRequests } = __testing__;@@ -84,6 +87,126 @@ beforeEach(() => {$dataSources.set(new Map());$dataSourceVariables.set(new Map());$resourcesCache.set(new Map());+ $externalContentRoots.set(new Map());+});++test("provides occurrence frontmatter to a repeated Content Block", () => {+ const sourceBlock: Instance = {+ type: "instance",+ id: "source-block",+ component: blockComponent,+ children: [],+ };+ const runtimeBlock: Instance = {+ ...sourceBlock,+ id: "runtime-block",+ };+ $instances.set(toMap([sourceBlock, runtimeBlock]));+ $dataSources.set(+ toMap([+ {+ type: "parameter",+ id: "document-data-source",+ scopeInstanceId: sourceBlock.id,+ name: contentBlockDocumentProp,+ },+ ])+ );+ $props.set(+ toMap([+ {+ id: "document-prop",+ instanceId: sourceBlock.id,+ name: contentBlockDocumentProp,+ type: "parameter",+ value: "document-data-source",+ },+ ])+ );+ $externalContentRoots.set(+ new Map([+ [+ "root",+ {+ sourceBlockInstanceId: sourceBlock.id,+ blockInstanceId: runtimeBlock.id,+ instanceIds: new Set<string>(),+ mutationRevision: 0,+ frontmatter: { title: "Occurrence title" },+ },+ ],+ ])+ );+ selectPageRoot(runtimeBlock.id);++ expect(+ $variableValuesByInstanceSelector+ .get()+ .get(getInstanceKey([runtimeBlock.id, ROOT_INSTANCE_ID]))+ ?.get("document-data-source")+ ).toEqual({ frontmatter: { title: "Occurrence title" } });+});++test("does not reuse frontmatter from a previous Collection occurrence", () => {+ const collectionData = new Variable("Posts", ["first", "second"]);+ const collectionItem = new Parameter("Collection Item");+ const document = new Parameter(contentBlockDocumentProp);+ const data = renderData(+ <$.Body ws:id="body">+ <ws.collection+ ws:id="collection"+ data={expression`${collectionData}`}+ item={collectionItem}+ >+ <ws.block ws:id="block" document={document}>+ <$.Box+ ws:id="title"+ ariaLabel={expression`${document}.frontmatter.title`}+ />+ </ws.block>+ </ws.collection>+ </$.Body>+ );+ $instances.set(data.instances);+ $dataSources.set(data.dataSources);+ $props.set(data.props);+ selectPageRoot("body");+ const firstBlockSelector = ["block", "collection[0]", "collection", "body"];+ $externalContentRoots.set(+ new Map([+ [+ "first",+ {+ sourceBlockInstanceId: "block",+ sourceRenderScope: JSON.stringify(firstBlockSelector),+ blockInstanceId: "runtime-first",+ instanceIds: new Set<string>(),+ mutationRevision: 0,+ frontmatter: { title: "First title" },+ },+ ],+ ])+ );++ const values = $propValuesByInstanceSelector.get();+ expect(+ values+ .get(getInstanceKey(["title", ...firstBlockSelector]))+ ?.get("ariaLabel")+ ).toBe("First title");+ expect(+ values+ .get(+ getInstanceKey([+ "title",+ "block",+ "collection[1]",+ "collection",+ "body",+ ])+ )+ ?.has("ariaLabel")+ ).toBe(false);});test("does not preload resources in statically hidden subtrees", () => {diff --git a/apps/builder/app/shared/nano-states/props.ts b/apps/builder/app/shared/nano-states/props.tsindex 47f02c232c..9a08a4c749 100644--- a/apps/builder/app/shared/nano-states/props.ts+++ b/apps/builder/app/shared/nano-states/props.ts@@ -10,6 +10,8 @@ import {decodeDataSourceVariable,encodeDataSourceVariable,collectionComponent,+ blockComponent,+ contentBlockDocumentProp,portalComponent,ROOT_INSTANCE_ID,SYSTEM_VARIABLE_ID,@@ -39,6 +41,10 @@ import {getResourceKey,preloadResources,} from "../resources";+import {+ $externalContentRoots,+ findExternalContentRoot,+} from "../external-content-mutations";export const assetBaseUrl = "/cgi/asset/";@@ -47,6 +53,54 @@ export const getIndexedInstanceId = (index: number | string) => `${instanceId}[${index}]`;+const setContentBlockDocumentValue = ({+ instance,+ instanceSelector,+ parameters,+ propsByInstanceId,+ variableValues,+ externalContentRoots,+}: {+ instance: Instance;+ instanceSelector: InstanceSelector;+ parameters: ReadonlyMap<Prop["name"], DataSource["id"]>;+ propsByInstanceId: ReadonlyMap<Instance["id"], readonly Prop[]>;+ variableValues: Map<string, unknown>;+ externalContentRoots: ReturnType<typeof $externalContentRoots.get>;+}) => {+ if (instance.component !== blockComponent) {+ return;+ }+ const root =+ findExternalContentRoot(+ externalContentRoots,+ instance.id,+ JSON.stringify(instanceSelector)+ ) ??+ Array.from(externalContentRoots.values()).find(+ (candidate) => candidate.blockInstanceId === instance.id+ );+ const sourceBlockInstanceId = root?.sourceBlockInstanceId ?? instance.id;+ const documentProp = propsByInstanceId+ .get(sourceBlockInstanceId)+ ?.find(+ (prop) =>+ prop.name === contentBlockDocumentProp && prop.type === "parameter"+ );+ const documentParameterId =+ parameters.get(contentBlockDocumentProp) ??+ (documentProp?.type === "parameter" ? documentProp.value : undefined);+ if (documentParameterId === undefined) {+ return;+ }+ variableValues.delete(documentParameterId);+ if (root?.frontmatter !== undefined) {+ variableValues.set(documentParameterId, {+ frontmatter: root.frontmatter,+ });+ }+};+/*** (arg1) => {* let $ws$dataSource$id = _getVariable('id')@@ -224,6 +278,7 @@ export const $propValuesByInstanceSelector = computed($pages,$assets,$uploadingFilesDataStore,+ $externalContentRoots,],(instances,@@ -232,7 +287,8 @@ export const $propValuesByInstanceSelector = computed(unscopedVariableValues,pages,assets,- uploadingFilesDataStore+ uploadingFilesDataStore,+ externalContentRoots) => {// already includes global variablesconst variableValues = new Map<string, unknown>(unscopedVariableValues);@@ -307,6 +363,15 @@ export const $propValuesByInstanceSelector = computed(}}+ setContentBlockDocumentValue({+ instance,+ instanceSelector,+ parameters,+ propsByInstanceId,+ variableValues,+ externalContentRoots,+ });+propValuesByInstanceSelector.set(getInstanceKey(instanceSelector),propValues@@ -389,6 +454,7 @@ export const $variableValuesByInstanceSelector = computed($resourceVariableValues,$resourcesCache,$currentSystem,+ $externalContentRoots,],(instances,@@ -399,7 +465,8 @@ export const $variableValuesByInstanceSelector = computed(resources,resourceVariableValues,resourcesCache,- system+ system,+ externalContentRoots) => {const propsByInstanceId = mapGroupBy(props.values(),@@ -518,6 +585,15 @@ export const $variableValuesByInstanceSelector = computed(return;}+ setContentBlockDocumentValue({+ instance,+ instanceSelector,+ parameters,+ propsByInstanceId,+ variableValues,+ externalContentRoots,+ });+if (instance.component === collectionComponent) {const originalData = propValues.get("data");const itemVariableId = parameters.get("item");diff --git a/apps/builder/app/shared/sync/reload-required.test.ts b/apps/builder/app/shared/sync/reload-required.test.tsnew file mode 100644index 0000000000..5d6d0e74b5--- /dev/null+++ b/apps/builder/app/shared/sync/reload-required.test.ts@@ -0,0 +1,24 @@+import { $syncStatus } from "@webstudio-is/sync-client";+import { afterEach, expect, test, vi } from "vitest";+import { requireBuilderReload } from "./reload-required";++afterEach(() => {+ $syncStatus.set({ status: "idle" });+});++test("uses the standard fatal sync state and reload flow", () => {+ const reload = vi.fn();+ const confirm = vi.fn(() => true);++ requireBuilderReload({+ error: "The MDX file changed remotely.",+ target: { confirm, location: { reload } } as never,+ });++ expect(confirm).toHaveBeenCalledWith("The MDX file changed remotely.");+ expect(reload).toHaveBeenCalledOnce();+ expect($syncStatus.get()).toEqual({+ status: "fatal",+ error: "The MDX file changed remotely.",+ });+});diff --git a/apps/builder/app/shared/sync/reload-required.ts b/apps/builder/app/shared/sync/reload-required.tsnew file mode 100644index 0000000000..379f637144--- /dev/null+++ b/apps/builder/app/shared/sync/reload-required.ts@@ -0,0 +1,25 @@+import { toast } from "@webstudio-is/design-system";+import { $syncStatus } from "@webstudio-is/sync-client";++export const requireBuilderReload = ({+ error,+ target = window.top ?? window,+ toastId,+}: {+ error: string;+ target?: Pick<Window, "confirm" | "location">;+ toastId?: string;+}) => {+ const shouldReload = target.confirm(error);+ if (shouldReload) {+ target.location.reload();+ }++ $syncStatus.set({ status: "fatal", error });+ if (shouldReload === false) {+ toast.error("Synchronization has been paused. Please reload to continue.", {+ id: toastId,+ duration: Number.POSITIVE_INFINITY,+ });+ }+};diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.tsindex 7c68b21187..381fd2da64 100644--- a/apps/builder/app/shared/sync/sync-stores.ts+++ b/apps/builder/app/shared/sync/sync-stores.ts@@ -86,6 +86,7 @@ import {areInstanceSelectorsEqual,type InstanceSelector,} from "@webstudio-is/project-build/runtime";+import { $externalContentRoots } from "../external-content-mutations";enableMapSet();// safari structuredClone fix@@ -93,6 +94,7 @@ setAutoFreeze(false);export const clientSyncStore = new Store();export const serverSyncStore = new Store();+export const externalContentSyncStore = new Store();const serverSyncStores = {pages: $pages,@@ -129,6 +131,10 @@ export const registerContainers = () => {name,serverSyncStores[name]);+ externalContentSyncStore.register<ServerSyncStoreValue>(+ name,+ serverSyncStores[name]+ );}};@@ -306,6 +312,7 @@ export const __testing__ = {export const createObjectPool = () => {return new SyncObjectPool([new ImmerhinSyncObject("server", serverSyncStore),+ new ImmerhinSyncObject("externalContent", externalContentSyncStore),new ImmerhinSyncObject("client", clientSyncStore),new SelectedPageAndInstanceSyncObject(),new NanostoresSyncObject("pointerPosition", $pointerPosition),@@ -379,6 +386,7 @@ export const createObjectPool = () => {new NanostoresSyncObject("registeredTemplates", $registeredTemplates),new NanostoresSyncObject("canvasScrollbarWidth", $canvasScrollbarSize),new NanostoresSyncObject("systemDataByPage", $systemDataByPage),+ new NanostoresSyncObject("externalContentRoots", $externalContentRoots),]);};diff --git a/apps/builder/app/shared/tailwind/tailwind.ts b/apps/builder/app/shared/tailwind/tailwind.tsindex b60ad488a4..20ea1112f3 100644--- a/apps/builder/app/shared/tailwind/tailwind.ts+++ b/apps/builder/app/shared/tailwind/tailwind.ts@@ -15,7 +15,10 @@ import {type Prop,type WebstudioFragment,} from "@webstudio-is/sdk";-import { isBaseBreakpoint } from "@webstudio-is/project-build/runtime";+import {+ createWebstudioDataFromFragment,+ isBaseBreakpoint,+} from "@webstudio-is/project-build/runtime";import { preflight } from "./__generated__/preflight";// breakpoints used to map tailwind classes to webstudio breakpoints@@ -738,15 +741,8 @@ export const generateFragmentFromTailwind = async (return breakpoint.id;};- const styleSourceSelections = new Map(- fragment.styleSourceSelections.map((item) => [item.instanceId, item])- );- const styleSources = new Map(- fragment.styleSources.map((item) => [item.id, item])- );- const styles = new Map(- fragment.styles.map((item) => [getStyleDeclKey(item), item])- );+ const { styleSourceSelections, styleSources, styles } =+ createWebstudioDataFromFragment(fragment);const preflightStyleDeclKeys = new Set<string>();const getLocalStyleSource = (instanceId: Instance["id"]) => {const styleSourceSelection = styleSourceSelections.get(instanceId);diff --git a/apps/builder/e2e/fixtures/assets/alternate-source.mdx b/apps/builder/e2e/fixtures/assets/alternate-source.mdxnew file mode 100644index 0000000000..2c8f4c00d9--- /dev/null+++ b/apps/builder/e2e/fixtures/assets/alternate-source.mdx@@ -0,0 +1,3 @@+# Alternate MDX heading++Alternate MDX source text.diff --git a/apps/builder/e2e/fixtures/assets/content-source.mdx b/apps/builder/e2e/fixtures/assets/content-source.mdxnew file mode 100644index 0000000000..97464e5758--- /dev/null+++ b/apps/builder/e2e/fixtures/assets/content-source.mdx@@ -0,0 +1,9 @@+---+title: Content source fixture+---++# MDX source heading++Editable MDX source text.++[Editable MDX link](https://example.com)diff --git a/apps/builder/e2e/fixtures/assets/empty-source.mdx b/apps/builder/e2e/fixtures/assets/empty-source.mdxnew file mode 100644index 0000000000..e69de29bb2diff --git a/apps/builder/e2e/fixtures/assets/unresolved-source.mdx b/apps/builder/e2e/fixtures/assets/unresolved-source.mdxnew file mode 100644index 0000000000..031b134814--- /dev/null+++ b/apps/builder/e2e/fixtures/assets/unresolved-source.mdx@@ -0,0 +1,5 @@+# Valid MDX sibling++<ws.element ws:name="Missing E2E Template" />++Valid content after the missing template.diff --git a/apps/builder/e2e/fixtures/mdx-content-block-project.ts b/apps/builder/e2e/fixtures/mdx-content-block-project.tsnew file mode 100644index 0000000000..96bab9ccca--- /dev/null+++ b/apps/builder/e2e/fixtures/mdx-content-block-project.ts@@ -0,0 +1,243 @@+import { encodeDataSourceVariable } from "@webstudio-is/sdk";+import { loadDevBuild, updateBuild } from "../db";++type InstanceData = {+ type: "instance";+ id: string;+ component: string;+ tag?: string;+ label?: string;+ children: Array<{ type: string; value: string }>;+};++type PropData = {+ id: string;+ instanceId: string;+ name: string;+ type: string;+ value: unknown;+};++type DataSourceData = {+ id: string;+ type: string;+ name: string;+ scopeInstanceId: string;+ value?: unknown;+};++const blockId = "content-block";+const templateId = "content-block-template";++const getBuildData = async (projectId: string) => {+ const build = await loadDevBuild({ projectId });+ return {+ build,+ instances: JSON.parse(build.instances) as InstanceData[],+ props: JSON.parse(build.props) as PropData[],+ dataSources: JSON.parse(build.dataSources) as DataSourceData[],+ };+};++export const configureRepresentableContentBlockBody = async (+ projectId: string+) => {+ const { build, instances } = await getBuildData(projectId);+ const block = instances.find((instance) => instance.id === blockId);+ if (block === undefined) {+ throw new Error("Expected the Content Block fixture instance");+ }+ block.children = [+ { type: "id", value: "list-item" },+ { type: "id", value: templateId },+ ];+ await updateBuild(build.id, { instances: JSON.stringify(instances) });+};++export const configureEmptyHeadingTemplate = async (projectId: string) => {+ const { build, instances } = await getBuildData(projectId);+ const templates = instances.find((instance) => instance.id === templateId);+ if (templates === undefined) {+ throw new Error("Expected the Content Block templates fixture instance");+ }+ const emptyHeadingId = "empty-heading-template";+ templates.children.push({ type: "id", value: emptyHeadingId });+ instances.push({+ type: "instance",+ id: emptyHeadingId,+ component: "ws:element",+ tag: "h1",+ label: "Empty Heading Template",+ children: [],+ });+ await updateBuild(build.id, { instances: JSON.stringify(instances) });+};++const configureSourceBlock = ({+ instances,+ props,+ expression,+}: {+ instances: InstanceData[];+ props: PropData[];+ expression: string;+}) => {+ const block = instances.find((instance) => instance.id === blockId);+ if (block === undefined) {+ throw new Error("Expected the Content Block fixture instance");+ }+ block.children = [{ type: "id", value: templateId }];+ props.push({+ id: "content-block-source",+ instanceId: blockId,+ name: "src",+ type: "expression",+ value: expression,+ });+};++export const configureDynamicDetailContentBlock = async ({+ projectId,+ initialAssetId,+}: {+ projectId: string;+ initialAssetId: string;+}) => {+ const { build, instances, props, dataSources } =+ await getBuildData(projectId);+ configureSourceBlock({+ instances,+ props,+ expression: "$ws$system.params.assetid",+ });+ const pages = JSON.parse(build.pages) as {+ homePageId: string;+ rootFolderId: string;+ pages: Array<{+ id: string;+ name: string;+ title: string;+ path: string;+ history?: string[];+ rootInstanceId: string;+ }>;+ folders: Array<{ id: string; children: string[] }>;+ };+ const homePage = pages.pages.find((page) => page.id === pages.homePageId);+ if (homePage === undefined) {+ throw new Error("Expected the Content Block fixture home page");+ }+ const dynamicPageId = homePage.id;+ const homeRootId = "mdx-detail-home-root";+ const body = instances.find(+ (instance) => instance.id === homePage.rootInstanceId+ );+ if (body === undefined) {+ throw new Error("Expected the Content Block fixture page root");+ }+ instances.push({ ...body, id: homeRootId, children: [] });+ pages.pages.push({+ ...homePage,+ id: "mdx-detail-home-page",+ name: "MDX detail home",+ title: JSON.stringify("MDX detail home"),+ path: "",+ history: [],+ rootInstanceId: homeRootId,+ });+ pages.homePageId = "mdx-detail-home-page";+ const rootFolder = pages.folders.find(+ (folder) => folder.id === pages.rootFolderId+ );+ if (rootFolder === undefined) {+ throw new Error("Expected the Content Block fixture root folder");+ }+ rootFolder.children = [+ pages.homePageId,+ dynamicPageId,+ ...rootFolder.children.filter((id) => id !== dynamicPageId),+ ];+ homePage.name = "Dynamic MDX detail";+ homePage.title = JSON.stringify("Dynamic MDX detail");+ homePage.path = "/:assetid";+ homePage.history = [`/${initialAssetId}`];+ await updateBuild(build.id, {+ instances: JSON.stringify(instances),+ props: JSON.stringify(props),+ dataSources: JSON.stringify(dataSources),+ pages: JSON.stringify(pages),+ });+ return dynamicPageId;+};++export const configureRepeatedContentBlock = async ({+ projectId,+ assetIds,+}: {+ projectId: string;+ assetIds: [string, string];+}) => {+ const { build, instances, props, dataSources } =+ await getBuildData(projectId);+ const collectionId = "mdx-content-collection";+ const itemParameterId = "mdx-content-collection-item";+ const itemKeyParameterId = "mdx-content-collection-item-key";+ configureSourceBlock({+ instances,+ props,+ expression: `${encodeDataSourceVariable(itemParameterId)}?.assetId`,+ });+ const body = instances.find((instance) => instance.id === "body");+ if (body === undefined) {+ throw new Error("Expected the Content Block fixture body");+ }+ body.children = [{ type: "id", value: collectionId }];+ instances.push({+ type: "instance",+ id: collectionId,+ component: "ws:collection",+ children: [{ type: "id", value: blockId }],+ });+ props.push(+ {+ id: "mdx-content-collection-data",+ instanceId: collectionId,+ name: "data",+ type: "json",+ value: assetIds.map((assetId) => ({ assetId })),+ },+ {+ id: "mdx-content-collection-item-prop",+ instanceId: collectionId,+ name: "item",+ type: "parameter",+ value: itemParameterId,+ },+ {+ id: "mdx-content-collection-item-key-prop",+ instanceId: collectionId,+ name: "itemKey",+ type: "parameter",+ value: itemKeyParameterId,+ }+ );+ dataSources.push(+ {+ id: itemParameterId,+ type: "parameter",+ name: "collectionItem",+ scopeInstanceId: collectionId,+ },+ {+ id: itemKeyParameterId,+ type: "parameter",+ name: "collectionItemKey",+ scopeInstanceId: collectionId,+ }+ );+ await updateBuild(build.id, {+ instances: JSON.stringify(instances),+ props: JSON.stringify(props),+ dataSources: JSON.stringify(dataSources),+ });+};diff --git a/apps/builder/e2e/flows/assets-panel.ts b/apps/builder/e2e/flows/assets-panel.tsindex 1c4dd06889..c96f6d3fd3 100644--- a/apps/builder/e2e/flows/assets-panel.ts+++ b/apps/builder/e2e/flows/assets-panel.ts@@ -174,6 +174,24 @@ export const chooseAssetByFilename = async ({filename: string;}) => {const title = await waitForAsset({ page, filename });- await page.getByAltText(title, { exact: true }).last().click();+ await page.getByTitle(title, { exact: true }).last().click();return title;};++export const getAssetIdByFilename = async ({+ page,+ filename,+}: {+ page: Page;+ filename: string;+}) => {+ const title = await waitForAsset({ page, filename });+ const dragKey = await page+ .getByTitle(title)+ .locator("xpath=ancestor-or-self::*[@data-asset-manager-drag-key][1]")+ .getAttribute("data-asset-manager-drag-key");+ if (dragKey?.startsWith("asset:") !== true) {+ throw new Error(`Expected uploaded asset ${filename} to expose its id`);+ }+ return dragKey.slice("asset:".length);+};diff --git a/apps/builder/e2e/flows/builder.ts b/apps/builder/e2e/flows/builder.tsindex cf3c1bcd5a..84f5e7f986 100644--- a/apps/builder/e2e/flows/builder.ts+++ b/apps/builder/e2e/flows/builder.ts@@ -128,16 +128,22 @@ export const openProjectBuilder = async ({authToken,mode,features,+ pageId,}: {page: Page;projectId: string;authToken?: string;mode?: "content" | "preview";features?: string[];+ pageId?: string;}): Promise<Frame> => {- await page.goto(+ const url = new URL(getProjectBuilderUrl({ projectId, authToken, mode, features }));+ if (pageId !== undefined) {+ url.searchParams.set("pageId", pageId);+ }+ await page.goto(url.href);await page.waitForLoadState("networkidle", { timeout: builderNetworkIdleTimeout }).catch(() => undefined);diff --git a/apps/builder/e2e/flows/content-block-source.ts b/apps/builder/e2e/flows/content-block-source.tsnew file mode 100644index 0000000000..525a39e978--- /dev/null+++ b/apps/builder/e2e/flows/content-block-source.ts@@ -0,0 +1,54 @@+import type { Page } from "playwright";+import { chooseAssetByFilename } from "./assets-panel";+import { selectNavigatorItem } from "./navigator";++export const selectContentBlock = async ({ page }: { page: Page }) => {+ await selectNavigatorItem({ page, name: "Content Block" });+ await page+ .getByRole("button", { name: /^(Connect \.mdx file|Open)$/ })+ .first()+ .waitFor({ state: "visible", timeout: 10_000 });+};++export const chooseContentBlockSource = async ({+ page,+ filename,+ action = "Choose file",+}: {+ page: Page;+ filename: string;+ action?: "Choose file" | "Switch file";+}) => {+ if (action === "Choose file") {+ await page+ .getByRole("button", { name: "Connect .mdx file", exact: true })+ .click();+ } else {+ await page+ .locator('[aria-label="Content source actions"] button')+ .first()+ .click();+ }+ await chooseAssetByFilename({ page, filename });+};++export const confirmContentBlockConnection = async ({+ page,+}: {+ page: Page;+}) => {+ const dialog = page.getByRole("dialog", { name: /content source$/i });+ await dialog.waitFor({ state: "visible" });+ await dialog.getByRole("button", { name: "Connect", exact: true }).click();+ await dialog.waitFor({ state: "hidden" });+};++export const disconnectContentBlockSource = async ({+ page,+}: {+ page: Page;+}) => {+ await page+ .getByRole("button", { name: "Source", exact: true })+ .click({ modifiers: ["Alt"] });+};diff --git a/apps/builder/e2e/flows/content-editing.ts b/apps/builder/e2e/flows/content-editing.tsindex 837d409b0e..cd55625a1c 100644--- a/apps/builder/e2e/flows/content-editing.ts+++ b/apps/builder/e2e/flows/content-editing.ts@@ -96,17 +96,21 @@ export const replaceCanvasText = async ({page,currentText,text,+ waitForProjectSync = true,}: {page: Page;currentText: string;text: string;+ waitForProjectSync?: boolean;}) => {const { canvas, editable } = await startCanvasTextEditingByText({page,currentText,});await page.keyboard.press("ControlOrMeta+A");- const save = waitForChangeToBeSaved({ page });+ const save = waitForProjectSync+ ? waitForChangeToBeSaved({ page })+ : Promise.resolve();try {await page.keyboard.type(text);await canvas.locator("body").click({ position: { x: 1, y: 1 } });diff --git a/apps/builder/e2e/flows/navigator.ts b/apps/builder/e2e/flows/navigator.tsindex 7e6ab82c26..e05c2b88f9 100644--- a/apps/builder/e2e/flows/navigator.ts+++ b/apps/builder/e2e/flows/navigator.ts@@ -10,3 +10,21 @@ export const openNavigatorPanel = async ({ page }: { page: Page }) => {timeout: 10_000,});};++export const selectNavigatorItem = async ({+ page,+ name,+}: {+ page: Page;+ name: string;+}) => {+ await openNavigatorPanel({ page });+ const tree = page.locator("[data-navigator-tree]");+ const item = tree+ .locator("[data-tree-button]")+ .filter({ has: page.getByText(name, { exact: true }) })+ .last();+ await item.waitFor({ state: "visible" });+ await item.click();+ await item.click();+};diff --git a/apps/builder/e2e/flows/props-panel.ts b/apps/builder/e2e/flows/props-panel.tsindex 0346ab2da7..4f171b664a 100644--- a/apps/builder/e2e/flows/props-panel.ts+++ b/apps/builder/e2e/flows/props-panel.ts@@ -10,11 +10,13 @@ export const fillSelectedStringProperty = async ({label,control,value,+ waitForProjectSync = true,}: {page: Page;label: string;control: "url" | "text";value: string;+ waitForProjectSync?: boolean;}) => {await getPropertyLabel({ page, label }).waitFor({state: "visible",@@ -27,7 +29,9 @@ export const fillSelectedStringProperty = async ({await waitForSyncStatus({ page, status: "idle", timeout: 3_000 }).catch(() => undefined);- const save = waitForChangeToBeSaved({ page });+ const save = waitForProjectSync+ ? waitForChangeToBeSaved({ page })+ : Promise.resolve();await input.fill(value);await input.blur();await save;diff --git a/apps/builder/e2e/tests/content-mode-editing.[shard-2].[shard-5].[shard-6].e2e.ts b/apps/builder/e2e/tests/content-mode-editing.[shard-2].[shard-5].[shard-6].e2e.tsindex 57b1c98210..e1f803cb6f 100644--- a/apps/builder/e2e/tests/content-mode-editing.[shard-2].[shard-5].[shard-6].e2e.ts+++ b/apps/builder/e2e/tests/content-mode-editing.[shard-2].[shard-5].[shard-6].e2e.ts@@ -21,9 +21,7 @@ import {replaceCanvasTextAndApplyInlineFormats,} from "../flows/content-editing";import {- fillSelectedNumberProperty,fillSelectedStringProperty,- waitForSelectedNumberPropertyValue,waitForSelectedStringPropertyValue,} from "../flows/props-panel";import {@@ -267,7 +265,6 @@ test("Editor can edit text and content props but not design props", async () =>const editedImageSrc ="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='80'%3E%3Crect width='120' height='80' fill='%23dff7e8'/%3E%3C/svg%3E";const editedImageAlt = "Edited image alt";- const editedImageWidth = 240;const editedVideoSrc = "https://example.com/edited-video.mp4";const editedContent = "Edited isolated content";const { page, close } = await newIsolatedPage();@@ -330,7 +327,14 @@ test("Editor can edit text and content props but not design props", async () =>message: "Expected Style tab to be unavailable in content mode",});await expectTextHidden({ page, text: "Style sources" });- await expectTextHidden({ page, text: "Target" });+ await page+ .getByText("Target", { exact: true })+ .first()+ .waitFor({ state: "visible" });+ await page+ .getByText("Download", { exact: true })+ .first()+ .waitFor({ state: "visible" });await selectCanvasTextInstanceForProps({page,@@ -360,11 +364,7 @@ test("Editor can edit text and content props but not design props", async () =>control: "text",value: editedImageAlt,});- await fillSelectedNumberProperty({- page,- label: "Width",- value: editedImageWidth,- });+ await expectTextHidden({ page, text: "Width" });await selectCanvasVideoSource({page,@@ -420,11 +420,7 @@ test("Editor can edit text and content props but not design props", async () =>control: "text",value: editedImageAlt,});- await waitForSelectedNumberPropertyValue({- page,- label: "Width",- value: editedImageWidth,- });+ await expectTextHidden({ page, text: "Width" });await selectCanvasVideoSource({page,diff --git a/apps/builder/e2e/tests/mdx-content-block.[shard-4].e2e.ts b/apps/builder/e2e/tests/mdx-content-block.[shard-4].e2e.tsnew file mode 100644index 0000000000..340adaa903--- /dev/null+++ b/apps/builder/e2e/tests/mdx-content-block.[shard-4].e2e.ts@@ -0,0 +1,765 @@+import type { Page, Response } from "playwright";+import { parseMdxDocument } from "@webstudio-is/content-engine/mdx";+import {+ configureDynamicDetailContentBlock,+ configureEmptyHeadingTemplate,+ configureRepresentableContentBlockBody,+ configureRepeatedContentBlock,+} from "../fixtures/mdx-content-block-project";+import { createContentModeProject } from "../fixtures/content-mode-suite";+import {+ getAssetIdByFilename,+ openAssetsPanel,+ uploadAsset,+} from "../flows/assets-panel";+import {+ openProjectBuilder,+ waitForCanvasFrame,+ waitForCanvasText,+ waitForCanvasTextHidden,+} from "../flows/builder";+import {+ chooseContentBlockSource,+ disconnectContentBlockSource,+ selectContentBlock,+ confirmContentBlockConnection,+} from "../flows/content-block-source";+import { replaceCanvasText } from "../flows/content-editing";+import { waitForContentEditMode } from "../flows/content-editing";+import { waitForSyncStatus } from "../flows/sync-status";+import { insertTemplateAfterCanvasText } from "../flows/template-insertion";+import { openNavigatorPanel } from "../flows/navigator";+import { selectCanvasTextInstanceForProps } from "../flows/canvas-selection";+import { fillSelectedStringProperty } from "../flows/props-panel";+import { getProjectBuilderUrl, newIsolatedPage, test } from "../harness";++const sourceFilename = "content-source.mdx";+const alternateFilename = "alternate-source.mdx";+const unresolvedFilename = "unresolved-source.mdx";+const emptyFilename = "empty-source.mdx";++const sourceHeading = "MDX source heading";+const editedHeading = "Edited MDX source heading";+const editedTemplateText = "Edited MDX template heading";+const alternateHeading = "Alternate MDX heading";++const isAssetContentResponse = (response: Response, method = "PUT") =>+ response.request().method() === method &&+ response.url().includes("/rest/assets/") &&+ response.url().includes("/content");++const waitForAssetWrite = (page: Page) =>+ page.waitForResponse(+ (response) => isAssetContentResponse(response) && response.status() === 200,+ { timeout: 30_000 }+ );++const waitForReorderedAssetWrite = ({+ page,+ before,+ after,+}: {+ page: Page;+ before: string;+ after: string;+}) =>+ page.waitForResponse(+ (response) => {+ if (isAssetContentResponse(response) === false) {+ return false;+ }+ const source = response.request().postData() ?? "";+ const beforeIndex = source.indexOf(before);+ const afterIndex = source.indexOf(after);+ return (+ beforeIndex !== -1 && afterIndex !== -1 && beforeIndex < afterIndex+ );+ },+ { timeout: 30_000 }+ );++const expectCanvasTextOrder = async ({+ page,+ before,+ after,+}: {+ page: Page;+ before: string;+ after: string;+}) => {+ const canvas = await waitForCanvasFrame({ page });+ const beforeElement = canvas.getByText(before, { exact: true });+ const afterElement = canvas.getByText(after, { exact: true });+ const deadline = Date.now() + 10_000;+ while (Date.now() < deadline) {+ const afterHandle = await afterElement.elementHandle();+ if (afterHandle !== null) {+ const isBefore = await beforeElement.evaluate(+ (element, afterElement) =>+ (element.compareDocumentPosition(afterElement) &+ Node.DOCUMENT_POSITION_FOLLOWING) !==+ 0,+ afterHandle+ );+ if (isBefore) {+ return;+ }+ }+ await page.waitForTimeout(100);+ }+ throw new Error(`Expected "${before}" before "${after}" on the canvas`);+};++const insertTemplateIntoEmptyContentBlock = async ({+ page,+ templateName,+}: {+ page: Page;+ templateName: string;+}) => {+ await waitForContentEditMode({ page });+ const canvas = await waitForCanvasFrame({ page });+ const block = canvas.locator('[data-ws-component="ws:block"]').last();+ await block.hover();+ const insert = page.getByRole("button", { name: "Insert block" }).last();+ await insert.waitFor({ state: "visible" });+ await insert.focus();+ await insert.press("Enter");+ await page.getByRole("menuitemradio", { name: templateName }).click();+};++const openFixture = async ({+ page,+ projectId,+ authToken,+ mode,+ pageId,+}: {+ page: Page;+ projectId: string;+ authToken: string;+ mode?: "content" | "preview";+ pageId?: string;+}) => {+ await openProjectBuilder({ page, projectId, authToken, mode, pageId });+ await waitForSyncStatus({ page, status: "idle" });+};++test("Content Block MDX source lifecycle persists edits and resets to empty", async () => {+ const fixture = await createContentModeProject({+ email: "[email protected]",+ title: "MDX Content Source E2E",+ });+ await configureRepresentableContentBlockBody(fixture.projectId);+ const { page, close } = await newIsolatedPage();++ try {+ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await openAssetsPanel({ page });+ await uploadAsset({ page, filename: sourceFilename });+ await uploadAsset({ page, filename: alternateFilename });++ await selectContentBlock({ page });+ await chooseContentBlockSource({ page, filename: sourceFilename });+ await confirmContentBlockConnection({ page });+ await waitForCanvasText({ page, text: sourceHeading });+ await waitForSyncStatus({ page, status: "idle" });+ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ const templateWrite = waitForAssetWrite(page).catch((error: unknown) =>+ error instanceof Error ? error : new Error("Asset write failed")+ );+ await insertTemplateAfterCanvasText({+ page,+ anchorText: sourceHeading,+ templateName: fixture.editableTextTemplateName,+ });+ await waitForCanvasText({+ page,+ text: fixture.editableTextTemplateText,+ });+ const templateResponse = await templateWrite;+ if (templateResponse instanceof Error) {+ throw templateResponse;+ }+ const templateDocument = await parseMdxDocument({+ source: templateResponse.request().postData() ?? "",+ });+ if (+ templateDocument.children.some(+ (node) =>+ node.type === "element" &&+ node.syntax === "markdown" &&+ node.tag === "p" &&+ node.children.some(+ (child) =>+ child.type === "text" &&+ child.value === fixture.editableTextTemplateText+ )+ ) === false+ ) {+ throw new Error(+ "Inserting a plain Content Block template must persist as Markdown"+ );+ }+ const templateTextWrite = waitForAssetWrite(page).catch((error: unknown) =>+ error instanceof Error ? error : new Error("Asset write failed")+ );+ await replaceCanvasText({+ page,+ currentText: fixture.editableTextTemplateText,+ text: editedTemplateText,+ waitForProjectSync: false,+ });+ const templateTextResponse = await templateTextWrite;+ if (templateTextResponse instanceof Error) {+ throw templateTextResponse;+ }+ const templateTextRequestBody = templateTextResponse.request().postData();+ const templateTextDocument = await parseMdxDocument({+ source: templateTextRequestBody ?? "",+ });+ if (+ templateTextDocument.children.some(+ (node) =>+ node.type === "element" &&+ node.syntax === "markdown" &&+ node.tag === "p" &&+ node.children.some(+ (child) =>+ child.type === "text" && child.value === editedTemplateText+ )+ ) === false+ ) {+ throw new Error(+ "Editing a plain Content Block template must persist as Markdown"+ );+ }+ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await selectContentBlock({ page });+ await page.getByRole("button", { name: "Open", exact: true }).click();+ const fileEditor = page.getByRole("dialog").locator(".cm-content");+ await fileEditor.waitFor({ state: "visible" });+ if (+ (await fileEditor.textContent())?.includes(editedTemplateText) !== true+ ) {+ throw new Error(+ "Opening an MDX Asset after a canvas save must show the latest content"+ );+ }+ await page.keyboard.press("Escape");+ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ await Promise.all([+ waitForAssetWrite(page),+ replaceCanvasText({+ page,+ currentText: sourceHeading,+ text: editedHeading,+ waitForProjectSync: false,+ }),+ ]);+ await openNavigatorPanel({ page });+ const contentBlockItem = page+ .locator("[data-navigator-tree] [data-tree-button]")+ .filter({ hasText: "Content Block" })+ .last();+ await contentBlockItem.press("ArrowRight");+ const editingCanvas = await waitForCanvasFrame({ page });+ await editingCanvas+ .getByText("Editable MDX source text.", { exact: true })+ .click();+ await page.keyboard.press("Escape");+ await Promise.all([+ waitForReorderedAssetWrite({+ page,+ before: "Editable MDX source text.",+ after: editedTemplateText,+ }),+ page.keyboard.press("Control+ArrowUp"),+ ]);+ await expectCanvasTextOrder({+ page,+ before: "Editable MDX source text.",+ after: editedTemplateText,+ });+ const deleteWrite = waitForAssetWrite(page);+ const canvas = await waitForCanvasFrame({ page });+ await page.keyboard.down("Alt");+ try {+ await canvas.getByText(editedTemplateText, { exact: true }).hover();+ await page.getByRole("button", { name: "Delete block" }).last().click();+ } finally {+ await page.keyboard.up("Alt");+ }+ const deleteSource = (await deleteWrite).request().postData() ?? "";+ if (+ deleteSource.includes(editedTemplateText) ||+ deleteSource.includes("Editable MDX source text.") === false+ ) {+ throw new Error(+ `Deleting one instance removed the wrong content: ${deleteSource}`+ );+ }+ await waitForCanvasTextHidden({ page, text: editedTemplateText });+ await waitForCanvasText({ page, text: "Editable MDX source text." });+ await selectCanvasTextInstanceForProps({+ page,+ text: "Editable MDX link",+ propertyLabel: "Href",+ });+ const linkWrite = waitForAssetWrite(page);+ await fillSelectedStringProperty({+ page,+ label: "Href",+ control: "url",+ value: "https://webstudio.is",+ waitForProjectSync: false,+ });+ const linkSource = (await linkWrite).request().postData() ?? "";+ const linkDocument = await parseMdxDocument({ source: linkSource });+ if (+ linkDocument.children.some(+ (node) =>+ node.type === "element" &&+ node.syntax === "markdown" &&+ node.tag === "p" &&+ node.children.some(+ (child) =>+ child.type === "element" &&+ child.syntax === "markdown" &&+ child.tag === "a" &&+ child.props.some(+ (prop) =>+ prop.name === "href" && prop.value === "https://webstudio.is/"+ ) &&+ child.children.some(+ (linkChild) =>+ linkChild.type === "text" &&+ linkChild.value === "Editable MDX link"+ )+ )+ ) === false+ ) {+ throw new Error(`Expected Markdown link persistence: ${linkSource}`);+ }++ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await waitForCanvasText({ page, text: editedHeading });+ await waitForCanvasTextHidden({ page, text: editedTemplateText });+ await selectContentBlock({ page });++ await chooseContentBlockSource({+ page,+ filename: alternateFilename,+ action: "Switch file",+ });+ await page.getByText(alternateFilename, { exact: true }).waitFor();+ await waitForCanvasText({ page, text: alternateHeading });+ await waitForCanvasTextHidden({ page, text: editedHeading });++ await selectContentBlock({ page });+ await page.getByRole("button", { name: "Open", exact: true }).click();+ const alternateEditor = page.getByRole("dialog").locator(".cm-content");+ await alternateEditor.waitFor({ state: "visible" });+ if (+ (await alternateEditor.textContent())?.includes(alternateHeading) !== true+ ) {+ throw new Error(+ "The selected alternate MDX Asset did not contain its expected source"+ );+ }+ await page.keyboard.press("Escape");+ await disconnectContentBlockSource({ page });+ await waitForSyncStatus({ page, status: "idle" });+ await waitForCanvasTextHidden({ page, text: alternateHeading });++ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await waitForCanvasTextHidden({ page, text: alternateHeading });+ await selectContentBlock({ page });+ await page+ .getByRole("button", { name: "Connect .mdx file", exact: true })+ .waitFor();+ } finally {+ await close();+ }+});++test("Empty MDX content supports insertion and keeps the next paragraph focused", async () => {+ const fixture = await createContentModeProject({+ email: "[email protected]",+ title: "Empty MDX Content Source E2E",+ });+ await configureEmptyHeadingTemplate(fixture.projectId);+ const { page, close } = await newIsolatedPage();++ try {+ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await openAssetsPanel({ page });+ await uploadAsset({ page, filename: emptyFilename });+ await selectContentBlock({ page });+ await chooseContentBlockSource({ page, filename: emptyFilename });+ await confirmContentBlockConnection({ page });+ await waitForSyncStatus({ page, status: "idle" });++ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ await insertTemplateIntoEmptyContentBlock({+ page,+ templateName: "Empty Heading Template",+ });+ const canvas = await waitForCanvasFrame({ page });+ await canvas.locator("h1").waitFor({ state: "visible" });+ const headingEditor = canvas.locator("h1[contenteditable]");+ await headingEditor.waitFor({ state: "visible" });+ await page.keyboard.type("First heading");+ await headingEditor.getByText("First heading", { exact: true }).waitFor();+ await page.keyboard.press("Enter");++ const paragraphEditor = canvas.locator("p[contenteditable]");+ await paragraphEditor.waitFor({ state: "visible" });+ await page.keyboard.press("/");+ await page+ .getByRole("menuitemradio", { name: "Empty Heading Template" })+ .last()+ .waitFor({ state: "visible" });+ await page.keyboard.press("Escape");+ await page.keyboard.type("Focused paragraph");+ const paragraphId = await paragraphEditor.getAttribute("data-ws-id");+ if (paragraphId === null) {+ throw new Error("Expected the focused paragraph instance id");+ }+ await page.keyboard.press("Enter");+ const emptyParagraphEditor = canvas.locator(+ `p[contenteditable]:not([data-ws-id="${paragraphId}"])`+ );+ await emptyParagraphEditor.waitFor({ state: "visible" });+ const emptyParagraphId =+ await emptyParagraphEditor.getAttribute("data-ws-id");+ if (emptyParagraphId === null) {+ throw new Error("Expected the new paragraph instance id");+ }+ await page.keyboard.press("ControlOrMeta+A");+ await page.keyboard.press("Backspace");+ await page.keyboard.press("Backspace");+ await canvas+ .locator(`p[data-ws-id="${emptyParagraphId}"]`)+ .waitFor({ state: "detached" });+ if (+ (await paragraphEditor.evaluate(+ (element) =>+ element === document.activeElement ||+ element.contains(document.activeElement)+ )) === false+ ) {+ throw new Error("Expected the previous paragraph to regain focus");+ }+ const finalWrite = waitForAssetWrite(page);+ await page.mouse.click(5, 5);+ const finalSource = (await finalWrite).request().postData() ?? "";+ if (+ finalSource.includes("# First heading") === false ||+ finalSource.includes("Focused paragraph") === false ||+ finalSource.includes('ws:tag="p"')+ ) {+ throw new Error(`Unexpected final MDX source: ${finalSource}`);+ }++ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ await waitForCanvasText({ page, text: "First heading" });+ await waitForCanvasText({ page, text: "Focused paragraph" });+ } finally {+ await close();+ }+});++test("Content Block requires a Builder reload after a stale file revision", async () => {+ const fixture = await createContentModeProject({+ email: "[email protected]",+ title: "MDX Content Conflict E2E",+ });+ const { page, close } = await newIsolatedPage();++ try {+ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await openAssetsPanel({ page });+ await uploadAsset({ page, filename: sourceFilename });+ await selectContentBlock({ page });+ await chooseContentBlockSource({ page, filename: sourceFilename });+ await confirmContentBlockConnection({ page });+ await waitForCanvasText({ page, text: sourceHeading });+ await waitForSyncStatus({ page, status: "idle" });+ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });++ await page.route("**/rest/assets/*/content?*", async (route) => {+ if (route.request().method() === "PUT") {+ await route.fulfill({+ status: 409,+ contentType: "application/json",+ body: JSON.stringify({ message: "Asset revision conflict" }),+ });+ return;+ }+ await route.continue();+ });++ let reloadPromptMessage: string | undefined;+ const reloadPromptHandled = new Promise<void>((resolve) => {+ page.once("dialog", (dialog) => {+ reloadPromptMessage = dialog.message();+ void dialog.dismiss().then(resolve);+ });+ });+ await replaceCanvasText({+ page,+ currentText: sourceHeading,+ text: "Unsaved conflict heading",+ waitForProjectSync: false,+ });+ await reloadPromptHandled;+ if (+ reloadPromptMessage !==+ "This file changed since it was opened. Reload it before saving again."+ ) {+ throw new Error(+ `Expected stale revision reload prompt: ${reloadPromptMessage}`+ );+ }+ await page+ .getByRole("status")+ .filter({+ hasText: "Synchronization has been paused. Please reload to continue.",+ })+ .first()+ .waitFor();++ await page.unroute("**/rest/assets/*/content?*");+ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await waitForCanvasText({ page, text: sourceHeading });+ } finally {+ await close();+ }+});++test("Unresolved MDX templates are selectable only in the Builder canvas", async () => {+ const fixture = await createContentModeProject({+ email: "[email protected]",+ title: "MDX Content Warning E2E",+ });+ const { page, close } = await newIsolatedPage();++ try {+ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await openAssetsPanel({ page });+ await uploadAsset({ page, filename: unresolvedFilename });+ await selectContentBlock({ page });+ await chooseContentBlockSource({ page, filename: unresolvedFilename });+ await confirmContentBlockConnection({ page });+ await waitForSyncStatus({ page, status: "idle" });++ await waitForCanvasText({ page, text: "Valid MDX sibling" });+ await waitForCanvasText({+ page,+ text: "Valid content after the missing template.",+ });+ const canvas = await waitForCanvasFrame({ page });+ const warning = canvas.getByText("Missing template: Missing E2E Template", {+ exact: true,+ });+ await warning.waitFor();+ await warning.click();+ await selectContentBlock({ page });+ await page.getByRole("img", { name: /^MDX source warning:/ }).waitFor();+ await page.getByRole("button", { name: "Open", exact: true }).waitFor();++ const previewUrl = getProjectBuilderUrl({+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "preview",+ });+ await page.goto(previewUrl);+ await waitForCanvasText({ page, text: "Valid MDX sibling" });+ await waitForCanvasText({+ page,+ text: "Valid content after the missing template.",+ });+ const previewCanvas = await waitForCanvasFrame({ page });+ await previewCanvas+ .getByText("Missing template: Missing E2E Template", { exact: true })+ .waitFor({ state: "hidden" });+ } finally {+ await close();+ }+});++test("Dynamic detail source follows the selected route parameter", async () => {+ const fixture = await createContentModeProject({+ email: "[email protected]",+ title: "MDX Content Detail E2E",+ });+ const { page, close } = await newIsolatedPage();++ try {+ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ });+ await openAssetsPanel({ page });+ await uploadAsset({ page, filename: sourceFilename });+ await uploadAsset({ page, filename: alternateFilename });+ const sourceAssetId = await getAssetIdByFilename({+ page,+ filename: sourceFilename,+ });+ const alternateAssetId = await getAssetIdByFilename({+ page,+ filename: alternateFilename,+ });+ const detailPageId = await configureDynamicDetailContentBlock({+ projectId: fixture.projectId,+ initialAssetId: sourceAssetId,+ });++ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ pageId: detailPageId,+ });+ await waitForCanvasText({ page, text: sourceHeading });++ await page+ .getByRole("button", { name: "Toggle dynamic page address" })+ .click();+ const parameter = page.getByPlaceholder("assetid");+ await parameter.fill(alternateAssetId);+ await parameter.press("Enter");+ await waitForCanvasText({ page, text: alternateHeading });+ await waitForCanvasTextHidden({ page, text: sourceHeading });++ await page+ .getByRole("button", { name: "Toggle dynamic page address" })+ .click();+ await page.getByPlaceholder("assetid").fill(sourceAssetId);+ await page.getByPlaceholder("assetid").press("Enter");+ await waitForCanvasText({ page, text: sourceHeading });+ await waitForCanvasTextHidden({ page, text: alternateHeading });+ } finally {+ await close();+ }+});++test("Repeated Content Block scopes edit distinct MDX files without leakage", async () => {+ const fixture = await createContentModeProject({+ email: "[email protected]",+ title: "MDX Content Repeated E2E",+ });+ const { page, close } = await newIsolatedPage();++ try {+ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ });+ await openAssetsPanel({ page });+ await uploadAsset({ page, filename: sourceFilename });+ await uploadAsset({ page, filename: alternateFilename });+ const sourceAssetId = await getAssetIdByFilename({+ page,+ filename: sourceFilename,+ });+ const alternateAssetId = await getAssetIdByFilename({+ page,+ filename: alternateFilename,+ });+ await configureRepeatedContentBlock({+ projectId: fixture.projectId,+ assetIds: [sourceAssetId, alternateAssetId],+ });++ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ });+ await waitForCanvasText({ page, text: sourceHeading });+ await waitForCanvasText({ page, text: alternateHeading });++ const write = waitForAssetWrite(page);+ await replaceCanvasText({+ page,+ currentText: sourceHeading,+ text: editedHeading,+ waitForProjectSync: false,+ });+ await write;+ await waitForCanvasText({ page, text: editedHeading });+ await waitForCanvasText({ page, text: alternateHeading });++ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ });+ await waitForCanvasText({ page, text: editedHeading });+ await waitForCanvasText({ page, text: alternateHeading });+ } finally {+ await close();+ }+});diff --git a/docs/university/core-components/code-text.md b/docs/university/core-components/code-text.mdindex bf0c9f9cb6..58f64c79c5 100644--- a/docs/university/core-components/code-text.md+++ b/docs/university/core-components/code-text.md@@ -18,15 +18,19 @@ Use [Text](text.md) for prose that does not need syntax highlighting.1. Open the **Components** panel.2. Expand **Typography**.3. Drag **Code Text** onto the canvas.-4. Enter the source in **Code** in the Settings panel, or edit it on the canvas.+4. Enter the source in **Text Content** in the Settings panel, or edit it on the canvas.5. Select the matching **Language**.6. Select a **Theme**.-You can bind **Code**, **Language**, and **Theme** to variables or resource-values. A fixed Language or Theme includes only that selected asset in the-published build. A bound Language or Theme makes the available catalog part of-the server build so any runtime value can be rendered. The browser loads only-the language and theme selected at runtime.+**Text Content** opens a code editor that uses the selected language for syntax highlighting.++In Content mode, editors can change **Text Content** and **Language**. Change **Theme** in Design mode.++You can bind **Text Content**, **Language**, and **Theme** to variables or+resource values. A fixed Language or Theme includes only that selected asset in+the published build. A bound Language or Theme makes the available catalog part+of the server build so any runtime value can be rendered. The browser loads+only the language and theme selected at runtime.The highlighted markup is rendered with SSR and SSG output, so it appearsconsistently when the page first loads and after it becomes interactive.diff --git a/docs/university/core-components/content-block.md b/docs/university/core-components/content-block.mdindex b4f0768aee..89a827c747 100644--- a/docs/university/core-components/content-block.md+++ b/docs/university/core-components/content-block.md@@ -50,17 +50,55 @@ Every top-level instance within Templates will appear in Content mode like this:<div><figure><img src="../../.gitbook/assets/templates-design-mode.png" alt="Templates in Design mode"><figcaption><p>Templates in Design mode</p></figcaption></figure> <figure><img src="../../.gitbook/assets/templates-content-mode.png" alt="Template in Content mode"><figcaption><p>Template in Content mode</p></figcaption></figure></div>-Each time they insert a template, its copy appears as a direct child of the Content Block, alongside any initial content. The Templates container remains protected source material.+Each time they insert a template, its copy appears inside the Content Block's Body outlet, alongside any initial body content. The Templates container remains protected source material.### Step 3: Add an initial setup (optional)-Optionally, you can add instances as direct children of Content Block.+Optionally, you can add instances inside the Content Block's Body outlet.<figure><img src="../../.gitbook/assets/startingpoint-content-block.png" alt="" width="357"><figcaption><p>The "Feature" instances are provided as a starting point</p></figcaption></figure>Doing so will provide an initial setup for editors.-Editors can delete direct children of the Content Block. They cannot delete the Templates container, templates, or nested instances independently.+Editors can delete children of the Body outlet. They cannot delete the designed shell, Templates container, templates, or nested instances independently.++### Store content in an MDX file++In Design mode, use the **Source** property under **Properties & attributes** to connect a `.mdx` file from Assets. Create the file in Assets first, then select it directly or bind the property to an Asset ID. The file becomes the source of the Body outlet's children; the designed shell and Templates container remain part of the project.++Connecting a file replaces the Body outlet's existing children. In Design mode, select the connected filename to switch files, or select **Open** to edit it. To disconnect, select the **Source** property label and choose **Reset value**. Disconnecting leaves the MDX file unchanged, removes its derived body content from the canvas, and preserves the designed shell with an empty Body outlet.++When you connect an older Content Block that has no Body outlet, Webstudio replaces its existing editable content and adds the outlet automatically.++In Content mode, **Source** shows the connected filename and an **Open** button so editors can identify and edit the file. Changing, binding, resetting, and disconnecting the source remain available only in Design mode.++Editors continue to use the normal Content mode controls. Their changes appear immediately on the canvas and then save to the connected file. Changes made in the file editor also update every Content Block connected to that file.++Component properties in Content mode are limited to authored content, such as links, media sources and alternative text, form labels and placeholders, code, and date values. Layout, dimensions, visual themes, form wiring, and interaction settings remain available only in Design mode.++Use Markdown for headings, paragraphs, links, lists, tables, code, and other standard document content. MDX uses Webstudio elements only for content that Markdown cannot represent:++```mdx+# Product update++Regular document content stays Markdown.++<ws.element ws:name="Promotion Card" />+```++The `ws:name` value must exactly match a unique top-level instance name in the Content Block's Templates list. Missing templates show a warning in Builder and are omitted from the published site. Invalid or unsupported MDX remains editable; Builder reports the source location and renders the valid content it can recover.++You can connect multiple Content Blocks to the same MDX file. Editing any connected occurrence updates the shared file and the other connected occurrences.++If the file changes after a canvas edit starts but before it is saved, Builder asks you to reload. It preserves the local canvas state until reload and does not merge or overwrite either version automatically.++Edit frontmatter as YAML in the MDX file editor. Canvas edits update only the document body and preserve the frontmatter source, including its comments and formatting. Content-mode users with Asset access can open the MDX file from Assets to edit its frontmatter.++To use frontmatter in the designed part of a Content Block, bind a property or text value to the Content Block's **Document** parameter. For example, bind a heading to `Document.frontmatter.title` or an image source to `Document.frontmatter.featureImage`. Direct frontmatter bindings remain part of the same MDX file and can be edited on the canvas in Content mode. Computed expressions and values supplied through another document's `$ref` remain read-only on the canvas; open the referenced file to edit referenced values.++New Content Blocks include a **Body** outlet. Place it anywhere inside the designed article layout: the connected file's MDX body renders there, while the surrounding instances can use frontmatter bindings. Templates stay protected and continue to control which custom instances editors may insert into the body.++To create another post with the same structure, duplicate the existing MDX Asset, edit the duplicate, and connect or bind the appropriate Content Block occurrence to it.## Content Block in Content modediff --git a/docs/university/core-components/html-embed.md b/docs/university/core-components/html-embed.mdindex 25bb191f4d..072c8f1b6c 100644--- a/docs/university/core-components/html-embed.md+++ b/docs/university/core-components/html-embed.md@@ -20,6 +20,8 @@ The "HTML Embed" component can be found in Components > General, and you can plaYou can add your custom HTML, CSS, or JavaScript code to the HTML Embed instance by selecting it and accessing its “Settings”.+The **Code** property is also available in Content mode when the HTML Embed is inside an editable Content Block.+#### Code<figure><img src="../../.gitbook/assets/gsap.png" alt=""><figcaption></figcaption></figure>diff --git a/docs/university/foundations/assets.md b/docs/university/foundations/assets.mdindex 10a49c9f80..e77fe4b22e 100644--- a/docs/university/foundations/assets.md+++ b/docs/university/foundations/assets.md@@ -17,7 +17,7 @@ The Assets panel is located on the left side of the builder. It stores all stati| **Video** | MP4, MOV, AVI, WebM || **Audio** | MP3, WAV, OGG, M4A || **Documents** | PDF, DOC, DOCX, XLS, XLSX, CSV, PPT, PPTX |-| **Code & text** | TXT, MD, JS, CSS, JSON, HTML, XML |+| **Code & text** | TXT, MD, MDX, JS, CSS, JSON, HTML, XML || **Archives** | ZIP, RAR |{% hint style="info" %}@@ -40,16 +40,21 @@ multiple selected assets does not insert multiple Image components.### Create and edit text filesOpen the add menu in the Assets panel and choose **Create text file**. Enter a-supported filename, such as `notes.md` or `data.json`.+supported filename, such as `notes.md`, `article.mdx`, or `data.json`.Webstudio creates the file in the current folder and opens it in the codeeditor. New JSON files start with an empty object so the Content Engine canindex them immediately.-You can open uploaded `txt`, `csv`, `md`, `js`, `css`, `json`, `html`, `xml`,+You can open uploaded `txt`, `csv`, `md`, `mdx`, `js`, `css`, `json`, `html`, `xml`,and `svg` assets in the same editor. Syntax highlighting follows the file type;unsupported text types use plain text. Markdown files also provide formattingcontrols and a preview.+MDX files use the same Markdown document features and additionally support+Webstudio elements for content that Markdown cannot represent. Rename a `.md`+file to `.mdx` to enable MDX parsing. Webstudio does not rewrite the file while+renaming it; invalid MDX remains editable and reports source-located errors.+Edits save when the editor loses focus or when you press `Command + S` onmacOS, `Ctrl + S` on Windows, or `Command/Ctrl + Enter`. Edit the completefilename in Asset settings to rename a text file or change its format. When you@@ -62,7 +67,7 @@ Converting an empty text file to `.json` initializes it with an empty object.### Use assets as content-Markdown and JSON files in Assets can be the source of truth for a site. The+Markdown, MDX, and JSON files in Assets can be the source of truth for a site. TheContent Engine reads their structured fields, queries the files, and resolveslinks between them. See [Content Engine](content-engine.md) for the supportedfile structure and a complete article workflow.diff --git a/docs/university/foundations/content-engine-reference.md b/docs/university/foundations/content-engine-reference.mdindex 01b61be833..d5dd1fa179 100644--- a/docs/university/foundations/content-engine-reference.md+++ b/docs/university/foundations/content-engine-reference.md@@ -220,6 +220,9 @@ Resolve paths relative to the file containing the reference. JSON Pointer uses `| JSON string | 16 KiB || Indexed properties per document | 64 KiB || Generated excerpt | 2 KiB |+| MDX nesting depth | 100 |+| MDX nodes | 20000 |+| MDX properties | 4000 || Loaded file | 1 MiB || Loaded content per query | 2 MiB || Loaded files per query | 20 |diff --git a/docs/university/mcp.md b/docs/university/mcp.mdindex 2c77356496..0597a4aea7 100644--- a/docs/university/mcp.md+++ b/docs/university/mcp.md@@ -2158,6 +2158,9 @@ Resolve paths relative to the file containing the reference. JSON Pointer uses `| JSON string | 16 KiB || Indexed properties per document | 64 KiB || Generated excerpt | 2 KiB |+| MDX nesting depth | 100 |+| MDX nodes | 20000 |+| MDX properties | 4000 || Loaded file | 1 MiB || Loaded content per query | 2 MiB || Loaded files per query | 20 |diff --git a/fixtures/react-router-cloudflare/.webstudio/data.json b/fixtures/react-router-cloudflare/.webstudio/data.jsonindex 7835eaa96b..5a29485a7c 100644--- a/fixtures/react-router-cloudflare/.webstudio/data.json+++ b/fixtures/react-router-cloudflare/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-8eygaw",+ "bundleVersion": "bundle-1mym82p","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.server.tsx b/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.server.tsxindex 023be09459..40d1b230d9 100644--- a/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.server.tsx+++ b/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsx b/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsxindex 3896f613db..55164bf9dd 100644--- a/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsx+++ b/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx b/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsxindex ab5d17cf89..d44cc286db 100644--- a/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx+++ b/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/react-router-cloudflare/app/routes/_index.tsx b/fixtures/react-router-cloudflare/app/routes/_index.tsxindex d8fe87ddaa..0b9d27d395 100644--- a/fixtures/react-router-cloudflare/app/routes/_index.tsx+++ b/fixtures/react-router-cloudflare/app/routes/_index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/react-router-docker/.webstudio/data.json b/fixtures/react-router-docker/.webstudio/data.jsonindex 7835eaa96b..5a29485a7c 100644--- a/fixtures/react-router-docker/.webstudio/data.json+++ b/fixtures/react-router-docker/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-8eygaw",+ "bundleVersion": "bundle-1mym82p","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-docker/app/__generated__/[another-page]._index.server.tsx b/fixtures/react-router-docker/app/__generated__/[another-page]._index.server.tsxindex 023be09459..40d1b230d9 100644--- a/fixtures/react-router-docker/app/__generated__/[another-page]._index.server.tsx+++ b/fixtures/react-router-docker/app/__generated__/[another-page]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/react-router-docker/app/__generated__/_index.server.tsx b/fixtures/react-router-docker/app/__generated__/_index.server.tsxindex 3896f613db..55164bf9dd 100644--- a/fixtures/react-router-docker/app/__generated__/_index.server.tsx+++ b/fixtures/react-router-docker/app/__generated__/_index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/react-router-docker/app/routes/[another-page]._index.tsx b/fixtures/react-router-docker/app/routes/[another-page]._index.tsxindex ab5d17cf89..d44cc286db 100644--- a/fixtures/react-router-docker/app/routes/[another-page]._index.tsx+++ b/fixtures/react-router-docker/app/routes/[another-page]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/react-router-docker/app/routes/_index.tsx b/fixtures/react-router-docker/app/routes/_index.tsxindex d8fe87ddaa..0b9d27d395 100644--- a/fixtures/react-router-docker/app/routes/_index.tsx+++ b/fixtures/react-router-docker/app/routes/_index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/react-router-netlify/.webstudio/data.json b/fixtures/react-router-netlify/.webstudio/data.jsonindex 7835eaa96b..5a29485a7c 100644--- a/fixtures/react-router-netlify/.webstudio/data.json+++ b/fixtures/react-router-netlify/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-8eygaw",+ "bundleVersion": "bundle-1mym82p","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-netlify/app/__generated__/[another-page]._index.server.tsx b/fixtures/react-router-netlify/app/__generated__/[another-page]._index.server.tsxindex 023be09459..40d1b230d9 100644--- a/fixtures/react-router-netlify/app/__generated__/[another-page]._index.server.tsx+++ b/fixtures/react-router-netlify/app/__generated__/[another-page]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/react-router-netlify/app/__generated__/_index.server.tsx b/fixtures/react-router-netlify/app/__generated__/_index.server.tsxindex 3896f613db..55164bf9dd 100644--- a/fixtures/react-router-netlify/app/__generated__/_index.server.tsx+++ b/fixtures/react-router-netlify/app/__generated__/_index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx b/fixtures/react-router-netlify/app/routes/[another-page]._index.tsxindex ab5d17cf89..d44cc286db 100644--- a/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx+++ b/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/react-router-netlify/app/routes/_index.tsx b/fixtures/react-router-netlify/app/routes/_index.tsxindex d8fe87ddaa..0b9d27d395 100644--- a/fixtures/react-router-netlify/app/routes/_index.tsx+++ b/fixtures/react-router-netlify/app/routes/_index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/react-router-vercel/.webstudio/data.json b/fixtures/react-router-vercel/.webstudio/data.jsonindex 7835eaa96b..5a29485a7c 100644--- a/fixtures/react-router-vercel/.webstudio/data.json+++ b/fixtures/react-router-vercel/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-8eygaw",+ "bundleVersion": "bundle-1mym82p","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-vercel/app/__generated__/[another-page]._index.server.tsx b/fixtures/react-router-vercel/app/__generated__/[another-page]._index.server.tsxindex 023be09459..40d1b230d9 100644--- a/fixtures/react-router-vercel/app/__generated__/[another-page]._index.server.tsx+++ b/fixtures/react-router-vercel/app/__generated__/[another-page]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/react-router-vercel/app/__generated__/_index.server.tsx b/fixtures/react-router-vercel/app/__generated__/_index.server.tsxindex 3896f613db..55164bf9dd 100644--- a/fixtures/react-router-vercel/app/__generated__/_index.server.tsx+++ b/fixtures/react-router-vercel/app/__generated__/_index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx b/fixtures/react-router-vercel/app/routes/[another-page]._index.tsxindex ab5d17cf89..d44cc286db 100644--- a/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx+++ b/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/react-router-vercel/app/routes/_index.tsx b/fixtures/react-router-vercel/app/routes/_index.tsxindex d8fe87ddaa..0b9d27d395 100644--- a/fixtures/react-router-vercel/app/routes/_index.tsx+++ b/fixtures/react-router-vercel/app/routes/_index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/ssg-cloudflare-pages/.webstudio/data.json b/fixtures/ssg-cloudflare-pages/.webstudio/data.jsonindex 136bae543f..842d2280d3 100644--- a/fixtures/ssg-cloudflare-pages/.webstudio/data.json+++ b/fixtures/ssg-cloudflare-pages/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-8eygaw",+ "bundleVersion": "bundle-1mym82p","build": {"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.server.tsx b/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.server.tsxindex 023be09459..40d1b230d9 100644--- a/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.server.tsx+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsx b/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsxindex 3896f613db..55164bf9dd 100644--- a/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsx+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/ssg-cloudflare-pages/pages/another-page/+data.ts b/fixtures/ssg-cloudflare-pages/pages/another-page/+data.tsindex a6b39df159..99ee0d0d3e 100644--- a/fixtures/ssg-cloudflare-pages/pages/another-page/+data.ts+++ b/fixtures/ssg-cloudflare-pages/pages/another-page/+data.ts@@ -70,6 +70,14 @@ export const data = async (pageContext: PageContextServer) => {getResources({ system }).data,url);+ Object.assign(+ resources,+ await loadResources(+ customFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url+ )+ );const pageMeta = getPageMeta({ system, resources });return {diff --git a/fixtures/ssg-cloudflare-pages/pages/index/+data.ts b/fixtures/ssg-cloudflare-pages/pages/index/+data.tsindex 41189eeabd..37824aa8d2 100644--- a/fixtures/ssg-cloudflare-pages/pages/index/+data.ts+++ b/fixtures/ssg-cloudflare-pages/pages/index/+data.ts@@ -70,6 +70,14 @@ export const data = async (pageContext: PageContextServer) => {getResources({ system }).data,url);+ Object.assign(+ resources,+ await loadResources(+ customFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url+ )+ );const pageMeta = getPageMeta({ system, resources });return {diff --git a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json b/fixtures/ssg-netlify-by-project-id/.webstudio/data.jsonindex 15b8786768..197ff4036e 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-8eygaw",+ "bundleVersion": "bundle-1mym82p","build": {"id": "8f0fdff2-e76b-4f86-9203-ea7df5f1143c","projectId": "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e",diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsxindex de8b65606e..49b47c91c4 100644--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsx+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsxindex 3896f613db..55164bf9dd 100644--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/ssg-netlify-by-project-id/pages/index/+data.ts b/fixtures/ssg-netlify-by-project-id/pages/index/+data.tsindex 41189eeabd..37824aa8d2 100644--- a/fixtures/ssg-netlify-by-project-id/pages/index/+data.ts+++ b/fixtures/ssg-netlify-by-project-id/pages/index/+data.ts@@ -70,6 +70,14 @@ export const data = async (pageContext: PageContextServer) => {getResources({ system }).data,url);+ Object.assign(+ resources,+ await loadResources(+ customFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url+ )+ );const pageMeta = getPageMeta({ system, resources });return {diff --git a/fixtures/ssg-netlify-by-project-id/pages/redirect/+data.ts b/fixtures/ssg-netlify-by-project-id/pages/redirect/+data.tsindex 8b9723c4ea..0b931cf67d 100644--- a/fixtures/ssg-netlify-by-project-id/pages/redirect/+data.ts+++ b/fixtures/ssg-netlify-by-project-id/pages/redirect/+data.ts@@ -70,6 +70,14 @@ export const data = async (pageContext: PageContextServer) => {getResources({ system }).data,url);+ Object.assign(+ resources,+ await loadResources(+ customFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url+ )+ );const pageMeta = getPageMeta({ system, resources });return {diff --git a/fixtures/webstudio-cloudflare-template/.webstudio/data.json b/fixtures/webstudio-cloudflare-template/.webstudio/data.jsonindex 136bae543f..842d2280d3 100644--- a/fixtures/webstudio-cloudflare-template/.webstudio/data.json+++ b/fixtures/webstudio-cloudflare-template/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-8eygaw",+ "bundleVersion": "bundle-1mym82p","build": {"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.server.tsx b/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.server.tsxindex 023be09459..40d1b230d9 100644--- a/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.server.tsx+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsx b/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsxindex 3896f613db..55164bf9dd 100644--- a/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsx+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx b/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsxindex bff4144f99..8ba1d66e4e 100644--- a/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx+++ b/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx@@ -128,6 +128,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx b/fixtures/webstudio-cloudflare-template/app/routes/_index.tsxindex eb8edabb69..87b03a8a3d 100644--- a/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx+++ b/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx@@ -128,6 +128,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/.webstudio/data.json b/fixtures/webstudio-features/.webstudio/data.jsonindex 174fb5c7db..16bcfd47ca 100644--- a/fixtures/webstudio-features/.webstudio/data.json+++ b/fixtures/webstudio-features/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-8eygaw",+ "bundleVersion": "bundle-1mym82p","build": {"id": "1b66ee06-8ea5-4420-9a0e-e0d3a67aca32","projectId": "cddc1d44-af37-4cb6-a430-d300cf6f932d",diff --git a/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.jsindex 8c754c068d..1cf2180777 100644--- a/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js+++ b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js@@ -1,6 +1,6 @@-var Xf=Object.defineProperty;var ed=(t,e)=>{for(var n in e)Xf(t,n,{get:e[n],enumerable:!0})};var Vs;function g(t,e,n){function r(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=i.prototype,d=Object.keys(u);for(let l=0;l<d.length;l++){let f=d[l];f in a||(a[f]=u[f].bind(a))}}let o=n?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=n?.Parent?new s:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Kh=Symbol("zod_brand"),Ce=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},At=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Vs=globalThis).__zod_globalConfig??(Vs.__zod_globalConfig={});var Et=globalThis.__zod_globalConfig;function ge(t){return t&&Object.assign(Et,t),Et}var M={};ed(M,{BIGINT_FORMAT_RANGES:()=>Ws,Class:()=>lo,NUMBER_FORMAT_RANGES:()=>go,aborted:()=>Xe,allowsEval:()=>mo,assert:()=>sd,assertEqual:()=>td,assertIs:()=>rd,assertNever:()=>od,assertNotEqual:()=>nd,assignProp:()=>Ye,base64ToUint8Array:()=>Hs,base64urlToUint8Array:()=>Ed,cached:()=>kt,captureStackTrace:()=>Gn,cleanEnum:()=>Ad,cleanRegex:()=>an,clone:()=>be,cloneDef:()=>cd,createTransparentProxy:()=>md,defineLazy:()=>P,esc:()=>Vn,escapeRegex:()=>Qe,explicitlyAborted:()=>bo,extend:()=>gd,finalizeIssue:()=>me,floatSafeRemainder:()=>fo,getElementAtPath:()=>ud,getEnumValues:()=>on,getLengthableOrigin:()=>cn,getParsedType:()=>pd,getSizableOrigin:()=>Ys,hexToUint8Array:()=>kd,isObject:()=>yt,isPlainObject:()=>He,issue:()=>Dt,joinValues:()=>id,jsonStringifyReplacer:()=>vt,merge:()=>wd,mergeDefs:()=>Ue,normalizeParams:()=>I,nullish:()=>sn,numKeys:()=>dd,objectClone:()=>ad,omit:()=>yd,optionalKeys:()=>yo,parsedType:()=>Sd,partial:()=>_d,pick:()=>hd,prefixIssues:()=>Ve,primitiveTypes:()=>qs,promiseAllObject:()=>ld,propertyKeyTypes:()=>ho,randomString:()=>fd,required:()=>xd,safeExtend:()=>bd,shallowClone:()=>Js,slugify:()=>po,stringifyPrimitive:()=>Ks,uint8ArrayToBase64:()=>Xs,uint8ArrayToBase64url:()=>vd,uint8ArrayToHex:()=>Dd,unwrapMessage:()=>rn});function td(t){return t}function nd(t){return t}function rd(t){}function od(t){throw new Error("Unexpected value in exhaustive check")}function sd(t){}function on(t){let e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,o])=>e.indexOf(+r)===-1).map(([r,o])=>o)}function id(t,e="|"){return t.map(n=>Ks(n)).join(e)}function vt(t,e){return typeof e=="bigint"?e.toString():e}function kt(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function sn(t){return t==null}function an(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function fo(t,e){let n=t/e,r=Math.round(n),o=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<o?0:n-r}var Gs=Symbol("evaluating");function P(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==Gs)return r===void 0&&(r=Gs,r=n()),r},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function ad(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Ye(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ue(...t){let e={};for(let n of t){let r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function cd(t){return Ue(t._zod.def)}function ud(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function ld(t){let e=Object.keys(t),n=e.map(r=>t[r]);return Promise.all(n).then(r=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=r[s];return o})}function fd(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<t;r++)n+=e[Math.floor(Math.random()*e.length)];return n}function Vn(t){return JSON.stringify(t)}function po(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Gn="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function yt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var mo=kt(()=>{if(Et.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function He(t){if(yt(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let n=e.prototype;return!(yt(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Js(t){return He(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function dd(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}var pd=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},ho=new Set(["string","number","symbol"]),qs=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Qe(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function be(t,e,n){let r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function I(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function md(t){let e;return new Proxy({},{get(n,r,o){return e??(e=t()),Reflect.get(e,r,o)},set(n,r,o,s){return e??(e=t()),Reflect.set(e,r,o,s)},has(n,r){return e??(e=t()),Reflect.has(e,r)},deleteProperty(n,r){return e??(e=t()),Reflect.deleteProperty(e,r)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,r){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,r)},defineProperty(n,r,o){return e??(e=t()),Reflect.defineProperty(e,r,o)}})}function Ks(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function yo(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var go={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]},Ws={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function hd(t,e){let n=t._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=Ue(t._zod.def,{get shape(){let i={};for(let a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(i[a]=n.shape[a])}return Ye(this,"shape",i),i},checks:[]});return be(t,s)}function yd(t,e){let n=t._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=Ue(t._zod.def,{get shape(){let i={...t._zod.def.shape};for(let a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete i[a]}return Ye(this,"shape",i),i},checks:[]});return be(t,s)}function gd(t,e){if(!He(e))throw new Error("Invalid input to extend: expected a plain object");let n=t._zod.def.checks;if(n&&n.length>0){let s=t._zod.def.shape;for(let i in e)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Ue(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return Ye(this,"shape",s),s}});return be(t,o)}function bd(t,e){if(!He(e))throw new Error("Invalid input to safeExtend: expected a plain object");let n=Ue(t._zod.def,{get shape(){let r={...t._zod.def.shape,...e};return Ye(this,"shape",r),r}});return be(t,n)}function wd(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=Ue(t._zod.def,{get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Ye(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return be(t,n)}function _d(t,e,n){let o=e._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let i=Ue(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(n)for(let u in n){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(c[u]=t?new t({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)c[u]=t?new t({type:"optional",innerType:a[u]}):a[u];return Ye(this,"shape",c),c},checks:[]});return be(e,i)}function xd(t,e,n){let r=Ue(e._zod.def,{get shape(){let o=e._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 t({type:"nonoptional",innerType:o[i]}))}else for(let i in o)s[i]=new t({type:"nonoptional",innerType:o[i]});return Ye(this,"shape",s),s}});return be(e,r)}function Xe(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function bo(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue===!1)return!0;return!1}function Ve(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function rn(t){return typeof t=="string"?t:t?.message}function me(t,e,n){let r=t.message?t.message:rn(t.inst?._zod.def?.error?.(t))??rn(e?.error?.(t))??rn(n.customError?.(t))??rn(n.localeError?.(t))??"Invalid input",{inst:o,continue:s,input:i,...a}=t;return a.path??(a.path=[]),a.message=r,e?.reportInput&&(a.input=i),a}function Ys(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function cn(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Sd(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let n=t;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return e}function Dt(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function Ad(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function Hs(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function Xs(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}function Ed(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-e.length%4)%4);return Hs(e+n)}function vd(t){return Xs(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function kd(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let n=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)n[r/2]=Number.parseInt(e.slice(r,r+2),16);return n}function Dd(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var lo=class{constructor(...e){}};var ei=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,vt,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Jn=g("$ZodError",ei),wo=g("$ZodError",ei,{Parent:Error});function ti(t,e=n=>n.message){let n={},r=[];for(let o of t.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:n}}function ni(t,e=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(a=>r({issues:a},[...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 a=[...s,...i.path];if(a.length===0)n._errors.push(e(i));else{let c=n,u=0;for(;u<a.length;){let d=a[u];u===a.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(e(i))):c[d]=c[d]||{_errors:[]},c=c[d],u++}}}};return r(t),n}var qn=t=>(e,n,r,o)=>{let s=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new Ce;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>me(c,s,ge())));throw Gn(a,o?.callee),a}return i.value};var Kn=t=>async(e,n,r,o)=>{let s=r?{...r,async:!0}:{async:!0},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>me(c,s,ge())));throw Gn(a,o?.callee),a}return i.value};var un=t=>(e,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Ce;return s.issues.length?{success:!1,error:new(t??Jn)(s.issues.map(i=>me(i,o,ge())))}:{success:!0,data:s.value}},ri=un(wo),ln=t=>async(e,n,r)=>{let o=r?{...r,async:!0}:{async:!0},s=e._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>me(i,o,ge())))}:{success:!0,data:s.value}},oi=ln(wo),si=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return qn(t)(e,n,o)};var ii=t=>(e,n,r)=>qn(t)(e,n,r);var ai=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Kn(t)(e,n,o)};var ci=t=>async(e,n,r)=>Kn(t)(e,n,r);var ui=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return un(t)(e,n,o)};var li=t=>(e,n,r)=>un(t)(e,n,r);var fi=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return ln(t)(e,n,o)};var di=t=>async(e,n,r)=>ln(t)(e,n,r);var pi=/^[cC][0-9a-z]{6,}$/,mi=/^[0-9a-z]+$/,hi=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,yi=/^[0-9a-vA-V]{20}$/,gi=/^[A-Za-z0-9]{27}$/,bi=/^[a-zA-Z0-9_-]{21}$/,wi=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var _i=/^([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})$/,_o=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[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 xi=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Id="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Si(){return new RegExp(Id,"u")}var Ai=/^(?:(?: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])$/,Ei=/^(([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 vi=/^((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])$/,ki=/^(([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])$/,Di=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,xo=/^[A-Za-z0-9_-]*$/;var Ri=/^https?$/,Ii=/^\+[1-9]\d{6,14}$/,Oi="(?:(?:\\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])))",Ci=new RegExp(`^${Oi}$`);function Ni(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function $i(t){return new RegExp(`^${Ni(t)}$`)}function Ti(t){let e=Ni({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${e}(?:${n.join("|")})`;return new RegExp(`^${Oi}T(?:${r})$`)}var zi=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Pi=/^-?\d+$/,So=/^-?\d+(?:\.\d+)?$/,Li=/^(?:true|false)$/i,Mi=/^null$/i;var Fi=/^[^A-Z]*$/,Zi=/^[^a-z]*$/;var X=g("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Bi={number:"number",bigint:"bigint",object:"date"},Ao=g("$ZodCheckLessThan",(t,e)=>{X.init(t,e);let n=Bi[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Eo=g("$ZodCheckGreaterThan",(t,e)=>{X.init(t,e);let n=Bi[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),ji=g("$ZodCheckMultipleOf",(t,e)=>{X.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):fo(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),Ui=g("$ZodCheckNumberFormat",(t,e)=>{X.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,s]=go[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,n&&(a.pattern=Pi)}),t._zod.check=i=>{let a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,inclusive:!0,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,inclusive:!0,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:t,continue:!e.abort})}});var Qi=g("$ZodCheckMaxLength",(t,e)=>{var n;X.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!sn(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let o=r.value;if(o.length<=e.maximum)return;let i=cn(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Vi=g("$ZodCheckMinLength",(t,e)=>{var n;X.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!sn(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let o=r.value;if(o.length>=e.minimum)return;let i=cn(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Gi=g("$ZodCheckLengthEquals",(t,e)=>{var n;X.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!sn(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=r=>{let o=r.value,s=o.length;if(s===e.length)return;let i=cn(o),a=s>e.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),fn=g("$ZodCheckStringFormat",(t,e)=>{var n,r;X.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),Ji=g("$ZodCheckRegex",(t,e)=>{fn.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),qi=g("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Fi),fn.init(t,e)}),Ki=g("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Zi),fn.init(t,e)}),Wi=g("$ZodCheckIncludes",(t,e)=>{X.init(t,e);let n=Qe(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Yi=g("$ZodCheckStartsWith",(t,e)=>{X.init(t,e);let n=new RegExp(`^${Qe(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),Hi=g("$ZodCheckEndsWith",(t,e)=>{X.init(t,e);let n=new RegExp(`.*${Qe(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}});var Xi=g("$ZodCheckOverwrite",(t,e)=>{X.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});var Yn=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`+var id=Object.defineProperty;var ad=(t,e)=>{for(var n in e)id(t,n,{get:e[n],enumerable:!0})};var Ks;function g(t,e,n){function r(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=i.prototype,p=Object.keys(u);for(let l=0;l<p.length;l++){let f=p[l];f in a||(a[f]=u[f].bind(a))}}let o=n?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=n?.Parent?new s:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let p of u._zod.deferred)p();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var ty=Symbol("zod_brand"),Ce=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Et=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Ks=globalThis).__zod_globalConfig??(Ks.__zod_globalConfig={});var vt=globalThis.__zod_globalConfig;function ge(t){return t&&Object.assign(vt,t),vt}var M={};ad(M,{BIGINT_FORMAT_RANGES:()=>ei,Class:()=>mo,NUMBER_FORMAT_RANGES:()=>_o,aborted:()=>Xe,allowsEval:()=>go,assert:()=>dd,assertEqual:()=>cd,assertIs:()=>ld,assertNever:()=>fd,assertNotEqual:()=>ud,assignProp:()=>Ye,base64ToUint8Array:()=>ni,base64urlToUint8Array:()=>Cd,cached:()=>Rt,captureStackTrace:()=>Jn,cleanEnum:()=>Od,cleanRegex:()=>cn,clone:()=>be,cloneDef:()=>hd,createTransparentProxy:()=>xd,defineLazy:()=>P,esc:()=>Gn,escapeRegex:()=>Qe,explicitlyAborted:()=>xo,extend:()=>Ed,finalizeIssue:()=>me,floatSafeRemainder:()=>ho,getElementAtPath:()=>yd,getEnumValues:()=>sn,getLengthableOrigin:()=>un,getParsedType:()=>_d,getSizableOrigin:()=>ti,hexToUint8Array:()=>Td,isObject:()=>gt,isPlainObject:()=>He,issue:()=>kt,joinValues:()=>pd,jsonStringifyReplacer:()=>Dt,merge:()=>Dd,mergeDefs:()=>Ue,normalizeParams:()=>I,nullish:()=>an,numKeys:()=>wd,objectClone:()=>md,omit:()=>Ad,optionalKeys:()=>wo,parsedType:()=>Id,partial:()=>Rd,pick:()=>Sd,prefixIssues:()=>Ve,primitiveTypes:()=>Hs,promiseAllObject:()=>gd,propertyKeyTypes:()=>bo,randomString:()=>bd,required:()=>kd,safeExtend:()=>vd,shallowClone:()=>Ys,slugify:()=>yo,stringifyPrimitive:()=>Xs,uint8ArrayToBase64:()=>ri,uint8ArrayToBase64url:()=>Nd,uint8ArrayToHex:()=>$d,unwrapMessage:()=>on});function cd(t){return t}function ud(t){return t}function ld(t){}function fd(t){throw new Error("Unexpected value in exhaustive check")}function dd(t){}function sn(t){let e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,o])=>e.indexOf(+r)===-1).map(([r,o])=>o)}function pd(t,e="|"){return t.map(n=>Xs(n)).join(e)}function Dt(t,e){return typeof e=="bigint"?e.toString():e}function Rt(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function an(t){return t==null}function cn(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function ho(t,e){let n=t/e,r=Math.round(n),o=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<o?0:n-r}var Ws=Symbol("evaluating");function P(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==Ws)return r===void 0&&(r=Ws,r=n()),r},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function md(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Ye(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ue(...t){let e={};for(let n of t){let r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function hd(t){return Ue(t._zod.def)}function yd(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function gd(t){let e=Object.keys(t),n=e.map(r=>t[r]);return Promise.all(n).then(r=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=r[s];return o})}function bd(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<t;r++)n+=e[Math.floor(Math.random()*e.length)];return n}function Gn(t){return JSON.stringify(t)}function yo(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Jn="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function gt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var go=Rt(()=>{if(vt.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function He(t){if(gt(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let n=e.prototype;return!(gt(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Ys(t){return He(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function wd(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}var _d=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},bo=new Set(["string","number","symbol"]),Hs=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Qe(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function be(t,e,n){let r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function I(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function xd(t){let e;return new Proxy({},{get(n,r,o){return e??(e=t()),Reflect.get(e,r,o)},set(n,r,o,s){return e??(e=t()),Reflect.set(e,r,o,s)},has(n,r){return e??(e=t()),Reflect.has(e,r)},deleteProperty(n,r){return e??(e=t()),Reflect.deleteProperty(e,r)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,r){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,r)},defineProperty(n,r,o){return e??(e=t()),Reflect.defineProperty(e,r,o)}})}function Xs(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function wo(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var _o={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]},ei={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Sd(t,e){let n=t._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=Ue(t._zod.def,{get shape(){let i={};for(let a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(i[a]=n.shape[a])}return Ye(this,"shape",i),i},checks:[]});return be(t,s)}function Ad(t,e){let n=t._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=Ue(t._zod.def,{get shape(){let i={...t._zod.def.shape};for(let a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete i[a]}return Ye(this,"shape",i),i},checks:[]});return be(t,s)}function Ed(t,e){if(!He(e))throw new Error("Invalid input to extend: expected a plain object");let n=t._zod.def.checks;if(n&&n.length>0){let s=t._zod.def.shape;for(let i in e)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Ue(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return Ye(this,"shape",s),s}});return be(t,o)}function vd(t,e){if(!He(e))throw new Error("Invalid input to safeExtend: expected a plain object");let n=Ue(t._zod.def,{get shape(){let r={...t._zod.def.shape,...e};return Ye(this,"shape",r),r}});return be(t,n)}function Dd(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=Ue(t._zod.def,{get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Ye(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return be(t,n)}function Rd(t,e,n){let o=e._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let i=Ue(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(n)for(let u in n){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(c[u]=t?new t({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)c[u]=t?new t({type:"optional",innerType:a[u]}):a[u];return Ye(this,"shape",c),c},checks:[]});return be(e,i)}function kd(t,e,n){let r=Ue(e._zod.def,{get shape(){let o=e._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 t({type:"nonoptional",innerType:o[i]}))}else for(let i in o)s[i]=new t({type:"nonoptional",innerType:o[i]});return Ye(this,"shape",s),s}});return be(e,r)}function Xe(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function xo(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue===!1)return!0;return!1}function Ve(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function on(t){return typeof t=="string"?t:t?.message}function me(t,e,n){let r=t.message?t.message:on(t.inst?._zod.def?.error?.(t))??on(e?.error?.(t))??on(n.customError?.(t))??on(n.localeError?.(t))??"Invalid input",{inst:o,continue:s,input:i,...a}=t;return a.path??(a.path=[]),a.message=r,e?.reportInput&&(a.input=i),a}function ti(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function un(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Id(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let n=t;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return e}function kt(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function Od(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function ni(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function ri(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}function Cd(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-e.length%4)%4);return ni(e+n)}function Nd(t){return ri(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Td(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let n=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)n[r/2]=Number.parseInt(e.slice(r,r+2),16);return n}function $d(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var mo=class{constructor(...e){}};var oi=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Dt,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},qn=g("$ZodError",oi),So=g("$ZodError",oi,{Parent:Error});function si(t,e=n=>n.message){let n={},r=[];for(let o of t.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:n}}function ii(t,e=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(a=>r({issues:a},[...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 a=[...s,...i.path];if(a.length===0)n._errors.push(e(i));else{let c=n,u=0;for(;u<a.length;){let p=a[u];u===a.length-1?(c[p]=c[p]||{_errors:[]},c[p]._errors.push(e(i))):c[p]=c[p]||{_errors:[]},c=c[p],u++}}}};return r(t),n}var Kn=t=>(e,n,r,o)=>{let s=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new Ce;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>me(c,s,ge())));throw Jn(a,o?.callee),a}return i.value};var Wn=t=>async(e,n,r,o)=>{let s=r?{...r,async:!0}:{async:!0},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>me(c,s,ge())));throw Jn(a,o?.callee),a}return i.value};var ln=t=>(e,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Ce;return s.issues.length?{success:!1,error:new(t??qn)(s.issues.map(i=>me(i,o,ge())))}:{success:!0,data:s.value}},ai=ln(So),fn=t=>async(e,n,r)=>{let o=r?{...r,async:!0}:{async:!0},s=e._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>me(i,o,ge())))}:{success:!0,data:s.value}},ci=fn(So),ui=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Kn(t)(e,n,o)};var li=t=>(e,n,r)=>Kn(t)(e,n,r);var fi=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Wn(t)(e,n,o)};var di=t=>async(e,n,r)=>Wn(t)(e,n,r);var pi=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return ln(t)(e,n,o)};var mi=t=>(e,n,r)=>ln(t)(e,n,r);var hi=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return fn(t)(e,n,o)};var yi=t=>async(e,n,r)=>fn(t)(e,n,r);var gi=/^[cC][0-9a-z]{6,}$/,bi=/^[0-9a-z]+$/,wi=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,_i=/^[0-9a-vA-V]{20}$/,xi=/^[A-Za-z0-9]{27}$/,Si=/^[a-zA-Z0-9_-]{21}$/,Ai=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Ei=/^([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})$/,Ao=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[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 vi=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Pd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Di(){return new RegExp(Pd,"u")}var Ri=/^(?:(?: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])$/,ki=/^(([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 Ii=/^((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])$/,Oi=/^(([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])$/,Ci=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Eo=/^[A-Za-z0-9_-]*$/;var Ni=/^https?$/,Ti=/^\+[1-9]\d{6,14}$/,$i="(?:(?:\\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])))",zi=new RegExp(`^${$i}$`);function Pi(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Li(t){return new RegExp(`^${Pi(t)}$`)}function Mi(t){let e=Pi({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${e}(?:${n.join("|")})`;return new RegExp(`^${$i}T(?:${r})$`)}var Fi=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Zi=/^-?\d+$/,vo=/^-?\d+(?:\.\d+)?$/,Bi=/^(?:true|false)$/i,ji=/^null$/i;var Ui=/^[^A-Z]*$/,Qi=/^[^a-z]*$/;var X=g("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Vi={number:"number",bigint:"bigint",object:"date"},Do=g("$ZodCheckLessThan",(t,e)=>{X.init(t,e);let n=Vi[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Ro=g("$ZodCheckGreaterThan",(t,e)=>{X.init(t,e);let n=Vi[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Gi=g("$ZodCheckMultipleOf",(t,e)=>{X.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):ho(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),Ji=g("$ZodCheckNumberFormat",(t,e)=>{X.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,s]=_o[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,n&&(a.pattern=Zi)}),t._zod.check=i=>{let a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,inclusive:!0,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,inclusive:!0,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:t,continue:!e.abort})}});var qi=g("$ZodCheckMaxLength",(t,e)=>{var n;X.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!an(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let o=r.value;if(o.length<=e.maximum)return;let i=un(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Ki=g("$ZodCheckMinLength",(t,e)=>{var n;X.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!an(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let o=r.value;if(o.length>=e.minimum)return;let i=un(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Wi=g("$ZodCheckLengthEquals",(t,e)=>{var n;X.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!an(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=r=>{let o=r.value,s=o.length;if(s===e.length)return;let i=un(o),a=s>e.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),dn=g("$ZodCheckStringFormat",(t,e)=>{var n,r;X.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),Yi=g("$ZodCheckRegex",(t,e)=>{dn.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Hi=g("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Ui),dn.init(t,e)}),Xi=g("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Qi),dn.init(t,e)}),ea=g("$ZodCheckIncludes",(t,e)=>{X.init(t,e);let n=Qe(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),ta=g("$ZodCheckStartsWith",(t,e)=>{X.init(t,e);let n=new RegExp(`^${Qe(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),na=g("$ZodCheckEndsWith",(t,e)=>{X.init(t,e);let n=new RegExp(`.*${Qe(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}});var ra=g("$ZodCheckOverwrite",(t,e)=>{X.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});var Hn=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.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 e=Function,n=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...n,o.join(`-`))}};var ta={major:4,minor:4,patch:3};var j=g("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=ta;let r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(let o of r)for(let s of o._zod.onattach)s(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,a,c)=>{let u=Xe(i),d;for(let l of a){if(l._zod.def.when){if(bo(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&&c?.async===!1)throw new Ce;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,a,c)=>{if(Xe(i))return i.aborted=!0,i;let u=o(a,r,c);if(u instanceof Promise){if(c.async===!1)throw new Ce;return u.then(d=>t._zod.parse(d,c))}return t._zod.parse(u,c)};t._zod.run=(i,a)=>{if(a.skipChecks)return t._zod.parse(i,a);if(a.direction==="backward"){let u=t._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(d=>s(d,i,a)):s(u,i,a)}let c=t._zod.parse(i,a);if(c instanceof Promise){if(a.async===!1)throw new Ce;return c.then(u=>o(u,r,a))}return o(c,r,a)}}P(t,"~standard",()=>({validate:o=>{try{let s=ri(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return oi(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),er=g("$ZodString",(t,e)=>{j.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??zi(t._zod.bag),t._zod.parse=(n,r)=>{if(e.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:t}),n}}),U=g("$ZodStringFormat",(t,e)=>{fn.init(t,e),er.init(t,e)}),la=g("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=_i),U.init(t,e)}),fa=g("$ZodUUID",(t,e)=>{if(e.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=_o(r))}else e.pattern??(e.pattern=_o());U.init(t,e)}),da=g("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=xi),U.init(t,e)}),pa=g("$ZodURL",(t,e)=>{U.init(t,e),t._zod.check=n=>{try{let r=n.value.trim();if(!e.normalize&&e.protocol?.source===Ri.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:t,continue:!e.abort});return}let o=new URL(r);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),e.normalize?n.value=o.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),ma=g("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Si()),U.init(t,e)}),ha=g("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=bi),U.init(t,e)}),ya=g("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=pi),U.init(t,e)}),ga=g("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=mi),U.init(t,e)}),ba=g("$ZodULID",(t,e)=>{e.pattern??(e.pattern=hi),U.init(t,e)}),wa=g("$ZodXID",(t,e)=>{e.pattern??(e.pattern=yi),U.init(t,e)}),_a=g("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=gi),U.init(t,e)}),xa=g("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Ti(e)),U.init(t,e)}),Sa=g("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Ci),U.init(t,e)}),Aa=g("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=$i(e)),U.init(t,e)}),Ea=g("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=wi),U.init(t,e)}),va=g("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Ai),U.init(t,e),t._zod.bag.format="ipv4"}),ka=g("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Ei),U.init(t,e),t._zod.bag.format="ipv6",t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}});var Da=g("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=vi),U.init(t,e)}),Ra=g("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=ki),U.init(t,e),t._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:t,continue:!e.abort})}}});function Ia(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Oa=g("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Di),U.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{Ia(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function Od(t){if(!xo.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Ia(n)}var Ca=g("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=xo),U.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{Od(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Na=g("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Ii),U.init(t,e)});function Cd(t,e=null){try{let n=t.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||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var $a=g("$ZodJWT",(t,e)=>{U.init(t,e),t._zod.check=n=>{Cd(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}});var ko=g("$ZodNumber",(t,e)=>{j.init(t,e),t._zod.pattern=t._zod.bag.pattern??So,t._zod.parse=(n,r)=>{if(e.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:t,...s?{received:s}:{}}),n}}),Ta=g("$ZodNumberFormat",(t,e)=>{Ui.init(t,e),ko.init(t,e)}),za=g("$ZodBoolean",(t,e)=>{j.init(t,e),t._zod.pattern=Li,t._zod.parse=(n,r)=>{if(e.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:t}),n}});var Pa=g("$ZodNull",(t,e)=>{j.init(t,e),t._zod.pattern=Mi,t._zod.values=new Set([null]),t._zod.parse=(n,r)=>{let o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),n}});var La=g("$ZodUnknown",(t,e)=>{j.init(t,e),t._zod.parse=n=>n}),Ma=g("$ZodNever",(t,e)=>{j.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function na(t,e,n){t.issues.length&&e.issues.push(...Ve(n,t.issues)),e.value[n]=t.value}var Fa=g("$ZodArray",(t,e)=>{j.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),n;n.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},r);c instanceof Promise?s.push(c.then(u=>na(u,n,i))):na(c,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function Xn(t,e,n,r,o,s){let i=n in r;if(t.issues.length){if(o&&s&&!i)return;e.issues.push(...Ve(n,t.issues))}if(!i&&!o){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}t.value===void 0?i&&(e.value[n]=void 0):e.value[n]=t.value}function Za(t){let e=Object.keys(t.shape);for(let r of e)if(!t.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);let n=yo(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Ba(t,e,n,r,o,s){let i=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,d=c.optin==="optional",l=c.optout==="optional";for(let f in e){if(f==="__proto__"||a.has(f))continue;if(u==="never"){i.push(f);continue}let p=c.run({value:e[f],issues:[]},r);p instanceof Promise?t.push(p.then(y=>Xn(y,n,f,e,d,l))):Xn(p,n,f,e,d,l)}return i.length&&n.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:s}),t.length?Promise.all(t).then(()=>n):n}var Nd=g("$ZodObject",(t,e)=>{if(j.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let r=kt(()=>Za(e));P(t._zod,"propValues",()=>{let a=e.shape,c={};for(let u in a){let d=a[u]._zod;if(d.values){c[u]??(c[u]=new Set);for(let l of d.values)c[u].add(l)}}return c});let o=yt,s=e.catchall,i;t._zod.parse=(a,c)=>{i??(i=r.value);let u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.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:[]},c);h instanceof Promise?d.push(h.then(b=>Xn(b,a,f,u,y,m))):Xn(h,a,f,u,y,m)}return s?Ba(d,u,a,c,r.value,t):d.length?Promise.all(d).then(()=>a):a}}),ja=g("$ZodObjectJIT",(t,e)=>{Nd.init(t,e);let n=t._zod.parse,r=kt(()=>Za(e)),o=f=>{let p=new Yn(["shape","payload","ctx"]),y=r.value,m=A=>{let _=Vn(A);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),b=0;for(let A of y.keys)h[A]=`key_${b++}`;p.write("const newResult = {};");for(let A of y.keys){let _=h[A],w=Vn(A),E=f[A],k=E?._zod?.optin==="optional",x=E?._zod?.optout==="optional";p.write(`const ${_} = ${m(A)};`),k&&x?p.write(`+`))}};var sa={major:4,minor:4,patch:3};var j=g("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=sa;let r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(let o of r)for(let s of o._zod.onattach)s(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,a,c)=>{let u=Xe(i),p;for(let l of a){if(l._zod.def.when){if(xo(i)||!l._zod.def.when(i))continue}else if(u)continue;let f=i.issues.length,d=l._zod.check(i);if(d instanceof Promise&&c?.async===!1)throw new Ce;if(p||d instanceof Promise)p=(p??Promise.resolve()).then(async()=>{await d,i.issues.length!==f&&(u||(u=Xe(i,f)))});else{if(i.issues.length===f)continue;u||(u=Xe(i,f))}}return p?p.then(()=>i):i},s=(i,a,c)=>{if(Xe(i))return i.aborted=!0,i;let u=o(a,r,c);if(u instanceof Promise){if(c.async===!1)throw new Ce;return u.then(p=>t._zod.parse(p,c))}return t._zod.parse(u,c)};t._zod.run=(i,a)=>{if(a.skipChecks)return t._zod.parse(i,a);if(a.direction==="backward"){let u=t._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(p=>s(p,i,a)):s(u,i,a)}let c=t._zod.parse(i,a);if(c instanceof Promise){if(a.async===!1)throw new Ce;return c.then(u=>o(u,r,a))}return o(c,r,a)}}P(t,"~standard",()=>({validate:o=>{try{let s=ai(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return ci(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),tr=g("$ZodString",(t,e)=>{j.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Fi(t._zod.bag),t._zod.parse=(n,r)=>{if(e.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:t}),n}}),U=g("$ZodStringFormat",(t,e)=>{dn.init(t,e),tr.init(t,e)}),ma=g("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Ei),U.init(t,e)}),ha=g("$ZodUUID",(t,e)=>{if(e.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Ao(r))}else e.pattern??(e.pattern=Ao());U.init(t,e)}),ya=g("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=vi),U.init(t,e)}),ga=g("$ZodURL",(t,e)=>{U.init(t,e),t._zod.check=n=>{try{let r=n.value.trim();if(!e.normalize&&e.protocol?.source===Ni.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:t,continue:!e.abort});return}let o=new URL(r);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),e.normalize?n.value=o.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),ba=g("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Di()),U.init(t,e)}),wa=g("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Si),U.init(t,e)}),_a=g("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=gi),U.init(t,e)}),xa=g("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=bi),U.init(t,e)}),Sa=g("$ZodULID",(t,e)=>{e.pattern??(e.pattern=wi),U.init(t,e)}),Aa=g("$ZodXID",(t,e)=>{e.pattern??(e.pattern=_i),U.init(t,e)}),Ea=g("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=xi),U.init(t,e)}),va=g("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Mi(e)),U.init(t,e)}),Da=g("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=zi),U.init(t,e)}),Ra=g("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Li(e)),U.init(t,e)}),ka=g("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Ai),U.init(t,e)}),Ia=g("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Ri),U.init(t,e),t._zod.bag.format="ipv4"}),Oa=g("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=ki),U.init(t,e),t._zod.bag.format="ipv6",t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}});var Ca=g("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Ii),U.init(t,e)}),Na=g("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Oi),U.init(t,e),t._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:t,continue:!e.abort})}}});function Ta(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var $a=g("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Ci),U.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{Ta(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function Ld(t){if(!Eo.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Ta(n)}var za=g("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Eo),U.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{Ld(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Pa=g("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Ti),U.init(t,e)});function Md(t,e=null){try{let n=t.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||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var La=g("$ZodJWT",(t,e)=>{U.init(t,e),t._zod.check=n=>{Md(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}});var Io=g("$ZodNumber",(t,e)=>{j.init(t,e),t._zod.pattern=t._zod.bag.pattern??vo,t._zod.parse=(n,r)=>{if(e.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:t,...s?{received:s}:{}}),n}}),Ma=g("$ZodNumberFormat",(t,e)=>{Ji.init(t,e),Io.init(t,e)}),Fa=g("$ZodBoolean",(t,e)=>{j.init(t,e),t._zod.pattern=Bi,t._zod.parse=(n,r)=>{if(e.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:t}),n}});var Za=g("$ZodNull",(t,e)=>{j.init(t,e),t._zod.pattern=ji,t._zod.values=new Set([null]),t._zod.parse=(n,r)=>{let o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),n}});var Ba=g("$ZodUnknown",(t,e)=>{j.init(t,e),t._zod.parse=n=>n}),ja=g("$ZodNever",(t,e)=>{j.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function ia(t,e,n){t.issues.length&&e.issues.push(...Ve(n,t.issues)),e.value[n]=t.value}var Ua=g("$ZodArray",(t,e)=>{j.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),n;n.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},r);c instanceof Promise?s.push(c.then(u=>ia(u,n,i))):ia(c,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function er(t,e,n,r,o,s){let i=n in r;if(t.issues.length){if(o&&s&&!i)return;e.issues.push(...Ve(n,t.issues))}if(!i&&!o){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}t.value===void 0?i&&(e.value[n]=void 0):e.value[n]=t.value}function Qa(t){let e=Object.keys(t.shape);for(let r of e)if(!t.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);let n=wo(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Va(t,e,n,r,o,s){let i=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,p=c.optin==="optional",l=c.optout==="optional";for(let f in e){if(f==="__proto__"||a.has(f))continue;if(u==="never"){i.push(f);continue}let d=c.run({value:e[f],issues:[]},r);d instanceof Promise?t.push(d.then(y=>er(y,n,f,e,p,l))):er(d,n,f,e,p,l)}return i.length&&n.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:s}),t.length?Promise.all(t).then(()=>n):n}var Fd=g("$ZodObject",(t,e)=>{if(j.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let r=Rt(()=>Qa(e));P(t._zod,"propValues",()=>{let a=e.shape,c={};for(let u in a){let p=a[u]._zod;if(p.values){c[u]??(c[u]=new Set);for(let l of p.values)c[u].add(l)}}return c});let o=gt,s=e.catchall,i;t._zod.parse=(a,c)=>{i??(i=r.value);let u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let p=[],l=i.shape;for(let f of i.keys){let d=l[f],y=d._zod.optin==="optional",m=d._zod.optout==="optional",h=d._zod.run({value:u[f],issues:[]},c);h instanceof Promise?p.push(h.then(b=>er(b,a,f,u,y,m))):er(h,a,f,u,y,m)}return s?Va(p,u,a,c,r.value,t):p.length?Promise.all(p).then(()=>a):a}}),Ga=g("$ZodObjectJIT",(t,e)=>{Fd.init(t,e);let n=t._zod.parse,r=Rt(()=>Qa(e)),o=f=>{let d=new Hn(["shape","payload","ctx"]),y=r.value,m=A=>{let _=Gn(A);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};d.write("const input = payload.value;");let h=Object.create(null),b=0;for(let A of y.keys)h[A]=`key_${b++}`;d.write("const newResult = {};");for(let A of y.keys){let _=h[A],w=Gn(A),E=f[A],D=E?._zod?.optin==="optional",x=E?._zod?.optout==="optional";d.write(`const ${_} = ${m(A)};`),D&&x?d.write(`if (${_}.issues.length) {if (${w} in input) {payload.issues = payload.issues.concat(${_}.issues.map(iss => ({@@ -18,7 +18,7 @@ var Xf=Object.defineProperty;var ed=(t,e)=>{for(var n in e)Xf(t,n,{get:e[n],enumnewResult[${w}] = ${_}.value;}- `):k?p.write(`+ `):D?d.write(`if (${_}.issues.length) {payload.issues = payload.issues.concat(${_}.issues.map(iss => ({...iss,@@ -34,7 +34,7 @@ var Xf=Object.defineProperty;var ed=(t,e)=>{for(var n in e)Xf(t,n,{get:e[n],enumnewResult[${w}] = ${_}.value;}- `):p.write(`+ `):d.write(`const ${_}_present = ${w} in input;if (${_}.issues.length) {payload.issues = payload.issues.concat(${_}.issues.map(iss => ({@@ -59,136 +59,136 @@ var Xf=Object.defineProperty;var ed=(t,e)=>{for(var n in e)Xf(t,n,{get:e[n],enum}}- `)}p.write("payload.value = newResult;"),p.write("return payload;");let S=p.compile();return(A,_)=>S(f,A,_)},s,i=yt,a=!Et.jitless,u=a&&mo.value,d=e.catchall,l;t._zod.parse=(f,p)=>{l??(l=r.value);let y=f.value;return i(y)?a&&u&&p?.async===!1&&p.jitless!==!0?(s||(s=o(e.shape)),f=s(f,p),d?Ba([],y,f,p,l,t):f):n(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:y,inst:t}),f)}});function ra(t,e,n,r){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;let o=t.filter(s=>!Xe(s));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(s=>s.issues.map(i=>me(i,r,ge())))}),e)}var Do=g("$ZodUnion",(t,e)=>{j.init(t,e),P(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),P(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),P(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),P(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>an(o.source)).join("|")})$`)}});let n=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(r,o)=>{if(n)return n(r,o);let s=!1,i=[];for(let a of e.options){let c=a._zod.run({value:r.value,issues:[]},o);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}return s?Promise.all(i).then(a=>ra(a,r,t,o)):ra(i,r,t,o)}});var Ua=g("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,Do.init(t,e);let n=t._zod.parse;P(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let r=kt(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!yt(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=r.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback||s.direction==="backward"?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(r.value.keys()),input:i,path:[e.discriminator],inst:t}),o)}}),Qa=g("$ZodIntersection",(t,e)=>{j.init(t,e),t._zod.parse=(n,r)=>{let o=n.value,s=e.left._zod.run({value:o,issues:[]},r),i=e.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>oa(n,c,u)):oa(n,s,i)}});function vo(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(He(t)&&He(e)){let n=Object.keys(e),r=Object.keys(t).filter(s=>n.indexOf(s)!==-1),o={...t,...e};for(let s of r){let i=vo(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<t.length;r++){let o=t[r],s=e[r],i=vo(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 oa(t,e,n){let r=new Map,o;for(let a of e.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(let c of a.keys)r.has(c)||r.set(c,{}),r.get(c).l=!0}else t.issues.push(a);for(let a of n.issues)if(a.code==="unrecognized_keys")for(let c of a.keys)r.has(c)||r.set(c,{}),r.get(c).r=!0;else t.issues.push(a);let s=[...r].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&o&&t.issues.push({...o,keys:s}),Xe(t))return t;let i=vo(e.value,n.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return t.value=i.data,t}var Va=g("$ZodRecord",(t,e)=>{j.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!He(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let s=[],i=e.keyType._zod.values;if(i){n.value={};let a=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let d=e.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=>me(p,r,ge())),input:u,path:[u],inst:t});continue}let l=d.value,f=e.valueType._zod.run({value:o[u],issues:[]},r);f instanceof Promise?s.push(f.then(p=>{p.issues.length&&n.issues.push(...Ve(u,p.issues)),n.value[l]=p.value})):(f.issues.length&&n.issues.push(...Ve(u,f.issues)),n.value[l]=f.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{n.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},r);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&So.test(a)&&c.issues.length){let l=e.keyType._zod.run({value:Number(a),issues:[]},r);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");l.issues.length===0&&(c=l)}if(c.issues.length){e.mode==="loose"?n.value[a]=o[a]:n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(l=>me(l,r,ge())),input:a,path:[a],inst:t});continue}let d=e.valueType._zod.run({value:o[a],issues:[]},r);d instanceof Promise?s.push(d.then(l=>{l.issues.length&&n.issues.push(...Ve(a,l.issues)),n.value[c.value]=l.value})):(d.issues.length&&n.issues.push(...Ve(a,d.issues)),n.value[c.value]=d.value)}}return s.length?Promise.all(s).then(()=>n):n}});var Ga=g("$ZodEnum",(t,e)=>{j.init(t,e);let n=on(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(o=>ho.has(typeof o)).map(o=>typeof o=="string"?Qe(o):o.toString()).join("|")})$`),t._zod.parse=(o,s)=>{let i=o.value;return r.has(i)||o.issues.push({code:"invalid_value",values:n,input:i,inst:t}),o}}),Ja=g("$ZodLiteral",(t,e)=>{if(j.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let n=new Set(e.values);t._zod.values=n,t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Qe(r):r?Qe(r.toString()):String(r)).join("|")})$`),t._zod.parse=(r,o)=>{let s=r.value;return n.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}});var qa=g("$ZodTransform",(t,e)=>{j.init(t,e),t._zod.optin="optional",t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new At(t.constructor.name);let o=e.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 Ce;return n.value=o,n.fallback=!0,n}});function sa(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var Ro=g("$ZodOptional",(t,e)=>{j.init(t,e),t._zod.optin="optional",t._zod.optout="optional",P(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),P(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${an(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>{if(e.innerType._zod.optin==="optional"){let o=n.value,s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(i=>sa(i,o)):sa(s,o)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),Ka=g("$ZodExactOptional",(t,e)=>{Ro.init(t,e),P(t._zod,"values",()=>e.innerType._zod.values),P(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(n,r)=>e.innerType._zod.run(n,r)}),Wa=g("$ZodNullable",(t,e)=>{j.init(t,e),P(t._zod,"optin",()=>e.innerType._zod.optin),P(t._zod,"optout",()=>e.innerType._zod.optout),P(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${an(n.source)}|null)$`):void 0}),P(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),Ya=g("$ZodDefault",(t,e)=>{j.init(t,e),t._zod.optin="optional",P(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);if(n.value===void 0)return n.value=e.defaultValue,n;let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>ia(s,e)):ia(o,e)}});function ia(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Ha=g("$ZodPrefault",(t,e)=>{j.init(t,e),t._zod.optin="optional",P(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),Xa=g("$ZodNonOptional",(t,e)=>{j.init(t,e),P(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>aa(s,t)):aa(o,t)}});function aa(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var ec=g("$ZodCatch",(t,e)=>{j.init(t,e),t._zod.optin="optional",P(t._zod,"optout",()=>e.innerType._zod.optout),P(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(i=>me(i,r,ge()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(s=>me(s,r,ge()))},input:n.value}),n.issues=[],n.fallback=!0),n)}});var tc=g("$ZodPipe",(t,e)=>{j.init(t,e),P(t._zod,"values",()=>e.in._zod.values),P(t._zod,"optin",()=>e.in._zod.optin),P(t._zod,"optout",()=>e.out._zod.optout),P(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,r)=>{if(r.direction==="backward"){let s=e.out._zod.run(n,r);return s instanceof Promise?s.then(i=>Hn(i,e.in,r)):Hn(s,e.in,r)}let o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Hn(s,e.out,r)):Hn(o,e.out,r)}});function Hn(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},n)}var nc=g("$ZodReadonly",(t,e)=>{j.init(t,e),P(t._zod,"propValues",()=>e.innerType._zod.propValues),P(t._zod,"values",()=>e.innerType._zod.values),P(t._zod,"optin",()=>e.innerType?._zod?.optin),P(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(ca):ca(o)}});function ca(t){return t.value=Object.freeze(t.value),t}var rc=g("$ZodLazy",(t,e)=>{j.init(t,e),P(t._zod,"innerType",()=>{let n=e;return n._cachedInner||(n._cachedInner=e.getter()),n._cachedInner}),P(t._zod,"pattern",()=>t._zod.innerType?._zod?.pattern),P(t._zod,"propValues",()=>t._zod.innerType?._zod?.propValues),P(t._zod,"optin",()=>t._zod.innerType?._zod?.optin??void 0),P(t._zod,"optout",()=>t._zod.innerType?._zod?.optout??void 0),t._zod.parse=(n,r)=>t._zod.innerType._zod.run(n,r)}),oc=g("$ZodCustom",(t,e)=>{X.init(t,e),j.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{let r=n.value,o=e.fn(r);if(o instanceof Promise)return o.then(s=>ua(s,n,r,t));ua(o,n,r,t)}});function ua(t,e,n,r){if(!t){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),e.issues.push(Dt(o))}}var sc,dy=Symbol("ZodOutput"),py=Symbol("ZodInput"),Io=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...n){let r=n[0];return this._map.set(e,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let r={...this.get(n)??{}};delete r.id;let o={...r,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function $d(){return new Io}(sc=globalThis).__zod_globalRegistry??(sc.__zod_globalRegistry=$d());var gt=globalThis.__zod_globalRegistry;function ic(t,e){return new t({type:"string",...I(e)})}function ac(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...I(e)})}function Oo(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...I(e)})}function cc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...I(e)})}function uc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(e)})}function lc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(e)})}function fc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(e)})}function dc(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...I(e)})}function pc(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...I(e)})}function mc(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(e)})}function hc(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...I(e)})}function yc(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(e)})}function gc(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...I(e)})}function bc(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...I(e)})}function wc(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(e)})}function _c(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(e)})}function xc(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(e)})}function Sc(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(e)})}function Ac(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(e)})}function Ec(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...I(e)})}function vc(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...I(e)})}function kc(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...I(e)})}function Dc(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...I(e)})}function Rc(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(e)})}function Ic(t,e){return new t({type:"string",format:"date",check:"string_format",...I(e)})}function Oc(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...I(e)})}function Cc(t,e){return new t({type:"string",format:"duration",check:"string_format",...I(e)})}function Nc(t,e){return new t({type:"number",checks:[],...I(e)})}function $c(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...I(e)})}function Tc(t,e){return new t({type:"boolean",...I(e)})}function zc(t,e){return new t({type:"null",...I(e)})}function Pc(t){return new t({type:"unknown"})}function Lc(t,e){return new t({type:"never",...I(e)})}function tr(t,e){return new Ao({check:"less_than",...I(e),value:t,inclusive:!1})}function dn(t,e){return new Ao({check:"less_than",...I(e),value:t,inclusive:!0})}function nr(t,e){return new Eo({check:"greater_than",...I(e),value:t,inclusive:!1})}function pn(t,e){return new Eo({check:"greater_than",...I(e),value:t,inclusive:!0})}function rr(t,e){return new ji({check:"multiple_of",...I(e),value:t})}function or(t,e){return new Qi({check:"max_length",...I(e),maximum:t})}function Rt(t,e){return new Vi({check:"min_length",...I(e),minimum:t})}function sr(t,e){return new Gi({check:"length_equals",...I(e),length:t})}function Co(t,e){return new Ji({check:"string_format",format:"regex",...I(e),pattern:t})}function No(t){return new qi({check:"string_format",format:"lowercase",...I(t)})}function $o(t){return new Ki({check:"string_format",format:"uppercase",...I(t)})}function To(t,e){return new Wi({check:"string_format",format:"includes",...I(e),includes:t})}function zo(t,e){return new Yi({check:"string_format",format:"starts_with",...I(e),prefix:t})}function Po(t,e){return new Hi({check:"string_format",format:"ends_with",...I(e),suffix:t})}function et(t){return new Xi({check:"overwrite",tx:t})}function Lo(t){return et(e=>e.normalize(t))}function Mo(){return et(t=>t.trim())}function Fo(){return et(t=>t.toLowerCase())}function Zo(){return et(t=>t.toUpperCase())}function Bo(){return et(t=>po(t))}function Mc(t,e,n){return new t({type:"array",element:e,...I(n)})}function Fc(t,e,n){return new t({type:"custom",check:"custom",fn:e,...I(n)})}function Zc(t,e){let n=Td(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(Dt(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(Dt(s))}},t(r.value,r)),e);return n}function Td(t,e){let n=new X({check:"custom",...I(e)});return n._zod.check=t,n}function jo(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??gt,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function q(t,e,n={path:[],schemaPath:[]}){var r;let o=t._zod.def,s=e.seen.get(t);if(s)return s.count++,n.schemaPath.includes(t)&&(s.cycle=n.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:n.path};e.seen.set(t,i);let a=t._zod.toJSONSchema?.();if(a)i.schema=a;else{let d={...n,schemaPath:[...n.schemaPath,t],path:n.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,i.schema,d);else{let f=i.schema,p=e.processors[o.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);p(t,e,f,d)}let l=t._zod.parent;l&&(i.ref||(i.ref=l),q(l,e,d),e.seen.get(l).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),e.io==="input"&&ne(t)&&(delete i.schema.examples,delete i.schema.default),e.io==="input"&&"_prefault"in i.schema&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,e.seen.get(t).schema}function Uo(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=new Map;for(let i of t.seen.entries()){let a=t.metadataRegistry.get(i[0])?.id;if(a){let c=r.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,i[0])}}let o=i=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let l=t.external.registry.get(i[0])?.id,f=t.external.uri??(y=>y);if(l)return{ref:f(l)};let p=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=p,{defId:p,ref:`${f("__shared")}#/${a}/${p}`}}if(i[1]===n)return{ref:"#"};let u=`#/${a}/`,d=i[1].schema.id??`__schema${t.counter++}`;return{defId:d,ref:u+d}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=o(i);a.def={...a.schema},u&&(a.defId=u);let d=a.schema;for(let l in d)delete d[l];d.$ref=c};if(t.cycles==="throw")for(let i of t.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>+ `)}d.write("payload.value = newResult;"),d.write("return payload;");let S=d.compile();return(A,_)=>S(f,A,_)},s,i=gt,a=!vt.jitless,u=a&&go.value,p=e.catchall,l;t._zod.parse=(f,d)=>{l??(l=r.value);let y=f.value;return i(y)?a&&u&&d?.async===!1&&d.jitless!==!0?(s||(s=o(e.shape)),f=s(f,d),p?Va([],y,f,d,l,t):f):n(f,d):(f.issues.push({expected:"object",code:"invalid_type",input:y,inst:t}),f)}});function aa(t,e,n,r){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;let o=t.filter(s=>!Xe(s));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(s=>s.issues.map(i=>me(i,r,ge())))}),e)}var Oo=g("$ZodUnion",(t,e)=>{j.init(t,e),P(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),P(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),P(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),P(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>cn(o.source)).join("|")})$`)}});let n=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(r,o)=>{if(n)return n(r,o);let s=!1,i=[];for(let a of e.options){let c=a._zod.run({value:r.value,issues:[]},o);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}return s?Promise.all(i).then(a=>aa(a,r,t,o)):aa(i,r,t,o)}});var Ja=g("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,Oo.init(t,e);let n=t._zod.parse;P(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let r=Rt(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!gt(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=r.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback||s.direction==="backward"?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(r.value.keys()),input:i,path:[e.discriminator],inst:t}),o)}}),qa=g("$ZodIntersection",(t,e)=>{j.init(t,e),t._zod.parse=(n,r)=>{let o=n.value,s=e.left._zod.run({value:o,issues:[]},r),i=e.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>ca(n,c,u)):ca(n,s,i)}});function ko(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(He(t)&&He(e)){let n=Object.keys(e),r=Object.keys(t).filter(s=>n.indexOf(s)!==-1),o={...t,...e};for(let s of r){let i=ko(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<t.length;r++){let o=t[r],s=e[r],i=ko(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 ca(t,e,n){let r=new Map,o;for(let a of e.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(let c of a.keys)r.has(c)||r.set(c,{}),r.get(c).l=!0}else t.issues.push(a);for(let a of n.issues)if(a.code==="unrecognized_keys")for(let c of a.keys)r.has(c)||r.set(c,{}),r.get(c).r=!0;else t.issues.push(a);let s=[...r].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&o&&t.issues.push({...o,keys:s}),Xe(t))return t;let i=ko(e.value,n.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return t.value=i.data,t}var Ka=g("$ZodRecord",(t,e)=>{j.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!He(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let s=[],i=e.keyType._zod.values;if(i){n.value={};let a=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let p=e.keyType._zod.run({value:u,issues:[]},r);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(p.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map(d=>me(d,r,ge())),input:u,path:[u],inst:t});continue}let l=p.value,f=e.valueType._zod.run({value:o[u],issues:[]},r);f instanceof Promise?s.push(f.then(d=>{d.issues.length&&n.issues.push(...Ve(u,d.issues)),n.value[l]=d.value})):(f.issues.length&&n.issues.push(...Ve(u,f.issues)),n.value[l]=f.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{n.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},r);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&vo.test(a)&&c.issues.length){let l=e.keyType._zod.run({value:Number(a),issues:[]},r);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");l.issues.length===0&&(c=l)}if(c.issues.length){e.mode==="loose"?n.value[a]=o[a]:n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(l=>me(l,r,ge())),input:a,path:[a],inst:t});continue}let p=e.valueType._zod.run({value:o[a],issues:[]},r);p instanceof Promise?s.push(p.then(l=>{l.issues.length&&n.issues.push(...Ve(a,l.issues)),n.value[c.value]=l.value})):(p.issues.length&&n.issues.push(...Ve(a,p.issues)),n.value[c.value]=p.value)}}return s.length?Promise.all(s).then(()=>n):n}});var Wa=g("$ZodEnum",(t,e)=>{j.init(t,e);let n=sn(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(o=>bo.has(typeof o)).map(o=>typeof o=="string"?Qe(o):o.toString()).join("|")})$`),t._zod.parse=(o,s)=>{let i=o.value;return r.has(i)||o.issues.push({code:"invalid_value",values:n,input:i,inst:t}),o}}),Ya=g("$ZodLiteral",(t,e)=>{if(j.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let n=new Set(e.values);t._zod.values=n,t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Qe(r):r?Qe(r.toString()):String(r)).join("|")})$`),t._zod.parse=(r,o)=>{let s=r.value;return n.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}});var Ha=g("$ZodTransform",(t,e)=>{j.init(t,e),t._zod.optin="optional",t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Et(t.constructor.name);let o=e.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 Ce;return n.value=o,n.fallback=!0,n}});function ua(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var Co=g("$ZodOptional",(t,e)=>{j.init(t,e),t._zod.optin="optional",t._zod.optout="optional",P(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),P(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${cn(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>{if(e.innerType._zod.optin==="optional"){let o=n.value,s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(i=>ua(i,o)):ua(s,o)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),Xa=g("$ZodExactOptional",(t,e)=>{Co.init(t,e),P(t._zod,"values",()=>e.innerType._zod.values),P(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(n,r)=>e.innerType._zod.run(n,r)}),ec=g("$ZodNullable",(t,e)=>{j.init(t,e),P(t._zod,"optin",()=>e.innerType._zod.optin),P(t._zod,"optout",()=>e.innerType._zod.optout),P(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${cn(n.source)}|null)$`):void 0}),P(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),tc=g("$ZodDefault",(t,e)=>{j.init(t,e),t._zod.optin="optional",P(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);if(n.value===void 0)return n.value=e.defaultValue,n;let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>la(s,e)):la(o,e)}});function la(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var nc=g("$ZodPrefault",(t,e)=>{j.init(t,e),t._zod.optin="optional",P(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),rc=g("$ZodNonOptional",(t,e)=>{j.init(t,e),P(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>fa(s,t)):fa(o,t)}});function fa(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var oc=g("$ZodCatch",(t,e)=>{j.init(t,e),t._zod.optin="optional",P(t._zod,"optout",()=>e.innerType._zod.optout),P(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(i=>me(i,r,ge()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(s=>me(s,r,ge()))},input:n.value}),n.issues=[],n.fallback=!0),n)}});var sc=g("$ZodPipe",(t,e)=>{j.init(t,e),P(t._zod,"values",()=>e.in._zod.values),P(t._zod,"optin",()=>e.in._zod.optin),P(t._zod,"optout",()=>e.out._zod.optout),P(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,r)=>{if(r.direction==="backward"){let s=e.out._zod.run(n,r);return s instanceof Promise?s.then(i=>Xn(i,e.in,r)):Xn(s,e.in,r)}let o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Xn(s,e.out,r)):Xn(o,e.out,r)}});function Xn(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},n)}var ic=g("$ZodReadonly",(t,e)=>{j.init(t,e),P(t._zod,"propValues",()=>e.innerType._zod.propValues),P(t._zod,"values",()=>e.innerType._zod.values),P(t._zod,"optin",()=>e.innerType?._zod?.optin),P(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(da):da(o)}});function da(t){return t.value=Object.freeze(t.value),t}var ac=g("$ZodLazy",(t,e)=>{j.init(t,e),P(t._zod,"innerType",()=>{let n=e;return n._cachedInner||(n._cachedInner=e.getter()),n._cachedInner}),P(t._zod,"pattern",()=>t._zod.innerType?._zod?.pattern),P(t._zod,"propValues",()=>t._zod.innerType?._zod?.propValues),P(t._zod,"optin",()=>t._zod.innerType?._zod?.optin??void 0),P(t._zod,"optout",()=>t._zod.innerType?._zod?.optout??void 0),t._zod.parse=(n,r)=>t._zod.innerType._zod.run(n,r)}),cc=g("$ZodCustom",(t,e)=>{X.init(t,e),j.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{let r=n.value,o=e.fn(r);if(o instanceof Promise)return o.then(s=>pa(s,n,r,t));pa(o,n,r,t)}});function pa(t,e,n,r){if(!t){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),e.issues.push(kt(o))}}var uc,by=Symbol("ZodOutput"),wy=Symbol("ZodInput"),No=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...n){let r=n[0];return this._map.set(e,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let r={...this.get(n)??{}};delete r.id;let o={...r,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Zd(){return new No}(uc=globalThis).__zod_globalRegistry??(uc.__zod_globalRegistry=Zd());var bt=globalThis.__zod_globalRegistry;function lc(t,e){return new t({type:"string",...I(e)})}function fc(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...I(e)})}function To(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...I(e)})}function dc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...I(e)})}function pc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(e)})}function mc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(e)})}function hc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(e)})}function yc(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...I(e)})}function gc(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...I(e)})}function bc(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(e)})}function wc(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...I(e)})}function _c(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(e)})}function xc(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...I(e)})}function Sc(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...I(e)})}function Ac(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(e)})}function Ec(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(e)})}function vc(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(e)})}function Dc(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(e)})}function Rc(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(e)})}function kc(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...I(e)})}function Ic(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...I(e)})}function Oc(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...I(e)})}function Cc(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...I(e)})}function Nc(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(e)})}function Tc(t,e){return new t({type:"string",format:"date",check:"string_format",...I(e)})}function $c(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...I(e)})}function zc(t,e){return new t({type:"string",format:"duration",check:"string_format",...I(e)})}function Pc(t,e){return new t({type:"number",checks:[],...I(e)})}function Lc(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...I(e)})}function Mc(t,e){return new t({type:"boolean",...I(e)})}function Fc(t,e){return new t({type:"null",...I(e)})}function Zc(t){return new t({type:"unknown"})}function Bc(t,e){return new t({type:"never",...I(e)})}function nr(t,e){return new Do({check:"less_than",...I(e),value:t,inclusive:!1})}function pn(t,e){return new Do({check:"less_than",...I(e),value:t,inclusive:!0})}function rr(t,e){return new Ro({check:"greater_than",...I(e),value:t,inclusive:!1})}function mn(t,e){return new Ro({check:"greater_than",...I(e),value:t,inclusive:!0})}function or(t,e){return new Gi({check:"multiple_of",...I(e),value:t})}function sr(t,e){return new qi({check:"max_length",...I(e),maximum:t})}function It(t,e){return new Ki({check:"min_length",...I(e),minimum:t})}function ir(t,e){return new Wi({check:"length_equals",...I(e),length:t})}function $o(t,e){return new Yi({check:"string_format",format:"regex",...I(e),pattern:t})}function zo(t){return new Hi({check:"string_format",format:"lowercase",...I(t)})}function Po(t){return new Xi({check:"string_format",format:"uppercase",...I(t)})}function Lo(t,e){return new ea({check:"string_format",format:"includes",...I(e),includes:t})}function Mo(t,e){return new ta({check:"string_format",format:"starts_with",...I(e),prefix:t})}function Fo(t,e){return new na({check:"string_format",format:"ends_with",...I(e),suffix:t})}function et(t){return new ra({check:"overwrite",tx:t})}function Zo(t){return et(e=>e.normalize(t))}function Bo(){return et(t=>t.trim())}function jo(){return et(t=>t.toLowerCase())}function Uo(){return et(t=>t.toUpperCase())}function Qo(){return et(t=>yo(t))}function jc(t,e,n){return new t({type:"array",element:e,...I(n)})}function Uc(t,e,n){return new t({type:"custom",check:"custom",fn:e,...I(n)})}function Qc(t,e){let n=Bd(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(kt(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(kt(s))}},t(r.value,r)),e);return n}function Bd(t,e){let n=new X({check:"custom",...I(e)});return n._zod.check=t,n}function Vo(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??bt,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function q(t,e,n={path:[],schemaPath:[]}){var r;let o=t._zod.def,s=e.seen.get(t);if(s)return s.count++,n.schemaPath.includes(t)&&(s.cycle=n.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:n.path};e.seen.set(t,i);let a=t._zod.toJSONSchema?.();if(a)i.schema=a;else{let p={...n,schemaPath:[...n.schemaPath,t],path:n.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,i.schema,p);else{let f=i.schema,d=e.processors[o.type];if(!d)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);d(t,e,f,p)}let l=t._zod.parent;l&&(i.ref||(i.ref=l),q(l,e,p),e.seen.get(l).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),e.io==="input"&&ne(t)&&(delete i.schema.examples,delete i.schema.default),e.io==="input"&&"_prefault"in i.schema&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,e.seen.get(t).schema}function Go(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=new Map;for(let i of t.seen.entries()){let a=t.metadataRegistry.get(i[0])?.id;if(a){let c=r.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,i[0])}}let o=i=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let l=t.external.registry.get(i[0])?.id,f=t.external.uri??(y=>y);if(l)return{ref:f(l)};let d=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=d,{defId:d,ref:`${f("__shared")}#/${a}/${d}`}}if(i[1]===n)return{ref:"#"};let u=`#/${a}/`,p=i[1].schema.id??`__schema${t.counter++}`;return{defId:p,ref:u+p}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=o(i);a.def={...a.schema},u&&(a.defId=u);let p=a.schema;for(let l in p)delete p[l];p.$ref=c};if(t.cycles==="throw")for(let i of t.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>-Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of t.seen.entries()){let a=i[1];if(e===i[0]){s(i);continue}if(t.external){let u=t.external.registry.get(i[0])?.id;if(e!==i[0]&&u){s(i);continue}}if(t.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&t.reused==="ref"){s(i);continue}}}function Qo(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,d={...u},l=c.ref;if(c.ref=null,l){r(l);let p=t.seen.get(l),y=p.schema;if(y.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(y)):Object.assign(u,y),Object.assign(u,d),a._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=a._zod.parent;if(f&&f!==l){r(f);let p=t.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]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())r(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,n.def??n.schema);let s=t.metadataRegistry.get(e)?.id;s!==void 0&&o.id===s&&delete o.id;let i=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:mn(e,"input",t.processors),output:mn(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function ne(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let r=t._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return ne(r.element,n);if(r.type==="set")return ne(r.valueType,n);if(r.type==="lazy")return ne(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 ne(r.innerType,n);if(r.type==="intersection")return ne(r.left,n)||ne(r.right,n);if(r.type==="record"||r.type==="map")return ne(r.keyType,n)||ne(r.valueType,n);if(r.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:ne(r.in,n)||ne(r.out,n);if(r.type==="object"){for(let o in r.shape)if(ne(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(ne(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(ne(o,n))return!0;return!!(r.rest&&ne(r.rest,n))}return!1}var Bc=(t,e={})=>n=>{let r=jo({...n,processors:e});return q(t,r),Uo(r,t),Qo(r,t)},mn=(t,e,n={})=>r=>{let{libraryOptions:o,target:s}=r??{},i=jo({...o??{},target:s,io:e,processors:n});return q(t,i),Uo(i,t),Qo(i,t)};var zd={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},jc=(t,e,n,r)=>{let o=n;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=zd[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),u&&(o.contentEncoding=u),c&&c.size>0){let d=[...c];d.length===1?o.pattern=d[0].source:d.length>1&&(o.allOf=[...d.map(l=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:l.source}))])}},Uc=(t,e,n,r)=>{let o=n,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=t._zod.bag;typeof a=="string"&&a.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=e.target==="draft-04"||e.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 c=="number"&&(o.multipleOf=c)},Qc=(t,e,n,r)=>{n.type="boolean"};var Vc=(t,e,n,r)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"};var Gc=(t,e,n,r)=>{n.not={}};var Jc=(t,e,n,r)=>{};var qc=(t,e,n,r)=>{let o=t._zod.def,s=on(o.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},Kc=(t,e,n,r)=>{let o=t._zod.def,s=[];for(let i of o.values)if(i===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(e.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,e.target==="draft-04"||e.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 Wc=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var Yc=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var Hc=(t,e,n,r)=>{let o=n,s=t._zod.def,{minimum:i,maximum:a}=t._zod.bag;typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=q(s.element,e,{...r,path:[...r.path,"items"]})},Xc=(t,e,n,r)=>{let o=n,s=t._zod.def;o.type="object",o.properties={};let i=s.shape;for(let u in i)o.properties[u]=q(i[u],e,{...r,path:[...r.path,"properties",u]});let a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{let d=s.shape[u]._zod;return e.io==="input"?d.optin===void 0:d.optout===void 0}));c.size>0&&(o.required=Array.from(c)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=q(s.catchall,e,{...r,path:[...r.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},eu=(t,e,n,r)=>{let o=t._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>q(a,e,{...r,path:[...r.path,s?"oneOf":"anyOf",c]}));s?n.oneOf=i:n.anyOf=i},tu=(t,e,n,r)=>{let o=t._zod.def,s=q(o.left,e,{...r,path:[...r.path,"allOf",0]}),i=q(o.right,e,{...r,path:[...r.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];n.allOf=c};var nu=(t,e,n,r)=>{let o=n,s=t._zod.def;o.type="object";let i=s.keyType,c=i._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let d=q(s.valueType,e,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let l of c)o.patternProperties[l.source]=d}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(o.propertyNames=q(s.keyType,e,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=q(s.valueType,e,{...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)}},ru=(t,e,n,r)=>{let o=t._zod.def,s=q(o.innerType,e,r),i=e.seen.get(t);e.target==="openapi-3.0"?(i.ref=o.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},ou=(t,e,n,r)=>{let o=t._zod.def;q(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType},su=(t,e,n,r)=>{let o=t._zod.def;q(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},iu=(t,e,n,r)=>{let o=t._zod.def;q(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},au=(t,e,n,r)=>{let o=t._zod.def;q(o.innerType,e,r);let s=e.seen.get(t);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},cu=(t,e,n,r)=>{let o=t._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=e.io==="input"?s?o.out:o.in:o.out;q(i,e,r);let a=e.seen.get(t);a.ref=i},uu=(t,e,n,r)=>{let o=t._zod.def;q(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType,n.readOnly=!0};var Vo=(t,e,n,r)=>{let o=t._zod.def;q(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType},lu=(t,e,n,r)=>{let o=t._zod.innerType;q(o,e,r);let s=e.seen.get(t);s.ref=o};var jd=g("ZodISODateTime",(t,e)=>{xa.init(t,e),J.init(t,e)});function fu(t){return Rc(jd,t)}var Ud=g("ZodISODate",(t,e)=>{Sa.init(t,e),J.init(t,e)});function du(t){return Ic(Ud,t)}var Qd=g("ZodISOTime",(t,e)=>{Aa.init(t,e),J.init(t,e)});function pu(t){return Oc(Qd,t)}var Vd=g("ZodISODuration",(t,e)=>{Ea.init(t,e),J.init(t,e)});function mu(t){return Cc(Vd,t)}var qd=(t,e)=>{Jn.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>ni(t,n)},flatten:{value:n=>ti(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,vt,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,vt,2)}},isEmpty:{get(){return t.issues.length===0}}})};var ue=g("ZodError",qd,{Parent:Error});var hu=qn(ue),yu=Kn(ue),gu=un(ue),bu=ln(ue),wu=si(ue),_u=ii(ue),xu=ai(ue),Su=ci(ue),Au=ui(ue),Eu=li(ue),vu=fi(ue),ku=di(ue);var Du=new WeakMap;function hn(t,e,n){let r=Object.getPrototypeOf(t),o=Du.get(r);if(o||(o=new Set,Du.set(r,o)),!o.has(e)){o.add(e);for(let s in n){let i=n[s];Object.defineProperty(r,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var Q=g("ZodType",(t,e)=>(j.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:mn(t,"input"),output:mn(t,"output")}}),t.toJSONSchema=Bc(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,r)=>hu(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>gu(t,n,r),t.parseAsync=async(n,r)=>yu(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>bu(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>wu(t,n,r),t.decode=(n,r)=>_u(t,n,r),t.encodeAsync=async(n,r)=>xu(t,n,r),t.decodeAsync=async(n,r)=>Su(t,n,r),t.safeEncode=(n,r)=>Au(t,n,r),t.safeDecode=(n,r)=>Eu(t,n,r),t.safeEncodeAsync=async(n,r)=>vu(t,n,r),t.safeDecodeAsync=async(n,r)=>ku(t,n,r),hn(t,"ZodType",{check(...n){let r=this.def;return this.clone(M.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 be(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(jp(n,r))},superRefine(n,r){return this.check(Up(n,r))},overwrite(n){return this.check(et(n))},optional(){return Nu(this)},exactOptional(){return Rp(this)},nullable(){return $u(this)},nullish(){return Nu($u(this))},nonoptional(n){return Tp(this,n)},array(){return V(this)},or(n){return It([this,n])},and(n){return Ap(this,n)},transform(n){return Tu(this,kp(n))},default(n){return Cp(this,n)},prefault(n){return $p(this,n)},catch(n){return Pp(this,n)},pipe(n){return Tu(this,n)},readonly(){return Fp(this)},describe(n){let r=this.clone();return gt.add(r,{description:n}),r},meta(...n){if(n.length===0)return gt.get(this);let r=this.clone();return gt.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(t,"description",{get(){return gt.get(t)?.description},configurable:!0}),t)),zu=g("_ZodString",(t,e)=>{er.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(r,o,s)=>jc(t,r,o,s);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,hn(t,"_ZodString",{regex(...r){return this.check(Co(...r))},includes(...r){return this.check(To(...r))},startsWith(...r){return this.check(zo(...r))},endsWith(...r){return this.check(Po(...r))},min(...r){return this.check(Rt(...r))},max(...r){return this.check(or(...r))},length(...r){return this.check(sr(...r))},nonempty(...r){return this.check(Rt(1,...r))},lowercase(r){return this.check(No(r))},uppercase(r){return this.check($o(r))},trim(){return this.check(Mo())},normalize(...r){return this.check(Lo(...r))},toLowerCase(){return this.check(Fo())},toUpperCase(){return this.check(Zo())},slugify(){return this.check(Bo())}})}),Wd=g("ZodString",(t,e)=>{er.init(t,e),zu.init(t,e),t.email=n=>t.check(ac(Yd,n)),t.url=n=>t.check(dc(Hd,n)),t.jwt=n=>t.check(Dc(pp,n)),t.emoji=n=>t.check(pc(Xd,n)),t.guid=n=>t.check(Oo(Ru,n)),t.uuid=n=>t.check(cc(ar,n)),t.uuidv4=n=>t.check(uc(ar,n)),t.uuidv6=n=>t.check(lc(ar,n)),t.uuidv7=n=>t.check(fc(ar,n)),t.nanoid=n=>t.check(mc(ep,n)),t.guid=n=>t.check(Oo(Ru,n)),t.cuid=n=>t.check(hc(tp,n)),t.cuid2=n=>t.check(yc(np,n)),t.ulid=n=>t.check(gc(rp,n)),t.base64=n=>t.check(Ec(lp,n)),t.base64url=n=>t.check(vc(fp,n)),t.xid=n=>t.check(bc(op,n)),t.ksuid=n=>t.check(wc(sp,n)),t.ipv4=n=>t.check(_c(ip,n)),t.ipv6=n=>t.check(xc(ap,n)),t.cidrv4=n=>t.check(Sc(cp,n)),t.cidrv6=n=>t.check(Ac(up,n)),t.e164=n=>t.check(kc(dp,n)),t.datetime=n=>t.check(fu(n)),t.date=n=>t.check(du(n)),t.time=n=>t.check(pu(n)),t.duration=n=>t.check(mu(n))});function v(t){return ic(Wd,t)}var J=g("ZodStringFormat",(t,e)=>{U.init(t,e),zu.init(t,e)}),Yd=g("ZodEmail",(t,e)=>{da.init(t,e),J.init(t,e)});var Ru=g("ZodGUID",(t,e)=>{la.init(t,e),J.init(t,e)});var ar=g("ZodUUID",(t,e)=>{fa.init(t,e),J.init(t,e)});var Hd=g("ZodURL",(t,e)=>{pa.init(t,e),J.init(t,e)});var Xd=g("ZodEmoji",(t,e)=>{ma.init(t,e),J.init(t,e)});var ep=g("ZodNanoID",(t,e)=>{ha.init(t,e),J.init(t,e)});var tp=g("ZodCUID",(t,e)=>{ya.init(t,e),J.init(t,e)});var np=g("ZodCUID2",(t,e)=>{ga.init(t,e),J.init(t,e)});var rp=g("ZodULID",(t,e)=>{ba.init(t,e),J.init(t,e)});var op=g("ZodXID",(t,e)=>{wa.init(t,e),J.init(t,e)});var sp=g("ZodKSUID",(t,e)=>{_a.init(t,e),J.init(t,e)});var ip=g("ZodIPv4",(t,e)=>{va.init(t,e),J.init(t,e)});var ap=g("ZodIPv6",(t,e)=>{ka.init(t,e),J.init(t,e)});var cp=g("ZodCIDRv4",(t,e)=>{Da.init(t,e),J.init(t,e)});var up=g("ZodCIDRv6",(t,e)=>{Ra.init(t,e),J.init(t,e)});var lp=g("ZodBase64",(t,e)=>{Oa.init(t,e),J.init(t,e)});var fp=g("ZodBase64URL",(t,e)=>{Ca.init(t,e),J.init(t,e)});var dp=g("ZodE164",(t,e)=>{Na.init(t,e),J.init(t,e)});var pp=g("ZodJWT",(t,e)=>{$a.init(t,e),J.init(t,e)});var Pu=g("ZodNumber",(t,e)=>{ko.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(r,o,s)=>Uc(t,r,o,s),hn(t,"ZodNumber",{gt(r,o){return this.check(nr(r,o))},gte(r,o){return this.check(pn(r,o))},min(r,o){return this.check(pn(r,o))},lt(r,o){return this.check(tr(r,o))},lte(r,o){return this.check(dn(r,o))},max(r,o){return this.check(dn(r,o))},int(r){return this.check(Iu(r))},safe(r){return this.check(Iu(r))},positive(r){return this.check(nr(0,r))},nonnegative(r){return this.check(pn(0,r))},negative(r){return this.check(tr(0,r))},nonpositive(r){return this.check(dn(0,r))},multipleOf(r,o){return this.check(rr(r,o))},step(r,o){return this.check(rr(r,o))},finite(){return this}});let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function Z(t){return Nc(Pu,t)}var mp=g("ZodNumberFormat",(t,e)=>{Ta.init(t,e),Pu.init(t,e)});function Iu(t){return $c(mp,t)}var hp=g("ZodBoolean",(t,e)=>{za.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Qc(t,n,r,o)});function tt(t){return Tc(hp,t)}var yp=g("ZodNull",(t,e)=>{Pa.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Vc(t,n,r,o)});function gp(t){return zc(yp,t)}var bp=g("ZodUnknown",(t,e)=>{La.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Jc(t,n,r,o)});function Ou(){return Pc(bp)}var wp=g("ZodNever",(t,e)=>{Ma.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Gc(t,n,r,o)});function Lu(t){return Lc(wp,t)}var _p=g("ZodArray",(t,e)=>{Fa.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Hc(t,n,r,o),t.element=e.element,hn(t,"ZodArray",{min(n,r){return this.check(Rt(n,r))},nonempty(n){return this.check(Rt(1,n))},max(n,r){return this.check(or(n,r))},length(n,r){return this.check(sr(n,r))},unwrap(){return this.element}})});function V(t,e){return Mc(_p,t,e)}var Mu=g("ZodObject",(t,e)=>{ja.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Xc(t,n,r,o),M.defineLazy(t,"shape",()=>e.shape),hn(t,"ZodObject",{keyof(){return ae(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Ou()})},loose(){return this.clone({...this._zod.def,catchall:Ou()})},strict(){return this.clone({...this._zod.def,catchall:Lu()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return M.extend(this,n)},safeExtend(n){return M.safeExtend(this,n)},merge(n){return M.merge(this,n)},pick(n){return M.pick(this,n)},omit(n){return M.omit(this,n)},partial(...n){return M.partial(Zu,this,n[0])},required(...n){return M.required(Bu,this,n[0])}})});function he(t,e){let n={type:"object",shape:t??{},...M.normalizeParams(e)};return new Mu(n)}function C(t,e){return new Mu({type:"object",shape:t,catchall:Lu(),...M.normalizeParams(e)})}var Fu=g("ZodUnion",(t,e)=>{Do.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>eu(t,n,r,o),t.options=e.options});function It(t,e){return new Fu({type:"union",options:t,...M.normalizeParams(e)})}var xp=g("ZodDiscriminatedUnion",(t,e)=>{Fu.init(t,e),Ua.init(t,e)});function Ot(t,e,n){return new xp({type:"union",options:e,discriminator:t,...M.normalizeParams(n)})}var Sp=g("ZodIntersection",(t,e)=>{Qa.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>tu(t,n,r,o)});function Ap(t,e){return new Sp({type:"intersection",left:t,right:e})}var Cu=g("ZodRecord",(t,e)=>{Va.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>nu(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType});function we(t,e,n){return!e||!e._zod?new Cu({type:"record",keyType:v(),valueType:t,...M.normalizeParams(e)}):new Cu({type:"record",keyType:t,valueType:e,...M.normalizeParams(n)})}var Go=g("ZodEnum",(t,e)=>{Ga.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(r,o,s)=>qc(t,r,o,s),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Go({...e,checks:[],...M.normalizeParams(o),entries:s})},t.exclude=(r,o)=>{let s={...e.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 Go({...e,checks:[],...M.normalizeParams(o),entries:s})}});function ae(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new Go({type:"enum",entries:n,...M.normalizeParams(e)})}var Ep=g("ZodLiteral",(t,e)=>{Ja.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Kc(t,n,r,o),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function F(t,e){return new Ep({type:"literal",values:Array.isArray(t)?t:[t],...M.normalizeParams(e)})}var vp=g("ZodTransform",(t,e)=>{qa.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Yc(t,n,r,o),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new At(t.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(M.issue(s,n.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),n.issues.push(M.issue(i))}};let o=e.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 kp(t){return new vp({type:"transform",transform:t})}var Zu=g("ZodOptional",(t,e)=>{Ro.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Vo(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Nu(t){return new Zu({type:"optional",innerType:t})}var Dp=g("ZodExactOptional",(t,e)=>{Ka.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Vo(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Rp(t){return new Dp({type:"optional",innerType:t})}var Ip=g("ZodNullable",(t,e)=>{Wa.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ru(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function $u(t){return new Ip({type:"nullable",innerType:t})}var Op=g("ZodDefault",(t,e)=>{Ya.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>su(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Cp(t,e){return new Op({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():M.shallowClone(e)}})}var Np=g("ZodPrefault",(t,e)=>{Ha.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>iu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function $p(t,e){return new Np({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():M.shallowClone(e)}})}var Bu=g("ZodNonOptional",(t,e)=>{Xa.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ou(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Tp(t,e){return new Bu({type:"nonoptional",innerType:t,...M.normalizeParams(e)})}var zp=g("ZodCatch",(t,e)=>{ec.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>au(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Pp(t,e){return new zp({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Lp=g("ZodPipe",(t,e)=>{tc.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>cu(t,n,r,o),t.in=e.in,t.out=e.out});function Tu(t,e){return new Lp({type:"pipe",in:t,out:e})}var Mp=g("ZodReadonly",(t,e)=>{nc.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>uu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Fp(t){return new Mp({type:"readonly",innerType:t})}var Zp=g("ZodLazy",(t,e)=>{rc.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>lu(t,n,r,o),t.unwrap=()=>t._zod.def.getter()});function Jo(t){return new Zp({type:"lazy",getter:t})}var Bp=g("ZodCustom",(t,e)=>{oc.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Wc(t,n,r,o)});function jp(t,e={}){return Fc(Bp,t,e)}function Up(t,e){return Zc(t,e)}function nt(t){let e=Jo(()=>It([v(t),Z(),tt(),gp(),V(e),we(v(),e)]));return e}var ju=t=>"field"in t?[t]:("all"in t?t.all:t.any).flatMap(ju),yn=t=>ju(t);var Ct=(t,e)=>{if("field"in t)return e(t);let n="all"in t?t.all:t.any,r=!1;if("all"in t){for(let o of n){let s=Ct(o,e);if(s===!1)return!1;r||=s===void 0}return r?void 0:!0}for(let o of n){let s=Ct(o,e);if(s===!0)return!0;r||=s===void 0}return r?void 0:!1},Uu=t=>JSON.stringify(t),qo=t=>{if("field"in t)return{conditions:1,depth:0};let e="all"in t?t.all:t.any,n=0,r=1;for(let o of e){let s=qo(o);n+=s.conditions,r=Math.max(r,s.depth+1)}return{conditions:n,depth:r}},Qu=(t,e={})=>{let n=o=>{let s=V(o),i=e.maximumChildren===void 0?s:s.max(e.maximumChildren);return It([t,C({all:i}),C({any:i})])},r=Jo(()=>n(r));return e.maximumConditions===void 0&&e.maximumDepth===void 0?r:r.superRefine((o,s)=>{let{conditions:i,depth:a}=qo(o);e.maximumConditions!==void 0&&i>e.maximumConditions&&s.addIssue({code:"custom",message:e.maximumConditionsMessage??"Query exceeds the condition limit"}),e.maximumDepth!==void 0&&a>e.maximumDepth&&s.addIssue({code:"custom",message:e.maximumDepthMessage??"Query exceeds the nesting limit"})})};var R={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 bt(t,e=new Set){if(typeof t=="number"&&isNaN(t))throw new Error("NaN is not allowed");if(typeof t=="number"&&!isFinite(t))throw new Error("Infinity is not allowed");if(t===null||typeof t!="object")return JSON.stringify(t);if(typeof t.toJSON=="function"){if(e.has(t))throw new Error("Circular reference detected");e.add(t);let r=bt(t.toJSON(),e);return e.delete(t),r}if(e.has(t))throw new Error("Circular reference detected");e.add(t);let n;if(Array.isArray(t))n=`[${t.map(o=>bt(o===void 0||typeof o=="symbol"?null:o,e)).join(",")}]`;else{let r=[];for(let o of Object.keys(t).sort())t[o]===void 0||typeof t[o]=="symbol"||r.push(`${bt(o)}:${bt(t[o],e)}`);n=`{${r.join(",")}}`}return e.delete(t),n}var Qp=new TextEncoder,Nt=t=>Qp.encode(t),Ne=t=>Nt(t).byteLength,re=class extends Error{constructor(){super("Byte stream exceeds the configured limit"),this.name="ByteLimitExceededError"}},Vp=(t,e)=>{let n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.byteLength;return n},$t=t=>typeof t=="string"?{async*[Symbol.asyncIterator](){yield Nt(t)}}:t instanceof Uint8Array?{async*[Symbol.asyncIterator](){yield t}}:t,Ko=async(t,e)=>{let n=[],r=0;for await(let o of $t(t)){let s=e-r;if(s<=0)break;let i=o.subarray(0,s);if(n.push(i),r+=i.byteLength,r===e)break}return Vp(n,r)},$e=async(t,e)=>{let n=await Ko(t,e+1);if(n.byteLength>e)throw new re;return n},le=t=>new TextDecoder("utf-8",{fatal:!0}).decode(t),Tt=t=>t.charCodeAt(0)===65279?t.slice(1):t;var Vu=t=>{for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n>=55296&&n<=56319){let r=t.charCodeAt(e+1);if(e+1>=t.length||r<56320||r>57343)throw new Error("JSON strings cannot contain lone Unicode surrogates");e+=1;continue}if(n>=56320&&n<=57343)throw new Error("JSON strings cannot contain lone Unicode surrogates")}},Wo=(t,e)=>{if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return Vu(t),t;if(typeof t=="number"){if(Number.isFinite(t)===!1)throw new Error("JSON cannot contain non-finite numbers");return t}if(Array.isArray(t)){if(Object.getOwnPropertySymbols(t).length>0)throw new Error("JSON arrays cannot contain symbol properties");if(e.has(t))throw new Error("JSON cannot contain circular references");e.add(t);try{let n=[];for(let r=0;r<t.length;r+=1){if(Object.hasOwn(t,r)===!1)throw new Error("JSON arrays cannot be sparse");let o=t[r];if(o===void 0)throw new Error("JSON arrays cannot contain undefined values");n.push(Wo(o,e))}if(Object.keys(t).length!==t.length)throw new Error("JSON arrays cannot contain named properties");return n}finally{e.delete(t)}}if(typeof t=="object"){let n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw new Error("JSON can contain only plain objects");if(Object.getOwnPropertySymbols(t).length>0)throw new Error("JSON objects cannot contain symbol properties");if(e.has(t))throw new Error("JSON cannot contain circular references");e.add(t);let r={};try{for(let[o,s]of Object.entries(t))Vu(o),s!==void 0&&Object.defineProperty(r,o,{value:Wo(s,e),enumerable:!0,configurable:!0,writable:!0})}finally{e.delete(t)}return r}throw new Error("Value cannot be represented as JSON")},rt=t=>Wo(t,new Set),fe=t=>{let e=bt(rt(t));if(e===void 0)throw new Error("Value cannot be represented as canonical JSON");return e},gn=(t,e)=>t===void 0||e===void 0?t===e:fe(t)===fe(e),Te=(t,e)=>t<e?-1:t>e?1:0,Yo=async t=>{let e=typeof t=="string"?Nt(t):t,n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")},Gu=async t=>`sha256:${await Yo(t)}`;var Ju=Ot("type",[C({type:F("document")}),C({type:F("json"),path:V(v()).min(1)}),C({type:F("markdown-body")}),C({type:F("markdown-frontmatter")})]),Ho=C({documentId:v().min(1),revision:v().min(1),representation:Ju}),Gp=t=>{let e=Ju.parse(t);return e.type==="json"?Object.freeze({...e,path:Object.freeze([...e.path])}):Object.freeze(e)},qu=t=>{let e=Ho.parse(t);return Object.freeze({...e,representation:Gp(e.representation)})};var cr=C({id:v().min(1),revision:v().min(1),contentRef:v().min(1),format:ae(["json","markdown"]).optional()}),ur=C({sourceId:v().min(1),referenceId:v().min(1),reference:Ho});var zt=t=>{let e=new Map;for(let n of t){let r=e.get(n.sourceId)??[];r.push(n),e.set(n.sourceId,r)}return e};var ze=class extends Error{code;documentIds;constructor({code:e,message:n,documentIds:r=[]}){super(n),this.name="DocumentGraphError",this.code=e,this.documentIds=Object.freeze([...r])}},Jp=(t,e)=>Te(t.sourceId,e.sourceId)||Te(t.referenceId,e.referenceId),bn=({nodes:t,edges:e})=>{let n=t.map(a=>Object.freeze(cr.parse(a))).sort((a,c)=>Te(a.id,c.id)),r=new Map,o=new Map;for(let a of n){if(r.has(a.id))throw new ze({code:"DUPLICATE_NODE",message:`Document graph contains duplicate node ${a.id}`,documentIds:[a.id]});r.set(a.id,a);let c=o.get(a.contentRef);if(c!==void 0&&(c.revision!==a.revision||c.format!==a.format))throw new ze({code:"CONTENT_IDENTITY_CONFLICT",message:`Document graph content reference ${a.contentRef} has conflicting identities`,documentIds:[c.id,a.id]});o.set(a.contentRef,a)}let s=e.map(a=>{let c=ur.parse(a);return Object.freeze({...c,reference:qu(c.reference)})}).sort(Jp),i=new Set;for(let a of s){if(r.get(a.sourceId)===void 0)throw new ze({code:"SOURCE_NOT_FOUND",message:`Document graph source ${a.sourceId} does not exist`,documentIds:[a.sourceId]});let u=r.get(a.reference.documentId);if(u===void 0)throw new ze({code:"TARGET_NOT_FOUND",message:`Document graph target ${a.reference.documentId} does not exist`,documentIds:[a.sourceId,a.reference.documentId]});if(u.revision!==a.reference.revision)throw new ze({code:"TARGET_REVISION_MISMATCH",message:`Document graph target ${u.id} revision does not match its reference`,documentIds:[a.sourceId,u.id]});let d=`${a.sourceId}\0${a.referenceId}`;if(i.has(d))throw new ze({code:"DUPLICATE_REFERENCE",message:`Document ${a.sourceId} contains duplicate reference ID ${a.referenceId}`,documentIds:[a.sourceId]});i.add(d)}return Object.freeze({nodes:Object.freeze(n),edges:Object.freeze(s)})},qp=t=>new Map(t.nodes.map(e=>[e.id,e]));var lr=({graph:t,rootIds:e})=>{let n=qp(t),r=zt(t.edges),o=new Map,s=[],i=[],a=c=>{let u=n.get(c);if(u===void 0)throw new ze({code:"ROOT_NOT_FOUND",message:`Document graph root ${c} does not exist`,documentIds:[c]});let d=o.get(c);if(d!=="visited"){if(d==="visiting"){let l=s.indexOf(c),f=[...s.slice(l),c];throw new ze({code:"CYCLE",message:`Document graph contains a cycle: ${f.join(" -> ")}`,documentIds:f})}o.set(c,"visiting"),s.push(c);for(let l of r.get(c)??[])a(l.reference.documentId);s.pop(),o.set(c,"visited"),i.push(u)}};for(let c of[...new Set(e)].sort(Te))a(c);return Object.freeze(i)};var Kp=v().regex(/^sha256:[a-f0-9]{64}$/),Ku=C({format:F("webstudio-document-graph"),version:F(1),nodes:V(cr),edges:V(ur),integrity:C({algorithm:F("sha256"),checksum:Kp})});var Wp=v().min(1).refine(t=>t.startsWith("/")===!1,{error:"Asset path must be relative"}).refine(t=>t.includes("\\")===!1&&t.split("/").every(e=>e.length>0&&e!==".."&&e!=="."),{error:"Asset path must be normalized and must not contain dot segments"}),Hu=C({_id:v().min(1),_type:F("asset.file"),name:v().min(1),description:v().optional(),path:Wp,key:v(),folderId:v().min(1).optional(),extension:v().regex(/^[a-z0-9]*$/),mimeType:v().min(1),size:Z().int().nonnegative(),createdAt:v().datetime().optional(),revision:v().min(1),contentRef:v().min(1),properties:we(v(),nt()),excerpt:v().optional(),metadataError:C({code:v().min(1),message:v().min(1)}).optional()}),es=Hu.partial().required({_id:!0}),Yp=ae(["null","boolean","number","string","object","array"]),Hp=he({format:F("webstudio-builder-asset-field-catalog"),version:F(1),canonicalRevision:v().regex(/^sha256:[a-f0-9]{64}$/),documentCount:Z().int().nonnegative(),fields:we(v().min(1),he({queryPath:V(v().min(1)).min(1).max(R.fieldPathDepth).optional(),types:V(Yp).min(1),occurrences:Z().int().positive(),optional:F(!0).optional(),mixed:F(!0).optional()}))}).superRefine((t,e)=>{for(let[n,r]of Object.entries(t.fields)){let o=[...new Set(r.types)].sort();JSON.stringify(r.types)!==JSON.stringify(o)&&e.addIssue({code:"custom",path:["fields",n,"types"],message:"Observed field types must be unique and sorted"}),r.occurrences>t.documentCount&&e.addIssue({code:"custom",path:["fields",n,"occurrences"],message:"Field occurrences cannot exceed the document count"});let s=r.occurrences<t.documentCount;r.optional===!0!==s&&e.addIssue({code:"custom",path:["fields",n,"optional"],message:"Field optionality must match its occurrence count"});let i=o.length>1;r.mixed===!0!==i&&e.addIssue({code:"custom",path:["fields",n,"mixed"],message:"Mixed status must match the observed types"})}}),fr=v().regex(/^sha256:[a-f0-9]{64}$/),Xu=C({fields:V(V(v().min(1)).min(1).max(R.fieldPathDepth)).min(1).max(R.outputFieldCount+1),rows:V(V(nt())).max(R.resultCount),totalCount:Z().int().nonnegative().max(R.candidateDocuments),hasMore:tt()}).superRefine(({fields:t,rows:e},n)=>{for(let[r,o]of e.entries())o.length!==t.length&&n.addIssue({code:"custom",path:["rows",r],message:"Materialized query rows must match the field count"})}),Wu=C({format:F("webstudio-content-database"),version:F(1),assetRevision:fr,documents:V(es),documentGraph:Ku.optional(),contents:we(v().min(1),v()).optional(),assetReferences:we(v().min(1),V(C({start:Z().int().nonnegative(),end:Z().int().positive(),assetId:v().min(1),suffix:v().min(1).optional()}).refine(({start:t,end:e})=>e>t,{message:"Markdown asset reference range must not be empty"}))).optional(),assetValueReferences:we(v().min(1),V(C({path:V(v().min(1).or(Z().int().nonnegative())).min(1),assetId:v().min(1),suffix:v().min(1).optional(),structured:F(!0).optional()}))).optional(),fieldCatalog:Hp,queries:we(fr,Xu).optional(),database:C({maxBytes:Z().int().positive(),unboundedBytes:Z().int().nonnegative(),sourceDocumentCount:Z().int().nonnegative(),includedDocumentCount:Z().int().nonnegative().optional()}).optional(),integrity:C({algorithm:F("sha256"),checksum:fr})}).superRefine((t,e)=>{t.documents.length>R.candidateDocuments&&e.addIssue({code:"custom",path:["documents"],message:"Asset index exceeds the document limit"}),(t.fieldCatalog.canonicalRevision!==t.assetRevision||t.fieldCatalog.documentCount!==t.documents.length)&&e.addIssue({code:"custom",path:["fieldCatalog"],message:"Asset index field catalog does not match its documents"}),t.database!==void 0&&t.database.sourceDocumentCount<t.documents.length&&e.addIssue({code:"custom",path:["database","sourceDocumentCount"],message:"Source document count cannot be smaller than the database"}),t.database?.includedDocumentCount!==void 0&&(t.database.includedDocumentCount<t.documents.length||t.database.includedDocumentCount>t.database.sourceDocumentCount)&&e.addIssue({code:"custom",path:["database","includedDocumentCount"],message:"Included document count must match the database bounds"});let n;for(let[o,s]of t.documents.entries())n!==void 0&&s._id<=n&&e.addIssue({code:"custom",path:["documents",o,"_id"],message:"Asset index documents must have unique sorted IDs"}),n=s._id;let r=new Set(t.documents.flatMap(({contentRef:o})=>o===void 0?[]:[o]));for(let o of Object.keys(t.contents??{}))r.has(o)===!1&&e.addIssue({code:"custom",path:["contents",o],message:"Embedded content must belong to an indexed document"});for(let o of Object.keys(t.assetReferences??{}))r.has(o)===!1&&e.addIssue({code:"custom",path:["assetReferences",o],message:"Asset references must belong to an indexed document"})}),Xp=Ot("mode",[he({mode:F("none")}),he({mode:F("full"),maxBytes:Z().int().positive().max(R.hydratedFileBytes).optional()}),he({mode:F("range"),offset:Z().int().nonnegative(),length:Z().int().positive().max(R.hydratedRangeBytes)}),he({mode:F("markdown-body-ref"),maxBytes:Z().int().positive().max(R.hydratedFileBytes).optional()})]),ts={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"]},el=Object.keys(ts),tl=["url","width","height"],dr=t=>tl.includes(t),nl=el.filter(t=>dr(t)===!1&&t!=="excerpt"),rl=nl.filter(t=>t!=="id"),ol=t=>nl.includes(t),em=ae(el),wn=V(v().min(1)).min(1).max(R.fieldPathDepth).superRefine((t,e)=>{if(t[0]==="properties"){t.length<2&&e.addIssue({code:"custom",message:"A properties field path must select a property"});return}(t.length!==1||em.safeParse(t[0]).success===!1)&&e.addIssue({code:"custom",message:"Asset query field path is unsupported"})}),Xo=tt().default(!0),tm=Ot("mode",[C({mode:F("all"),includeMetadata:Xo}),C({mode:F("base"),includeMetadata:Xo}),C({mode:F("fields"),includeMetadata:Xo,fields:V(wn).max(R.outputFieldCount).refine(t=>new Set(t.map(Uu)).size===t.length,{error:"Selected output fields must be unique"})})]),nm={mode:"fields",includeMetadata:!1,fields:tl.map(t=>[t])},sl=["eq","ne","contains","startsWith","endsWith","gt","gte","lt","lte"],Sb=[...sl,"in","exists","isEmpty"],rm=C({field:wn,operator:ae(sl),value:nt()}),om=C({field:wn,operator:F("in"),value:V(nt()).max(R.resultCount)}),sm=C({field:wn,operator:ae(["exists","isEmpty"]),value:tt()}),im=Ot("operator",[rm,om,sm]),am=Qu(im,{maximumChildren:R.filterCount,maximumConditions:R.filterCount,maximumDepth:R.filterDepth,maximumConditionsMessage:"Asset query exceeds the filter limit",maximumDepthMessage:"Asset query exceeds the filter nesting limit"});var cm=am,il=t=>{let e=new Set(["eq","ne","in","exists"]);return t.some(n=>n==="string"||n==="array")&&e.add("contains"),t.includes("string")&&(e.add("startsWith"),e.add("endsWith")),t.some(n=>n==="string"||n==="number")&&(e.add("gt"),e.add("gte"),e.add("lt"),e.add("lte")),t.some(n=>n==="string"||n==="array"||n==="object")&&e.add("isEmpty"),[...e]},um=C({field:wn,direction:ae(["asc","desc"])}),lm=ae(["many","one","first","last"]),fm=({output:t,content:e})=>t.includeMetadata||t.mode==="all"||t.mode==="fields"&&t.fields.length>0||e.mode!=="none",ot=C({result:lm.default("many"),where:cm.default({all:[]}),sort:V(um).max(R.sortCount).default([]),limit:Z().int().nonnegative().max(R.resultCount).default(R.defaultResultCount),offset:Z().int().nonnegative().max(R.candidateDocuments).default(0),output:tm.default(nm),content:Xp.default({mode:"none"})}).superRefine((t,e)=>{fm(t)===!1&&e.addIssue({code:"custom",message:"Select at least one asset query output"}),(t.result==="first"||t.result==="last")&&t.sort.length===0&&e.addIssue({code:"custom",path:["sort"],message:"Add sorting to define which item is first."})}),al=C({query:ot,indexRevision:v().min(1).max(255).optional()}),dm=he({_id:v().min(1),revision:v().min(1),contentRef:v().min(1),encoding:F("utf-8"),text:v(),range:he({offset:Z().int().nonnegative(),length:Z().int().nonnegative(),total:Z().int().nonnegative()}).optional()}),pm=dm.omit({_id:!0,revision:!0,contentRef:!0}),cl=Hu.omit({_id:!0,_type:!0,contentRef:!0}).partial().extend({id:v().min(1),url:v().min(1).optional(),width:Z().positive().optional(),height:Z().positive().optional(),content:pm.optional()}).refine(t=>t.width===void 0==(t.height===void 0),{error:"Asset dimensions must include both width and height"}),mm=C({format:F("webstudio-content-database"),version:F(1),revision:fr,usedBytes:Z().int().nonnegative(),maxBytes:Z().int().positive(),unboundedBytes:Z().int().nonnegative(),includedDocumentCount:Z().int().nonnegative(),omittedDocumentCount:Z().int().nonnegative(),omissionReason:ae(["size","unavailable"]).optional(),truncated:tt()}),Yu=mm.pick({usedBytes:!0,maxBytes:!0,unboundedBytes:!0,includedDocumentCount:!0,omittedDocumentCount:!0,omissionReason:!0,truncated:!0}),ns=C({items:V(cl),totalCount:Z().int().nonnegative(),hasMore:tt()}),hm=C({item:cl.nullable(),totalCount:Z().int().nonnegative()}),ul=It([ns,hm]),ym=C({scope:F("query-preview"),query:Yu,database:Yu,artifacts:C({query:Wu,database:Wu}).optional(),unresolved:ul.optional()}),Ab=C({data:ul,__diagnostics__:ym}),gm=ae(["INVALID_REQUEST","REQUEST_CANCELLED","UNAUTHORIZED","FORBIDDEN","STALE_INDEX","CONTENT_IDENTITY_REQUIRED","CONTENT_NOT_TEXT","CONTENT_DECODING_FAILED","CONTENT_LIMIT_EXCEEDED","MULTIPLE_RESULTS","INTERNAL_ERROR"]),bm=he({ok:F(!1),error:he({code:gm,message:v().min(1),retryable:tt(),details:we(v(),nt()).optional()}),meta:he({queryHash:v().min(1).optional(),indexRevision:v().min(1).optional(),assetRevision:v().min(1).optional()}).optional()}),ll=({code:t,message:e,retryable:n=!1,details:r})=>bm.parse({ok:!1,error:{code:t,message:e,retryable:n,details:r}});var fl=function*(t){if(t.length>0&&!t.startsWith("/")||/~(?![01])/.test(t))throw Error("Invalid JSON Pointer");let e=1,n=0;for(;n<t.length;){let r=t.indexOf("/",e);n=r===-1?t.length:r;let o=t.slice(e,n);e=n+1,yield _m(o)}};var rs=(t,e)=>e+"/"+wm(t),wm=t=>t.toString().replace(/~/g,"~0").replace(/\//g,"~1"),_m=t=>t.toString().replace(/~1/g,"/").replace(/~0/g,"~");var pr=async(t,e,n)=>{if(Number.isSafeInteger(e)===!1||e<=0)throw new Error("Concurrency must be a positive safe integer");let r=0,o=new Array(t.length),s=async()=>{for(;r<t.length;){let u=r;r+=1,o[u]=await n(t[u])}},i=Array.from({length:Math.min(e,t.length)},s),c=(await Promise.allSettled(i)).find(u=>u.status==="rejected");if(c!==void 0)throw c.reason;return o};var Pt=t=>typeof t=="object"&&t!==null&&Array.isArray(t)===!1,mr=t=>{if(Pt(t)===!1)return;let e=Object.keys(t);if(!(e.length!==1||e[0]!=="$ref"))return t.$ref};var de=class extends Error{code;referenceId;constructor({code:e,message:n,referenceId:r,cause:o}){super(n,{cause:o}),this.name="JsonDocumentError",this.code=e,this.referenceId=r}},xm=(t,e)=>{let n=mr(t);if(n!==void 0){if(typeof n!="string")throw new de({code:"INVALID_REFERENCE_MARKER",message:`JSON reference marker ${e} must contain a string $ref`,referenceId:e});return n}},Sm=t=>`#${t}`;var dl=async({source:t,maximumBytes:e=R.hydratedFileBytes})=>{let n;try{n=await $e(t,e)}catch(o){throw o instanceof re?new de({code:"CONTENT_LIMIT_EXCEEDED",message:"JSON document exceeds the byte limit",cause:o}):o}let r;try{r=Tt(le(n))}catch(o){throw new de({code:"CONTENT_DECODING_FAILED",message:"JSON document is not valid UTF-8",cause:o})}try{return rt(JSON.parse(r))}catch(o){throw new de({code:"INVALID_DOCUMENT",message:"JSON document is invalid",cause:o})}};var Am=(t,e)=>{let n=t;for(let r of e){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(Pt(n)&&Object.hasOwn(n,r)){n=n[r];continue}return}return n},pl=({document:t,representation:e})=>{let n=rt(t);if(e.type==="document")return n;if(e.type!=="json")throw new de({code:"UNSUPPORTED_REPRESENTATION",message:`JSON documents do not support ${e.type}`});let r=Am(n,e.path);if(r===void 0)throw new de({code:"JSON_PATH_NOT_FOUND",message:"JSON document path does not exist"});return r},Em=(t,e,n)=>{Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0})},hr=({document:t,references:e,allowUnresolvedReferences:n=!1})=>{let r=rt(t),o=new Set,s=(a,c)=>{let u=Sm(c);if(xm(a,u)!==void 0){if(e.has(u)===!1){if(n)return a;throw new de({code:"REFERENCE_NOT_FOUND",message:`Resolved JSON reference ${u} is unavailable`,referenceId:u})}o.add(u);try{return rt(e.get(u))}catch(l){throw new de({code:"INVALID_RESOLVED_VALUE",message:`Resolved JSON reference ${u} is not JSON-compatible`,referenceId:u,cause:l})}}if(Array.isArray(a))return a.map((l,f)=>s(l,rs(String(f),c)));if(Pt(a)){let l={};for(let[f,p]of Object.entries(a))Em(l,f,s(p,rs(f,c)));return l}return a},i=s(r,"");for(let a of[...e.keys()].sort())if(o.has(a)===!1)throw new de({code:"UNUSED_REFERENCE",message:`Resolved JSON reference ${a} has no marker`,referenceId:a});return i};var yr=Symbol.for("yaml.alias"),gr=Symbol.for("yaml.document"),_e=Symbol.for("yaml.map"),os=Symbol.for("yaml.pair"),pe=Symbol.for("yaml.scalar"),Ge=Symbol.for("yaml.seq"),oe=Symbol.for("yaml.node.type"),xe=t=>!!t&&typeof t=="object"&&t[oe]===yr,Pe=t=>!!t&&typeof t=="object"&&t[oe]===gr,Se=t=>!!t&&typeof t=="object"&&t[oe]===_e,$=t=>!!t&&typeof t=="object"&&t[oe]===os,N=t=>!!t&&typeof t=="object"&&t[oe]===pe,Ae=t=>!!t&&typeof t=="object"&&t[oe]===Ge;function B(t){if(t&&typeof t=="object")switch(t[oe]){case _e:case Ge:return!0}return!1}function L(t){if(t&&typeof t=="object")switch(t[oe]){case yr:case _e:case pe:case Ge:return!0}return!1}var br=t=>(N(t)||B(t))&&!!t.anchor;var ce=Symbol("break visit"),ml=Symbol("skip children"),Le=Symbol("remove node");function Me(t,e){let n=hl(e);Pe(t)?Lt(null,t.contents,n,Object.freeze([t]))===Le&&(t.contents=null):Lt(null,t,n,Object.freeze([]))}Me.BREAK=ce;Me.SKIP=ml;Me.REMOVE=Le;function Lt(t,e,n,r){let o=yl(t,e,n,r);if(L(o)||$(o))return gl(t,r,o),Lt(t,o,n,r);if(typeof o!="symbol"){if(B(e)){r=Object.freeze(r.concat(e));for(let s=0;s<e.items.length;++s){let i=Lt(s,e.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===ce)return ce;i===Le&&(e.items.splice(s,1),s-=1)}}}else if($(e)){r=Object.freeze(r.concat(e));let s=Lt("key",e.key,n,r);if(s===ce)return ce;s===Le&&(e.key=null);let i=Lt("value",e.value,n,r);if(i===ce)return ce;i===Le&&(e.value=null)}}return o}async function wr(t,e){let n=hl(e);Pe(t)?await Mt(null,t.contents,n,Object.freeze([t]))===Le&&(t.contents=null):await Mt(null,t,n,Object.freeze([]))}wr.BREAK=ce;wr.SKIP=ml;wr.REMOVE=Le;async function Mt(t,e,n,r){let o=await yl(t,e,n,r);if(L(o)||$(o))return gl(t,r,o),Mt(t,o,n,r);if(typeof o!="symbol"){if(B(e)){r=Object.freeze(r.concat(e));for(let s=0;s<e.items.length;++s){let i=await Mt(s,e.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===ce)return ce;i===Le&&(e.items.splice(s,1),s-=1)}}}else if($(e)){r=Object.freeze(r.concat(e));let s=await Mt("key",e.key,n,r);if(s===ce)return ce;s===Le&&(e.key=null);let i=await Mt("value",e.value,n,r);if(i===ce)return ce;i===Le&&(e.value=null)}}return o}function hl(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function yl(t,e,n,r){if(typeof n=="function")return n(t,e,r);if(Se(e))return n.Map?.(t,e,r);if(Ae(e))return n.Seq?.(t,e,r);if($(e))return n.Pair?.(t,e,r);if(N(e))return n.Scalar?.(t,e,r);if(xe(e))return n.Alias?.(t,e,r)}function gl(t,e,n){let r=e[e.length-1];if(B(r))r.items[t]=n;else if($(r))t==="key"?r.key=n:r.value=n;else if(Pe(r))r.contents=n;else{let o=xe(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}var vm={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},km=t=>t.replace(/[!,[\]{}]/g,e=>vm[e]),Fe=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let r=e.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(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let i=e.slice(2,-1);return i==="!"||i==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),i)}let[,r,o]=e.match(/^(.*!)([^!]*)$/s);o||n(`The ${e} 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==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,r]of Object.entries(this.tags))if(e.startsWith(r))return n+km(e.substring(r.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),o;if(e&&r.length>0&&L(e.contents)){let s={};Me(e.contents,(i,a)=>{L(a)&&a.tag&&(s[a.tag]=!0)}),o=Object.keys(s)}else o=[];for(let[s,i]of r)s==="!!"&&i==="tag:yaml.org,2002:"||(!e||o.some(a=>a.startsWith(i)))&&n.push(`%TAG ${s} ${i}`);return n.join(`-`)}};Fe.defaultYaml={explicit:!1,version:"1.2"};Fe.defaultTags={"!!":"tag:yaml.org,2002:"};function _r(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function ss(t){let e=new Set;return Me(t,{Value(n,r){r.anchor&&e.add(r.anchor)}}),e}function is(t,e){for(let n=1;;++n){let r=`${t}${n}`;if(!e.has(r))return r}}function bl(t,e){let n=[],r=new Map,o=null;return{onAnchor:s=>{n.push(s),o??(o=ss(t));let i=is(e,o);return o.add(i),i},setAnchors:()=>{for(let s of n){let i=r.get(s);if(typeof i=="object"&&i.anchor&&(N(i.node)||B(i.node)))i.node.anchor=i.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:r}}function st(t,e,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],a=st(t,r,String(o),i);a===void 0?delete r[o]:a!==i&&(r[o]=a)}else if(r instanceof Map)for(let o of Array.from(r.keys())){let s=r.get(o),i=st(t,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=st(t,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=st(t,r,o,s);i===void 0?delete r[o]:i!==s&&(r[o]=i)}return t.call(e,n,r)}function Y(t,e,n){if(Array.isArray(t))return t.map((r,o)=>Y(r,String(o),n));if(t&&typeof t.toJSON=="function"){if(!n||!br(t))return t.toJSON(e,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(t,r),n.onCreate=s=>{r.res=s,delete n.onCreate};let o=t.toJSON(e,n);return n.onCreate&&n.onCreate(o),o}return typeof t=="bigint"&&!n?.keep?Number(t):t}var it=class{constructor(e){Object.defineProperty(this,oe,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:r,onAnchor:o,reviver:s}={}){if(!Pe(e))throw new TypeError("A document argument is required");let i={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=Y(this,"",i);if(typeof o=="function")for(let{count:c,res:u}of i.anchors.values())o(u,c);return typeof s=="function"?st(s,{"":a},"",a):a}};var Je=class extends it{constructor(e){super(yr),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],Me(e,{Node:(s,i)=>{(xe(i)||br(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(e,n){if(!n)return{source:this.source};let{anchors:r,doc:o,maxAliasCount:s}=n,i=this.resolve(o,n);if(!i){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=r.get(i);if(a||(Y(i,null,n),a=r.get(i)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=xr(o,i,r)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,n,r){let o=`*${this.source}`;if(e){if(_r(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${o} `}return o}};function xr(t,e,n){if(xe(e)){let r=e.resolve(t),o=n&&r&&n.get(r);return o?o.count*o.aliasCount:0}else if(B(e)){let r=0;for(let o of e.items){let s=xr(t,o,n);s>r&&(r=s)}return r}else if($(e)){let r=xr(t,e.key,n),o=xr(t,e.value,n);return Math.max(r,o)}return 1}var Sr=t=>!t||typeof t!="function"&&typeof t!="object",D=class extends it{constructor(e){super(pe),this.value=e}toJSON(e,n){return n?.keep?this.value:Y(this.value,e,n)}toString(){return String(this.value)}};D.BLOCK_FOLDED="BLOCK_FOLDED";D.BLOCK_LITERAL="BLOCK_LITERAL";D.PLAIN="PLAIN";D.QUOTE_DOUBLE="QUOTE_DOUBLE";D.QUOTE_SINGLE="QUOTE_SINGLE";var Dm="tag:yaml.org,2002:";function Rm(t,e,n){if(e){let r=n.filter(s=>s.tag===e),o=r.find(s=>!s.format)??r[0];if(!o)throw new Error(`Tag ${e} not found`);return o}return n.find(r=>r.identify?.(t)&&!r.format)}function qe(t,e,n){if(Pe(t)&&(t=t.contents),L(t))return t;if($(t)){let l=n.schema[_e].createNode?.(n.schema,null,n);return l.items.push(t),l}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:r,onAnchor:o,onTagObj:s,schema:i,sourceObjects:a}=n,c;if(r&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=o(t)),new Je(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=Dm+e.slice(2));let u=Rm(t,e,i.tags);if(!u){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let l=new D(t);return c&&(c.node=l),l}u=t instanceof Map?i[_e]:Symbol.iterator in Object(t)?i[Ge]:i[_e]}s&&(s(u),delete n.onTagObj);let d=u?.createNode?u.createNode(n.schema,t,n):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(n.schema,t,n):new D(t);return e?d.tag=e:u.default||(d.tag=u.tag),c&&(c.node=d),d}function _n(t,e,n){let r=n;for(let o=e.length-1;o>=0;--o){let s=e[o];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let i=[];i[s]=r,r=i}else r=new Map([[s,r]])}return qe(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Zt=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Ft=class extends it{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(r=>L(r)||$(r)?r.clone(e):r),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(Zt(e))this.add(n);else{let[r,...o]=e,s=this.get(r,!0);if(B(s))s.addIn(o,n);else if(s===void 0&&this.schema)this.set(r,_n(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}deleteIn(e){let[n,...r]=e;if(r.length===0)return this.delete(n);let o=this.get(n,!0);if(B(o))return o.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(e,n){let[r,...o]=e,s=this.get(r,!0);return o.length===0?!n&&N(s)?s.value:s:B(s)?s.getIn(o,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!$(n))return!1;let r=n.value;return r==null||e&&N(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[n,...r]=e;if(r.length===0)return this.has(n);let o=this.get(n,!0);return B(o)?o.hasIn(r):!1}setIn(e,n){let[r,...o]=e;if(o.length===0)this.set(r,n);else{let s=this.get(r,!0);if(B(s))s.setIn(o,n);else if(s===void 0&&this.schema)this.set(r,_n(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}};var wl=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function ye(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Ze=(t,e,n)=>t.endsWith(`+Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of t.seen.entries()){let a=i[1];if(e===i[0]){s(i);continue}if(t.external){let u=t.external.registry.get(i[0])?.id;if(e!==i[0]&&u){s(i);continue}}if(t.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&t.reused==="ref"){s(i);continue}}}function Jo(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,p={...u},l=c.ref;if(c.ref=null,l){r(l);let d=t.seen.get(l),y=d.schema;if(y.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(y)):Object.assign(u,y),Object.assign(u,p),a._zod.parent===l)for(let h in u)h==="$ref"||h==="allOf"||h in p||delete u[h];if(y.$ref&&d.def)for(let h in u)h==="$ref"||h==="allOf"||h in d.def&&JSON.stringify(u[h])===JSON.stringify(d.def[h])&&delete u[h]}let f=a._zod.parent;if(f&&f!==l){r(f);let d=t.seen.get(f);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]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())r(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,n.def??n.schema);let s=t.metadataRegistry.get(e)?.id;s!==void 0&&o.id===s&&delete o.id;let i=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:hn(e,"input",t.processors),output:hn(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function ne(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let r=t._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return ne(r.element,n);if(r.type==="set")return ne(r.valueType,n);if(r.type==="lazy")return ne(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 ne(r.innerType,n);if(r.type==="intersection")return ne(r.left,n)||ne(r.right,n);if(r.type==="record"||r.type==="map")return ne(r.keyType,n)||ne(r.valueType,n);if(r.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:ne(r.in,n)||ne(r.out,n);if(r.type==="object"){for(let o in r.shape)if(ne(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(ne(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(ne(o,n))return!0;return!!(r.rest&&ne(r.rest,n))}return!1}var Vc=(t,e={})=>n=>{let r=Vo({...n,processors:e});return q(t,r),Go(r,t),Jo(r,t)},hn=(t,e,n={})=>r=>{let{libraryOptions:o,target:s}=r??{},i=Vo({...o??{},target:s,io:e,processors:n});return q(t,i),Go(i,t),Jo(i,t)};var jd={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Gc=(t,e,n,r)=>{let o=n;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=jd[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),u&&(o.contentEncoding=u),c&&c.size>0){let p=[...c];p.length===1?o.pattern=p[0].source:p.length>1&&(o.allOf=[...p.map(l=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:l.source}))])}},Jc=(t,e,n,r)=>{let o=n,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:p}=t._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";let l=typeof p=="number"&&p>=(s??Number.NEGATIVE_INFINITY),f=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),d=e.target==="draft-04"||e.target==="openapi-3.0";l?d?(o.minimum=p,o.exclusiveMinimum=!0):o.exclusiveMinimum=p:typeof s=="number"&&(o.minimum=s),f?d?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof c=="number"&&(o.multipleOf=c)},qc=(t,e,n,r)=>{n.type="boolean"};var Kc=(t,e,n,r)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"};var Wc=(t,e,n,r)=>{n.not={}};var Yc=(t,e,n,r)=>{};var Hc=(t,e,n,r)=>{let o=t._zod.def,s=sn(o.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},Xc=(t,e,n,r)=>{let o=t._zod.def,s=[];for(let i of o.values)if(i===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(e.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,e.target==="draft-04"||e.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 eu=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var tu=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var nu=(t,e,n,r)=>{let o=n,s=t._zod.def,{minimum:i,maximum:a}=t._zod.bag;typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=q(s.element,e,{...r,path:[...r.path,"items"]})},ru=(t,e,n,r)=>{let o=n,s=t._zod.def;o.type="object",o.properties={};let i=s.shape;for(let u in i)o.properties[u]=q(i[u],e,{...r,path:[...r.path,"properties",u]});let a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{let p=s.shape[u]._zod;return e.io==="input"?p.optin===void 0:p.optout===void 0}));c.size>0&&(o.required=Array.from(c)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=q(s.catchall,e,{...r,path:[...r.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},ou=(t,e,n,r)=>{let o=t._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>q(a,e,{...r,path:[...r.path,s?"oneOf":"anyOf",c]}));s?n.oneOf=i:n.anyOf=i},su=(t,e,n,r)=>{let o=t._zod.def,s=q(o.left,e,{...r,path:[...r.path,"allOf",0]}),i=q(o.right,e,{...r,path:[...r.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];n.allOf=c};var iu=(t,e,n,r)=>{let o=n,s=t._zod.def;o.type="object";let i=s.keyType,c=i._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let p=q(s.valueType,e,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let l of c)o.patternProperties[l.source]=p}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(o.propertyNames=q(s.keyType,e,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=q(s.valueType,e,{...r,path:[...r.path,"additionalProperties"]});let u=i._zod.values;if(u){let p=[...u].filter(l=>typeof l=="string"||typeof l=="number");p.length>0&&(o.required=p)}},au=(t,e,n,r)=>{let o=t._zod.def,s=q(o.innerType,e,r),i=e.seen.get(t);e.target==="openapi-3.0"?(i.ref=o.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},cu=(t,e,n,r)=>{let o=t._zod.def;q(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType},uu=(t,e,n,r)=>{let o=t._zod.def;q(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},lu=(t,e,n,r)=>{let o=t._zod.def;q(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},fu=(t,e,n,r)=>{let o=t._zod.def;q(o.innerType,e,r);let s=e.seen.get(t);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},du=(t,e,n,r)=>{let o=t._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=e.io==="input"?s?o.out:o.in:o.out;q(i,e,r);let a=e.seen.get(t);a.ref=i},pu=(t,e,n,r)=>{let o=t._zod.def;q(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType,n.readOnly=!0};var qo=(t,e,n,r)=>{let o=t._zod.def;q(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType},mu=(t,e,n,r)=>{let o=t._zod.innerType;q(o,e,r);let s=e.seen.get(t);s.ref=o};var Kd=g("ZodISODateTime",(t,e)=>{va.init(t,e),J.init(t,e)});function hu(t){return Nc(Kd,t)}var Wd=g("ZodISODate",(t,e)=>{Da.init(t,e),J.init(t,e)});function yu(t){return Tc(Wd,t)}var Yd=g("ZodISOTime",(t,e)=>{Ra.init(t,e),J.init(t,e)});function gu(t){return $c(Yd,t)}var Hd=g("ZodISODuration",(t,e)=>{ka.init(t,e),J.init(t,e)});function bu(t){return zc(Hd,t)}var tp=(t,e)=>{qn.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>ii(t,n)},flatten:{value:n=>si(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,Dt,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,Dt,2)}},isEmpty:{get(){return t.issues.length===0}}})};var ue=g("ZodError",tp,{Parent:Error});var wu=Kn(ue),_u=Wn(ue),xu=ln(ue),Su=fn(ue),Au=ui(ue),Eu=li(ue),vu=fi(ue),Du=di(ue),Ru=pi(ue),ku=mi(ue),Iu=hi(ue),Ou=yi(ue);var Cu=new WeakMap;function yn(t,e,n){let r=Object.getPrototypeOf(t),o=Cu.get(r);if(o||(o=new Set,Cu.set(r,o)),!o.has(e)){o.add(e);for(let s in n){let i=n[s];Object.defineProperty(r,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var Q=g("ZodType",(t,e)=>(j.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:hn(t,"input"),output:hn(t,"output")}}),t.toJSONSchema=Vc(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,r)=>wu(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>xu(t,n,r),t.parseAsync=async(n,r)=>_u(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Su(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>Au(t,n,r),t.decode=(n,r)=>Eu(t,n,r),t.encodeAsync=async(n,r)=>vu(t,n,r),t.decodeAsync=async(n,r)=>Du(t,n,r),t.safeEncode=(n,r)=>Ru(t,n,r),t.safeDecode=(n,r)=>ku(t,n,r),t.safeEncodeAsync=async(n,r)=>Iu(t,n,r),t.safeDecodeAsync=async(n,r)=>Ou(t,n,r),yn(t,"ZodType",{check(...n){let r=this.def;return this.clone(M.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 be(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Kp(n,r))},superRefine(n,r){return this.check(Wp(n,r))},overwrite(n){return this.check(et(n))},optional(){return Pu(this)},exactOptional(){return zp(this)},nullable(){return Lu(this)},nullish(){return Pu(Lu(this))},nonoptional(n){return Bp(this,n)},array(){return V(this)},or(n){return Ot([this,n])},and(n){return Op(this,n)},transform(n){return Mu(this,Tp(n))},default(n){return Mp(this,n)},prefault(n){return Zp(this,n)},catch(n){return Up(this,n)},pipe(n){return Mu(this,n)},readonly(){return Gp(this)},describe(n){let r=this.clone();return bt.add(r,{description:n}),r},meta(...n){if(n.length===0)return bt.get(this);let r=this.clone();return bt.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(t,"description",{get(){return bt.get(t)?.description},configurable:!0}),t)),Fu=g("_ZodString",(t,e)=>{tr.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(r,o,s)=>Gc(t,r,o,s);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,yn(t,"_ZodString",{regex(...r){return this.check($o(...r))},includes(...r){return this.check(Lo(...r))},startsWith(...r){return this.check(Mo(...r))},endsWith(...r){return this.check(Fo(...r))},min(...r){return this.check(It(...r))},max(...r){return this.check(sr(...r))},length(...r){return this.check(ir(...r))},nonempty(...r){return this.check(It(1,...r))},lowercase(r){return this.check(zo(r))},uppercase(r){return this.check(Po(r))},trim(){return this.check(Bo())},normalize(...r){return this.check(Zo(...r))},toLowerCase(){return this.check(jo())},toUpperCase(){return this.check(Uo())},slugify(){return this.check(Qo())}})}),rp=g("ZodString",(t,e)=>{tr.init(t,e),Fu.init(t,e),t.email=n=>t.check(fc(op,n)),t.url=n=>t.check(yc(sp,n)),t.jwt=n=>t.check(Cc(_p,n)),t.emoji=n=>t.check(gc(ip,n)),t.guid=n=>t.check(To(Nu,n)),t.uuid=n=>t.check(dc(cr,n)),t.uuidv4=n=>t.check(pc(cr,n)),t.uuidv6=n=>t.check(mc(cr,n)),t.uuidv7=n=>t.check(hc(cr,n)),t.nanoid=n=>t.check(bc(ap,n)),t.guid=n=>t.check(To(Nu,n)),t.cuid=n=>t.check(wc(cp,n)),t.cuid2=n=>t.check(_c(up,n)),t.ulid=n=>t.check(xc(lp,n)),t.base64=n=>t.check(kc(gp,n)),t.base64url=n=>t.check(Ic(bp,n)),t.xid=n=>t.check(Sc(fp,n)),t.ksuid=n=>t.check(Ac(dp,n)),t.ipv4=n=>t.check(Ec(pp,n)),t.ipv6=n=>t.check(vc(mp,n)),t.cidrv4=n=>t.check(Dc(hp,n)),t.cidrv6=n=>t.check(Rc(yp,n)),t.e164=n=>t.check(Oc(wp,n)),t.datetime=n=>t.check(hu(n)),t.date=n=>t.check(yu(n)),t.time=n=>t.check(gu(n)),t.duration=n=>t.check(bu(n))});function v(t){return lc(rp,t)}var J=g("ZodStringFormat",(t,e)=>{U.init(t,e),Fu.init(t,e)}),op=g("ZodEmail",(t,e)=>{ya.init(t,e),J.init(t,e)});var Nu=g("ZodGUID",(t,e)=>{ma.init(t,e),J.init(t,e)});var cr=g("ZodUUID",(t,e)=>{ha.init(t,e),J.init(t,e)});var sp=g("ZodURL",(t,e)=>{ga.init(t,e),J.init(t,e)});var ip=g("ZodEmoji",(t,e)=>{ba.init(t,e),J.init(t,e)});var ap=g("ZodNanoID",(t,e)=>{wa.init(t,e),J.init(t,e)});var cp=g("ZodCUID",(t,e)=>{_a.init(t,e),J.init(t,e)});var up=g("ZodCUID2",(t,e)=>{xa.init(t,e),J.init(t,e)});var lp=g("ZodULID",(t,e)=>{Sa.init(t,e),J.init(t,e)});var fp=g("ZodXID",(t,e)=>{Aa.init(t,e),J.init(t,e)});var dp=g("ZodKSUID",(t,e)=>{Ea.init(t,e),J.init(t,e)});var pp=g("ZodIPv4",(t,e)=>{Ia.init(t,e),J.init(t,e)});var mp=g("ZodIPv6",(t,e)=>{Oa.init(t,e),J.init(t,e)});var hp=g("ZodCIDRv4",(t,e)=>{Ca.init(t,e),J.init(t,e)});var yp=g("ZodCIDRv6",(t,e)=>{Na.init(t,e),J.init(t,e)});var gp=g("ZodBase64",(t,e)=>{$a.init(t,e),J.init(t,e)});var bp=g("ZodBase64URL",(t,e)=>{za.init(t,e),J.init(t,e)});var wp=g("ZodE164",(t,e)=>{Pa.init(t,e),J.init(t,e)});var _p=g("ZodJWT",(t,e)=>{La.init(t,e),J.init(t,e)});var Zu=g("ZodNumber",(t,e)=>{Io.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(r,o,s)=>Jc(t,r,o,s),yn(t,"ZodNumber",{gt(r,o){return this.check(rr(r,o))},gte(r,o){return this.check(mn(r,o))},min(r,o){return this.check(mn(r,o))},lt(r,o){return this.check(nr(r,o))},lte(r,o){return this.check(pn(r,o))},max(r,o){return this.check(pn(r,o))},int(r){return this.check(Tu(r))},safe(r){return this.check(Tu(r))},positive(r){return this.check(rr(0,r))},nonnegative(r){return this.check(mn(0,r))},negative(r){return this.check(nr(0,r))},nonpositive(r){return this.check(pn(0,r))},multipleOf(r,o){return this.check(or(r,o))},step(r,o){return this.check(or(r,o))},finite(){return this}});let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function Z(t){return Pc(Zu,t)}var xp=g("ZodNumberFormat",(t,e)=>{Ma.init(t,e),Zu.init(t,e)});function Tu(t){return Lc(xp,t)}var Sp=g("ZodBoolean",(t,e)=>{Fa.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>qc(t,n,r,o)});function tt(t){return Mc(Sp,t)}var Ap=g("ZodNull",(t,e)=>{Za.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Kc(t,n,r,o)});function Ep(t){return Fc(Ap,t)}var vp=g("ZodUnknown",(t,e)=>{Ba.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Yc(t,n,r,o)});function $u(){return Zc(vp)}var Dp=g("ZodNever",(t,e)=>{ja.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Wc(t,n,r,o)});function Bu(t){return Bc(Dp,t)}var Rp=g("ZodArray",(t,e)=>{Ua.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>nu(t,n,r,o),t.element=e.element,yn(t,"ZodArray",{min(n,r){return this.check(It(n,r))},nonempty(n){return this.check(It(1,n))},max(n,r){return this.check(sr(n,r))},length(n,r){return this.check(ir(n,r))},unwrap(){return this.element}})});function V(t,e){return jc(Rp,t,e)}var ju=g("ZodObject",(t,e)=>{Ga.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ru(t,n,r,o),M.defineLazy(t,"shape",()=>e.shape),yn(t,"ZodObject",{keyof(){return ae(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:$u()})},loose(){return this.clone({...this._zod.def,catchall:$u()})},strict(){return this.clone({...this._zod.def,catchall:Bu()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return M.extend(this,n)},safeExtend(n){return M.safeExtend(this,n)},merge(n){return M.merge(this,n)},pick(n){return M.pick(this,n)},omit(n){return M.omit(this,n)},partial(...n){return M.partial(Qu,this,n[0])},required(...n){return M.required(Vu,this,n[0])}})});function he(t,e){let n={type:"object",shape:t??{},...M.normalizeParams(e)};return new ju(n)}function C(t,e){return new ju({type:"object",shape:t,catchall:Bu(),...M.normalizeParams(e)})}var Uu=g("ZodUnion",(t,e)=>{Oo.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ou(t,n,r,o),t.options=e.options});function Ot(t,e){return new Uu({type:"union",options:t,...M.normalizeParams(e)})}var kp=g("ZodDiscriminatedUnion",(t,e)=>{Uu.init(t,e),Ja.init(t,e)});function Ct(t,e,n){return new kp({type:"union",options:e,discriminator:t,...M.normalizeParams(n)})}var Ip=g("ZodIntersection",(t,e)=>{qa.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>su(t,n,r,o)});function Op(t,e){return new Ip({type:"intersection",left:t,right:e})}var zu=g("ZodRecord",(t,e)=>{Ka.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>iu(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType});function we(t,e,n){return!e||!e._zod?new zu({type:"record",keyType:v(),valueType:t,...M.normalizeParams(e)}):new zu({type:"record",keyType:t,valueType:e,...M.normalizeParams(n)})}var Ko=g("ZodEnum",(t,e)=>{Wa.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(r,o,s)=>Hc(t,r,o,s),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Ko({...e,checks:[],...M.normalizeParams(o),entries:s})},t.exclude=(r,o)=>{let s={...e.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 Ko({...e,checks:[],...M.normalizeParams(o),entries:s})}});function ae(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new Ko({type:"enum",entries:n,...M.normalizeParams(e)})}var Cp=g("ZodLiteral",(t,e)=>{Ya.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Xc(t,n,r,o),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function F(t,e){return new Cp({type:"literal",values:Array.isArray(t)?t:[t],...M.normalizeParams(e)})}var Np=g("ZodTransform",(t,e)=>{Ha.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>tu(t,n,r,o),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Et(t.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(M.issue(s,n.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),n.issues.push(M.issue(i))}};let o=e.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 Tp(t){return new Np({type:"transform",transform:t})}var Qu=g("ZodOptional",(t,e)=>{Co.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>qo(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Pu(t){return new Qu({type:"optional",innerType:t})}var $p=g("ZodExactOptional",(t,e)=>{Xa.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>qo(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function zp(t){return new $p({type:"optional",innerType:t})}var Pp=g("ZodNullable",(t,e)=>{ec.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>au(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Lu(t){return new Pp({type:"nullable",innerType:t})}var Lp=g("ZodDefault",(t,e)=>{tc.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>uu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Mp(t,e){return new Lp({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():M.shallowClone(e)}})}var Fp=g("ZodPrefault",(t,e)=>{nc.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>lu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Zp(t,e){return new Fp({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():M.shallowClone(e)}})}var Vu=g("ZodNonOptional",(t,e)=>{rc.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>cu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Bp(t,e){return new Vu({type:"nonoptional",innerType:t,...M.normalizeParams(e)})}var jp=g("ZodCatch",(t,e)=>{oc.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>fu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Up(t,e){return new jp({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Qp=g("ZodPipe",(t,e)=>{sc.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>du(t,n,r,o),t.in=e.in,t.out=e.out});function Mu(t,e){return new Qp({type:"pipe",in:t,out:e})}var Vp=g("ZodReadonly",(t,e)=>{ic.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>pu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Gp(t){return new Vp({type:"readonly",innerType:t})}var Jp=g("ZodLazy",(t,e)=>{ac.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>mu(t,n,r,o),t.unwrap=()=>t._zod.def.getter()});function Wo(t){return new Jp({type:"lazy",getter:t})}var qp=g("ZodCustom",(t,e)=>{cc.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>eu(t,n,r,o)});function Kp(t,e={}){return Uc(qp,t,e)}function Wp(t,e){return Qc(t,e)}function nt(t){let e=Wo(()=>Ot([v(t),Z(),tt(),Ep(),V(e),we(v(),e)]));return e}var Gu=t=>"field"in t?[t]:("all"in t?t.all:t.any).flatMap(Gu),gn=t=>Gu(t);var Nt=(t,e)=>{if("field"in t)return e(t);let n="all"in t?t.all:t.any,r=!1;if("all"in t){for(let o of n){let s=Nt(o,e);if(s===!1)return!1;r||=s===void 0}return r?void 0:!0}for(let o of n){let s=Nt(o,e);if(s===!0)return!0;r||=s===void 0}return r?void 0:!1},Ju=t=>JSON.stringify(t),Yo=t=>{if("field"in t)return{conditions:1,depth:0};let e="all"in t?t.all:t.any,n=0,r=1;for(let o of e){let s=Yo(o);n+=s.conditions,r=Math.max(r,s.depth+1)}return{conditions:n,depth:r}},qu=(t,e={})=>{let n=o=>{let s=V(o),i=e.maximumChildren===void 0?s:s.max(e.maximumChildren);return Ot([t,C({all:i}),C({any:i})])},r=Wo(()=>n(r));return e.maximumConditions===void 0&&e.maximumDepth===void 0?r:r.superRefine((o,s)=>{let{conditions:i,depth:a}=Yo(o);e.maximumConditions!==void 0&&i>e.maximumConditions&&s.addIssue({code:"custom",message:e.maximumConditionsMessage??"Query exceeds the condition limit"}),e.maximumDepth!==void 0&&a>e.maximumDepth&&s.addIssue({code:"custom",message:e.maximumDepthMessage??"Query exceeds the nesting limit"})})};var k={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,mdxDepth:100,mdxNodes:2e4,mdxProps:4e3,hydratedFileBytes:1048576,hydratedTotalBytes:2097152,hydratedFileCount:20,hydratedRangeBytes:262144,concurrentContentReads:8};function wt(t,e=new Set){if(typeof t=="number"&&isNaN(t))throw new Error("NaN is not allowed");if(typeof t=="number"&&!isFinite(t))throw new Error("Infinity is not allowed");if(t===null||typeof t!="object")return JSON.stringify(t);if(typeof t.toJSON=="function"){if(e.has(t))throw new Error("Circular reference detected");e.add(t);let r=wt(t.toJSON(),e);return e.delete(t),r}if(e.has(t))throw new Error("Circular reference detected");e.add(t);let n;if(Array.isArray(t))n=`[${t.map(o=>wt(o===void 0||typeof o=="symbol"?null:o,e)).join(",")}]`;else{let r=[];for(let o of Object.keys(t).sort())t[o]===void 0||typeof t[o]=="symbol"||r.push(`${wt(o)}:${wt(t[o],e)}`);n=`{${r.join(",")}}`}return e.delete(t),n}var Yp=new TextEncoder,Tt=t=>Yp.encode(t),Ne=t=>Tt(t).byteLength,re=class extends Error{constructor(){super("Byte stream exceeds the configured limit"),this.name="ByteLimitExceededError"}},Hp=(t,e)=>{let n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.byteLength;return n},$t=t=>typeof t=="string"?{async*[Symbol.asyncIterator](){yield Tt(t)}}:t instanceof Uint8Array?{async*[Symbol.asyncIterator](){yield t}}:t,Ku=t=>({async*[Symbol.asyncIterator](){let e=t.getReader(),n=!1;try{for(;;){let r=await e.read();if(r.done){n=!0;return}yield r.value}}finally{if(n===!1)try{await e.cancel()}catch{}e.releaseLock()}}}),Ho=async(t,e)=>{let n=[],r=0;for await(let o of $t(t)){let s=e-r;if(s<=0)break;let i=o.subarray(0,s);if(n.push(i),r+=i.byteLength,r===e)break}return Hp(n,r)},Te=async(t,e)=>{let n=await Ho(t,e+1);if(n.byteLength>e)throw new re;return n},le=t=>new TextDecoder("utf-8",{fatal:!0}).decode(t),zt=t=>t.charCodeAt(0)===65279?t.slice(1):t;var Wu=t=>{for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n>=55296&&n<=56319){let r=t.charCodeAt(e+1);if(e+1>=t.length||r<56320||r>57343)throw new Error("JSON strings cannot contain lone Unicode surrogates");e+=1;continue}if(n>=56320&&n<=57343)throw new Error("JSON strings cannot contain lone Unicode surrogates")}},Xo=(t,e)=>{if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return Wu(t),t;if(typeof t=="number"){if(Number.isFinite(t)===!1)throw new Error("JSON cannot contain non-finite numbers");return t}if(Array.isArray(t)){if(Object.getOwnPropertySymbols(t).length>0)throw new Error("JSON arrays cannot contain symbol properties");if(e.has(t))throw new Error("JSON cannot contain circular references");e.add(t);try{let n=[];for(let r=0;r<t.length;r+=1){if(Object.hasOwn(t,r)===!1)throw new Error("JSON arrays cannot be sparse");let o=t[r];if(o===void 0)throw new Error("JSON arrays cannot contain undefined values");n.push(Xo(o,e))}if(Object.keys(t).length!==t.length)throw new Error("JSON arrays cannot contain named properties");return n}finally{e.delete(t)}}if(typeof t=="object"){let n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw new Error("JSON can contain only plain objects");if(Object.getOwnPropertySymbols(t).length>0)throw new Error("JSON objects cannot contain symbol properties");if(e.has(t))throw new Error("JSON cannot contain circular references");e.add(t);let r={};try{for(let[o,s]of Object.entries(t))Wu(o),s!==void 0&&Object.defineProperty(r,o,{value:Xo(s,e),enumerable:!0,configurable:!0,writable:!0})}finally{e.delete(t)}return r}throw new Error("Value cannot be represented as JSON")},rt=t=>Xo(t,new Set),fe=t=>{let e=wt(rt(t));if(e===void 0)throw new Error("Value cannot be represented as canonical JSON");return e},bn=(t,e)=>t===void 0||e===void 0?t===e:fe(t)===fe(e),$e=(t,e)=>t<e?-1:t>e?1:0,es=async t=>{let e=typeof t=="string"?Tt(t):t,n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")},Yu=async t=>`sha256:${await es(t)}`;var Hu=Ct("type",[C({type:F("document")}),C({type:F("json"),path:V(v()).min(1)}),C({type:F("markdown-body")}),C({type:F("markdown-frontmatter")})]),ts=C({documentId:v().min(1),revision:v().min(1),representation:Hu}),Xp=t=>{let e=Hu.parse(t);return e.type==="json"?Object.freeze({...e,path:Object.freeze([...e.path])}):Object.freeze(e)},Xu=t=>{let e=ts.parse(t);return Object.freeze({...e,representation:Xp(e.representation)})};var wn=["json","markdown","mdx"],el=t=>typeof t=="string"&&wn.includes(t),tl=t=>{let e=t.split(";",1)[0].trim().toLowerCase();if(e==="application/json")return"json";if(e==="text/markdown")return"markdown";if(e==="text/mdx")return"mdx"};var ur=C({id:v().min(1),revision:v().min(1),contentRef:v().min(1),format:ae(wn).optional()}),lr=C({sourceId:v().min(1),referenceId:v().min(1),reference:ts});var Pt=t=>{let e=new Map;for(let n of t){let r=e.get(n.sourceId)??[];r.push(n),e.set(n.sourceId,r)}return e};var ze=class extends Error{code;documentIds;constructor({code:e,message:n,documentIds:r=[]}){super(n),this.name="DocumentGraphError",this.code=e,this.documentIds=Object.freeze([...r])}},em=(t,e)=>$e(t.sourceId,e.sourceId)||$e(t.referenceId,e.referenceId),_n=({nodes:t,edges:e})=>{let n=t.map(a=>Object.freeze(ur.parse(a))).sort((a,c)=>$e(a.id,c.id)),r=new Map,o=new Map;for(let a of n){if(r.has(a.id))throw new ze({code:"DUPLICATE_NODE",message:`Document graph contains duplicate node ${a.id}`,documentIds:[a.id]});r.set(a.id,a);let c=o.get(a.contentRef);if(c!==void 0&&(c.revision!==a.revision||c.format!==a.format))throw new ze({code:"CONTENT_IDENTITY_CONFLICT",message:`Document graph content reference ${a.contentRef} has conflicting identities`,documentIds:[c.id,a.id]});o.set(a.contentRef,a)}let s=e.map(a=>{let c=lr.parse(a);return Object.freeze({...c,reference:Xu(c.reference)})}).sort(em),i=new Set;for(let a of s){if(r.get(a.sourceId)===void 0)throw new ze({code:"SOURCE_NOT_FOUND",message:`Document graph source ${a.sourceId} does not exist`,documentIds:[a.sourceId]});let u=r.get(a.reference.documentId);if(u===void 0)throw new ze({code:"TARGET_NOT_FOUND",message:`Document graph target ${a.reference.documentId} does not exist`,documentIds:[a.sourceId,a.reference.documentId]});if(u.revision!==a.reference.revision)throw new ze({code:"TARGET_REVISION_MISMATCH",message:`Document graph target ${u.id} revision does not match its reference`,documentIds:[a.sourceId,u.id]});let p=`${a.sourceId}\0${a.referenceId}`;if(i.has(p))throw new ze({code:"DUPLICATE_REFERENCE",message:`Document ${a.sourceId} contains duplicate reference ID ${a.referenceId}`,documentIds:[a.sourceId]});i.add(p)}return Object.freeze({nodes:Object.freeze(n),edges:Object.freeze(s)})},tm=t=>new Map(t.nodes.map(e=>[e.id,e]));var fr=({graph:t,rootIds:e})=>{let n=tm(t),r=Pt(t.edges),o=new Map,s=[],i=[],a=c=>{let u=n.get(c);if(u===void 0)throw new ze({code:"ROOT_NOT_FOUND",message:`Document graph root ${c} does not exist`,documentIds:[c]});let p=o.get(c);if(p!=="visited"){if(p==="visiting"){let l=s.indexOf(c),f=[...s.slice(l),c];throw new ze({code:"CYCLE",message:`Document graph contains a cycle: ${f.join(" -> ")}`,documentIds:f})}o.set(c,"visiting"),s.push(c);for(let l of r.get(c)??[])a(l.reference.documentId);s.pop(),o.set(c,"visited"),i.push(u)}};for(let c of[...new Set(e)].sort($e))a(c);return Object.freeze(i)};var nm=v().regex(/^sha256:[a-f0-9]{64}$/),nl=C({format:F("webstudio-document-graph"),version:F(1),nodes:V(ur),edges:V(lr),integrity:C({algorithm:F("sha256"),checksum:nm})});var rm=v().min(1).refine(t=>t.startsWith("/")===!1,{error:"Asset path must be relative"}).refine(t=>t.includes("\\")===!1&&t.split("/").every(e=>e.length>0&&e!==".."&&e!=="."),{error:"Asset path must be normalized and must not contain dot segments"}),sl=C({_id:v().min(1),_type:F("asset.file"),name:v().min(1),description:v().optional(),path:rm,key:v(),folderId:v().min(1).optional(),extension:v().regex(/^[a-z0-9]*$/),mimeType:v().min(1),size:Z().int().nonnegative(),createdAt:v().datetime().optional(),revision:v().min(1),contentRef:v().min(1),properties:we(v(),nt()),excerpt:v().optional(),metadataError:C({code:v().min(1),message:v().min(1)}).optional()}),rs=sl.partial().required({_id:!0}),om=ae(["null","boolean","number","string","object","array"]),sm=he({format:F("webstudio-builder-asset-field-catalog"),version:F(1),canonicalRevision:v().regex(/^sha256:[a-f0-9]{64}$/),documentCount:Z().int().nonnegative(),fields:we(v().min(1),he({queryPath:V(v().min(1)).min(1).max(k.fieldPathDepth).optional(),types:V(om).min(1),occurrences:Z().int().positive(),optional:F(!0).optional(),mixed:F(!0).optional()}))}).superRefine((t,e)=>{for(let[n,r]of Object.entries(t.fields)){let o=[...new Set(r.types)].sort();JSON.stringify(r.types)!==JSON.stringify(o)&&e.addIssue({code:"custom",path:["fields",n,"types"],message:"Observed field types must be unique and sorted"}),r.occurrences>t.documentCount&&e.addIssue({code:"custom",path:["fields",n,"occurrences"],message:"Field occurrences cannot exceed the document count"});let s=r.occurrences<t.documentCount;r.optional===!0!==s&&e.addIssue({code:"custom",path:["fields",n,"optional"],message:"Field optionality must match its occurrence count"});let i=o.length>1;r.mixed===!0!==i&&e.addIssue({code:"custom",path:["fields",n,"mixed"],message:"Mixed status must match the observed types"})}}),dr=v().regex(/^sha256:[a-f0-9]{64}$/),il=C({fields:V(V(v().min(1)).min(1).max(k.fieldPathDepth)).min(1).max(k.outputFieldCount+1),rows:V(V(nt())).max(k.resultCount),totalCount:Z().int().nonnegative().max(k.candidateDocuments),hasMore:tt()}).superRefine(({fields:t,rows:e},n)=>{for(let[r,o]of e.entries())o.length!==t.length&&n.addIssue({code:"custom",path:["rows",r],message:"Materialized query rows must match the field count"})}),rl=C({format:F("webstudio-content-database"),version:F(1),assetRevision:dr,documents:V(rs),documentGraph:nl.optional(),contents:we(v().min(1),v()).optional(),assetReferences:we(v().min(1),V(C({start:Z().int().nonnegative(),end:Z().int().positive(),assetId:v().min(1),suffix:v().min(1).optional()}).refine(({start:t,end:e})=>e>t,{message:"Markdown asset reference range must not be empty"}))).optional(),assetValueReferences:we(v().min(1),V(C({path:V(v().min(1).or(Z().int().nonnegative())).min(1),assetId:v().min(1),suffix:v().min(1).optional(),structured:F(!0).optional()}))).optional(),fieldCatalog:sm,queries:we(dr,il).optional(),database:C({maxBytes:Z().int().positive(),unboundedBytes:Z().int().nonnegative(),sourceDocumentCount:Z().int().nonnegative(),includedDocumentCount:Z().int().nonnegative().optional()}).optional(),integrity:C({algorithm:F("sha256"),checksum:dr})}).superRefine((t,e)=>{t.documents.length>k.candidateDocuments&&e.addIssue({code:"custom",path:["documents"],message:"Asset index exceeds the document limit"}),(t.fieldCatalog.canonicalRevision!==t.assetRevision||t.fieldCatalog.documentCount!==t.documents.length)&&e.addIssue({code:"custom",path:["fieldCatalog"],message:"Asset index field catalog does not match its documents"}),t.database!==void 0&&t.database.sourceDocumentCount<t.documents.length&&e.addIssue({code:"custom",path:["database","sourceDocumentCount"],message:"Source document count cannot be smaller than the database"}),t.database?.includedDocumentCount!==void 0&&(t.database.includedDocumentCount<t.documents.length||t.database.includedDocumentCount>t.database.sourceDocumentCount)&&e.addIssue({code:"custom",path:["database","includedDocumentCount"],message:"Included document count must match the database bounds"});let n;for(let[o,s]of t.documents.entries())n!==void 0&&s._id<=n&&e.addIssue({code:"custom",path:["documents",o,"_id"],message:"Asset index documents must have unique sorted IDs"}),n=s._id;let r=new Set(t.documents.flatMap(({contentRef:o})=>o===void 0?[]:[o]));for(let o of t.documentGraph?.nodes??[])r.add(o.contentRef);for(let o of Object.keys(t.contents??{}))r.has(o)===!1&&e.addIssue({code:"custom",path:["contents",o],message:"Embedded content must belong to an indexed document"});for(let o of Object.keys(t.assetReferences??{}))r.has(o)===!1&&e.addIssue({code:"custom",path:["assetReferences",o],message:"Asset references must belong to an indexed document"})}),im=Ct("mode",[he({mode:F("none")}),he({mode:F("full"),maxBytes:Z().int().positive().max(k.hydratedFileBytes).optional()}),he({mode:F("range"),offset:Z().int().nonnegative(),length:Z().int().positive().max(k.hydratedRangeBytes)}),he({mode:F("markdown-body-ref"),maxBytes:Z().int().positive().max(k.hydratedFileBytes).optional()})]),os={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"]},al=Object.keys(os),cl=["url","width","height"],pr=t=>cl.includes(t),ul=al.filter(t=>pr(t)===!1&&t!=="excerpt"),ll=ul.filter(t=>t!=="id"),fl=t=>ul.includes(t),am=ae(al),xn=V(v().min(1)).min(1).max(k.fieldPathDepth).superRefine((t,e)=>{if(t[0]==="properties"){t.length<2&&e.addIssue({code:"custom",message:"A properties field path must select a property"});return}(t.length!==1||am.safeParse(t[0]).success===!1)&&e.addIssue({code:"custom",message:"Asset query field path is unsupported"})}),ns=tt().default(!0),cm=Ct("mode",[C({mode:F("all"),includeMetadata:ns}),C({mode:F("base"),includeMetadata:ns}),C({mode:F("fields"),includeMetadata:ns,fields:V(xn).max(k.outputFieldCount).refine(t=>new Set(t.map(Ju)).size===t.length,{error:"Selected output fields must be unique"})})]),um={mode:"fields",includeMetadata:!1,fields:cl.map(t=>[t])},dl=["eq","ne","contains","startsWith","endsWith","gt","gte","lt","lte"],Ob=[...dl,"in","exists","isEmpty"],lm=C({field:xn,operator:ae(dl),value:nt()}),fm=C({field:xn,operator:F("in"),value:V(nt()).max(k.resultCount)}),dm=C({field:xn,operator:ae(["exists","isEmpty"]),value:tt()}),pm=Ct("operator",[lm,fm,dm]),mm=qu(pm,{maximumChildren:k.filterCount,maximumConditions:k.filterCount,maximumDepth:k.filterDepth,maximumConditionsMessage:"Asset query exceeds the filter limit",maximumDepthMessage:"Asset query exceeds the filter nesting limit"});var hm=mm,pl=t=>{let e=new Set(["eq","ne","in","exists"]);return t.some(n=>n==="string"||n==="array")&&e.add("contains"),t.includes("string")&&(e.add("startsWith"),e.add("endsWith")),t.some(n=>n==="string"||n==="number")&&(e.add("gt"),e.add("gte"),e.add("lt"),e.add("lte")),t.some(n=>n==="string"||n==="array"||n==="object")&&e.add("isEmpty"),[...e]},ym=C({field:xn,direction:ae(["asc","desc"])}),gm=ae(["many","one","first","last"]),bm=({output:t,content:e})=>t.includeMetadata||t.mode==="all"||t.mode==="fields"&&t.fields.length>0||e.mode!=="none",ot=C({result:gm.default("many"),where:hm.default({all:[]}),sort:V(ym).max(k.sortCount).default([]),limit:Z().int().nonnegative().max(k.resultCount).default(k.defaultResultCount),offset:Z().int().nonnegative().max(k.candidateDocuments).default(0),output:cm.default(um),content:im.default({mode:"none"})}).superRefine((t,e)=>{bm(t)===!1&&e.addIssue({code:"custom",message:"Select at least one asset query output"}),(t.result==="first"||t.result==="last")&&t.sort.length===0&&e.addIssue({code:"custom",path:["sort"],message:"Add sorting to define which item is first."})}),ml=C({query:ot,indexRevision:v().min(1).max(255).optional()}),wm=he({_id:v().min(1),revision:v().min(1),contentRef:v().min(1),encoding:F("utf-8"),text:v(),range:he({offset:Z().int().nonnegative(),length:Z().int().nonnegative(),total:Z().int().nonnegative()}).optional()}),_m=wm.omit({_id:!0,revision:!0,contentRef:!0}),hl=sl.omit({_id:!0,_type:!0,contentRef:!0}).partial().extend({id:v().min(1),url:v().min(1).optional(),width:Z().positive().optional(),height:Z().positive().optional(),content:_m.optional()}).refine(t=>t.width===void 0==(t.height===void 0),{error:"Asset dimensions must include both width and height"}),xm=C({format:F("webstudio-content-database"),version:F(1),revision:dr,usedBytes:Z().int().nonnegative(),maxBytes:Z().int().positive(),unboundedBytes:Z().int().nonnegative(),includedDocumentCount:Z().int().nonnegative(),omittedDocumentCount:Z().int().nonnegative(),omissionReason:ae(["size","unavailable"]).optional(),truncated:tt()}),ol=xm.pick({usedBytes:!0,maxBytes:!0,unboundedBytes:!0,includedDocumentCount:!0,omittedDocumentCount:!0,omissionReason:!0,truncated:!0}),ss=C({items:V(hl),totalCount:Z().int().nonnegative(),hasMore:tt()}),Sm=C({item:hl.nullable(),totalCount:Z().int().nonnegative()}),yl=Ot([ss,Sm]),Am=C({scope:F("query-preview"),query:ol,database:ol,artifacts:C({query:rl,database:rl}).optional(),unresolved:yl.optional()}),Cb=C({data:yl,__diagnostics__:Am}),Em=ae(["INVALID_REQUEST","REQUEST_CANCELLED","UNAUTHORIZED","FORBIDDEN","STALE_INDEX","CONTENT_IDENTITY_REQUIRED","CONTENT_NOT_TEXT","CONTENT_DECODING_FAILED","CONTENT_LIMIT_EXCEEDED","MULTIPLE_RESULTS","INTERNAL_ERROR"]),vm=he({ok:F(!1),error:he({code:Em,message:v().min(1),retryable:tt(),details:we(v(),nt()).optional()}),meta:he({queryHash:v().min(1).optional(),indexRevision:v().min(1).optional(),assetRevision:v().min(1).optional()}).optional()}),gl=({code:t,message:e,retryable:n=!1,details:r})=>vm.parse({ok:!1,error:{code:t,message:e,retryable:n,details:r}});var bl=function*(t){if(t.length>0&&!t.startsWith("/")||/~(?![01])/.test(t))throw Error("Invalid JSON Pointer");let e=1,n=0;for(;n<t.length;){let r=t.indexOf("/",e);n=r===-1?t.length:r;let o=t.slice(e,n);e=n+1,yield Rm(o)}};var is=(t,e)=>e+"/"+Dm(t),Dm=t=>t.toString().replace(/~/g,"~0").replace(/\//g,"~1"),Rm=t=>t.toString().replace(/~1/g,"/").replace(/~0/g,"~");var mr=async(t,e,n)=>{if(Number.isSafeInteger(e)===!1||e<=0)throw new Error("Concurrency must be a positive safe integer");let r=0,o=new Array(t.length),s=async()=>{for(;r<t.length;){let u=r;r+=1,o[u]=await n(t[u])}},i=Array.from({length:Math.min(e,t.length)},s),c=(await Promise.allSettled(i)).find(u=>u.status==="rejected");if(c!==void 0)throw c.reason;return o};var Lt=t=>typeof t=="object"&&t!==null&&Array.isArray(t)===!1,hr=t=>{if(Lt(t)===!1)return;let e=Object.keys(t);if(!(e.length!==1||e[0]!=="$ref"))return t.$ref};var de=class extends Error{code;referenceId;constructor({code:e,message:n,referenceId:r,cause:o}){super(n,{cause:o}),this.name="JsonDocumentError",this.code=e,this.referenceId=r}},km=(t,e)=>{let n=hr(t);if(n!==void 0){if(typeof n!="string")throw new de({code:"INVALID_REFERENCE_MARKER",message:`JSON reference marker ${e} must contain a string $ref`,referenceId:e});return n}},Im=t=>`#${t}`;var wl=async({source:t,maximumBytes:e=k.hydratedFileBytes})=>{let n;try{n=await Te(t,e)}catch(o){throw o instanceof re?new de({code:"CONTENT_LIMIT_EXCEEDED",message:"JSON document exceeds the byte limit",cause:o}):o}let r;try{r=zt(le(n))}catch(o){throw new de({code:"CONTENT_DECODING_FAILED",message:"JSON document is not valid UTF-8",cause:o})}try{return rt(JSON.parse(r))}catch(o){throw new de({code:"INVALID_DOCUMENT",message:"JSON document is invalid",cause:o})}};var Om=(t,e)=>{let n=t;for(let r of e){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(Lt(n)&&Object.hasOwn(n,r)){n=n[r];continue}return}return n},_l=({document:t,representation:e})=>{let n=rt(t);if(e.type==="document")return n;if(e.type!=="json")throw new de({code:"UNSUPPORTED_REPRESENTATION",message:`JSON documents do not support ${e.type}`});let r=Om(n,e.path);if(r===void 0)throw new de({code:"JSON_PATH_NOT_FOUND",message:"JSON document path does not exist"});return r},Cm=(t,e,n)=>{Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0})},yr=({document:t,references:e,allowUnresolvedReferences:n=!1})=>{let r=rt(t),o=new Set,s=(a,c)=>{let u=Im(c);if(km(a,u)!==void 0){if(e.has(u)===!1){if(n)return a;throw new de({code:"REFERENCE_NOT_FOUND",message:`Resolved JSON reference ${u} is unavailable`,referenceId:u})}o.add(u);try{return rt(e.get(u))}catch(l){throw new de({code:"INVALID_RESOLVED_VALUE",message:`Resolved JSON reference ${u} is not JSON-compatible`,referenceId:u,cause:l})}}if(Array.isArray(a))return a.map((l,f)=>s(l,is(String(f),c)));if(Lt(a)){let l={};for(let[f,d]of Object.entries(a))Cm(l,f,s(d,is(f,c)));return l}return a},i=s(r,"");for(let a of[...e.keys()].sort())if(o.has(a)===!1)throw new de({code:"UNUSED_REFERENCE",message:`Resolved JSON reference ${a} has no marker`,referenceId:a});return i};var gr=Symbol.for("yaml.alias"),br=Symbol.for("yaml.document"),_e=Symbol.for("yaml.map"),as=Symbol.for("yaml.pair"),pe=Symbol.for("yaml.scalar"),Ge=Symbol.for("yaml.seq"),oe=Symbol.for("yaml.node.type"),xe=t=>!!t&&typeof t=="object"&&t[oe]===gr,Pe=t=>!!t&&typeof t=="object"&&t[oe]===br,Se=t=>!!t&&typeof t=="object"&&t[oe]===_e,T=t=>!!t&&typeof t=="object"&&t[oe]===as,N=t=>!!t&&typeof t=="object"&&t[oe]===pe,Ae=t=>!!t&&typeof t=="object"&&t[oe]===Ge;function B(t){if(t&&typeof t=="object")switch(t[oe]){case _e:case Ge:return!0}return!1}function L(t){if(t&&typeof t=="object")switch(t[oe]){case gr:case _e:case pe:case Ge:return!0}return!1}var wr=t=>(N(t)||B(t))&&!!t.anchor;var ce=Symbol("break visit"),xl=Symbol("skip children"),Le=Symbol("remove node");function Me(t,e){let n=Sl(e);Pe(t)?Mt(null,t.contents,n,Object.freeze([t]))===Le&&(t.contents=null):Mt(null,t,n,Object.freeze([]))}Me.BREAK=ce;Me.SKIP=xl;Me.REMOVE=Le;function Mt(t,e,n,r){let o=Al(t,e,n,r);if(L(o)||T(o))return El(t,r,o),Mt(t,o,n,r);if(typeof o!="symbol"){if(B(e)){r=Object.freeze(r.concat(e));for(let s=0;s<e.items.length;++s){let i=Mt(s,e.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===ce)return ce;i===Le&&(e.items.splice(s,1),s-=1)}}}else if(T(e)){r=Object.freeze(r.concat(e));let s=Mt("key",e.key,n,r);if(s===ce)return ce;s===Le&&(e.key=null);let i=Mt("value",e.value,n,r);if(i===ce)return ce;i===Le&&(e.value=null)}}return o}async function _r(t,e){let n=Sl(e);Pe(t)?await Ft(null,t.contents,n,Object.freeze([t]))===Le&&(t.contents=null):await Ft(null,t,n,Object.freeze([]))}_r.BREAK=ce;_r.SKIP=xl;_r.REMOVE=Le;async function Ft(t,e,n,r){let o=await Al(t,e,n,r);if(L(o)||T(o))return El(t,r,o),Ft(t,o,n,r);if(typeof o!="symbol"){if(B(e)){r=Object.freeze(r.concat(e));for(let s=0;s<e.items.length;++s){let i=await Ft(s,e.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===ce)return ce;i===Le&&(e.items.splice(s,1),s-=1)}}}else if(T(e)){r=Object.freeze(r.concat(e));let s=await Ft("key",e.key,n,r);if(s===ce)return ce;s===Le&&(e.key=null);let i=await Ft("value",e.value,n,r);if(i===ce)return ce;i===Le&&(e.value=null)}}return o}function Sl(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function Al(t,e,n,r){if(typeof n=="function")return n(t,e,r);if(Se(e))return n.Map?.(t,e,r);if(Ae(e))return n.Seq?.(t,e,r);if(T(e))return n.Pair?.(t,e,r);if(N(e))return n.Scalar?.(t,e,r);if(xe(e))return n.Alias?.(t,e,r)}function El(t,e,n){let r=e[e.length-1];if(B(r))r.items[t]=n;else if(T(r))t==="key"?r.key=n:r.value=n;else if(Pe(r))r.contents=n;else{let o=xe(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}var Nm={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Tm=t=>t.replace(/[!,[\]{}]/g,e=>Nm[e]),Fe=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let r=e.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(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let i=e.slice(2,-1);return i==="!"||i==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),i)}let[,r,o]=e.match(/^(.*!)([^!]*)$/s);o||n(`The ${e} 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==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,r]of Object.entries(this.tags))if(e.startsWith(r))return n+Tm(e.substring(r.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),o;if(e&&r.length>0&&L(e.contents)){let s={};Me(e.contents,(i,a)=>{L(a)&&a.tag&&(s[a.tag]=!0)}),o=Object.keys(s)}else o=[];for(let[s,i]of r)s==="!!"&&i==="tag:yaml.org,2002:"||(!e||o.some(a=>a.startsWith(i)))&&n.push(`%TAG ${s} ${i}`);return n.join(`+`)}};Fe.defaultYaml={explicit:!1,version:"1.2"};Fe.defaultTags={"!!":"tag:yaml.org,2002:"};function xr(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function cs(t){let e=new Set;return Me(t,{Value(n,r){r.anchor&&e.add(r.anchor)}}),e}function us(t,e){for(let n=1;;++n){let r=`${t}${n}`;if(!e.has(r))return r}}function vl(t,e){let n=[],r=new Map,o=null;return{onAnchor:s=>{n.push(s),o??(o=cs(t));let i=us(e,o);return o.add(i),i},setAnchors:()=>{for(let s of n){let i=r.get(s);if(typeof i=="object"&&i.anchor&&(N(i.node)||B(i.node)))i.node.anchor=i.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:r}}function st(t,e,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],a=st(t,r,String(o),i);a===void 0?delete r[o]:a!==i&&(r[o]=a)}else if(r instanceof Map)for(let o of Array.from(r.keys())){let s=r.get(o),i=st(t,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=st(t,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=st(t,r,o,s);i===void 0?delete r[o]:i!==s&&(r[o]=i)}return t.call(e,n,r)}function Y(t,e,n){if(Array.isArray(t))return t.map((r,o)=>Y(r,String(o),n));if(t&&typeof t.toJSON=="function"){if(!n||!wr(t))return t.toJSON(e,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(t,r),n.onCreate=s=>{r.res=s,delete n.onCreate};let o=t.toJSON(e,n);return n.onCreate&&n.onCreate(o),o}return typeof t=="bigint"&&!n?.keep?Number(t):t}var it=class{constructor(e){Object.defineProperty(this,oe,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:r,onAnchor:o,reviver:s}={}){if(!Pe(e))throw new TypeError("A document argument is required");let i={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=Y(this,"",i);if(typeof o=="function")for(let{count:c,res:u}of i.anchors.values())o(u,c);return typeof s=="function"?st(s,{"":a},"",a):a}};var Je=class extends it{constructor(e){super(gr),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],Me(e,{Node:(s,i)=>{(xe(i)||wr(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(e,n){if(!n)return{source:this.source};let{anchors:r,doc:o,maxAliasCount:s}=n,i=this.resolve(o,n);if(!i){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=r.get(i);if(a||(Y(i,null,n),a=r.get(i)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Sr(o,i,r)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,n,r){let o=`*${this.source}`;if(e){if(xr(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${o} `}return o}};function Sr(t,e,n){if(xe(e)){let r=e.resolve(t),o=n&&r&&n.get(r);return o?o.count*o.aliasCount:0}else if(B(e)){let r=0;for(let o of e.items){let s=Sr(t,o,n);s>r&&(r=s)}return r}else if(T(e)){let r=Sr(t,e.key,n),o=Sr(t,e.value,n);return Math.max(r,o)}return 1}var Ar=t=>!t||typeof t!="function"&&typeof t!="object",R=class extends it{constructor(e){super(pe),this.value=e}toJSON(e,n){return n?.keep?this.value:Y(this.value,e,n)}toString(){return String(this.value)}};R.BLOCK_FOLDED="BLOCK_FOLDED";R.BLOCK_LITERAL="BLOCK_LITERAL";R.PLAIN="PLAIN";R.QUOTE_DOUBLE="QUOTE_DOUBLE";R.QUOTE_SINGLE="QUOTE_SINGLE";var $m="tag:yaml.org,2002:";function zm(t,e,n){if(e){let r=n.filter(s=>s.tag===e),o=r.find(s=>!s.format)??r[0];if(!o)throw new Error(`Tag ${e} not found`);return o}return n.find(r=>r.identify?.(t)&&!r.format)}function qe(t,e,n){if(Pe(t)&&(t=t.contents),L(t))return t;if(T(t)){let l=n.schema[_e].createNode?.(n.schema,null,n);return l.items.push(t),l}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:r,onAnchor:o,onTagObj:s,schema:i,sourceObjects:a}=n,c;if(r&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=o(t)),new Je(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=$m+e.slice(2));let u=zm(t,e,i.tags);if(!u){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let l=new R(t);return c&&(c.node=l),l}u=t instanceof Map?i[_e]:Symbol.iterator in Object(t)?i[Ge]:i[_e]}s&&(s(u),delete n.onTagObj);let p=u?.createNode?u.createNode(n.schema,t,n):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(n.schema,t,n):new R(t);return e?p.tag=e:u.default||(p.tag=u.tag),c&&(c.node=p),p}function Sn(t,e,n){let r=n;for(let o=e.length-1;o>=0;--o){let s=e[o];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let i=[];i[s]=r,r=i}else r=new Map([[s,r]])}return qe(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Bt=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Zt=class extends it{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(r=>L(r)||T(r)?r.clone(e):r),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(Bt(e))this.add(n);else{let[r,...o]=e,s=this.get(r,!0);if(B(s))s.addIn(o,n);else if(s===void 0&&this.schema)this.set(r,Sn(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}deleteIn(e){let[n,...r]=e;if(r.length===0)return this.delete(n);let o=this.get(n,!0);if(B(o))return o.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(e,n){let[r,...o]=e,s=this.get(r,!0);return o.length===0?!n&&N(s)?s.value:s:B(s)?s.getIn(o,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!T(n))return!1;let r=n.value;return r==null||e&&N(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[n,...r]=e;if(r.length===0)return this.has(n);let o=this.get(n,!0);return B(o)?o.hasIn(r):!1}setIn(e,n){let[r,...o]=e;if(o.length===0)this.set(r,n);else{let s=this.get(r,!0);if(B(s))s.setIn(o,n);else if(s===void 0&&this.schema)this.set(r,Sn(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}};var Dl=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function ye(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Ze=(t,e,n)=>t.endsWith(``)?ye(n,e):n.includes(``)?`-`+ye(n,e):(t.endsWith(" ")?"":" ")+n;var as="flow",Ar="block",xn="quoted";function Sn(t,e,n="flow",{indentAtStart:r,lineWidth:o=80,minContentWidth:s=20,onFold:i,onOverflow:a}={}){if(!o||o<0)return t;o<s&&(s=0);let c=Math.max(1+s,1+o-e.length);if(t.length<=c)return t;let u=[],d={},l=o-e.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===Ar&&(m=_l(t,m,e.length),m!==-1&&(l=m+c));for(let A;A=t[m+=1];){if(n===xn&&A==="\\"){switch(h=m,t[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}b=m}if(A===`-`)n===Ar&&(m=_l(t,m,e.length)),l=m+e.length+c,f=void 0;else{if(A===" "&&p&&p!==" "&&p!==`-`&&p!==" "){let _=t[m+1];_&&_!==" "&&_!==`-`&&_!==" "&&(f=m)}if(m>=l)if(f)u.push(f),l=f+c,f=void 0;else if(n===xn){for(;p===" "||p===" ";)p=A,A=t[m+=1],y=!0;let _=m>b+1?m-2:h-1;if(d[_])return t;u.push(_),d[_]=!0,l=_+c,f=void 0}else y=!0}p=A}if(y&&a&&a(),u.length===0)return t;i&&i();let S=t.slice(0,u[0]);for(let A=0;A<u.length;++A){let _=u[A],w=u[A+1]||t.length;_===0?S=`-${e}${t.slice(0,w)}`:(n===xn&&d[_]&&(S+=`${t[_]}\\`),S+=`-${e}${t.slice(_+1,w)}`)}return S}function _l(t,e,n){let r=e,o=e+1,s=t[o];for(;s===" "||s===" ";)if(e<o+n)s=t[++e];else{do s=t[++e];while(s&&s!==`-`);r=e,o=e+1,s=t[o]}return r}var vr=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),kr=t=>/^(%|---|\.\.\.)/m.test(t);function Im(t,e,n){if(!e||e<0)return!1;let r=e-n,o=t.length;if(o<=r)return!1;for(let s=0,i=0;s<o;++s)if(t[s]===`-`){if(s-i>r)return!0;if(i=s+1,o-i<=r)return!1}return!0}function An(t,e){let n=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=e,o=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(kr(t)?" ":""),i="",a=0;for(let c=0,u=n[c];u;u=n[++c])if(u===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(i+=n.slice(a,c)+"\\ ",c+=1,a=c,u="\\"),u==="\\")switch(n[c+1]){case"u":{i+=n.slice(a,c);let d=n.substr(c+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(c,6)}c+=5,a=c+1}break;case"n":if(r||n[c+2]==='"'||n.length<o)c+=1;else{for(i+=n.slice(a,c)+`+`+ye(n,e):(t.endsWith(" ")?"":" ")+n;var ls="flow",Er="block",An="quoted";function En(t,e,n="flow",{indentAtStart:r,lineWidth:o=80,minContentWidth:s=20,onFold:i,onOverflow:a}={}){if(!o||o<0)return t;o<s&&(s=0);let c=Math.max(1+s,1+o-e.length);if(t.length<=c)return t;let u=[],p={},l=o-e.length;typeof r=="number"&&(r>o-Math.max(2,s)?u.push(0):l=o-r);let f,d,y=!1,m=-1,h=-1,b=-1;n===Er&&(m=Rl(t,m,e.length),m!==-1&&(l=m+c));for(let A;A=t[m+=1];){if(n===An&&A==="\\"){switch(h=m,t[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}b=m}if(A===`+`)n===Er&&(m=Rl(t,m,e.length)),l=m+e.length+c,f=void 0;else{if(A===" "&&d&&d!==" "&&d!==`+`&&d!==" "){let _=t[m+1];_&&_!==" "&&_!==`+`&&_!==" "&&(f=m)}if(m>=l)if(f)u.push(f),l=f+c,f=void 0;else if(n===An){for(;d===" "||d===" ";)d=A,A=t[m+=1],y=!0;let _=m>b+1?m-2:h-1;if(p[_])return t;u.push(_),p[_]=!0,l=_+c,f=void 0}else y=!0}d=A}if(y&&a&&a(),u.length===0)return t;i&&i();let S=t.slice(0,u[0]);for(let A=0;A<u.length;++A){let _=u[A],w=u[A+1]||t.length;_===0?S=`+${e}${t.slice(0,w)}`:(n===An&&p[_]&&(S+=`${t[_]}\\`),S+=`+${e}${t.slice(_+1,w)}`)}return S}function Rl(t,e,n){let r=e,o=e+1,s=t[o];for(;s===" "||s===" ";)if(e<o+n)s=t[++e];else{do s=t[++e];while(s&&s!==`+`);r=e,o=e+1,s=t[o]}return r}var Dr=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),Rr=t=>/^(%|---|\.\.\.)/m.test(t);function Pm(t,e,n){if(!e||e<0)return!1;let r=e-n,o=t.length;if(o<=r)return!1;for(let s=0,i=0;s<o;++s)if(t[s]===`+`){if(s-i>r)return!0;if(i=s+1,o-i<=r)return!1}return!0}function vn(t,e){let n=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=e,o=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(Rr(t)?" ":""),i="",a=0;for(let c=0,u=n[c];u;u=n[++c])if(u===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(i+=n.slice(a,c)+"\\ ",c+=1,a=c,u="\\"),u==="\\")switch(n[c+1]){case"u":{i+=n.slice(a,c);let p=n.substr(c+2,4);switch(p){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:p.substr(0,2)==="00"?i+="\\x"+p.substr(2):i+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(r||n[c+2]==='"'||n.length<o)c+=1;else{for(i+=n.slice(a,c)+``;n[c+2]==="\\"&&n[c+3]==="n"&&n[c+4]!=='"';)i+=`-`,c+=2;i+=s,n[c+2]===" "&&(i+="\\"),c+=1,a=c+1}break;default:c+=1}return i=a?i+n.slice(a):n,r?i:Sn(i,s,xn,vr(e,!1))}function cs(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`-`)||/[ \t]\n|\n[ \t]/.test(t))return An(t,e);let n=e.indent||(kr(t)?" ":""),r="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&-${n}`)+"'";return e.implicitKey?r:Sn(r,n,as,vr(e,!1))}function Bt(t,e){let{singleQuote:n}=e.options,r;if(n===!1)r=An;else{let o=t.includes('"'),s=t.includes("'");o&&!s?r=cs:s&&!o?r=An:r=n?cs:An}return r(t,e)}var us;try{us=new RegExp(`(^|(?<!+`,c+=2;i+=s,n[c+2]===" "&&(i+="\\"),c+=1,a=c+1}break;default:c+=1}return i=a?i+n.slice(a):n,r?i:En(i,s,An,Dr(e,!1))}function fs(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`+`)||/[ \t]\n|\n[ \t]/.test(t))return vn(t,e);let n=e.indent||(Rr(t)?" ":""),r="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&+${n}`)+"'";return e.implicitKey?r:En(r,n,ls,Dr(e,!1))}function jt(t,e){let{singleQuote:n}=e.options,r;if(n===!1)r=vn;else{let o=t.includes('"'),s=t.includes("'");o&&!s?r=fs:s&&!o?r=vn:r=n?fs:vn}return r(t,e)}var ds;try{ds=new RegExp(`(^|(?<!))+(?!-|$)`,"g")}catch{us=/\n+(?!\n|$)/g}function Er({comment:t,type:e,value:n},r,o,s){let{blockQuote:i,commentString:a,lineWidth:c}=r.options;if(!i||/\n[\t ]+$/.test(n))return Bt(n,r);let u=r.indent||(r.forceBlockIndent||kr(n)?" ":""),d=i==="literal"?!0:i==="folded"||e===D.BLOCK_FOLDED?!1:e===D.BLOCK_LITERAL?!0:!Im(n,c,u.length);if(!n)return d?`|+|$)`,"g")}catch{ds=/\n+(?!\n|$)/g}function vr({comment:t,type:e,value:n},r,o,s){let{blockQuote:i,commentString:a,lineWidth:c}=r.options;if(!i||/\n[\t ]+$/.test(n))return jt(n,r);let u=r.indent||(r.forceBlockIndent||Rr(n)?" ":""),p=i==="literal"?!0:i==="folded"||e===R.BLOCK_FOLDED?!1:e===R.BLOCK_LITERAL?!0:!Pm(n,c,u.length);if(!n)return p?`|`:`>`;let l,f;for(f=n.length;f>0;--f){let w=n[f-1];if(w!==`-`&&w!==" "&&w!==" ")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(us,`$&${u}`));let m=!1,h,b=-1;for(h=0;h<n.length;++h){let w=n[h];if(w===" ")m=!0;else if(w===`-`)b=h;else break}let S=n.substring(0,b<h?b+1:h);S&&(n=n.substring(S.length),S=S.replace(/\n+/g,`$&${u}`));let _=(m?u?"2":"1":"")+l;if(t&&(_+=" "+a(t.replace(/ ?[\r\n]+/g," ")),o&&o()),!d){let w=n.replace(/\n+/g,`-$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`),E=!1,k=vr(r,!0);i!=="folded"&&e!==D.BLOCK_FOLDED&&(k.onOverflow=()=>{E=!0});let x=Sn(`${S}${w}${p}`,u,Ar,k);if(!E)return`>${_}+`&&w!==" "&&w!==" ")break}let d=n.substring(f),y=d.indexOf(`+`);y===-1?l="-":n===d||y!==d.length-1?(l="+",s&&s()):l="",d&&(n=n.slice(0,-d.length),d[d.length-1]===`+`&&(d=d.slice(0,-1)),d=d.replace(ds,`$&${u}`));let m=!1,h,b=-1;for(h=0;h<n.length;++h){let w=n[h];if(w===" ")m=!0;else if(w===`+`)b=h;else break}let S=n.substring(0,b<h?b+1:h);S&&(n=n.substring(S.length),S=S.replace(/\n+/g,`$&${u}`));let _=(m?u?"2":"1":"")+l;if(t&&(_+=" "+a(t.replace(/ ?[\r\n]+/g," ")),o&&o()),!p){let w=n.replace(/\n+/g,`+$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`),E=!1,D=Dr(r,!0);i!=="folded"&&e!==R.BLOCK_FOLDED&&(D.onOverflow=()=>{E=!0});let x=En(`${S}${w}${d}`,u,Er,D);if(!E)return`>${_}${u}${x}`}return n=n.replace(/\n+/g,`$&${u}`),`|${_}-${u}${S}${n}${p}`}function Om(t,e,n,r){let{type:o,value:s}=t,{actualString:i,implicitKey:a,indent:c,indentStep:u,inFlow:d}=e;if(a&&s.includes(`-`)||d&&/[[\]{},]/.test(s))return Bt(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||d||!s.includes(`-`)?Bt(s,e):Er(t,e,n,r);if(!a&&!d&&o!==D.PLAIN&&s.includes(`-`))return Er(t,e,n,r);if(kr(s)){if(c==="")return e.forceBlockIndent=!0,Er(t,e,n,r);if(a&&c===u)return Bt(s,e)}let l=s.replace(/\n+/g,`$&-${c}`);if(i){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(l),{compat:p,tags:y}=e.doc.schema;if(y.some(f)||p?.some(f))return Bt(s,e)}return a?l:Sn(l,c,as,vr(e,!1))}function wt(t,e,n,r){let{implicitKey:o,inFlow:s}=e,i=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==D.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(i.value)&&(a=D.QUOTE_DOUBLE);let c=d=>{switch(d){case D.BLOCK_FOLDED:case D.BLOCK_LITERAL:return o||s?Bt(i.value,e):Er(i,e,n,r);case D.QUOTE_DOUBLE:return An(i.value,e);case D.QUOTE_SINGLE:return cs(i.value,e);case D.PLAIN:return Om(i,e,n,r);default:return null}},u=c(a);if(u===null){let{defaultKeyType:d,defaultStringType:l}=e.options,f=o&&d||l;if(u=c(f),u===null)throw new Error(`Unsupported default string type ${f}`)}return u}function Dr(t,e){let n=Object.assign({blockQuote:!0,commentString:wl,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},t.schema.toStringOptions,e),r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:r,options:n}}function Cm(t,e){if(e.tag){let o=t.filter(s=>s.tag===e.tag);if(o.length>0)return o.find(s=>s.format===e.format)??o[0]}let n,r;if(N(e)){r=e.value;let o=t.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===e.format)??o.find(s=>!s.format)}else r=e,n=t.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 Nm(t,e,{anchors:n,doc:r}){if(!r.directives)return"";let o=[],s=(N(t)||B(t))&&t.anchor;s&&_r(s)&&(n.add(s),o.push(`&${s}`));let i=t.tag??(e.default?null:e.tag);return i&&o.push(r.directives.tagString(i)),o.join(" ")}function Ke(t,e,n,r){if($(t))return t.toString(e,n,r);if(xe(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let o,s=L(t)?t:e.doc.createNode(t,{onTagObj:c=>o=c});o??(o=Cm(e.doc.schema.tags,s));let i=Nm(s,o,e);i.length>0&&(e.indentAtStart=(e.indentAtStart??0)+i.length+1);let a=typeof o.stringify=="function"?o.stringify(s,e,n,r):N(s)?wt(s,e,n,r):s.toString(e,n,r);return i?N(s)||a[0]==="{"||a[0]==="["?`${i} ${a}`:`${i}-${e.indent}${a}`:a}function xl({key:t,value:e},n,r,o){let{allNullValues:s,doc:i,indent:a,indentStep:c,options:{commentString:u,indentSeq:d,simpleKeys:l}}=n,f=L(t)&&t.comment||null;if(l){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(B(t)||!L(t)&&typeof t=="object"){let k="With simple keys, collection cannot be used as a key value";throw new Error(k)}}let p=!l&&(!t||f&&e==null&&!n.inFlow||B(t)||(N(t)?t.type===D.BLOCK_FOLDED||t.type===D.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(l||!s),indent:a+c});let y=!1,m=!1,h=Ke(t,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||e==null)return y&&r&&r(),h===""?"?":p?`? ${h}`:h}else if(s&&!l||e==null&&p)return h=`? ${h}`,f&&!y?h+=Ze(h,n.indent,u(f)):m&&o&&o(),h;y&&(f=null),p?(f&&(h+=Ze(h,n.indent,u(f))),h=`? ${h}-${a}:`):(h=`${h}:`,f&&(h+=Ze(h,n.indent,u(f))));let b,S,A;L(e)?(b=!!e.spaceBefore,S=e.commentBefore,A=e.comment):(b=!1,S=null,A=null,e&&typeof e=="object"&&(e=i.createNode(e))),n.implicitKey=!1,!p&&!f&&N(e)&&(n.indentAtStart=h.length+1),m=!1,!d&&c.length>=2&&!n.inFlow&&!p&&Ae(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let _=!1,w=Ke(e,n,()=>_=!0,()=>m=!0),E=" ";if(f||b||S){if(E=b?`-`:"",S){let k=u(S);E+=`-${ye(k,n.indent)}`}w===""&&!n.inFlow?E===`+${u}${S}${n}${d}`}function Lm(t,e,n,r){let{type:o,value:s}=t,{actualString:i,implicitKey:a,indent:c,indentStep:u,inFlow:p}=e;if(a&&s.includes(`+`)||p&&/[[\]{},]/.test(s))return jt(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||p||!s.includes(`+`)?jt(s,e):vr(t,e,n,r);if(!a&&!p&&o!==R.PLAIN&&s.includes(`+`))return vr(t,e,n,r);if(Rr(s)){if(c==="")return e.forceBlockIndent=!0,vr(t,e,n,r);if(a&&c===u)return jt(s,e)}let l=s.replace(/\n+/g,`$&+${c}`);if(i){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(l),{compat:d,tags:y}=e.doc.schema;if(y.some(f)||d?.some(f))return jt(s,e)}return a?l:En(l,c,ls,Dr(e,!1))}function _t(t,e,n,r){let{implicitKey:o,inFlow:s}=e,i=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==R.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(i.value)&&(a=R.QUOTE_DOUBLE);let c=p=>{switch(p){case R.BLOCK_FOLDED:case R.BLOCK_LITERAL:return o||s?jt(i.value,e):vr(i,e,n,r);case R.QUOTE_DOUBLE:return vn(i.value,e);case R.QUOTE_SINGLE:return fs(i.value,e);case R.PLAIN:return Lm(i,e,n,r);default:return null}},u=c(a);if(u===null){let{defaultKeyType:p,defaultStringType:l}=e.options,f=o&&p||l;if(u=c(f),u===null)throw new Error(`Unsupported default string type ${f}`)}return u}function kr(t,e){let n=Object.assign({blockQuote:!0,commentString:Dl,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},t.schema.toStringOptions,e),r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:r,options:n}}function Mm(t,e){if(e.tag){let o=t.filter(s=>s.tag===e.tag);if(o.length>0)return o.find(s=>s.format===e.format)??o[0]}let n,r;if(N(e)){r=e.value;let o=t.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===e.format)??o.find(s=>!s.format)}else r=e,n=t.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 Fm(t,e,{anchors:n,doc:r}){if(!r.directives)return"";let o=[],s=(N(t)||B(t))&&t.anchor;s&&xr(s)&&(n.add(s),o.push(`&${s}`));let i=t.tag??(e.default?null:e.tag);return i&&o.push(r.directives.tagString(i)),o.join(" ")}function Ke(t,e,n,r){if(T(t))return t.toString(e,n,r);if(xe(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let o,s=L(t)?t:e.doc.createNode(t,{onTagObj:c=>o=c});o??(o=Mm(e.doc.schema.tags,s));let i=Fm(s,o,e);i.length>0&&(e.indentAtStart=(e.indentAtStart??0)+i.length+1);let a=typeof o.stringify=="function"?o.stringify(s,e,n,r):N(s)?_t(s,e,n,r):s.toString(e,n,r);return i?N(s)||a[0]==="{"||a[0]==="["?`${i} ${a}`:`${i}+${e.indent}${a}`:a}function kl({key:t,value:e},n,r,o){let{allNullValues:s,doc:i,indent:a,indentStep:c,options:{commentString:u,indentSeq:p,simpleKeys:l}}=n,f=L(t)&&t.comment||null;if(l){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(B(t)||!L(t)&&typeof t=="object"){let D="With simple keys, collection cannot be used as a key value";throw new Error(D)}}let d=!l&&(!t||f&&e==null&&!n.inFlow||B(t)||(N(t)?t.type===R.BLOCK_FOLDED||t.type===R.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!d&&(l||!s),indent:a+c});let y=!1,m=!1,h=Ke(t,n,()=>y=!0,()=>m=!0);if(!d&&!n.inFlow&&h.length>1024){if(l)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");d=!0}if(n.inFlow){if(s||e==null)return y&&r&&r(),h===""?"?":d?`? ${h}`:h}else if(s&&!l||e==null&&d)return h=`? ${h}`,f&&!y?h+=Ze(h,n.indent,u(f)):m&&o&&o(),h;y&&(f=null),d?(f&&(h+=Ze(h,n.indent,u(f))),h=`? ${h}+${a}:`):(h=`${h}:`,f&&(h+=Ze(h,n.indent,u(f))));let b,S,A;L(e)?(b=!!e.spaceBefore,S=e.commentBefore,A=e.comment):(b=!1,S=null,A=null,e&&typeof e=="object"&&(e=i.createNode(e))),n.implicitKey=!1,!d&&!f&&N(e)&&(n.indentAtStart=h.length+1),m=!1,!p&&c.length>=2&&!n.inFlow&&!d&&Ae(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let _=!1,w=Ke(e,n,()=>_=!0,()=>m=!0),E=" ";if(f||b||S){if(E=b?`+`:"",S){let D=u(S);E+=`+${ye(D,n.indent)}`}w===""&&!n.inFlow?E===``&&A&&(E=``):E+=`-${n.indent}`}else if(!p&&B(e)){let k=w[0],x=w.indexOf(`-`),O=x!==-1,T=n.inFlow??e.flow??e.items.length===0;if(O||!T){let G=!1;if(O&&(k==="&"||k==="!")){let z=w.indexOf(" ");k==="&"&&z!==-1&&z<x&&w[z+1]==="!"&&(z=w.indexOf(" ",z+1)),(z===-1||x<z)&&(G=!0)}G||(E=`+${n.indent}`}else if(!d&&B(e)){let D=w[0],x=w.indexOf(`+`),O=x!==-1,$=n.inFlow??e.flow??e.items.length===0;if(O||!$){let G=!1;if(O&&(D==="&"||D==="!")){let z=w.indexOf(" ");D==="&"&&z!==-1&&z<x&&w[z+1]==="!"&&(z=w.indexOf(" ",z+1)),(z===-1||x<z)&&(G=!0)}G||(E=`${n.indent}`)}}else(w===""||w[0]===`-`)&&(E="");return h+=E+w,n.inFlow?_&&r&&r():A&&!_?h+=Ze(h,n.indent,u(A)):m&&o&&o(),h}function ls(t,e){(t==="debug"||t==="warn")&&console.warn(e)}var Rr="<<",Ee={identify:t=>t===Rr||typeof t=="symbol"&&t.description===Rr,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new D(Symbol(Rr)),{addToJSMap:ds}),stringify:()=>Rr},Sl=(t,e)=>(Ee.identify(e)||N(e)&&(!e.type||e.type===D.PLAIN)&&Ee.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===Ee.tag&&n.default);function ds(t,e,n){let r=Al(t,n);if(Ae(r))for(let o of r.items)fs(t,e,o);else if(Array.isArray(r))for(let o of r)fs(t,e,o);else fs(t,e,r)}function fs(t,e,n){let r=Al(t,n);if(!Se(r))throw new Error("Merge sources must be maps or map aliases");let o=r.toJSON(null,t,Map);for(let[s,i]of o)e instanceof Map?e.has(s)||e.set(s,i):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:i,writable:!0,enumerable:!0,configurable:!0});return e}function Al(t,e){return t&&xe(e)?e.resolve(t.doc,t):e}function Ir(t,e,{key:n,value:r}){if(L(n)&&n.addToJSMap)n.addToJSMap(t,e,r);else if(Sl(t,n))ds(t,e,r);else{let o=Y(n,"",t);if(e instanceof Map)e.set(o,Y(r,o,t));else if(e instanceof Set)e.add(o);else{let s=$m(n,o,t),i=Y(r,s,t);s in e?Object.defineProperty(e,s,{value:i,writable:!0,enumerable:!0,configurable:!0}):e[s]=i}}return e}function $m(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(L(t)&&n?.doc){let r=Dr(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=t.toString(r);if(!n.mapKeyWarned){let s=JSON.stringify(o);s.length>40&&(s=s.substring(0,36)+'..."'),ls(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(e)}function jt(t,e,n){let r=qe(t,void 0,n),o=qe(e,void 0,n);return new K(r,o)}var K=class t{constructor(e,n=null){Object.defineProperty(this,oe,{value:os}),this.key=e,this.value=n}clone(e){let{key:n,value:r}=this;return L(n)&&(n=n.clone(e)),L(r)&&(r=r.clone(e)),new t(n,r)}toJSON(e,n){let r=n?.mapAsMap?new Map:{};return Ir(n,r,this)}toString(e,n,r){return e?.doc?xl(this,e,n,r):JSON.stringify(this)}};function Cr(t,e,n){return(e.inFlow??t.flow?zm:Tm)(t,e,n)}function Tm({comment:t,items:e},n,{blockItemPrefix:r,flowChars:o,itemIndent:s,onChompKeep:i,onComment:a}){let{indent:c,options:{commentString:u}}=n,d=Object.assign({},n,{indent:s,type:null}),l=!1,f=[];for(let y=0;y<e.length;++y){let m=e[y],h=null;if(L(m))!l&&m.spaceBefore&&f.push(""),Or(n,f,m.commentBefore,l),m.comment&&(h=m.comment);else if($(m)){let S=L(m.key)?m.key:null;S&&(!l&&S.spaceBefore&&f.push(""),Or(n,f,S.commentBefore,l))}l=!1;let b=Ke(m,d,()=>h=null,()=>l=!0);h&&(b+=Ze(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?`+`)&&(E="");return h+=E+w,n.inFlow?_&&r&&r():A&&!_?h+=Ze(h,n.indent,u(A)):m&&o&&o(),h}function ps(t,e){(t==="debug"||t==="warn")&&console.warn(e)}var Ir="<<",Ee={identify:t=>t===Ir||typeof t=="symbol"&&t.description===Ir,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new R(Symbol(Ir)),{addToJSMap:hs}),stringify:()=>Ir},Il=(t,e)=>(Ee.identify(e)||N(e)&&(!e.type||e.type===R.PLAIN)&&Ee.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===Ee.tag&&n.default);function hs(t,e,n){let r=Ol(t,n);if(Ae(r))for(let o of r.items)ms(t,e,o);else if(Array.isArray(r))for(let o of r)ms(t,e,o);else ms(t,e,r)}function ms(t,e,n){let r=Ol(t,n);if(!Se(r))throw new Error("Merge sources must be maps or map aliases");let o=r.toJSON(null,t,Map);for(let[s,i]of o)e instanceof Map?e.has(s)||e.set(s,i):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:i,writable:!0,enumerable:!0,configurable:!0});return e}function Ol(t,e){return t&&xe(e)?e.resolve(t.doc,t):e}function Or(t,e,{key:n,value:r}){if(L(n)&&n.addToJSMap)n.addToJSMap(t,e,r);else if(Il(t,n))hs(t,e,r);else{let o=Y(n,"",t);if(e instanceof Map)e.set(o,Y(r,o,t));else if(e instanceof Set)e.add(o);else{let s=Zm(n,o,t),i=Y(r,s,t);s in e?Object.defineProperty(e,s,{value:i,writable:!0,enumerable:!0,configurable:!0}):e[s]=i}}return e}function Zm(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(L(t)&&n?.doc){let r=kr(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=t.toString(r);if(!n.mapKeyWarned){let s=JSON.stringify(o);s.length>40&&(s=s.substring(0,36)+'..."'),ps(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(e)}function Ut(t,e,n){let r=qe(t,void 0,n),o=qe(e,void 0,n);return new K(r,o)}var K=class t{constructor(e,n=null){Object.defineProperty(this,oe,{value:as}),this.key=e,this.value=n}clone(e){let{key:n,value:r}=this;return L(n)&&(n=n.clone(e)),L(r)&&(r=r.clone(e)),new t(n,r)}toJSON(e,n){let r=n?.mapAsMap?new Map:{};return Or(n,r,this)}toString(e,n,r){return e?.doc?kl(this,e,n,r):JSON.stringify(this)}};function Nr(t,e,n){return(e.inFlow??t.flow?jm:Bm)(t,e,n)}function Bm({comment:t,items:e},n,{blockItemPrefix:r,flowChars:o,itemIndent:s,onChompKeep:i,onComment:a}){let{indent:c,options:{commentString:u}}=n,p=Object.assign({},n,{indent:s,type:null}),l=!1,f=[];for(let y=0;y<e.length;++y){let m=e[y],h=null;if(L(m))!l&&m.spaceBefore&&f.push(""),Cr(n,f,m.commentBefore,l),m.comment&&(h=m.comment);else if(T(m)){let S=L(m.key)?m.key:null;S&&(!l&&S.spaceBefore&&f.push(""),Cr(n,f,S.commentBefore,l))}l=!1;let b=Ke(m,p,()=>h=null,()=>l=!0);h&&(b+=Ze(b,s,u(h))),l&&h&&(l=!1),f.push(r+b)}let d;if(f.length===0)d=o.start+o.end;else{d=f[0];for(let y=1;y<f.length;++y){let m=f[y];d+=m?`${c}${m}`:`-`}}return t?(p+=`-`+ye(u(t),c),a&&a()):l&&i&&i(),p}function zm({items:t},e,{flowChars:n,itemIndent:r}){let{indent:o,indentStep:s,flowCollectionPadding:i,options:{commentString:a}}=e;r+=s;let c=Object.assign({},e,{indent:r,inFlow:!0,type:null}),u=!1,d=0,l=[];for(let y=0;y<t.length;++y){let m=t[y],h=null;if(L(m))m.spaceBefore&&l.push(""),Or(e,l,m.commentBefore,!1),m.comment&&(h=m.comment);else if($(m)){let S=L(m.key)?m.key:null;S&&(S.spaceBefore&&l.push(""),Or(e,l,S.commentBefore,!1),S.comment&&(u=!0));let A=L(m.value)?m.value:null;A?(A.comment&&(h=A.comment),A.commentBefore&&(u=!0)):m.value==null&&S?.comment&&(h=S.comment)}h&&(u=!0);let b=Ke(m,c,()=>h=null);u||(u=l.length>d||b.includes(`-`)),y<t.length-1?b+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(u||(u=l.reduce((S,A)=>S+A.length+2,2)+(b.length+2)>e.options.lineWidth)),u&&(b+=",")),h&&(b+=Ze(b,r,a(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=e.options.lineWidth>0&&y>e.options.lineWidth}if(u){let y=f;for(let m of l)y+=m?`+`}}return t?(d+=`+`+ye(u(t),c),a&&a()):l&&i&&i(),d}function jm({items:t},e,{flowChars:n,itemIndent:r}){let{indent:o,indentStep:s,flowCollectionPadding:i,options:{commentString:a}}=e;r+=s;let c=Object.assign({},e,{indent:r,inFlow:!0,type:null}),u=!1,p=0,l=[];for(let y=0;y<t.length;++y){let m=t[y],h=null;if(L(m))m.spaceBefore&&l.push(""),Cr(e,l,m.commentBefore,!1),m.comment&&(h=m.comment);else if(T(m)){let S=L(m.key)?m.key:null;S&&(S.spaceBefore&&l.push(""),Cr(e,l,S.commentBefore,!1),S.comment&&(u=!0));let A=L(m.value)?m.value:null;A?(A.comment&&(h=A.comment),A.commentBefore&&(u=!0)):m.value==null&&S?.comment&&(h=S.comment)}h&&(u=!0);let b=Ke(m,c,()=>h=null);u||(u=l.length>p||b.includes(`+`)),y<t.length-1?b+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(u||(u=l.reduce((S,A)=>S+A.length+2,2)+(b.length+2)>e.options.lineWidth)),u&&(b+=",")),h&&(b+=Ze(b,r,a(h))),l.push(b),p=l.length}let{start:f,end:d}=n;if(l.length===0)return f+d;if(!u){let y=l.reduce((m,h)=>m+h.length+2,2);u=e.options.lineWidth>0&&y>e.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 Or({indent:t,options:{commentString:e}},n,r,o){if(r&&o&&(r=r.replace(/^\n+/,"")),r){let s=ye(e(r),t);n.push(s.trimStart())}}function at(t,e){let n=N(e)?e.value:e;for(let r of t)if($(r)&&(r.key===e||r.key===n||N(r.key)&&r.key.value===n))return r}var W=class extends Ft{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(_e,e),this.items=[]}static from(e,n,r){let{keepUndefined:o,replacer:s}=r,i=new this(e),a=(c,u)=>{if(typeof s=="function")u=s.call(n,c,u);else if(Array.isArray(s)&&!s.includes(c))return;(u!==void 0||o)&&i.items.push(jt(c,u,r))};if(n instanceof Map)for(let[c,u]of n)a(c,u);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&i.items.sort(e.sortMapEntries),i}add(e,n){let r;$(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new K(e,e?.value):r=new K(e.key,e.value);let o=at(this.items,r.key),s=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${r.key} already set`);N(o.value)&&Sr(r.value)?o.value.value=r.value:o.value=r.value}else if(s){let i=this.items.findIndex(a=>s(r,a)<0);i===-1?this.items.push(r):this.items.splice(i,0,r)}else this.items.push(r)}delete(e){let n=at(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let o=at(this.items,e)?.value;return(!n&&N(o)?o.value:o)??void 0}has(e){return!!at(this.items,e)}set(e,n){this.add(new K(e,n),!0)}toJSON(e,n,r){let o=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(o);for(let s of this.items)Ir(n,o,s);return o}toString(e,n,r){if(!e)return JSON.stringify(this);for(let o of this.items)if(!$(o))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Cr(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:n})}};var ve={collection:"map",default:!0,nodeClass:W,tag:"tag:yaml.org,2002:map",resolve(t,e){return Se(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>W.from(t,e,n)};var ee=class extends Ft{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Ge,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=Nr(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let r=Nr(e);if(typeof r!="number")return;let o=this.items[r];return!n&&N(o)?o.value:o}has(e){let n=Nr(e);return typeof n=="number"&&n<this.items.length}set(e,n){let r=Nr(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);let o=this.items[r];N(o)&&Sr(n)?o.value=n:this.items[r]=n}toJSON(e,n){let r=[];n?.onCreate&&n.onCreate(r);let o=0;for(let s of this.items)r.push(Y(s,String(o++),n));return r}toString(e,n,r){return e?Cr(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:r,onComment:n}):JSON.stringify(this)}static from(e,n,r){let{replacer:o}=r,s=new this(e);if(n&&Symbol.iterator in Object(n)){let i=0;for(let a of n){if(typeof o=="function"){let c=n instanceof Set?a:String(i++);a=o.call(n,c,a)}s.items.push(qe(a,void 0,r))}}return s}};function Nr(t){let e=N(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}var ke={collection:"seq",default:!0,nodeClass:ee,tag:"tag:yaml.org,2002:seq",resolve(t,e){return Ae(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>ee.from(t,e,n)};var ct={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,r){return e=Object.assign({actualString:!0},e),wt(t,e,n,r)}};var _t={identify:t=>t==null,createNode:()=>new D(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new D(null),stringify:({source:t},e)=>typeof t=="string"&&_t.test.test(t)?t:e.options.nullStr};var En={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new D(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&En.test.test(t)){let r=t[0]==="t"||t[0]==="T";if(e===r)return t}return e?n.options.trueStr:n.options.falseStr}};function te({format:t,minFractionDigits:e,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(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let i=s.indexOf(".");i<0&&(i=s.length,s+=".");let a=e-(s.length-i-1);for(;a-- >0;)s+="0"}return s}var $r={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:te},Tr={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():te(t)}},zr={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new D(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:te};var Pr=t=>typeof t=="bigint"||Number.isInteger(t),ps=(t,e,n,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),n);function El(t,e,n){let{value:r}=t;return Pr(r)&&r>=0?n+r.toString(e):te(t)}var Lr={identify:t=>Pr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>ps(t,2,8,n),stringify:t=>El(t,8,"0o")},Mr={identify:Pr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>ps(t,0,10,n),stringify:te},Fr={identify:t=>Pr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>ps(t,2,16,n),stringify:t=>El(t,16,"0x")};var vl=[ve,ke,ct,_t,En,Lr,Mr,Fr,$r,Tr,zr];function kl(t){return typeof t=="bigint"||Number.isInteger(t)}var Zr=({value:t})=>JSON.stringify(t),Pm=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:Zr},{identify:t=>t==null,createNode:()=>new D(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Zr},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:Zr},{identify:kl,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:n})=>n?BigInt(t):parseInt(t,10),stringify:({value:t})=>kl(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:Zr}],Lm={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Dl=[ve,ke].concat(Pm,Lm);var vn={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof atob=="function"){let n=atob(t.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 e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:n},r,o,s){if(!n)return"";let i=n,a;if(typeof btoa=="function"){let c="";for(let u=0;u<i.length;++u)c+=String.fromCharCode(i[u]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=D.BLOCK_LITERAL),e!==D.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),u=Math.ceil(a.length/c),d=new Array(u);for(let l=0,f=0;l<u;++l,f+=c)d[l]=a.substr(f,c);a=d.join(e===D.BLOCK_LITERAL?`-`:" ")}return wt({comment:t,type:e,value:a},r,o,s)}};function ms(t,e){if(Ae(t))for(let n=0;n<t.items.length;++n){let r=t.items[n];if(!$(r)){if(Se(r)){r.items.length>1&&e("Each pair must have its own sequence indicator");let o=r.items[0]||new K(new D(null));if(r.commentBefore&&(o.key.commentBefore=o.key.commentBefore?`${r.commentBefore}+${o}${d}`}else return`${f}${i}${l.join(" ")}${i}${d}`}function Cr({indent:t,options:{commentString:e}},n,r,o){if(r&&o&&(r=r.replace(/^\n+/,"")),r){let s=ye(e(r),t);n.push(s.trimStart())}}function at(t,e){let n=N(e)?e.value:e;for(let r of t)if(T(r)&&(r.key===e||r.key===n||N(r.key)&&r.key.value===n))return r}var W=class extends Zt{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(_e,e),this.items=[]}static from(e,n,r){let{keepUndefined:o,replacer:s}=r,i=new this(e),a=(c,u)=>{if(typeof s=="function")u=s.call(n,c,u);else if(Array.isArray(s)&&!s.includes(c))return;(u!==void 0||o)&&i.items.push(Ut(c,u,r))};if(n instanceof Map)for(let[c,u]of n)a(c,u);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&i.items.sort(e.sortMapEntries),i}add(e,n){let r;T(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new K(e,e?.value):r=new K(e.key,e.value);let o=at(this.items,r.key),s=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${r.key} already set`);N(o.value)&&Ar(r.value)?o.value.value=r.value:o.value=r.value}else if(s){let i=this.items.findIndex(a=>s(r,a)<0);i===-1?this.items.push(r):this.items.splice(i,0,r)}else this.items.push(r)}delete(e){let n=at(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let o=at(this.items,e)?.value;return(!n&&N(o)?o.value:o)??void 0}has(e){return!!at(this.items,e)}set(e,n){this.add(new K(e,n),!0)}toJSON(e,n,r){let o=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(o);for(let s of this.items)Or(n,o,s);return o}toString(e,n,r){if(!e)return JSON.stringify(this);for(let o of this.items)if(!T(o))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Nr(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:n})}};var ve={collection:"map",default:!0,nodeClass:W,tag:"tag:yaml.org,2002:map",resolve(t,e){return Se(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>W.from(t,e,n)};var ee=class extends Zt{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Ge,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=Tr(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let r=Tr(e);if(typeof r!="number")return;let o=this.items[r];return!n&&N(o)?o.value:o}has(e){let n=Tr(e);return typeof n=="number"&&n<this.items.length}set(e,n){let r=Tr(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);let o=this.items[r];N(o)&&Ar(n)?o.value=n:this.items[r]=n}toJSON(e,n){let r=[];n?.onCreate&&n.onCreate(r);let o=0;for(let s of this.items)r.push(Y(s,String(o++),n));return r}toString(e,n,r){return e?Nr(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:r,onComment:n}):JSON.stringify(this)}static from(e,n,r){let{replacer:o}=r,s=new this(e);if(n&&Symbol.iterator in Object(n)){let i=0;for(let a of n){if(typeof o=="function"){let c=n instanceof Set?a:String(i++);a=o.call(n,c,a)}s.items.push(qe(a,void 0,r))}}return s}};function Tr(t){let e=N(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}var De={collection:"seq",default:!0,nodeClass:ee,tag:"tag:yaml.org,2002:seq",resolve(t,e){return Ae(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>ee.from(t,e,n)};var ct={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,r){return e=Object.assign({actualString:!0},e),_t(t,e,n,r)}};var xt={identify:t=>t==null,createNode:()=>new R(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new R(null),stringify:({source:t},e)=>typeof t=="string"&&xt.test.test(t)?t:e.options.nullStr};var Dn={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new R(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&Dn.test.test(t)){let r=t[0]==="t"||t[0]==="T";if(e===r)return t}return e?n.options.trueStr:n.options.falseStr}};function te({format:t,minFractionDigits:e,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(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let i=s.indexOf(".");i<0&&(i=s.length,s+=".");let a=e-(s.length-i-1);for(;a-- >0;)s+="0"}return s}var $r={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:te},zr={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():te(t)}},Pr={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new R(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:te};var Lr=t=>typeof t=="bigint"||Number.isInteger(t),ys=(t,e,n,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),n);function Cl(t,e,n){let{value:r}=t;return Lr(r)&&r>=0?n+r.toString(e):te(t)}var Mr={identify:t=>Lr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>ys(t,2,8,n),stringify:t=>Cl(t,8,"0o")},Fr={identify:Lr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>ys(t,0,10,n),stringify:te},Zr={identify:t=>Lr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>ys(t,2,16,n),stringify:t=>Cl(t,16,"0x")};var Nl=[ve,De,ct,xt,Dn,Mr,Fr,Zr,$r,zr,Pr];function Tl(t){return typeof t=="bigint"||Number.isInteger(t)}var Br=({value:t})=>JSON.stringify(t),Um=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:Br},{identify:t=>t==null,createNode:()=>new R(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Br},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:Br},{identify:Tl,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:n})=>n?BigInt(t):parseInt(t,10),stringify:({value:t})=>Tl(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:Br}],Qm={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},$l=[ve,De].concat(Um,Qm);var Rn={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof atob=="function"){let n=atob(t.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 e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:n},r,o,s){if(!n)return"";let i=n,a;if(typeof btoa=="function"){let c="";for(let u=0;u<i.length;++u)c+=String.fromCharCode(i[u]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=R.BLOCK_LITERAL),e!==R.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),u=Math.ceil(a.length/c),p=new Array(u);for(let l=0,f=0;l<u;++l,f+=c)p[l]=a.substr(f,c);a=p.join(e===R.BLOCK_LITERAL?`+`:" ")}return _t({comment:t,type:e,value:a},r,o,s)}};function gs(t,e){if(Ae(t))for(let n=0;n<t.items.length;++n){let r=t.items[n];if(!T(r)){if(Se(r)){r.items.length>1&&e("Each pair must have its own sequence indicator");let o=r.items[0]||new K(new R(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}t.items[n]=$(r)?r:new K(r)}}else e("Expected a sequence for this tag");return t}function hs(t,e,n){let{replacer:r}=n,o=new ee(t);o.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let i of e){typeof r=="function"&&(i=r.call(e,String(s++),i));let a,c;if(Array.isArray(i))if(i.length===2)a=i[0],c=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)a=u[0],c=i[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=i;o.items.push(jt(a,c,n))}return o}var kn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ms,createNode:hs};var Ut=class t extends ee{constructor(){super(),this.add=W.prototype.add.bind(this),this.delete=W.prototype.delete.bind(this),this.get=W.prototype.get.bind(this),this.has=W.prototype.has.bind(this),this.set=W.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let r=new Map;n?.onCreate&&n.onCreate(r);for(let o of this.items){let s,i;if($(o)?(s=Y(o.key,"",n),i=Y(o.value,s,n)):s=Y(o,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,i)}return r}static from(e,n,r){let o=hs(e,n,r),s=new this;return s.items=o.items,s}};Ut.tag="tag:yaml.org,2002:omap";var Dn={collection:"seq",identify:t=>t instanceof Map,nodeClass:Ut,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=ms(t,e),r=[];for(let{key:o}of n.items)N(o)&&(r.includes(o.value)?e(`Ordered maps must not include duplicate keys: ${o.value}`):r.push(o.value));return Object.assign(new Ut,n)},createNode:(t,e,n)=>Ut.from(t,e,n)};function Rl({value:t,source:e},n){return e&&(t?ys:gs).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var ys={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new D(!0),stringify:Rl},gs={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new D(!1),stringify:Rl};var Il={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:te},Ol={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():te(t)}},Cl={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new D(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let r=t.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:te};var Rn=t=>typeof t=="bigint"||Number.isInteger(t);function Br(t,e,n,{intAsBigInt:r}){let o=t[0];if((o==="-"||o==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),r){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let i=BigInt(t);return o==="-"?BigInt(-1)*i:i}let s=parseInt(t,n);return o==="-"?-1*s:s}function bs(t,e,n){let{value:r}=t;if(Rn(r)){let o=r.toString(e);return r<0?"-"+n+o.substr(1):n+o}return te(t)}var Nl={identify:Rn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>Br(t,2,2,n),stringify:t=>bs(t,2,"0b")},$l={identify:Rn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>Br(t,1,8,n),stringify:t=>bs(t,8,"0")},Tl={identify:Rn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>Br(t,0,10,n),stringify:te},zl={identify:Rn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>Br(t,2,16,n),stringify:t=>bs(t,16,"0x")};var Qt=class t extends W{constructor(e){super(e),this.tag=t.tag}add(e){let n;$(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new K(e.key,null):n=new K(e,null),at(this.items,n.key)||this.items.push(n)}get(e,n){let r=at(this.items,e);return!n&&$(r)?N(r.key)?r.key.value:r.key:r}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=at(this.items,e);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new K(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(e,n,r){let{replacer:o}=r,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let i of n)typeof o=="function"&&(i=o.call(n,i,i)),s.items.push(jt(i,null,r));return s}};Qt.tag="tag:yaml.org,2002:set";var In={collection:"map",identify:t=>t instanceof Set,nodeClass:Qt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>Qt.from(t,e,n),resolve(t,e){if(Se(t)){if(t.hasAllNullValues(!0))return Object.assign(new Qt,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};function ws(t,e){let n=t[0],r=n==="-"||n==="+"?t.substring(1):t,o=i=>e?BigInt(i):Number(i),s=r.replace(/_/g,"").split(":").reduce((i,a)=>i*o(60)+o(a),o(0));return n==="-"?o(-1)*s:s}function Pl(t){let{value:e}=t,n=i=>i;if(typeof e=="bigint")n=i=>BigInt(i);else if(isNaN(e)||!isFinite(e))return te(t);let r="";e<0&&(r="-",e*=n(-1));let o=n(60),s=[e%o];return e<60?s.unshift(0):(e=(e-s[0])/o,s.unshift(e%o),e>=60&&(e=(e-s[0])/o,s.unshift(e))),r+s.map(i=>String(i).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var jr={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>ws(t,n),stringify:Pl},Ur={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>ws(t,!1),stringify:Pl},Vt={identify:t=>t 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(t){let e=t.match(Vt.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,o,s,i,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,u=Date.UTC(n,r-1,o,s||0,i||0,a||0,c),d=e[8];if(d&&d!=="Z"){let l=ws(d,!1);Math.abs(l)<30&&(l*=60),u-=6e4*l}return new Date(u)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};var _s=[ve,ke,ct,_t,ys,gs,Nl,$l,Tl,zl,Il,Ol,Cl,vn,Ee,Dn,kn,In,jr,Ur,Vt];var Ll=new Map([["core",vl],["failsafe",[ve,ke,ct]],["json",Dl],["yaml11",_s],["yaml-1.1",_s]]),Ml={binary:vn,bool:En,float:zr,floatExp:Tr,floatNaN:$r,floatTime:Ur,int:Mr,intHex:Fr,intOct:Lr,intTime:jr,map:ve,merge:Ee,null:_t,omap:Dn,pairs:kn,seq:ke,set:In,timestamp:Vt},Fl={"tag:yaml.org,2002:binary":vn,"tag:yaml.org,2002:merge":Ee,"tag:yaml.org,2002:omap":Dn,"tag:yaml.org,2002:pairs":kn,"tag:yaml.org,2002:set":In,"tag:yaml.org,2002:timestamp":Vt};function Qr(t,e,n){let r=Ll.get(e);if(r&&!t)return n&&!r.includes(Ee)?r.concat(Ee):r.slice();let o=r;if(!o)if(Array.isArray(t))o=[];else{let s=Array.from(Ll.keys()).filter(i=>i!=="yaml11").map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(t))for(let s of t)o=o.concat(s);else typeof t=="function"&&(o=t(o.slice()));return n&&(o=o.concat(Ee)),o.reduce((s,i)=>{let a=typeof i=="string"?Ml[i]:i;if(!a){let c=JSON.stringify(i),u=Object.keys(Ml).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${u}`)}return s.includes(a)||s.push(a),s},[])}var Mm=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,On=class t{constructor({compat:e,customTags:n,merge:r,resolveKnownTags:o,schema:s,sortMapEntries:i,toStringDefaults:a}){this.compat=Array.isArray(e)?Qr(e,"compat"):e?Qr(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=o?Fl:{},this.tags=Qr(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,_e,{value:ve}),Object.defineProperty(this,pe,{value:ct}),Object.defineProperty(this,Ge,{value:ke}),this.sortMapEntries=typeof i=="function"?i:i===!0?Mm:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function Zl(t,e){let n=[],r=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),r=!0):t.directives.docStart&&(r=!0)}r&&n.push("---");let o=Dr(t,e),{commentString:s}=o.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(ye(c,""))}let i=!1,a=null;if(t.contents){if(L(t.contents)){if(t.contents.spaceBefore&&r&&n.push(""),t.contents.commentBefore){let d=s(t.contents.commentBefore);n.push(ye(d,""))}o.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>i=!0,u=Ke(t.contents,o,()=>a=null,c);a&&(u+=Ze(u,"",s(a))),(u[0]==="|"||u[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${u}`:n.push(u)}else n.push(Ke(t.contents,o));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(`+${s.comment}`:r.comment}r=o}t.items[n]=T(r)?r:new K(r)}}else e("Expected a sequence for this tag");return t}function bs(t,e,n){let{replacer:r}=n,o=new ee(t);o.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let i of e){typeof r=="function"&&(i=r.call(e,String(s++),i));let a,c;if(Array.isArray(i))if(i.length===2)a=i[0],c=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)a=u[0],c=i[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=i;o.items.push(Ut(a,c,n))}return o}var kn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:gs,createNode:bs};var Qt=class t extends ee{constructor(){super(),this.add=W.prototype.add.bind(this),this.delete=W.prototype.delete.bind(this),this.get=W.prototype.get.bind(this),this.has=W.prototype.has.bind(this),this.set=W.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let r=new Map;n?.onCreate&&n.onCreate(r);for(let o of this.items){let s,i;if(T(o)?(s=Y(o.key,"",n),i=Y(o.value,s,n)):s=Y(o,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,i)}return r}static from(e,n,r){let o=bs(e,n,r),s=new this;return s.items=o.items,s}};Qt.tag="tag:yaml.org,2002:omap";var In={collection:"seq",identify:t=>t instanceof Map,nodeClass:Qt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=gs(t,e),r=[];for(let{key:o}of n.items)N(o)&&(r.includes(o.value)?e(`Ordered maps must not include duplicate keys: ${o.value}`):r.push(o.value));return Object.assign(new Qt,n)},createNode:(t,e,n)=>Qt.from(t,e,n)};function zl({value:t,source:e},n){return e&&(t?ws:_s).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var ws={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new R(!0),stringify:zl},_s={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new R(!1),stringify:zl};var Pl={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:te},Ll={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():te(t)}},Ml={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new R(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let r=t.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:te};var On=t=>typeof t=="bigint"||Number.isInteger(t);function jr(t,e,n,{intAsBigInt:r}){let o=t[0];if((o==="-"||o==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),r){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let i=BigInt(t);return o==="-"?BigInt(-1)*i:i}let s=parseInt(t,n);return o==="-"?-1*s:s}function xs(t,e,n){let{value:r}=t;if(On(r)){let o=r.toString(e);return r<0?"-"+n+o.substr(1):n+o}return te(t)}var Fl={identify:On,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>jr(t,2,2,n),stringify:t=>xs(t,2,"0b")},Zl={identify:On,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>jr(t,1,8,n),stringify:t=>xs(t,8,"0")},Bl={identify:On,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>jr(t,0,10,n),stringify:te},jl={identify:On,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>jr(t,2,16,n),stringify:t=>xs(t,16,"0x")};var Vt=class t extends W{constructor(e){super(e),this.tag=t.tag}add(e){let n;T(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new K(e.key,null):n=new K(e,null),at(this.items,n.key)||this.items.push(n)}get(e,n){let r=at(this.items,e);return!n&&T(r)?N(r.key)?r.key.value:r.key:r}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=at(this.items,e);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new K(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(e,n,r){let{replacer:o}=r,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let i of n)typeof o=="function"&&(i=o.call(n,i,i)),s.items.push(Ut(i,null,r));return s}};Vt.tag="tag:yaml.org,2002:set";var Cn={collection:"map",identify:t=>t instanceof Set,nodeClass:Vt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>Vt.from(t,e,n),resolve(t,e){if(Se(t)){if(t.hasAllNullValues(!0))return Object.assign(new Vt,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};function Ss(t,e){let n=t[0],r=n==="-"||n==="+"?t.substring(1):t,o=i=>e?BigInt(i):Number(i),s=r.replace(/_/g,"").split(":").reduce((i,a)=>i*o(60)+o(a),o(0));return n==="-"?o(-1)*s:s}function Ul(t){let{value:e}=t,n=i=>i;if(typeof e=="bigint")n=i=>BigInt(i);else if(isNaN(e)||!isFinite(e))return te(t);let r="";e<0&&(r="-",e*=n(-1));let o=n(60),s=[e%o];return e<60?s.unshift(0):(e=(e-s[0])/o,s.unshift(e%o),e>=60&&(e=(e-s[0])/o,s.unshift(e))),r+s.map(i=>String(i).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Ur={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>Ss(t,n),stringify:Ul},Qr={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>Ss(t,!1),stringify:Ul},Gt={identify:t=>t 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(t){let e=t.match(Gt.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,o,s,i,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,u=Date.UTC(n,r-1,o,s||0,i||0,a||0,c),p=e[8];if(p&&p!=="Z"){let l=Ss(p,!1);Math.abs(l)<30&&(l*=60),u-=6e4*l}return new Date(u)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};var As=[ve,De,ct,xt,ws,_s,Fl,Zl,Bl,jl,Pl,Ll,Ml,Rn,Ee,In,kn,Cn,Ur,Qr,Gt];var Ql=new Map([["core",Nl],["failsafe",[ve,De,ct]],["json",$l],["yaml11",As],["yaml-1.1",As]]),Vl={binary:Rn,bool:Dn,float:Pr,floatExp:zr,floatNaN:$r,floatTime:Qr,int:Fr,intHex:Zr,intOct:Mr,intTime:Ur,map:ve,merge:Ee,null:xt,omap:In,pairs:kn,seq:De,set:Cn,timestamp:Gt},Gl={"tag:yaml.org,2002:binary":Rn,"tag:yaml.org,2002:merge":Ee,"tag:yaml.org,2002:omap":In,"tag:yaml.org,2002:pairs":kn,"tag:yaml.org,2002:set":Cn,"tag:yaml.org,2002:timestamp":Gt};function Vr(t,e,n){let r=Ql.get(e);if(r&&!t)return n&&!r.includes(Ee)?r.concat(Ee):r.slice();let o=r;if(!o)if(Array.isArray(t))o=[];else{let s=Array.from(Ql.keys()).filter(i=>i!=="yaml11").map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(t))for(let s of t)o=o.concat(s);else typeof t=="function"&&(o=t(o.slice()));return n&&(o=o.concat(Ee)),o.reduce((s,i)=>{let a=typeof i=="string"?Vl[i]:i;if(!a){let c=JSON.stringify(i),u=Object.keys(Vl).map(p=>JSON.stringify(p)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${u}`)}return s.includes(a)||s.push(a),s},[])}var Vm=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,Nn=class t{constructor({compat:e,customTags:n,merge:r,resolveKnownTags:o,schema:s,sortMapEntries:i,toStringDefaults:a}){this.compat=Array.isArray(e)?Vr(e,"compat"):e?Vr(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=o?Gl:{},this.tags=Vr(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,_e,{value:ve}),Object.defineProperty(this,pe,{value:ct}),Object.defineProperty(this,Ge,{value:De}),this.sortMapEntries=typeof i=="function"?i:i===!0?Vm:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function Jl(t,e){let n=[],r=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),r=!0):t.directives.docStart&&(r=!0)}r&&n.push("---");let o=kr(t,e),{commentString:s}=o.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(ye(c,""))}let i=!1,a=null;if(t.contents){if(L(t.contents)){if(t.contents.spaceBefore&&r&&n.push(""),t.contents.commentBefore){let p=s(t.contents.commentBefore);n.push(ye(p,""))}o.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>i=!0,u=Ke(t.contents,o,()=>a=null,c);a&&(u+=Ze(u,"",s(a))),(u[0]==="|"||u[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${u}`:n.push(u)}else n.push(Ke(t.contents,o));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(``)?(n.push("..."),n.push(ye(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=t.comment;c&&i&&(c=c.replace(/^\n+/,"")),c&&((!i||a)&&n[n.length-1]!==""&&n.push(""),n.push(ye(s(c),"")))}return n.join(``)+`-`}var ut=class t{constructor(e,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,oe,{value:gr});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 Fe({version:i}),this.setSchema(i,r),this.contents=e===void 0?null:this.createNode(e,o,r)}clone(){let e=Object.create(t.prototype,{[oe]:{value:gr}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=L(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Gt(this.contents)&&this.contents.add(e)}addIn(e,n){Gt(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let r=ss(this);e.anchor=!n||r.has(n)?is(n||"a",r):n}return new Je(e.anchor)}createNode(e,n,r){let o;if(typeof n=="function")e=n.call({"":e},"",e),o=n;else if(Array.isArray(n)){let h=S=>typeof S=="number"||S instanceof String||S 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:a,keepUndefined:c,onTagObj:u,tag:d}=r??{},{onAnchor:l,setAnchors:f,sourceObjects:p}=bl(this,i||"a"),y={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:l,onTagObj:u,replacer:o,schema:this.schema,sourceObjects:p},m=qe(e,d,y);return a&&B(m)&&(m.flow=!0),f(),m}createPair(e,n,r={}){let o=this.createNode(e,null,r),s=this.createNode(n,null,r);return new K(o,s)}delete(e){return Gt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Zt(e)?this.contents==null?!1:(this.contents=null,!0):Gt(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return B(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return Zt(e)?!n&&N(this.contents)?this.contents.value:this.contents:B(this.contents)?this.contents.getIn(e,n):void 0}has(e){return B(this.contents)?this.contents.has(e):!1}hasIn(e){return Zt(e)?this.contents!==void 0:B(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=_n(this.schema,[e],n):Gt(this.contents)&&this.contents.set(e,n)}setIn(e,n){Zt(e)?this.contents=n:this.contents==null?this.contents=_n(this.schema,Array.from(e),n):Gt(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let r;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Fe({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Fe({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let o=JSON.stringify(e);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 On(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:r,maxAliasCount:o,onAnchor:s,reviver:i}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof o=="number"?o:100},c=Y(this.contents,n??"",a);if(typeof s=="function")for(let{count:u,res:d}of a.anchors.values())s(d,u);return typeof i=="function"?st(i,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return Zl(this,e)}};function Gt(t){if(B(t))return!0;throw new Error("Expected a YAML collection as document contents")}var Cn=class extends Error{constructor(e,n,r,o){super(),this.name=e,this.code=r,this.message=o,this.pos=n}},De=class extends Cn{constructor(e,n,r){super("YAMLParseError",e,n,r)}},Nn=class extends Cn{constructor(e,n,r){super("YAMLWarning",e,n,r)}},xs=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:r,col:o}=n.linePos[0];n.message+=` at line ${r}, column ${o}`;let s=o-1,i=t.substring(e.lineStarts[r-1],e.lineStarts[r]).replace(/[\n\r]+$/,"");if(s>=60&&i.length>80){let a=Math.min(s-39,i.length-79);i="\u2026"+i.substring(a),s-=a-1}if(i.length>80&&(i=i.substring(0,79)+"\u2026"),r>1&&/^ *$/.test(i.substring(0,s))){let a=t.substring(e.lineStarts[r-2],e.lineStarts[r-1]);a.length>80&&(a=a.substring(0,79)+`\u2026+`}var ut=class t{constructor(e,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,oe,{value:br});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 Fe({version:i}),this.setSchema(i,r),this.contents=e===void 0?null:this.createNode(e,o,r)}clone(){let e=Object.create(t.prototype,{[oe]:{value:br}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=L(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Jt(this.contents)&&this.contents.add(e)}addIn(e,n){Jt(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let r=cs(this);e.anchor=!n||r.has(n)?us(n||"a",r):n}return new Je(e.anchor)}createNode(e,n,r){let o;if(typeof n=="function")e=n.call({"":e},"",e),o=n;else if(Array.isArray(n)){let h=S=>typeof S=="number"||S instanceof String||S 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:a,keepUndefined:c,onTagObj:u,tag:p}=r??{},{onAnchor:l,setAnchors:f,sourceObjects:d}=vl(this,i||"a"),y={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:l,onTagObj:u,replacer:o,schema:this.schema,sourceObjects:d},m=qe(e,p,y);return a&&B(m)&&(m.flow=!0),f(),m}createPair(e,n,r={}){let o=this.createNode(e,null,r),s=this.createNode(n,null,r);return new K(o,s)}delete(e){return Jt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Bt(e)?this.contents==null?!1:(this.contents=null,!0):Jt(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return B(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return Bt(e)?!n&&N(this.contents)?this.contents.value:this.contents:B(this.contents)?this.contents.getIn(e,n):void 0}has(e){return B(this.contents)?this.contents.has(e):!1}hasIn(e){return Bt(e)?this.contents!==void 0:B(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=Sn(this.schema,[e],n):Jt(this.contents)&&this.contents.set(e,n)}setIn(e,n){Bt(e)?this.contents=n:this.contents==null?this.contents=Sn(this.schema,Array.from(e),n):Jt(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let r;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Fe({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Fe({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let o=JSON.stringify(e);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 Nn(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:r,maxAliasCount:o,onAnchor:s,reviver:i}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof o=="number"?o:100},c=Y(this.contents,n??"",a);if(typeof s=="function")for(let{count:u,res:p}of a.anchors.values())s(p,u);return typeof i=="function"?st(i,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return Jl(this,e)}};function Jt(t){if(B(t))return!0;throw new Error("Expected a YAML collection as document contents")}var Tn=class extends Error{constructor(e,n,r,o){super(),this.name=e,this.code=r,this.message=o,this.pos=n}},Re=class extends Tn{constructor(e,n,r){super("YAMLParseError",e,n,r)}},$n=class extends Tn{constructor(e,n,r){super("YAMLWarning",e,n,r)}},Es=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:r,col:o}=n.linePos[0];n.message+=` at line ${r}, column ${o}`;let s=o-1,i=t.substring(e.lineStarts[r-1],e.lineStarts[r]).replace(/[\n\r]+$/,"");if(s>=60&&i.length>80){let a=Math.min(s-39,i.length-79);i="\u2026"+i.substring(a),s-=a-1}if(i.length>80&&(i=i.substring(0,79)+"\u2026"),r>1&&/^ *$/.test(i.substring(0,s))){let a=t.substring(e.lineStarts[r-2],e.lineStarts[r-1]);a.length>80&&(a=a.substring(0,79)+`\u2026`),i=a+i}if(/[^ ]/.test(i)){let a=1,c=n.linePos[1];c?.line===r&&c.col>o&&(a=Math.max(1,Math.min(c.col-o,80-s)));let u=" ".repeat(s)+"^".repeat(a);n.message+=`:${i}${u}-`}};function Be(t,{flow:e,indicator:n,next:r,offset:o,onError:s,parentIndent:i,startOnNewline:a}){let c=!1,u=a,d=a,l="",f="",p=!1,y=!1,m=null,h=null,b=null,S=null,A=null,_=null,w=null;for(let x of t)switch(y&&(x.type!=="space"&&x.type!=="newline"&&x.type!=="comma"&&s(x.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),m&&(u&&x.type!=="comment"&&x.type!=="newline"&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),x.type){case"space":!e&&(n!=="doc-start"||r?.type!=="flow-collection")&&x.source.includes(" ")&&(m=x),d=!0;break;case"comment":{d||s(x,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let O=x.source.substring(1)||" ";l?l+=f+O:l=O,f="",u=!1;break}case"newline":u?l?l+=x.source:(!_||n!=="seq-item-ind")&&(c=!0):f+=x.source,u=!0,p=!0,(h||b)&&(S=x),d=!0;break;case"anchor":h&&s(x,"MULTIPLE_ANCHORS","A node can have at most one anchor"),x.source.endsWith(":")&&s(x.offset+x.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),h=x,w??(w=x.offset),u=!1,d=!1,y=!0;break;case"tag":{b&&s(x,"MULTIPLE_TAGS","A node can have at most one tag"),b=x,w??(w=x.offset),u=!1,d=!1,y=!0;break}case n:(h||b)&&s(x,"BAD_PROP_ORDER",`Anchors and tags must be after the ${x.source} indicator`),_&&s(x,"UNEXPECTED_TOKEN",`Unexpected ${x.source} in ${e??"collection"}`),_=x,u=n==="seq-item-ind"||n==="explicit-key-ind",d=!1;break;case"comma":if(e){A&&s(x,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),A=x,u=!1,d=!1;break}default:s(x,"UNEXPECTED_TOKEN",`Unexpected ${x.type} token`),u=!1,d=!1}let E=t[t.length-1],k=E?E.offset+E.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:A,found:_,spaceBefore:c,comment:l,hasNewline:p,anchor:h,tag:b,newlineAfterProp:S,end:k,start:w??k}}function lt(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`-`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(lt(e.key)||lt(e.value))return!0}return!1;default:return!0}}function $n(t,e,n){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&<(e)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function Vr(t,e,n){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let o=typeof r=="function"?r:(s,i)=>s===i||N(s)&&N(i)&&s.value===i.value;return e.some(s=>o(s.key,n))}var Bl="All mapping items must start at the same column";function jl({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=s?.nodeClass??W,a=new i(n.schema);n.atRoot&&(n.atRoot=!1);let c=r.offset,u=null;for(let d of r.items){let{start:l,key:f,sep:p,value:y}=d,m=Be(l,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:o,parentIndent:r.indent,startOnNewline:!0}),h=!m.found;if(h){if(f&&(f.type==="block-seq"?o(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&o(c,"BAD_INDENT",Bl)),!m.anchor&&!m.tag&&!p){u=m.end,m.comment&&(a.comment?a.comment+=`-`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||lt(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(c,"BAD_INDENT",Bl);n.atKey=!0;let b=m.end,S=f?t(n,f,m,o):e(n,b,l,null,m,o);n.schema.compat&&$n(r.indent,f,o),n.atKey=!1,Vr(n,a.items,S)&&o(b,"DUPLICATE_KEY","Map keys must be unique");let A=Be(p??[],{indicator:"map-value-ind",next:y,offset:S.range[2],onError:o,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=A.end,A.found){h&&(y?.type==="block-map"&&!A.hasNewline&&o(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&m.start<A.found.offset-1024&&o(S.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let _=y?t(n,y,A,o):e(n,c,p,null,A,o);n.schema.compat&&$n(r.indent,y,o),c=_.range[2];let w=new K(S,_);n.options.keepSourceTokens&&(w.srcToken=d),a.items.push(w)}else{h&&o(S.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),A.comment&&(S.comment?S.comment+=`-`+A.comment:S.comment=A.comment);let _=new K(S);n.options.keepSourceTokens&&(_.srcToken=d),a.items.push(_)}}return u&&u<c&&o(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,c,u??c],a}function Ul({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=s?.nodeClass??ee,a=new i(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=r.offset,u=null;for(let{start:d,value:l}of r.items){let f=Be(d,{indicator:"seq-item-ind",next:l,offset:c,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(c,"MISSING_CHAR","Sequence item without - indicator");else{u=f.end,f.comment&&(a.comment=f.comment);continue}let p=l?t(n,l,f,o):e(n,f.end,d,null,f,o);n.schema.compat&&$n(r.indent,l,o),c=p.range[2],a.items.push(p)}return a.range=[r.offset,c,u??c],a}function je(t,e,n,r){let o="";if(t){let s=!1,i="";for(let a of t){let{source:c,type:u}=a;switch(u){case"space":s=!0;break;case"comment":{n&&!s&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=c.substring(1)||" ";o?o+=i+d:o=d,i="";break}case"newline":o&&(i+=c),s=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=c.length}}return{comment:o,offset:e}}var Ss="Block collections are not allowed within flow collections",As=t=>t&&(t.type==="block-map"||t.type==="block-seq");function Ql({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=r.start.source==="{",a=i?"flow map":"flow sequence",c=s?.nodeClass??(i?W:ee),u=new c(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:S,key:A,sep:_,value:w}=b,E=Be(S,{flow:a,indicator:"explicit-key-ind",next:A??_?.[0],offset:l,onError:o,parentIndent:r.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!_&&!w){h===0&&E.comma?o(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):h<r.items.length-1&&o(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),E.comment&&(u.comment?u.comment+=`-`+E.comment:u.comment=E.comment),l=E.end;continue}!i&&n.options.strict&<(A)&&o(A,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(h===0)E.comma&&o(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(E.comma||o(E.start,"MISSING_CHAR",`Missing , between ${a} items`),E.comment){let k="";e:for(let x of S)switch(x.type){case"comma":case"space":break;case"comment":k=x.source.substring(1);break e;default:break e}if(k){let x=u.items[u.items.length-1];$(x)&&(x=x.value??x.key),x.comment?x.comment+=`-`+k:x.comment=k,E.comment=E.comment.substring(k.length+1)}}if(!i&&!_&&!E.found){let k=w?t(n,w,E,o):e(n,E.end,_,null,E,o);u.items.push(k),l=k.range[2],As(w)&&o(k.range,"BLOCK_IN_FLOW",Ss)}else{n.atKey=!0;let k=E.end,x=A?t(n,A,E,o):e(n,k,S,null,E,o);As(A)&&o(x.range,"BLOCK_IN_FLOW",Ss),n.atKey=!1;let O=Be(_??[],{flow:a,indicator:"map-value-ind",next:w,offset:x.range[2],onError:o,parentIndent:r.indent,startOnNewline:!1});if(O.found){if(!i&&!E.found&&n.options.strict){if(_)for(let z of _){if(z===O.found)break;if(z.type==="newline"){o(z,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<O.found.offset-1024&&o(O.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else w&&("source"in w&&w.source?.[0]===":"?o(w,"MISSING_CHAR",`Missing space after : in ${a}`):o(O.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let T=w?t(n,w,O,o):O.found?e(n,O.end,_,null,O,o):null;T?As(w)&&o(T.range,"BLOCK_IN_FLOW",Ss):O.comment&&(x.comment?x.comment+=`-`+O.comment:x.comment=O.comment);let G=new K(x,T);if(n.options.keepSourceTokens&&(G.srcToken=b),i){let z=u;Vr(n,z.items,x)&&o(k,"DUPLICATE_KEY","Map keys must be unique"),z.items.push(G)}else{let z=new W(n.schema);z.flow=!0,z.items.push(G);let ht=(T??x).range;z.range=[x.range[0],ht[1],ht[2]],u.items.push(z)}l=T?T.range[2]:O.end}}let f=i?"}":"]",[p,...y]=r.end,m=l;if(p?.source===f)m=p.offset+p.source.length;else{let h=a[0].toUpperCase()+a.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=je(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 Es(t,e,n,r,o,s){let i=n.type==="block-map"?jl(t,e,n,r,s):n.type==="block-seq"?Ul(t,e,n,r,s):Ql(t,e,n,r,s),a=i.constructor;return o==="!"||o===a.tagName?(i.tag=a.tagName,i):(o&&(i.tag=o),i)}function Vl(t,e,n,r,o){let s=r.tag,i=s?e.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 a=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!s||!i||i==="!"||i===W.tagName&&a==="map"||i===ee.tagName&&a==="seq")return Es(t,e,n,o,i);let c=e.schema.tags.find(f=>f.tag===i&&f.collection===a);if(!c){let f=e.schema.knownTags[i];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?o(s,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):o(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,!0),Es(t,e,n,o,i)}let u=Es(t,e,n,o,i,c),d=c.resolve?.(u,f=>o(s,"TAG_RESOLVE_FAILED",f),e.options)??u,l=L(d)?d:new D(d);return l.range=u.range,l.tag=i,c?.format&&(l.format=c.format),l}function vs(t,e,n){let r=e.offset,o=Fm(e,t.options.strict,n);if(!o)return{value:"",type:null,comment:"",range:[r,r,r]};let s=o.mode===">"?D.BLOCK_FOLDED:D.BLOCK_LITERAL,i=e.source?Zm(e.source):[],a=i.length;for(let m=i.length-1;m>=0;--m){let h=i[m][1];if(h===""||h==="\r")a=m;else break}if(a===0){let m=o.chomp==="+"&&i.length>0?`-`.repeat(Math.max(1,i.length-1)):"",h=r+o.length;return e.source&&(h+=e.source.length),{value:m,type:s,comment:o.comment,range:[r,h,h]}}let c=e.indent+o.indent,u=e.offset+o.length,d=0;for(let m=0;m<a;++m){let[h,b]=i[m];if(b===""||b==="\r")o.indent===0&&h.length>c&&(c=h.length);else{h.length<c&&n(u+h.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),o.indent===0&&(c=h.length),d=m,c===0&&!t.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>=a;--m)i[m][0].length>c&&(a=m+1);let l="",f="",p=!1;for(let m=0;m<d;++m)l+=i[m][0].slice(c)+`-`;for(let m=d;m<a;++m){let[h,b]=i[m];u+=h.length+b.length+1;let S=b[b.length-1]==="\r";if(S&&(b=b.slice(0,-1)),b&&h.length<c){let _=`Block scalar lines must not be less indented than their ${o.indent?"explicit indentation indicator":"first line"}`;n(u-b.length-(S?2:1),"BAD_INDENT",_),h=""}s===D.BLOCK_LITERAL?(l+=f+h.slice(c)+b,f=`+`}};function Be(t,{flow:e,indicator:n,next:r,offset:o,onError:s,parentIndent:i,startOnNewline:a}){let c=!1,u=a,p=a,l="",f="",d=!1,y=!1,m=null,h=null,b=null,S=null,A=null,_=null,w=null;for(let x of t)switch(y&&(x.type!=="space"&&x.type!=="newline"&&x.type!=="comma"&&s(x.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),m&&(u&&x.type!=="comment"&&x.type!=="newline"&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),x.type){case"space":!e&&(n!=="doc-start"||r?.type!=="flow-collection")&&x.source.includes(" ")&&(m=x),p=!0;break;case"comment":{p||s(x,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let O=x.source.substring(1)||" ";l?l+=f+O:l=O,f="",u=!1;break}case"newline":u?l?l+=x.source:(!_||n!=="seq-item-ind")&&(c=!0):f+=x.source,u=!0,d=!0,(h||b)&&(S=x),p=!0;break;case"anchor":h&&s(x,"MULTIPLE_ANCHORS","A node can have at most one anchor"),x.source.endsWith(":")&&s(x.offset+x.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),h=x,w??(w=x.offset),u=!1,p=!1,y=!0;break;case"tag":{b&&s(x,"MULTIPLE_TAGS","A node can have at most one tag"),b=x,w??(w=x.offset),u=!1,p=!1,y=!0;break}case n:(h||b)&&s(x,"BAD_PROP_ORDER",`Anchors and tags must be after the ${x.source} indicator`),_&&s(x,"UNEXPECTED_TOKEN",`Unexpected ${x.source} in ${e??"collection"}`),_=x,u=n==="seq-item-ind"||n==="explicit-key-ind",p=!1;break;case"comma":if(e){A&&s(x,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),A=x,u=!1,p=!1;break}default:s(x,"UNEXPECTED_TOKEN",`Unexpected ${x.type} token`),u=!1,p=!1}let E=t[t.length-1],D=E?E.offset+E.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:A,found:_,spaceBefore:c,comment:l,hasNewline:d,anchor:h,tag:b,newlineAfterProp:S,end:D,start:w??D}}function lt(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`+`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(lt(e.key)||lt(e.value))return!0}return!1;default:return!0}}function zn(t,e,n){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&<(e)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function Gr(t,e,n){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let o=typeof r=="function"?r:(s,i)=>s===i||N(s)&&N(i)&&s.value===i.value;return e.some(s=>o(s.key,n))}var ql="All mapping items must start at the same column";function Kl({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=s?.nodeClass??W,a=new i(n.schema);n.atRoot&&(n.atRoot=!1);let c=r.offset,u=null;for(let p of r.items){let{start:l,key:f,sep:d,value:y}=p,m=Be(l,{indicator:"explicit-key-ind",next:f??d?.[0],offset:c,onError:o,parentIndent:r.indent,startOnNewline:!0}),h=!m.found;if(h){if(f&&(f.type==="block-seq"?o(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&o(c,"BAD_INDENT",ql)),!m.anchor&&!m.tag&&!d){u=m.end,m.comment&&(a.comment?a.comment+=`+`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||lt(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(c,"BAD_INDENT",ql);n.atKey=!0;let b=m.end,S=f?t(n,f,m,o):e(n,b,l,null,m,o);n.schema.compat&&zn(r.indent,f,o),n.atKey=!1,Gr(n,a.items,S)&&o(b,"DUPLICATE_KEY","Map keys must be unique");let A=Be(d??[],{indicator:"map-value-ind",next:y,offset:S.range[2],onError:o,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=A.end,A.found){h&&(y?.type==="block-map"&&!A.hasNewline&&o(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&m.start<A.found.offset-1024&&o(S.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let _=y?t(n,y,A,o):e(n,c,d,null,A,o);n.schema.compat&&zn(r.indent,y,o),c=_.range[2];let w=new K(S,_);n.options.keepSourceTokens&&(w.srcToken=p),a.items.push(w)}else{h&&o(S.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),A.comment&&(S.comment?S.comment+=`+`+A.comment:S.comment=A.comment);let _=new K(S);n.options.keepSourceTokens&&(_.srcToken=p),a.items.push(_)}}return u&&u<c&&o(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,c,u??c],a}function Wl({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=s?.nodeClass??ee,a=new i(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=r.offset,u=null;for(let{start:p,value:l}of r.items){let f=Be(p,{indicator:"seq-item-ind",next:l,offset:c,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(c,"MISSING_CHAR","Sequence item without - indicator");else{u=f.end,f.comment&&(a.comment=f.comment);continue}let d=l?t(n,l,f,o):e(n,f.end,p,null,f,o);n.schema.compat&&zn(r.indent,l,o),c=d.range[2],a.items.push(d)}return a.range=[r.offset,c,u??c],a}function je(t,e,n,r){let o="";if(t){let s=!1,i="";for(let a of t){let{source:c,type:u}=a;switch(u){case"space":s=!0;break;case"comment":{n&&!s&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let p=c.substring(1)||" ";o?o+=i+p:o=p,i="";break}case"newline":o&&(i+=c),s=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=c.length}}return{comment:o,offset:e}}var vs="Block collections are not allowed within flow collections",Ds=t=>t&&(t.type==="block-map"||t.type==="block-seq");function Yl({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=r.start.source==="{",a=i?"flow map":"flow sequence",c=s?.nodeClass??(i?W:ee),u=new c(n.schema);u.flow=!0;let p=n.atRoot;p&&(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:S,key:A,sep:_,value:w}=b,E=Be(S,{flow:a,indicator:"explicit-key-ind",next:A??_?.[0],offset:l,onError:o,parentIndent:r.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!_&&!w){h===0&&E.comma?o(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):h<r.items.length-1&&o(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),E.comment&&(u.comment?u.comment+=`+`+E.comment:u.comment=E.comment),l=E.end;continue}!i&&n.options.strict&<(A)&&o(A,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(h===0)E.comma&&o(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(E.comma||o(E.start,"MISSING_CHAR",`Missing , between ${a} items`),E.comment){let D="";e:for(let x of S)switch(x.type){case"comma":case"space":break;case"comment":D=x.source.substring(1);break e;default:break e}if(D){let x=u.items[u.items.length-1];T(x)&&(x=x.value??x.key),x.comment?x.comment+=`+`+D:x.comment=D,E.comment=E.comment.substring(D.length+1)}}if(!i&&!_&&!E.found){let D=w?t(n,w,E,o):e(n,E.end,_,null,E,o);u.items.push(D),l=D.range[2],Ds(w)&&o(D.range,"BLOCK_IN_FLOW",vs)}else{n.atKey=!0;let D=E.end,x=A?t(n,A,E,o):e(n,D,S,null,E,o);Ds(A)&&o(x.range,"BLOCK_IN_FLOW",vs),n.atKey=!1;let O=Be(_??[],{flow:a,indicator:"map-value-ind",next:w,offset:x.range[2],onError:o,parentIndent:r.indent,startOnNewline:!1});if(O.found){if(!i&&!E.found&&n.options.strict){if(_)for(let z of _){if(z===O.found)break;if(z.type==="newline"){o(z,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<O.found.offset-1024&&o(O.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else w&&("source"in w&&w.source?.[0]===":"?o(w,"MISSING_CHAR",`Missing space after : in ${a}`):o(O.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let $=w?t(n,w,O,o):O.found?e(n,O.end,_,null,O,o):null;$?Ds(w)&&o($.range,"BLOCK_IN_FLOW",vs):O.comment&&(x.comment?x.comment+=`+`+O.comment:x.comment=O.comment);let G=new K(x,$);if(n.options.keepSourceTokens&&(G.srcToken=b),i){let z=u;Gr(n,z.items,x)&&o(D,"DUPLICATE_KEY","Map keys must be unique"),z.items.push(G)}else{let z=new W(n.schema);z.flow=!0,z.items.push(G);let yt=($??x).range;z.range=[x.range[0],yt[1],yt[2]],u.items.push(z)}l=$?$.range[2]:O.end}}let f=i?"}":"]",[d,...y]=r.end,m=l;if(d?.source===f)m=d.offset+d.source.length;else{let h=a[0].toUpperCase()+a.substring(1),b=p?`${h} must end with a ${f}`:`${h} in block collection must be sufficiently indented and end with a ${f}`;o(l,p?"MISSING_CHAR":"BAD_INDENT",b),d&&d.source.length!==1&&y.unshift(d)}if(y.length>0){let h=je(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 Rs(t,e,n,r,o,s){let i=n.type==="block-map"?Kl(t,e,n,r,s):n.type==="block-seq"?Wl(t,e,n,r,s):Yl(t,e,n,r,s),a=i.constructor;return o==="!"||o===a.tagName?(i.tag=a.tagName,i):(o&&(i.tag=o),i)}function Hl(t,e,n,r,o){let s=r.tag,i=s?e.directives.tagName(s.source,f=>o(s,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:d}=r,y=f&&s?f.offset>s.offset?f:s:f??s;y&&(!d||d.offset<y.offset)&&o(y,"MISSING_CHAR","Missing newline after block sequence props")}let a=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!s||!i||i==="!"||i===W.tagName&&a==="map"||i===ee.tagName&&a==="seq")return Rs(t,e,n,o,i);let c=e.schema.tags.find(f=>f.tag===i&&f.collection===a);if(!c){let f=e.schema.knownTags[i];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?o(s,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):o(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,!0),Rs(t,e,n,o,i)}let u=Rs(t,e,n,o,i,c),p=c.resolve?.(u,f=>o(s,"TAG_RESOLVE_FAILED",f),e.options)??u,l=L(p)?p:new R(p);return l.range=u.range,l.tag=i,c?.format&&(l.format=c.format),l}function ks(t,e,n){let r=e.offset,o=Gm(e,t.options.strict,n);if(!o)return{value:"",type:null,comment:"",range:[r,r,r]};let s=o.mode===">"?R.BLOCK_FOLDED:R.BLOCK_LITERAL,i=e.source?Jm(e.source):[],a=i.length;for(let m=i.length-1;m>=0;--m){let h=i[m][1];if(h===""||h==="\r")a=m;else break}if(a===0){let m=o.chomp==="+"&&i.length>0?`+`.repeat(Math.max(1,i.length-1)):"",h=r+o.length;return e.source&&(h+=e.source.length),{value:m,type:s,comment:o.comment,range:[r,h,h]}}let c=e.indent+o.indent,u=e.offset+o.length,p=0;for(let m=0;m<a;++m){let[h,b]=i[m];if(b===""||b==="\r")o.indent===0&&h.length>c&&(c=h.length);else{h.length<c&&n(u+h.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),o.indent===0&&(c=h.length),p=m,c===0&&!t.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>=a;--m)i[m][0].length>c&&(a=m+1);let l="",f="",d=!1;for(let m=0;m<p;++m)l+=i[m][0].slice(c)+`+`;for(let m=p;m<a;++m){let[h,b]=i[m];u+=h.length+b.length+1;let S=b[b.length-1]==="\r";if(S&&(b=b.slice(0,-1)),b&&h.length<c){let _=`Block scalar lines must not be less indented than their ${o.indent?"explicit indentation indicator":"first line"}`;n(u-b.length-(S?2:1),"BAD_INDENT",_),h=""}s===R.BLOCK_LITERAL?(l+=f+h.slice(c)+b,f=``):h.length>c||b[0]===" "?(f===" "?f=`-`:!p&&f===`+`:!d&&f===``&&(f=``),l+=f+h.slice(c)+b,f=`-`,p=!0):b===""?f===`+`,d=!0):b===""?f===``?l+=``:f=`-`:(l+=f+b,f=" ",p=!1)}switch(o.chomp){case"-":break;case"+":for(let m=a;m<i.length;++m)l+=`+`:(l+=f+b,f=" ",d=!1)}switch(o.chomp){case"-":break;case"+":for(let m=a;m<i.length;++m)l+=``+i[m][0].slice(c);l[l.length-1]!==``&&(l+=``);break;default:l+=`-`}let y=r+o.length+e.source.length;return{value:l,type:s,comment:o.comment,range:[r,y,y]}}function Fm({offset:t,props:e},n,r){if(e[0].type!=="block-scalar-header")return r(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:o}=e[0],s=o[0],i=0,a="",c=-1;for(let f=1;f<o.length;++f){let p=o[f];if(!a&&(p==="-"||p==="+"))a=p;else{let y=Number(p);!i&&y?i=y:c===-1&&(c=t+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${o}`);let u=!1,d="",l=o.length;for(let f=1;f<e.length;++f){let p=e[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:a,comment:d,length:l}}function Zm(t){let e=t.split(/\n( *)/),n=e[0],r=n.match(/^( *)/),s=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let i=1;i<e.length;i+=2)s.push([e[i],e[i+1]]);return s}function ks(t,e,n){let{offset:r,type:o,source:s,end:i}=t,a,c,u=(f,p,y)=>n(r+f,p,y);switch(o){case"scalar":a=D.PLAIN,c=Bm(s,u);break;case"single-quoted-scalar":a=D.QUOTE_SINGLE,c=jm(s,u);break;case"double-quoted-scalar":a=D.QUOTE_DOUBLE,c=Um(s,u);break;default:return n(t,"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=je(i,d,e,n);return{value:c,type:a,comment:l.comment,range:[r,d,l.offset]}}function Bm(t,e){let n="";switch(t[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 ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),Gl(t)}function jm(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),Gl(t.slice(1,-1)).replace(/''/g,"'")}function Gl(t){let e,n;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?+`}let y=r+o.length+e.source.length;return{value:l,type:s,comment:o.comment,range:[r,y,y]}}function Gm({offset:t,props:e},n,r){if(e[0].type!=="block-scalar-header")return r(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:o}=e[0],s=o[0],i=0,a="",c=-1;for(let f=1;f<o.length;++f){let d=o[f];if(!a&&(d==="-"||d==="+"))a=d;else{let y=Number(d);!i&&y?i=y:c===-1&&(c=t+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${o}`);let u=!1,p="",l=o.length;for(let f=1;f<e.length;++f){let d=e[f];switch(d.type){case"space":u=!0;case"newline":l+=d.source.length;break;case"comment":n&&!u&&r(d,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),l+=d.source.length,p=d.source.substring(1);break;case"error":r(d,"UNEXPECTED_TOKEN",d.message),l+=d.source.length;break;default:{let y=`Unexpected token in block scalar header: ${d.type}`;r(d,"UNEXPECTED_TOKEN",y);let m=d.source;m&&typeof m=="string"&&(l+=m.length)}}}return{mode:s,indent:i,chomp:a,comment:p,length:l}}function Jm(t){let e=t.split(/\n( *)/),n=e[0],r=n.match(/^( *)/),s=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let i=1;i<e.length;i+=2)s.push([e[i],e[i+1]]);return s}function Is(t,e,n){let{offset:r,type:o,source:s,end:i}=t,a,c,u=(f,d,y)=>n(r+f,d,y);switch(o){case"scalar":a=R.PLAIN,c=qm(s,u);break;case"single-quoted-scalar":a=R.QUOTE_SINGLE,c=Km(s,u);break;case"double-quoted-scalar":a=R.QUOTE_DOUBLE,c=Wm(s,u);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${o}`),{value:"",type:null,comment:"",range:[r,r+s.length,r+s.length]}}let p=r+s.length,l=je(i,p,e,n);return{value:c,type:a,comment:l.comment,range:[r,p,l.offset]}}function qm(t,e){let n="";switch(t[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 ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),Xl(t)}function Km(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),Xl(t.slice(1,-1)).replace(/''/g,"'")}function Xl(t){let e,n;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?`,"sy"),n=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=e.exec(t);if(!r)return t;let o=r[1],s=" ",i=e.lastIndex;for(n.lastIndex=i;r=n.exec(t);)r[1]===""?s===``?o+=s:s=`-`:(o+=s+r[1],s=" "),i=n.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=i,r=a.exec(t),o+s+(r?.[1]??"")}function Um(t,e){let n="";for(let r=1;r<t.length-1;++r){let o=t[r];if(!(o==="\r"&&t[r+1]===`+`:(o+=s+r[1],s=" "),i=n.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=i,r=a.exec(t),o+s+(r?.[1]??"")}function Wm(t,e){let n="";for(let r=1;r<t.length-1;++r){let o=t[r];if(!(o==="\r"&&t[r+1]===``))if(o===`-`){let{fold:s,offset:i}=Qm(t,r);n+=s,r=i}else if(o==="\\"){let s=t[++r],i=Vm[s];if(i)n+=i;else if(s===`+`){let{fold:s,offset:i}=Ym(t,r);n+=s,r=i}else if(o==="\\"){let s=t[++r],i=Hm[s];if(i)n+=i;else if(s===``)for(s=t[r+1];s===" "||s===" ";)s=t[++r+1];else if(s==="\r"&&t[r+1]===`-`)for(s=t[++r+1];s===" "||s===" ";)s=t[++r+1];else if(s==="x"||s==="u"||s==="U"){let a=s==="x"?2:s==="u"?4:8;n+=Gm(t,r+1,a,e),r+=a}else{let a=t.substr(r-1,2);e(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),n+=a}}else if(o===" "||o===" "){let s=r,i=t[r+1];for(;i===" "||i===" ";)i=t[++r+1];i!==`+`)for(s=t[++r+1];s===" "||s===" ";)s=t[++r+1];else if(s==="x"||s==="u"||s==="U"){let a=s==="x"?2:s==="u"?4:8;n+=Xm(t,r+1,a,e),r+=a}else{let a=t.substr(r-1,2);e(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),n+=a}}else if(o===" "||o===" "){let s=r,i=t[r+1];for(;i===" "||i===" ";)i=t[++r+1];i!==``&&!(i==="\r"&&t[r+2]===`-`)&&(n+=r>s?t.slice(s,r+1):o)}else n+=o}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),n}function Qm(t,e){let n="",r=t[e+1];for(;(r===" "||r===" "||r===`+`)&&(n+=r>s?t.slice(s,r+1):o)}else n+=o}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),n}function Ym(t,e){let n="",r=t[e+1];for(;(r===" "||r===" "||r===``||r==="\r")&&!(r==="\r"&&t[e+2]!==``);)r===``&&(n+=`-`),e+=1,r=t[e+1];return n||(n=" "),{fold:n,offset:e}}var Vm={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`-`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Gm(t,e,n,r){let o=t.substr(e,n),i=o.length===n&&/^[0-9a-fA-F]+$/.test(o)?parseInt(o,16):NaN;try{return String.fromCodePoint(i)}catch{let a=t.substr(e-2,n+2);return r(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}function Ds(t,e,n,r){let{value:o,type:s,comment:i,range:a}=e.type==="block-scalar"?vs(t,e,r):ks(e,t.options.strict,r),c=n?t.directives.tagName(n.source,l=>r(n,"TAG_RESOLVE_FAILED",l)):null,u;t.options.stringKeys&&t.atKey?u=t.schema[pe]:c?u=Jm(t.schema,o,c,n,r):e.type==="scalar"?u=qm(t,o,e,r):u=t.schema[pe];let d;try{let l=u.resolve(o,f=>r(n??e,"TAG_RESOLVE_FAILED",f),t.options);d=N(l)?l:new D(l)}catch(l){let f=l instanceof Error?l.message:String(l);r(n??e,"TAG_RESOLVE_FAILED",f),d=new D(o)}return d.range=a,d.source=o,s&&(d.type=s),c&&(d.tag=c),u.format&&(d.format=u.format),i&&(d.comment=i),d}function Jm(t,e,n,r,o){if(n==="!")return t[pe];let s=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let i=t.knownTags[n];return i&&!i.collection?(t.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"),t[pe])}function qm({atKey:t,directives:e,schema:n},r,o,s){let i=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(r))||n[pe];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(r))??n[pe];if(i.tag!==a.tag){let c=e.tagString(i.tag),u=e.tagString(a.tag),d=`Value may be parsed as either ${c} or ${u}`;s(o,"TAG_RESOLVE_FAILED",d,!0)}}return i}function Jl(t,e,n){if(e){n??(n=e.length);for(let r=n-1;r>=0;--r){let o=e[r];switch(o.type){case"space":case"comment":case"newline":t-=o.source.length;continue}for(o=e[++r];o?.type==="space";)t+=o.source.length,o=e[++r];break}}return t}var Km={composeNode:Rs,composeEmptyNode:Gr};function Rs(t,e,n,r){let o=t.atKey,{spaceBefore:s,comment:i,anchor:a,tag:c}=n,u,d=!0;switch(e.type){case"alias":u=Wm(t,e,r),(a||c)&&r(e,"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(t,e,c,r),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{u=Vl(Km,t,e,n,r),a&&(u.anchor=a.source.substring(1))}catch(l){let f=l instanceof Error?l.message:String(l);r(e,"RESOURCE_EXHAUSTION",f)}break;default:{let l=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",l),d=!1}}return u??(u=Gr(t,e.offset,void 0,null,n,r)),a&&u.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),o&&t.options.stringKeys&&(!N(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&r(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(u.spaceBefore=!0),i&&(e.type==="scalar"&&e.source===""?u.comment=i:u.commentBefore=i),t.options.keepSourceTokens&&d&&(u.srcToken=e),u}function Gr(t,e,n,r,{spaceBefore:o,comment:s,anchor:i,tag:a,end:c},u){let d={type:"scalar",offset:Jl(e,n,r),indent:-1,source:""},l=Ds(t,d,a,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]=c),l}function Wm({options:t},{offset:e,source:n,end:r},o){let s=new Je(n.substring(1));s.source===""&&o(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&o(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let i=e+n.length,a=je(r,i,t.strict,o);return s.range=[e,i,a.offset],a.comment&&(s.comment=a.comment),s}function ql(t,e,{offset:n,start:r,value:o,end:s},i){let a=Object.assign({_directives:e},t),c=new ut(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=Be(r,{indicator:"doc-start",next:o??s?.[0],offset:n,onError:i,parentIndent:0,startOnNewline:!0});d.found&&(c.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")),c.contents=o?Rs(u,o,d,i):Gr(u,d.end,r,null,d,i);let l=c.contents.range[2],f=je(s,l,!1,i);return f.comment&&(c.comment=f.comment),c.range=[n,l,f.offset],c}function Tn(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function Kl(t){let e="",n=!1,r=!1;for(let o=0;o<t.length;++o){let s=t[o];switch(s[0]){case"#":e+=(e===""?"":r?`+`),e+=1,r=t[e+1];return n||(n=" "),{fold:n,offset:e}}var Hm={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`+`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Xm(t,e,n,r){let o=t.substr(e,n),i=o.length===n&&/^[0-9a-fA-F]+$/.test(o)?parseInt(o,16):NaN;try{return String.fromCodePoint(i)}catch{let a=t.substr(e-2,n+2);return r(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}function Os(t,e,n,r){let{value:o,type:s,comment:i,range:a}=e.type==="block-scalar"?ks(t,e,r):Is(e,t.options.strict,r),c=n?t.directives.tagName(n.source,l=>r(n,"TAG_RESOLVE_FAILED",l)):null,u;t.options.stringKeys&&t.atKey?u=t.schema[pe]:c?u=eh(t.schema,o,c,n,r):e.type==="scalar"?u=th(t,o,e,r):u=t.schema[pe];let p;try{let l=u.resolve(o,f=>r(n??e,"TAG_RESOLVE_FAILED",f),t.options);p=N(l)?l:new R(l)}catch(l){let f=l instanceof Error?l.message:String(l);r(n??e,"TAG_RESOLVE_FAILED",f),p=new R(o)}return p.range=a,p.source=o,s&&(p.type=s),c&&(p.tag=c),u.format&&(p.format=u.format),i&&(p.comment=i),p}function eh(t,e,n,r,o){if(n==="!")return t[pe];let s=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let i=t.knownTags[n];return i&&!i.collection?(t.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"),t[pe])}function th({atKey:t,directives:e,schema:n},r,o,s){let i=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(r))||n[pe];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(r))??n[pe];if(i.tag!==a.tag){let c=e.tagString(i.tag),u=e.tagString(a.tag),p=`Value may be parsed as either ${c} or ${u}`;s(o,"TAG_RESOLVE_FAILED",p,!0)}}return i}function ef(t,e,n){if(e){n??(n=e.length);for(let r=n-1;r>=0;--r){let o=e[r];switch(o.type){case"space":case"comment":case"newline":t-=o.source.length;continue}for(o=e[++r];o?.type==="space";)t+=o.source.length,o=e[++r];break}}return t}var nh={composeNode:Cs,composeEmptyNode:Jr};function Cs(t,e,n,r){let o=t.atKey,{spaceBefore:s,comment:i,anchor:a,tag:c}=n,u,p=!0;switch(e.type){case"alias":u=rh(t,e,r),(a||c)&&r(e,"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=Os(t,e,c,r),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{u=Hl(nh,t,e,n,r),a&&(u.anchor=a.source.substring(1))}catch(l){let f=l instanceof Error?l.message:String(l);r(e,"RESOURCE_EXHAUSTION",f)}break;default:{let l=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",l),p=!1}}return u??(u=Jr(t,e.offset,void 0,null,n,r)),a&&u.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),o&&t.options.stringKeys&&(!N(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&r(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(u.spaceBefore=!0),i&&(e.type==="scalar"&&e.source===""?u.comment=i:u.commentBefore=i),t.options.keepSourceTokens&&p&&(u.srcToken=e),u}function Jr(t,e,n,r,{spaceBefore:o,comment:s,anchor:i,tag:a,end:c},u){let p={type:"scalar",offset:ef(e,n,r),indent:-1,source:""},l=Os(t,p,a,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]=c),l}function rh({options:t},{offset:e,source:n,end:r},o){let s=new Je(n.substring(1));s.source===""&&o(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&o(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let i=e+n.length,a=je(r,i,t.strict,o);return s.range=[e,i,a.offset],a.comment&&(s.comment=a.comment),s}function tf(t,e,{offset:n,start:r,value:o,end:s},i){let a=Object.assign({_directives:e},t),c=new ut(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},p=Be(r,{indicator:"doc-start",next:o??s?.[0],offset:n,onError:i,parentIndent:0,startOnNewline:!0});p.found&&(c.directives.docStart=!0,o&&(o.type==="block-map"||o.type==="block-seq")&&!p.hasNewline&&i(p.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=o?Cs(u,o,p,i):Jr(u,p.end,r,null,p,i);let l=c.contents.range[2],f=je(s,l,!1,i);return f.comment&&(c.comment=f.comment),c.range=[n,l,f.offset],c}function Pn(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function nf(t){let e="",n=!1,r=!1;for(let o=0;o<t.length;++o){let s=t[o];switch(s[0]){case"#":e+=(e===""?"":r?``:`-`)+(s.substring(1)||" "),n=!0,r=!1;break;case"%":t[o+1]?.[0]!=="#"&&(o+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:e,afterEmptyLine:r}}var zn=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,o,s)=>{let i=Tn(n);s?this.warnings.push(new Nn(i,r,o)):this.errors.push(new De(i,r,o))},this.directives=new Fe({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:r,afterEmptyLine:o}=Kl(this.prelude);if(r){let s=e.contents;if(n)e.comment=e.comment?`${e.comment}-${r}`:r;else if(o||e.directives.docStart||!s)e.commentBefore=r;else if(B(s)&&!s.flow&&s.items.length>0){let i=s.items[0];$(i)&&(i=i.key);let a=i.commentBefore;i.commentBefore=a?`${r}+`)+(s.substring(1)||" "),n=!0,r=!1;break;case"%":t[o+1]?.[0]!=="#"&&(o+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:e,afterEmptyLine:r}}var Ln=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,o,s)=>{let i=Pn(n);s?this.warnings.push(new $n(i,r,o)):this.errors.push(new Re(i,r,o))},this.directives=new Fe({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:r,afterEmptyLine:o}=nf(this.prelude);if(r){let s=e.contents;if(n)e.comment=e.comment?`${e.comment}+${r}`:r;else if(o||e.directives.docStart||!s)e.commentBefore=r;else if(B(s)&&!s.flow&&s.items.length>0){let i=s.items[0];T(i)&&(i=i.key);let a=i.commentBefore;i.commentBefore=a?`${r}${a}`:r}else{let i=s.commentBefore;s.commentBefore=i?`${r}-${i}`:r}}if(n){for(let s=0;s<this.errors.length;++s)e.errors.push(this.errors[s]);for(let s=0;s<this.warnings.length;++s)e.warnings.push(this.warnings[s])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Kl(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,n=!1,r=-1){for(let o of e)yield*this.next(o);yield*this.end(n,r)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(n,r,o)=>{let s=Tn(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",r,o)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=ql(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"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(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,r=new De(Tn(e),"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 De(Tn(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=je(e.end,e.offset+e.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 De(Tn(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),o=new ut(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 Is=Symbol("break visit"),Ym=Symbol("skip children"),Wl=Symbol("remove item");function xt(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Yl(Object.freeze([]),t,e)}xt.BREAK=Is;xt.SKIP=Ym;xt.REMOVE=Wl;xt.itemAtPath=(t,e)=>{let n=t;for(let[r,o]of e){let s=n?.[r];if(s&&"items"in s)n=s.items[o];else return}return n};xt.parentCollection=(t,e)=>{let n=xt.itemAtPath(t,e.slice(0,-1)),r=e[e.length-1][0],o=n?.[r];if(o&&"items"in o)return o;throw new Error("Parent collection not found")};function Yl(t,e,n){let r=n(e,t);if(typeof r=="symbol")return r;for(let o of["key","value"]){let s=e[o];if(s&&"items"in s){for(let i=0;i<s.items.length;++i){let a=Yl(Object.freeze(t.concat([[o,i]])),s.items[i],n);if(typeof a=="number")i=a-1;else{if(a===Is)return Is;a===Wl&&(s.items.splice(i,1),i-=1)}}typeof r=="function"&&o==="key"&&(r=r(e,t))}}return typeof r=="function"?r(e,t):r}var Os="\uFEFF",Cs="",Ns="",Jr="";function Hl(t){switch(t){case Os:return"byte-order-mark";case Cs:return"doc-mode";case Ns:return"flow-error-end";case Jr:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`+${i}`:r}}if(n){for(let s=0;s<this.errors.length;++s)e.errors.push(this.errors[s]);for(let s=0;s<this.warnings.length;++s)e.warnings.push(this.warnings[s])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:nf(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,n=!1,r=-1){for(let o of e)yield*this.next(o);yield*this.end(n,r)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(n,r,o)=>{let s=Pn(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",r,o)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=tf(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"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(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,r=new Re(Pn(e),"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 Re(Pn(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=je(e.end,e.offset+e.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 Re(Pn(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),o=new ut(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 Ns=Symbol("break visit"),oh=Symbol("skip children"),rf=Symbol("remove item");function St(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),of(Object.freeze([]),t,e)}St.BREAK=Ns;St.SKIP=oh;St.REMOVE=rf;St.itemAtPath=(t,e)=>{let n=t;for(let[r,o]of e){let s=n?.[r];if(s&&"items"in s)n=s.items[o];else return}return n};St.parentCollection=(t,e)=>{let n=St.itemAtPath(t,e.slice(0,-1)),r=e[e.length-1][0],o=n?.[r];if(o&&"items"in o)return o;throw new Error("Parent collection not found")};function of(t,e,n){let r=n(e,t);if(typeof r=="symbol")return r;for(let o of["key","value"]){let s=e[o];if(s&&"items"in s){for(let i=0;i<s.items.length;++i){let a=of(Object.freeze(t.concat([[o,i]])),s.items[i],n);if(typeof a=="number")i=a-1;else{if(a===Ns)return Ns;a===rf&&(s.items.splice(i,1),i-=1)}}typeof r=="function"&&o==="key"&&(r=r(e,t))}}return typeof r=="function"?r(e,t):r}var Ts="\uFEFF",$s="",zs="",qr="";function sf(t){switch(t){case Ts:return"byte-order-mark";case $s:return"doc-mode";case zs:return"flow-error-end";case qr: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(t[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 Re(t){switch(t){case void 0:case" ":case`-`:case"\r":case" ":return!0;default:return!1}}var Xl=new Set("0123456789ABCDEFabcdef"),Xm=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),qr=new Set(",[]{}"),eh=new Set(` ,[]{}-\r `),$s=t=>!t||eh.has(t),Pn=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(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===`+`: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(t[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(t){switch(t){case void 0:case" ":case`+`:case"\r":case" ":return!0;default:return!1}}var af=new Set("0123456789ABCDEFabcdef"),ih=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Kr=new Set(",[]{}"),ah=new Set(` ,[]{}+\r `),Ps=t=>!t||ah.has(t),Mn=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(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===``?!0:n==="\r"?this.buffer[e+1]===``:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let n=this.buffer[e];if(this.indentNext>0){let r=0;for(;n===" ";)n=this.buffer[++r+e];if(n==="\r"){let o=this.buffer[r+e+1];if(o===``||!o&&!this.atEnd)return e+r+1}return n===`-`||r>=this.indentNext||!n&&!this.atEnd?e+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(e,3);if((r==="---"||r==="...")&&Re(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`-`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){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 e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Os&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let n=e.length,r=e.indexOf("#");for(;r!==-1;){let s=e[r-1];if(s===" "||s===" "){n=r-1;break}else r=e.indexOf("#",r+1)}for(;;){let s=e[n-1];if(s===" "||s===" ")n-=1;else break}let o=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-o),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-n),yield*this.pushNewline(),"stream"}return yield Cs,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let n=this.peek(3);if((n==="---"||n==="...")&&Re(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&&!Re(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Re(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 e=this.getLine();if(e===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(e[n]){case"#":yield*this.pushCount(e.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($s),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,n,r=-1;do e=yield*this.pushNewline(),e>0?(n=yield*this.pushSpaces(!1),this.indentValue=r=n):n=0,n+=yield*this.pushSpaces(!0);while(e+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("..."))&&Re(o[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(o[0]==="]"||o[0]==="}")))return this.flowLevel=0,yield Ns,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($s),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let i=this.charAt(1);if(this.flowKey||Re(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 e=this.charAt(0),n=this.buffer.indexOf(e,this.pos+1);if(e==="'")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(`+`||r>=this.indentNext||!n&&!this.atEnd?e+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(e,3);if((r==="---"||r==="...")&&ke(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`+`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){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 e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Ts&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let n=e.length,r=e.indexOf("#");for(;r!==-1;){let s=e[r-1];if(s===" "||s===" "){n=r-1;break}else r=e.indexOf("#",r+1)}for(;;){let s=e[n-1];if(s===" "||s===" ")n-=1;else break}let o=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-o),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-n),yield*this.pushNewline(),"stream"}return yield $s,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){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[e,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&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 e=this.getLine();if(e===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(e[n]){case"#":yield*this.pushCount(e.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(Ps),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,n,r=-1;do e=yield*this.pushNewline(),e>0?(n=yield*this.pushSpaces(!1),this.indentValue=r=n):n=0,n+=yield*this.pushSpaces(!0);while(e+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 zs,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(Ps),"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 e=this.charAt(0),n=this.buffer.indexOf(e,this.pos+1);if(e==="'")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 e=this.pos;for(;;){let n=this.buffer[++e];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=>Re(n)||n==="#")}*parseBlockScalar(){let e=this.pos-1,n=0,r;e:for(let s=this.pos;r=this.buffer[s];++s)switch(r){case" ":n+=1;break;case`+`,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 e=this.pos;for(;;){let n=this.buffer[++e];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 e=this.pos-1,n=0,r;e:for(let s=this.pos;r=this.buffer[s];++s)switch(r){case" ":n+=1;break;case``:e=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(e+1);if(s===-1)break;e=this.buffer.indexOf(``,s)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let o=e+1;for(r=this.buffer[o];r===" ";)r=this.buffer[++o];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===``;)r=this.buffer[++o];e=o-1}else if(!this.blockScalarKeep)do{let s=e-1,i=this.buffer[s];i==="\r"&&(i=this.buffer[--s]);let a=s;for(;i===" ";)i=this.buffer[--s];if(i===`-`&&s>=this.pos&&s+1+n>a)e=s;else break}while(!0);return yield Jr,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=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(Re(s)||e&&qr.has(s))break;n=r}else if(Re(o)){let s=this.buffer[r+1];if(o==="\r"&&(s===`+`&&s>=this.pos&&s+1+n>a)e=s;else break}while(!0);return yield qr,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=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)||e&&Kr.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==="#"||e&&qr.has(s))break;if(o===`-`){let i=this.continueScalar(r+1);if(i===-1)break;r=Math.max(r,i-2)}}else{if(e&&qr.has(o))break;n=r}return!o&&!this.atEnd?this.setNext("plain-scalar"):(yield Jr,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let r=this.buffer.slice(this.pos,e);return r?(yield r,this.pos+=r.length,r.length):(n&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil($s),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(Re(r)||n&&qr.has(r)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!Re(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(Xm.has(n))n=this.buffer[++e];else if(n==="%"&&Xl.has(this.buffer[e+1])&&Xl.has(this.buffer[e+2]))n=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`+`,s=this.buffer[r+1]):n=r),s==="#"||e&&Kr.has(s))break;if(o===`+`){let i=this.continueScalar(r+1);if(i===-1)break;r=Math.max(r,i-2)}}else{if(e&&Kr.has(o))break;n=r}return!o&&!this.atEnd?this.setNext("plain-scalar"):(yield qr,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let r=this.buffer.slice(this.pos,e);return r?(yield r,this.pos+=r.length,r.length):(n&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Ps),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(ke(r)||n&&Kr.has(r)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!ke(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(ih.has(n))n=this.buffer[++e];else if(n==="%"&&af.has(this.buffer[e+1])&&af.has(this.buffer[e+2]))n=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===``?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`-`?yield*this.pushCount(2):0}*pushSpaces(e){let n=this.pos-1,r;do r=this.buffer[++n];while(r===" "||e&&r===" ");let o=n-this.pos;return o>0&&(yield this.buffer.substr(this.pos,o),this.pos=n),o}*pushUntil(e){let n=this.pos,r=this.buffer[n];for(;!e(r);)r=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};var Ln=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,r=this.lineStarts.length;for(;n<r;){let s=n+r>>1;this.lineStarts[s]<e?n=s+1:r=s}if(this.lineStarts[n]===e)return{line:n+1,col:1};if(n===0)return{line:0,col:e};let o=this.lineStarts[n-1];return{line:n,col:e-o+1}}}};function ft(t,e){for(let n=0;n<t.length;++n)if(t[n].type===e)return!0;return!1}function ef(t){for(let e=0;e<t.length;++e)switch(t[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function nf(t){switch(t?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Kr(t){switch(t.type){case"document":return t.start;case"block-map":{let e=t.items[t.items.length-1];return e.sep??e.start}case"block-seq":return t.items[t.items.length-1].start;default:return[]}}function Jt(t){if(t.length===0)return[];let e=t.length;e:for(;--e>=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function Wr(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let n=0;n<e.length;++n)t.push(e[n])}function tf(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!ft(e.start,"explicit-key-ind")&&!ft(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,nf(e.value)?e.value.end?Wr(e.value.end,e.sep):e.value.end=e.sep:Wr(e.start,e.sep),delete e.sep)}var Mn=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Pn,this.onNewLine=e}*parse(e,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(e,n))yield*this.next(r);n||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let n=Hl(e);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+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let r=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:e}),this.offset+=e.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 e=this.peek(1);if(this.type==="doc-end"&&e?.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(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let n=e??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"&&tf(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&&ef(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 e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{ef(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let n=Kr(this.peek(2)),r=Jt(n),o;e.end?(o=e.end,o.push(this.sourceToken),delete e.end):o=[this.sourceToken];let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let n=this.source.indexOf(`+`?yield*this.pushCount(2):0}*pushSpaces(e){let n=this.pos-1,r;do r=this.buffer[++n];while(r===" "||e&&r===" ");let o=n-this.pos;return o>0&&(yield this.buffer.substr(this.pos,o),this.pos=n),o}*pushUntil(e){let n=this.pos,r=this.buffer[n];for(;!e(r);)r=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};var Fn=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,r=this.lineStarts.length;for(;n<r;){let s=n+r>>1;this.lineStarts[s]<e?n=s+1:r=s}if(this.lineStarts[n]===e)return{line:n+1,col:1};if(n===0)return{line:0,col:e};let o=this.lineStarts[n-1];return{line:n,col:e-o+1}}}};function ft(t,e){for(let n=0;n<t.length;++n)if(t[n].type===e)return!0;return!1}function cf(t){for(let e=0;e<t.length;++e)switch(t[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function lf(t){switch(t?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Wr(t){switch(t.type){case"document":return t.start;case"block-map":{let e=t.items[t.items.length-1];return e.sep??e.start}case"block-seq":return t.items[t.items.length-1].start;default:return[]}}function qt(t){if(t.length===0)return[];let e=t.length;e:for(;--e>=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function Yr(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let n=0;n<e.length;++n)t.push(e[n])}function uf(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!ft(e.start,"explicit-key-ind")&&!ft(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,lf(e.value)?e.value.end?Yr(e.value.end,e.sep):e.value.end=e.sep:Yr(e.start,e.sep),delete e.sep)}var Zn=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Mn,this.onNewLine=e}*parse(e,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(e,n))yield*this.next(r);n||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let n=sf(e);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+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let r=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:e}),this.offset+=e.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 e=this.peek(1);if(this.type==="doc-end"&&e?.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(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let n=e??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"&&uf(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&&cf(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 e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{cf(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let n=Wr(this.peek(2)),r=qt(n),o;e.end?(o=e.end,o.push(this.sourceToken),delete e.end):o=[this.sourceToken];let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.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(e){let n=e.items[e.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):e.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)e.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){Wr(o,n.start),o.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,o=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(o&&n.sep&&!n.value){let i=[];for(let a=0;a<n.sep.length;++a){let c=n.sep[a];switch(c.type){case"newline":i.push(a);break;case"space":break;case"comment":c.indent>e.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),e.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),e.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)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(ft(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(nf(n.key)&&!ft(n.sep,"newline")){let i=Jt(n.start),a=n.key,c=n.sep;c.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:a,sep:c}]})}else s.length>0?n.sep=n.sep.concat(s,this.sourceToken):n.sep.push(this.sourceToken);else if(ft(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let i=Jt(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?e.items.push({start:s,key:null,sep:[this.sourceToken]}):ft(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?(e.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(e);if(i){if(i.type==="block-seq"){if(!n.explicitKey&&n.sep&&!ft(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&&e.items.push({start:s});this.stack.push(i);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.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):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){Wr(o,n.start),o.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=e.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;n.value||ft(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.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(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.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?e.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?e.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":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);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===e.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=Kr(r),s=Jt(o);tf(e);let i=e.end.splice(1,e.end.length);i.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let n=this.source.indexOf(`+`,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let n=e.items[e.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):e.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)e.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){Yr(o,n.start),o.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,o=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(o&&n.sep&&!n.value){let i=[];for(let a=0;a<n.sep.length;++a){let c=n.sep[a];switch(c.type){case"newline":i.push(a);break;case"space":break;case"comment":c.indent>e.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),e.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),e.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)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(ft(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(lf(n.key)&&!ft(n.sep,"newline")){let i=qt(n.start),a=n.key,c=n.sep;c.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:a,sep:c}]})}else s.length>0?n.sep=n.sep.concat(s,this.sourceToken):n.sep.push(this.sourceToken);else if(ft(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let i=qt(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?e.items.push({start:s,key:null,sep:[this.sourceToken]}):ft(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?(e.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(e);if(i){if(i.type==="block-seq"){if(!n.explicitKey&&n.sep&&!ft(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&&e.items.push({start:s});this.stack.push(i);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.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):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){Yr(o,n.start),o.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=e.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;n.value||ft(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.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(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.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?e.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?e.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":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);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===e.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=Wr(r),s=qt(o);uf(e);let i=e.end.splice(1,e.end.length);i.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){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:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){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=Kr(e),r=Jt(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=Kr(e),r=Jt(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){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:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};function th(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Ln||null,prettyErrors:e}}function Ts(t,e={}){let{lineCounter:n,prettyErrors:r}=th(e),o=new Mn(n?.addNewLine),s=new zn(e),i=null;for(let a of s.compose(o.parse(t),!0,t.length))if(!i)i=a;else if(i.options.logLevel!=="silent"){i.errors.push(new De(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(i.errors.forEach(xs(t,n)),i.warnings.forEach(xs(t,n))),i}var Ie=class extends Error{code;constructor(e){super(`Structured data failed validation: ${e}`),this.name="StructuredDataError",this.code=e}},rh=t=>Ne(JSON.stringify(t)),rf=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},of=(t,e)=>{if(rf(t)===!1)throw new Ie("INVALID");let n=0,r=(s,i)=>{if(i>e.depth)throw new Ie("DEPTH_EXCEEDED");if(typeof s=="string"){if(Ne(s)>e.stringBytes)throw new Ie("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(a=>{if(n+=1,n>e.fields)throw new Ie("FIELDS_EXCEEDED");return r(a,i+1)});if(rf(s)){let a=Object.create(null);for(let[c,u]of Object.entries(s)){if(n+=1,n>e.fields)throw new Ie("FIELDS_EXCEEDED");a[c]=r(u,i+1)}return a}throw new Ie("INVALID")},o=r(t,1);if(rh(o)>e.serializedBytes)throw new Ie("SERIALIZED_BYTES_EXCEEDED");return o};var H=class extends Error{code;constructor(e,n){super(n),this.name="MarkdownMetadataError",this.code=e}};var Fn=new Uint8Array([239,187,191]),sf=Fn.byteLength+10,oh=(t,e,n=0)=>t.byteLength-n<e.byteLength?!1:e.every((r,o)=>t[n+o]===r),Zn=(t,e)=>{let n=0;if(oh(t,Fn))n=Fn.byteLength;else if(t.byteLength<Fn.byteLength&&Fn.slice(0,t.byteLength).every((s,i)=>s===t[i]))return e?null:void 0;if(t.byteLength<n+4)return e?null:void 0;if(t[n]!==45||t[n+1]!==45||t[n+2]!==45)return null;let r=n+3;if(t[r]===10)r+=1;else if(t[r]===13){if(t.byteLength===r+1)return e?null:void 0;if(t[r+1]!==10)return null;r+=2}else return null;let o=r;for(let s=r;s<=t.byteLength;s+=1){let i=s===t.byteLength;if(i===!1&&t[s]!==10)continue;if(i&&e===!1)return;let a=s;if(a>o&&t[a-1]===13&&(a-=1),a-o===3&&(t[o]===45&&t[o+1]===45&&t[o+2]===45||t[o]===46&&t[o+1]===46&&t[o+2]===46))return{yamlStart:r,yamlEnd:o,blockEnd:i?s:s+1};o=s+1}};var sh={bytes:R.frontmatterBytes,depth:R.frontmatterDepth,fields:R.frontmatterFields,stringBytes:R.frontmatterStringBytes,serializedBytes:R.indexedPropertiesBytes},af=t=>{try{return le(t)}catch{throw new H("FRONTMATTER_DECODING_FAILED","Markdown frontmatter is not valid UTF-8")}},cf=(t,e)=>{let n=Ts(t,{schema:"core",uniqueKeys:!0});if(n.errors.length>0)throw new H("FRONTMATTER_INVALID","Markdown frontmatter contains invalid YAML");let r;try{r=n.toJS({maxAliasCount:0})}catch{throw new H("FRONTMATTER_INVALID","Markdown frontmatter contains unsupported YAML aliases")}if(r===null)return{};try{return of(r,e)}catch(o){throw o instanceof Ie?o.code==="DEPTH_EXCEEDED"?new H("FRONTMATTER_DEPTH_EXCEEDED","Markdown frontmatter exceeds the nesting limit"):o.code==="FIELDS_EXCEEDED"?new H("FRONTMATTER_FIELDS_EXCEEDED","Markdown frontmatter exceeds the field limit"):o.code==="STRING_BYTES_EXCEEDED"?new H("FRONTMATTER_STRING_BYTES_EXCEEDED","Markdown frontmatter contains a string that exceeds the byte limit"):o.code==="SERIALIZED_BYTES_EXCEEDED"?new H("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter properties exceed the indexed byte limit"):new H("FRONTMATTER_INVALID","Markdown frontmatter must contain a JSON-compatible object"):o}},uf=async(t,e={})=>{let n={...sh,...e},r=n.bytes+sf,o=new Uint8Array(r),s=0;for await(let c of $t(t)){let u=0;for(;u<c.byteLength;){let d=r-s;if(d<=0)break;let l=Math.max(0,6-s),f=Math.min(c.byteLength-u,l);if(l===0){let m=c.subarray(u,Math.min(c.byteLength,u+d)),h=m.indexOf(10);f=h===-1?m.byteLength:h+1}o.set(c.subarray(u,u+f),s),s+=f,u+=f;let p=o.subarray(0,s),y=Zn(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 H("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter exceeds the byte limit");let h=af(p.subarray(y.yamlStart,y.yamlEnd));return{properties:cf(h,n),frontmatterBytes:m,consumedBytes:y.blockEnd}}}if(s>=r)break}let i=o.subarray(0,s),a=Zn(i,!0);if(a===null)return{properties:{},frontmatterBytes:0,consumedBytes:i.length};if(a!==void 0){let c=a.yamlEnd-a.yamlStart;if(c<=n.bytes){let u=af(i.subarray(a.yamlStart,a.yamlEnd));return{properties:cf(u,n),frontmatterBytes:c,consumedBytes:a.blockEnd}}}throw new H("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter is not closed within the byte limit")};var Yr=async(t,e=R.hydratedFileBytes)=>{if(Number.isInteger(e)===!1||e<=0||e>R.hydratedFileBytes)throw new H("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown body byte limit is outside the supported range");let n;try{n=await $e(t,e)}catch(a){throw a instanceof re?new H("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown content exceeds the byte limit"):a}let r;try{r=le(n)}catch{throw new H("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}let s=Zn(n,!0)?.blockEnd??0,i;try{i=s===0?Tt(r):le(n.subarray(s))}catch{throw new H("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}return{body:i,bodyBytes:Ne(i),sourceBytes:n.byteLength}};var dt=class extends Error{code;referenceId;constructor({code:e,message:n,referenceId:r,cause:o}){super(n,{cause:o}),this.name="MarkdownDocumentError",this.code=e,this.referenceId=r}},ih=C({source:v(),body:v(),frontmatter:we(v(),nt())}),Xr=t=>{let e;try{e=ih.parse(t)}catch(n){throw new dt({code:"INVALID_DOCUMENT",message:"Markdown document is invalid",cause:n})}return Object.freeze({source:e.source,body:e.body,frontmatter:rt(e.frontmatter)})},Hr="#frontmatter",ah=t=>`${Hr}${t.slice(1)}`,ch=t=>{if(t!==Hr&&t.startsWith(`${Hr}/`)===!1)throw new dt({code:"UNUSED_REFERENCE",message:`Resolved Markdown reference ${t} is outside frontmatter`,referenceId:t});return`#${t.slice(Hr.length)}`},uh=t=>{let e=t.referenceId===void 0?void 0:ah(t.referenceId),n="INVALID_DOCUMENT";throw(t.code==="INVALID_REFERENCE_MARKER"||t.code==="INVALID_REFERENCE"||t.code==="REFERENCE_NOT_FOUND"||t.code==="INVALID_RESOLVED_VALUE"||t.code==="UNUSED_REFERENCE")&&(n=t.code),new dt({code:n,message:t.message,referenceId:e,cause:t})},lf=async({source:t,maximumBytes:e=R.hydratedFileBytes})=>{let n;try{n=await $e(t,e)}catch(i){throw i instanceof re?new dt({code:"CONTENT_LIMIT_EXCEEDED",message:"Markdown document exceeds the byte limit",cause:i}):i}let r;try{r=Tt(le(n))}catch(i){throw new dt({code:"CONTENT_DECODING_FAILED",message:"Markdown document is not valid UTF-8",cause:i})}let[o,s]=await Promise.all([Yr(n,e),uf(n)]);return Xr({source:r,body:o.body,frontmatter:s.properties})};var ff=({document:t,references:e,allowUnresolvedReferences:n=!1})=>{let r=Xr(t),o=new Map;for(let[i,a]of e)o.set(ch(i),a);let s;try{s=hr({document:r.frontmatter,references:o,allowUnresolvedReferences:n})}catch(i){throw i instanceof de&&uh(i),i}return Xr({...r,frontmatter:s})},df=({document:t,representation:e})=>{let n=Xr(t);if(e.type==="document")return n.source;if(e.type==="markdown-body")return n.body;if(e.type==="markdown-frontmatter")return n.frontmatter;throw new dt({code:"UNSUPPORTED_REPRESENTATION",message:`Markdown documents do not support ${e.type}`})};var pf=t=>{let e=t.format==="markdown"?t.value.frontmatter:t.value;return Pt(e)?e:void 0},eo=t=>Object.freeze(t),mf=async({format:t,source:e,maximumBytes:n=R.hydratedFileBytes})=>eo(t==="json"?{format:t,value:await dl({source:e,maximumBytes:n})}:{format:t,value:await lf({source:e,maximumBytes:n})});var hf=({document:t,references:e,allowUnresolvedReferences:n})=>t.format==="json"?eo({format:t.format,value:hr({document:t.value,references:e,allowUnresolvedReferences:n})}):eo({format:t.format,value:ff({document:t.value,references:e,allowUnresolvedReferences:n})}),yf=({document:t,representation:e})=>t.format==="json"?pl({document:t.value,representation:e}):df({document:t.value,representation:e});var to=class extends Error{code;documentId;expectedRevision;actualRevision;expectedFormat;actualFormat;constructor({code:e,documentId:n,expectedRevision:r,actualRevision:o,expectedFormat:s,actualFormat:i}){super(`Document ${n} source ${e==="REVISION_MISMATCH"?"revision":"format"} does not match its graph`),this.name="DocumentSourceError",this.code=e,this.documentId=n,this.expectedRevision=r,this.actualRevision=o,this.expectedFormat=s,this.actualFormat=i}},qt=({node:t,source:e})=>{if(e.revision!==t.revision)throw new to({code:"REVISION_MISMATCH",documentId:t.id,expectedRevision:t.revision,actualRevision:e.revision});if(t.format!==void 0&&e.format!==t.format)throw new to({code:"FORMAT_MISMATCH",documentId:t.id,expectedFormat:t.format,actualFormat:e.format});return e};var Kt=t=>{if(typeof t=="object"&&t!==null){let e=Reflect.get(t,"code");if(typeof e=="string"&&e.length>0)return e;let n=Reflect.get(t,"name");if(typeof n=="string"&&n.length>0)return n}return"UNKNOWN"},se=(t,e)=>{try{t?.(e)}catch{}},gf=({load:t,onEvent:e})=>async(n,r)=>{let o={documentId:n.id,revision:n.revision};se(e,{type:"document-fetch-started",...o});try{let s=await t(n,r);return se(e,{type:"document-fetch-completed",...o}),s}catch(s){throw se(e,{type:"document-fetch-failed",...o,errorCode:Kt(s)}),s}};var lh=C({format:ae(["json","markdown"]),revision:v().min(1)}),Wt=class extends Error{code;documentId;status;constructor({code:e,message:n,documentId:r,status:o,cause:s}){super(n,{cause:s}),this.name="HttpDocumentLoaderError",this.code=e,this.documentId=r,this.status=o}},fh=t=>({async*[Symbol.asyncIterator](){let e=t.getReader(),n=!1;try{for(;;){let r=await e.read();if(r.done){n=!0;return}yield r.value}}finally{if(n===!1)try{await e.cancel()}catch{}e.releaseLock()}}}),bf=({fetch:t,getRequest:e,getMetadata:n,onEvent:r})=>gf({load:async(s,{signal:i})=>{let a;try{a=await t(e(s),{signal:i})}catch(d){throw new Wt({code:"REQUEST_FAILED",message:`Document ${s.id} request failed`,documentId:s.id,cause:d})}if(a.ok===!1)throw new Wt({code:"HTTP_STATUS",message:`Document ${s.id} request returned status ${a.status}`,documentId:s.id,status:a.status});let c;try{c=lh.parse(n({node:s,response:a}))}catch(d){throw new Wt({code:"INVALID_METADATA",message:`Document ${s.id} response metadata is invalid`,documentId:s.id,cause:d})}let u=a.body;if(u===null)throw new Wt({code:"BODY_MISSING",message:`Document ${s.id} response body is unavailable`,documentId:s.id});return Object.freeze({...c,source:fh(u)})},onEvent:r});var Yt=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,_f=new Set,zs=typeof process=="object"&&process?process:{},xf=(t,e,n,r)=>{typeof zs.emitWarning=="function"?zs.emitWarning(t,e,n,r):console.error(`[${n}] ${e}: ${t}`)},no=globalThis.AbortController,wf=globalThis.AbortSignal;if(typeof no>"u"){wf=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},no=class{constructor(){e()}signal=new wf;abort(r){if(!this.signal.aborted){this.signal.reason=r,this.signal.aborted=!0;for(let o of this.signal._onabort)o(r);this.signal.onabort?.(r)}}};let t=zs.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,xf("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var dh=t=>!_f.has(t),tv=Symbol("type"),pt=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Sf=t=>pt(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Ht:null:null,Ht=class extends Array{constructor(e){super(e),this.fill(0)}},Ps=class t{heap;length;static#c=!1;static create(e){let n=Sf(e);if(!n)return[];t.#c=!0;let r=new t(e,n);return t.#c=!1,r}constructor(e,n){if(!t.#c)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new n(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Xt=class t{#c;#f;#h;#y;#O;#C;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#g;#r;#n;#e;#u;#d;#a;#s;#b;#i;#w;#_;#p;#x;#k;#l;static unsafeExposeInternals(e){return{starts:e.#_,ttls:e.#p,sizes:e.#w,keyMap:e.#r,keyList:e.#n,valList:e.#e,next:e.#u,prev:e.#d,get head(){return e.#a},get tail(){return e.#s},free:e.#b,isBackgroundFetch:n=>e.#t(n),backgroundFetch:(n,r,o,s)=>e.#T(n,r,o,s),moveToTail:n=>e.#I(n),indexes:n=>e.#S(n),rindexes:n=>e.#A(n),isStale:n=>e.#m(n)}}get max(){return this.#c}get maxSize(){return this.#f}get calculatedSize(){return this.#g}get size(){return this.#o}get fetchMethod(){return this.#O}get memoMethod(){return this.#C}get dispose(){return this.#h}get disposeAfter(){return this.#y}constructor(e){let{max:n=0,ttl:r,ttlResolution:o=1,ttlAutopurge:s,updateAgeOnGet:i,updateAgeOnHas:a,allowStale:c,dispose:u,disposeAfter:d,noDisposeOnSet:l,noUpdateTTL:f,maxSize:p=0,maxEntrySize:y=0,sizeCalculation:m,fetchMethod:h,memoMethod:b,noDeleteOnFetchRejection:S,noDeleteOnStaleGet:A,allowStaleOnFetchRejection:_,allowStaleOnFetchAbort:w,ignoreFetchAbort:E}=e;if(n!==0&&!pt(n))throw new TypeError("max option must be a nonnegative integer");let k=n?Sf(n):Array;if(!k)throw new Error("invalid max value: "+n);if(this.#c=n,this.#f=p,this.maxEntrySize=y||this.#f,this.sizeCalculation=m,this.sizeCalculation){if(!this.#f&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(b!==void 0&&typeof b!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#C=b,h!==void 0&&typeof h!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=h,this.#k=!!h,this.#r=new Map,this.#n=new Array(n).fill(void 0),this.#e=new Array(n).fill(void 0),this.#u=new k(n),this.#d=new k(n),this.#a=0,this.#s=0,this.#b=Ps.create(n),this.#o=0,this.#g=0,typeof u=="function"&&(this.#h=u),typeof d=="function"?(this.#y=d,this.#i=[]):(this.#y=void 0,this.#i=void 0),this.#x=!!this.#h,this.#l=!!this.#y,this.noDisposeOnSet=!!l,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!S,this.allowStaleOnFetchRejection=!!_,this.allowStaleOnFetchAbort=!!w,this.ignoreFetchAbort=!!E,this.maxEntrySize!==0){if(this.#f!==0&&!pt(this.#f))throw new TypeError("maxSize must be a positive integer if specified");if(!pt(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#B()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!A,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!a,this.ttlResolution=pt(o)||o===0?o:1,this.ttlAutopurge=!!s,this.ttl=r||0,this.ttl){if(!pt(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#z()}if(this.#c===0&&this.ttl===0&&this.#f===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#c&&!this.#f){let x="LRU_CACHE_UNBOUNDED";dh(x)&&(_f.add(x),xf("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",x,t))}}getRemainingTTL(e){return this.#r.has(e)?1/0:0}#z(){let e=new Ht(this.#c),n=new Ht(this.#c);this.#p=e,this.#_=n,this.#P=(s,i,a=Yt.now())=>{if(n[s]=i!==0?a:0,e[s]=i,i!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#m(s)&&this.#E(this.#n[s],"expire")},i+1);c.unref&&c.unref()}},this.#D=s=>{n[s]=e[s]!==0?Yt.now():0},this.#v=(s,i)=>{if(e[i]){let a=e[i],c=n[i];if(!a||!c)return;s.ttl=a,s.start=c,s.now=r||o();let u=s.now-c;s.remainingTTL=a-u}};let r=0,o=()=>{let s=Yt.now();if(this.ttlResolution>0){r=s;let i=setTimeout(()=>r=0,this.ttlResolution);i.unref&&i.unref()}return s};this.getRemainingTTL=s=>{let i=this.#r.get(s);if(i===void 0)return 0;let a=e[i],c=n[i];if(!a||!c)return 1/0;let u=(r||o())-c;return a-u},this.#m=s=>{let i=n[s],a=e[s];return!!a&&!!i&&(r||o())-i>a}}#D=()=>{};#v=()=>{};#P=()=>{};#m=()=>!1;#B(){let e=new Ht(this.#c);this.#g=0,this.#w=e,this.#R=n=>{this.#g-=e[n],e[n]=0},this.#L=(n,r,o,s)=>{if(this.#t(r))return 0;if(!pt(o))if(s){if(typeof s!="function")throw new TypeError("sizeCalculation must be a function");if(o=s(r,n),!pt(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#N=(n,r,o)=>{if(e[n]=r,this.#f){let s=this.#f-e[n];for(;this.#g>s;)this.#$(!0)}this.#g+=e[n],o&&(o.entrySize=r,o.totalCalculatedSize=this.#g)}}#R=e=>{};#N=(e,n,r)=>{};#L=(e,n,r,o)=>{if(r||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#S({allowStale:e=this.allowStale}={}){if(this.#o)for(let n=this.#s;!(!this.#M(n)||((e||!this.#m(n))&&(yield n),n===this.#a));)n=this.#d[n]}*#A({allowStale:e=this.allowStale}={}){if(this.#o)for(let n=this.#a;!(!this.#M(n)||((e||!this.#m(n))&&(yield n),n===this.#s));)n=this.#u[n]}#M(e){return e!==void 0&&this.#r.get(this.#n[e])===e}*entries(){for(let e of this.#S())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*rentries(){for(let e of this.#A())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*keys(){for(let e of this.#S()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*rkeys(){for(let e of this.#A()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*values(){for(let e of this.#S())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#A())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,n={}){for(let r of this.#S()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;if(s!==void 0&&e(s,this.#n[r],this))return this.get(this.#n[r],n)}}forEach(e,n=this){for(let r of this.#S()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;s!==void 0&&e.call(n,s,this.#n[r],this)}}rforEach(e,n=this){for(let r of this.#A()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;s!==void 0&&e.call(n,s,this.#n[r],this)}}purgeStale(){let e=!1;for(let n of this.#A({allowStale:!0}))this.#m(n)&&(this.#E(this.#n[n],"expire"),e=!0);return e}info(e){let n=this.#r.get(e);if(n===void 0)return;let r=this.#e[n],o=this.#t(r)?r.__staleWhileFetching:r;if(o===void 0)return;let s={value:o};if(this.#p&&this.#_){let i=this.#p[n],a=this.#_[n];if(i&&a){let c=i-(Yt.now()-a);s.ttl=c,s.start=Date.now()}}return this.#w&&(s.size=this.#w[n]),s}dump(){let e=[];for(let n of this.#S({allowStale:!0})){let r=this.#n[n],o=this.#e[n],s=this.#t(o)?o.__staleWhileFetching:o;if(s===void 0||r===void 0)continue;let i={value:s};if(this.#p&&this.#_){i.ttl=this.#p[n];let a=Yt.now()-this.#_[n];i.start=Math.floor(Date.now()-a)}this.#w&&(i.size=this.#w[n]),e.unshift([r,i])}return e}load(e){this.clear();for(let[n,r]of e){if(r.start){let o=Date.now()-r.start;r.start=Yt.now()-o}this.set(n,r.value,r)}}set(e,n,r={}){if(n===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:s,noDisposeOnSet:i=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=r,{noUpdateTTL:u=this.noUpdateTTL}=r,d=this.#L(e,n,r.size||0,a);if(this.maxEntrySize&&d>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#E(e,"set"),this;let l=this.#o===0?void 0:this.#r.get(e);if(l===void 0)l=this.#o===0?this.#s:this.#b.length!==0?this.#b.pop():this.#o===this.#c?this.#$(!1):this.#o,this.#n[l]=e,this.#e[l]=n,this.#r.set(e,l),this.#u[this.#s]=l,this.#d[l]=this.#s,this.#s=l,this.#o++,this.#N(l,d,c),c&&(c.set="add"),u=!1;else{this.#I(l);let f=this.#e[l];if(n!==f){if(this.#k&&this.#t(f)){f.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:p}=f;p!==void 0&&!i&&(this.#x&&this.#h?.(p,e,"set"),this.#l&&this.#i?.push([p,e,"set"]))}else i||(this.#x&&this.#h?.(f,e,"set"),this.#l&&this.#i?.push([f,e,"set"]));if(this.#R(l),this.#N(l,d,c),this.#e[l]=n,c){c.set="replace";let p=f&&this.#t(f)?f.__staleWhileFetching:f;p!==void 0&&(c.oldValue=p)}}else c&&(c.set="update")}if(o!==0&&!this.#p&&this.#z(),this.#p&&(u||this.#P(l,o,s),c&&this.#v(c,l)),!i&&this.#l&&this.#i){let f=this.#i,p;for(;p=f?.shift();)this.#y?.(...p)}return this}pop(){try{for(;this.#o;){let e=this.#e[this.#a];if(this.#$(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#l&&this.#i){let e=this.#i,n;for(;n=e?.shift();)this.#y?.(...n)}}}#$(e){let n=this.#a,r=this.#n[n],o=this.#e[n];return this.#k&&this.#t(o)?o.__abortController.abort(new Error("evicted")):(this.#x||this.#l)&&(this.#x&&this.#h?.(o,r,"evict"),this.#l&&this.#i?.push([o,r,"evict"])),this.#R(n),e&&(this.#n[n]=void 0,this.#e[n]=void 0,this.#b.push(n)),this.#o===1?(this.#a=this.#s=0,this.#b.length=0):this.#a=this.#u[n],this.#r.delete(r),this.#o--,n}has(e,n={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:o}=n,s=this.#r.get(e);if(s!==void 0){let i=this.#e[s];if(this.#t(i)&&i.__staleWhileFetching===void 0)return!1;if(this.#m(s))o&&(o.has="stale",this.#v(o,s));else return r&&this.#D(s),o&&(o.has="hit",this.#v(o,s)),!0}else o&&(o.has="miss");return!1}peek(e,n={}){let{allowStale:r=this.allowStale}=n,o=this.#r.get(e);if(o===void 0||!r&&this.#m(o))return;let s=this.#e[o];return this.#t(s)?s.__staleWhileFetching:s}#T(e,n,r,o){let s=n===void 0?void 0:this.#e[n];if(this.#t(s))return s;let i=new no,{signal:a}=r;a?.addEventListener("abort",()=>i.abort(a.reason),{signal:i.signal});let c={signal:i.signal,options:r,context:o},u=(m,h=!1)=>{let{aborted:b}=i.signal,S=r.ignoreFetchAbort&&m!==void 0;if(r.status&&(b&&!h?(r.status.fetchAborted=!0,r.status.fetchError=i.signal.reason,S&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),b&&!S&&!h)return l(i.signal.reason);let A=p;return this.#e[n]===p&&(m===void 0?A.__staleWhileFetching?this.#e[n]=A.__staleWhileFetching:this.#E(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,m,c.options))),m},d=m=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=m),l(m)),l=m=>{let{aborted:h}=i.signal,b=h&&r.allowStaleOnFetchAbort,S=b||r.allowStaleOnFetchRejection,A=S||r.noDeleteOnFetchRejection,_=p;if(this.#e[n]===p&&(!A||_.__staleWhileFetching===void 0?this.#E(e,"fetch"):b||(this.#e[n]=_.__staleWhileFetching)),S)return r.status&&_.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),_.__staleWhileFetching;if(_.__returned===_)throw m},f=(m,h)=>{let b=this.#O?.(e,s,c);b&&b instanceof Promise&&b.then(S=>m(S===void 0?void 0:S),h),i.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(m(void 0),r.allowStaleOnFetchAbort&&(m=S=>u(S,!0)))})};r.status&&(r.status.fetchDispatched=!0);let p=new Promise(f).then(u,d),y=Object.assign(p,{__abortController:i,__staleWhileFetching:s,__returned:void 0});return n===void 0?(this.set(e,y,{...c.options,status:void 0}),n=this.#r.get(e)):this.#e[n]=y,y}#t(e){if(!this.#k)return!1;let n=e;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof no}async fetch(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:l=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:y=this.allowStaleOnFetchAbort,context:m,forceRefresh:h=!1,status:b,signal:S}=n;if(!this.#k)return b&&(b.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,status:b});let A={allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,ttl:i,noDisposeOnSet:a,size:c,sizeCalculation:u,noUpdateTTL:d,noDeleteOnFetchRejection:l,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:y,ignoreFetchAbort:p,status:b,signal:S},_=this.#r.get(e);if(_===void 0){b&&(b.fetch="miss");let w=this.#T(e,_,A,m);return w.__returned=w}else{let w=this.#e[_];if(this.#t(w)){let T=r&&w.__staleWhileFetching!==void 0;return b&&(b.fetch="inflight",T&&(b.returnedStale=!0)),T?w.__staleWhileFetching:w.__returned=w}let E=this.#m(_);if(!h&&!E)return b&&(b.fetch="hit"),this.#I(_),o&&this.#D(_),b&&this.#v(b,_),w;let k=this.#T(e,_,A,m),O=k.__staleWhileFetching!==void 0&&r;return b&&(b.fetch=E?"stale":"refresh",O&&E&&(b.returnedStale=!0)),O?k.__staleWhileFetching:k.__returned=k}}async forceFetch(e,n={}){let r=await this.fetch(e,n);if(r===void 0)throw new Error("fetch() returned undefined");return r}memo(e,n={}){let r=this.#C;if(!r)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:s,...i}=n,a=this.get(e,i);if(!s&&a!==void 0)return a;let c=r(e,a,{options:i,context:o});return this.set(e,c,i),c}get(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,status:i}=n,a=this.#r.get(e);if(a!==void 0){let c=this.#e[a],u=this.#t(c);return i&&this.#v(i,a),this.#m(a)?(i&&(i.get="stale"),u?(i&&r&&c.__staleWhileFetching!==void 0&&(i.returnedStale=!0),r?c.__staleWhileFetching:void 0):(s||this.#E(e,"expire"),i&&r&&(i.returnedStale=!0),r?c:void 0)):(i&&(i.get="hit"),u?c.__staleWhileFetching:(this.#I(a),o&&this.#D(a),c))}else i&&(i.get="miss")}#F(e,n){this.#d[n]=e,this.#u[e]=n}#I(e){e!==this.#s&&(e===this.#a?this.#a=this.#u[e]:this.#F(this.#d[e],this.#u[e]),this.#F(this.#s,e),this.#s=e)}delete(e){return this.#E(e,"delete")}#E(e,n){let r=!1;if(this.#o!==0){let o=this.#r.get(e);if(o!==void 0)if(r=!0,this.#o===1)this.#Z(n);else{this.#R(o);let s=this.#e[o];if(this.#t(s)?s.__abortController.abort(new Error("deleted")):(this.#x||this.#l)&&(this.#x&&this.#h?.(s,e,n),this.#l&&this.#i?.push([s,e,n])),this.#r.delete(e),this.#n[o]=void 0,this.#e[o]=void 0,o===this.#s)this.#s=this.#d[o];else if(o===this.#a)this.#a=this.#u[o];else{let i=this.#d[o];this.#u[i]=this.#u[o];let a=this.#u[o];this.#d[a]=this.#d[o]}this.#o--,this.#b.push(o)}}if(this.#l&&this.#i?.length){let o=this.#i,s;for(;s=o?.shift();)this.#y?.(...s)}return r}clear(){return this.#Z("delete")}#Z(e){for(let n of this.#A({allowStale:!0})){let r=this.#e[n];if(this.#t(r))r.__abortController.abort(new Error("deleted"));else{let o=this.#n[n];this.#x&&this.#h?.(r,o,e),this.#l&&this.#i?.push([r,o,e])}}if(this.#r.clear(),this.#e.fill(void 0),this.#n.fill(void 0),this.#p&&this.#_&&(this.#p.fill(0),this.#_.fill(0)),this.#w&&this.#w.fill(0),this.#a=0,this.#s=0,this.#b.length=0,this.#g=0,this.#o=0,this.#l&&this.#i){let n=this.#i,r;for(;r=n?.shift();)this.#y?.(...r)}}};var Ls=({maximumBytes:t=R.hydratedTotalBytes*4}={})=>{if(Number.isSafeInteger(t)===!1||t<=0)throw new TypeError("Document source cache byte limit must be positive");return new Xt({maxSize:t,sizeCalculation:e=>Math.max(1,e.bytes.byteLength)})},Bn=class extends Error{code="CONTENT_LIMIT_EXCEEDED";documentId;contentByteLimit;constructor({message:e,documentId:n,contentByteLimit:r,cause:o}){super(e,{cause:o}),this.name="CachedDocumentLoaderError",this.documentId=n,this.contentByteLimit=r}},ro=({contentRef:t,revision:e,format:n})=>fe([t,e,n??null]),ph=t=>{if(typeof t!="object"||t===null)return!1;let e=t;return(e.format==="json"||e.format==="markdown")&&typeof e.revision=="string"&&e.revision.length>0&&e.bytes instanceof Uint8Array},Af=t=>Object.freeze({format:t.format,revision:t.revision,source:t.bytes}),Ef=({load:t,cache:e,maximumBytes:n=R.hydratedFileBytes,onEvent:r})=>{let o=new Map;return async(s,i)=>{let a=ro(s),c=o.get(a)??new Map;o.set(a,c);let u=c.get(i.signal);if(u!==void 0)return await u;let d=(async()=>{let l;try{l=await e.get(a)}catch(m){se(r,{type:"document-cache-read-failed",documentId:s.id,revision:s.revision,errorCode:Kt(m)})}if(ph(l)&&l.revision===s.revision&&l.bytes.byteLength<=n&&(s.format===void 0||l.format===s.format))return se(r,{type:"document-cache-hit",documentId:s.id,revision:s.revision}),Af(l);se(r,{type:"document-cache-miss",documentId:s.id,revision:s.revision});let f=qt({node:s,source:await t(s,i)}),p;try{p=await $e(f.source,n)}catch(m){throw m instanceof re?new Bn({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 e.set(a,y),se(r,{type:"document-cache-stored",documentId:s.id,revision:s.revision})}catch(m){se(r,{type:"document-cache-write-failed",documentId:s.id,revision:s.revision,errorCode:Kt(m)})}return Af(y)})();c.set(i.signal,d);try{return await d}finally{c.delete(i.signal),c.size===0&&o.delete(a)}}};var We=class extends Error{code;documentId;referenceId;constructor({code:e,message:n,documentId:r,referenceId:o,cause:s}){super(n,{cause:s}),this.name="DocumentGraphResolutionError",this.code=e,this.documentId=r,this.referenceId=o}},oo=t=>{if(t?.aborted)throw new We({code:"REQUEST_CANCELLED",message:"Document graph resolution was cancelled",cause:t.reason})},vf=async({graph:t,rootIds:e,concurrency:n,signal:r,load:o,select:s,assemble:i})=>{oo(r);let a=lr({graph:t,rootIds:e}),c=new Map(a.map(p=>[p.id,p])),u=new Map,d=new Map;for(let p of a){let y=d.get(p.contentRef);y===void 0?d.set(p.contentRef,{representative:p,nodes:[p]}):y.nodes.push(p)}await pr([...d.values()],n,async p=>{oo(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&&oo(r),new We({code:"DOCUMENT_LOAD_FAILED",message:`Document ${y.id} could not be loaded`,documentId:y.id,cause:m})}});let l=zt(t.edges),f=new Map;for(let p of a){oo(r);let y=new Map;for(let h of l.get(p.id)??[]){let b=c.get(h.reference.documentId);if(b===void 0||f.has(h.reference.documentId)===!1)throw new We({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${p.id} dependency ${h.reference.documentId} is unavailable`,documentId:p.id,referenceId:h.referenceId});let S=f.get(h.reference.documentId),A;if(s===void 0){if(h.reference.representation.type!=="document")throw new We({code:"REPRESENTATION_SELECTOR_REQUIRED",message:`Document ${p.id} reference ${h.referenceId} requires a representation selector`,documentId:p.id,referenceId:h.referenceId});A=S}else try{A=await s({reference:h.reference,value:S,sourceNode:p,targetNode:b})}catch(_){throw new We({code:"DOCUMENT_SELECTION_FAILED",message:`Document ${p.id} reference ${h.referenceId} could not be selected`,documentId:p.id,referenceId:h.referenceId,cause:_})}y.set(h.referenceId,A)}if(u.has(p.id)===!1)throw new We({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 We({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${p.id} could not be assembled`,documentId:p.id,cause:h})}}return Object.freeze({roots:Object.freeze(e.map(p=>f.get(p))),values:f})};var St=class extends Error{code;documentId;documentCount;documentLimit;contentByteLimit;totalBytes;totalByteLimit;constructor({code:e,message:n,documentId:r,documentCount:o,documentLimit:s,contentByteLimit:i,totalBytes:a,totalByteLimit:c,cause:u}){super(n,{cause:u}),this.name="DocumentResolutionLimitError",this.code=e,this.documentId=r,this.documentCount=o,this.documentLimit=s,this.contentByteLimit=i,this.totalBytes=a,this.totalByteLimit=c}},mh=(t,e)=>{let n=0,r=[],o=async()=>{if(e?.throwIfAborted(),n<t){n+=1;return}await new Promise((i,a)=>{let c,u=()=>{let d=r.indexOf(c);d!==-1&&r.splice(d,1);try{e?.throwIfAborted()}catch(l){a(l)}};c={start:()=>{e?.removeEventListener("abort",u),i()}},r.push(c),e?.addEventListener("abort",u,{once:!0})})},s=()=>{let i=r.shift();if(i===void 0){n-=1;return}i.start()};return async i=>{await o();try{return await i()}finally{s()}}},hh=async({graph:t,rootIds:e,concurrency:n,maximumBytes:r,maximumTotalBytes:o=R.hydratedTotalBytes,maximumDocuments:s=R.hydratedFileCount,signal:i,onEvent:a,allowUnresolvedReferences:c=!1,load:u})=>{let d=lr({graph:t,rootIds:e}).length,l={rootCount:e.length,documentCount:d};se(a,{type:"resolution-started",...l});try{if(d>s)throw new St({code:"DOCUMENT_COUNT_EXCEEDED",message:"Document graph resolution exceeds the document limit",documentCount:d,documentLimit:s});let f=0,p=Promise.resolve(),y=await vf({graph:t,rootIds:e,concurrency:n,signal:i,load:async(m,h)=>{let b=p,S=()=>{};p=new Promise(_=>{S=_});let A;try{A={status:"fulfilled",value:await u(m,h)}}catch(_){A={status:"rejected",reason:_}}await b;try{if(A.status==="rejected")throw A.reason;if(A.value.byteLength>r)throw new St({code:"CONTENT_LIMIT_EXCEEDED",message:`Document ${m.id} exceeds the byte limit`,documentId:m.id,contentByteLimit:r,cause:new re});let _=f+A.value.byteLength;if(_>o)throw new St({code:"TOTAL_BYTES_EXCEEDED",message:"Document graph resolution exceeds the total byte limit",documentId:m.id,totalBytes:_,totalByteLimit:o});return f=_,await A.value.parse()}finally{S()}},select:({reference:m,value:h})=>yf({document:h,representation:m.representation}),assemble:({source:m,references:h})=>hf({document:m,references:h,allowUnresolvedReferences:c})});return se(a,{type:"resolution-completed",...l}),y}catch(f){throw se(a,{type:"resolution-failed",...l,errorCode:Kt(f)}),f}},kf=({load:t,concurrency:e,signal:n,maximumDocumentBytes:r=R.hydratedFileBytes,maximumCacheBytes:o=R.hydratedTotalBytes*4})=>{if(Number.isSafeInteger(e)===!1||e<=0)throw new TypeError("Document resolution concurrency must be positive");if(Number.isSafeInteger(r)===!1||r<=0)throw new TypeError("Document resolution byte limit must be positive");if(Number.isSafeInteger(o)===!1||o<=0)throw new TypeError("Document resolution cache byte limit must be positive");let s=new Xt({maxSize:o,sizeCalculation:({byteLength:f})=>Math.max(1,f)}),i=new Map,a=mh(e,n),c=f=>{if(f!==void 0&&f!==n)throw new TypeError("Document resolution session signal does not match");n?.throwIfAborted()},u=async f=>(c(),n===void 0?await f:await new Promise((p,y)=>{let m=()=>n.removeEventListener("abort",h),h=()=>{m();try{n.throwIfAborted()}catch(b){y(b)}};n.addEventListener("abort",h,{once:!0}),f.then(b=>{m(),p(b)},b=>{m(),y(b)}),n.aborted&&h()})),d=async(f,p)=>{c(p.signal);let y=ro(f),m=s.get(y);if(m!==void 0)return m;let h=i.get(y);if(h!==void 0)return await u(h);let b=a(async()=>{c(p.signal);let S=qt({node:f,source:await t(f,{signal:n})});c(p.signal);let A=await Ko(S.source,r+1);c(p.signal);let _,w=Object.freeze({format:S.format,revision:S.revision,bytes:A,byteLength:A.byteLength,parse:()=>(_??=mf({format:S.format,source:A,maximumBytes:r}),_)});return w.byteLength<=o&&s.set(y,w),w});i.set(y,b);try{return await u(b)}finally{i.delete(y)}};return Object.freeze({getCached:f=>{c();let p=s.get(ro(f));if(!(p===void 0||p.byteLength>r))return Object.freeze({format:p.format,revision:p.revision,source:p.bytes.slice()})},resolve:async f=>await hh({...f,concurrency:e,maximumBytes:r,signal:n,load:d})})};var Df=t=>{if(t.output.mode==="all")return"all";let e=[];for(let{field:n}of yn(t.where))n[0]==="properties"&&e.push(n);for(let{field:n}of t.sort)n[0]==="properties"&&e.push(n);if(t.output.mode==="fields")for(let n of t.output.fields)n[0]==="properties"&&e.push(n);return e},Rf=t=>{let e;if(t==="#frontmatter")e="";else if(t.startsWith("#frontmatter/"))e=t.slice(12);else if(t==="#")e="";else if(t.startsWith("#/"))e=t.slice(1);else return;try{return["properties",...fl(e)]}catch{return}},If=(t,e)=>{let n=Math.min(t.length,e.length);for(let r=0;r<n;r+=1)if(t[r]!==e[r])return!1;return!0},Of=({queryPaths:t,referenceId:e})=>{let n=Rf(e);return n!==void 0&&(t==="all"||t.some(r=>If(r,n)))},Cf=({graph:t,sourceId:e,field:n})=>n[0]!=="properties"?!1:t.edges.some(r=>{if(r.sourceId!==e)return!1;let o=Rf(r.referenceId);return o!==void 0&&If(n,o)}),Nf=({graph:t,query:e})=>{let n=Df(e),r=new Set;for(let o of t.edges)Of({queryPaths:n,referenceId:o.referenceId})&&r.add(o.sourceId);return[...r]},$f=({graph:t,query:e,rootIds:n})=>{let r=Df(e),o=new Set(n),s=new Map(t.nodes.map(l=>[l.id,l])),i=zt(t.edges),a=new Set(n),c=new Set,u=new Set,d=l=>{if(a.add(l),!u.has(l)){u.add(l);for(let f of i.get(l)??[])c.add(f),d(f.reference.documentId)}};for(let l of t.edges)o.has(l.sourceId)&&Of({queryPaths:r,referenceId:l.referenceId})&&(c.add(l),d(l.reference.documentId));return bn({nodes:[...a].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:[...c]})};var Tf=({artifact:t})=>{if(t.documentGraph===void 0)return;let e=new Map(t.documents.map(s=>[s._id,s])),n=new Map(t.documentGraph.nodes.map(s=>[s.id,s])),r=new Map;for(let{sourceId:s}of t.documentGraph.edges){if(n.has(s))continue;let i=e.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:bn({nodes:[...n.values()],edges:t.documentGraph.edges.map(({sourceId:s,referenceId:i,documentId:a,representation:c})=>{let u=n.get(a);if(u===void 0)throw new Error(`Runtime document graph target ${a} is unavailable`);return{sourceId:s,referenceId:i,reference:{documentId:a,revision:u.revision,representation:c}}})}),inlineDocuments:r}};var yh=(t,e)=>{if(e===void 0||e.length===0)return t;let n=new URL("https://content.webstudio.invalid/__assets__/"),r=new URL(t,n),o=new URL(e,n);for(let[a,c]of o.searchParams)r.searchParams.append(a,c);if(o.hash!==""&&(r.hash=o.hash),URL.canParse(t))return r.href;if(t.startsWith("//"))return`//${r.host}${r.pathname}${r.search}${r.hash}`;if(t.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}`},zf=({markdown:t,references:e,assetUrls:n})=>{let r=t.length,o=t;for(let s of[...e].sort((i,a)=>a.start-i.start)){if(s.start<0||s.end<=s.start||s.end>t.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 a=yh(i,s.suffix);o=`${o.slice(0,s.start)}${a}${o.slice(s.end)}`}return o};var ie=class extends Error{code;details;constructor({code:e,message:n,details:r}){super(n),this.name="AssetResourceHydrationError",this.code=e,this.details=r}},gh=t=>{if(t===null)return[];let e=Array.isArray(t)?t:[t],n=new Map;for(let r of e){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 ie({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 ie({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())},bh=t=>typeof t.mimeType=="string"&&(t.mimeType.startsWith("text/")||["application/json","application/javascript","application/xml","image/svg+xml"].includes(t.mimeType)),wh=async({read:t,contentRef:e,range:n,maximumBytes:r})=>{if(r===0)return new Uint8Array;let o=await t(e,n);try{return await $e(o.data,r)}catch(s){throw s instanceof re?new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Asset storage returned more content than requested"}):s}},_h=t=>{try{return le(t)}catch{throw new ie({code:"CONTENT_DECODING_FAILED",message:"Selected asset content is not valid UTF-8"})}},xh=(t,e)=>{if(e.mode==="range")return Math.max(0,Math.min(e.length,t.size-e.offset));let n=e.maxBytes??R.hydratedFileBytes;if(t.size>n)throw new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected asset exceeds the per-file content limit",details:{assetId:t._id,assetBytes:t.size,fileByteLimit:n}});return t.size},Pf=async({result:t,documents:e,options:n,read:r,assetReferences:o,assetUrls:s})=>{if(n.mode==="none")return{content:{},hydratedFileCount:0,hydratedBytes:0};let i=gh(t);if(i.length>R.hydratedFileCount)throw new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Too many selected assets requested content hydration",details:{fileCount:i.length,fileCountLimit:R.hydratedFileCount}});let a=new Map(e.map(l=>[l._id,l])),c=i.map(l=>{let f=a.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 ie({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(bh(p)===!1)throw new ie({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:xh(p,n)}}),u=c.reduce((l,f)=>l+f.readLength,0);if(u>R.hydratedTotalBytes)throw new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected assets exceed the total hydrated-content limit",details:{totalReadBytes:u,totalByteLimit:R.hydratedTotalBytes}});let d=await pr(c,R.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 wh({read:r,contentRef:l.identity.contentRef,range:f,maximumBytes:l.readLength});if(p.byteLength!==l.readLength)throw new ie({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-ref")try{y=(await Yr(p,l.readLength||1)).body;let h=o?.[l.identity.contentRef];h!==void 0&&s!==void 0&&(y=zf({markdown:y,references:h,assetUrls:s}))}catch{throw new ie({code:"CONTENT_DECODING_FAILED",message:"Selected Markdown body could not be decoded",details:{assetId:l.identity._id}})}else y=_h(p);let m=Ne(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:c.length,hydratedBytes:d.reduce((l,{returnedBytes:f})=>l+f,0)}};var Fv=v().datetime({offset:!0}).transform(t=>new Date(t).toISOString());var Sh=/^[A-Za-z_][A-Za-z0-9_]*$/,Lf=(t,e)=>Sh.test(e)?`${t}.${e}`:`${t}[${JSON.stringify(e)}]`;var Mf=({document:t,includes:e})=>{let n={};for(let r of rl){let o=t[r];o!==void 0&&e(r)&&(n[r]=o)}return n},mt=Symbol("missing property selection"),Ms=(t,e)=>{if(e.some(r=>r.length===0)||typeof mr(t)=="string")return t;if(Array.isArray(t)){let r=e.filter(([s])=>s==="*").map(s=>s.slice(1));if(r.length===0)return mt;let o=t.map(s=>Ms(s,r));return o.some(s=>s!==mt)?o.map(s=>s===mt?null:s):mt}if(typeof t!="object"||t===null)return mt;let n={};for(let[r,o]of Object.entries(t)){let s=e.filter(([a])=>a===r).map(a=>a.slice(1));if(s.length===0)continue;let i=Ms(o,s);i!==mt&&(n[r]=i)}return Object.keys(n).length===0?mt:n},Ff=({properties:t,fields:e})=>{let n=e.filter(([o])=>o==="properties").map(o=>o.slice(1)),r=Ms(t,n);return r===mt?{}:r};var Zf=t=>Object.fromEntries(Object.entries(t??{}).map(([e,n])=>[e,n.url]));var Bf=(t,e)=>{if(e===void 0)return t;let n="https://content.webstudio.invalid",r=new URL(t,`${n}/`),o=new URL(e,`${n}/`);for(let[s,i]of o.searchParams)r.searchParams.append(s,i);return o.hash!==""&&(r.hash=o.hash),t.startsWith("//")?`//${r.host}${r.pathname}${r.search}${r.hash}`:t.startsWith("/")?`${r.pathname}${r.search}${r.hash}`:r.href},Fs=({value:t,path:e,replacement:n})=>{let[r,...o]=e;if(r===void 0)return n;if(typeof t!="object"||t===null||Object.hasOwn(t,r)===!1)return t;if(Array.isArray(t)){if(typeof r!="number")return t;let s=[...t];return s[r]=Fs({value:t[r],path:o,replacement:n}),s}return typeof r!="string"?t:{...t,[r]:Fs({value:t[r],path:o,replacement:n})}},Ah=({reference:t,runtimeAsset:e})=>{let{url:n,contentRef:r,...o}=e;return{...o,id:t.assetId,src:Bf(n,t.suffix)}},en=({value:t,references:e,runtimeAssets:n={},assetUrls:r})=>{let o=t;for(let s of e??[]){let i=r?.[s.assetId],a=n[s.assetId]??(i===void 0?void 0:{url:i});a!==void 0&&(o=Fs({value:o,path:s.path,replacement:s.structured===!0?Ah({reference:s,runtimeAsset:a}):Bf(a.url,s.suffix)}))}return o};var Oe=class extends Error{constructor(e,n){super(e,n),this.name="AssetQueryExecutionError"}},jn=class extends Oe{code="MULTIPLE_RESULTS";matchedCount;constructor(e){super(`Expected at most one asset, but the query matched ${e}.`),this.matchedCount=e,this.name="AssetQueryMultipleResultsError"}},nn=class extends Error{constructor(){super("The requested asset index revision is stale"),this.name="AssetIndexRevisionError"}},jf=t=>{if(t[0]!=="properties")return t[0];let e="properties";for(let n of t.slice(1))e=Lf(e,n);return e},Uf=({filter:t,fieldTypes:e})=>il(e).includes(t.operator),Qf=(t,e)=>t!==void 0&&Object.hasOwn(t.fields,e)?t.fields[e]:void 0,Eh=({query:t,catalog:e})=>{let n=ot.parse(t),r=new Map,o=[];for(let s of yn(n.where)){let i=jf(s.field);if(r.set(i,s.field),s.field[0]==="properties"){let a=Qf(e,i);e!==void 0&&a===void 0?o.push(`Asset field ${i} is not currently observed`):a!==void 0&&Uf({filter:s,fieldTypes:a.types})===!1&&o.push(`Operator ${s.operator} is not compatible with the currently observed types of ${i}`)}else if(Uf({filter:s,fieldTypes:ts[s.field[0]]})===!1)throw new Oe(`Operator ${s.operator} is incompatible with ${i}`)}for(let s of n.sort){let i=jf(s.field);if(r.set(i,s.field),s.field[0]==="properties"){let a=Qf(e,i);e!==void 0&&a===void 0?o.push(`Asset field ${i} is not currently observed`):a!==void 0&&a.types.some(c=>c==="object"||c==="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)]}},Bs=(t,e,n)=>{let r=e[0]==="id"?t._id:dr(e[0])?n?.[e[0]]:t[e[0]];for(let o of e.slice(1)){if(typeof r!="object"||r===null||Object.hasOwn(r,o)===!1)return;r=r[o]}return r},vh=t=>typeof t=="string"||Array.isArray(t)?t.length===0:typeof t=="object"&&t!==null&&Object.keys(t).length===0,kh=(t,e)=>{if(typeof t=="number"&&typeof e=="number")return t-e;if(typeof t=="string"&&typeof e=="string")return Te(t,e)},js=(t,e,n)=>{let r=Bs(t,e.field,n);if(e.operator==="exists")return r!=null===e.value;if(e.operator==="isEmpty")return vh(r)===e.value;if(e.operator==="eq")return gn(r,e.value);if(e.operator==="ne")return gn(r,e.value)===!1;if(e.operator==="in")return e.value.some(s=>gn(r,s));if(e.operator==="contains")return typeof r=="string"&&typeof e.value=="string"?r.includes(e.value):Array.isArray(r)&&r.some(s=>gn(s,e.value));if(e.operator==="startsWith")return typeof r=="string"&&typeof e.value=="string"&&r.startsWith(e.value);if(e.operator==="endsWith")return typeof r=="string"&&typeof e.value=="string"&&r.endsWith(e.value);let o=kh(r,e.value);return o===void 0?!1:e.operator==="gt"?o>0:e.operator==="gte"?o>=0:e.operator==="lt"?o<0:o<=0},Dh=({document:t,where:e,runtimeAsset:n,filterKeys:r,filterResults:o})=>Ct(e,s=>{let i=r.get(s)??fe(s),a=o.get(i);if(a!==void 0)return a;let c=js(t,s,n);return o.set(i,c),c})===!0,Rh=({document:t,content:e})=>e.mode!=="markdown-body-ref"||t.mimeType==="text/markdown"||t.extension==="md",Ih=(t,e)=>{let n=t==null,r=e==null;return n||r?n===r?0:n?1:-1:typeof t=="number"&&typeof e=="number"?t-e:(typeof t=="string"||typeof t=="boolean")&&(typeof e=="string"||typeof e=="boolean")?Te(String(t),String(e)):Te(fe(t),fe(e))},Oh=({left:t,right:e,sort:n,runtimeAssets:r})=>{for(let o of n){let s=Ih(Bs(t,o.field,r?.[t._id]),Bs(e,o.field,r?.[e._id]));if(s!==0)return o.direction==="asc"?s:-s}return Te(t._id,e._id)};var Ch=(t,e)=>{if(t.properties===void 0)return;if(e.mode==="all")return Object.keys(t.properties).length===0?void 0:t.properties;if(e.mode!=="fields"||e.fields.some(r=>r[0]==="properties")===!1)return;let n=Ff({properties:t.properties,fields:e.fields});return Object.keys(n).length===0?void 0:n},tn=(t,e)=>t.includeMetadata&&ol(e)||t.mode==="fields"&&t.fields.some(n=>n.length===1&&n[0]===e),Nh=t=>t.mode==="all"||t.mode==="fields"&&t.fields.some(e=>e.length===1&&e[0]==="excerpt"),$h=(t,e,n)=>{if(tn(e,"url")&&n===void 0)throw new Error(`Asset URL is unavailable for ${t._id}`);let r=Ch(t,e),o=n?.width!==void 0&&n.height!==void 0;return{...n!==void 0&&tn(e,"url")?{url:n.url}:{},...o&&tn(e,"width")?{width:n.width}:{},...o&&tn(e,"height")?{height:n.height}:{},...Mf({document:t,includes:s=>tn(e,s)}),...r===void 0?{}:{properties:r},...t.excerpt===void 0||Nh(e)===!1?{}:{excerpt:t.excerpt},...t.metadataError===void 0||e.includeMetadata===!1?{}:{metadataError:t.metadataError}}},Us=t=>{if(Ne(fe(t))>R.resultBytes)throw new Oe("Asset query result exceeds the byte limit")},so=(t,e,n)=>{t[e]={status:"rejected",reason:n}},Th=({inputs:t,catalog:e,results:n})=>{let r=new Map,o=new Map,s=[];for(let[i,a]of t.entries()){let c;try{c=Eh({query:a,catalog:e}).query}catch(l){so(n,i,l);continue}for(let l of yn(c.where))o.set(l,fe(l));let u=fe(c.sort),d=r.get(u);d===void 0&&(d={sort:c.sort,documents:new Set,sorted:[]},r.set(u,d)),s.push({index:i,query:c,matches:new Map,sortGroup:d})}return{filterKeys:o,preparedQueries:s,sortGroups:r}},Vf=({preparedQueries:t,results:e,createReason:n})=>{for(let{index:r}of t)so(e,r,n())},Zs=t=>t.map(e=>{if(e===void 0)throw new Error("Asset query result was not settled");return e}),zh=({preparedQueries:t,documents:e,filterKeys:n,sortGroups:r,results:o,runtimeAssets:s})=>{for(let i of e){let a=s?.[i._id],c=new Map;for(let u of t){if(o[u.index]!==void 0)continue;let{query:d}=u;try{if(Rh({document:i,content:d.content})===!1||Dh({document:i,where:d.where,runtimeAsset:a,filterKeys:n,filterResults:c})===!1)continue;let l=$h(i,d.output,a);if(d.content.mode==="none"&&Object.keys(l).length===0&&tn(d.output,"id")===!1)continue;let f={document:i,item:{id:i._id,...l}};u.matches.set(i,f),u.sortGroup.documents.add(i)}catch(l){so(o,u.index,l)}}}for(let i of r.values())i.sorted=[...i.documents].sort((a,c)=>Oh({left:a,right:c,sort:i.sort,runtimeAssets:s}))},Ph=async({preparedQueries:t,results:e,read:n,assetReferences:r,assetUrls:o})=>{await Promise.all(t.map(async s=>{if(e[s.index]!==void 0)return;let{query:i}=s;try{let a=s.sortGroup.sorted.flatMap(p=>{let y=s.matches.get(p);return y===void 0?[]:[y]}),c=i.result??"many";if(c==="one"&&a.length>1)throw new jn(a.length);let u=c==="many"?a.slice(i.offset,i.offset+i.limit):c==="last"?a.slice(-1):a.slice(0,1),d=u.map(({document:p})=>p),l=u.map(({item:p})=>p);if(i.content.mode!=="none"){let p=i.content;if(n===void 0)throw new Oe("Asset content reader is unavailable");let y=await Pf({result:d,documents:d,options:p,read:n,assetReferences:r,assetUrls:r===void 0?void 0:o});l=d.map((m,h)=>{let b=y.content[m._id];if(b===void 0)throw new Oe("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=c==="many"?{items:l,totalCount:a.length,hasMore:i.offset+u.length<a.length}:{item:l[0]??null,totalCount:a.length};Us(f),e[s.index]={status:"fulfilled",value:f}}catch(a){so(e,s.index,a)}}))},Gf=async({queries:t,catalog:e,documents:n,read:r,runtimeAssets:o,assetReferences:s,assetValueReferences:i})=>{let a=Array.from({length:t.length}),{filterKeys:c,preparedQueries:u,sortGroups:d}=Th({inputs:t,catalog:e,results:a});if(n.length>R.candidateDocuments)return Vf({preparedQueries:u,results:a,createReason:()=>new Oe("Asset query document limit was exceeded")}),Zs(a);let l;try{l=n.map(p=>en({value:p,references:i?.[p._id],runtimeAssets:o??{}}))}catch(p){return Vf({preparedQueries:u,results:a,createReason:()=>p}),Zs(a)}zh({preparedQueries:u,documents:l,filterKeys:c,sortGroups:d,results:a,runtimeAssets:o});let f=Zf(o);return await Ph({preparedQueries:u,results:a,read:r,assetReferences:s,assetUrls:f}),Zs(a)};var Lh=async t=>await Gu(fe(ot.parse(t)));var Mh=({item:t,field:e,value:n})=>{let r=t;for(let[o,s]of e.entries()){if(o===e.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 a={};Object.defineProperty(r,s,{value:a,enumerable:!0,configurable:!0,writable:!0}),r=a}},Fh=t=>ns.parse({items:t.rows.map(e=>{let n={};for(let[r,o]of t.fields.entries())Mh({item:n,field:o,value:e[r]});return n}),totalCount:t.totalCount,hasMore:t.hasMore}),Jf=async({queries:t,query:e,assetValueReferences:n,runtimeAssets:r={}})=>{if(t===void 0)return;let o=t[await Lh(ot.parse(e))];if(o===void 0)return;let s=Fh(o),i={...s,items:s.items.map(a=>en({value:a,references:n?.[a.id],runtimeAssets:r}))};return Us(i),i};var Zh=(t,e)=>e===void 0?$t(t):{async*[Symbol.asyncIterator](){let n=0,r=0;for await(let o of $t(t)){if(r===e.length)return;if(n+o.byteLength<=e.offset){n+=o.byteLength;continue}let s=Math.max(0,e.offset-n),i=Math.min(o.byteLength-s,e.length-r);i>0&&(yield o.subarray(s,s+i),r+=i),n+=o.byteLength}}},Bh=({graph:t,load:e,getCached:n,readFallback:r,signal:o})=>{let s=new Map(t.nodes.map(i=>[i.contentRef,i]));return async(i,a)=>{let c=s.get(i);if(c===void 0){if(r!==void 0)return await r(i,a);throw new Error(`Document content reference ${i} is unavailable`)}let u=qt({node:c,source:n(c)??await e(c,{signal:o})});return{data:Zh(u.source,a),...a===void 0?{}:{contentLength:a.length}}}},jh=({artifact:t,revision:e,catalog:n,documentGraph:r,inlineDocuments:o,readContent:s})=>{let i=new Map(t.documents.map(w=>[w._id,w])),a=w=>{if(w.indexRevision!==void 0&&w.indexRevision!==e)throw new nn},c=w=>async(E,k)=>{let x=t.contents?.[E];if(x===void 0){let G=w??s;if(G===void 0)throw new Error("Content is not embedded in this database");return await G(E,k)}let O=Nt(x),T=k===void 0?O:O.slice(k.offset,k.offset+k.length);return{data:async function*(){yield T}(),contentLength:T.byteLength}},u=w=>{if(w.status==="rejected")throw w.reason;return w.value},d=async({requests:w,queryContentReader:E,runtimeAssets:k,documents:x=t.documents})=>await Gf({queries:w.map(({query:O})=>O),catalog:n,documents:x,read:c(E),runtimeAssets:k,assetReferences:t.assetReferences,assetValueReferences:t.assetValueReferences}),l=async({request:w,...E})=>u((await d({...E,requests:[w]}))[0]),f=async({requests:w,queryContentReader:E,runtimeAssets:k})=>{let x=Array.from({length:w.length}),O=[];for(let[T,G]of w.entries()){try{a(G);let z=await Jf({queries:t.queries,query:G.query,assetValueReferences:t.assetValueReferences,runtimeAssets:k});if(z!==void 0){x[T]={status:"fulfilled",value:z};continue}}catch(z){x[T]={status:"rejected",reason:z};continue}O.push(T)}if(O.length>0){let T=await d({requests:O.map(G=>w[G]),queryContentReader:E,runtimeAssets:k});for(let[G,z]of O.entries())x[z]=T[G]}return x.map(T=>{if(T===void 0)throw new Error("Content database query was not settled");return T})},p=async(w,E,k)=>u((await f({requests:[w],queryContentReader:E,runtimeAssets:k}))[0]),y=async(...w)=>await p(...w),m=w=>async(E,k)=>{let x=o?.get(E.id);return x!==void 0?{format:"json",revision:E.revision,source:JSON.stringify(x.properties)}:await w(E,k)},h=({graph:w,query:E,runtimeAssets:k})=>Nf({graph:w,query:E}).filter(x=>{let O=i.get(x),T=O===void 0?void 0:en({value:O,references:t.assetValueReferences?.[x],runtimeAssets:k??{}});return T===void 0?!1:Ct(E.where,G=>{if(!Cf({graph:w,sourceId:x,field:G.field}))return js(T,G,k?.[x])})!==!1}),b=({rootIds:w,roots:E})=>{let k=new Map(w.flatMap((x,O)=>{let T=pf(E[O]);return T===void 0?[]:[[x,T]]}));return t.documents.map(x=>{let O=k.get(x._id);return O===void 0?x:es.parse({...x,properties:O})})},S=async({request:w,graph:E,resolutionSession:k,contentReader:x,runtimeAssets:O,onEvent:T})=>{a(w);let G=ot.parse(w.query),z=h({graph:E,query:G,runtimeAssets:O});if(z.length===0)return await p(w,x,O);let ht=$f({graph:E,query:G,rootIds:z});se(T,{type:"roots-selected",rootCount:z.length});let ao=await k.resolve({graph:ht,rootIds:z,onEvent:T,allowUnresolvedReferences:!0}),co=b({rootIds:z,roots:ao.roots});return await l({request:w,queryContentReader:x,runtimeAssets:O,documents:co})},A=async({requests:w,load:E,resolutionSession:k,readContent:x,runtimeAssets:O,signal:T,onEvent:G})=>{if(r===void 0)return await f({requests:w,queryContentReader:x,runtimeAssets:O});let z=m(E),ht=k??kf({load:z,concurrency:R.concurrentContentReads,signal:T}),ao=Bh({graph:r,load:z,getCached:ht.getCached,readFallback:x??s,signal:T});return await Promise.allSettled(w.map(co=>S({request:co,graph:r,resolutionSession:ht,contentReader:ao,runtimeAssets:O,onEvent:G})))};return{query:y,queryManyWithDocumentGraph:A,queryWithDocumentGraph:async({request:w,...E})=>u((await A({...E,requests:[w]}))[0])}};var Qs=({artifact:t,readContent:e})=>{let n=Tf({artifact:t});return jh({artifact:t,revision:t.revision,documentGraph:n?.graph,inlineDocuments:n?.inlineDocuments,readContent:e})};var io=class extends Error{constructor(e,n){super(e,n),this.name="AssetQueryRequestError"}},Un=class extends Error{},Uh=async(t,e)=>{if(Number.isSafeInteger(e)===!1||e<0)throw new TypeError("Request byte limit must be a non-negative integer");let n=Number(t.headers.get("content-length"));if(Number.isFinite(n)&&n>e)throw new Un("Request exceeds the byte limit");let r=t.body?.getReader(),o=[],s=0;if(r!==void 0)for(;;){let{done:c,value:u}=await r.read();if(c)break;if(s+=u.byteLength,s>e){try{await r.cancel()}catch{}throw new Un("Request exceeds the byte limit")}o.push(u)}let i=new Uint8Array(s),a=0;for(let c of o)i.set(c,a),a+=c.byteLength;return i},qf=async t=>{let e;try{e=await Uh(t,R.requestBytes)}catch(n){throw n instanceof Un?new io("Asset query request exceeds the byte limit",{cause:n}):n}try{return al.parse(JSON.parse(le(e)))}catch(n){throw new io("Asset query request is invalid",{cause:n})}};var Kf=t=>{if(t instanceof nn)return{code:"STALE_INDEX",message:t.message,retryable:!1,status:409};if(t instanceof jn)return{code:t.code,message:t.message,retryable:!1,details:{matchedCount:t.matchedCount},status:409};if(t instanceof Oe)return{code:"INVALID_REQUEST",message:t.message,retryable:!1,status:400};if(t instanceof ie)return{code:t.code,message:t.message,retryable:!1,details:t.details,status:400};let e=new Set,n=t;for(;n!==void 0&&e.has(n)===!1;){if(n instanceof St){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 Bn)return{code:"CONTENT_LIMIT_EXCEEDED",message:n.message,retryable:!1,details:{assetId:n.documentId,contentByteLimit:n.contentByteLimit},status:400};e.add(n),n=n instanceof Error?n.cause:void 0}};var Qh="/$resources/assets",Wf=(t,e=200)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json; charset=utf-8"}}),Qn=({code:t,message:e,status:n,retryable:r=!1,details:o})=>Wf(ll({code:t,message:e,retryable:r,details:o}),n),Vh=(t,e,n)=>typeof t=="string"||t instanceof URL?new Request(new URL(t,e),n):new Request(t,n),Gh=async({deploymentId:t,artifact:e,request:n})=>{let r=await n.clone().text(),o=n.headers.get("cache-control"),s=await Yo(JSON.stringify([t,e.revision,r,o])),i=new URL(n.url);return i.searchParams.set("ws-asset-resource",s),new Request(i,{method:"GET"})},Nk=({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,fetchDocument:s=globalThis.fetch,onDocumentGraphEvent:i})=>{Yf({artifact:e,runtimeAssets:n});let a=Ls();return Hf({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,database:Qs({artifact:e}),fetchDocument:s,documentCache:a,onDocumentGraphEvent:i})},Jh=({baseUrl:t,runtimeAssets:e,fetchDocument:n,cache:r,onEvent:o})=>Ef({cache:r,onEvent:o,load:bf({fetch:n,getRequest:s=>{let i=e[s.id];if(i===void 0)throw new Error(`Published document URL is unavailable for ${s.id}`);return new URL(i.url,t)},getMetadata:({node:s})=>({format:s.format,revision:s.revision}),onEvent:o})}),Yf=({artifact:t,runtimeAssets:e})=>{let n=[t.assetReferences,t.assetValueReferences].flatMap(s=>Object.values(s??{}).flat()).map(({assetId:s})=>s).find(s=>e[s]===void 0);if(n!==void 0)throw new Error(`Published referenced asset URL is unavailable for ${n}`);let r=t.documentGraph?.nodes.find(({id:s})=>e[s]===void 0)?.id;if(r!==void 0)throw new Error(`Published document URL is unavailable for ${r}`);let o=t.documentGraph?.nodes.find(({id:s,contentRef:i})=>e[s]?.contentRef!==i)?.id;if(o!==void 0)throw new Error(`Published document identity does not match graph node ${o}`)},Hf=({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,database:s,fetchDocument:i,documentCache:a,onDocumentGraphEvent:c})=>{let u=new URL(o).origin,d=Jh({baseUrl:o,runtimeAssets:n,fetchDocument:i,cache:a,onEvent:c});return async(l,f)=>{let p=Vh(l,o,f),y=new URL(p.url);if(y.origin!==u||y.pathname!==Qh||p.method.toUpperCase()!=="POST")return;let m;try{m=await qf(p.clone())}catch{return Qn({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 Gh({deploymentId:t,artifact:e,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 Qn({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let b=Wf(await s.queryWithDocumentGraph({request:m,load:d,runtimeAssets:n,signal:p.signal,onEvent:c}));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 Qn({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let S=Kf(b);return Qn(S!==void 0?S:{code:"INTERNAL_ERROR",message:"Published asset query failed",status:500,retryable:!0})}}},$k=({deploymentId:t,artifact:e,runtimeAssets:n,onDocumentGraphEvent:r=void 0})=>{let o=globalThis.caches,s,i=()=>(s??=o.open(`webstudio-assets-${t}`),s),a=o===void 0?void 0:{match:async d=>(await i()).match(d),put:async(d,l)=>(await i()).put(d,l)};Yf({artifact:e,runtimeAssets:n});let c=Qs({artifact:e}),u=Ls();return async({request:d,fallback:l})=>{let f=new URL(d.url).origin,p=Hf({deploymentId:t,artifact:e,runtimeAssets:n,cache:a,baseUrl:f,database:c,fetchDocument:l,documentCache:u,onDocumentGraphEvent:r});return async(y,m)=>await p(y,m)??l(y,m)}};export{$k as createGeneratedAssetResourceRuntime,Nk as createPublishedAssetResourceFetch};+`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){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=Wr(e),r=qt(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=Wr(e),r=qt(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){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:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};function ch(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Fn||null,prettyErrors:e}}function Ls(t,e={}){let{lineCounter:n,prettyErrors:r}=ch(e),o=new Zn(n?.addNewLine),s=new Ln(e),i=null;for(let a of s.compose(o.parse(t),!0,t.length))if(!i)i=a;else if(i.options.logLevel!=="silent"){i.errors.push(new Re(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(i.errors.forEach(Es(t,n)),i.warnings.forEach(Es(t,n))),i}var Ie=class extends Error{code;constructor(e){super(`Structured data failed validation: ${e}`),this.name="StructuredDataError",this.code=e}},fh=t=>Ne(JSON.stringify(t)),ff=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},df=(t,e)=>{if(ff(t)===!1)throw new Ie("INVALID");let n=0,r=(s,i)=>{if(i>e.depth)throw new Ie("DEPTH_EXCEEDED");if(typeof s=="string"){if(Ne(s)>e.stringBytes)throw new Ie("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(a=>{if(n+=1,n>e.fields)throw new Ie("FIELDS_EXCEEDED");return r(a,i+1)});if(ff(s)){let a=Object.create(null);for(let[c,u]of Object.entries(s)){if(n+=1,n>e.fields)throw new Ie("FIELDS_EXCEEDED");a[c]=r(u,i+1)}return a}throw new Ie("INVALID")},o=r(t,1);if(fh(o)>e.serializedBytes)throw new Ie("SERIALIZED_BYTES_EXCEEDED");return o};var H=class extends Error{code;constructor(e,n){super(n),this.name="MarkdownMetadataError",this.code=e}};var Kt=new Uint8Array([239,187,191]),pf=Kt.byteLength+10,dh=(t,e,n=0)=>t.byteLength-n<e.byteLength?!1:e.every((r,o)=>t[n+o]===r),Bn=(t,e)=>{let n=0;if(dh(t,Kt))n=Kt.byteLength;else if(t.byteLength<Kt.byteLength&&Kt.slice(0,t.byteLength).every((s,i)=>s===t[i]))return e?null:void 0;if(t.byteLength<n+4)return e?null:void 0;if(t[n]!==45||t[n+1]!==45||t[n+2]!==45)return null;let r=n+3;if(t[r]===10)r+=1;else if(t[r]===13){if(t.byteLength===r+1)return e?null:void 0;if(t[r+1]!==10)return null;r+=2}else return null;let o=r;for(let s=r;s<=t.byteLength;s+=1){let i=s===t.byteLength;if(i===!1&&t[s]!==10)continue;if(i&&e===!1)return;let a=s;if(a>o&&t[a-1]===13&&(a-=1),a-o===3&&(t[o]===45&&t[o+1]===45&&t[o+2]===45||t[o]===46&&t[o+1]===46&&t[o+2]===46))return{yamlStart:r,yamlEnd:o,blockEnd:i?s:s+1};o=s+1}};var ph={bytes:k.frontmatterBytes,depth:k.frontmatterDepth,fields:k.frontmatterFields,stringBytes:k.frontmatterStringBytes,serializedBytes:k.indexedPropertiesBytes},mf=t=>{try{return le(t)}catch{throw new H("FRONTMATTER_DECODING_FAILED","Markdown frontmatter is not valid UTF-8")}},hf=(t,e)=>{let n=Ls(t,{schema:"core",uniqueKeys:!0});if(n.errors.length>0)throw new H("FRONTMATTER_INVALID","Markdown frontmatter contains invalid YAML");let r;try{r=n.toJS({maxAliasCount:0})}catch{throw new H("FRONTMATTER_INVALID","Markdown frontmatter contains unsupported YAML aliases")}if(r===null)return{};try{return df(r,e)}catch(o){throw o instanceof Ie?o.code==="DEPTH_EXCEEDED"?new H("FRONTMATTER_DEPTH_EXCEEDED","Markdown frontmatter exceeds the nesting limit"):o.code==="FIELDS_EXCEEDED"?new H("FRONTMATTER_FIELDS_EXCEEDED","Markdown frontmatter exceeds the field limit"):o.code==="STRING_BYTES_EXCEEDED"?new H("FRONTMATTER_STRING_BYTES_EXCEEDED","Markdown frontmatter contains a string that exceeds the byte limit"):o.code==="SERIALIZED_BYTES_EXCEEDED"?new H("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter properties exceed the indexed byte limit"):new H("FRONTMATTER_INVALID","Markdown frontmatter must contain a JSON-compatible object"):o}},yf=async(t,e={})=>{let n={...ph,...e},r=n.bytes+pf,o=new Uint8Array(r),s=0;for await(let c of $t(t)){let u=0;for(;u<c.byteLength;){let p=r-s;if(p<=0)break;let l=Math.max(0,6-s),f=Math.min(c.byteLength-u,l);if(l===0){let m=c.subarray(u,Math.min(c.byteLength,u+p)),h=m.indexOf(10);f=h===-1?m.byteLength:h+1}o.set(c.subarray(u,u+f),s),s+=f,u+=f;let d=o.subarray(0,s),y=Bn(d,!1);if(y===null)return{properties:{},frontmatterBytes:0,consumedBytes:d.length};if(y!==void 0){let m=y.yamlEnd-y.yamlStart;if(m>n.bytes)throw new H("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter exceeds the byte limit");let h=mf(d.subarray(y.yamlStart,y.yamlEnd));return{properties:hf(h,n),frontmatterBytes:m,consumedBytes:y.blockEnd}}}if(s>=r)break}let i=o.subarray(0,s),a=Bn(i,!0);if(a===null)return{properties:{},frontmatterBytes:0,consumedBytes:i.length};if(a!==void 0){let c=a.yamlEnd-a.yamlStart;if(c<=n.bytes){let u=mf(i.subarray(a.yamlStart,a.yamlEnd));return{properties:hf(u,n),frontmatterBytes:c,consumedBytes:a.blockEnd}}}throw new H("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter is not closed within the byte limit")};var Hr=async(t,e=k.hydratedFileBytes)=>{if(Number.isInteger(e)===!1||e<=0||e>k.hydratedFileBytes)throw new H("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown body byte limit is outside the supported range");let n;try{n=await Te(t,e)}catch(a){throw a instanceof re?new H("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown content exceeds the byte limit"):a}let r;try{r=le(n)}catch{throw new H("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}let s=Bn(n,!0)?.blockEnd??0,i;try{i=s===0?zt(r):le(n.subarray(s))}catch{throw new H("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}return{body:i,bodyBytes:Ne(i),sourceBytes:n.byteLength}};var dt=class extends Error{code;referenceId;constructor({code:e,message:n,referenceId:r,cause:o}){super(n,{cause:o}),this.name="MarkdownDocumentError",this.code=e,this.referenceId=r}},mh=C({source:v(),body:v(),frontmatter:we(v(),nt())}),eo=t=>{let e;try{e=mh.parse(t)}catch(n){throw new dt({code:"INVALID_DOCUMENT",message:"Markdown document is invalid",cause:n})}return Object.freeze({source:e.source,body:e.body,frontmatter:rt(e.frontmatter)})},Xr="#frontmatter",hh=t=>`${Xr}${t.slice(1)}`,yh=t=>{if(t!==Xr&&t.startsWith(`${Xr}/`)===!1)throw new dt({code:"UNUSED_REFERENCE",message:`Resolved Markdown reference ${t} is outside frontmatter`,referenceId:t});return`#${t.slice(Xr.length)}`},gh=t=>{let e=t.referenceId===void 0?void 0:hh(t.referenceId),n="INVALID_DOCUMENT";throw(t.code==="INVALID_REFERENCE_MARKER"||t.code==="INVALID_REFERENCE"||t.code==="REFERENCE_NOT_FOUND"||t.code==="INVALID_RESOLVED_VALUE"||t.code==="UNUSED_REFERENCE")&&(n=t.code),new dt({code:n,message:t.message,referenceId:e,cause:t})},gf=async({source:t,maximumBytes:e=k.hydratedFileBytes})=>{let n;try{n=await Te(t,e)}catch(i){throw i instanceof re?new dt({code:"CONTENT_LIMIT_EXCEEDED",message:"Markdown document exceeds the byte limit",cause:i}):i}let r;try{r=zt(le(n))}catch(i){throw new dt({code:"CONTENT_DECODING_FAILED",message:"Markdown document is not valid UTF-8",cause:i})}let[o,s]=await Promise.all([Hr(n,e),yf(n)]);return eo({source:r,body:o.body,frontmatter:s.properties})};var bf=({document:t,references:e,allowUnresolvedReferences:n=!1})=>{let r=eo(t),o=new Map;for(let[i,a]of e)o.set(yh(i),a);let s;try{s=yr({document:r.frontmatter,references:o,allowUnresolvedReferences:n})}catch(i){throw i instanceof de&&gh(i),i}return eo({...r,frontmatter:s})},wf=({document:t,representation:e})=>{let n=eo(t);if(e.type==="document")return n.source;if(e.type==="markdown-body")return n.body;if(e.type==="markdown-frontmatter")return n.frontmatter;throw new dt({code:"UNSUPPORTED_REPRESENTATION",message:`Markdown documents do not support ${e.type}`})};var _f=t=>Object.fromEntries(Object.entries(t??{}).map(([e,n])=>[e,n.url]));var to=(t,e)=>{if(e===void 0||e.length===0)return t;let n=new URL("https://content.webstudio.invalid/__assets__/"),r=new URL(t,n),o=new URL(e,n);for(let[a,c]of o.searchParams)r.searchParams.append(a,c);if(o.hash!==""&&(r.hash=o.hash),t.startsWith("//"))return`//${r.host}${r.pathname}${r.search}${r.hash}`;if(t.startsWith("/"))return`${r.pathname}${r.search}${r.hash}`;let s=!1;try{new URL(t),s=!0}catch{}return s?r.href:`${r.pathname.startsWith(n.pathname)?r.pathname.slice(n.pathname.length):r.pathname}${r.search}${r.hash}`},Ms=({value:t,path:e,replacement:n})=>{let[r,...o]=e;if(r===void 0)return n;if(typeof t!="object"||t===null||Object.hasOwn(t,r)===!1)return t;if(Array.isArray(t)){if(typeof r!="number")return t;let s=[...t];return s[r]=Ms({value:t[r],path:o,replacement:n}),s}return typeof r!="string"?t:{...t,[r]:Ms({value:t[r],path:o,replacement:n})}},bh=({reference:t,runtimeAsset:e})=>{let{url:n,contentRef:r,...o}=e;return{...o,id:t.assetId,src:to(n,t.suffix)}},pt=({value:t,references:e,runtimeAssets:n={},assetUrls:r})=>{let o=t;for(let s of e??[]){let i=r?.[s.assetId],a=n[s.assetId]??(i===void 0?void 0:{url:i});a!==void 0&&(o=Ms({value:o,path:s.path,replacement:s.structured===!0?bh({reference:s,runtimeAsset:a}):to(a.url,s.suffix)}))}return o};var ro=t=>{let e=t.format==="json"?t.value:t.value.frontmatter;return Lt(e)?e:void 0},Fs=({document:t,references:e,runtimeAssets:n})=>{let r=ro(t);if(r===void 0||e===void 0)return t;let o=pt({value:{properties:r},references:e,runtimeAssets:n}).properties;return t.format==="json"?Object.freeze({...t,value:o}):Object.freeze({...t,value:Object.freeze({...t.value,frontmatter:o})})},no=t=>Object.freeze(t),xf=async({format:t,source:e,maximumBytes:n=k.hydratedFileBytes})=>no(t==="json"?{format:t,value:await wl({source:e,maximumBytes:n})}:{format:t,value:await gf({source:e,maximumBytes:n})});var Sf=({document:t,references:e,allowUnresolvedReferences:n})=>t.format==="json"?no({format:t.format,value:yr({document:t.value,references:e,allowUnresolvedReferences:n})}):no({format:t.format,value:bf({document:t.value,references:e,allowUnresolvedReferences:n})}),Af=({document:t,representation:e})=>t.format==="json"?_l({document:t.value,representation:e}):wf({document:t.value,representation:e});var oo=class extends Error{code;documentId;expectedRevision;actualRevision;expectedFormat;actualFormat;constructor({code:e,documentId:n,expectedRevision:r,actualRevision:o,expectedFormat:s,actualFormat:i}){super(`Document ${n} source ${e==="REVISION_MISMATCH"?"revision":"format"} does not match its graph`),this.name="DocumentSourceError",this.code=e,this.documentId=n,this.expectedRevision=r,this.actualRevision=o,this.expectedFormat=s,this.actualFormat=i}},Wt=({node:t,source:e})=>{if(e.revision!==t.revision)throw new oo({code:"REVISION_MISMATCH",documentId:t.id,expectedRevision:t.revision,actualRevision:e.revision});if(t.format!==void 0&&e.format!==t.format)throw new oo({code:"FORMAT_MISMATCH",documentId:t.id,expectedFormat:t.format,actualFormat:e.format});return e};var Yt=t=>{if(typeof t=="object"&&t!==null){let e=Reflect.get(t,"code");if(typeof e=="string"&&e.length>0)return e;let n=Reflect.get(t,"name");if(typeof n=="string"&&n.length>0)return n}return"UNKNOWN"},se=(t,e)=>{try{t?.(e)}catch{}},Ef=({load:t,onEvent:e})=>async(n,r)=>{let o={documentId:n.id,revision:n.revision};se(e,{type:"document-fetch-started",...o});try{let s=await t(n,r);return se(e,{type:"document-fetch-completed",...o}),s}catch(s){throw se(e,{type:"document-fetch-failed",...o,errorCode:Yt(s)}),s}};var wh=C({format:ae(wn),revision:v().min(1)}),Ht=class extends Error{code;documentId;status;constructor({code:e,message:n,documentId:r,status:o,cause:s}){super(n,{cause:s}),this.name="HttpDocumentLoaderError",this.code=e,this.documentId=r,this.status=o}},vf=({fetch:t,getRequest:e,getMetadata:n,onEvent:r})=>Ef({load:async(s,{signal:i})=>{let a;try{a=await t(e(s),{signal:i})}catch(p){throw new Ht({code:"REQUEST_FAILED",message:`Document ${s.id} request failed`,documentId:s.id,cause:p})}if(a.ok===!1)throw new Ht({code:"HTTP_STATUS",message:`Document ${s.id} request returned status ${a.status}`,documentId:s.id,status:a.status});let c;try{c=wh.parse(n({node:s,response:a}))}catch(p){throw new Ht({code:"INVALID_METADATA",message:`Document ${s.id} response metadata is invalid`,documentId:s.id,cause:p})}let u=a.body;if(u===null)throw new Ht({code:"BODY_MISSING",message:`Document ${s.id} response body is unavailable`,documentId:s.id});return Object.freeze({...c,source:Ku(u)})},onEvent:r});var Xt=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Rf=new Set,Zs=typeof process=="object"&&process?process:{},kf=(t,e,n,r)=>{typeof Zs.emitWarning=="function"?Zs.emitWarning(t,e,n,r):console.error(`[${n}] ${e}: ${t}`)},so=globalThis.AbortController,Df=globalThis.AbortSignal;if(typeof so>"u"){Df=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},so=class{constructor(){e()}signal=new Df;abort(r){if(!this.signal.aborted){this.signal.reason=r,this.signal.aborted=!0;for(let o of this.signal._onabort)o(r);this.signal.onabort?.(r)}}};let t=Zs.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,kf("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var _h=t=>!Rf.has(t),dv=Symbol("type"),mt=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),If=t=>mt(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?en:null:null,en=class extends Array{constructor(e){super(e),this.fill(0)}},Bs=class t{heap;length;static#c=!1;static create(e){let n=If(e);if(!n)return[];t.#c=!0;let r=new t(e,n);return t.#c=!1,r}constructor(e,n){if(!t.#c)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new n(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},tn=class t{#c;#f;#h;#y;#O;#C;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#g;#r;#n;#e;#u;#d;#a;#s;#b;#i;#w;#_;#p;#x;#D;#l;static unsafeExposeInternals(e){return{starts:e.#_,ttls:e.#p,sizes:e.#w,keyMap:e.#r,keyList:e.#n,valList:e.#e,next:e.#u,prev:e.#d,get head(){return e.#a},get tail(){return e.#s},free:e.#b,isBackgroundFetch:n=>e.#t(n),backgroundFetch:(n,r,o,s)=>e.#$(n,r,o,s),moveToTail:n=>e.#I(n),indexes:n=>e.#S(n),rindexes:n=>e.#A(n),isStale:n=>e.#m(n)}}get max(){return this.#c}get maxSize(){return this.#f}get calculatedSize(){return this.#g}get size(){return this.#o}get fetchMethod(){return this.#O}get memoMethod(){return this.#C}get dispose(){return this.#h}get disposeAfter(){return this.#y}constructor(e){let{max:n=0,ttl:r,ttlResolution:o=1,ttlAutopurge:s,updateAgeOnGet:i,updateAgeOnHas:a,allowStale:c,dispose:u,disposeAfter:p,noDisposeOnSet:l,noUpdateTTL:f,maxSize:d=0,maxEntrySize:y=0,sizeCalculation:m,fetchMethod:h,memoMethod:b,noDeleteOnFetchRejection:S,noDeleteOnStaleGet:A,allowStaleOnFetchRejection:_,allowStaleOnFetchAbort:w,ignoreFetchAbort:E}=e;if(n!==0&&!mt(n))throw new TypeError("max option must be a nonnegative integer");let D=n?If(n):Array;if(!D)throw new Error("invalid max value: "+n);if(this.#c=n,this.#f=d,this.maxEntrySize=y||this.#f,this.sizeCalculation=m,this.sizeCalculation){if(!this.#f&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(b!==void 0&&typeof b!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#C=b,h!==void 0&&typeof h!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=h,this.#D=!!h,this.#r=new Map,this.#n=new Array(n).fill(void 0),this.#e=new Array(n).fill(void 0),this.#u=new D(n),this.#d=new D(n),this.#a=0,this.#s=0,this.#b=Bs.create(n),this.#o=0,this.#g=0,typeof u=="function"&&(this.#h=u),typeof p=="function"?(this.#y=p,this.#i=[]):(this.#y=void 0,this.#i=void 0),this.#x=!!this.#h,this.#l=!!this.#y,this.noDisposeOnSet=!!l,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!S,this.allowStaleOnFetchRejection=!!_,this.allowStaleOnFetchAbort=!!w,this.ignoreFetchAbort=!!E,this.maxEntrySize!==0){if(this.#f!==0&&!mt(this.#f))throw new TypeError("maxSize must be a positive integer if specified");if(!mt(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#B()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!A,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!a,this.ttlResolution=mt(o)||o===0?o:1,this.ttlAutopurge=!!s,this.ttl=r||0,this.ttl){if(!mt(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#z()}if(this.#c===0&&this.ttl===0&&this.#f===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#c&&!this.#f){let x="LRU_CACHE_UNBOUNDED";_h(x)&&(Rf.add(x),kf("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",x,t))}}getRemainingTTL(e){return this.#r.has(e)?1/0:0}#z(){let e=new en(this.#c),n=new en(this.#c);this.#p=e,this.#_=n,this.#P=(s,i,a=Xt.now())=>{if(n[s]=i!==0?a:0,e[s]=i,i!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#m(s)&&this.#E(this.#n[s],"expire")},i+1);c.unref&&c.unref()}},this.#R=s=>{n[s]=e[s]!==0?Xt.now():0},this.#v=(s,i)=>{if(e[i]){let a=e[i],c=n[i];if(!a||!c)return;s.ttl=a,s.start=c,s.now=r||o();let u=s.now-c;s.remainingTTL=a-u}};let r=0,o=()=>{let s=Xt.now();if(this.ttlResolution>0){r=s;let i=setTimeout(()=>r=0,this.ttlResolution);i.unref&&i.unref()}return s};this.getRemainingTTL=s=>{let i=this.#r.get(s);if(i===void 0)return 0;let a=e[i],c=n[i];if(!a||!c)return 1/0;let u=(r||o())-c;return a-u},this.#m=s=>{let i=n[s],a=e[s];return!!a&&!!i&&(r||o())-i>a}}#R=()=>{};#v=()=>{};#P=()=>{};#m=()=>!1;#B(){let e=new en(this.#c);this.#g=0,this.#w=e,this.#k=n=>{this.#g-=e[n],e[n]=0},this.#L=(n,r,o,s)=>{if(this.#t(r))return 0;if(!mt(o))if(s){if(typeof s!="function")throw new TypeError("sizeCalculation must be a function");if(o=s(r,n),!mt(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#N=(n,r,o)=>{if(e[n]=r,this.#f){let s=this.#f-e[n];for(;this.#g>s;)this.#T(!0)}this.#g+=e[n],o&&(o.entrySize=r,o.totalCalculatedSize=this.#g)}}#k=e=>{};#N=(e,n,r)=>{};#L=(e,n,r,o)=>{if(r||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#S({allowStale:e=this.allowStale}={}){if(this.#o)for(let n=this.#s;!(!this.#M(n)||((e||!this.#m(n))&&(yield n),n===this.#a));)n=this.#d[n]}*#A({allowStale:e=this.allowStale}={}){if(this.#o)for(let n=this.#a;!(!this.#M(n)||((e||!this.#m(n))&&(yield n),n===this.#s));)n=this.#u[n]}#M(e){return e!==void 0&&this.#r.get(this.#n[e])===e}*entries(){for(let e of this.#S())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*rentries(){for(let e of this.#A())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*keys(){for(let e of this.#S()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*rkeys(){for(let e of this.#A()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*values(){for(let e of this.#S())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#A())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,n={}){for(let r of this.#S()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;if(s!==void 0&&e(s,this.#n[r],this))return this.get(this.#n[r],n)}}forEach(e,n=this){for(let r of this.#S()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;s!==void 0&&e.call(n,s,this.#n[r],this)}}rforEach(e,n=this){for(let r of this.#A()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;s!==void 0&&e.call(n,s,this.#n[r],this)}}purgeStale(){let e=!1;for(let n of this.#A({allowStale:!0}))this.#m(n)&&(this.#E(this.#n[n],"expire"),e=!0);return e}info(e){let n=this.#r.get(e);if(n===void 0)return;let r=this.#e[n],o=this.#t(r)?r.__staleWhileFetching:r;if(o===void 0)return;let s={value:o};if(this.#p&&this.#_){let i=this.#p[n],a=this.#_[n];if(i&&a){let c=i-(Xt.now()-a);s.ttl=c,s.start=Date.now()}}return this.#w&&(s.size=this.#w[n]),s}dump(){let e=[];for(let n of this.#S({allowStale:!0})){let r=this.#n[n],o=this.#e[n],s=this.#t(o)?o.__staleWhileFetching:o;if(s===void 0||r===void 0)continue;let i={value:s};if(this.#p&&this.#_){i.ttl=this.#p[n];let a=Xt.now()-this.#_[n];i.start=Math.floor(Date.now()-a)}this.#w&&(i.size=this.#w[n]),e.unshift([r,i])}return e}load(e){this.clear();for(let[n,r]of e){if(r.start){let o=Date.now()-r.start;r.start=Xt.now()-o}this.set(n,r.value,r)}}set(e,n,r={}){if(n===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:s,noDisposeOnSet:i=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=r,{noUpdateTTL:u=this.noUpdateTTL}=r,p=this.#L(e,n,r.size||0,a);if(this.maxEntrySize&&p>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#E(e,"set"),this;let l=this.#o===0?void 0:this.#r.get(e);if(l===void 0)l=this.#o===0?this.#s:this.#b.length!==0?this.#b.pop():this.#o===this.#c?this.#T(!1):this.#o,this.#n[l]=e,this.#e[l]=n,this.#r.set(e,l),this.#u[this.#s]=l,this.#d[l]=this.#s,this.#s=l,this.#o++,this.#N(l,p,c),c&&(c.set="add"),u=!1;else{this.#I(l);let f=this.#e[l];if(n!==f){if(this.#D&&this.#t(f)){f.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:d}=f;d!==void 0&&!i&&(this.#x&&this.#h?.(d,e,"set"),this.#l&&this.#i?.push([d,e,"set"]))}else i||(this.#x&&this.#h?.(f,e,"set"),this.#l&&this.#i?.push([f,e,"set"]));if(this.#k(l),this.#N(l,p,c),this.#e[l]=n,c){c.set="replace";let d=f&&this.#t(f)?f.__staleWhileFetching:f;d!==void 0&&(c.oldValue=d)}}else c&&(c.set="update")}if(o!==0&&!this.#p&&this.#z(),this.#p&&(u||this.#P(l,o,s),c&&this.#v(c,l)),!i&&this.#l&&this.#i){let f=this.#i,d;for(;d=f?.shift();)this.#y?.(...d)}return this}pop(){try{for(;this.#o;){let e=this.#e[this.#a];if(this.#T(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#l&&this.#i){let e=this.#i,n;for(;n=e?.shift();)this.#y?.(...n)}}}#T(e){let n=this.#a,r=this.#n[n],o=this.#e[n];return this.#D&&this.#t(o)?o.__abortController.abort(new Error("evicted")):(this.#x||this.#l)&&(this.#x&&this.#h?.(o,r,"evict"),this.#l&&this.#i?.push([o,r,"evict"])),this.#k(n),e&&(this.#n[n]=void 0,this.#e[n]=void 0,this.#b.push(n)),this.#o===1?(this.#a=this.#s=0,this.#b.length=0):this.#a=this.#u[n],this.#r.delete(r),this.#o--,n}has(e,n={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:o}=n,s=this.#r.get(e);if(s!==void 0){let i=this.#e[s];if(this.#t(i)&&i.__staleWhileFetching===void 0)return!1;if(this.#m(s))o&&(o.has="stale",this.#v(o,s));else return r&&this.#R(s),o&&(o.has="hit",this.#v(o,s)),!0}else o&&(o.has="miss");return!1}peek(e,n={}){let{allowStale:r=this.allowStale}=n,o=this.#r.get(e);if(o===void 0||!r&&this.#m(o))return;let s=this.#e[o];return this.#t(s)?s.__staleWhileFetching:s}#$(e,n,r,o){let s=n===void 0?void 0:this.#e[n];if(this.#t(s))return s;let i=new so,{signal:a}=r;a?.addEventListener("abort",()=>i.abort(a.reason),{signal:i.signal});let c={signal:i.signal,options:r,context:o},u=(m,h=!1)=>{let{aborted:b}=i.signal,S=r.ignoreFetchAbort&&m!==void 0;if(r.status&&(b&&!h?(r.status.fetchAborted=!0,r.status.fetchError=i.signal.reason,S&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),b&&!S&&!h)return l(i.signal.reason);let A=d;return this.#e[n]===d&&(m===void 0?A.__staleWhileFetching?this.#e[n]=A.__staleWhileFetching:this.#E(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,m,c.options))),m},p=m=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=m),l(m)),l=m=>{let{aborted:h}=i.signal,b=h&&r.allowStaleOnFetchAbort,S=b||r.allowStaleOnFetchRejection,A=S||r.noDeleteOnFetchRejection,_=d;if(this.#e[n]===d&&(!A||_.__staleWhileFetching===void 0?this.#E(e,"fetch"):b||(this.#e[n]=_.__staleWhileFetching)),S)return r.status&&_.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),_.__staleWhileFetching;if(_.__returned===_)throw m},f=(m,h)=>{let b=this.#O?.(e,s,c);b&&b instanceof Promise&&b.then(S=>m(S===void 0?void 0:S),h),i.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(m(void 0),r.allowStaleOnFetchAbort&&(m=S=>u(S,!0)))})};r.status&&(r.status.fetchDispatched=!0);let d=new Promise(f).then(u,p),y=Object.assign(d,{__abortController:i,__staleWhileFetching:s,__returned:void 0});return n===void 0?(this.set(e,y,{...c.options,status:void 0}),n=this.#r.get(e)):this.#e[n]=y,y}#t(e){if(!this.#D)return!1;let n=e;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof so}async fetch(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:p=this.noUpdateTTL,noDeleteOnFetchRejection:l=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:d=this.ignoreFetchAbort,allowStaleOnFetchAbort:y=this.allowStaleOnFetchAbort,context:m,forceRefresh:h=!1,status:b,signal:S}=n;if(!this.#D)return b&&(b.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,status:b});let A={allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,ttl:i,noDisposeOnSet:a,size:c,sizeCalculation:u,noUpdateTTL:p,noDeleteOnFetchRejection:l,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:y,ignoreFetchAbort:d,status:b,signal:S},_=this.#r.get(e);if(_===void 0){b&&(b.fetch="miss");let w=this.#$(e,_,A,m);return w.__returned=w}else{let w=this.#e[_];if(this.#t(w)){let $=r&&w.__staleWhileFetching!==void 0;return b&&(b.fetch="inflight",$&&(b.returnedStale=!0)),$?w.__staleWhileFetching:w.__returned=w}let E=this.#m(_);if(!h&&!E)return b&&(b.fetch="hit"),this.#I(_),o&&this.#R(_),b&&this.#v(b,_),w;let D=this.#$(e,_,A,m),O=D.__staleWhileFetching!==void 0&&r;return b&&(b.fetch=E?"stale":"refresh",O&&E&&(b.returnedStale=!0)),O?D.__staleWhileFetching:D.__returned=D}}async forceFetch(e,n={}){let r=await this.fetch(e,n);if(r===void 0)throw new Error("fetch() returned undefined");return r}memo(e,n={}){let r=this.#C;if(!r)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:s,...i}=n,a=this.get(e,i);if(!s&&a!==void 0)return a;let c=r(e,a,{options:i,context:o});return this.set(e,c,i),c}get(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,status:i}=n,a=this.#r.get(e);if(a!==void 0){let c=this.#e[a],u=this.#t(c);return i&&this.#v(i,a),this.#m(a)?(i&&(i.get="stale"),u?(i&&r&&c.__staleWhileFetching!==void 0&&(i.returnedStale=!0),r?c.__staleWhileFetching:void 0):(s||this.#E(e,"expire"),i&&r&&(i.returnedStale=!0),r?c:void 0)):(i&&(i.get="hit"),u?c.__staleWhileFetching:(this.#I(a),o&&this.#R(a),c))}else i&&(i.get="miss")}#F(e,n){this.#d[n]=e,this.#u[e]=n}#I(e){e!==this.#s&&(e===this.#a?this.#a=this.#u[e]:this.#F(this.#d[e],this.#u[e]),this.#F(this.#s,e),this.#s=e)}delete(e){return this.#E(e,"delete")}#E(e,n){let r=!1;if(this.#o!==0){let o=this.#r.get(e);if(o!==void 0)if(r=!0,this.#o===1)this.#Z(n);else{this.#k(o);let s=this.#e[o];if(this.#t(s)?s.__abortController.abort(new Error("deleted")):(this.#x||this.#l)&&(this.#x&&this.#h?.(s,e,n),this.#l&&this.#i?.push([s,e,n])),this.#r.delete(e),this.#n[o]=void 0,this.#e[o]=void 0,o===this.#s)this.#s=this.#d[o];else if(o===this.#a)this.#a=this.#u[o];else{let i=this.#d[o];this.#u[i]=this.#u[o];let a=this.#u[o];this.#d[a]=this.#d[o]}this.#o--,this.#b.push(o)}}if(this.#l&&this.#i?.length){let o=this.#i,s;for(;s=o?.shift();)this.#y?.(...s)}return r}clear(){return this.#Z("delete")}#Z(e){for(let n of this.#A({allowStale:!0})){let r=this.#e[n];if(this.#t(r))r.__abortController.abort(new Error("deleted"));else{let o=this.#n[n];this.#x&&this.#h?.(r,o,e),this.#l&&this.#i?.push([r,o,e])}}if(this.#r.clear(),this.#e.fill(void 0),this.#n.fill(void 0),this.#p&&this.#_&&(this.#p.fill(0),this.#_.fill(0)),this.#w&&this.#w.fill(0),this.#a=0,this.#s=0,this.#b.length=0,this.#g=0,this.#o=0,this.#l&&this.#i){let n=this.#i,r;for(;r=n?.shift();)this.#y?.(...r)}}};var js=({maximumBytes:t=k.hydratedTotalBytes*4}={})=>{if(Number.isSafeInteger(t)===!1||t<=0)throw new TypeError("Document source cache byte limit must be positive");return new tn({maxSize:t,sizeCalculation:e=>Math.max(1,e.bytes.byteLength)})},jn=class extends Error{code="CONTENT_LIMIT_EXCEEDED";documentId;contentByteLimit;constructor({message:e,documentId:n,contentByteLimit:r,cause:o}){super(e,{cause:o}),this.name="CachedDocumentLoaderError",this.documentId=n,this.contentByteLimit=r}},io=({contentRef:t,revision:e,format:n})=>fe([t,e,n??null]),xh=t=>{if(typeof t!="object"||t===null)return!1;let e=t;return el(e.format)&&typeof e.revision=="string"&&e.revision.length>0&&e.bytes instanceof Uint8Array},Of=t=>Object.freeze({format:t.format,revision:t.revision,source:t.bytes}),Cf=({load:t,cache:e,maximumBytes:n=k.hydratedFileBytes,onEvent:r})=>{let o=new Map;return async(s,i)=>{let a=io(s),c=o.get(a)??new Map;o.set(a,c);let u=c.get(i.signal);if(u!==void 0)return await u;let p=(async()=>{let l;try{l=await e.get(a)}catch(m){se(r,{type:"document-cache-read-failed",documentId:s.id,revision:s.revision,errorCode:Yt(m)})}if(xh(l)&&l.revision===s.revision&&l.bytes.byteLength<=n&&(s.format===void 0||l.format===s.format))return se(r,{type:"document-cache-hit",documentId:s.id,revision:s.revision}),Of(l);se(r,{type:"document-cache-miss",documentId:s.id,revision:s.revision});let f=Wt({node:s,source:await t(s,i)}),d;try{d=await Te(f.source,n)}catch(m){throw m instanceof re?new jn({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:d});try{await e.set(a,y),se(r,{type:"document-cache-stored",documentId:s.id,revision:s.revision})}catch(m){se(r,{type:"document-cache-write-failed",documentId:s.id,revision:s.revision,errorCode:Yt(m)})}return Of(y)})();c.set(i.signal,p);try{return await p}finally{c.delete(i.signal),c.size===0&&o.delete(a)}}};var We=class extends Error{code;documentId;referenceId;constructor({code:e,message:n,documentId:r,referenceId:o,cause:s}){super(n,{cause:s}),this.name="DocumentGraphResolutionError",this.code=e,this.documentId=r,this.referenceId=o}},ao=t=>{if(t?.aborted)throw new We({code:"REQUEST_CANCELLED",message:"Document graph resolution was cancelled",cause:t.reason})},Nf=async({graph:t,rootIds:e,concurrency:n,signal:r,load:o,select:s,assemble:i})=>{ao(r);let a=fr({graph:t,rootIds:e}),c=new Map(a.map(d=>[d.id,d])),u=new Map,p=new Map;for(let d of a){let y=p.get(d.contentRef);y===void 0?p.set(d.contentRef,{representative:d,nodes:[d]}):y.nodes.push(d)}await mr([...p.values()],n,async d=>{ao(r);let y=d.representative;try{let m=await o(y,{signal:r});for(let h of d.nodes)u.set(h.id,m)}catch(m){throw r?.aborted&&ao(r),new We({code:"DOCUMENT_LOAD_FAILED",message:`Document ${y.id} could not be loaded`,documentId:y.id,cause:m})}});let l=Pt(t.edges),f=new Map;for(let d of a){ao(r);let y=new Map;for(let h of l.get(d.id)??[]){let b=c.get(h.reference.documentId);if(b===void 0||f.has(h.reference.documentId)===!1)throw new We({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${d.id} dependency ${h.reference.documentId} is unavailable`,documentId:d.id,referenceId:h.referenceId});let S=f.get(h.reference.documentId),A;if(s===void 0){if(h.reference.representation.type!=="document")throw new We({code:"REPRESENTATION_SELECTOR_REQUIRED",message:`Document ${d.id} reference ${h.referenceId} requires a representation selector`,documentId:d.id,referenceId:h.referenceId});A=S}else try{A=await s({reference:h.reference,value:S,sourceNode:d,targetNode:b})}catch(_){throw new We({code:"DOCUMENT_SELECTION_FAILED",message:`Document ${d.id} reference ${h.referenceId} could not be selected`,documentId:d.id,referenceId:h.referenceId,cause:_})}y.set(h.referenceId,A)}if(u.has(d.id)===!1)throw new We({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${d.id} source is unavailable`,documentId:d.id});let m=u.get(d.id);try{f.set(d.id,await i({node:d,source:m,references:y}))}catch(h){throw new We({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${d.id} could not be assembled`,documentId:d.id,cause:h})}}return Object.freeze({roots:Object.freeze(e.map(d=>f.get(d))),values:f})};var At=class extends Error{code;documentId;documentCount;documentLimit;contentByteLimit;totalBytes;totalByteLimit;constructor({code:e,message:n,documentId:r,documentCount:o,documentLimit:s,contentByteLimit:i,totalBytes:a,totalByteLimit:c,cause:u}){super(n,{cause:u}),this.name="DocumentResolutionLimitError",this.code=e,this.documentId=r,this.documentCount=o,this.documentLimit=s,this.contentByteLimit=i,this.totalBytes=a,this.totalByteLimit=c}},Sh=(t,e)=>{let n=0,r=[],o=async()=>{if(e?.throwIfAborted(),n<t){n+=1;return}await new Promise((i,a)=>{let c,u=()=>{let p=r.indexOf(c);p!==-1&&r.splice(p,1);try{e?.throwIfAborted()}catch(l){a(l)}};c={start:()=>{e?.removeEventListener("abort",u),i()}},r.push(c),e?.addEventListener("abort",u,{once:!0})})},s=()=>{let i=r.shift();if(i===void 0){n-=1;return}i.start()};return async i=>{await o();try{return await i()}finally{s()}}},Ah=async({graph:t,rootIds:e,concurrency:n,maximumBytes:r,maximumTotalBytes:o=k.hydratedTotalBytes,maximumDocuments:s=k.hydratedFileCount,signal:i,onEvent:a,allowUnresolvedReferences:c=!1,transformDocument:u,load:p})=>{let l=fr({graph:t,rootIds:e}).length,f={rootCount:e.length,documentCount:l};se(a,{type:"resolution-started",...f});try{if(l>s)throw new At({code:"DOCUMENT_COUNT_EXCEEDED",message:"Document graph resolution exceeds the document limit",documentCount:l,documentLimit:s});let d=0,y=Promise.resolve(),m=await Nf({graph:t,rootIds:e,concurrency:n,signal:i,load:async(h,b)=>{let S=y,A=()=>{};y=new Promise(w=>{A=w});let _;try{_={status:"fulfilled",value:await p(h,b)}}catch(w){_={status:"rejected",reason:w}}await S;try{if(_.status==="rejected")throw _.reason;if(_.value.byteLength>r)throw new At({code:"CONTENT_LIMIT_EXCEEDED",message:`Document ${h.id} exceeds the byte limit`,documentId:h.id,contentByteLimit:r,cause:new re});let w=d+_.value.byteLength;if(w>o)throw new At({code:"TOTAL_BYTES_EXCEEDED",message:"Document graph resolution exceeds the total byte limit",documentId:h.id,totalBytes:w,totalByteLimit:o});return d=w,await _.value.parse()}finally{A()}},select:({reference:h,value:b})=>Af({document:b,representation:h.representation}),assemble:({node:h,source:b,references:S})=>{let A=Sf({document:b,references:S,allowUnresolvedReferences:c});return u?.({node:h,document:A})??A}});return se(a,{type:"resolution-completed",...f}),m}catch(d){throw se(a,{type:"resolution-failed",...f,errorCode:Yt(d)}),d}},Tf=({load:t,concurrency:e,signal:n,maximumDocumentBytes:r=k.hydratedFileBytes,maximumCacheBytes:o=k.hydratedTotalBytes*4})=>{if(Number.isSafeInteger(e)===!1||e<=0)throw new TypeError("Document resolution concurrency must be positive");if(Number.isSafeInteger(r)===!1||r<=0)throw new TypeError("Document resolution byte limit must be positive");if(Number.isSafeInteger(o)===!1||o<=0)throw new TypeError("Document resolution cache byte limit must be positive");let s=new tn({maxSize:o,sizeCalculation:({byteLength:f})=>Math.max(1,f)}),i=new Map,a=Sh(e,n),c=f=>{if(f!==void 0&&f!==n)throw new TypeError("Document resolution session signal does not match");n?.throwIfAborted()},u=async f=>(c(),n===void 0?await f:await new Promise((d,y)=>{let m=()=>n.removeEventListener("abort",h),h=()=>{m();try{n.throwIfAborted()}catch(b){y(b)}};n.addEventListener("abort",h,{once:!0}),f.then(b=>{m(),d(b)},b=>{m(),y(b)}),n.aborted&&h()})),p=async(f,d)=>{c(d.signal);let y=io(f),m=s.get(y);if(m!==void 0)return m;let h=i.get(y);if(h!==void 0)return await u(h);let b=a(async()=>{c(d.signal);let S=Wt({node:f,source:await t(f,{signal:n})});c(d.signal);let A=await Ho(S.source,r+1);c(d.signal);let _,w=Object.freeze({format:S.format,revision:S.revision,bytes:A,byteLength:A.byteLength,parse:()=>(_??=xf({format:S.format,source:A,maximumBytes:r}),_)});return w.byteLength<=o&&s.set(y,w),w});i.set(y,b);try{return await u(b)}finally{i.delete(y)}};return Object.freeze({getCached:f=>{c();let d=s.get(io(f));if(!(d===void 0||d.byteLength>r))return Object.freeze({format:d.format,revision:d.revision,source:d.bytes.slice()})},resolve:async f=>await Ah({...f,concurrency:e,maximumBytes:r,signal:n,load:p})})};var $f=t=>{if(t.output.mode==="all")return"all";let e=[];for(let{field:n}of gn(t.where))n[0]==="properties"&&e.push(n);for(let{field:n}of t.sort)n[0]==="properties"&&e.push(n);if(t.output.mode==="fields")for(let n of t.output.fields)n[0]==="properties"&&e.push(n);return e},zf=t=>{let e;if(t==="#frontmatter")e="";else if(t.startsWith("#frontmatter/"))e=t.slice(12);else if(t==="#")e="";else if(t.startsWith("#/"))e=t.slice(1);else return;try{return["properties",...bl(e)]}catch{return}},Pf=(t,e)=>{let n=Math.min(t.length,e.length);for(let r=0;r<n;r+=1)if(t[r]!==e[r])return!1;return!0},Lf=({queryPaths:t,referenceId:e})=>{let n=zf(e);return n!==void 0&&(t==="all"||t.some(r=>Pf(r,n)))},Mf=({graph:t,sourceId:e,field:n})=>n[0]!=="properties"?!1:t.edges.some(r=>{if(r.sourceId!==e)return!1;let o=zf(r.referenceId);return o!==void 0&&Pf(n,o)}),Ff=({graph:t,query:e})=>{let n=$f(e),r=new Set;for(let o of t.edges)Lf({queryPaths:n,referenceId:o.referenceId})&&r.add(o.sourceId);return[...r]},Zf=({graph:t,query:e,rootIds:n})=>{let r=$f(e),o=new Set(n),s=new Map(t.nodes.map(l=>[l.id,l])),i=Pt(t.edges),a=new Set(n),c=new Set,u=new Set,p=l=>{if(a.add(l),!u.has(l)){u.add(l);for(let f of i.get(l)??[])c.add(f),p(f.reference.documentId)}};for(let l of t.edges)o.has(l.sourceId)&&Lf({queryPaths:r,referenceId:l.referenceId})&&(c.add(l),p(l.reference.documentId));return _n({nodes:[...a].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:[...c]})};var Bf=({artifact:t})=>{if(t.documentGraph===void 0)return;let e=new Map(t.documents.map(s=>[s._id,s])),n=new Map(t.documentGraph.nodes.map(s=>[s.id,s])),r=new Map;for(let{sourceId:s}of t.documentGraph.edges){if(n.has(s))continue;let i=e.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:_n({nodes:[...n.values()],edges:t.documentGraph.edges.map(({sourceId:s,referenceId:i,documentId:a,representation:c})=>{let u=n.get(a);if(u===void 0)throw new Error(`Runtime document graph target ${a} is unavailable`);return{sourceId:s,referenceId:i,reference:{documentId:a,revision:u.revision,representation:c}}})}),inlineDocuments:r}};var jf=({markdown:t,references:e,assetUrls:n})=>{let r=t.length,o=t;for(let s of[...e].sort((i,a)=>a.start-i.start)){if(s.start<0||s.end<=s.start||s.end>t.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 a=to(i,s.suffix);o=`${o.slice(0,s.start)}${a}${o.slice(s.end)}`}return o};var ie=class extends Error{code;details;constructor({code:e,message:n,details:r}){super(n),this.name="AssetResourceHydrationError",this.code=e,this.details=r}},Eh=t=>{if(t===null)return[];let e=Array.isArray(t)?t:[t],n=new Map;for(let r of e){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 ie({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 ie({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())},vh=t=>typeof t.mimeType=="string"&&(t.mimeType.startsWith("text/")||["application/json","application/javascript","application/xml","image/svg+xml"].includes(t.mimeType)),Dh=async({read:t,contentRef:e,range:n,maximumBytes:r})=>{if(r===0)return new Uint8Array;let o=await t(e,n);try{return await Te(o.data,r)}catch(s){throw s instanceof re?new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Asset storage returned more content than requested"}):s}},Rh=t=>{try{return le(t)}catch{throw new ie({code:"CONTENT_DECODING_FAILED",message:"Selected asset content is not valid UTF-8"})}},kh=(t,e)=>{if(e.mode==="range")return Math.max(0,Math.min(e.length,t.size-e.offset));let n=e.maxBytes??k.hydratedFileBytes;if(t.size>n)throw new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected asset exceeds the per-file content limit",details:{assetId:t._id,assetBytes:t.size,fileByteLimit:n}});return t.size},Uf=async({result:t,documents:e,options:n,read:r,assetReferences:o,assetUrls:s})=>{if(n.mode==="none")return{content:{},hydratedFileCount:0,hydratedBytes:0};let i=Eh(t);if(i.length>k.hydratedFileCount)throw new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Too many selected assets requested content hydration",details:{fileCount:i.length,fileCountLimit:k.hydratedFileCount}});let a=new Map(e.map(l=>[l._id,l])),c=i.map(l=>{let f=a.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 ie({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset content identity is stale or unavailable",details:{assetId:l._id}});let d={...f,size:f.size,mimeType:f.mimeType};if(vh(d)===!1)throw new ie({code:"CONTENT_NOT_TEXT",message:"Selected binary asset cannot be embedded as text",details:{assetId:l._id,mimeType:d.mimeType}});return{identity:l,document:d,readLength:kh(d,n)}}),u=c.reduce((l,f)=>l+f.readLength,0);if(u>k.hydratedTotalBytes)throw new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected assets exceed the total hydrated-content limit",details:{totalReadBytes:u,totalByteLimit:k.hydratedTotalBytes}});let p=await mr(c,k.concurrentContentReads,async l=>{let f=n.mode==="range"?{offset:n.offset,length:l.readLength}:l.readLength===0?void 0:{offset:0,length:l.readLength},d=await Dh({read:r,contentRef:l.identity.contentRef,range:f,maximumBytes:l.readLength});if(d.byteLength!==l.readLength)throw new ie({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-ref")try{y=(await Hr(d,l.readLength||1)).body;let h=o?.[l.identity.contentRef];h!==void 0&&s!==void 0&&(y=jf({markdown:y,references:h,assetUrls:s}))}catch{throw new ie({code:"CONTENT_DECODING_FAILED",message:"Selected Markdown body could not be decoded",details:{assetId:l.identity._id}})}else y=Rh(d);let m=Ne(y);return{id:l.identity._id,returnedBytes:m,content:{...l.identity,encoding:"utf-8",text:y,...n.mode==="range"?{range:{offset:n.offset,length:d.byteLength,total:l.document.size}}:{}}}});return{content:Object.fromEntries(p.map(({id:l,content:f})=>[l,f])),hydratedFileCount:c.length,hydratedBytes:p.reduce((l,{returnedBytes:f})=>l+f,0)}};var Hv=v().datetime({offset:!0}).transform(t=>new Date(t).toISOString());var Ih=/^[A-Za-z_][A-Za-z0-9_]*$/,Qf=(t,e)=>Ih.test(e)?`${t}.${e}`:`${t}[${JSON.stringify(e)}]`;var Vf=({document:t,includes:e})=>{let n={};for(let r of ll){let o=t[r];o!==void 0&&e(r)&&(n[r]=o)}return n},ht=Symbol("missing property selection"),Us=(t,e)=>{if(e.some(r=>r.length===0)||typeof hr(t)=="string")return t;if(Array.isArray(t)){let r=e.filter(([s])=>s==="*").map(s=>s.slice(1));if(r.length===0)return ht;let o=t.map(s=>Us(s,r));return o.some(s=>s!==ht)?o.map(s=>s===ht?null:s):ht}if(typeof t!="object"||t===null)return ht;let n={};for(let[r,o]of Object.entries(t)){let s=e.filter(([a])=>a===r).map(a=>a.slice(1));if(s.length===0)continue;let i=Us(o,s);i!==ht&&(n[r]=i)}return Object.keys(n).length===0?ht:n},Gf=({properties:t,fields:e})=>{let n=e.filter(([o])=>o==="properties").map(o=>o.slice(1)),r=Us(t,n);return r===ht?{}:r};var Oe=class extends Error{constructor(e,n){super(e,n),this.name="AssetQueryExecutionError"}},Un=class extends Oe{code="MULTIPLE_RESULTS";matchedCount;constructor(e){super(`Expected at most one asset, but the query matched ${e}.`),this.matchedCount=e,this.name="AssetQueryMultipleResultsError"}},rn=class extends Error{constructor(){super("The requested asset index revision is stale"),this.name="AssetIndexRevisionError"}},Jf=t=>{if(t[0]!=="properties")return t[0];let e="properties";for(let n of t.slice(1))e=Qf(e,n);return e},qf=({filter:t,fieldTypes:e})=>pl(e).includes(t.operator),Kf=(t,e)=>t!==void 0&&Object.hasOwn(t.fields,e)?t.fields[e]:void 0,Oh=({query:t,catalog:e})=>{let n=ot.parse(t),r=new Map,o=[];for(let s of gn(n.where)){let i=Jf(s.field);if(r.set(i,s.field),s.field[0]==="properties"){let a=Kf(e,i);e!==void 0&&a===void 0?o.push(`Asset field ${i} is not currently observed`):a!==void 0&&qf({filter:s,fieldTypes:a.types})===!1&&o.push(`Operator ${s.operator} is not compatible with the currently observed types of ${i}`)}else if(qf({filter:s,fieldTypes:os[s.field[0]]})===!1)throw new Oe(`Operator ${s.operator} is incompatible with ${i}`)}for(let s of n.sort){let i=Jf(s.field);if(r.set(i,s.field),s.field[0]==="properties"){let a=Kf(e,i);e!==void 0&&a===void 0?o.push(`Asset field ${i} is not currently observed`):a!==void 0&&a.types.some(c=>c==="object"||c==="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)]}},Vs=(t,e,n)=>{let r=e[0]==="id"?t._id:pr(e[0])?n?.[e[0]]:t[e[0]];for(let o of e.slice(1)){if(typeof r!="object"||r===null||Object.hasOwn(r,o)===!1)return;r=r[o]}return r},Ch=t=>typeof t=="string"||Array.isArray(t)?t.length===0:typeof t=="object"&&t!==null&&Object.keys(t).length===0,Nh=(t,e)=>{if(typeof t=="number"&&typeof e=="number")return t-e;if(typeof t=="string"&&typeof e=="string")return $e(t,e)},Gs=(t,e,n)=>{let r=Vs(t,e.field,n);if(e.operator==="exists")return r!=null===e.value;if(e.operator==="isEmpty")return Ch(r)===e.value;if(e.operator==="eq")return bn(r,e.value);if(e.operator==="ne")return bn(r,e.value)===!1;if(e.operator==="in")return e.value.some(s=>bn(r,s));if(e.operator==="contains")return typeof r=="string"&&typeof e.value=="string"?r.includes(e.value):Array.isArray(r)&&r.some(s=>bn(s,e.value));if(e.operator==="startsWith")return typeof r=="string"&&typeof e.value=="string"&&r.startsWith(e.value);if(e.operator==="endsWith")return typeof r=="string"&&typeof e.value=="string"&&r.endsWith(e.value);let o=Nh(r,e.value);return o===void 0?!1:e.operator==="gt"?o>0:e.operator==="gte"?o>=0:e.operator==="lt"?o<0:o<=0},Th=({document:t,where:e,runtimeAsset:n,filterKeys:r,filterResults:o})=>Nt(e,s=>{let i=r.get(s)??fe(s),a=o.get(i);if(a!==void 0)return a;let c=Gs(t,s,n);return o.set(i,c),c})===!0,$h=({document:t,content:e})=>{if(e.mode!=="markdown-body-ref")return!0;let n=t.mimeType===void 0?void 0:tl(t.mimeType);return n==="markdown"||n==="mdx"?!0:t.extension==="md"||t.extension==="mdx"},zh=(t,e)=>{let n=t==null,r=e==null;return n||r?n===r?0:n?1:-1:typeof t=="number"&&typeof e=="number"?t-e:(typeof t=="string"||typeof t=="boolean")&&(typeof e=="string"||typeof e=="boolean")?$e(String(t),String(e)):$e(fe(t),fe(e))},Ph=({left:t,right:e,sort:n,runtimeAssets:r})=>{for(let o of n){let s=zh(Vs(t,o.field,r?.[t._id]),Vs(e,o.field,r?.[e._id]));if(s!==0)return o.direction==="asc"?s:-s}return $e(t._id,e._id)};var Lh=(t,e)=>{if(t.properties===void 0)return;if(e.mode==="all")return Object.keys(t.properties).length===0?void 0:t.properties;if(e.mode!=="fields"||e.fields.some(r=>r[0]==="properties")===!1)return;let n=Gf({properties:t.properties,fields:e.fields});return Object.keys(n).length===0?void 0:n},nn=(t,e)=>t.includeMetadata&&fl(e)||t.mode==="fields"&&t.fields.some(n=>n.length===1&&n[0]===e),Mh=t=>t.mode==="all"||t.mode==="fields"&&t.fields.some(e=>e.length===1&&e[0]==="excerpt"),Fh=(t,e,n)=>{if(nn(e,"url")&&n===void 0)throw new Error(`Asset URL is unavailable for ${t._id}`);let r=Lh(t,e),o=n?.width!==void 0&&n.height!==void 0;return{...n!==void 0&&nn(e,"url")?{url:n.url}:{},...o&&nn(e,"width")?{width:n.width}:{},...o&&nn(e,"height")?{height:n.height}:{},...Vf({document:t,includes:s=>nn(e,s)}),...r===void 0?{}:{properties:r},...t.excerpt===void 0||Mh(e)===!1?{}:{excerpt:t.excerpt},...t.metadataError===void 0||e.includeMetadata===!1?{}:{metadataError:t.metadataError}}},Js=t=>{if(Ne(fe(t))>k.resultBytes)throw new Oe("Asset query result exceeds the byte limit")},co=(t,e,n)=>{t[e]={status:"rejected",reason:n}},Zh=({inputs:t,catalog:e,results:n})=>{let r=new Map,o=new Map,s=[];for(let[i,a]of t.entries()){let c;try{c=Oh({query:a,catalog:e}).query}catch(l){co(n,i,l);continue}for(let l of gn(c.where))o.set(l,fe(l));let u=fe(c.sort),p=r.get(u);p===void 0&&(p={sort:c.sort,documents:new Set,sorted:[]},r.set(u,p)),s.push({index:i,query:c,matches:new Map,sortGroup:p})}return{filterKeys:o,preparedQueries:s,sortGroups:r}},Wf=({preparedQueries:t,results:e,createReason:n})=>{for(let{index:r}of t)co(e,r,n())},Qs=t=>t.map(e=>{if(e===void 0)throw new Error("Asset query result was not settled");return e}),Bh=({preparedQueries:t,documents:e,filterKeys:n,sortGroups:r,results:o,runtimeAssets:s})=>{for(let i of e){let a=s?.[i._id],c=new Map;for(let u of t){if(o[u.index]!==void 0)continue;let{query:p}=u;try{if($h({document:i,content:p.content})===!1||Th({document:i,where:p.where,runtimeAsset:a,filterKeys:n,filterResults:c})===!1)continue;let l=Fh(i,p.output,a);if(p.content.mode==="none"&&Object.keys(l).length===0&&nn(p.output,"id")===!1)continue;let f={document:i,item:{id:i._id,...l}};u.matches.set(i,f),u.sortGroup.documents.add(i)}catch(l){co(o,u.index,l)}}}for(let i of r.values())i.sorted=[...i.documents].sort((a,c)=>Ph({left:a,right:c,sort:i.sort,runtimeAssets:s}))},jh=async({preparedQueries:t,results:e,read:n,assetReferences:r,assetUrls:o})=>{await Promise.all(t.map(async s=>{if(e[s.index]!==void 0)return;let{query:i}=s;try{let a=s.sortGroup.sorted.flatMap(d=>{let y=s.matches.get(d);return y===void 0?[]:[y]}),c=i.result??"many";if(c==="one"&&a.length>1)throw new Un(a.length);let u=c==="many"?a.slice(i.offset,i.offset+i.limit):c==="last"?a.slice(-1):a.slice(0,1),p=u.map(({document:d})=>d),l=u.map(({item:d})=>d);if(i.content.mode!=="none"){let d=i.content;if(n===void 0)throw new Oe("Asset content reader is unavailable");let y=await Uf({result:p,documents:p,options:d,read:n,assetReferences:r,assetUrls:r===void 0?void 0:o});l=p.map((m,h)=>{let b=y.content[m._id];if(b===void 0)throw new Oe("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=c==="many"?{items:l,totalCount:a.length,hasMore:i.offset+u.length<a.length}:{item:l[0]??null,totalCount:a.length};Js(f),e[s.index]={status:"fulfilled",value:f}}catch(a){co(e,s.index,a)}}))},Yf=async({queries:t,catalog:e,documents:n,read:r,runtimeAssets:o,assetReferences:s,assetValueReferences:i})=>{let a=Array.from({length:t.length}),{filterKeys:c,preparedQueries:u,sortGroups:p}=Zh({inputs:t,catalog:e,results:a});if(n.length>k.candidateDocuments)return Wf({preparedQueries:u,results:a,createReason:()=>new Oe("Asset query document limit was exceeded")}),Qs(a);let l;try{l=n.map(d=>pt({value:d,references:i?.[d._id],runtimeAssets:o??{}}))}catch(d){return Wf({preparedQueries:u,results:a,createReason:()=>d}),Qs(a)}Bh({preparedQueries:u,documents:l,filterKeys:c,sortGroups:p,results:a,runtimeAssets:o});let f=_f(o);return await jh({preparedQueries:u,results:a,read:r,assetReferences:s,assetUrls:f}),Qs(a)};var Uh=async t=>await Yu(fe(ot.parse(t)));var Qh=({item:t,field:e,value:n})=>{let r=t;for(let[o,s]of e.entries()){if(o===e.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 a={};Object.defineProperty(r,s,{value:a,enumerable:!0,configurable:!0,writable:!0}),r=a}},Vh=t=>ss.parse({items:t.rows.map(e=>{let n={};for(let[r,o]of t.fields.entries())Qh({item:n,field:o,value:e[r]});return n}),totalCount:t.totalCount,hasMore:t.hasMore}),Hf=async({queries:t,query:e,assetValueReferences:n,runtimeAssets:r={}})=>{if(t===void 0)return;let o=t[await Uh(ot.parse(e))];if(o===void 0)return;let s=Vh(o),i={...s,items:s.items.map(a=>pt({value:a,references:n?.[a.id],runtimeAssets:r}))};return Js(i),i};var Gh=(t,e)=>e===void 0?$t(t):{async*[Symbol.asyncIterator](){let n=0,r=0;for await(let o of $t(t)){if(r===e.length)return;if(n+o.byteLength<=e.offset){n+=o.byteLength;continue}let s=Math.max(0,e.offset-n),i=Math.min(o.byteLength-s,e.length-r);i>0&&(yield o.subarray(s,s+i),r+=i),n+=o.byteLength}}},Jh=({graph:t,load:e,getCached:n,readFallback:r,signal:o})=>{let s=new Map(t.nodes.map(i=>[i.contentRef,i]));return async(i,a)=>{let c=s.get(i);if(c===void 0){if(r!==void 0)return await r(i,a);throw new Error(`Document content reference ${i} is unavailable`)}let u=Wt({node:c,source:n(c)??await e(c,{signal:o})});return{data:Gh(u.source,a),...a===void 0?{}:{contentLength:a.length}}}},qh=({artifact:t,revision:e,catalog:n,documentGraph:r,inlineDocuments:o,readContent:s})=>{let i=new Map(t.documents.map(w=>[w._id,w])),a=w=>{if(w.indexRevision!==void 0&&w.indexRevision!==e)throw new rn},c=w=>async(E,D)=>{let x=t.contents?.[E];if(x===void 0){let G=w??s;if(G===void 0)throw new Error("Content is not embedded in this database");return await G(E,D)}let O=Tt(x),$=D===void 0?O:O.slice(D.offset,D.offset+D.length);return{data:async function*(){yield $}(),contentLength:$.byteLength}},u=w=>{if(w.status==="rejected")throw w.reason;return w.value},p=async({requests:w,queryContentReader:E,runtimeAssets:D,documents:x=t.documents})=>await Yf({queries:w.map(({query:O})=>O),catalog:n,documents:x,read:c(E),runtimeAssets:D,assetReferences:t.assetReferences,assetValueReferences:t.assetValueReferences}),l=async({request:w,...E})=>u((await p({...E,requests:[w]}))[0]),f=async({requests:w,queryContentReader:E,runtimeAssets:D})=>{let x=Array.from({length:w.length}),O=[];for(let[$,G]of w.entries()){try{a(G);let z=await Hf({queries:t.queries,query:G.query,assetValueReferences:t.assetValueReferences,runtimeAssets:D});if(z!==void 0){x[$]={status:"fulfilled",value:z};continue}}catch(z){x[$]={status:"rejected",reason:z};continue}O.push($)}if(O.length>0){let $=await p({requests:O.map(G=>w[G]),queryContentReader:E,runtimeAssets:D});for(let[G,z]of O.entries())x[z]=$[G]}return x.map($=>{if($===void 0)throw new Error("Content database query was not settled");return $})},d=async(w,E,D)=>u((await f({requests:[w],queryContentReader:E,runtimeAssets:D}))[0]),y=async(...w)=>await d(...w),m=w=>async(E,D)=>{let x=o?.get(E.id);return x!==void 0?{format:"json",revision:E.revision,source:JSON.stringify(x.properties)}:await w(E,D)},h=({graph:w,query:E,runtimeAssets:D})=>Ff({graph:w,query:E}).filter(x=>{let O=i.get(x),$=O===void 0?void 0:pt({value:O,references:t.assetValueReferences?.[x],runtimeAssets:D??{}});return $===void 0?!1:Nt(E.where,G=>{if(!Mf({graph:w,sourceId:x,field:G.field}))return Gs($,G,D?.[x])})!==!1}),b=({rootIds:w,roots:E})=>{let D=new Map(w.flatMap((x,O)=>{let $=ro(E[O]);return $===void 0?[]:[[x,$]]}));return t.documents.map(x=>{let O=D.get(x._id);return O===void 0?x:rs.parse({...x,properties:O})})},S=async({request:w,graph:E,resolutionSession:D,contentReader:x,runtimeAssets:O,onEvent:$})=>{a(w);let G=ot.parse(w.query),z=h({graph:E,query:G,runtimeAssets:O});if(z.length===0)return await d(w,x,O);let yt=Zf({graph:E,query:G,rootIds:z});se($,{type:"roots-selected",rootCount:z.length});let lo=await D.resolve({graph:yt,rootIds:z,onEvent:$,allowUnresolvedReferences:!0,transformDocument:({node:od,document:sd})=>Fs({document:sd,references:t.assetValueReferences?.[od.id],runtimeAssets:O})}),fo=b({rootIds:z,roots:lo.roots});return await l({request:w,queryContentReader:x,runtimeAssets:O,documents:fo})},A=async({requests:w,load:E,resolutionSession:D,readContent:x,runtimeAssets:O,signal:$,onEvent:G})=>{if(r===void 0)return await f({requests:w,queryContentReader:x,runtimeAssets:O});let z=m(E),yt=D??Tf({load:z,concurrency:k.concurrentContentReads,signal:$}),lo=Jh({graph:r,load:z,getCached:yt.getCached,readFallback:x??s,signal:$});return await Promise.allSettled(w.map(fo=>S({request:fo,graph:r,resolutionSession:yt,contentReader:lo,runtimeAssets:O,onEvent:G})))};return{query:y,queryManyWithDocumentGraph:A,queryWithDocumentGraph:async({request:w,...E})=>u((await A({...E,requests:[w]}))[0])}};var qs=({artifact:t,readContent:e})=>{let n=Bf({artifact:t});return qh({artifact:t,revision:t.revision,documentGraph:n?.graph,inlineDocuments:n?.inlineDocuments,readContent:e})};var uo=class extends Error{constructor(e,n){super(e,n),this.name="AssetQueryRequestError"}},Qn=class extends Error{},Kh=async(t,e)=>{if(Number.isSafeInteger(e)===!1||e<0)throw new TypeError("Request byte limit must be a non-negative integer");let n=Number(t.headers.get("content-length"));if(Number.isFinite(n)&&n>e)throw new Qn("Request exceeds the byte limit");let r=t.body?.getReader(),o=[],s=0;if(r!==void 0)for(;;){let{done:c,value:u}=await r.read();if(c)break;if(s+=u.byteLength,s>e){try{await r.cancel()}catch{}throw new Qn("Request exceeds the byte limit")}o.push(u)}let i=new Uint8Array(s),a=0;for(let c of o)i.set(c,a),a+=c.byteLength;return i},Xf=async t=>{let e;try{e=await Kh(t,k.requestBytes)}catch(n){throw n instanceof Qn?new uo("Asset query request exceeds the byte limit",{cause:n}):n}try{return ml.parse(JSON.parse(le(e)))}catch(n){throw new uo("Asset query request is invalid",{cause:n})}};var ed=t=>{if(t instanceof rn)return{code:"STALE_INDEX",message:t.message,retryable:!1,status:409};if(t instanceof Un)return{code:t.code,message:t.message,retryable:!1,details:{matchedCount:t.matchedCount},status:409};if(t instanceof Oe)return{code:"INVALID_REQUEST",message:t.message,retryable:!1,status:400};if(t instanceof ie)return{code:t.code,message:t.message,retryable:!1,details:t.details,status:400};let e=new Set,n=t;for(;n!==void 0&&e.has(n)===!1;){if(n instanceof At){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 jn)return{code:"CONTENT_LIMIT_EXCEEDED",message:n.message,retryable:!1,details:{assetId:n.documentId,contentByteLimit:n.contentByteLimit},status:400};e.add(n),n=n instanceof Error?n.cause:void 0}};var Wh="/$resources/assets",td=(t,e=200)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json; charset=utf-8"}}),Vn=({code:t,message:e,status:n,retryable:r=!1,details:o})=>td(gl({code:t,message:e,retryable:r,details:o}),n),Yh=(t,e,n)=>typeof t=="string"||t instanceof URL?new Request(new URL(t,e),n):new Request(t,n),Hh=async({deploymentId:t,artifact:e,request:n})=>{let r=await n.clone().text(),o=n.headers.get("cache-control"),s=await es(JSON.stringify([t,e.revision,r,o])),i=new URL(n.url);return i.searchParams.set("ws-asset-resource",s),new Request(i,{method:"GET"})},VD=({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,fetchDocument:s=globalThis.fetch,onDocumentGraphEvent:i})=>{nd({artifact:e,runtimeAssets:n});let a=js();return rd({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,database:qs({artifact:e}),fetchDocument:s,documentCache:a,onDocumentGraphEvent:i})},Xh=({baseUrl:t,runtimeAssets:e,fetchDocument:n,cache:r,onEvent:o})=>Cf({cache:r,onEvent:o,load:vf({fetch:n,getRequest:s=>{let i=e[s.id];if(i===void 0)throw new Error(`Published document URL is unavailable for ${s.id}`);return new URL(i.url,t)},getMetadata:({node:s})=>({format:s.format,revision:s.revision}),onEvent:o})}),nd=({artifact:t,runtimeAssets:e})=>{let n=[t.assetReferences,t.assetValueReferences].flatMap(s=>Object.values(s??{}).flat()).map(({assetId:s})=>s).find(s=>e[s]===void 0);if(n!==void 0)throw new Error(`Published referenced asset URL is unavailable for ${n}`);let r=t.documentGraph?.nodes.find(({id:s})=>e[s]===void 0)?.id;if(r!==void 0)throw new Error(`Published document URL is unavailable for ${r}`);let o=t.documentGraph?.nodes.find(({id:s,contentRef:i})=>e[s]?.contentRef!==i)?.id;if(o!==void 0)throw new Error(`Published document identity does not match graph node ${o}`)},rd=({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,database:s,fetchDocument:i,documentCache:a,onDocumentGraphEvent:c})=>{let u=new URL(o).origin,p=Xh({baseUrl:o,runtimeAssets:n,fetchDocument:i,cache:a,onEvent:c});return async(l,f)=>{let d=Yh(l,o,f),y=new URL(d.url);if(y.origin!==u||y.pathname!==Wh||d.method.toUpperCase()!=="POST")return;let m;try{m=await Xf(d.clone())}catch{return Vn({code:"INVALID_REQUEST",message:"Asset resource request is invalid",status:400})}let h=r===void 0||d.headers.has("cache-control")===!1?void 0:await Hh({deploymentId:t,artifact:e,request:d});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(d.signal.aborted)return Vn({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let b=td(await s.queryWithDocumentGraph({request:m,load:p,runtimeAssets:n,signal:d.signal,onEvent:c}));return h!==void 0&&r!==void 0&&d.signal.aborted===!1&&(b.headers.set("cache-control",d.headers.get("cache-control")),await r.put(h,b.clone()).catch(()=>{})),b}catch(b){if(d.signal.aborted)return Vn({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let S=ed(b);return Vn(S!==void 0?S:{code:"INTERNAL_ERROR",message:"Published asset query failed",status:500,retryable:!0})}}},GD=({deploymentId:t,artifact:e,runtimeAssets:n,onDocumentGraphEvent:r=void 0})=>{let o=globalThis.caches,s,i=()=>(s??=o.open(`webstudio-assets-${t}`),s),a=o===void 0?void 0:{match:async p=>(await i()).match(p),put:async(p,l)=>(await i()).put(p,l)};nd({artifact:e,runtimeAssets:n});let c=qs({artifact:e}),u=js();return async({request:p,fallback:l})=>{let f=new URL(p.url).origin,d=rd({deploymentId:t,artifact:e,runtimeAssets:n,cache:a,baseUrl:f,database:c,fetchDocument:l,documentCache:u,onDocumentGraphEvent:r});return async(y,m)=>await d(y,m)??l(y,m)}};export{GD as createGeneratedAssetResourceRuntime,VD as createPublishedAssetResourceFetch};diff --git a/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.server.tsxindex 908255b01e..59e808545c 100644--- a/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsxindex 8fd5e5c714..324b645289 100644--- a/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsxindex 19d72d077f..3cec61be47 100644--- a/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx@@ -4,7 +4,7 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const assets_1: ResourceRequest = {name: "assets",control: "system",@@ -38,9 +38,10 @@ export const getResources = (_props: { system: System }) => {const _data = new Map<string, ResourceRequest>([["assets_1", assets_1],])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsxindex 8fd5e5c714..324b645289 100644--- a/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsxindex 8fd5e5c714..324b645289 100644--- a/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsxindex 07a3cfbb2a..8ccd45a432 100644--- a/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsxindex 07695cd8b1..d2f7281338 100644--- a/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx@@ -4,7 +4,7 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const jsonResourceVariable_1: ResourceRequest = {name: "jsonResourceVariable",url: "https://httpbin.org/get?hello=world",@@ -17,9 +17,10 @@ export const getResources = (_props: { system: System }) => {const _data = new Map<string, ResourceRequest>([["jsonResourceVariable_1", jsonResourceVariable_1],])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsxindex 4c3f3c98ae..8ab770bac1 100644--- a/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx@@ -4,7 +4,7 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const action: ResourceRequest = {name: "action",url: "/custom",@@ -17,10 +17,11 @@ export const getResources = (_props: { system: System }) => {}const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([["action", action],])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsxindex 8fd5e5c714..324b645289 100644--- a/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.server.tsxindex 52fd99106b..8bfd9038ef 100644--- a/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.server.tsxindex aaaee6f246..a9d43cecfa 100644--- a/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsxindex 49d91d7a44..e2d727acc8 100644--- a/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsxindex 0058dccf45..05d6e3c411 100644--- a/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx@@ -4,7 +4,7 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const list_1: ResourceRequest = {name: "list",url: "https://gist.githubusercontent.com/TrySound/56507c301ec85669db5f1541406a9259/raw/a49548730ab592c86b9e7781f5b29beec4765494/collection.json",@@ -17,9 +17,10 @@ export const getResources = (_props: { system: System }) => {const _data = new Map<string, ResourceRequest>([["list_1", list_1],])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsxindex 8fd5e5c714..324b645289 100644--- a/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsxindex 07a3cfbb2a..8ccd45a432 100644--- a/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/_index.server.tsx b/fixtures/webstudio-features/app/__generated__/_index.server.tsxindex 1b005258f3..09e9e94c2e 100644--- a/fixtures/webstudio-features/app/__generated__/_index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/_index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx b/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsxindex 14e31beba9..8b9e13bb86 100644--- a/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[animations]._index.tsx b/fixtures/webstudio-features/app/routes/[animations]._index.tsxindex c148140643..535c941404 100644--- a/fixtures/webstudio-features/app/routes/[animations]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[animations]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[assets1]._index.tsx b/fixtures/webstudio-features/app/routes/[assets1]._index.tsxindex 8d4dc03b5c..403bc792ef 100644--- a/fixtures/webstudio-features/app/routes/[assets1]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[assets1]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[class-names]._index.tsx b/fixtures/webstudio-features/app/routes/[class-names]._index.tsxindex 45945d1444..fba594a77b 100644--- a/fixtures/webstudio-features/app/routes/[class-names]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[class-names]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[content-block]._index.tsx b/fixtures/webstudio-features/app/routes/[content-block]._index.tsxindex 26f1edfbd9..546175503b 100644--- a/fixtures/webstudio-features/app/routes/[content-block]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[content-block]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[duration]._index.tsx b/fixtures/webstudio-features/app/routes/[duration]._index.tsxindex 5960aa5eea..151ffbd878 100644--- a/fixtures/webstudio-features/app/routes/[duration]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[duration]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[expressions]._index.tsx b/fixtures/webstudio-features/app/routes/[expressions]._index.tsxindex 0719819103..1eae8491cd 100644--- a/fixtures/webstudio-features/app/routes/[expressions]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[expressions]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[form]._index.tsx b/fixtures/webstudio-features/app/routes/[form]._index.tsxindex af34978760..89ff380174 100644--- a/fixtures/webstudio-features/app/routes/[form]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[form]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx b/fixtures/webstudio-features/app/routes/[head-tag]._index.tsxindex 353d2435ff..77ee10baec 100644--- a/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx b/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsxindex 7babde7a97..0d392a9473 100644--- a/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx b/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsxindex 6c3f7cb0be..fd7be339c3 100644--- a/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[radix]._index.tsx b/fixtures/webstudio-features/app/routes/[radix]._index.tsxindex 0204454424..c6e5b70c1b 100644--- a/fixtures/webstudio-features/app/routes/[radix]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[radix]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[resources]._index.tsx b/fixtures/webstudio-features/app/routes/[resources]._index.tsxindex dd03504701..036104153e 100644--- a/fixtures/webstudio-features/app/routes/[resources]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[resources]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx b/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsxindex 7f252952d7..49757f0670 100644--- a/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx@@ -103,6 +103,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx b/fixtures/webstudio-features/app/routes/[text-duration]._index.tsxindex 89b4a62206..fc5f1067d6 100644--- a/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/_index.tsx b/fixtures/webstudio-features/app/routes/_index.tsxindex d8fe87ddaa..0b9d27d395 100644--- a/fixtures/webstudio-features/app/routes/_index.tsx+++ b/fixtures/webstudio-features/app/routes/_index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/packages/asset-uploader/src/asset-repository.ts b/packages/asset-uploader/src/asset-repository.tsindex b50506e918..29a2dbcdd1 100644--- a/packages/asset-uploader/src/asset-repository.ts+++ b/packages/asset-uploader/src/asset-repository.ts@@ -105,6 +105,7 @@ import {type AssetQueryPerformanceObserver,type AssetQueryPerformancePhase,} from "./query-performance";+import type { AssetContentRead as SharedAssetContentRead } from "@webstudio-is/content-engine/asset-content-repository";type CreateId = () => Asset["id"];type RepositoryObjectStore = AssetObjectReader & Partial<AssetObjectWriter>;@@ -189,10 +190,8 @@ export class AssetIndexPreparationError extends Error {}}-export type AssetContentRead = {+export type AssetContentRead = Omit<SharedAssetContentRead, "asset"> & {asset: Asset;- data: AsyncIterable<Uint8Array>;- contentLength?: number;};type AssetQueryPreviewOptions = {diff --git a/packages/asset-uploader/src/canonical-metadata-backfill.ts b/packages/asset-uploader/src/canonical-metadata-backfill.tsindex ddf763acda..8a3daa4fc0 100644--- a/packages/asset-uploader/src/canonical-metadata-backfill.ts+++ b/packages/asset-uploader/src/canonical-metadata-backfill.ts@@ -14,6 +14,7 @@ import {import type { AssetFileDocument } from "@webstudio-is/content-engine";import {createAssetFolderHierarchy,+ createAssetContentRevision,formatAssetName,getFileNameParts,getMimeTypeByFilename,@@ -23,7 +24,6 @@ import type { Client } from "@webstudio-is/postgrest/index.server";import type { AssetObjectStore } from "./client";import { loadAssetFoldersByProjectWithClient } from "./folder-persistence";import { assertPostgrestSuccess } from "./patch-utils";-import { isContentHash } from "./content-hash";import {deleteCanonicalAssetFileEntryIfMatches,deleteInvalidCanonicalAssetFileEntryIfMatches,@@ -46,21 +46,6 @@ export type CanonicalAssetSynchronizationIssue = {const getErrorMessage = (error: unknown) =>error instanceof Error ? error.message : "Unknown asset indexing failure";-const createAssetContentRevision = ({- storageName,- updatedAt,- size,- contentHash,-}: {- storageName: string;- updatedAt: string;- size: number;- contentHash?: string | null;-}) =>- isContentHash(contentHash)- ? `sha256:${contentHash}`- : `file:${encodeURIComponent(storageName)}:${updatedAt}:${size}`;-type UploadedAssetRow = {id: string;projectId: string;diff --git a/packages/asset-uploader/src/content-hash.ts b/packages/asset-uploader/src/content-hash.tsindex eea9b46813..7e2439ecb0 100644--- a/packages/asset-uploader/src/content-hash.ts+++ b/packages/asset-uploader/src/content-hash.ts@@ -1,4 +1,2 @@-const contentHashPattern = /^[a-f0-9]{64}$/;--export const isContentHash = (value: unknown): value is string =>- typeof value === "string" && contentHashPattern.test(value);+// Compatibility export for existing Asset Uploader consumers.+export { isContentHash } from "@webstudio-is/sdk";diff --git a/packages/asset-uploader/src/publication.test.ts b/packages/asset-uploader/src/publication.test.tsindex 5a54e66d73..c9fdff8a29 100644--- a/packages/asset-uploader/src/publication.test.ts+++ b/packages/asset-uploader/src/publication.test.ts@@ -93,4 +93,44 @@ describe("published asset data", () => {expect(prepareIndex).toHaveBeenCalledTimes(2);expect(loadAssetDataByProject).toHaveBeenCalledTimes(4);});++ test("recompiles and validates bounded dynamic publication dependencies", async () => {+ const preliminaryArtifact = { documents: [{ _id: "post" }] } as never;+ const finalArtifact = {+ documents: [{ _id: "post" }, { _id: "article.mdx" }],+ } as never;+ const initialPlan = { queries: [{ id: "posts" }] } as never;+ const resolvedPlan = {+ queries: [{ id: "posts" }, { id: "mdx:article" }],+ } as never;+ const prepareIndex = vi+ .fn()+ .mockResolvedValueOnce(preliminaryArtifact)+ .mockResolvedValueOnce(finalArtifact);+ const resolvePlan = vi.fn(() => resolvedPlan);+ const assetData = { assets: [], assetFolders: [] };++ const result = await preparePublishedAssetData(+ {+ projectId: "project-1",+ context: {} as never,+ assetStore: {} as never,+ contentDatabaseMaxBytes: 512_000,+ plan: initialPlan,+ retainedAssetIds: [],+ resolvePlan,+ },+ {+ createRepository: vi.fn(() => ({ prepareIndex })),+ loadAssetDataByProject: vi.fn().mockResolvedValue(assetData),+ } as never+ );++ expect(result.artifact).toBe(finalArtifact);+ expect(prepareIndex.mock.calls).toEqual([[initialPlan], [resolvedPlan]]);+ expect(resolvePlan.mock.calls).toEqual([+ [preliminaryArtifact],+ [finalArtifact],+ ]);+ });});diff --git a/packages/asset-uploader/src/publication.ts b/packages/asset-uploader/src/publication.tsindex 24b795a39d..e948ed33b2 100644--- a/packages/asset-uploader/src/publication.ts+++ b/packages/asset-uploader/src/publication.ts@@ -1,7 +1,9 @@import {getContentArtifactRuntimeAssetIds,type ContentCompilationPlan,+ type ContentArtifactV1,} from "@webstudio-is/content-engine";+import { serializeJsonDeterministically } from "@webstudio-is/content-engine/compiler";import type { Asset } from "@webstudio-is/sdk";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";import { PostgresAssetRepository } from "./asset-repository";@@ -23,6 +25,7 @@ export const preparePublishedAssetData = async (contentDatabaseMaxBytes,plan,retainedAssetIds,+ resolvePlan,}: {projectId: string;context: AppContext;@@ -30,6 +33,9 @@ export const preparePublishedAssetData = async (contentDatabaseMaxBytes: number;plan: ContentCompilationPlan;retainedAssetIds: Iterable<string>;+ resolvePlan?: (+ artifact: ContentArtifactV1+ ) => ContentCompilationPlan | Promise<ContentCompilationPlan>;},dependencies = defaultDependencies) => {@@ -44,12 +50,34 @@ export const preparePublishedAssetData = async (projectId,context);- const artifact = await repository.prepareIndex(plan);+ let artifact = await repository.prepareIndex(plan);+ if (resolvePlan !== undefined) {+ let resolvedPlan = await resolvePlan(artifact);+ for (let dependencyPass = 0; dependencyPass < 20; dependencyPass += 1) {+ artifact = await repository.prepareIndex(resolvedPlan);+ const validatedPlan = await resolvePlan(artifact);+ if (+ serializeJsonDeterministically(resolvedPlan) ===+ serializeJsonDeterministically(validatedPlan)+ ) {+ break;+ }+ if (dependencyPass === 19) {+ throw new Error(+ "Dynamic MDX dependency closure exceeds the safe publication depth"+ );+ }+ resolvedPlan = validatedPlan;+ }+ }const assetDataAfter = await dependencies.loadAssetDataByProject(projectId,context);- if (JSON.stringify(assetDataBefore) !== JSON.stringify(assetDataAfter)) {+ if (+ serializeJsonDeterministically(assetDataBefore) !==+ serializeJsonDeterministically(assetDataAfter)+ ) {if (attempt === 0) {continue;}diff --git a/packages/asset-uploader/src/revision.ts b/packages/asset-uploader/src/revision.tsindex 0ec8f8135a..bdaca3897c 100644--- a/packages/asset-uploader/src/revision.ts+++ b/packages/asset-uploader/src/revision.ts@@ -16,8 +16,8 @@ import { createUniqueAssetFilename } from "./utils/get-unique-filename";import { sanitizeS3Key } from "./utils/sanitize-s3-key";import { formatAsset } from "./utils/format-asset";import { assertPostgrestSuccess } from "./patch-utils";--export class AssetRevisionConflictError extends Error {}+import { AssetRevisionConflictError } from "@webstudio-is/content-engine/asset-content-repository";+export { AssetRevisionConflictError } from "@webstudio-is/content-engine/asset-content-repository";const getRevisionFilename = ({name,diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex 28250688a8..0c5db246cb 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -23,7 +23,7 @@"scripts": {"typecheck": "tsc --noEmit","generate-docs": "tsx scripts/generate-docs.ts && oxfmt src/docs.generated.ts",- "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:content-runtime": "esbuild @webstudio-is/content-engine/runtime --bundle --format=esm --platform=browser --target=es2022 --conditions=webstudio,worker --minify --outfile=lib/content-runtime.js","fixtures:build": "pnpm build:content-runtime","build": "pnpm generate-docs && rm -rf lib && vite build && pnpm build:content-runtime","pretest": "mkdir -p lib && pnpm build:content-runtime",diff --git a/packages/cli/src/commands/mcp.test.ts b/packages/cli/src/commands/mcp.test.tsindex 5849a5352f..f954cc9156 100644--- a/packages/cli/src/commands/mcp.test.ts+++ b/packages/cli/src/commands/mcp.test.ts@@ -31,6 +31,7 @@ const {createMcpStatusReporter,getLoadedProjectSessionSnapshot,getMcpOperationInput,+ withMdxAssetWriteFeedback,reportMcpSingleOpCallTermination,reportMcpRunTermination,createMcpRunTerminationController,@@ -1254,6 +1255,39 @@ test("adapts MCP asset content input to the shared revision client", async () =>await expect(input.readAssetData()).resolves.toBe('{"theme":"dark"}');});+test("returns diagnostics without rejecting an invalid MDX Asset write", async () => {+ const source = "# Kept\n\n<ws.element";+ const operationInput = getMcpOperationInput("update-asset-content", {+ assetId: "asset-id",+ expectedName: "article_hash.mdx",+ content: source,+ });++ await expect(+ withMdxAssetWriteFeedback({+ command: "update-asset-content",+ input: {+ assetId: "asset-id",+ expectedName: "article_hash.mdx",+ content: source,+ },+ operationInput,+ result: { result: { assetId: "asset-id" } },+ })+ ).resolves.toEqual({+ result: {+ assetId: "asset-id",+ source,+ diagnostics: [+ expect.objectContaining({+ code: "invalid-mdx",+ severity: "error",+ }),+ ],+ },+ });+});+test("exposes asset content editing through MCP discovery", () => {const tool = listProjectSessionMcpTools(publicApiOperations).find(({ name }) => name === "update-asset-content"diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.tsindex 34cebb46a0..e069290d47 100644--- a/packages/cli/src/commands/mcp.ts+++ b/packages/cli/src/commands/mcp.ts@@ -21,6 +21,16 @@ import * as httpClient from "@webstudio-is/http-client";import packageJson from "../../package.json" with { type: "json" };import type { ProjectSessionSnapshot } from "@webstudio-is/project-build/project-session";import type { SemanticValidationIssue } from "@webstudio-is/project-build/runtime";+import {+ inspectMdxAssetSource,+ mdxAssetInspectionNamespaces,+} from "@webstudio-is/project-build/runtime";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";+import {+ createMdxSourceDiagnostics,+ parseMdxDocumentRecovering,+} from "@webstudio-is/content-engine/mdx";+import { getFileExtension, isMdxFileAsset } from "@webstudio-is/sdk";import { resolveApiConnection } from "../api-connection";import {getCliErrorIssues,@@ -41,6 +51,7 @@ import {getSupportedPublicApiOperations,type CliServerApiContract,writeCliProjectSessionPreviewDataFile,+ type CliProjectSession,} from "../project-session";import { executeProjectSessionApiOperation } from "../project-session-api";import { createPreviewController } from "../preview-server";@@ -211,7 +222,7 @@ const getMcpUpdateAssetContentInput = (input: unknown) => {"update-asset-content requires assetId and expectedName strings.");}- return createLocalUpdateAssetContentInput({+ const prepared = createLocalUpdateAssetContentInput({assetId: input.assetId,expectedName: input.expectedName,extension:@@ -220,6 +231,86 @@ const getMcpUpdateAssetContentInput = (input: unknown) => {content: typeof input.content === "string" ? input.content : undefined,readFile,});+ let content: Promise<unknown> | undefined;+ return {+ ...prepared,+ readAssetData: () => (content ??= prepared.readAssetData()),+ };+};++const inspectMdxSource = async (source: string) => {+ const parsed = await parseMdxDocumentRecovering({ source });+ return createMdxSourceDiagnostics(parsed.diagnostics);+};++const decodeMdxSource = (value: unknown) => {+ if (typeof value === "string") {+ return value;+ }+ if (value instanceof Uint8Array) {+ return new TextDecoder("utf-8", { fatal: true }).decode(value);+ }+ throw new Error("MDX Asset content must be UTF-8 text.");+};++const withMdxAssetWriteFeedback = async <Envelope extends { result: unknown }>({+ command,+ input,+ operationInput,+ result,+ session,+}: {+ command: string;+ input: unknown;+ operationInput: unknown;+ result: Envelope;+ session?: Pick<CliProjectSession, "ensureNamespaces">;+}): Promise<Envelope> => {+ if (+ command !== "update-asset-content" ||+ isPlainRecord(input) === false ||+ isPlainRecord(operationInput) === false ||+ typeof operationInput.readAssetData !== "function" ||+ (typeof input.extension === "string"+ ? input.extension+ : typeof input.expectedName === "string"+ ? getFileExtension(input.expectedName)+ : undefined+ )?.toLowerCase() !== "mdx"+ ) {+ return result;+ }+ const source = decodeMdxSource(await operationInput.readAssetData());+ const assetId =+ typeof input.assetId === "string"+ ? input.assetId+ : isPlainRecord(result.result) &&+ typeof result.result.assetId === "string"+ ? result.result.assetId+ : undefined;+ const snapshot =+ assetId === undefined || session === undefined+ ? undefined+ : await session.ensureNamespaces(mdxAssetInspectionNamespaces);+ return {+ ...result,+ result: {+ ...(isPlainRecord(result.result)+ ? result.result+ : { result: result.result }),+ source,+ diagnostics:+ assetId === undefined || snapshot === undefined+ ? await inspectMdxSource(source)+ : await inspectMdxAssetSource({+ source,+ assetId,+ state: snapshot.state,+ metas: componentMetas,+ projectId: snapshot.projectId,+ }),+ },+ };};const getMcpOperationInput = (command: string, input: unknown) => {@@ -1061,9 +1152,10 @@ const createCliMcpHost = async ({createProjectSession: () => session,onProjectSessionChange: previewFreshness.markStale,executeOperation: async ({ command, input, dryRun }) => {+ const operationInput = getMcpOperationInput(command, input);const result = await executeProjectSessionApiOperation({command,- input: getMcpOperationInput(command, input),+ input: operationInput,connection: apiConnection,createProjectSession: () => session,dryRun,@@ -1071,7 +1163,13 @@ const createCliMcpHost = async ({if (dryRun !== true && shouldInvalidatePreview(command)) {previewFreshness.markStale();}- return result;+ return withMdxAssetWriteFeedback({+ command,+ input,+ operationInput,+ result,+ session,+ });},restorePoints: {async create({ name }) {@@ -1143,9 +1241,28 @@ const createCliMcpHost = async ({assetsDirectory: input.assetsDir,origin: connection.origin,});+ const localPath = getLocalAssetPath(asset.name, input.assetsDir);+ if (isMdxFileAsset(asset)) {+ const source = await readFile(localPath, "utf8");+ const inspectionSnapshot = await session.ensureNamespaces(+ mdxAssetInspectionNamespaces+ );+ return {+ assetId: asset.id,+ path: localPath,+ source,+ diagnostics: await inspectMdxAssetSource({+ source,+ assetId: asset.id,+ state: inspectionSnapshot.state,+ metas: componentMetas,+ projectId: inspectionSnapshot.projectId,+ }),+ };+ }return {assetId: asset.id,- path: getLocalAssetPath(asset.name, input.assetsDir),+ path: localPath,};},async startPreview(input, progress) {@@ -1868,6 +1985,7 @@ export const __testing__ = {createMcpRunCheckpointStopPayload,getLoadedProjectSessionSnapshot,getMcpOperationInput,+ withMdxAssetWriteFeedback,parseMcpSingleOpCallInput,validateSingleOpCallInput,isMcpToolCallFailure,diff --git a/packages/cli/src/commands/schema.test.ts b/packages/cli/src/commands/schema.test.tsindex f4d1f5232b..4f8336fa02 100644--- a/packages/cli/src/commands/schema.test.ts+++ b/packages/cli/src/commands/schema.test.ts@@ -168,7 +168,7 @@ test("prints compact mcp tool summaries as json by default", () => {inputSchema,}));- expect(JSON.stringify(handshakePayload).length).toBeLessThan(201_000);+ expect(JSON.stringify(handshakePayload).length).toBeLessThan(215_000);expect(JSON.stringify(expectedTools.find(({ name }) => name === "insert-page-transfer-item")@@ -249,6 +249,7 @@ test("prints full mcp tool input schemas when requested", () => {"contentMode","mode","insertIndex",+ "templateNameConfirmation","dryRun",]);const fragmentSchema = insertFragmentTool.inputSchema.properties.fragment;diff --git a/packages/cli/src/content-engine-reference.ts b/packages/cli/src/content-engine-reference.tsindex c03a57fffe..8f39bdef6c 100644--- a/packages/cli/src/content-engine-reference.ts+++ b/packages/cli/src/content-engine-reference.ts@@ -127,6 +127,9 @@ const documentedLimitKeys = ["jsonStringBytes","indexedPropertiesBytes","excerptBytes",+ "mdxDepth",+ "mdxNodes",+ "mdxProps","hydratedFileBytes","hydratedTotalBytes","hydratedFileCount",@@ -268,6 +271,9 @@ const contentLimitsTable = table({formatBytes(contentEngineLimits.indexedPropertiesBytes),],["Generated excerpt", formatBytes(contentEngineLimits.excerptBytes)],+ ["MDX nesting depth", String(contentEngineLimits.mdxDepth)],+ ["MDX nodes", String(contentEngineLimits.mdxNodes)],+ ["MDX properties", String(contentEngineLimits.mdxProps)],["Loaded file", formatBytes(contentEngineLimits.hydratedFileBytes)],["Loaded content per query",diff --git a/packages/cli/src/prebuild.test.ts b/packages/cli/src/prebuild.test.tsindex b0a8938aef..d6009f085c 100644--- a/packages/cli/src/prebuild.test.ts+++ b/packages/cli/src/prebuild.test.ts@@ -33,6 +33,7 @@ import {createCanonicalAssetFileEntry,createContentRuntimeArtifact,} from "@webstudio-is/content-engine/compiler";+import { contentEngineLimits } from "@webstudio-is/content-engine/limits";import { createPublishedAssetResourceFetch } from "@webstudio-is/content-engine/runtime";import {createStructuredAssetQueryResourceBody,@@ -782,6 +783,470 @@ test("hydrates encoded filenames from an embedded SSG database", async () => {});describe("prebuild", () => {+ test("materializes direct MDX Content Blocks into generated page code", async () => {+ const source = "# Published from MDX";+ const article: AssetFileDocument = {+ ...indexedDocument,+ _id: "article",+ name: "article.mdx",+ path: "article.mdx",+ key: "article",+ extension: "mdx",+ mimeType: "text/mdx",+ size: new TextEncoder().encode(source).byteLength,+ revision: "article-revision",+ contentRef: "article.mdx",+ properties: {},+ };+ const siteData = createSiteData({+ assets: [createAssetForIndexedDocument(article)],+ instances: [+ [+ "root",+ {+ id: "root",+ component: "Box",+ children: [{ type: "id", value: "content" }],+ },+ ],+ [+ "content",+ {+ id: "content",+ component: "ws:block",+ children: [],+ },+ ],+ ],+ props: [+ [+ "content-src",+ {+ id: "content-src",+ instanceId: "content",+ name: "src",+ type: "asset",+ value: "article",+ },+ ],+ ],+ });+ const siteDataWithIndex = {+ ...siteData,+ assetIndex: await createTestAssetIndex(article, {+ "article.mdx": source,+ }),+ };+ await writeSiteData(siteDataWithIndex);++ await prebuild({ assets: false, template: ["react-router"] });++ const generatedPage = await readFile(+ "app/__generated__/_index.tsx",+ "utf8"+ );+ expect(generatedPage).toContain("Published from MDX");+ expect(generatedPage).not.toContain("fetch(");+ });++ test("materializes Content Blocks introduced by an MDX template", async () => {+ const outerSource = '<ws.element ws:name="Nested" />';+ const innerSource = "# Nested published content";+ const createMdxDocument = (+ id: string,+ source: string+ ): AssetFileDocument => ({+ ...indexedDocument,+ _id: id,+ name: `${id}.mdx`,+ path: `${id}.mdx`,+ key: id,+ extension: "mdx",+ mimeType: "text/mdx",+ size: new TextEncoder().encode(source).byteLength,+ revision: `${id}-revision`,+ contentRef: `${id}.mdx`,+ properties: {},+ });+ const outer = createMdxDocument("outer", outerSource);+ const inner = createMdxDocument("inner", innerSource);+ const siteData = createSiteData({+ assets: [outer, inner].map(createAssetForIndexedDocument),+ instances: [+ [+ "root",+ {+ id: "root",+ component: "Box",+ children: [{ type: "id", value: "outer-block" }],+ },+ ],+ [+ "outer-block",+ {+ id: "outer-block",+ component: "ws:block",+ children: [{ type: "id", value: "templates" }],+ },+ ],+ [+ "templates",+ {+ id: "templates",+ component: "ws:block-template",+ children: [{ type: "id", value: "nested-block" }],+ },+ ],+ [+ "nested-block",+ {+ id: "nested-block",+ component: "ws:block",+ label: "Nested",+ children: [],+ },+ ],+ ],+ props: [+ [+ "outer-source",+ {+ id: "outer-source",+ instanceId: "outer-block",+ name: "src",+ type: "asset",+ value: "outer",+ },+ ],+ [+ "inner-source",+ {+ id: "inner-source",+ instanceId: "nested-block",+ name: "src",+ type: "asset",+ value: "inner",+ },+ ],+ ],+ });+ const siteDataWithIndex = {+ ...siteData,+ assetIndex: await createTestAssetIndex([outer, inner], {+ "outer.mdx": outerSource,+ "inner.mdx": innerSource,+ }),+ };+ await writeSiteData(siteDataWithIndex);++ await prebuild({ assets: false, template: ["react-router"] });++ await expect(+ readFile("app/__generated__/_index.tsx", "utf8")+ ).resolves.toContain("Nested published content");+ });++ test("warns and stops excessive published Content Block expansion", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const source = "# Published";+ const article: AssetFileDocument = {+ ...indexedDocument,+ _id: "article",+ name: "article.mdx",+ path: "article.mdx",+ key: "article",+ extension: "mdx",+ mimeType: "text/mdx",+ size: new TextEncoder().encode(source).byteLength,+ revision: "article-revision",+ contentRef: "article.mdx",+ properties: {},+ };+ const blockIds = Array.from(+ { length: contentEngineLimits.candidateDocuments + 1 },+ (_, index) => `content-${index}`+ );+ const siteData = createSiteData({+ assets: [createAssetForIndexedDocument(article)],+ instances: [+ [+ "root",+ {+ id: "root",+ component: "Box",+ children: blockIds.map((value) => ({ type: "id", value })),+ },+ ],+ ...blockIds.map(+ (id) =>+ [id, { id, component: "ws:block", children: [] }] as [+ string,+ Omit<Instance, "type">,+ ]+ ),+ ],+ props: blockIds.map((instanceId) => [+ `${instanceId}-source`,+ {+ id: `${instanceId}-source`,+ instanceId,+ name: "src",+ type: "asset",+ value: "article",+ },+ ]),+ });+ const siteDataWithIndex = {+ ...siteData,+ assetIndex: await createTestAssetIndex(article, {+ "article.mdx": source,+ }),+ };+ await writeSiteData(siteDataWithIndex);++ await prebuild({ assets: false, template: ["react-router"] });++ expect(+ warn.mock.calls+ .map(([message]) => JSON.parse(String(message)))+ .find(+ ({ message }) =>+ message ===+ "Published MDX Content Block count exceeds the safe limit"+ )+ ).toMatchObject({+ type: "webstudio-build-warning",+ feature: "content-block-mdx",+ code: "invalid-mdx",+ severity: "error",+ });+ });++ test("materializes finite dynamic MDX candidates without publishing unrelated files", async () => {+ const createDocument = (+ id: string,+ extension: "json" | "mdx",+ properties?: Record<string, string>+ ): AssetFileDocument => ({+ ...indexedDocument,+ _id: id,+ name: `${id}.${extension}`,+ path: `${id}.${extension}`,+ key: id,+ extension,+ mimeType: extension === "mdx" ? "text/mdx" : "application/json",+ revision: `${id}-revision`,+ contentRef: `${id}.${extension}`,+ properties: properties ?? {},+ });+ const post = createDocument("post", "json", {+ category: "published",+ mdx: "article",+ });+ const privatePost = createDocument("private-post", "json", {+ category: "private",+ mdx: "private",+ });+ const article = createDocument("article", "mdx");+ const privateArticle = createDocument("private", "mdx");+ const documents = [post, privatePost, article, privateArticle];+ const sourceExpression = `${encodeDataSourceVariable(+ "posts-data"+ )}.data.properties.mdx`;+ const siteData = createSiteData({+ assets: [+ ...documents.map(createAssetForIndexedDocument),+ {+ id: "dynamic-background",+ projectId: "project-1",+ name: "dynamic.png",+ type: "image",+ format: "png",+ size: 1,+ meta: { width: 1, height: 1 },+ description: null,+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ],+ instances: [+ [+ "root",+ {+ id: "root",+ component: "Box",+ children: [{ type: "id", value: "content" }],+ },+ ],+ [+ "content",+ {+ id: "content",+ component: "ws:block",+ children: [{ type: "id", value: "templates" }],+ },+ ],+ [+ "templates",+ {+ id: "templates",+ component: "ws:block-template",+ children: [{ type: "id", value: "dynamic-card" }],+ },+ ],+ [+ "dynamic-card",+ {+ id: "dynamic-card",+ component: "ws:element",+ tag: "section",+ label: "Dynamic card",+ children: [],+ },+ ],+ ],+ props: [+ [+ "content-src",+ {+ id: "content-src",+ instanceId: "content",+ name: "src",+ type: "expression",+ value: sourceExpression,+ },+ ],+ ],+ });+ siteData.build.dataSources = [+ [+ "posts-data",+ {+ type: "resource",+ id: "posts-data",+ scopeInstanceId: "root",+ name: "posts",+ resourceId: "posts",+ },+ ],+ ] as never;+ siteData.build.resources = [+ [+ "posts",+ {+ ...createQueryResource(),+ body: createStructuredAssetQueryResourceBody({+ where: {+ all: [+ {+ field: ["properties", "category"],+ operator: "eq",+ value: '"published"',+ },+ ],+ },+ sort: [],+ limit: "100",+ offset: "0",+ output: { mode: "all", includeMetadata: true },+ content: { mode: "none" },+ }),+ },+ ],+ ] as never;+ siteData.build.styleSources = [+ ["dynamic-style", { type: "local", id: "dynamic-style" }],+ ] as never;+ siteData.build.styleSourceSelections = [+ [+ "dynamic-card",+ { instanceId: "dynamic-card", values: ["dynamic-style"] },+ ],+ ] as never;+ siteData.build.breakpoints = [["base", { id: "base", label: "" }]] as never;+ siteData.build.styles = [+ [+ "dynamic-background-style",+ {+ styleSourceId: "dynamic-style",+ breakpointId: "base",+ property: "backgroundImage",+ value: {+ type: "layers",+ value: [+ {+ type: "image",+ value: { type: "asset", value: "dynamic-background" },+ },+ ],+ },+ },+ ],+ ] as never;+ const siteDataWithIndex = {+ ...siteData,+ assetIndex: await createTestAssetIndex(documents, {+ "article.mdx":+ '# Public article\n\n<ws.element ws:name="Dynamic card" />',+ "private.mdx": "# Private article",+ }),+ };+ await writeSiteData(siteDataWithIndex);++ await prebuild({ assets: false, template: ["react-router"] });++ const generatedPage = await readFile(+ "app/__generated__/_index.tsx",+ "utf8"+ );+ expect(generatedPage).toContain("Public article");+ expect(generatedPage).not.toContain("Private article");+ expect(generatedPage).toContain('=== "article"');+ expect(generatedPage).toContain("<section");+ expect(generatedPage).not.toContain('"dynamic.png"');+ });++ test("warns and skips a dynamic MDX source without finite candidates", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const siteData = createSiteData({+ instances: [+ [+ "root",+ {+ id: "root",+ component: "Box",+ children: [{ type: "id", value: "content" }],+ },+ ],+ ["content", { id: "content", component: "ws:block", children: [] }],+ ],+ props: [+ [+ "content-src",+ {+ id: "content-src",+ instanceId: "content",+ name: "src",+ type: "expression",+ value: "post.body",+ },+ ],+ ],+ });+ await writeSiteData(siteData);++ await prebuild({ assets: false, template: ["react-router"] });++ expect(+ warn.mock.calls+ .map(([message]) => JSON.parse(String(message)))+ .find(({ feature }) => feature === "content-block-mdx")+ ).toMatchObject({+ type: "webstudio-build-warning",+ code: "invalid-mdx",+ blockInstanceId: "content",+ });+ });+test("excludes resources in statically hidden subtrees", async () => {const siteData = createSiteData({instances: [@@ -1039,7 +1504,7 @@ describe("prebuild", () => {legacyCode.attrs.map(({ name, value }) => [name, value]))).toMatchObject({ class: "w-code-text", lang: "en" });- expect(findElementsByTagName(legacyCode, "span")).toHaveLength(0);+ expect(findElementsByTagName(legacyCode, "span").length).toBeGreaterThan(0);expect(getTextContent(legacyCode)).toBe("legacy <code>");}, 30_000);diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.tsindex b950bda79e..abe1182309 100644--- a/packages/cli/src/prebuild.ts+++ b/packages/cli/src/prebuild.ts@@ -14,8 +14,10 @@ import { fileURLToPath } from "node:url";import { parse } from "acorn";import { log, spinner } from "@clack/prompts";import merge from "deepmerge";+import deepEqual from "fast-deep-equal";import {generateWebstudioComponent,+ type PublishedContentBlock,type Params,normalizeProps,generateRemixRoute,@@ -35,13 +37,16 @@ import {isCoreComponent,coreMetas,decodeDataSourceVariable,+ findTreeInstanceIdsExcludingBlockTemplates,SYSTEM_VARIABLE_ID,generateCss,ROOT_INSTANCE_ID,elementComponent,toAssetReferenceRuntimeData,matchPathnameParams,- createReachableAssetContentCompilationPlan,+ blockComponent,+ getContentBlockSources,+ findContentBlockBodyContainers,parseStructuredAssetQueryResourceBody,type StructuredAssetQueryFilterBinding,type StructuredAssetQueryWhereBinding,@@ -59,12 +64,23 @@ import {import { migratePages } from "@webstudio-is/project-migrations/pages";import {collectFontFamiliesFromStyleDecls,+ createWebstudioDataFromFragment,+ createPublishedMdxMaterializationCache,+ getUnsafeDynamicPublishedMdxDiagnostic,+ materializePublishedMdx,getZodValidationIssues,} from "@webstudio-is/project-build/runtime";+import {+ createPublishedBuildContentCompilationPlan,+ getDynamicPublishedMdxSourceBlockIds,+ hasDynamicPublishedMdxSources,+ resolvePublishedMdxAssetCandidates,+} from "@webstudio-is/project-build";import {assetQueryFilter,type AssetRuntimeData,type AssetQueryFilter,+ type ContentArtifactV1,type ContentRuntimeArtifact,type ContentDatabaseDocument,createContentRuntimeArtifact,@@ -76,6 +92,7 @@ import {serializeContentRuntimeArtifact,verifyContentArtifact,} from "@webstudio-is/content-engine";+import { contentEngineLimits } from "@webstudio-is/content-engine/limits";import { assetResourceLimits } from "@webstudio-is/sdk/asset-resource-limits";import {parseJsonExpression,@@ -135,6 +152,7 @@ type SiteDataByPage = {assets: Array<Asset>;params?: Params;pages: Array<Page>;+ publishedContentBlocks?: ReadonlyMap<string, PublishedContentBlock>;};};@@ -550,25 +568,21 @@ export const createGeneratedAssetResourceFetch = ({ request, fallback }: ${input`;};-export const materializeAssetIndex = async ({+const materializeVerifiedAssetIndex = async ({index,runtimeAssets,includeDocumentRuntimeAssets,generatedDirectory,deploymentId,}: {- index: PublishedProjectBundle["assetIndex"];+ index: ContentArtifactV1 | undefined;runtimeAssets: Readonly<Record<string, AssetRuntimeData>>;includeDocumentRuntimeAssets: boolean;generatedDirectory: string;deploymentId: string;}) => {- const verifiedIndex =- index === undefined ? undefined : await verifyContentArtifact(index);const runtimeIndex =- verifiedIndex === undefined- ? undefined- : createContentRuntimeArtifact(verifiedIndex);+ index === undefined ? undefined : createContentRuntimeArtifact(index);const serializedIndex =runtimeIndex === undefined? undefined@@ -581,9 +595,7 @@ export const materializeAssetIndex = async ({includeDocuments: includeDocumentRuntimeAssets,});const referencedAssetIds = new Set(- verifiedIndex === undefined- ? []- : getContentArtifactReferencedAssetIds(verifiedIndex)+ index === undefined ? [] : getContentArtifactReferencedAssetIds(index));const documentIds = new Set(runtimeIndex?.documentGraph?.nodes.map(({ id }) => id) ?? []@@ -606,7 +618,7 @@ export const materializeAssetIndex = async ({}));const runtimePath = join(generatedDirectory, contentRuntimeFile);- if (index === undefined) {+ if (runtimeIndex === undefined) {await rm(runtimePath, { force: true });} else {await cp(contentRuntimeBundleUrl, runtimePath);@@ -633,6 +645,21 @@ export const assetQueryDatabase = ${serializedIndex};);};+export const materializeAssetIndex = async ({+ index,+ ...options+}: {+ index: PublishedProjectBundle["assetIndex"];+ runtimeAssets: Readonly<Record<string, AssetRuntimeData>>;+ includeDocumentRuntimeAssets: boolean;+ generatedDirectory: string;+ deploymentId: string;+}) =>+ materializeVerifiedAssetIndex({+ ...options,+ index: index === undefined ? undefined : await verifyContentArtifact(index),+ });+const writeWsAuthResources = async (generatedDir: string,pages: Pages,@@ -930,6 +957,46 @@ export const prebuild = async (options: {);}const siteData = parsedSiteData.data;+ const pages = migratePages(siteData.build.pages);+ const publicationBuild = { ...siteData.build, pages };+ const verifiedAssetIndex =+ siteData.assetIndex === undefined+ ? undefined+ : await verifyContentArtifact(siteData.assetIndex);+ let dynamicMdxCandidates: ReadonlyMap<string, readonly string[]> | undefined;+ if (hasDynamicPublishedMdxSources(publicationBuild)) {+ dynamicMdxCandidates =+ verifiedAssetIndex === undefined+ ? new Map()+ : resolvePublishedMdxAssetCandidates({+ build: publicationBuild,+ artifact: verifiedAssetIndex,+ allowUnresolved: true,+ });+ for (const blockInstanceId of getDynamicPublishedMdxSourceBlockIds(+ publicationBuild+ )) {+ if (dynamicMdxCandidates.has(blockInstanceId)) {+ continue;+ }+ console.warn(+ JSON.stringify({+ type: "webstudio-build-warning",+ feature: "content-block-mdx",+ code: "invalid-mdx",+ severity: "error",+ blockInstanceId,+ renderScope: `publication:block:${blockInstanceId}`,+ message:+ "The dynamic MDX source has no finite, discoverable Asset candidate set and was skipped.",+ })+ );+ }+ }+ const assetCompilationPlan = createPublishedBuildContentCompilationPlan(+ publicationBuild,+ dynamicMdxCandidates+ );await configureSsgAssetResourceFetch({enabled: siteData.assetIndex !== undefined,});@@ -937,7 +1004,6 @@ export const prebuild = async (options: {const usedMetas = new Map<Instance["component"], WsComponentMeta>(Object.entries(coreMetas));- const pages = migratePages(siteData.build.pages);const publishablePages = getPublishablePages(pages);const generatedPages = options.includeDraftPages? getAllPages(pages)@@ -1026,59 +1092,332 @@ export const prebuild = async (options: {page,assets: siteData.assets,};+ }- // Extract background SVGs and Font assets- const styleSourceSelections = siteData.build?.styleSourceSelections ?? [];- const pageStyleSourceIds = new Set(- styleSourceSelections- .filter(([, { instanceId }]) => pageInstanceSet.has(instanceId))- .map(([, { values }]) => values)- .flat()- );+ const assets = new Map(siteData.assets.map((asset) => [asset.id, asset]));+ const runtimeAssetsById = Object.fromEntries(+ siteData.assets.map((asset) => {+ const runtimeAsset = toAssetReferenceRuntimeData(+ 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 publishedInstances = new Map(siteData.build.instances);+ const publishedProps = new Map(siteData.build.props);+ const publishedStyleSources = new Map(siteData.build.styleSources);+ const publishedStyleSourceSelections = new Map(+ siteData.build.styleSourceSelections+ );+ const publishedStyles = new Map(siteData.build.styles);+ const publishedBreakpoints = new Map(siteData.build.breakpoints);+ if (verifiedAssetIndex !== undefined) {+ const cache = createPublishedMdxMaterializationCache();+ const mergeRecords = <Value>(+ target: Map<string, Value>,+ records: Iterable<readonly [string, Value]>,+ namespace: string+ ) => {+ for (const [key, value] of records) {+ const existing = target.get(key);+ if (existing !== undefined && deepEqual(existing, value)) {+ continue;+ }+ if (existing !== undefined) {+ throw new Error(+ `Published MDX ${namespace} collision for ${JSON.stringify(key)}`+ );+ }+ target.set(key, value);+ }+ };- const pageStyles =- siteData.build?.styles- ?.filter(([, { styleSourceId }]) =>- pageStyleSourceIds.has(styleSourceId)+ for (const page of generatedPages) {+ const pageData = siteDataByPage[page.id];+ const route = getPagePath(page.id, pages);+ const pageInstances = new Map(pageData.build.instances);+ const pageProps = new Map(pageData.build.props);+ const materializationProps = new Map(+ siteData.build.props.filter(([, prop]) =>+ pageInstances.has(prop.instanceId))- .map(([, style]) => style) ?? [];-- // Extract fonts- const pageFontFamilies = collectFontFamiliesFromStyleDecls(pageStyles);+ );+ const pageDataSources = new Map(pageData.build.dataSources);+ const pageResources = new Map(pageData.build.resources);+ const candidatesByBlock = new Map<string, PublishedContentBlock>();+ const processedBlockIds = new Set<string>();+ const queuedTreeRootIds = [page.rootInstanceId];+ const discoveredTreeRootIds = new Set(queuedTreeRootIds);++ for (;;) {+ const sourcesByBlockId = getContentBlockSources({+ instances: pageInstances.values(),+ props: materializationProps.values(),+ });+ const pendingBlockIds = new Set<string>();+ for (const rootInstanceId of queuedTreeRootIds.splice(0)) {+ for (const instanceId of findTreeInstanceIdsExcludingBlockTemplates(+ pageInstances,+ rootInstanceId+ )) {+ if (+ processedBlockIds.has(instanceId) === false &&+ pageInstances.get(instanceId)?.component === blockComponent &&+ sourcesByBlockId.has(instanceId)+ ) {+ pendingBlockIds.add(instanceId);+ }+ }+ }+ if (pendingBlockIds.size === 0) {+ break;+ }+ if (+ processedBlockIds.size + pendingBlockIds.size >+ contentEngineLimits.candidateDocuments+ ) {+ console.warn(+ JSON.stringify({+ type: "webstudio-build-warning",+ feature: "content-block-mdx",+ route,+ code: "invalid-mdx",+ severity: "error",+ blockInstanceId: pendingBlockIds.values().next().value,+ message:+ "Published MDX Content Block count exceeds the safe limit",+ })+ );+ break;+ }+ for (const blockId of pendingBlockIds) {+ processedBlockIds.add(blockId);+ }+ const pageBuild = {+ instances: Array.from(pageInstances.values()),+ props: Array.from(materializationProps.values()),+ dataSources: Array.from(pageDataSources.values()),+ resources: Array.from(pageResources.values()),+ };+ const pageDynamicCandidates = hasDynamicPublishedMdxSources(+ pageBuild,+ pendingBlockIds+ )+ ? resolvePublishedMdxAssetCandidates({+ build: pageBuild,+ artifact: verifiedAssetIndex,+ blockInstanceIds: pendingBlockIds,+ })+ : undefined;+ const materialized = await materializePublishedMdx({+ route,+ data: {+ instances: pageInstances,+ props: materializationProps,+ dataSources: pageDataSources,+ resources: pageResources,+ styleSources: publishedStyleSources,+ styleSourceSelections: publishedStyleSourceSelections,+ styles: publishedStyles,+ breakpoints: publishedBreakpoints,+ assets,+ },+ artifact: verifiedAssetIndex,+ metas: usedMetas,+ projectId: siteData.build.projectId,+ cache,+ dynamicAssetIdsByBlock: pageDynamicCandidates,+ blockInstanceIds: pendingBlockIds,+ runtimeAssets: runtimeAssetsById,+ });+ for (const root of materialized.roots) {+ const diagnostic = getUnsafeDynamicPublishedMdxDiagnostic({+ root,+ route,+ dataSources: pageDataSources,+ props: materializationProps,+ });+ if (diagnostic !== undefined) {+ console.warn(+ JSON.stringify({+ type: "webstudio-build-warning",+ feature: "content-block-mdx",+ route,+ ...diagnostic,+ })+ );+ continue;+ }+ const fragmentData = createWebstudioDataFromFragment(root.fragment);+ mergeRecords(pageInstances, fragmentData.instances, "instance");+ mergeRecords(publishedInstances, fragmentData.instances, "instance");+ for (const child of root.fragment.children) {+ if (+ child.type === "id" &&+ discoveredTreeRootIds.has(child.value) === false+ ) {+ discoveredTreeRootIds.add(child.value);+ queuedTreeRootIds.push(child.value);+ }+ }+ mergeRecords(+ materializationProps,+ fragmentData.props,+ "authored prop"+ );+ const normalizedFragmentProps = normalizeProps({+ props: root.fragment.props,+ assetBaseUrl,+ assets,+ uploadingImageAssets: [],+ pages,+ source: "prebuild",+ });+ const normalizedProps = normalizedFragmentProps.map(+ (prop) => [prop.id, prop] as const+ );+ mergeRecords(pageProps, normalizedProps, "prop");+ mergeRecords(publishedProps, normalizedProps, "prop");+ mergeRecords(+ pageDataSources,+ fragmentData.dataSources,+ "data source"+ );+ mergeRecords(pageResources, fragmentData.resources, "resource");+ mergeRecords(+ publishedStyleSources,+ fragmentData.styleSources,+ "style source"+ );+ mergeRecords(+ publishedStyleSourceSelections,+ fragmentData.styleSourceSelections,+ "style source selection"+ );+ mergeRecords(+ publishedStyles,+ fragmentData.styles,+ "style declaration"+ );+ mergeRecords(+ publishedBreakpoints,+ fragmentData.breakpoints,+ "breakpoint"+ );+ const previous = candidatesByBlock.get(root.identity.blockInstanceId);+ const blockInstance = pageInstances.get(+ root.identity.blockInstanceId+ );+ const bodyInstanceId =+ blockInstance === undefined+ ? undefined+ : findContentBlockBodyContainers({+ blockInstance,+ instances: pageInstances,+ })[0]?.id;+ candidatesByBlock.set(root.identity.blockInstanceId, {+ ...(bodyInstanceId === undefined ? {} : { bodyInstanceId }),+ ...(root.source.type === "expression"+ ? { sourceExpression: root.source.value }+ : {}),+ candidates: [+ ...(previous?.candidates ?? []),+ {+ assetId: root.identity.assetId,+ dependencyRevision: root.dependencyRevision,+ children: root.fragment.children,+ frontmatter: root.resolvedFrontmatter,+ resourceIds: root.fragment.resources.map(({ id }) => id),+ },+ ],+ });+ }+ for (const warning of materialized.warnings) {+ console.warn(+ JSON.stringify({+ type: "webstudio-build-warning",+ feature: "content-block-mdx",+ route: warning.route,+ ...warning.diagnostic,+ })+ );+ }+ }+ pageData.build.instances = Array.from(pageInstances);+ pageData.build.props = Array.from(pageProps);+ pageData.build.dataSources = Array.from(pageDataSources);+ pageData.build.resources = Array.from(pageResources);+ pageData.publishedContentBlocks = candidatesByBlock;+ }+ }- const pageFontAssets = siteData.assets+ for (const page of generatedPages) {+ const pageInstances = new Map(siteDataByPage[page.id].build.instances);+ const renderedIds = findTreeInstanceIdsExcludingBlockTemplates(+ pageInstances,+ page.rootInstanceId+ );+ for (const block of siteDataByPage[+ page.id+ ].publishedContentBlocks?.values() ?? []) {+ if (block.sourceExpression !== undefined) {+ continue;+ }+ for (const candidate of block.candidates) {+ for (const child of candidate.children) {+ if (child.type === "id") {+ for (const instanceId of findTreeInstanceIdsExcludingBlockTemplates(+ pageInstances,+ child.value+ )) {+ renderedIds.add(instanceId);+ }+ }+ }+ }+ }+ const styleSourceIds = new Set(+ Array.from(publishedStyleSourceSelections.values())+ .filter(({ instanceId }) => renderedIds.has(instanceId))+ .flatMap(({ values }) => values)+ );+ const pageStyles = Array.from(publishedStyles.values()).filter(+ ({ styleSourceId }) => styleSourceIds.has(styleSourceId)+ );+ const fontFamilies = collectFontFamiliesFromStyleDecls(pageStyles);+ fontAssetsByPage[page.id] = siteData.assets.filter((asset) => asset.type === "font")- .filter((fontAsset) => pageFontFamilies.has(fontAsset.meta.family))+ .filter((asset) => fontFamilies.has(asset.meta.family)).map((asset) => asset.name);-- fontAssetsByPage[page.id] = pageFontAssets;-- // Extract background images- // backgroundImage => "value.type=="layers" => value.type == "image" => .value (assetId)- const backgroundImageAssetIdSet = new Set(- pageStyles- .filter(({ property }) => property === "backgroundImage")- .map(({ value }) =>- value.type === "layers"- ? value.value.map((layer) =>- layer.type === "image"- ? layer.value.type === "asset"- ? layer.value.value- : undefined- : undefined- )- : undefined- )- .flat()- .filter(<T>(value: T): value is NonNullable<T> => value !== undefined)+ const backgroundImageAssetIds = new Set(+ pageStyles.flatMap(({ property, value }) =>+ property === "backgroundImage" && value.type === "layers"+ ? value.value.flatMap((layer) =>+ layer.type === "image" && layer.value.type === "asset"+ ? [layer.value.value]+ : []+ )+ : []+ ));-- const backgroundImageAssets = siteData.assets+ backgroundImageAssetsByPage[page.id] = siteData.assets.filter((asset) => asset.type === "image")- .filter((imageAsset) => backgroundImageAssetIdSet.has(imageAsset.id))+ .filter((asset) => backgroundImageAssetIds.has(asset.id)).map((asset) => asset.name);-- backgroundImageAssetsByPage[page.id] = backgroundImageAssets;}if (options.assets === true) {@@ -1089,15 +1428,13 @@ export const prebuild = async (options: {}}- const assets = new Map(siteData.assets.map((asset) => [asset.id, asset]));-const { cssText, classes } = generateCss({- instances: new Map(siteData.build.instances),- props: new Map(siteData.build.props),+ instances: publishedInstances,+ props: publishedProps,assets,- breakpoints: new Map(siteData.build?.breakpoints),- styles: new Map(siteData.build?.styles),- styleSourceSelections: new Map(siteData.build?.styleSourceSelections),+ breakpoints: publishedBreakpoints,+ styles: publishedStyles,+ styleSourceSelections: publishedStyleSourceSelections,// pass only used metas to not generate unused preset stylescomponentMetas: usedMetas,assetBaseUrl,@@ -1248,6 +1585,7 @@ export const prebuild = async (options: {classesMap: classes,metas: usedMetas,tagsOverrides: framework.tags,+ publishedContentBlocks: pageData.publishedContentBlocks,});const projectMeta = siteData.build.projectSettings?.meta ?? pages.meta;@@ -1346,6 +1684,23 @@ export const prebuild = async (options: {dataSources,props,resources,+ contentBlockResourceSelections: Array.from(+ pageData.publishedContentBlocks?.values() ?? []+ ).flatMap((block) =>+ block.sourceExpression === undefined+ ? []+ : [+ {+ sourceExpression: block.sourceExpression,+ candidates: block.candidates.map(+ ({ assetId, resourceIds = [] }) => ({+ assetId,+ resourceIds,+ })+ ),+ },+ ]+ ),})}${generatePageMeta({@@ -1441,40 +1796,11 @@ export const prebuild = async (options: {`);- // Generate assets resource file.- // 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) => {- const runtimeAsset = toAssetReferenceRuntimeData(- 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),- dataSources: siteData.build.dataSources.map(([, dataSource]) => dataSource),- resources: siteData.build.resources.map(([, resource]) => resource),- });-- await materializeAssetIndex({- index: siteData.assetIndex,- runtimeAssets: assetsById,+ // Generate assets resource file. The same deployment URLs are used above+ // when resolving MDX frontmatter into generated component bindings.+ await materializeVerifiedAssetIndex({+ index: verifiedAssetIndex,+ runtimeAssets: runtimeAssetsById,includeDocumentRuntimeAssets:assetCompilationPlan !== undefined &&requiresRuntimeDocumentData(assetCompilationPlan),@@ -1498,7 +1824,7 @@ export const prebuild = async (options: {await writeGeneratedFile(join(generatedDir, "$resources.assets.ts"),`- export const assets = ${JSON.stringify(assetsById, null, 2)};+ export const assets = ${JSON.stringify(runtimeAssetsById, null, 2)};`);diff --git a/packages/cli/src/project-session.ts b/packages/cli/src/project-session.tsindex e3d5a588eb..1f7a2abb35 100644--- a/packages/cli/src/project-session.ts+++ b/packages/cli/src/project-session.ts@@ -10,6 +10,9 @@ import {serializePages,} from "@webstudio-is/project-migrations/pages";import * as httpClient from "@webstudio-is/http-client";+import { createHttpAssetContentRepository } from "@webstudio-is/content-engine/asset-content-repository";+import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";import {bundleVersion,getPublicBuildIncludes,@@ -54,7 +57,10 @@ import {type SerializedBuilderStateSnapshot,} from "@webstudio-is/project-build/state";import { removeLegacyProjectSettingsFromPages } from "@webstudio-is/project-build";-import { getValidationIssues } from "@webstudio-is/project-build/runtime";+import {+ createContentBlockApplication,+ getValidationIssues,+} from "@webstudio-is/project-build/runtime";import type { BuilderStateFreshness } from "@webstudio-is/project-build/state";import { getLocalProjectStateDirectory, LOCAL_DATA_FILE } from "./config";import type { ApiConnection } from "./api-connection";@@ -558,6 +564,19 @@ export const createCliProjectSessionTransport = ({)) as Result),});+export const createCliAssetContentRepository = ({+ connection,+}: {+ connection: ApiConnection;+}) =>+ createHttpAssetContentRepository({+ projectId: connection.projectId,+ ...httpClient.createProjectAssetContentTransport({+ ...connection,+ authToken: () => connection.authToken,+ }),+ });+export const createCliProjectSession = ({connection,storage,@@ -566,6 +585,7 @@ export const createCliProjectSession = ({executeServerOperation,getPermissions,issueReportRuntime,+ assetContentRepository = createCliAssetContentRepository({ connection }),}: {connection: ApiConnection;storage?: ProjectSessionStorage;@@ -574,8 +594,21 @@ export const createCliProjectSession = ({executeServerOperation?: ProjectSessionTransport["executeServerOperation"];getPermissions?: ProjectSessionTransport["getPermissions"];issueReportRuntime?: () => IssueReportRuntime;-}) =>- createProjectSession({+ assetContentRepository?: ReturnType<typeof createCliAssetContentRepository>;+}) => {+ let projectSession: ReturnType<typeof createProjectSession>;+ const contentSession = createAssetContentSession({+ repository: assetContentRepository,+ authorize: async ({ operation }) => {+ const permissions = await projectSession.getPermissions();+ return (+ permissions.canUseApi &&+ permissions.canView &&+ (operation === "read" || permissions.canEdit)+ );+ },+ });+ projectSession = createProjectSession({projectId: connection.projectId,transport: createCliProjectSessionTransport({connection,@@ -589,7 +622,18 @@ export const createCliProjectSession = ({getCliProjectSessionFile(projectRoot, sessionProjectId)),compatibilityVersion,+ runtimeContext: {+ createId: randomUUID,+ projectId: connection.projectId,+ contentBlockApplication: createContentBlockApplication({+ projectId: connection.projectId,+ session: contentSession,+ metas: componentMetas,+ }),+ },});+ return projectSession;+};export type CliProjectSession = ReturnType<typeof createCliProjectSession>;diff --git a/packages/cli/templates/defaults/app/route-templates/html.tsx b/packages/cli/templates/defaults/app/route-templates/html.tsxindex 318f55ed13..5507cb745a 100644--- a/packages/cli/templates/defaults/app/route-templates/html.tsx+++ b/packages/cli/templates/defaults/app/route-templates/html.tsx@@ -128,6 +128,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/packages/cli/templates/defaults/app/route-templates/text.tsx b/packages/cli/templates/defaults/app/route-templates/text.tsxindex 843fc771d8..64b8fabe56 100644--- a/packages/cli/templates/defaults/app/route-templates/text.tsx+++ b/packages/cli/templates/defaults/app/route-templates/text.tsx@@ -87,6 +87,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/packages/cli/templates/defaults/app/route-templates/xml.tsx b/packages/cli/templates/defaults/app/route-templates/xml.tsxindex 5697d3cbd2..ebfe35b587 100644--- a/packages/cli/templates/defaults/app/route-templates/xml.tsx+++ b/packages/cli/templates/defaults/app/route-templates/xml.tsx@@ -95,6 +95,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/packages/cli/templates/react-router/app/route-templates/html.tsx b/packages/cli/templates/react-router/app/route-templates/html.tsxindex 193b5f5e6e..514fd8c004 100644--- a/packages/cli/templates/react-router/app/route-templates/html.tsx+++ b/packages/cli/templates/react-router/app/route-templates/html.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/packages/cli/templates/react-router/app/route-templates/text.tsx b/packages/cli/templates/react-router/app/route-templates/text.tsxindex 47aa3e535e..637ae82b41 100644--- a/packages/cli/templates/react-router/app/route-templates/text.tsx+++ b/packages/cli/templates/react-router/app/route-templates/text.tsx@@ -87,6 +87,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/packages/cli/templates/react-router/app/route-templates/xml.tsx b/packages/cli/templates/react-router/app/route-templates/xml.tsxindex 29a6545d32..90d8ec6502 100644--- a/packages/cli/templates/react-router/app/route-templates/xml.tsx+++ b/packages/cli/templates/react-router/app/route-templates/xml.tsx@@ -95,6 +95,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/packages/cli/templates/ssg/app/route-templates/html/+data.ts b/packages/cli/templates/ssg/app/route-templates/html/+data.tsindex 7362c216e4..c40e4927cd 100644--- a/packages/cli/templates/ssg/app/route-templates/html/+data.ts+++ b/packages/cli/templates/ssg/app/route-templates/html/+data.ts@@ -67,6 +67,14 @@ export const data = async (pageContext: PageContextServer) => {getResources({ system }).data,url);+ Object.assign(+ resources,+ await loadResources(+ customFetch,+ getResources({ system, resources }).contentData ?? new Map(),+ url+ )+ );const pageMeta = getPageMeta({ system, resources });return {diff --git a/packages/content-engine/package.json b/packages/content-engine/package.jsonindex 7ce2534af1..4388a50cac 100644--- a/packages/content-engine/package.json+++ b/packages/content-engine/package.json@@ -10,7 +10,7 @@"scripts": {"benchmark:index": "NODE_OPTIONS=--conditions=webstudio pnpm tsx scripts/benchmark-index.mjs","benchmark:scale": "NODE_OPTIONS=--conditions=webstudio pnpm tsx scripts/benchmark-scale.mjs",- "build": "rm -rf lib && esbuild src/index.ts src/compiler.ts src/limits.ts src/markdown-assets.ts src/markdown-references.ts src/published-runtime.ts --outdir=lib --bundle --format=esm --packages=external",+ "build": "rm -rf lib && esbuild src/index.ts src/asset-content-repository.ts src/asset-content-session.ts src/compiler.ts src/jsx-attributes.ts src/limits.ts src/markdown-assets.ts src/markdown-references.ts src/mdx.ts src/published-runtime.ts --outdir=lib --bundle --format=esm --packages=external","dts": "tsc --project tsconfig.dts.json","test": "vitest run","typecheck": "tsc --noEmit"@@ -20,9 +20,19 @@"@webstudio-is/expression": "workspace:*","@webstudio-is/query-builder": "workspace:*","canonicalize": "3.0.0",+ "hast-util-to-mdast": "9.0.0","lru-cache": "10.4.3",+ "mdast-util-gfm": "2.0.2",+ "mdast-util-mdx-expression": "1.3.2",+ "mdast-util-mdx-jsx": "2.1.4",+ "mdast-util-to-hast": "12.3.0",+ "mdast-util-to-markdown": "1.5.0","micromark": "4.0.2",+ "micromark-extension-mdxjs": "3.0.0","micromark-util-decode-string": "2.0.1",+ "remark-frontmatter": "4.0.1",+ "remark-gfm": "3.0.1",+ "remark-mdx": "2.3.0","remark-parse": "10.0.2","unified": "10.1.2","yaml": "2.9.0",@@ -46,6 +56,18 @@"import": "./lib/compiler.js","default": "./src/compiler.ts"},+ "./asset-content-repository": {+ "webstudio": "./src/asset-content-repository.ts",+ "types": "./lib/types/asset-content-repository.d.ts",+ "import": "./lib/asset-content-repository.js",+ "default": "./src/asset-content-repository.ts"+ },+ "./asset-content-session": {+ "webstudio": "./src/asset-content-session.ts",+ "types": "./lib/types/asset-content-session.d.ts",+ "import": "./lib/asset-content-session.js",+ "default": "./src/asset-content-session.ts"+ },"./runtime": {"webstudio": "./src/published-runtime.ts","types": "./lib/types/published-runtime.d.ts",@@ -58,6 +80,12 @@"import": "./lib/limits.js","default": "./src/limits.ts"},+ "./jsx-attributes": {+ "webstudio": "./src/jsx-attributes.ts",+ "types": "./lib/types/jsx-attributes.d.ts",+ "import": "./lib/jsx-attributes.js",+ "default": "./src/jsx-attributes.ts"+ },"./markdown-assets": {"webstudio": "./src/markdown-assets.ts","types": "./lib/types/markdown-assets.d.ts",@@ -69,6 +97,12 @@"types": "./lib/types/markdown-references.d.ts","import": "./lib/markdown-references.js","default": "./src/markdown-references.ts"+ },+ "./mdx": {+ "webstudio": "./src/mdx.ts",+ "types": "./lib/types/mdx.d.ts",+ "import": "./lib/mdx.js",+ "default": "./src/mdx.ts"}},"files": [diff --git a/packages/react-sdk/src/__generated__/standard-attributes.ts b/packages/content-engine/src/__generated__/standard-attributes.tssimilarity index 100%rename from packages/react-sdk/src/__generated__/standard-attributes.tsrename to packages/content-engine/src/__generated__/standard-attributes.tsdiff --git a/packages/content-engine/src/asset-content-repository.test.ts b/packages/content-engine/src/asset-content-repository.test.tsnew file mode 100644index 0000000000..5d59e94b48--- /dev/null+++ b/packages/content-engine/src/asset-content-repository.test.ts@@ -0,0 +1,47 @@+import { describe, expect, test } from "vitest";+import {+ readAssetContentBytes,+ type AssetContentRepository,+} from "./asset-content-repository";++const createRepository = (size: number): AssetContentRepository => ({+ readContent: async () => ({+ asset: {+ id: "asset",+ projectId: "project",+ name: "article.mdx",+ type: "file",+ format: "mdx",+ size,+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ data: (async function* () {+ yield new TextEncoder().encode("Current content");+ })(),+ }),+ updateContent: async () => {+ throw new Error("Not implemented");+ },+});++describe("readAssetContentBytes", () => {+ test("reads exact bounded content", async () => {+ const result = await readAssetContentBytes({+ repository: createRepository(15),+ assetId: "asset",+ maxSize: 100,+ });++ expect(new TextDecoder().decode(result.bytes)).toBe("Current content");+ });++ test("rejects content that does not match the descriptor size", async () => {+ await expect(+ readAssetContentBytes({+ repository: createRepository(14),+ assetId: "asset",+ maxSize: 100,+ })+ ).rejects.toThrow("does not match its declared size");+ });+});diff --git a/packages/content-engine/src/asset-content-repository.ts b/packages/content-engine/src/asset-content-repository.tsnew file mode 100644index 0000000000..56805f440c--- /dev/null+++ b/packages/content-engine/src/asset-content-repository.ts@@ -0,0 +1,179 @@+import { contentEngineLimits } from "@webstudio-is/content-engine/limits";+import {+ readableStreamToAsyncIterable,+ readBoundedBytes,+} from "@webstudio-is/content-engine/compiler";++export type AssetContentDescriptor = {+ id: string;+ projectId: string;+ name: string;+ type: string;+ format: string;+ size: number;+ createdAt: string;+ updatedAt?: string;+};++export type AssetContentRead = {+ asset: AssetContentDescriptor;+ data: AsyncIterable<Uint8Array>;+ contentLength?: number;+};++export interface AssetContentRepository {+ readContent(input: {+ assetId: string;+ range?: { offset: number; length: number };+ }): Promise<AssetContentRead>;+ updateContent(input: {+ assetId: string;+ expectedName: string;+ data: ReadableStream<Uint8Array>;+ }): Promise<AssetContentDescriptor>;+}++export class AssetContentIntegrityError extends Error {}++export const readAssetContentBytes = async ({+ repository,+ assetId,+ maxSize,+}: {+ repository: Pick<AssetContentRepository, "readContent">;+ assetId: string;+ maxSize: number;+}) => {+ const content = await repository.readContent({ assetId });+ const bytes = await readBoundedBytes(content.data, maxSize);+ if (bytes.byteLength !== content.asset.size) {+ throw new AssetContentIntegrityError(+ "Asset content does not match its declared size"+ );+ }+ return { asset: content.asset, bytes };+};++export class AssetRevisionConflictError extends Error {}++export class AssetContentAuthorizationError extends Error {}++const cancelBody = async (response: Response) => {+ try {+ await response.body?.cancel();+ } catch {+ // Keep the protocol failure that required cancellation.+ }+};++const mapError = (error: unknown): never => {+ const status =+ typeof error === "object" && error !== null && "status" in error+ ? error.status+ : undefined;+ if (status === 401 || status === 403) {+ throw new AssetContentAuthorizationError(+ "This Asset is not authorized for content access",+ { cause: error }+ );+ }+ if (status === 409) {+ throw new AssetRevisionConflictError(+ "This file changed since it was opened. Reload it before saving again.",+ { cause: error }+ );+ }+ throw error;+};++export const createHttpAssetContentRepository = ({+ projectId,+ read,+ update,+ parseAsset,+}: {+ projectId: string;+ read: (input: {+ assetId: string;+ range?: { offset: number; length: number };+ }) => Promise<Response>;+ update: (input: {+ assetId: string;+ expectedName: string;+ data: Uint8Array;+ }) => Promise<AssetContentDescriptor>;+ parseAsset: (response: Response) => AssetContentDescriptor;+}): AssetContentRepository => ({+ readContent: async ({ assetId, range }) => {+ try {+ const response = await read({ assetId, range });+ const expectedStatus = range === undefined ? 200 : 206;+ if (response.status !== expectedStatus) {+ await cancelBody(response);+ throw Object.assign(+ new Error(+ `Asset content response has unexpected status ${response.status}`+ ),+ { status: response.status }+ );+ }+ let asset: AssetContentDescriptor;+ try {+ asset = parseAsset(response);+ } catch (error) {+ await cancelBody(response);+ throw error;+ }+ if (asset.id !== assetId || asset.projectId !== projectId) {+ await cancelBody(response);+ throw new Error(+ "Asset content response does not match the requested Asset"+ );+ }+ if (+ range === undefined &&+ asset.size > contentEngineLimits.hydratedFileBytes+ ) {+ await cancelBody(response);+ throw new Error("Asset content exceeds the MDX editing limit");+ }+ if (response.body === null) {+ throw new Error("Asset content response has no body");+ }+ const contentLengthHeader = response.headers.get("content-length");+ const contentLength =+ contentLengthHeader === null ? undefined : Number(contentLengthHeader);+ if (+ contentLength !== undefined &&+ (Number.isSafeInteger(contentLength) === false || contentLength < 0)+ ) {+ await cancelBody(response);+ throw new Error("Asset content response has an invalid content length");+ }+ return {+ asset,+ data: readableStreamToAsyncIterable(response.body),+ contentLength,+ };+ } catch (error) {+ return mapError(error);+ }+ },+ updateContent: async ({ assetId, expectedName, data }) => {+ try {+ const bytes = await readBoundedBytes(+ readableStreamToAsyncIterable(data),+ contentEngineLimits.hydratedFileBytes+ );+ const descriptor = await update({ assetId, expectedName, data: bytes });+ if (descriptor.id !== assetId || descriptor.projectId !== projectId) {+ throw new Error(+ "Asset content update does not match the requested Asset"+ );+ }+ return descriptor;+ } catch (error) {+ return mapError(error);+ }+ },+});diff --git a/packages/content-engine/src/asset-content-session.test.ts b/packages/content-engine/src/asset-content-session.test.tsnew file mode 100644index 0000000000..749cd5ecd8--- /dev/null+++ b/packages/content-engine/src/asset-content-session.test.ts@@ -0,0 +1,263 @@+import { describe, expect, test, vi } from "vitest";+import type {+ AssetContentDescriptor,+ AssetContentRepository,+} from "./asset-content-repository";+import { AssetRevisionConflictError } from "./asset-content-repository";+import { createAssetContentSession } from "./asset-content-session";++const descriptor = (name = "article_v1.mdx"): AssetContentDescriptor => ({+ id: "asset",+ projectId: "project",+ name,+ type: "file",+ format: "mdx",+ size: 7,+ createdAt: "2026-01-01T00:00:00.000Z",+});++describe("Asset content session", () => {+ test("deduplicates concurrent loads for one Asset", async () => {+ let resolveRead!: (+ value: Awaited<ReturnType<AssetContentRepository["readContent"]>>+ ) => void;+ const readContent = vi.fn(+ () =>+ new Promise<Awaited<ReturnType<AssetContentRepository["readContent"]>>>(+ (resolve) => {+ resolveRead = resolve;+ }+ )+ );+ const session = createAssetContentSession({+ repository: {+ readContent,+ updateContent: vi.fn(),+ },+ authorize: async () => true,+ debounceMilliseconds: 0,+ });++ const first = session.open("asset");+ const second = session.open("asset");+ await vi.waitFor(() => expect(readContent).toHaveBeenCalledOnce());+ resolveRead({+ asset: descriptor(),+ data: (async function* () {+ yield new TextEncoder().encode("Initial");+ })(),+ });++ await expect(first).resolves.toMatchObject({ source: "Initial" });+ await expect(second).resolves.toMatchObject({ source: "Initial" });+ expect(readContent).toHaveBeenCalledOnce();+ });++ test("coalesces rapid edits and prepares the next write from the latest local source", async () => {+ const writes: string[] = [];+ let releaseFirst!: () => void;+ const repository: AssetContentRepository = {+ readContent: async () => ({+ asset: descriptor(),+ data: (async function* () {+ yield new TextEncoder().encode("Initial");+ })(),+ }),+ updateContent: async ({ data }) => {+ const source = await new Response(data).text();+ writes.push(source);+ if (writes.length === 1) {+ await new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });+ }+ return descriptor(`article_v${writes.length + 1}.mdx`);+ },+ };+ const session = createAssetContentSession({+ repository,+ authorize: async () => true,+ debounceMilliseconds: 0,+ });+ await session.open("asset");++ session.save("asset", "First");+ const flushing = session.flush("asset");+ await vi.waitFor(() => expect(writes).toEqual(["First"]));+ session.save("asset", "Latest");+ releaseFirst();+ await flushing;++ expect(writes).toEqual(["First", "Latest"]);+ expect(session.get("asset")).toMatchObject({+ status: "saved",+ source: "Latest",+ });+ });++ test("keeps failed local content retryable", async () => {+ let shouldFail = true;+ const repository: AssetContentRepository = {+ readContent: async () => ({+ asset: descriptor(),+ data: (async function* () {+ yield new TextEncoder().encode("Initial");+ })(),+ }),+ updateContent: async () => {+ if (shouldFail) {+ throw new Error("Temporary failure");+ }+ return descriptor("article_v2.mdx");+ },+ };+ const session = createAssetContentSession({+ repository,+ authorize: async () => true,+ debounceMilliseconds: 0,+ });+ await session.open("asset");+ session.save("asset", "Local");+ await expect(session.flush("asset")).rejects.toThrow("Temporary failure");+ expect(session.get("asset")).toMatchObject({+ status: "failed",+ source: "Local",+ });++ shouldFail = false;+ await session.retry("asset");+ expect(session.get("asset")).toMatchObject({+ status: "saved",+ source: "Local",+ });+ });++ test("flushes every accepted pending write before session teardown", async () => {+ const writes: string[] = [];+ const session = createAssetContentSession({+ repository: {+ readContent: async ({ assetId }) => ({+ asset: { ...descriptor(`${assetId}_v1.mdx`), id: assetId },+ data: (async function* () {+ yield new TextEncoder().encode("Initial");+ })(),+ }),+ updateContent: async ({ assetId, data }) => {+ writes.push(`${assetId}:${await new Response(data).text()}`);+ return { ...descriptor(`${assetId}_v2.mdx`), id: assetId };+ },+ },+ authorize: () => true,+ schedule: () => Symbol(),+ cancelScheduled: () => {},+ });+ await Promise.all([session.open("first"), session.open("second")]);+ session.save("first", "First draft");+ session.save("second", "Second draft");++ await session.flushAll();+ session.dispose();++ expect(writes.sort()).toEqual(["first:First draft", "second:Second draft"]);+ });++ test("preserves local content and enters conflict state on an external revision", async () => {+ const repository: AssetContentRepository = {+ readContent: async () => ({+ asset: descriptor(),+ data: (async function* () {+ yield new TextEncoder().encode("Initial");+ })(),+ }),+ updateContent: async () => {+ throw new AssetRevisionConflictError("Conflict");+ },+ };+ const session = createAssetContentSession({+ repository,+ authorize: async () => true,+ debounceMilliseconds: 0,+ });+ await session.open("asset");+ session.save("asset", "Local");+ await expect(session.flush("asset")).rejects.toThrow("Conflict");+ expect(session.get("asset")).toMatchObject({+ status: "conflicting",+ source: "Local",+ });+ });++ test("reload revalidates the exact revision before a confirmed operation", async () => {+ let current = descriptor();+ const session = createAssetContentSession({+ repository: {+ readContent: async () => ({+ asset: current,+ data: (async function* () {+ yield new TextEncoder().encode("Initial");+ })(),+ }),+ updateContent: async () => current,+ },+ authorize: () => true,+ });+ await session.open("asset");+ current = descriptor("article_v2.mdx");++ await expect(+ session.reload("asset", { expectedName: "article_v1.mdx" })+ ).rejects.toThrow(AssetRevisionConflictError);+ expect(session.get("asset")).toMatchObject({+ asset: { name: "article_v1.mdx" },+ source: "Initial",+ });+ });++ test("reload does not overwrite edits made while its read is in flight", async () => {+ let readCount = 0;+ let resolveReload!: (+ value: Awaited<ReturnType<AssetContentRepository["readContent"]>>+ ) => void;+ const session = createAssetContentSession({+ repository: {+ readContent: async () => {+ readCount += 1;+ if (readCount === 1) {+ return {+ asset: descriptor(),+ data: (async function* () {+ yield new TextEncoder().encode("Initial");+ })(),+ };+ }+ return new Promise((resolve) => {+ resolveReload = resolve;+ });+ },+ updateContent: async () => descriptor(),+ },+ authorize: () => true,+ schedule: () => Symbol(),+ cancelScheduled: () => {},+ });+ await session.open("asset");++ const reloading = session.reload("asset");+ await vi.waitFor(() => expect(readCount).toBe(2));+ session.save("asset", "Local");+ resolveReload({+ asset: { ...descriptor("article_v2.mdx"), size: 6 },+ data: (async function* () {+ yield new TextEncoder().encode("Remote");+ })(),+ });++ await expect(reloading).rejects.toThrow(+ "Asset content session has unsaved changes"+ );+ expect(session.get("asset")).toMatchObject({+ status: "pending",+ source: "Local",+ });+ });+});diff --git a/packages/content-engine/src/asset-content-session.ts b/packages/content-engine/src/asset-content-session.tsnew file mode 100644index 0000000000..fdda959dd4--- /dev/null+++ b/packages/content-engine/src/asset-content-session.ts@@ -0,0 +1,319 @@+import { decodeUtf8 } from "@webstudio-is/content-engine/compiler";+import { contentEngineLimits } from "@webstudio-is/content-engine/limits";+import {+ AssetRevisionConflictError,+ readAssetContentBytes,+ type AssetContentDescriptor,+ type AssetContentRepository,+} from "./asset-content-repository";++type AssetContentSessionStatus =+ | "saved"+ | "pending"+ | "saving"+ | "failed"+ | "conflicting";++export type AssetContentSessionState = Readonly<{+ asset: AssetContentDescriptor;+ source: string;+ status: AssetContentSessionStatus;+ error?: Error;+}>;++export type AssetContentSession = ReturnType<typeof createAssetContentSession>;++type Entry = {+ asset: AssetContentDescriptor;+ source: string;+ committedSource: string;+ status: AssetContentSessionStatus;+ error?: Error;+ timer?: unknown;+ flushPromise?: Promise<AssetContentSessionState>;+};++type Schedule = (callback: () => void, delayMilliseconds: number) => unknown;++export const createAssetContentSession = ({+ repository,+ authorize,+ schedule = (callback, delayMilliseconds) =>+ setTimeout(callback, delayMilliseconds),+ cancelScheduled = (handle) =>+ clearTimeout(handle as ReturnType<typeof setTimeout>),+ debounceMilliseconds = 300,+}: {+ repository: AssetContentRepository;+ authorize: (input: {+ assetId: string;+ operation: "read" | "write";+ }) => boolean | Promise<boolean>;+ schedule?: Schedule;+ cancelScheduled?: (handle: unknown) => void;+ debounceMilliseconds?: number;+}) => {+ const entries = new Map<string, Entry>();+ const openPromises = new Map<string, Promise<AssetContentSessionState>>();+ const listeners = new Set<+ (assetId: string, state: AssetContentSessionState) => void+ >();+ let disposed = false;++ const toState = (entry: Entry): AssetContentSessionState => ({+ asset: entry.asset,+ source: entry.source,+ status: entry.status,+ ...(entry.error === undefined ? {} : { error: entry.error }),+ });++ const publish = (assetId: string, entry: Entry) => {+ const state = toState(entry);+ for (const listener of listeners) {+ listener(assetId, state);+ }+ return state;+ };++ const requireEntry = (assetId: string) => {+ const entry = entries.get(assetId);+ if (entry === undefined) {+ throw new Error(`Asset content session "${assetId}" is not open`);+ }+ return entry;+ };++ const requireAuthorization = async (+ assetId: string,+ operation: "read" | "write"+ ) => {+ if ((await authorize({ assetId, operation })) !== true) {+ throw new Error(+ `Asset "${assetId}" is not authorized for content ${operation}`+ );+ }+ };++ const flush = async (assetId: string): Promise<AssetContentSessionState> => {+ if (disposed) {+ throw new Error("Asset content session is disposed");+ }+ const entry = requireEntry(assetId);+ if (entry.timer !== undefined) {+ cancelScheduled(entry.timer);+ entry.timer = undefined;+ }+ if (entry.flushPromise !== undefined) {+ return entry.flushPromise;+ }+ if (entry.status === "conflicting") {+ throw entry.error ?? new AssetRevisionConflictError("Conflict");+ }++ const promise = (async () => {+ while (entry.source !== entry.committedSource) {+ const source = entry.source;+ try {+ await requireAuthorization(assetId, "write");+ entry.status = "saving";+ entry.error = undefined;+ publish(assetId, entry);+ const asset = await repository.updateContent({+ assetId,+ expectedName: entry.asset.name,+ data: new Response(source).body!,+ });+ entry.asset = asset;+ entry.committedSource = source;+ entry.status =+ entry.source === entry.committedSource ? "saved" : "pending";+ publish(assetId, entry);+ } catch (error) {+ entry.error =+ error instanceof Error ? error : new Error("Unable to save Asset");+ entry.status =+ error instanceof AssetRevisionConflictError+ ? "conflicting"+ : "failed";+ publish(assetId, entry);+ throw entry.error;+ }+ }+ entry.status = "saved";+ entry.error = undefined;+ return publish(assetId, entry);+ })();+ entry.flushPromise = promise;+ try {+ return await promise;+ } finally {+ entry.flushPromise = undefined;+ }+ };++ const open = async (assetId: string) => {+ if (disposed) {+ throw new Error("Asset content session is disposed");+ }+ const existing = entries.get(assetId);+ if (existing !== undefined) {+ return toState(existing);+ }+ const pending = openPromises.get(assetId);+ if (pending !== undefined) {+ return pending;+ }+ const promise = (async () => {+ await requireAuthorization(assetId, "read");+ const { asset, bytes } = await readAssetContentBytes({+ repository,+ assetId,+ maxSize: contentEngineLimits.hydratedFileBytes,+ });+ if (disposed) {+ throw new Error("Asset content session is disposed");+ }+ const source = decodeUtf8(bytes);+ const entry: Entry = {+ asset,+ source,+ committedSource: source,+ status: "saved",+ };+ entries.set(assetId, entry);+ return publish(assetId, entry);+ })();+ openPromises.set(assetId, promise);+ try {+ return await promise;+ } finally {+ openPromises.delete(assetId);+ }+ };++ const reload = async (+ assetId: string,+ { expectedName }: { expectedName?: string } = {}+ ) => {+ if (disposed) {+ throw new Error("Asset content session is disposed");+ }+ const entry = requireEntry(assetId);+ if (+ entry.flushPromise !== undefined ||+ entry.source !== entry.committedSource+ ) {+ throw new Error("Asset content session has unsaved changes");+ }+ const assetBeforeReload = entry.asset;+ const sourceBeforeReload = entry.source;+ await requireAuthorization(assetId, "read");+ const { asset, bytes } = await readAssetContentBytes({+ repository,+ assetId,+ maxSize: contentEngineLimits.hydratedFileBytes,+ });+ if (+ entry.flushPromise !== undefined ||+ entry.source !== sourceBeforeReload ||+ entry.committedSource !== sourceBeforeReload+ ) {+ throw new Error("Asset content session has unsaved changes");+ }+ if (entry.asset !== assetBeforeReload) {+ throw new AssetRevisionConflictError(+ "Asset content session changed while it was reloading"+ );+ }+ if (expectedName !== undefined && asset.name !== expectedName) {+ throw new AssetRevisionConflictError(+ "This file changed since it was opened. Reload it before continuing."+ );+ }+ if (disposed) {+ throw new Error("Asset content session is disposed");+ }+ const source = decodeUtf8(bytes);+ entry.asset = asset;+ entry.source = source;+ entry.committedSource = source;+ entry.status = "saved";+ entry.error = undefined;+ return publish(assetId, entry);+ };++ const save = (assetId: string, source: string) => {+ if (disposed) {+ throw new Error("Asset content session is disposed");+ }+ const entry = requireEntry(assetId);+ if (entry.status === "conflicting") {+ throw entry.error ?? new AssetRevisionConflictError("Conflict");+ }+ entry.source = source;+ entry.status = entry.source === entry.committedSource ? "saved" : "pending";+ entry.error = undefined;+ publish(assetId, entry);+ if (entry.timer !== undefined) {+ cancelScheduled(entry.timer);+ }+ if (entry.status === "pending") {+ entry.timer = schedule(() => {+ entry.timer = undefined;+ void flush(assetId).catch(() => {});+ }, debounceMilliseconds);+ } else {+ entry.timer = undefined;+ }+ };++ const retry = async (assetId: string) => {+ const entry = requireEntry(assetId);+ if (entry.status === "conflicting") {+ throw entry.error ?? new AssetRevisionConflictError("Conflict");+ }+ entry.status = entry.source === entry.committedSource ? "saved" : "pending";+ entry.error = undefined;+ return flush(assetId);+ };++ const flushAll = async () => {+ const results = await Promise.allSettled(+ Array.from(entries.keys(), (assetId) => flush(assetId))+ );+ const failed = results.find(+ (result): result is PromiseRejectedResult => result.status === "rejected"+ );+ if (failed !== undefined) {+ throw failed.reason;+ }+ };++ return {+ open,+ reload,+ save,+ flush,+ flushAll,+ retry,+ get: (assetId: string) => {+ const entry = entries.get(assetId);+ return entry === undefined ? undefined : toState(entry);+ },+ subscribe: (+ listener: (assetId: string, state: AssetContentSessionState) => void+ ) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ dispose: () => {+ disposed = true;+ for (const entry of entries.values()) {+ if (entry.timer !== undefined) {+ cancelScheduled(entry.timer);+ }+ }+ listeners.clear();+ },+ };+};diff --git a/packages/content-engine/src/asset-index.ts b/packages/content-engine/src/asset-index.tsindex d8a3781fc3..7e00c4021a 100644--- a/packages/content-engine/src/asset-index.ts+++ b/packages/content-engine/src/asset-index.ts@@ -31,6 +31,7 @@ import {} from "./materialized-query";import {createDocumentGraphArtifact,+ getDocumentGraphClosure,getDocumentGraphQueryRootIds,type DocumentGraph,type DocumentGraphArtifactV1,@@ -54,6 +55,12 @@ export type ContentCompilerDiagnostics = {}>;largestDocuments: Array<{ id: string; path: string; bytes: number }>;affectedQueryIds: string[];+ assetReferenceIssues?: readonly {+ code: "ASSET_NOT_FOUND";+ sourceDocumentId: string;+ referenceId: string;+ assetUrl: string;+ }[];};const getDocumentBytes = (@@ -268,6 +275,7 @@ const buildAssetIndex = async ({assetReferences,assetValueReferences,documentGraph,+ documentContents,plan,finalize = true,}: {@@ -278,6 +286,7 @@ const buildAssetIndex = async ({assetReferences?: MarkdownAssetReferences;assetValueReferences?: AssetValueReferences;documentGraph?: DocumentGraphArtifactV1;+ documentContents?: Readonly<Record<string, string>>;plan?: ContentCompilationPlan;finalize?: boolean;}) => {@@ -346,8 +355,43 @@ const buildAssetIndex = async ({projectContentDatabaseDocument({ document, plan: runtimePlan })).sort((left, right) => compareStrings(left._id, right._id));- const contents = Object.fromEntries(- runtimeEntries+ const includedDocumentIds = new Set(entries.map(({ assetId }) => assetId));+ const graphNodeIds = new Set(documentGraph?.nodes.map(({ id }) => id) ?? []);+ const runtimeGraphRootIds = runtimeEntries+ .map(({ assetId }) => assetId)+ .filter((assetId) => graphNodeIds.has(assetId));+ const runtimeGraphNodes =+ documentGraph === undefined+ ? []+ : getDocumentGraphClosure({+ graph: documentGraph,+ rootIds: runtimeGraphRootIds,+ });+ for (const node of runtimeGraphNodes) {+ includedDocumentIds.add(node.id);+ }+ const embeddedGraphNodeIds = new Set(+ documentGraph === undefined+ ? []+ : getDocumentGraphClosure({+ graph: documentGraph,+ rootIds: runtimeEntries+ .filter(({ content }) => content !== undefined)+ .map(({ assetId }) => assetId)+ .filter((assetId) => graphNodeIds.has(assetId)),+ }).map(({ id }) => id)+ );+ const contents = Object.fromEntries([+ ...runtimeGraphNodes.flatMap((node) => {+ if (embeddedGraphNodeIds.has(node.id) === false) {+ return [];+ }+ const content = documentContents?.[node.contentRef];+ return content === undefined+ ? []+ : ([[node.contentRef, content]] as const);+ }),+ ...runtimeEntries.filter((entry): entry is ContentCompilerInput & { content: string } =>entry.content !== undefined@@ -355,17 +399,17 @@ const buildAssetIndex = async ({.sort((left, right) =>compareStrings(left.document.contentRef, right.document.contentRef))- .map((entry) => [entry.document.contentRef, entry.content])- );- const includedContentRefs = new Set(- runtimeEntries.map(({ document }) => document.contentRef)- );+ .map((entry) => [entry.document.contentRef, entry.content] as const),+ ]);+ const includedContentRefs = new Set([+ ...runtimeEntries.map(({ document }) => document.contentRef),+ ...Object.keys(contents),+ ]);const includedAssetReferences = Object.fromEntries(Object.entries(assetReferences ?? {}).filter(([contentRef]) =>includedContentRefs.has(contentRef)));- const includedDocumentIds = new Set(entries.map(({ assetId }) => assetId));const includedAssetValueReferences = Object.fromEntries(Object.entries(assetValueReferences ?? {}).filter(([documentId]) =>includedDocumentIds.has(documentId)@@ -443,6 +487,7 @@ export const compileContentArtifact = async ({assetReferences,assetValueReferences,documentGraph,+ documentContents,plan,}: {projectId: string;@@ -451,6 +496,7 @@ export const compileContentArtifact = async ({assetReferences?: MarkdownAssetReferences;assetValueReferences?: AssetValueReferences;documentGraph?: DocumentGraph;+ documentContents?: Readonly<Record<string, string>>;plan?: ContentCompilationPlan;}): Promise<{artifact: ContentArtifactV1;@@ -509,6 +555,7 @@ export const compileContentArtifact = async ({assetReferences,assetValueReferences,documentGraph: documentGraphArtifact,+ documentContents,plan,finalize: false,});@@ -537,6 +584,7 @@ export const compileContentArtifact = async ({assetReferences,assetValueReferences,documentGraph: documentGraphArtifact,+ documentContents,plan,finalize: false,});@@ -570,6 +618,7 @@ export const compileContentArtifact = async ({assetReferences,assetValueReferences,documentGraph: documentGraphArtifact,+ documentContents,plan,finalize: false,});@@ -604,6 +653,7 @@ export const compileContentArtifact = async ({assetReferences,assetValueReferences,documentGraph: documentGraphArtifact,+ documentContents,plan,});const boundedBytes = getUtf8ByteLength(serializeContentArtifact(artifact));@@ -656,6 +706,7 @@ export const createAssetIndex = async (input: {assetReferences?: MarkdownAssetReferences;assetValueReferences?: AssetValueReferences;documentGraph?: DocumentGraph;+ documentContents?: Readonly<Record<string, string>>;plan?: ContentCompilationPlan;}): Promise<ContentArtifactV1> =>(await compileContentArtifact(input)).artifact;diff --git a/packages/content-engine/src/asset-reference-utils.ts b/packages/content-engine/src/asset-reference-utils.tsnew file mode 100644index 0000000000..04d2380bca--- /dev/null+++ b/packages/content-engine/src/asset-reference-utils.ts@@ -0,0 +1,62 @@+import { createCanonicalAssetPath } from "./asset-path";+import {+ createAssetIdResolver,+ createUniqueAssetIdsByPath,+} from "./asset-path-resolution";++export type ResolvedAssetReference = {+ assetId: string;+ suffix?: string;+};++export const createNamedAssetReferenceContext = ({+ source,+ assets,+}: {+ source: { name: string; folderNames: readonly string[] };+ assets: Iterable<{+ id: string;+ name: string;+ folderNames: readonly string[];+ }>;+}) => ({+ sourcePath: createCanonicalAssetPath(source),+ assetIdsByPath: createUniqueAssetIdsByPath(+ Array.from(assets, (asset) => ({+ id: asset.id,+ path: createCanonicalAssetPath(asset),+ }))+ ),+});++const getAssetReferenceSuffix = (value: string) => {+ let parsed: URL;+ try {+ parsed = new URL(value, "https://content.webstudio.invalid/");+ } catch {+ return;+ }+ const suffix = `${parsed.search}${parsed.hash}`;+ return suffix === "" ? undefined : suffix;+};++export const createAssetReferenceResolver = ({+ sourcePath,+ assetIdsByPath,+}: {+ sourcePath: string;+ assetIdsByPath: ReadonlyMap<string, string>;+}) => {+ const resolveAssetId = createAssetIdResolver(assetIdsByPath, sourcePath);+ return (value: string): ResolvedAssetReference | undefined => {+ const assetId = resolveAssetId(value);+ if (assetId === undefined) {+ return;+ }+ const suffix = getAssetReferenceSuffix(value);+ return {+ assetId,+ ...(suffix === undefined ? {} : { suffix }),+ };+ };+};diff --git a/packages/content-engine/src/asset-value-references.test.ts b/packages/content-engine/src/asset-value-references.test.tsindex f9a067ac6e..de2bb1ba0a 100644--- a/packages/content-engine/src/asset-value-references.test.ts+++ b/packages/content-engine/src/asset-value-references.test.ts@@ -3,6 +3,7 @@ import {discoverAssetValueReferences,mergeAssetUrlSuffix,resolveAssetValueReferences,+ rewriteAssetValueReferences,} from "./asset-value-references";describe("structured asset value references", () => {@@ -147,6 +148,9 @@ describe("structured asset value references", () => {"?download=1#section")).toBe("https://cdn.example.com/guide.pdf?format=raw&download=1#section");+ expect(mergeAssetUrlSuffix("assets/hero.png", "?width=1200#cover")).toBe(+ "assets/hero.png?width=1200#cover"+ );});test("resolves an explicit asset marker to structured metadata", () => {@@ -203,4 +207,21 @@ describe("structured asset value references", () => {},});});++ test("rewrites an authored asset marker without materializing it", () => {+ expect(+ rewriteAssetValueReferences({+ value: { author: { $ref: "../authors/oleg.md#frontmatter" } },+ references: [+ {+ path: ["author"],+ assetId: "author",+ suffix: "#frontmatter",+ structured: true,+ },+ ],+ assetUrls: { author: "oleg_1.md" },+ })+ ).toEqual({ author: { $ref: "oleg_1.md#frontmatter" } });+ });});diff --git a/packages/content-engine/src/asset-value-references.ts b/packages/content-engine/src/asset-value-references.tsindex 06f5dd04c5..046383866c 100644--- a/packages/content-engine/src/asset-value-references.ts+++ b/packages/content-engine/src/asset-value-references.ts@@ -1,11 +1,12 @@import { getJsonReferenceMarkerValue } from "./document-graph/document-utils";import type { JsonValue } from "./canonical-json";-import { createAssetIdResolver } from "./asset-path-resolution";+import {+ createAssetReferenceResolver,+ type ResolvedAssetReference,+} from "./asset-reference-utils";-export type AssetValueReference = {+export type AssetValueReference = ResolvedAssetReference & {path: Array<string | number>;- assetId: string;- suffix?: string;structured?: true;};@@ -26,52 +27,42 @@ export const getRuntimeAssetUrls = (Object.entries(runtimeAssets ?? {}).map(([id, asset]) => [id, asset.url]));-const getUrlSuffix = (value: string) => {- let parsed: URL;- try {- parsed = new URL(value, "https://content.webstudio.invalid/");- } catch {- return;- }- const suffix = `${parsed.search}${parsed.hash}`;- return suffix === "" ? undefined : suffix;-};-export const discoverAssetValueReferences = ({properties,sourcePath,assetIdsByPath,structuredAssetIds,+ rootPath = ["properties"],}: {- properties: Readonly<Record<string, unknown>>;+ properties: unknown;sourcePath: string;assetIdsByPath: ReadonlyMap<string, string>;structuredAssetIds?: ReadonlySet<string>;+ rootPath?: Array<string | number>;}): AssetValueReference[] => {- const resolveAssetId = createAssetIdResolver(assetIdsByPath, sourcePath);+ const resolveAssetReference = createAssetReferenceResolver({+ sourcePath,+ assetIdsByPath,+ });const references: AssetValueReference[] = [];const visit = (value: unknown, path: Array<string | number>) => {if (typeof value === "string") {- const assetId = resolveAssetId(value);- if (assetId !== undefined) {- const suffix = getUrlSuffix(value);- references.push({- path,- assetId,- ...(suffix === undefined ? {} : { suffix }),- });+ const reference = resolveAssetReference(value);+ if (reference !== undefined) {+ references.push({ path, ...reference });}return;}const marker = getJsonReferenceMarkerValue(value as JsonValue);if (typeof marker === "string") {- const assetId = resolveAssetId(marker);- if (assetId !== undefined && structuredAssetIds?.has(assetId)) {- const suffix = getUrlSuffix(marker);+ const reference = resolveAssetReference(marker);+ if (+ reference !== undefined &&+ structuredAssetIds?.has(reference.assetId)+ ) {references.push({path,- assetId,- ...(suffix === undefined ? {} : { suffix }),+ ...reference,structured: true,});}@@ -90,17 +81,17 @@ export const discoverAssetValueReferences = ({visit(item, [...path, key]);}};- visit(properties, ["properties"]);+ visit(properties, rootPath);return references;};export const mergeAssetUrlSuffix = (url: string, suffix?: string) => {- if (suffix === undefined) {+ if (suffix === undefined || suffix.length === 0) {return url;}- const base = "https://content.webstudio.invalid";- const canonical = new URL(url, `${base}/`);- const authored = new URL(suffix, `${base}/`);+ const base = new URL("https://content.webstudio.invalid/__assets__/");+ const canonical = new URL(url, base);+ const authored = new URL(suffix, base);for (const [key, value] of authored.searchParams) {canonical.searchParams.append(key, value);}@@ -113,7 +104,20 @@ export const mergeAssetUrlSuffix = (url: string, suffix?: string) => {if (url.startsWith("/")) {return `${canonical.pathname}${canonical.search}${canonical.hash}`;}- return canonical.href;+ let isAbsoluteUrl = false;+ try {+ new URL(url);+ isAbsoluteUrl = true;+ } catch {+ // Relative Asset paths are handled below.+ }+ if (isAbsoluteUrl) {+ return canonical.href;+ }+ const pathname = canonical.pathname.startsWith(base.pathname)+ ? canonical.pathname.slice(base.pathname.length)+ : canonical.pathname;+ return `${pathname}${canonical.search}${canonical.hash}`;};const replaceValueAtPath = ({@@ -208,3 +212,29 @@ export const resolveAssetValueReferences = <Value>({}return resolved as Value;};++/** Rewrites authored Asset paths while preserving structured `$ref` markers. */+export const rewriteAssetValueReferences = <Value>({+ value,+ references,+ assetUrls,+}: {+ value: Value;+ references: readonly AssetValueReference[] | undefined;+ assetUrls: Readonly<Record<string, string>>;+}): Value => {+ let rewritten: unknown = value;+ for (const reference of references ?? []) {+ const assetUrl = assetUrls[reference.assetId];+ if (assetUrl === undefined) {+ continue;+ }+ const url = mergeAssetUrlSuffix(assetUrl, reference.suffix);+ rewritten = replaceValueAtPath({+ value: rewritten,+ path: reference.path,+ replacement: reference.structured === true ? { $ref: url } : url,+ });+ }+ return rewritten as Value;+};diff --git a/packages/content-engine/src/byte-stream.ts b/packages/content-engine/src/byte-stream.tsindex e44ea0d655..dd255926a9 100644--- a/packages/content-engine/src/byte-stream.ts+++ b/packages/content-engine/src/byte-stream.ts@@ -42,6 +42,34 @@ export const toByteChunks = (source: ByteSource): AsyncIterable<Uint8Array> => {return source;};+export const readableStreamToAsyncIterable = (+ stream: ReadableStream<Uint8Array>+): AsyncIterable<Uint8Array> => ({+ async *[Symbol.asyncIterator]() {+ const reader = stream.getReader();+ let completed = false;+ try {+ for (;;) {+ const result = await reader.read();+ if (result.done) {+ completed = true;+ return;+ }+ yield result.value;+ }+ } finally {+ if (completed === false) {+ try {+ await reader.cancel();+ } catch {+ // Preserve the consumer error that stopped the stream.+ }+ }+ reader.releaseLock();+ }+ },+});+export const readBytePrefix = async (source: ByteSource,maximumBytes: numberdiff --git a/packages/content-engine/src/canonical.ts b/packages/content-engine/src/canonical.tsindex e807d42e6e..4178dc1ded 100644--- a/packages/content-engine/src/canonical.ts+++ b/packages/content-engine/src/canonical.ts@@ -40,11 +40,11 @@ export type CanonicalAssetMetadataRequirements = {};/**- * Generation of the Markdown/JSON extraction behavior used by persistent+ * Generation of the Markdown/MDX/JSON extraction behavior used by persistent* metadata caches. Increment only when unchanged source files must be parsed* again because extraction semantics changed.*/-export const canonicalAssetMetadataExtractorGeneration = 1;+export const canonicalAssetMetadataExtractorGeneration = 2;export const fullCanonicalAssetMetadataRequirements = {structuredProperties: true,diff --git a/packages/content-engine/src/compiler.ts b/packages/content-engine/src/compiler.tsindex fbab8fd608..457ac1aa89 100644--- a/packages/content-engine/src/compiler.ts+++ b/packages/content-engine/src/compiler.ts@@ -8,5 +8,10 @@ export * from "./content-source";export * from "./document-metadata";export * from "./asset-value-references";export { serializeJsonDeterministically } from "./canonical-json";-export { decodeUtf8, readBoundedBytes, readBytePrefix } from "./byte-stream";+export {+ decodeUtf8,+ readableStreamToAsyncIterable,+ readBoundedBytes,+ readBytePrefix,+} from "./byte-stream";export { mapBounded } from "./async-utils";diff --git a/packages/content-engine/src/content-database.ts b/packages/content-engine/src/content-database.tsindex b0df83f18b..f0875ec99f 100644--- a/packages/content-engine/src/content-database.ts+++ b/packages/content-engine/src/content-database.ts@@ -29,6 +29,7 @@ import {getAdaptedDocumentProperties,isDocumentGraphFieldAffected,getDocumentGraphQueryRootIds,+ resolveAdaptedDocumentAssetReferences,selectDocumentGraphForQuery,type AdaptedDocument,type DocumentResolutionSession,@@ -438,6 +439,12 @@ const createQueryableContentDatabase = ({rootIds,onEvent,allowUnresolvedReferences: true,+ transformDocument: ({ node, document }) =>+ resolveAdaptedDocumentAssetReferences({+ document,+ references: artifact.assetValueReferences?.[node.id],+ runtimeAssets,+ }),});const documents = replaceResolvedRootProperties({rootIds,diff --git a/packages/content-engine/src/content-source.test.ts b/packages/content-engine/src/content-source.test.tsindex 0599c76f73..aad4747fe4 100644--- a/packages/content-engine/src/content-source.test.ts+++ b/packages/content-engine/src/content-source.test.ts@@ -1,5 +1,7 @@import { describe, expect, test } from "vitest";import { createCanonicalAssetFileEntry } from "./canonical";+import { getContentArtifactReferencedAssetIds } from "./content-artifact";+import { createContentDatabase } from "./content-database";import {compileContentSource,ContentSourceChangedError,@@ -119,6 +121,360 @@ const createDocumentSource = ({});describe("content source snapshots", () => {+ test("compiles MDX sources into the document graph", async () => {+ const mdx =+ '---\nauthor:\n $ref: ./author.json#/profile\n---\n<ws.element ws:name="Hero">Hello</ws.element>\n';+ const post = createFile({+ id: "post",+ path: "blog/post.mdx",+ contentType: "text/mdx",+ contentRef: "revisions/post.mdx",+ size: new TextEncoder().encode(mdx).byteLength,+ });+ const author = createFile({+ id: "author",+ path: "blog/author.json",+ contentType: "application/json",+ });+ const source = createDocumentSource({+ files: [post, author],+ sources: {+ post: mdx,+ author: '{"profile":{"name":"Ada"}}',+ },+ });++ 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, format }) => [id, format])+ ).toEqual([+ ["author", "json"],+ ["post", "mdx"],+ ]);+ expect(result.documentGraph?.edges).toEqual([+ expect.objectContaining({+ sourceId: "post",+ referenceId: "#frontmatter/author",+ }),+ ]);+ });++ test("resolves Asset values from referenced document frontmatter", async () => {+ const post = createFile({+ id: "post",+ path: "blog/post.mdx",+ contentType: "text/mdx",+ });+ const author = createFile({+ id: "author",+ path: "blog/author.md",+ });+ const avatar = createFile({+ id: "avatar",+ path: "blog/avatar.png",+ contentType: "image/png",+ });+ const sources = {+ post: "---\nauthor:\n $ref: ./author.md#frontmatter\n---\nPost\n",+ author: "---\nname: Ada\nprofileImage:\n $ref: ./avatar.png\n---\n",+ };+ const source: ContentSource = {+ async openSnapshot() {+ return {+ revision: "snapshot",+ files: [post, author, avatar],+ async loadEntries() {+ const entry = createEntry(post);+ return [+ {+ ...entry,+ document: {+ ...entry.document,+ properties: {+ author: { $ref: "./author.md#frontmatter" },+ },+ },+ content: sources.post,+ } as typeof entry,+ ];+ },+ async loadDocumentSources() {+ return [+ { id: "post", source: sources.post },+ { id: "author", source: sources.author },+ ];+ },+ async isCurrent() {+ return true;+ },+ };+ },+ };+ const query = {+ where: { all: [] },+ sort: [],+ limit: 1,+ output: {+ mode: "fields" as const,+ includeMetadata: false,+ fields: [["properties", "author"]],+ },+ content: { mode: "full" as const },+ };+ const compiled = await compileContentSource({+ source,+ projectId,+ plan: {+ standardFields: [],+ structuredPropertyPaths: [["properties", "author"]],+ excerpt: false,+ metadataError: false,+ queries: [+ {+ id: "post",+ ...query,+ limit: { type: "literal", value: 1 },+ offset: { type: "literal", value: 0 },+ },+ ],+ },+ });++ expect(compiled.artifact.assetValueReferences?.author).toEqual([+ {+ path: ["properties", "profileImage"],+ assetId: "avatar",+ structured: true,+ },+ ]);+ expect(compiled.artifact.contents?.[author.contentRef]).toBe(+ sources.author+ );+ const database = createContentDatabase({ artifact: compiled.artifact });+ await expect(+ database.queryWithDocumentGraph({+ request: { query },+ load: async (node) => ({+ format: node.format as "markdown" | "mdx",+ revision: node.revision,+ source: sources[node.id as keyof typeof sources],+ }),+ runtimeAssets: {+ avatar: { url: "/cgi/image/avatar.png?format=raw" },+ },+ })+ ).resolves.toMatchObject({+ items: [+ {+ properties: {+ author: {+ name: "Ada",+ profileImage: {+ id: "avatar",+ src: "/cgi/image/avatar.png?format=raw",+ },+ },+ },+ },+ ],+ });+ });++ test("keeps missing nested Asset refs out of the document graph", async () => {+ const post = createFile({+ id: "post",+ path: "blog/post.mdx",+ contentType: "text/mdx",+ });+ const author = createFile({+ id: "author",+ path: "authors/author.md",+ });+ const avatar = createFile({+ id: "avatar",+ path: "authors/avatar.png",+ contentType: "image/png",+ });+ const sources = {+ post: "---\nauthor:\n $ref: ../authors/author.md#frontmatter\n---\nPost\n",+ author:+ "---\nprofileImage: ./avatar.png\ngallery:\n - $ref: ./avatar.png\n - $ref: ./missing.png\n---\n",+ };+ const source: ContentSource = {+ async openSnapshot() {+ return {+ revision: "snapshot",+ files: [post, author, avatar],+ async loadEntries() {+ const entry = createEntry(post);+ return [+ {+ ...entry,+ document: {+ ...entry.document,+ properties: {+ author: { $ref: "../authors/author.md#frontmatter" },+ },+ },+ content: sources.post,+ } as typeof entry,+ ];+ },+ async loadDocumentSources() {+ return [+ { id: "post", source: sources.post },+ { id: "author", source: sources.author },+ ];+ },+ async isCurrent() {+ return true;+ },+ };+ },+ };+ const query = {+ where: { all: [] },+ sort: [],+ limit: 1,+ output: {+ mode: "fields" as const,+ includeMetadata: false,+ fields: [["properties", "author"]],+ },+ content: { mode: "none" as const },+ };++ const compiled = await compileContentSource({+ source,+ projectId,+ plan: {+ standardFields: [],+ structuredPropertyPaths: [["properties", "author"]],+ excerpt: false,+ metadataError: false,+ queries: [+ {+ id: "post",+ ...query,+ limit: { type: "literal", value: 1 },+ offset: { type: "literal", value: 0 },+ },+ ],+ },+ });+ const database = createContentDatabase({ artifact: compiled.artifact });++ await expect(+ database.queryWithDocumentGraph({+ request: { query },+ load: async (node) => ({+ format: node.format as "markdown" | "mdx",+ revision: node.revision,+ source: sources[node.id as keyof typeof sources],+ }),+ runtimeAssets: {+ avatar: { url: "/cgi/image/avatar.png?format=raw" },+ },+ })+ ).resolves.toMatchObject({+ items: [+ {+ properties: {+ author: {+ profileImage: "/cgi/image/avatar.png?format=raw",+ gallery: [+ {+ id: "avatar",+ src: "/cgi/image/avatar.png?format=raw",+ },+ { $ref: "./missing.png" },+ ],+ },+ },+ },+ ],+ });+ expect(compiled.diagnostics.assetReferenceIssues).toEqual([+ {+ code: "ASSET_NOT_FOUND",+ sourceDocumentId: "author",+ referenceId: "#frontmatter/gallery/1",+ assetUrl: "https://content.webstudio.local/authors/missing.png",+ },+ ]);+ });++ test("reports a missing Asset ref when the root has no document edges", async () => {+ const post = createFile({ id: "post", path: "blog/post.mdx" });+ const source = createDocumentSource({+ files: [post],+ sources: {+ post: "---\ncover:\n $ref: ./missing.png\n---\nPost\n",+ },+ });++ const compiled = await compileContentSource({+ source,+ projectId,+ plan: {+ standardFields: [],+ structuredPropertyPaths: [["properties", "cover"]],+ excerpt: false,+ metadataError: false,+ queries: [+ {+ id: "post",+ where: { all: [] },+ sort: [],+ limit: { type: "literal", value: 1 },+ offset: { type: "literal", value: 0 },+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["properties", "cover"]],+ },+ content: { mode: "none" },+ },+ ],+ },+ });++ expect(compiled.documentGraph).toBeUndefined();+ expect(compiled.diagnostics.assetReferenceIssues).toEqual([+ {+ code: "ASSET_NOT_FOUND",+ sourceDocumentId: "post",+ referenceId: "#frontmatter/cover",+ assetUrl: "https://content.webstudio.local/blog/missing.png",+ },+ ]);+ });+test("analyzes only query roots and their reachable document targets", async () => {const post = createFile({ id: "post", path: "blog/post.md" });const author = createFile({@@ -586,6 +942,129 @@ describe("content source snapshots", () => {});});+ test("exposes MDX frontmatter and authored Asset references", async () => {+ const mdx = createFile({+ id: "post",+ path: "blog/post.mdx",+ contentType: "text/mdx",+ contentRef: "revisions/post.mdx",+ });+ const cover = createFile({+ id: "cover",+ path: "blog/cover.png",+ contentType: "image/png",+ });+ const hero = createFile({+ id: "hero",+ path: "blog/hero.png",+ contentType: "image/png",+ });+ const video = createFile({+ id: "video",+ path: "blog/video.jpg",+ contentType: "image/jpeg",+ });+ const content = `---+cover: ./cover.png+---+++<ws.element ws:name="Card" poster="./video.jpg" />+`;+ const source: ContentSource = {+ async openSnapshot() {+ return {+ revision: "snapshot",+ files: [mdx, cover, hero, video],+ async loadEntries() {+ const entry = createEntry(mdx);+ return [+ {+ ...entry,+ document: {+ ...entry.document,+ properties: { cover: "./cover.png" },+ },+ content,+ } as typeof entry & { content: string },+ ];+ },+ async isCurrent() {+ return true;+ },+ };+ },+ };++ const result = await compileContentSource({ source, projectId });++ expect(result.artifact.documents[0]?.properties).toEqual({+ cover: "./cover.png",+ });+ expect(result.artifact.assetValueReferences).toEqual({+ post: [+ {+ path: ["properties", "cover"],+ assetId: "cover",+ },+ {+ path: ["children", 0, "children", 0, "props", 0, "value"],+ assetId: "hero",+ suffix: "#crop",+ },+ {+ path: ["children", 1, "props", 0, "value"],+ assetId: "video",+ },+ ],+ });+ expect(getContentArtifactReferencedAssetIds(result.artifact)).toEqual([+ "cover",+ "hero",+ "video",+ ]);+ });++ test("retains MDX body Asset references without frontmatter references", async () => {+ const mdx = createFile({+ id: "post",+ path: "blog/post.mdx",+ contentType: "text/mdx",+ });+ const hero = createFile({+ id: "hero",+ path: "blog/hero.png",+ contentType: "image/png",+ });+ const source: ContentSource = {+ async openSnapshot() {+ return {+ revision: "snapshot",+ files: [mdx, hero],+ async loadEntries() {+ const entry = createEntry(mdx);+ return [+ {+ ...entry,+ document: { ...entry.document, properties: {} },+ content: "",+ } as typeof entry & { content: string },+ ];+ },+ async isCurrent() {+ return true;+ },+ };+ },+ };++ const result = await compileContentSource({ source, projectId });++ expect(+ result.artifact.assetValueReferences?.post?.map(({ assetId }) => assetId)+ ).toEqual(["hero"]);+ });+test("resolves the same relative URL independently for each Markdown folder", async () => {const firstPost = createFile({id: "first-post",@@ -718,77 +1197,95 @@ 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;- },- };- },- };+ test.each([+ {+ label: "Markdown",+ extension: "md",+ contentType: "text/markdown",+ format: "markdown",+ },+ {+ label: "MDX",+ extension: "mdx",+ contentType: "text/mdx",+ format: "mdx",+ },+ ] as const)(+ "keeps $label body content in storage for graph-backed queries",+ async ({ extension, contentType, format }) => {+ const markdown = "---\ntitle: Post\nslug: post\n---\nStored body\n";+ const post = createFile({+ id: "post",+ path: `blog/post.${extension}`,+ contentType,+ contentRef: `revisions/post.${extension}`,+ 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: [+ 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-ref" },+ },+ ],+ },+ });++ expect(result.artifact.contents).toBeUndefined();+ expect(result.artifact.documentGraph).toMatchObject({+ nodes: [{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-ref" },+ contentRef: `revisions/post.${extension}`,+ format,},],- },- });-- expect(result.artifact.contents).toBeUndefined();- expect(result.artifact.documentGraph).toMatchObject({- nodes: [- {- id: "post",- contentRef: "revisions/post.md",- format: "markdown",- },- ],- edges: [],- });- });+ edges: [],+ });+ }+ );test("does not resolve an ambiguous Asset path", async () => {const post = createFile({ id: "post", path: "blog/post.md" });diff --git a/packages/content-engine/src/content-source.ts b/packages/content-engine/src/content-source.tsindex b85d057e6b..b8a9b3ff76 100644--- a/packages/content-engine/src/content-source.ts+++ b/packages/content-engine/src/content-source.ts@@ -18,12 +18,20 @@ import {type AssetValueReferences,} from "./asset-value-references";import { compareStrings } from "./canonical-json";-import { encodeUtf8, type ByteSource } from "./byte-stream";+import {+ decodeUtf8,+ encodeUtf8,+ readBoundedBytes,+ type ByteSource,+} from "./byte-stream";import { extractMarkdownBody } from "./markdown-body";import { contentEngineLimits } from "./limits";+import { discoverMdxBodyAssetReferences, parseMdxDocument } from "./mdx";import {compileDocumentSourceGraph,+ createDocumentSourceUrl,getDocumentFormatByContentType,+ type SourceReferenceOccurrence,type DocumentGraph,} from "./document-graph";@@ -218,13 +226,15 @@ const discoverSnapshotAssetReferences = async ({return references;};-const discoverSnapshotAssetValueReferences = ({+const discoverSnapshotAssetValueReferences = async ({snapshot,entries,+ analyzedProperties,}: {snapshot: ContentSourceSnapshot;entries: readonly ContentCompilerInput[];-}): AssetValueReferences => {+ analyzedProperties: ReadonlyMap<string, Readonly<Record<string, unknown>>>;+}): Promise<AssetValueReferences> => {const assetIdsByPath = createUniqueAssetIdsByPath(snapshot.files);const structuredAssetIds = new Set(snapshot.files@@ -232,28 +242,64 @@ const discoverSnapshotAssetValueReferences = ({.map(({ id }) => id));const references: AssetValueReferences = {};+ const discoverProperties = ({+ path,+ properties,+ }: {+ path: string;+ properties: Readonly<Record<string, unknown>>;+ }) => {+ return discoverAssetValueReferences({+ properties,+ sourcePath: path,+ assetIdsByPath,+ structuredAssetIds,+ });+ };for (const entry of [...entries].sort((left, right) =>compareStrings(left.assetId, right.assetId))) {- const discovered = discoverAssetValueReferences({+ const discovered = discoverProperties({+ path: entry.document.path,properties: entry.document.properties ?? {},- sourcePath: entry.document.path,- assetIdsByPath,- structuredAssetIds,});+ if (+ entry.content !== undefined &&+ getDocumentFormatByContentType(entry.document.mimeType) === "mdx"+ ) {+ const document = await parseMdxDocument({ source: entry.content });+ discovered.push(+ ...discoverMdxBodyAssetReferences({+ document,+ sourcePath: entry.document.path,+ assetIdsByPath,+ })+ );+ }if (discovered.length > 0) {references[entry.assetId] = discovered;}}+ const entryIds = new Set(entries.map(({ assetId }) => assetId));+ const filesById = new Map(snapshot.files.map((file) => [file.id, file]));+ for (const [id, properties] of analyzedProperties) {+ if (entryIds.has(id)) {+ continue;+ }+ const file = filesById.get(id);+ if (file !== undefined) {+ const discovered = discoverProperties({+ path: file.path,+ properties,+ });+ if (discovered.length > 0) {+ references[id] = discovered;+ }+ }+ }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]) => {@@ -275,11 +321,49 @@ const planReferencesMarkdownBodies = (plan?: ContentCompilationPlan) =>plan?.queries.some(({ content }) => content.mode === "markdown-body-ref") ===true;+type AssetReferenceIssue = NonNullable<+ ContentCompilerDiagnostics["assetReferenceIssues"]+>[number];++const documentPathExtensions = new Set(["json", "md", "markdown", "mdx"]);++const isMissingLocalAssetReference = ({+ occurrence,+ documentUrls,+}: {+ occurrence: SourceReferenceOccurrence;+ documentUrls: ReadonlySet<string>;+}) => {+ const url = new URL(occurrence.reference.documentUrl);+ if (+ url.origin !== new URL(createDocumentSourceUrl("")).origin ||+ documentUrls.has(url.href)+ ) {+ return false;+ }+ const filename = url.pathname.slice(url.pathname.lastIndexOf("/") + 1);+ const dotIndex = filename.lastIndexOf(".");+ if (dotIndex === -1 || dotIndex === filename.length - 1) {+ return false;+ }+ return documentPathExtensions.has(filename.slice(dotIndex + 1).toLowerCase())+ ? false+ : true;+};+const discoverSnapshotDocumentGraph = async (snapshot: ContentSourceSnapshot,entries: readonly ContentCompilerInput[],+ analyzedProperties: Map<string, Readonly<Record<string, unknown>>>,plan?: ContentCompilationPlan-): Promise<DocumentGraph | undefined> => {+): Promise<+ | Readonly<{+ graph?: DocumentGraph;+ contents?: Readonly<Record<string, string>>;+ assetReferenceIssues: readonly AssetReferenceIssue[];+ }>+ | undefined+> => {if (snapshot.loadDocumentSources === undefined ||(plan !== undefined && plan.queries.some(queryNeedsDocumentGraph) === false)@@ -302,11 +386,28 @@ const discoverSnapshotDocumentGraph = async (}sourcesById.set(document.id, document.source);}+ const bytesById = new Map<string, Promise<Uint8Array>>();+ const getBytes = (id: string) => {+ let bytes = bytesById.get(id);+ if (bytes === undefined) {+ const source = sourcesById.get(id);+ if (source === undefined) {+ throw new Error("Content source document catalog is incomplete");+ }+ bytes = readBoundedBytes(source, contentEngineLimits.hydratedFileBytes);+ bytesById.set(id, bytes);+ }+ return bytes;+ };const supportedFiles = snapshot.files.filter(isDocumentFile);+ const documentUrls = new Set(+ supportedFiles.map((file) => createDocumentSourceUrl(file.path))+ );+ const assetReferenceIssues: AssetReferenceIssue[] = [];const ignoredReferenceUrls = new Set(snapshot.files.filter((file) => isDocumentFile(file) === false)- .map((file) => getDocumentUrl(file.path))+ .map((file) => createDocumentSourceUrl(file.path)));if (supportedFiles.some((file) => sourcesById.has(file.id) === false)) {throw new Error("Content source omitted a supported document source");@@ -320,14 +421,35 @@ const discoverSnapshotDocumentGraph = async (}return {id: file.id,- documentUrl: getDocumentUrl(file.path),+ documentUrl: createDocumentSourceUrl(file.path),revision: file.revision,contentRef: file.contentRef,format,- source,+ source: {+ async *[Symbol.asyncIterator]() {+ yield await getBytes(file.id);+ },+ },};}),ignoredReferenceUrls,+ ignoreReference: (occurrence) => {+ if (+ isMissingLocalAssetReference({ occurrence, documentUrls }) === false+ ) {+ return false;+ }+ assetReferenceIssues.push({+ code: "ASSET_NOT_FOUND",+ sourceDocumentId: occurrence.sourceDocumentId,+ referenceId: occurrence.referenceId,+ assetUrl: occurrence.reference.documentUrl,+ });+ return true;+ },+ onDocumentProperties: ({ id, properties }) => {+ analyzedProperties.set(id, properties);+ },...(plan === undefined? {}: {@@ -336,10 +458,23 @@ const discoverSnapshotDocumentGraph = async (),}),});- return graph.edges.length === 0 &&+ if (+ graph.edges.length === 0 &&planReferencesMarkdownBodies(plan) === false- ? undefined- : graph;+ ) {+ return assetReferenceIssues.length === 0+ ? undefined+ : { assetReferenceIssues };+ }+ const contents = Object.fromEntries(+ await Promise.all(+ graph.nodes.map(async (node) => [+ node.contentRef,+ decodeUtf8(await getBytes(node.id)),+ ])+ )+ );+ return { graph, contents, assetReferenceIssues };};export const materializeContentSnapshot = async ({@@ -359,12 +494,23 @@ export const materializeContentSnapshot = async ({try {const entries = await snapshot.loadEntries(plan, { maximumContentBytes });validateEntries({ snapshot, entries });- const documentGraph = await measureContentSourcePerformance({+ const analyzedProperties = new Map<+ string,+ Readonly<Record<string, unknown>>+ >();+ const documentGraphResult = await measureContentSourcePerformance({phase: "document-graph",observer: onPerformanceEvent,now: performanceNow,- operation: () => discoverSnapshotDocumentGraph(snapshot, entries, plan),+ operation: () =>+ discoverSnapshotDocumentGraph(+ snapshot,+ entries,+ analyzedProperties,+ plan+ ),});+ const documentGraph = documentGraphResult?.graph;const assetReferences = await measureContentSourcePerformance({phase: "asset-references",observer: onPerformanceEvent,@@ -372,9 +518,10 @@ export const materializeContentSnapshot = async ({operation: () =>discoverSnapshotAssetReferences({ snapshot, entries, plan }),});- const assetValueReferences = discoverSnapshotAssetValueReferences({+ const assetValueReferences = await discoverSnapshotAssetValueReferences({snapshot,entries,+ analyzedProperties,});if (await measureContentSourcePerformance({@@ -390,6 +537,8 @@ export const materializeContentSnapshot = async ({assetReferences,assetValueReferences,documentGraph,+ documentContents: documentGraphResult?.contents,+ assetReferenceIssues: documentGraphResult?.assetReferenceIssues ?? [],};}} catch (error) {@@ -433,6 +582,8 @@ export const compileContentSource = async ({assetReferences,assetValueReferences,documentGraph,+ documentContents,+ assetReferenceIssues,} = await materializeContentSource({source,plan,@@ -446,10 +597,19 @@ export const compileContentSource = async ({assetReferences,assetValueReferences,documentGraph,+ documentContents,...(plan === undefined ? {} : { plan }),...(maxBytes === undefined ? {} : { maxBytes }),});- return { sourceRevision, documentGraph, ...compiled };+ return {+ sourceRevision,+ documentGraph,+ ...compiled,+ diagnostics: {+ ...compiled.diagnostics,+ ...(assetReferenceIssues.length === 0 ? {} : { assetReferenceIssues }),+ },+ };};export const materializeContentSource = async ({@@ -470,6 +630,8 @@ export const materializeContentSource = async ({assetReferences: MarkdownAssetReferences;assetValueReferences: AssetValueReferences;documentGraph?: DocumentGraph;+ documentContents?: Readonly<Record<string, string>>;+ assetReferenceIssues: readonly AssetReferenceIssue[];}> => {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.tsindex 9ce5095a8a..e16f40e9a2 100644--- a/packages/content-engine/src/document-graph/cached-document-loader.test.ts+++ b/packages/content-engine/src/document-graph/cached-document-loader.test.ts@@ -87,6 +87,38 @@ describe("cached document source loader", () => {});});+ test("reuses cached MDX sources", async () => {+ const cached: CachedDocumentSource = {+ format: "mdx",+ revision: "post-r1",+ bytes: new TextEncoder().encode("# Cached"),+ };+ const load = vi.fn(async () => {+ throw new Error("source loader must not run");+ });+ const result = await createCachedDocumentSourceLoader({+ cache: {+ get: async () => cached,+ set: async () => undefined,+ },+ load,+ })(+ {+ id: "post",+ revision: "post-r1",+ contentRef: "content:post",+ format: "mdx",+ },+ {}+ );++ expect(result.format).toBe("mdx");+ expect(load).not.toHaveBeenCalled();+ await expect(parseDocumentSource(result)).resolves.toMatchObject({+ format: "mdx",+ });+ });+test("does not reuse a cached source with a different format", async () => {const load = vi.fn(async () => ({format: "json" as const,diff --git a/packages/content-engine/src/document-graph/cached-document-loader.ts b/packages/content-engine/src/document-graph/cached-document-loader.tsindex 780e126b2a..22ff5cef9e 100644--- a/packages/content-engine/src/document-graph/cached-document-loader.ts+++ b/packages/content-engine/src/document-graph/cached-document-loader.ts@@ -2,7 +2,7 @@ import { LRUCache } from "lru-cache";import { ByteLimitExceededError, readBoundedBytes } from "../byte-stream";import { serializeJsonDeterministically } from "../canonical-json";import { contentEngineLimits } from "../limits";-import type { DocumentFormat } from "./document-adapter";+import { isDocumentFormat, type DocumentFormat } from "./document-format";import type { DocumentGraphNode } from "./graph";import {assertDocumentSourceIdentity,@@ -83,7 +83,7 @@ const isCachedDocumentSource = (}const value = input as Partial<CachedDocumentSource>;return (- (value.format === "json" || value.format === "markdown") &&+ isDocumentFormat(value.format) &&typeof value.revision === "string" &&value.revision.length > 0 &&value.bytes instanceof Uint8Arraydiff --git a/packages/content-engine/src/document-graph/compiler.ts b/packages/content-engine/src/document-graph/compiler.tsindex 2e42bb7817..d9e3bcdceb 100644--- a/packages/content-engine/src/document-graph/compiler.ts+++ b/packages/content-engine/src/document-graph/compiler.ts@@ -1,4 +1,5 @@import { compareStrings } from "../canonical-json";+import type { DocumentFormat } from "./document-format";import {createDocumentGraph,DocumentGraphError,@@ -12,7 +13,7 @@ export type DocumentDescriptor = Readonly<{documentUrl: string;revision: string;contentRef: string;- format?: "json" | "markdown";+ format?: DocumentFormat;}>;export type DocumentGraphCompilationErrorCode =diff --git a/packages/content-engine/src/document-graph/document-adapter.test.ts b/packages/content-engine/src/document-graph/document-adapter.test.tsindex dc7e1aff7f..3838c71aa6 100644--- a/packages/content-engine/src/document-graph/document-adapter.test.ts+++ b/packages/content-engine/src/document-graph/document-adapter.test.ts@@ -2,8 +2,11 @@ import { describe, expect, test } from "vitest";import {analyzeDocumentSource,assembleDocument,+ getAdaptedDocumentProperties,+ parseDocumentSource,selectDocumentRepresentation,} from "./document-adapter";+import { getDocumentFormatByContentType } from "./document-format";const documentUrl = "https://content.webstudio.test/posts/hello";@@ -19,6 +22,12 @@ describe("document adapter", () => {source: "---\nauthor:\n $ref: ../authors/ada.json\n---\n# Hello\n",referenceId: "#frontmatter/author",},+ {+ format: "mdx" as const,+ source:+ '---\nauthor:\n $ref: ../authors/ada.json\n---\n<ws.element ws:name="Hero">Hello</ws.element>\n',+ referenceId: "#frontmatter/author",+ },])("analyzes $format sources through one contract", async (fixture) => {const analyzed = await analyzeDocumentSource({format: fixture.format,@@ -33,6 +42,33 @@ describe("document adapter", () => {]);});+ test("maps MDX content types without changing Markdown", () => {+ expect(getDocumentFormatByContentType("text/mdx; charset=utf-8")).toBe(+ "mdx"+ );+ expect(getDocumentFormatByContentType("text/markdown")).toBe("markdown");+ });++ test("analyzes valid MDX frontmatter independently from an invalid body", async () => {+ const analyzed = await analyzeDocumentSource({+ format: "mdx",+ source:+ "---\ntitle: Visible metadata\n---\n<figure><p>Invalid MDX<br></p></figure>\n",+ sourceDocumentId: "post",+ documentUrl,+ });++ expect(getAdaptedDocumentProperties(analyzed)).toEqual({+ title: "Visible metadata",+ });+ expect(+ selectDocumentRepresentation({+ document: analyzed,+ representation: { type: "markdown-body" },+ })+ ).toBe("<figure><p>Invalid MDX<br></p></figure>\n");+ });+test("assembles and selects JSON representations without losing the format", async () => {const analyzed = await analyzeDocumentSource({format: "json",@@ -83,4 +119,50 @@ describe("document adapter", () => {})).toBe("# Hello\n");});++ test("parses MDX through the shared Markdown data representations", async () => {+ const source =+ '---\ntitle: Hello\n---\n<ws.element ws:name="Hero">Body</ws.element>\n';+ const parsed = await parseDocumentSource({ format: "mdx", source });++ expect(parsed.format).toBe("mdx");+ if (parsed.format !== "mdx") {+ throw new Error("Expected an MDX document");+ }+ expect(parsed.value.body).toBe(+ '<ws.element ws:name="Hero">Body</ws.element>\n'+ );+ expect(+ selectDocumentRepresentation({+ document: parsed,+ representation: { type: "markdown-frontmatter" },+ })+ ).toEqual({ title: "Hello" });+ expect(+ selectDocumentRepresentation({+ document: parsed,+ representation: { type: "markdown-body" },+ })+ ).toBe('<ws.element ws:name="Hero">Body</ws.element>\n');+ });++ test("resolves MDX frontmatter without changing the body", async () => {+ const analyzed = await analyzeDocumentSource({+ format: "mdx",+ 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("mdx");+ if (assembled.format !== "mdx") {+ throw new Error("Expected an MDX document");+ }+ expect(assembled.value.frontmatter).toEqual({ author: { name: "Ada" } });+ expect(assembled.value.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.tsindex 7d3790c9c6..bcf33b4f89 100644--- a/packages/content-engine/src/document-graph/document-adapter.ts+++ b/packages/content-engine/src/document-graph/document-adapter.ts@@ -17,24 +17,19 @@ import {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";- }-};+import type { DocumentFormat } from "./document-format";+import {+ resolveAssetValueReferences,+ type AssetRuntimeData,+ type AssetValueReference,+} from "../asset-value-references";export type AdaptedDocument =| Readonly<{ format: "json"; value: JsonValue }>- | Readonly<{ format: "markdown"; value: MarkdownDocument }>;+ | Readonly<{+ format: "markdown" | "mdx";+ value: MarkdownDocument;+ }>;export type AnalyzedDocument =| Readonly<{@@ -43,19 +38,45 @@ export type AnalyzedDocument =references: readonly SourceReferenceOccurrence[];}>| Readonly<{- format: "markdown";+ format: "markdown" | "mdx";value: MarkdownDocument;references: readonly SourceReferenceOccurrence[];}>;export const getAdaptedDocumentProperties = (document: AdaptedDocument) => {const value =- document.format === "markdown"- ? document.value.frontmatter- : document.value;+ document.format === "json" ? document.value : document.value.frontmatter;return isJsonObject(value) ? value : undefined;};+/** Resolves local Asset references without changing the document format. */+export const resolveAdaptedDocumentAssetReferences = ({+ document,+ references,+ runtimeAssets,+}: {+ document: AdaptedDocument;+ references?: readonly AssetValueReference[];+ runtimeAssets?: Readonly<Record<string, AssetRuntimeData>>;+}): AdaptedDocument => {+ const properties = getAdaptedDocumentProperties(document);+ if (properties === undefined || references === undefined) {+ return document;+ }+ const resolved = resolveAssetValueReferences({+ value: { properties },+ references,+ runtimeAssets,+ }).properties;+ if (document.format === "json") {+ return Object.freeze({ ...document, value: resolved });+ }+ return Object.freeze({+ ...document,+ value: Object.freeze({ ...document.value, frontmatter: resolved }),+ });+};+const freezeDocument = <Document extends AdaptedDocument | AnalyzedDocument>(document: Document) => Object.freeze(document);diff --git a/packages/content-engine/src/document-graph/document-format.ts b/packages/content-engine/src/document-graph/document-format.tsnew file mode 100644index 0000000000..fd9a6c26d8--- /dev/null+++ b/packages/content-engine/src/document-graph/document-format.ts@@ -0,0 +1,21 @@+export const documentFormats = ["json", "markdown", "mdx"] as const;+export type DocumentFormat = (typeof documentFormats)[number];++export const isDocumentFormat = (value: unknown): value is DocumentFormat =>+ typeof value === "string" &&+ documentFormats.includes(value as DocumentFormat);++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";+ }+ if (mimeType === "text/mdx") {+ return "mdx";+ }+};diff --git a/packages/content-engine/src/document-graph/document-resolution.ts b/packages/content-engine/src/document-graph/document-resolution.tsindex fd0420b4bc..cfae27a397 100644--- a/packages/content-engine/src/document-graph/document-resolution.ts+++ b/packages/content-engine/src/document-graph/document-resolution.ts@@ -3,11 +3,13 @@ import { ByteLimitExceededError, readBytePrefix } from "../byte-stream";import { contentEngineLimits } from "../limits";import {assembleDocument,+ getAdaptedDocumentProperties,parseDocumentSource,+ resolveAdaptedDocumentAssetReferences,selectDocumentRepresentation,type AdaptedDocument,- type DocumentFormat,} from "./document-adapter";+import type { DocumentFormat } from "./document-format";import {getDocumentGraphClosure,type DocumentGraph,@@ -25,6 +27,10 @@ import {getDocumentGraphErrorCode,type DocumentGraphRuntimeObserver,} from "./observability";+import type {+ AssetRuntimeData,+ AssetValueReferences,+} from "../asset-value-references";export type DocumentResolutionLimitErrorCode =| "DOCUMENT_COUNT_EXCEEDED"@@ -88,6 +94,10 @@ type ResolveDocumentGraphInput = {maximumDocuments?: number;onEvent?: DocumentGraphRuntimeObserver;allowUnresolvedReferences?: boolean;+ transformDocument?: (input: {+ node: DocumentGraphNode;+ document: AdaptedDocument;+ }) => AdaptedDocument;};export type DocumentResolutionSession = Readonly<{@@ -163,6 +173,7 @@ const resolveWithSessionDocumentLoader = async ({signal,onEvent,allowUnresolvedReferences = false,+ transformDocument,load,}: ResolveDocumentGraphInput & {concurrency: number;@@ -246,12 +257,14 @@ const resolveWithSessionDocumentLoader = async ({document: value,representation: reference.representation,}),- assemble: ({ source, references }) =>- assembleDocument({+ assemble: ({ node, source, references }) => {+ const document = assembleDocument({document: source,references,allowUnresolvedReferences,- }),+ });+ return transformDocument?.({ node, document }) ?? document;+ },});emitDocumentGraphRuntimeEvent(onEvent, {type: "resolution-completed",@@ -425,6 +438,39 @@ export const createDocumentResolutionSession = ({});};+/** Resolves one document's graph-backed properties and local Asset references. */+export const resolveDocumentGraphProperties = async ({+ graph,+ rootId,+ load,+ assetValueReferences,+ runtimeAssets,+ concurrency = contentEngineLimits.concurrentContentReads,+}: {+ graph: DocumentGraph;+ rootId: string;+ load: DocumentSourceLoader;+ assetValueReferences?: AssetValueReferences;+ runtimeAssets?: Readonly<Record<string, AssetRuntimeData>>;+ concurrency?: number;+}) => {+ const resolution = await createDocumentResolutionSession({+ load,+ concurrency,+ }).resolve({+ graph,+ rootIds: [rootId],+ allowUnresolvedReferences: true,+ transformDocument: ({ node, document }) =>+ resolveAdaptedDocumentAssetReferences({+ document,+ references: assetValueReferences?.[node.id],+ runtimeAssets,+ }),+ });+ return getAdaptedDocumentProperties(resolution.roots[0]);+};+/** Resolves parsed JSON and Markdown values without depending on storage. */export const resolveAdaptedDocumentGraph = async ({graph,diff --git a/packages/content-engine/src/document-graph/document-source.ts b/packages/content-engine/src/document-graph/document-source.tsindex 053d011d79..aea52b8b31 100644--- a/packages/content-engine/src/document-graph/document-source.ts+++ b/packages/content-engine/src/document-graph/document-source.ts@@ -1,5 +1,5 @@import type { ByteSource } from "../byte-stream";-import type { DocumentFormat } from "./document-adapter";+import type { DocumentFormat } from "./document-format";import type { DocumentGraphNode } from "./graph";export type DocumentSource = Readonly<{diff --git a/packages/content-engine/src/document-graph/graph-schema.ts b/packages/content-engine/src/document-graph/graph-schema.tsindex 1308bf2d2e..8d21304e64 100644--- a/packages/content-engine/src/document-graph/graph-schema.ts+++ b/packages/content-engine/src/document-graph/graph-schema.ts@@ -1,11 +1,12 @@import { enum as zEnum, strictObject, string } from "zod";+import { documentFormats } from "./document-format";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(),+ format: zEnum(documentFormats).optional(),});export const documentGraphEdgeSchema = strictObject({diff --git a/packages/content-engine/src/document-graph/graph.test.ts b/packages/content-engine/src/document-graph/graph.test.tsindex 41cb94e8a3..c449bc0142 100644--- a/packages/content-engine/src/document-graph/graph.test.ts+++ b/packages/content-engine/src/document-graph/graph.test.ts@@ -34,6 +34,22 @@ const edges = [];describe("document graph", () => {+ test("accepts MDX document identities", () => {+ expect(+ createDocumentGraph({+ nodes: [+ {+ id: "post",+ revision: "post-r1",+ contentRef: "content:post",+ format: "mdx",+ },+ ],+ edges: [],+ }).nodes[0]?.format+ ).toBe("mdx");+ });+test("rejects conflicting revisions for one content reference", () => {expect(() =>createDocumentGraph({diff --git a/packages/content-engine/src/document-graph/graph.ts b/packages/content-engine/src/document-graph/graph.tsindex 65c63b0a77..a3003f542d 100644--- a/packages/content-engine/src/document-graph/graph.ts+++ b/packages/content-engine/src/document-graph/graph.ts@@ -1,4 +1,5 @@import { compareStrings } from "../canonical-json";+import type { DocumentFormat } from "./document-format";import { createDocumentReference, type DocumentReference } from "./reference";import {documentGraphEdgeSchema,@@ -10,7 +11,7 @@ export type DocumentGraphNode = Readonly<{id: string;revision: string;contentRef: string;- format?: "json" | "markdown";+ format?: DocumentFormat;}>;export type DocumentGraphEdge = Readonly<{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.tsindex 3691fea9f6..e490823b90 100644--- a/packages/content-engine/src/document-graph/http-document-loader.test.ts+++ b/packages/content-engine/src/document-graph/http-document-loader.test.ts@@ -36,6 +36,20 @@ describe("HTTP document loader", () => {});});+ test("accepts MDX response metadata", async () => {+ const load = createHttpDocumentSourceLoader({+ fetch: async () => new Response("# Hello"),+ getRequest: () => "https://cdn.webstudio.test/post.mdx",+ getMetadata: () => ({ format: "mdx", revision: "post-r1" }),+ });++ const loaded = await load(node, {});+ expect(loaded.format).toBe("mdx");+ await expect(parseDocumentSource(loaded)).resolves.toMatchObject({+ format: "mdx",+ });+ });+test("reports non-success responses without consuming their body", async () => {let bodyRead = false;const response = {diff --git a/packages/content-engine/src/document-graph/http-document-loader.ts b/packages/content-engine/src/document-graph/http-document-loader.tsindex 604a02b19d..0f170481dd 100644--- a/packages/content-engine/src/document-graph/http-document-loader.ts+++ b/packages/content-engine/src/document-graph/http-document-loader.ts@@ -1,4 +1,6 @@import { enum as zEnum, strictObject, string } from "zod";+import { readableStreamToAsyncIterable } from "../byte-stream";+import { documentFormats } from "./document-format";import type { DocumentGraphNode } from "./graph";import type { DocumentSourceLoader } from "./document-source";import {@@ -7,7 +9,7 @@ import {} from "./observability";const documentSourceMetadata = strictObject({- format: zEnum(["json", "markdown"]),+ format: zEnum(documentFormats),revision: string().min(1),});@@ -43,34 +45,6 @@ export class HttpDocumentLoaderError extends Error {}}-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,@@ -127,7 +101,7 @@ export const createHttpDocumentSourceLoader = ({}return Object.freeze({...metadata,- source: streamResponseBody(body),+ source: readableStreamToAsyncIterable(body),});};return observeDocumentSourceLoader({ load, onEvent });diff --git a/packages/content-engine/src/document-graph/index.ts b/packages/content-engine/src/document-graph/index.tsindex c3c58232ea..f251770b73 100644--- a/packages/content-engine/src/document-graph/index.ts+++ b/packages/content-engine/src/document-graph/index.ts@@ -6,6 +6,7 @@ export * from "./compiler";export * from "./source-compiler";export * from "./json-document";export * from "./markdown-document";+export * from "./document-format";export * from "./document-adapter";export * from "./document-source";export * from "./http-document-loader";diff --git a/packages/content-engine/src/document-graph/query-resolution.test.ts b/packages/content-engine/src/document-graph/query-resolution.test.tsindex 5086537cd3..de063a180e 100644--- a/packages/content-engine/src/document-graph/query-resolution.test.ts+++ b/packages/content-engine/src/document-graph/query-resolution.test.ts@@ -316,17 +316,26 @@ describe("document graph query resolution", () => {const { artifact } = await compileContentArtifact({projectId: "project",entries,- assetValueReferences: Object.fromEntries(- entries.map(({ assetId }) => [- assetId,- [- {- path: ["properties", "featureImage"],- assetId: "hero",- },- ],- ])- ),+ assetValueReferences: {+ ...Object.fromEntries(+ entries.map(({ assetId }) => [+ assetId,+ [+ {+ path: ["properties", "featureImage"],+ assetId: "hero",+ },+ ],+ ])+ ),+ "author-ada": [+ {+ path: ["properties", "profileImage"],+ assetId: "ada-avatar",+ structured: true,+ },+ ],+ },documentGraph: graph,});const sources: Record<string, string> = {@@ -334,7 +343,7 @@ describe("document graph query resolution", () => {'{"author":{"$ref":"../authors/ada.json"},"featureImage":"./assets/hero.png"}',"post-grace":'{"author":{"$ref":"../authors/grace.json"},"featureImage":"./assets/hero.png"}',- "author-ada": '{"name":"Ada"}',+ "author-ada": '{"name":"Ada","profileImage":{"$ref":"./ada.png"}}',"author-grace": '{"name":"Grace"}',};const load = vi.fn(async (node: (typeof graph.nodes)[number]) => ({@@ -372,6 +381,7 @@ describe("document graph query resolution", () => {includeMetadata: false,fields: [["properties", "author", "name"],+ ["properties", "author", "profileImage", "src"],["properties", "featureImage"],],},@@ -381,6 +391,10 @@ describe("document graph query resolution", () => {load,runtimeAssets: {hero: { url: "/cgi/image/hero.png?format=raw" },+ "ada-avatar": {+ url: "/cgi/image/ada.png?format=raw",+ description: "Portrait of Ada",+ },},});@@ -389,7 +403,12 @@ describe("document graph query resolution", () => {{id: "post-ada",properties: {- author: { name: "Ada" },+ author: {+ name: "Ada",+ profileImage: {+ src: "/cgi/image/ada.png?format=raw",+ },+ },featureImage: "/cgi/image/hero.png?format=raw",},},diff --git a/packages/content-engine/src/document-graph/source-compiler.test.ts b/packages/content-engine/src/document-graph/source-compiler.test.tsindex 2fa9a89517..019b2d4d1a 100644--- a/packages/content-engine/src/document-graph/source-compiler.test.ts+++ b/packages/content-engine/src/document-graph/source-compiler.test.ts@@ -1,6 +1,7 @@import { describe, expect, test } from "vitest";import {compileDocumentSourceGraph,+ createDocumentSourceUrl,DocumentSourceCompilationError,} from "./source-compiler";@@ -34,6 +35,12 @@ const documents = [];describe("document source graph compiler", () => {+ test("encodes every Asset path segment as document URL data", () => {+ expect(createDocumentSourceUrl("authors/Ada #1/プロフィール.md")).toBe(+ "https://content.webstudio.local/authors/Ada%20%231/%E3%83%97%E3%83%AD%E3%83%95%E3%82%A3%E3%83%BC%E3%83%AB.md"+ );+ });+test("discovers mixed-format references and compiles a deterministic graph", async () => {const graph = await compileDocumentSourceGraph({documents: [...documents].reverse(),diff --git a/packages/content-engine/src/document-graph/source-compiler.ts b/packages/content-engine/src/document-graph/source-compiler.tsindex 764607575b..3f7bc7ee7a 100644--- a/packages/content-engine/src/document-graph/source-compiler.ts+++ b/packages/content-engine/src/document-graph/source-compiler.ts@@ -3,7 +3,11 @@ 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 {+ analyzeDocumentSource,+ getAdaptedDocumentProperties,+} from "./document-adapter";+import type { DocumentFormat } from "./document-format";import type { DocumentGraph } from "./graph";import type { SourceReferenceOccurrence } from "./reference-codec";@@ -13,6 +17,12 @@ export type DocumentSourceDescriptor = DocumentDescriptor &source: ByteSource;}>;+export const createDocumentSourceUrl = (path: string) =>+ new URL(+ path.split("/").map(encodeURIComponent).join("/"),+ "https://content.webstudio.local/"+ ).href;+export type DocumentSourceCompilationErrorCode =| "REQUEST_CANCELLED"| "ROOT_NOT_FOUND"@@ -57,6 +67,8 @@ export const compileDocumentSourceGraph = async ({concurrency = contentEngineLimits.concurrentContentReads,maximumBytes = contentEngineLimits.hydratedFileBytes,ignoredReferenceUrls,+ ignoreReference,+ onDocumentProperties,signal,}: {documents: readonly DocumentSourceDescriptor[];@@ -64,6 +76,11 @@ export const compileDocumentSourceGraph = async ({concurrency?: number;maximumBytes?: number;ignoredReferenceUrls?: ReadonlySet<string>;+ ignoreReference?: (occurrence: SourceReferenceOccurrence) => boolean;+ onDocumentProperties?: (input: {+ id: string;+ properties: Readonly<Record<string, unknown>>;+ }) => void;signal?: AbortSignal;}): Promise<DocumentGraph> => {assertActive(signal);@@ -103,7 +120,10 @@ export const compileDocumentSourceGraph = async ({documentUrl: document.documentUrl,maximumBytes,});- return { document, references: result.references };+ return {+ document,+ analyzedDocument: result,+ };} catch (cause) {assertActive(signal);throw new DocumentSourceCompilationError({@@ -115,12 +135,19 @@ export const compileDocumentSourceGraph = async ({}});- for (const { document } of analyzed) {+ for (const { document, analyzedDocument } of analyzed) {analyzedIds.add(document.id);+ const properties = getAdaptedDocumentProperties(analyzedDocument);+ if (properties !== undefined) {+ onDocumentProperties?.({ id: document.id, properties });+ }}for (const result of analyzed) {- for (const occurrence of result.references) {- if (ignoredReferenceUrls?.has(occurrence.reference.documentUrl)) {+ for (const occurrence of result.analyzedDocument.references) {+ if (+ ignoredReferenceUrls?.has(occurrence.reference.documentUrl) ||+ ignoreReference?.(occurrence) === true+ ) {continue;}references.push(occurrence);diff --git a/packages/content-engine/src/document-metadata.test.ts b/packages/content-engine/src/document-metadata.test.tsindex 7762a8dced..9c3d0fffb0 100644--- a/packages/content-engine/src/document-metadata.test.ts+++ b/packages/content-engine/src/document-metadata.test.ts@@ -7,11 +7,15 @@ const createEntry = ({properties = {},excerpt,prepared = false,+ format = "markdown",+ size = 44,}: {revision?: string;properties?: Record<string, string>;excerpt?: string;prepared?: boolean;+ format?: "markdown" | "mdx";+ size?: number;} = {}) =>createCanonicalAssetFileEntry({projectId: "project",@@ -22,20 +26,37 @@ const createEntry = ({document: {_id: "post",_type: "asset.file",- name: "post.md",- path: "blog/post.md",+ name: `post.${format === "markdown" ? "md" : "mdx"}`,+ path: `blog/post.${format === "markdown" ? "md" : "mdx"}`,key: "post",- extension: "md",- mimeType: "text/markdown",- size: 44,+ extension: format === "markdown" ? "md" : "mdx",+ mimeType: format === "markdown" ? "text/markdown" : "text/mdx",+ size,revision,- contentRef: "post.md",+ contentRef: `post.${format === "markdown" ? "md" : "mdx"}`,properties,...(excerpt === undefined ? {} : { excerpt }),},});describe("content metadata cache", () => {+ test("indexes MDX frontmatter without generating a Markdown excerpt", async () => {+ const bytes = new TextEncoder().encode(+ "---\ntitle: MDX post\n---\n<ws.element>Body</ws.element>"+ );+ const readBytes = vi.fn(async () => bytes);++ const prepared = await prepareCanonicalContentMetadata({+ base: createEntry({ format: "mdx", size: bytes.byteLength }),+ requirements: { structuredProperties: true, excerpt: true },+ readBytes,+ });++ expect(prepared.document.properties).toEqual({ title: "MDX post" });+ expect(prepared.document).not.toHaveProperty("excerpt");+ expect(readBytes).toHaveBeenCalledWith(bytes.byteLength);+ });+test("reuses a matching prepared entry without reading source bytes", async () => {const cached = createEntry({properties: { title: "Cached" },diff --git a/packages/content-engine/src/document-metadata.ts b/packages/content-engine/src/document-metadata.tsindex 3a9a44f9bd..e5875c97d0 100644--- a/packages/content-engine/src/document-metadata.ts+++ b/packages/content-engine/src/document-metadata.ts@@ -16,6 +16,9 @@ import { markdownFrontmatterEnvelopeBytes } from "./markdown-scanner";const isMarkdown = (entry: CanonicalAssetFileEntry) =>entry.document.extension.toLowerCase() === "md";+const hasMarkdownFrontmatter = (entry: CanonicalAssetFileEntry) =>+ isMarkdown(entry) || entry.document.extension.toLowerCase() === "mdx";+const isJson = (entry: CanonicalAssetFileEntry) =>entry.document.extension.toLowerCase() === "json";@@ -108,14 +111,23 @@ export const prepareCanonicalContentMetadata = async ({const needsExcerpt =requirements.excerpt && cachedRequirements.excerpt === false;- if (isMarkdown(base) && (needsProperties || needsExcerpt)) {- // Frontmatter discovery needs only the bounded opening block. Excerpt- // generation still receives the larger Markdown body budget.- const maximumBytes = needsExcerpt- ? contentEngineLimits.hydratedFileBytes- : contentEngineLimits.frontmatterBytes + markdownFrontmatterEnvelopeBytes;+ if (+ (hasMarkdownFrontmatter(base) && needsProperties) ||+ (isMarkdown(base) && needsExcerpt)+ ) {+ // Frontmatter discovery needs only the bounded opening block. Markdown+ // excerpt generation still receives the larger body budget.+ const maximumBytes =+ isMarkdown(base) && needsExcerpt+ ? contentEngineLimits.hydratedFileBytes+ : contentEngineLimits.frontmatterBytes ++ markdownFrontmatterEnvelopeBytes;let bytes = await readBytes(Math.min(base.document.size, maximumBytes));- if (needsExcerpt && base.document.size > bytes.byteLength) {+ if (+ isMarkdown(base) &&+ needsExcerpt &&+ base.document.size > bytes.byteLength+ ) {bytes = trimIncompleteUtf8Suffix(bytes);}if (needsProperties) {@@ -128,7 +140,7 @@ export const prepareCanonicalContentMetadata = async ({metadataError = { code: error.code, message: error.message };}}- if (needsExcerpt) {+ if (isMarkdown(base) && needsExcerpt) {try {excerpt = (await extractMarkdownBodyAndExcerpt(bytes)).excerpt;} catch (error) {diff --git a/packages/content-engine/src/frontmatter.ts b/packages/content-engine/src/frontmatter.tsindex 912a8970a9..421459cf03 100644--- a/packages/content-engine/src/frontmatter.ts+++ b/packages/content-engine/src/frontmatter.ts@@ -1,5 +1,5 @@import { contentEngineLimits } from "./limits";-import { parseDocument } from "yaml";+import { parseDocument, stringify as stringifyYaml } from "yaml";import {decodeUtf8 as decodeUtf8Bytes,toByteChunks,@@ -12,6 +12,7 @@ import {import { MarkdownMetadataError } from "./markdown-errors";import {findMarkdownFrontmatter,+ markdownByteOrderMark,markdownFrontmatterEnvelopeBytes,} from "./markdown-scanner";@@ -204,3 +205,52 @@ export const extractMarkdownFrontmatter = async ("Markdown frontmatter is not closed within the byte limit");};++export const serializeMarkdownFrontmatter = (+ properties: Readonly<Record<string, unknown>>+) => {+ const yaml = stringifyYaml(properties, {+ aliasDuplicateObjects: false,+ lineWidth: 0,+ sortMapEntries: true,+ }).trimEnd();+ return `---\n${yaml}\n---\n\n`;+};++/** Updates frontmatter without parsing or otherwise rewriting the body. */+export const replaceMarkdownFrontmatter = async ({+ source,+ properties,+}: {+ source: string;+ properties: Readonly<Record<string, unknown>>;+}) => {+ const replacement = serializeMarkdownFrontmatter(properties);+ await extractMarkdownFrontmatter(replacement);++ const encoder = new TextEncoder();+ const bytes = encoder.encode(source);+ const range = findMarkdownFrontmatter(bytes, true);+ const hasByteOrderMark = markdownByteOrderMark.every(+ (value, index) => bytes[index] === value+ );+ const prefix = hasByteOrderMark ? "\uFEFF" : "";+ if (range === null || range === undefined) {+ return prefix + replacement + source.slice(prefix.length);+ }++ const bodyStart = new TextDecoder("utf-8", { ignoreBOM: true }).decode(+ bytes.subarray(0, range.blockEnd)+ ).length;+ const suffix = source.slice(bodyStart);+ const separatorLength = suffix.startsWith("\r\n\r\n")+ ? 4+ : suffix.startsWith("\n\n")+ ? 2+ : suffix.startsWith("\r\n")+ ? 2+ : suffix.startsWith("\n")+ ? 1+ : 0;+ return prefix + replacement + suffix.slice(separatorLength);+};diff --git a/packages/content-engine/src/index.ts b/packages/content-engine/src/index.tsindex cae443e72f..89e4611164 100644--- a/packages/content-engine/src/index.ts+++ b/packages/content-engine/src/index.ts@@ -12,3 +12,5 @@ export * from "./query-source";export * from "./query-error";export * from "./document-graph";export * from "./asset-value-references";+export * from "./json-assets";+export { createUniqueAssetIdsByPath } from "./asset-path-resolution";diff --git a/packages/content-engine/src/json-assets.test.ts b/packages/content-engine/src/json-assets.test.tsnew file mode 100644index 0000000000..d2c5a42235--- /dev/null+++ b/packages/content-engine/src/json-assets.test.ts@@ -0,0 +1,26 @@+import { expect, test } from "vitest";+import { rewriteJsonAssetReferences } from "./json-assets";++test("rewrites scalar and structured JSON Asset references", async () => {+ const rewritten = await rewriteJsonAssetReferences({+ source: JSON.stringify({+ avatar: "../media/avatar.png#profile",+ organization: { $ref: "./organization.json#frontmatter" },+ }),+ sourcePath: "authors/oleg.json",+ assetPaths: new Map([+ ["avatar", "media/avatar.png"],+ ["organization", "authors/organization.json"],+ ]),+ replacementPaths: new Map([+ ["avatar", "avatar_1.png"],+ ["organization", "organization_1.json"],+ ]),+ });++ expect(JSON.parse(rewritten)).toEqual({+ avatar: "avatar_1.png#profile",+ organization: { $ref: "organization_1.json#frontmatter" },+ });+ expect(rewritten.endsWith("\n")).toBe(true);+});diff --git a/packages/content-engine/src/json-assets.ts b/packages/content-engine/src/json-assets.tsnew file mode 100644index 0000000000..af7e485c8e--- /dev/null+++ b/packages/content-engine/src/json-assets.ts@@ -0,0 +1,78 @@+import {+ discoverAssetValueReferences,+ rewriteAssetValueReferences,+} from "./asset-value-references";+import { createNamedAssetReferenceContext } from "./asset-reference-utils";+import { createUniqueAssetIdsByPath } from "./asset-path-resolution";+import { parseJsonDocumentSource } from "./document-graph/json-document";++export class JsonAssetReferenceError extends Error {+ constructor(cause: unknown) {+ super("Unable to parse JSON Asset references", { cause });+ this.name = "JsonAssetReferenceError";+ }+}++const parseJson = async (source: string) => {+ try {+ return await parseJsonDocumentSource({ source });+ } catch (cause) {+ throw new JsonAssetReferenceError(cause);+ }+};++export const discoverNamedJsonAssetReferences = async ({+ source,+ asset,+ assets,+}: {+ source: string;+ asset: { name: string; folderNames: readonly string[] };+ assets: Iterable<{+ id: string;+ name: string;+ folderNames: readonly string[];+ }>;+}) => {+ const properties = await parseJson(source);+ const assetList = Array.from(assets);+ return discoverAssetValueReferences({+ properties,+ ...createNamedAssetReferenceContext({ source: asset, assets: assetList }),+ structuredAssetIds: new Set(assetList.map(({ id }) => id)),+ rootPath: [],+ });+};++export const rewriteJsonAssetReferences = async ({+ source,+ sourcePath,+ assetPaths,+ replacementPaths,+}: {+ source: string;+ sourcePath: string;+ assetPaths: ReadonlyMap<string, string>;+ replacementPaths: ReadonlyMap<string, string>;+}) => {+ const properties = await parseJson(source);+ const assetIdsByPath = createUniqueAssetIdsByPath(+ Array.from(assetPaths, ([id, path]) => ({ id, path }))+ );+ const references = discoverAssetValueReferences({+ properties,+ sourcePath,+ assetIdsByPath,+ structuredAssetIds: new Set(assetIdsByPath.values()),+ rootPath: [],+ });+ if (references.length === 0) {+ return source;+ }+ const rewritten = rewriteAssetValueReferences({+ value: properties,+ references,+ assetUrls: Object.fromEntries(replacementPaths),+ });+ return `${JSON.stringify(rewritten, undefined, 2)}\n`;+};diff --git a/packages/content-engine/src/jsx-attributes.test.ts b/packages/content-engine/src/jsx-attributes.test.tsnew file mode 100644index 0000000000..764b02dce4--- /dev/null+++ b/packages/content-engine/src/jsx-attributes.test.ts@@ -0,0 +1,62 @@+import { expect, test } from "vitest";+import { mapAttributeNames } from "./jsx-attributes";++test("maps complete prop lists in both directions", () => {+ expect(+ mapAttributeNames({+ attributes: [{ name: "class" }, { name: "tabindex" }],+ direction: "instance-to-jsx",+ acceptsHtmlAttributes: true,+ })+ ).toEqual([{ name: "className" }, { name: "tabIndex" }]);+ expect(+ mapAttributeNames({+ attributes: [{ name: "className" }, { name: "tabIndex" }],+ direction: "jsx-to-instance",+ acceptsHtmlAttributes: true,+ })+ ).toEqual([{ name: "class" }, { name: "tabindex" }]);+});++test("always maps the JSX class alias", () => {+ expect(+ mapAttributeNames({+ attributes: [{ name: "class" }],+ direction: "instance-to-jsx",+ acceptsHtmlAttributes: false,+ })+ ).toEqual([{ name: "className" }]);+ expect(+ mapAttributeNames({+ attributes: [{ name: "className" }],+ direction: "jsx-to-instance",+ acceptsHtmlAttributes: false,+ })+ ).toEqual([{ name: "class" }]);+ expect(+ mapAttributeNames({+ attributes: [{ name: "className" }],+ direction: "jsx-to-instance",+ acceptsHtmlAttributes: false,+ componentPropNames: new Set(["className"]),+ })+ ).toEqual([{ name: "class" }]);+ expect(+ mapAttributeNames({+ attributes: [{ name: "class" }],+ direction: "instance-to-jsx",+ acceptsHtmlAttributes: false,+ componentPropNames: new Set(["class"]),+ })+ ).toEqual([{ name: "className" }]);+});++test("rejects names that collide after conversion", () => {+ expect(() =>+ mapAttributeNames({+ attributes: [{ name: "class" }, { name: "className" }],+ direction: "instance-to-jsx",+ acceptsHtmlAttributes: true,+ })+ ).toThrow('Multiple properties map to "className"');+});diff --git a/packages/content-engine/src/jsx-attributes.ts b/packages/content-engine/src/jsx-attributes.tsnew file mode 100644index 0000000000..6225a946b1--- /dev/null+++ b/packages/content-engine/src/jsx-attributes.ts@@ -0,0 +1,97 @@+import {+ reactPropsToStandardAttributes,+ standardAttributesToReactProps,+} from "./__generated__/standard-attributes";++type JsxPropContext = Readonly<{+ acceptsHtmlAttributes: boolean;+ componentPropNames?: ReadonlySet<string>;+}>;++type AttributeNameDirection = "instance-to-jsx" | "jsx-to-instance";++type NamedAttribute = Readonly<{ name: string }>;++type MappedAttribute<Attribute extends NamedAttribute> = Omit<+ Attribute,+ "name"+> & { name: string };++export const assertUniqueAttributeNames = (+ attributes: readonly NamedAttribute[]+) => {+ const names = new Set<string>();+ for (const { name } of attributes) {+ if (names.has(name)) {+ throw new Error(`Multiple properties map to "${name}"`);+ }+ names.add(name);+ }+};++export const getJsxPropName = ({+ instancePropName,+ acceptsHtmlAttributes,+ componentPropNames,+}: JsxPropContext & { instancePropName: string }) => {+ if (instancePropName === "class") {+ return "className";+ }+ if (componentPropNames?.has(instancePropName)) {+ return instancePropName;+ }+ if (acceptsHtmlAttributes === false) {+ return instancePropName;+ }+ return standardAttributesToReactProps[instancePropName] ?? instancePropName;+};++export const getInstancePropName = ({+ jsxPropName,+ acceptsHtmlAttributes,+ componentPropNames,+}: JsxPropContext & { jsxPropName: string }) => {+ if (jsxPropName === "className") {+ return "class";+ }+ if (componentPropNames?.has(jsxPropName)) {+ return jsxPropName;+ }+ if (acceptsHtmlAttributes === false) {+ return jsxPropName;+ }+ return reactPropsToStandardAttributes[jsxPropName] ?? jsxPropName;+};++export const mapAttributeNames = <Attribute extends NamedAttribute>({+ attributes,+ direction,+ acceptsHtmlAttributes,+ componentPropNames,+}: JsxPropContext & {+ attributes: readonly Attribute[];+ direction: AttributeNameDirection;+}): MappedAttribute<Attribute>[] => {+ const mappedAttributes = attributes.map((attribute) => {+ const name =+ direction === "instance-to-jsx"+ ? getJsxPropName({+ instancePropName: attribute.name,+ acceptsHtmlAttributes,+ componentPropNames,+ })+ : getInstancePropName({+ jsxPropName: attribute.name,+ acceptsHtmlAttributes,+ componentPropNames,+ });+ return { ...attribute, name };+ });+ assertUniqueAttributeNames(mappedAttributes);+ return mappedAttributes;+};++export {+ reactPropsToStandardAttributes,+ standardAttributesToReactProps,+} from "./__generated__/standard-attributes";diff --git a/packages/content-engine/src/limits.ts b/packages/content-engine/src/limits.tsindex 77247b2e27..5fc0ac2f92 100644--- a/packages/content-engine/src/limits.ts+++ b/packages/content-engine/src/limits.ts@@ -21,6 +21,9 @@ export const contentEngineLimits = {jsonStringBytes: 16 * 1024,indexedPropertiesBytes: 64 * 1024,excerptBytes: 2 * 1024,+ mdxDepth: 100,+ mdxNodes: 20_000,+ mdxProps: 4_000,hydratedFileBytes: 1024 * 1024,hydratedTotalBytes: 2 * 1024 * 1024,hydratedFileCount: 20,diff --git a/packages/content-engine/src/markdown-assets.ts b/packages/content-engine/src/markdown-assets.tsindex a469a3c3a8..0b3d3b74f9 100644--- a/packages/content-engine/src/markdown-assets.ts+++ b/packages/content-engine/src/markdown-assets.ts@@ -1,11 +1,25 @@import { parse, postprocess, preprocess } from "micromark";import { decodeString } from "micromark-util-decode-string";-import { createCanonicalAssetPath } from "./asset-path";import {- createAssetIdResolver,- createUniqueAssetIdsByPath,-} from "./asset-path-resolution";+ createAssetReferenceResolver,+ createNamedAssetReferenceContext,+} from "./asset-reference-utils";+import {+ discoverAssetValueReferences,+ rewriteAssetValueReferences,+} from "./asset-value-references";+import { createUniqueAssetIdsByPath } from "./asset-path-resolution";+import { parseMarkdownDocumentSource } from "./document-graph/markdown-document";+import { replaceMarkdownFrontmatter } from "./frontmatter";import type { MarkdownAssetReference } from "./markdown-references";+import { rewriteMarkdownAssetReferenceRanges } from "./markdown-references";++export class MarkdownAssetReferenceError extends Error {+ constructor(cause: unknown) {+ super("Unable to parse Markdown Asset references", { cause });+ this.name = "MarkdownAssetReferenceError";+ }+}const getMarkdownUrlTokens = (markdown: string) => {const events = postprocess(@@ -41,15 +55,16 @@ export const discoverMarkdownAssetReferenceRanges = ({sourcePath: string;assetIdsByPath: ReadonlyMap<string, string>;}): MarkdownAssetReference[] => {- const resolveAssetId = createAssetIdResolver(assetIdsByPath, sourcePath);+ const resolveAssetReference = createAssetReferenceResolver({+ assetIdsByPath,+ sourcePath,+ });return getMarkdownUrlTokens(markdown).flatMap(({ start, end, url }) => {- const assetId = resolveAssetId(url);- if (assetId === undefined) {+ const reference = resolveAssetReference(url);+ if (reference === undefined) {return [];}- const parsed = new URL(url, "https://content.webstudio.invalid/");- const suffix = `${parsed.search}${parsed.hash}`;- return [{ start, end, assetId, ...(suffix === "" ? {} : { suffix }) }];+ return [{ start, end, ...reference }];});};@@ -68,11 +83,92 @@ export const discoverNamedMarkdownAssetReferenceRanges = ({}) =>discoverMarkdownAssetReferenceRanges({markdown,- sourcePath: createCanonicalAssetPath(source),- assetIdsByPath: createUniqueAssetIdsByPath(- Array.from(assets, (asset) => ({- id: asset.id,- path: createCanonicalAssetPath(asset),- }))- ),+ ...createNamedAssetReferenceContext({ source, assets }),+ });++export const discoverNamedMarkdownDocumentAssetReferences = async ({+ markdown,+ source,+ assets,+}: {+ markdown: string;+ source: { name: string; folderNames: readonly string[] };+ assets: Iterable<{+ id: string;+ name: string;+ folderNames: readonly string[];+ }>;+}) => {+ const assetList = Array.from(assets);+ const context = createNamedAssetReferenceContext({+ source,+ assets: assetList,+ });+ const document = await parseMarkdownDocumentSource({ source: markdown });+ return [+ ...discoverAssetValueReferences({+ properties: document.frontmatter,+ ...context,+ structuredAssetIds: new Set(assetList.map(({ id }) => id)),+ }),+ ...discoverMarkdownAssetReferenceRanges({+ markdown: document.body,+ ...context,+ }),+ ];+};++export const rewriteMarkdownAssetReferences = async ({+ source,+ sourcePath,+ assetPaths,+ replacementPaths,+}: {+ source: string;+ sourcePath: string;+ assetPaths: ReadonlyMap<string, string>;+ replacementPaths: ReadonlyMap<string, string>;+}) => {+ let document;+ try {+ document = await parseMarkdownDocumentSource({ source });+ } catch (cause) {+ throw new MarkdownAssetReferenceError(cause);+ }+ const assetIdsByPath = createUniqueAssetIdsByPath(+ Array.from(assetPaths, ([id, path]) => ({ id, path }))+ );+ const assetUrls = Object.fromEntries(replacementPaths);+ const frontmatterReferences = discoverAssetValueReferences({+ properties: document.frontmatter,+ sourcePath,+ assetIdsByPath,+ structuredAssetIds: new Set(assetIdsByPath.values()),+ });+ const bodyReferences = discoverMarkdownAssetReferenceRanges({+ markdown: document.body,+ sourcePath,+ assetIdsByPath,+ });+ const body = rewriteMarkdownAssetReferenceRanges({+ markdown: document.body,+ references: bodyReferences,+ assetUrls,});+ let rewritten = source;+ if (body !== document.body) {+ rewritten = `${source.slice(0, source.length - document.body.length)}${body}`;+ }+ if (frontmatterReferences.length > 0) {+ const frontmatter = rewriteAssetValueReferences({+ value: { properties: document.frontmatter },+ references: frontmatterReferences,+ assetUrls,+ }).properties;+ rewritten = await replaceMarkdownFrontmatter({+ source: rewritten,+ properties: frontmatter,+ });+ }+ return rewritten;+};diff --git a/packages/content-engine/src/markdown-ast.ts b/packages/content-engine/src/markdown-ast.tsnew file mode 100644index 0000000000..cffa77a0cf--- /dev/null+++ b/packages/content-engine/src/markdown-ast.ts@@ -0,0 +1,52 @@+import remarkFrontmatter from "remark-frontmatter";+import remarkGfm from "remark-gfm";+import remarkMdx, { type Options as RemarkMdxOptions } from "remark-mdx";+import remarkParse from "remark-parse";+import { unified } from "unified";++export type SyntaxTreeNode = {+ type: string;+ children?: unknown;+ position?: unknown;+ data?: unknown;+ [key: string]: unknown;+};++export const isSyntaxTreeNode = (value: unknown): value is SyntaxTreeNode =>+ typeof value === "object" &&+ value !== null &&+ "type" in value &&+ typeof value.type === "string";++export const getSyntaxTreeChildren = (node: SyntaxTreeNode) => {+ if (Array.isArray(node.children) === false) {+ return [];+ }+ return node.children.filter(isSyntaxTreeNode);+};++const createMarkdownAstParser = () =>+ unified().use(remarkParse).use(remarkFrontmatter, ["yaml"]).use(remarkGfm);++const markdownAstParser = createMarkdownAstParser();+// Match standalone Webstudio JSX. remark-mdx 2 exposes obsolete types but+// uses Acorn 8 at runtime.+const mdxOptions = {+ acornOptions: {+ ecmaVersion: "latest",+ sourceType: "module",+ },+} as unknown as RemarkMdxOptions;+const mdxAstParser = createMarkdownAstParser().use(remarkMdx, mdxOptions);++/**+ * Parses CommonMark, GFM, and frontmatter consistently. MDX syntax additionally+ * interprets HTML-shaped input as JSX.+ */+export const parseMarkdownAst = (+ source: string,+ syntax: "markdown" | "mdx" = "markdown"+): SyntaxTreeNode =>+ (syntax === "mdx" ? mdxAstParser : markdownAstParser).parse(+ source+ ) as SyntaxTreeNode;diff --git a/packages/content-engine/src/markdown-references.ts b/packages/content-engine/src/markdown-references.tsindex ff1adc9a9c..e917844a9c 100644--- a/packages/content-engine/src/markdown-references.ts+++ b/packages/content-engine/src/markdown-references.ts@@ -1,46 +1,15 @@-export type MarkdownAssetReference = {+import { mergeAssetUrlSuffix } from "./asset-value-references";+import type { ResolvedAssetReference } from "./asset-reference-utils";++export type MarkdownAssetReference = ResolvedAssetReference & {start: number;end: number;- assetId: string;- suffix?: string;};export type MarkdownAssetReferences = Readonly<Record<string, readonly MarkdownAssetReference[]>>;-const appendMarkdownReferenceSuffix = (- assetUrl: string,- suffix: string | undefined-) => {- if (suffix === undefined || suffix.length === 0) {- return assetUrl;- }- const base = new URL("https://content.webstudio.invalid/__assets__/");- const target = new URL(assetUrl, base);- const reference = new URL(suffix, base);- for (const [name, value] of reference.searchParams) {- target.searchParams.append(name, value);- }- if (reference.hash !== "") {- target.hash = reference.hash;- }- if (URL.canParse(assetUrl)) {- return target.href;- }- if (assetUrl.startsWith("//")) {- return `//${target.host}${target.pathname}${target.search}${target.hash}`;- }- if (assetUrl.startsWith("/")) {- return `${target.pathname}${target.search}${target.hash}`;- }- const basePath = base.pathname;- const pathname = target.pathname.startsWith(basePath)- ? target.pathname.slice(basePath.length)- : target.pathname;- return `${pathname}${target.search}${target.hash}`;-};-export const rewriteMarkdownAssetReferenceRanges = ({markdown,references,@@ -68,10 +37,7 @@ export const rewriteMarkdownAssetReferenceRanges = ({if (assetUrl === undefined) {continue;}- const resolvedUrl = appendMarkdownReferenceSuffix(- assetUrl,- reference.suffix- );+ const resolvedUrl = mergeAssetUrlSuffix(assetUrl, reference.suffix);result = `${result.slice(0, reference.start)}${resolvedUrl}${result.slice(reference.end)}`;}return result;diff --git a/packages/content-engine/src/markdown.test.ts b/packages/content-engine/src/markdown.test.tsindex 2d2729df59..f9688eb777 100644--- a/packages/content-engine/src/markdown.test.ts+++ b/packages/content-engine/src/markdown.test.ts@@ -215,6 +215,12 @@ describe("Markdown body and excerpt extraction", () => {).toBe("Hello world Use code and links.");});+ test("uses GFM semantics in plain-text excerpts", () => {+ expect(extractMarkdownExcerpt("- [x] Ready\n\n~~obsolete~~")).toBe(+ "Ready obsolete"+ );+ });+test("truncates excerpts at a valid UTF-8 character boundary", () => {expect(extractMarkdownExcerpt("Hello 🌍 world", 10)).toBe("Hello 🌍");expect(diff --git a/packages/content-engine/src/markdown.ts b/packages/content-engine/src/markdown.tsindex 1356d49e5a..967874a4bc 100644--- a/packages/content-engine/src/markdown.ts+++ b/packages/content-engine/src/markdown.ts@@ -1,9 +1,12 @@import { contentEngineLimits } from "./limits";-import remarkParse from "remark-parse";-import { unified } from "unified";import { getUtf8ByteLength, type ByteSource } from "./byte-stream";import { MarkdownMetadataError } from "./markdown-errors";import { extractMarkdownBody } from "./markdown-body";+import {+ getSyntaxTreeChildren,+ parseMarkdownAst,+ type SyntaxTreeNode,+} from "./markdown-ast";export {MarkdownMetadataError,@@ -15,12 +18,6 @@ export {type MarkdownFrontmatter,} from "./frontmatter";-type MarkdownNode = {- type: string;- value?: unknown;- children?: MarkdownNode[];-};-const textNodeTypes = new Set(["text", "inlineCode", "code"]);const separatingNodeTypes = new Set(["paragraph",@@ -31,16 +28,16 @@ const separatingNodeTypes = new Set([]);const markdownToPlainText = (body: string) => {- const tree = unified().use(remarkParse).parse(body) as MarkdownNode;+ const tree = parseMarkdownAst(body);const parts: string[] = [];- const visit = (node: MarkdownNode) => {+ const visit = (node: SyntaxTreeNode) => {if (textNodeTypes.has(node.type) && typeof node.value === "string") {parts.push(node.value);}if (node.type === "html" || node.type === "yaml") {return;}- for (const child of node.children ?? []) {+ for (const child of getSyntaxTreeChildren(node)) {visit(child);}if (separatingNodeTypes.has(node.type)) {diff --git a/packages/content-engine/src/mdx-serialization.ts b/packages/content-engine/src/mdx-serialization.tsnew file mode 100644index 0000000000..dc1ac72460--- /dev/null+++ b/packages/content-engine/src/mdx-serialization.ts@@ -0,0 +1,259 @@+import {+ defaultHandlers,+ toMdast,+ type Handle,+ type NodeHandle,+} from "hast-util-to-mdast";+import { gfmToMarkdown } from "mdast-util-gfm";+import { mdxExpressionToMarkdown } from "mdast-util-mdx-expression";+import {+ mdxJsxToMarkdown,+ type MdxJsxAttribute,+ type MdxJsxFlowElement,+ type MdxJsxTextElement,+} from "mdast-util-mdx-jsx";+import { toMarkdown } from "mdast-util-to-markdown";+import { serializeMarkdownFrontmatter } from "./frontmatter";+import type {+ MdxAuthoredNode,+ MdxAuthoredProp,+ MdxDocument,+ MdxMarkdownListItem,+ MdxMode,+} from "./mdx";+import {+ assertUniqueAttributeNames,+ mapAttributeNames,+} from "./jsx-attributes";++type SerializationNode = {+ type: string;+ tagName?: string;+ properties?: Record<string, unknown>;+ value?: string;+ children?: SerializationNode[];+ data?: {+ listItem?: MdxMarkdownListItem;+ mode?: MdxMode;+ props?: readonly MdxAuthoredProp[];+ propsUseJsxNames?: boolean;+ rawText?: string;+ rawSource?: string;+ };+};++const protectTextWhitespace = (value: string) =>+ value.replace(/[\t\n\v\f\r ]/g, "\uE000");++const toHastProperties = (props: readonly MdxAuthoredProp[]) =>+ Object.fromEntries(+ mapAttributeNames({+ attributes: props.map(({ name, value }) => ({+ name,+ value:+ name === "class" && typeof value === "string"+ ? value.split(" ")+ : value,+ })),+ direction: "instance-to-jsx",+ acceptsHtmlAttributes: true,+ }).map(({ name, value }) => [name, value])+ );++const toTextNode = (+ value: string,+ protectWhitespace = true+): SerializationNode =>+ protectWhitespace+ ? {+ type: "text",+ value: protectTextWhitespace(value),+ data: { rawText: value },+ }+ : { type: "text", value };++const toWebstudioElement = ({+ mode,+ props,+ children,+ propsUseJsxNames,+}: {+ mode: MdxMode;+ props: readonly MdxAuthoredProp[];+ children: readonly MdxAuthoredNode[];+ propsUseJsxNames: boolean;+}): SerializationNode => ({+ type: "element",+ tagName: "ws.element",+ properties: {},+ children: children.map((child) => toSerializationNode(child)),+ data: { mode, props, propsUseJsxNames },+});++const toSerializationNode = (+ node: MdxAuthoredNode,+ hastPreservesWhitespace = false+): SerializationNode => {+ if (node.type === "text") {+ return toTextNode(node.value, hastPreservesWhitespace === false);+ }+ if (node.type === "comment") {+ return { type: "comment", value: node.value, data: { mode: node.mdxMode } };+ }+ if (node.type === "opaque") {+ return {+ type: "opaque",+ value: node.value,+ data: { mode: node.mdxMode, rawSource: node.value },+ };+ }+ if (node.type === "template") {+ return toWebstudioElement({+ mode: node.mdxMode,+ props: [{ name: "ws:name", value: node.name }, ...node.props],+ children: node.children,+ propsUseJsxNames: true,+ });+ }+ if (node.syntax === "mdx") {+ return toWebstudioElement({+ mode: node.mdxMode,+ props: [{ name: "ws:tag", value: node.tag }, ...node.props],+ children: node.children,+ propsUseJsxNames: false,+ });+ }++ let children = node.children.map((child) =>+ toSerializationNode(+ child,+ hastPreservesWhitespace || node.preserveTextWhitespace === true+ )+ );+ if (+ node.markdownListItem?.checked !== undefined &&+ node.markdownListItem.spread === false+ ) {+ children = [{ type: "element", tagName: "p", properties: {}, children }];+ }+ return {+ type: "element",+ tagName: node.tag,+ properties: toHastProperties(node.props),+ children,+ data:+ node.markdownListItem === undefined+ ? undefined+ : { listItem: node.markdownListItem },+ };+};++const getSerializationData = (node: { data?: unknown }) =>+ node.data as SerializationNode["data"];++const mapWebstudioElement: Handle = (state, node) => {+ const data = getSerializationData(node);+ const props = data?.props ?? [];+ const mappedProps =+ data?.propsUseJsxNames === true+ ? props+ : mapAttributeNames({+ attributes: props,+ direction: "instance-to-jsx",+ acceptsHtmlAttributes: true,+ });+ assertUniqueAttributeNames(mappedProps);+ const attributes: MdxJsxAttribute[] = mappedProps.map((prop) => ({+ type: "mdxJsxAttribute",+ name: prop.name,+ value: prop.value === true ? null : prop.value,+ }));+ const children = state.all(node as never);+ if (data?.mode === "text") {+ return {+ type: "mdxJsxTextElement",+ name: "ws.element",+ attributes,+ children,+ } as MdxJsxTextElement;+ }+ return {+ type: "mdxJsxFlowElement",+ name: "ws.element",+ attributes,+ children: state.toFlow(children),+ } as MdxJsxFlowElement;+};++const mapComment: NodeHandle = (_state, node) => ({+ type:+ getSerializationData(node)?.mode === "text"+ ? "mdxTextExpression"+ : "mdxFlowExpression",+ value: typeof node.value === "string" ? node.value : "",+});++const mapText: NodeHandle = (_state, node) => ({+ type: "text",+ value:+ getSerializationData(node)?.rawText ??+ (typeof node.value === "string" ? node.value : ""),+});++const mapOpaque: NodeHandle = (_state, node) => ({+ type: "html",+ value: getSerializationData(node)?.rawSource ?? "",+});++const mapListItem: Handle = (state, node) => {+ const result = defaultHandlers.li(state, node);+ const listItem = getSerializationData(node)?.listItem;+ if (+ listItem !== undefined &&+ result !== undefined &&+ Array.isArray(result) === false &&+ result.type === "listItem"+ ) {+ result.spread = listItem.spread;+ }+ return result;+};++const serializeFrontmatter = (document: MdxDocument, hasBody: boolean) => {+ if (document.frontmatter.authoredSource !== undefined) {+ const source = document.frontmatter.authoredSource;+ return hasBody && source.endsWith("\n") === false ? `${source}\n` : source;+ }+ if (+ document.frontmatter.sourceRange === undefined &&+ Object.keys(document.frontmatter.properties).length === 0+ ) {+ return "";+ }+ return serializeMarkdownFrontmatter(document.frontmatter.properties);+};++export const serializeMdxDocument = (document: MdxDocument) => {+ const hast = {+ type: "root",+ children: document.children.map((node) => toSerializationNode(node)),+ } as Parameters<typeof toMdast>[0];+ const mdast = toMdast(hast, {+ document: true,+ handlers: { li: mapListItem, "ws.element": mapWebstudioElement },+ nodeHandlers: { comment: mapComment, opaque: mapOpaque, text: mapText },+ });+ const body = toMarkdown(mdast, {+ bullet: "-",+ bulletOther: "*",+ bulletOrderedOther: ")",+ emphasis: "_",+ extensions: [+ gfmToMarkdown(),+ mdxExpressionToMarkdown,+ mdxJsxToMarkdown({ quote: '"' }),+ ],+ fences: true,+ });+ return serializeFrontmatter(document, body !== "") + body;+};diff --git a/packages/content-engine/src/mdx.test.ts b/packages/content-engine/src/mdx.test.tsnew file mode 100644index 0000000000..d41e3c51a5--- /dev/null+++ b/packages/content-engine/src/mdx.test.ts@@ -0,0 +1,1218 @@+import { describe, expect, test } from "vitest";+import { resolveAssetValueReferences } from "./asset-value-references";+import { parseMarkdownAst } from "./markdown-ast";+import {+ createMdxCodeBlock,+ createMdxSourceDiagnostics,+ discoverMdxAssetReferences,+ MdxDocumentError,+ parseMdxDocument,+ parseMdxDocumentRecovering,+ preferMarkdownSyntax,+ readMdxCodeBlock,+ replaceMdxFrontmatter,+ rewriteMdxAssetReferences,+ serializeMdxDocument,+ type MdxAuthoredNode,+} from "./mdx";++test("creates and reads canonical fenced code blocks", async () => {+ const node = createMdxCodeBlock({+ value: "const ready = true;",+ language: "javascript",+ });+ const source = serializeMdxDocument({+ frontmatter: { properties: {} },+ children: [node],+ });+ const document = await parseMdxDocument({ source });++ expect(source).toBe("```javascript\nconst ready = true;\n```\n");+ expect(readMdxCodeBlock(document.children[0]!)).toEqual({+ value: "const ready = true;",+ language: "javascript",+ });+});++test("rewrites Markdown, MDX, and frontmatter Asset references together", async () => {+ const rewritten = await rewriteMdxAssetReferences({+ source: [+ "---",+ "hero: images/hero.png?width=1200",+ "---",+ "",+ "",+ "",+ '<ws.element ws:tag="img" src="images/hero.png" />',+ ].join("\n"),+ sourcePath: "article.mdx",+ assetPaths: new Map([["hero", "images/hero.png"]]),+ replacementPaths: new Map([["hero", "hero_1.png"]]),+ });++ expect(rewritten).toContain("hero: hero_1.png?width=1200");+ expect(rewritten).toContain("");+ expect(rewritten).toContain('src="hero_1.png"');+});++test("preserves authored frontmatter during body-only Asset rewrites", async () => {+ const frontmatter = `---+# keep formatting+title: 'Example'+---+`;+ const rewritten = await rewriteMdxAssetReferences({+ source: `${frontmatter}`,+ sourcePath: "article.mdx",+ assetPaths: new Map([["hero", "images/hero.png"]]),+ replacementPaths: new Map([["hero", "hero_1.png"]]),+ });++ expect(rewritten).toBe(`${frontmatter}\n`);+});++test("maps recoverable and unrecoverable MDX failures consistently", () => {+ const sourceRange = {+ start: { line: 2, column: 3, offset: 5 },+ end: { line: 2, column: 8, offset: 10 },+ };+ expect(+ createMdxSourceDiagnostics([+ new MdxDocumentError({+ code: "unsafe-mdx",+ message: "Unsupported expression",+ reason: "Executable expressions are not supported",+ nodeType: "mdxTextExpression",+ sourceRange,+ }),+ new MdxDocumentError({+ code: "invalid-mdx",+ message: "Unexpected closing tag",+ sourceRange,+ }),+ ])+ ).toEqual([+ {+ code: "unsafe-mdx",+ severity: "warning",+ message: "Executable expressions are not supported",+ reason: "Executable expressions are not supported",+ nodeType: "mdxTextExpression",+ sourceRange,+ },+ {+ code: "invalid-mdx",+ severity: "error",+ message: "Unexpected closing tag",+ sourceRange,+ },+ ]);+});++const omitSourceRanges = (value: unknown): unknown => {+ if (Array.isArray(value)) {+ return value.map(omitSourceRanges);+ }+ if (typeof value !== "object" || value === null) {+ return value;+ }+ return Object.fromEntries(+ Object.entries(value).flatMap(([key, item]) =>+ key === "sourceRange" ? [] : [[key, omitSourceRanges(item)]]+ )+ );+};++const forceGenericMdx = (node: MdxAuthoredNode): MdxAuthoredNode => {+ if (+ node.type === "text" ||+ node.type === "comment" ||+ node.type === "opaque"+ ) {+ return node;+ }+ if (node.type === "template") {+ return { ...node, children: node.children.map(forceGenericMdx) };+ }+ return {+ ...node,+ syntax: "mdx",+ mdxMode: "flow",+ children: node.children.map(forceGenericMdx),+ };+};++describe("parseMdxDocument", () => {+ test("parses Markdown-only input identically through Markdown and MDX", () => {+ const source = `---+title: Shared grammar+---+# Heading *with emphasis*++Paragraph with **strong**, ~~deleted~~, [inline](/docs), [reference][docs], and https://example.com.++> Blockquote++- [x] Task+- Item++1. Ordered+2. List++| Name | Ready |+| :--- | ---: |+| Ada | Yes |++\`inline code\`++\`\`\`ts+const ready = true;+\`\`\`++++---++[docs]: /guide "Guide"+`;++ expect(parseMarkdownAst(source, "mdx")).toEqual(parseMarkdownAst(source));+ });++ test("parses frontmatter and semantic Markdown with source ranges", async () => {+ const document = await parseMdxDocument({+ source: `---+title: Hello+author:+ $ref: ./author.json+---+# Hello **world**++[Read more](/docs)+`,+ });++ expect(document.frontmatter).toEqual({+ properties: {+ title: "Hello",+ author: { $ref: "./author.json" },+ },+ authoredSource: `---+title: Hello+author:+ $ref: ./author.json+---+`,+ sourceRange: {+ start: { line: 1, column: 1, offset: 0 },+ end: { line: 5, column: 4, offset: 50 },+ },+ });+ expect(document.children).toEqual([+ {+ type: "element",+ syntax: "markdown",+ tag: "h1",+ props: [],+ children: [+ {+ type: "text",+ value: "Hello ",+ sourceRange: {+ start: { line: 6, column: 3, offset: 53 },+ end: { line: 6, column: 9, offset: 59 },+ },+ },+ {+ type: "element",+ syntax: "markdown",+ tag: "strong",+ props: [],+ children: [+ expect.objectContaining({ type: "text", value: "world" }),+ ],+ sourceRange: {+ start: { line: 6, column: 9, offset: 59 },+ end: { line: 6, column: 18, offset: 68 },+ },+ },+ ],+ sourceRange: {+ start: { line: 6, column: 1, offset: 51 },+ end: { line: 6, column: 18, offset: 68 },+ },+ },+ {+ type: "element",+ syntax: "markdown",+ tag: "p",+ props: [],+ children: [+ {+ type: "element",+ syntax: "markdown",+ tag: "a",+ props: [{ name: "href", value: "/docs" }],+ children: [+ expect.objectContaining({ type: "text", value: "Read more" }),+ ],+ sourceRange: {+ start: { line: 8, column: 1, offset: 70 },+ end: { line: 8, column: 19, offset: 88 },+ },+ },+ ],+ sourceRange: {+ start: { line: 8, column: 1, offset: 70 },+ end: { line: 8, column: 19, offset: 88 },+ },+ },+ ]);+ });++ test("maps GFM tables and inline marks to semantic elements", async () => {+ const document = await parseMdxDocument({+ source: `| Name | Ready |+| :--- | ---: |+| **Ada** | ~~No~~ |+`,+ });++ expect(document.children[0]).toMatchObject({+ type: "element",+ tag: "table",+ children: [+ {+ type: "element",+ tag: "thead",+ children: [+ {+ type: "element",+ tag: "tr",+ children: [+ {+ type: "element",+ tag: "th",+ props: [{ name: "align", value: "left" }],+ },+ {+ type: "element",+ tag: "th",+ props: [{ name: "align", value: "right" }],+ },+ ],+ },+ ],+ },+ {+ type: "element",+ tag: "tbody",+ children: [+ {+ type: "element",+ tag: "tr",+ children: [+ {+ type: "element",+ tag: "td",+ children: [{ type: "element", tag: "strong" }],+ },+ {+ type: "element",+ tag: "td",+ children: [{ type: "element", tag: "del" }],+ },+ ],+ },+ ],+ },+ ],+ });+ });++ test("parses generic elements, template usages, and nested Markdown", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:tag="section" data-kind="hero" hidden>+ <ws.element ws:name="Hero Card" tone="quiet">+ ## Nested title+ </ws.element>+</ws.element>+`,+ });++ expect(document.children).toEqual([+ expect.objectContaining({+ type: "element",+ syntax: "mdx",+ mdxMode: "flow",+ tag: "section",+ props: [+ expect.objectContaining({ name: "data-kind", value: "hero" }),+ expect.objectContaining({ name: "hidden", value: true }),+ ],+ children: [+ expect.objectContaining({+ type: "template",+ mdxMode: "flow",+ name: "Hero Card",+ props: [expect.objectContaining({ name: "tone", value: "quiet" })],+ children: [expect.objectContaining({ type: "element", tag: "h2" })],+ }),+ ],+ }),+ ]);+ });++ test("preserves non-executable MDX comments", async () => {+ const document = await parseMdxDocument({+ source: `{/* keep this note */}++<ws.element ws:tag="p">Text {/* inline note */}</ws.element>+`,+ });++ expect(document.children).toEqual([+ expect.objectContaining({+ type: "comment",+ mdxMode: "flow",+ value: "/* keep this note */",+ }),+ expect.objectContaining({+ type: "element",+ tag: "p",+ children: [+ expect.objectContaining({ type: "text", value: "Text " }),+ expect.objectContaining({+ type: "comment",+ mdxMode: "text",+ value: "/* inline note */",+ }),+ ],+ }),+ ]);+ });++ test("resolves reference-style links and images", async () => {+ const document = await parseMdxDocument({+ source: `[Read][docs] and ![Cover][image]++[docs]: /guide "Guide"+[image]: /cover.png+`,+ });++ expect(document.children[0]).toMatchObject({+ type: "element",+ tag: "p",+ children: [+ {+ type: "element",+ tag: "a",+ props: [+ { name: "href", value: "/guide" },+ { name: "title", value: "Guide" },+ ],+ },+ { type: "text", value: " and " },+ {+ type: "element",+ tag: "img",+ props: [+ { name: "src", value: "/cover.png" },+ { name: "alt", value: "Cover" },+ ],+ },+ ],+ });+ });++ test("preserves tight and loose list rendering semantics", async () => {+ const tight = await parseMdxDocument({ source: "- one\n- two\n" });+ const loose = await parseMdxDocument({ source: "- one\n\n- two\n" });++ expect(tight.children[0]).toMatchObject({+ type: "element",+ tag: "ul",+ children: [+ {+ type: "element",+ tag: "li",+ children: [{ type: "text", value: "one" }],+ },+ {+ type: "element",+ tag: "li",+ children: [{ type: "text", value: "two" }],+ },+ ],+ });+ expect(loose.children[0]).toMatchObject({+ type: "element",+ tag: "ul",+ children: [+ {+ type: "element",+ tag: "li",+ children: [{ type: "element", tag: "p" }],+ },+ {+ type: "element",+ tag: "li",+ children: [{ type: "element", tag: "p" }],+ },+ ],+ });+ });++ test("preserves standard GFM output details", async () => {+ const document = await parseMdxDocument({+ source: `[missing][reference]++- [x] Done++\`\`\`js+const ready = true;+\`\`\`+`,+ });++ expect(document.children).toMatchObject([+ {+ type: "element",+ tag: "p",+ children: [{ type: "text", value: "[missing][reference]" }],+ },+ {+ type: "element",+ tag: "ul",+ props: [{ name: "class", value: "contains-task-list" }],+ children: [+ {+ type: "element",+ syntax: "markdown",+ tag: "li",+ props: [{ name: "class", value: "task-list-item" }],+ markdownListItem: { checked: true, spread: false },+ children: [+ { type: "element", tag: "input" },+ { type: "text", value: " " },+ { type: "text", value: "Done" },+ ],+ },+ ],+ },+ {+ type: "element",+ tag: "pre",+ children: [+ {+ type: "element",+ tag: "code",+ props: [{ name: "class", value: "language-js" }],+ children: [{ type: "text", value: "const ready = true;\n" }],+ },+ ],+ },+ ]);+ });++ test("discovers and rewrites frontmatter and authored prop Asset references", async () => {+ const document = await parseMdxDocument({+ source: `---+cover: ./cover.png?size=2+---+++<ws.element ws:name="Card" poster="./video.jpg">+ Text containing ./ignored.png+</ws.element>+`,+ });+ const references = discoverMdxAssetReferences({+ document,+ sourcePath: "posts/post.mdx",+ assetIdsByPath: new Map([+ ["posts/cover.png", "cover"],+ ["posts/hero.png", "hero"],+ ["posts/video.jpg", "video"],+ ["posts/ignored.png", "ignored"],+ ]),+ });++ expect(references).toEqual([+ {+ path: ["frontmatter", "properties", "cover"],+ assetId: "cover",+ suffix: "?size=2",+ },+ {+ path: ["children", 0, "children", 0, "props", 0, "value"],+ assetId: "hero",+ suffix: "#crop",+ },+ {+ path: ["children", 1, "props", 0, "value"],+ assetId: "video",+ },+ ]);++ expect(+ resolveAssetValueReferences({+ value: document,+ references,+ assetUrls: {+ cover: "/assets/cover.png",+ hero: "/assets/hero.png",+ video: "/assets/video.jpg",+ },+ })+ ).toMatchObject({+ frontmatter: { properties: { cover: "/assets/cover.png?size=2" } },+ children: [+ {+ children: [+ {+ props: [+ { name: "src", value: "/assets/hero.png#crop" },+ { name: "alt", value: "Hero" },+ ],+ },+ ],+ },+ { props: [{ name: "poster", value: "/assets/video.jpg" }] },+ ],+ });+ expect(document.frontmatter.properties.cover).toBe("./cover.png?size=2");+ });++ test("serializes supported documents deterministically with semantic round trips", async () => {+ const document = await parseMdxDocument({+ source: `---+title: Example+author:+ $ref: ./author.json+---+# Hello **world**++- [x] Ready++| Name | State |+| --- | --- |+| Ada | ~~Done~~ |++<ws.element ws:tag="section" data-kind="hero">+ <ws.element ws:name="Hero Card" tone="quiet">+ ## Nested title+ </ws.element>+</ws.element>++Paragraph with <ws.element ws:tag="span">inline</ws.element> content.++{/* keep this note */}+`,+ });++ const serialized = serializeMdxDocument(document);+ expect(serializeMdxDocument(document)).toBe(serialized);+ expect(serialized).toContain("$ref: ./author.json");+ expect(serialized.indexOf("title:")).toBeLessThan(+ serialized.indexOf("author:")+ );+ expect(serialized).toContain('<ws.element ws:tag="section"');+ expect(serialized).toContain('<ws.element ws:name="Hero Card"');+ expect(serialized).toContain("{/* keep this note */}");++ const reparsed = await parseMdxDocument({ source: serialized });+ expect(omitSourceRanges(reparsed)).toEqual(omitSourceRanges(document));+ });++ test("preserves authored frontmatter while serializing body edits", async () => {+ const frontmatter = `\uFEFF---\r\n# Keep this comment\r\ntitle: 'Quoted title'\r\ndraft: FALSE\r\n---\r\n`;+ const document = await parseMdxDocument({+ source: `${frontmatter}# Before\n`,+ });++ const source = serializeMdxDocument({+ ...document,+ children: [+ {+ type: "element",+ syntax: "markdown",+ tag: "h1",+ props: [],+ children: [{ type: "text", value: "After" }],+ },+ ],+ });++ expect(source).toBe(`${frontmatter}# After\n`);+ });++ test("separates an added body from frontmatter that ended at EOF", async () => {+ const document = await parseMdxDocument({+ source: "---\ntitle: Empty post\n---",+ });++ const source = serializeMdxDocument({+ ...document,+ children: [+ {+ type: "element",+ syntax: "markdown",+ tag: "p",+ props: [],+ children: [{ type: "text", value: "New body" }],+ },+ ],+ });++ expect(source).toBe("---\ntitle: Empty post\n---\nNew body\n");+ });++ test("prefers Markdown while preserving elements that require JSX", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:tag="p">Read the <ws.element ws:tag="a" href="/guide">guide</ws.element>.</ws.element>++<ws.element ws:tag="ul">+ <ws.element ws:tag="li">First</ws.element>++ <ws.element ws:tag="li">Second</ws.element>+</ws.element>++<ws.element ws:tag="section" data-kind="hero"><ws.element ws:tag="h2">Title</ws.element></ws.element>`,+ });+ const source = serializeMdxDocument(await preferMarkdownSyntax(document));++ expect(source).toContain("Read the [guide](/guide).");+ expect(source).toContain("- First\n- Second");+ expect(source).not.toContain('<ws.element ws:tag="p"');+ expect(source).not.toContain('<ws.element ws:tag="ul"');+ expect(source).toContain('<ws.element ws:tag="section" data-kind="hero">');+ expect(source).toContain("## Title");+ expect(source).not.toContain('<ws.element ws:tag="h2"');+ expect(+ serializeMdxDocument(+ await preferMarkdownSyntax(await parseMdxDocument({ source }))+ )+ ).toBe(source);+ });++ test.each([+ ["ul", "- First\n\n* Second", "- First\n\n* Second\n"],+ ["ol", "1. First\n\n1) Second", "1. First\n\n1) Second\n"],+ ])(+ "keeps adjacent %s elements separate with MDX-safe Markdown",+ async (tag, input, expected) => {+ const document = await parseMdxDocument({ source: input });+ const source = serializeMdxDocument(document);++ expect(source).toBe(expected);+ await expect(parseMdxDocument({ source })).resolves.toMatchObject({+ children: [{ tag }, { tag }],+ });+ }+ );++ test.each([+ `<ws.element ws:tag="a" href="https://google.com/">Test link</ws.element>`,+ `<ws.element ws:tag="a" href="https://google.com/">+Test link+</ws.element>`,+ ])("serializes a standalone Markdown link without JSX", async (source) => {+ const document = await parseMdxDocument({ source });++ expect(serializeMdxDocument(await preferMarkdownSyntax(document))).toBe(+ "[Test link](https://google.com/)\n"+ );+ });++ test("serializes every generic Content Block Markdown template as Markdown", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:tag="p">Paragraph</ws.element>++<ws.element ws:tag="h1">Heading 1</ws.element>++<ws.element ws:tag="h2">Heading 2</ws.element>++<ws.element ws:tag="h3">Heading 3</ws.element>++<ws.element ws:tag="h4">Heading 4</ws.element>++<ws.element ws:tag="h5">Heading 5</ws.element>++<ws.element ws:tag="h6">Heading 6</ws.element>++<ws.element ws:tag="ul"><ws.element ws:tag="li">Unordered</ws.element></ws.element>++<ws.element ws:tag="ol"><ws.element ws:tag="li">Ordered</ws.element></ws.element>++<ws.element ws:tag="a" href="/guide">Link</ws.element>++<ws.element ws:tag="hr" />++<ws.element ws:tag="blockquote">Quote</ws.element>`,+ });++ const source = serializeMdxDocument(await preferMarkdownSyntax(document));++ expect(source).not.toContain("<ws.element");+ expect(source).toContain("# Heading 1");+ expect(source).toContain("###### Heading 6");+ expect(source).toContain("- Unordered");+ expect(source).toContain("1. Ordered");+ expect(source).toContain("[Link](/guide)");+ expect(source).toContain("> Quote");+ });++ test("canonicalizes every Markdown-native element without JSX", async () => {+ const markdown = `# Heading 1++## Heading 2++### Heading 3++#### Heading 4++##### Heading 5++###### Heading 6++Paragraph with **strong**, _emphasis_, ~~deleted~~, [link](/guide), , and \`code\`.\\+Next line.++> Quote++- Unordered++1. Ordered++- [x] Task++---++\`\`\`js+const ready = true;+\`\`\`++| Name | Ready |+| :--- | ---: |+| Ada | Yes |+`;+ const document = await parseMdxDocument({ source: markdown });+ const genericDocument = {+ ...document,+ children: document.children.map(forceGenericMdx),+ };++ const source = serializeMdxDocument(+ await preferMarkdownSyntax(genericDocument)+ );++ expect(source).not.toContain("<ws.element");+ expect(omitSourceRanges(await parseMdxDocument({ source }))).toEqual(+ omitSourceRanges(document)+ );+ });++ test.each([+ ["blockquote", "> Quote\n"],+ ["break", "First\\\nSecond\n"],+ ["code", "```js\nconst ready = true;\n```\n"],+ ["definition", "[Guide][guide]\n\n[guide]: /guide\n"],+ ["emphasis", "*Emphasis*\n"],+ ["heading", "# Heading\n"],+ ["image", "\n"],+ ["image reference", "![Image][image]\n\n[image]: /image.png\n"],+ ["inline code", "`const ready = true`\n"],+ ["link", "[Guide](/guide)\n"],+ ["link reference", "[Guide][guide]\n\n[guide]: /guide\n"],+ ["list", "- First\n- Second\n"],+ ["list item", "- Item\n"],+ ["paragraph", "Paragraph\n"],+ ["strong", "**Strong**\n"],+ ["thematic break", "***\n"],+ ])(+ "converts the core Markdown %s construct without JSX",+ async (_name, source) => {+ const document = await parseMdxDocument({ source });+ const genericDocument = {+ ...document,+ children: document.children.map(forceGenericMdx),+ };+ const markdown = serializeMdxDocument(+ await preferMarkdownSyntax(genericDocument)+ );++ expect(markdown).not.toContain("<ws.element");+ expect(+ omitSourceRanges(await parseMdxDocument({ source: markdown }))+ ).toEqual(omitSourceRanges(document));+ }+ );++ test("preserves elements that Markdown cannot represent losslessly", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:tag="input" type="checkbox" disabled />++<ws.element ws:tag="code" class="custom">+ <ws.element ws:tag="strong">Nested</ws.element>+</ws.element>++<ws.element ws:tag="a" href="/guide" target="_blank">Guide</ws.element>++<ws.element ws:tag="ul">+ <ws.element ws:tag="div">Not a list item</ws.element>+</ws.element>++<ws.element ws:tag="p" />++<ws.element ws:tag="table" />++<ws.element ws:tag="li">Standalone item</ws.element>++<ws.element ws:tag="div">line+next</ws.element>++<ws.element ws:tag="div">before {/* inline */} after</ws.element>++<ws.element ws:tag="pre"><ws.element ws:tag="code" /></ws.element>++<ws.element ws:tag="ol" start="007">+ <ws.element ws:tag="li">Leading zero</ws.element>+</ws.element>++<ws.element ws:tag="table">+ <ws.element ws:tag="thead">+ <ws.element ws:tag="tr">+ <ws.element ws:tag="th">+ <ws.element ws:tag="p">Invalid cell block</ws.element>+ </ws.element>+ </ws.element>+ </ws.element>+</ws.element>+`,+ });++ const serialized = serializeMdxDocument(document);+ const reparsed = await parseMdxDocument({ source: serialized });+ expect(omitSourceRanges(reparsed)).toEqual(omitSourceRanges(document));++ const preferred = serializeMdxDocument(+ await preferMarkdownSyntax(document)+ );+ expect(preferred).toContain(+ '<ws.element ws:tag="ul">\n <ws.element ws:tag="div">Not a list item</ws.element>\n</ws.element>'+ );+ expect(preferred).toContain(+ '<ws.element ws:tag="a" href="/guide" target="_blank">Guide</ws.element>'+ );+ expect(preferred).toContain('<ws.element ws:tag="ol" start="007">');+ });++ test.each([+ ["empty content", ""],+ ["ordered task lists", "1. [x] Done\n2. [ ] Pending\n"],+ ["loose task lists", "- [x] Done\n\n- [ ] Pending\n"],+ ["nested lists", "- Parent\n 1. Child\n"],+ ["ordered list starts", "7. Seven\n8. Eight\n"],+ ["fenced code without a language", "```\nvalue\n```\n"],+ ])("round trips %s", async (_name, source) => {+ const document = await parseMdxDocument({ source });+ const reparsed = await parseMdxDocument({+ source: serializeMdxDocument(document),+ });++ expect(omitSourceRanges(reparsed)).toEqual(omitSourceRanges(document));+ });++ test("preserves template prop names while normalizing HTML prop names", async () => {+ const source = serializeMdxDocument({+ frontmatter: { properties: {} },+ children: [+ {+ type: "template",+ name: "Card",+ props: [+ { name: "className", value: "featured" },+ { name: "htmlFor", value: "title" },+ { name: "tabIndex", value: "0" },+ { name: "readOnly", value: true },+ ],+ children: [],+ mdxMode: "flow",+ },+ ],+ });++ expect(source).toBe(+ '<ws.element ws:name="Card" className="featured" htmlFor="title" tabIndex="0" readOnly />\n'+ );+ expect(omitSourceRanges(await parseMdxDocument({ source }))).toMatchObject({+ frontmatter: { properties: {} },+ children: [+ {+ type: "template",+ props: [+ { name: "className", value: "featured" },+ { name: "htmlFor", value: "title" },+ { name: "tabIndex", value: "0" },+ { name: "readOnly", value: true },+ ],+ },+ ],+ });++ const element = await parseMdxDocument({+ source:+ '<ws.element ws:tag="label" className="featured" htmlFor="title" tabIndex="0" />',+ });+ expect(omitSourceRanges(element.children[0])).toMatchObject({+ type: "element",+ props: [+ { name: "class", value: "featured" },+ { name: "for", value: "title" },+ { name: "tabindex", value: "0" },+ ],+ });+ });++ test("roundtrips template JSX prop names without component metadata", async () => {+ const source = '<ws.element ws:name="Card" class="featured" />\n';+ const document = await parseMdxDocument({ source });++ expect(serializeMdxDocument(document)).toBe(source);+ });++ test("preserves template prop aliases for metadata-aware materialization", async () => {+ const source =+ '<ws.element ws:name="Card" class="legacy" className="canonical" />\n';+ const document = await parseMdxDocument({ source });++ expect(document.children[0]).toMatchObject({+ type: "template",+ props: [+ { name: "class", value: "legacy" },+ { name: "className", value: "canonical" },+ ],+ });+ expect(serializeMdxDocument(document)).toBe(source);+ });++ test.each([+ ['<ws.element ws:tag="script">alert(1)</ws.element>', "unsafe tag"],+ ['<ws.element ws:name="Card" ws:tag="div" />', "conflicting selectors"],+ [+ '<ws.element ws:tag="div" class="one" className="two" />',+ "conflicting property names",+ ],+ ['<ws.element ws:tag="div" onclick="alert(1)" />', "event prop"],+ ['<ws.element ws:tag="iframe" srcdoc="<script />" />', "srcdoc"],+ ['<ws.element ws:tag="a" href="javascript:alert(1)" />', "unsafe link URL"],+ [+ '<ws.element ws:tag="img" src="data:text/html,<script />" />',+ "unsafe source URL",+ ],+ [+ '<ws.element ws:tag="use" xlinkHref="javascript:alert(1)" />',+ "unsafe SVG link URL",+ ],+ ["[unsafe](javascript:alert(1))", "unsafe Markdown link URL"],+ ["", "unsafe Markdown image URL"],+ [+ "[unsafe][target]\n\n[target]: javascript:alert(1)",+ "unsafe reference URL",+ ],+ ])("rejects %s", async (source) => {+ await expect(parseMdxDocument({ source })).rejects.toMatchObject({+ code: "unsafe-mdx",+ sourceRange: expect.objectContaining({+ start: expect.objectContaining({ line: 1 }),+ }),+ } satisfies Partial<MdxDocumentError>);+ });++ test("rejects documents that exceed structural limits", async () => {+ const deepSource =+ "<ws.element>".repeat(101) + "text" + "</ws.element>".repeat(101);+ const nodeHeavySource = "paragraph\n\n".repeat(10_001);+ const propHeavySource = `<ws.element ${Array.from(+ { length: 4_001 },+ (_, index) => `data-${index}="value"`+ ).join(" ")} />`;++ for (const source of [deepSource, nodeHeavySource, propHeavySource]) {+ await expect(parseMdxDocument({ source })).rejects.toMatchObject({+ code: "invalid-mdx",+ } satisfies Partial<MdxDocumentError>);+ }+ }, 15_000);++ test.each([+ ["imports", 'import Card from "./card"', "mdxjsEsm"],+ ["exports", "export const value = 1", "mdxjsEsm"],+ ["flow expressions", "{call()}", "mdxFlowExpression"],+ ["text expressions", "Hello {name}", "mdxTextExpression"],+ [+ "attribute expressions",+ '<ws.element ws:tag="div" value={1_000} />',+ "mdxJsxAttributeValueExpression",+ ],+ [+ "attribute spreads",+ '<ws.element ws:tag="div" {...props} />',+ "mdxJsxExpressionAttribute",+ ],+ ["arbitrary components", "<Card />", "mdxJsxFlowElement"],+ ["HTML-looking JSX", "<div>Unsafe</div>", "mdxJsxTextElement"],+ ])("rejects %s", async (_name, source, nodeType) => {+ await expect(parseMdxDocument({ source })).rejects.toMatchObject({+ code: "unsafe-mdx",+ nodeType,+ sourceRange: expect.objectContaining({+ start: expect.objectContaining({ line: 1 }),+ }),+ } satisfies Partial<MdxDocumentError>);+ });++ test("reports malformed JSX as invalid MDX", async () => {+ await expect(+ parseMdxDocument({ source: "<ws.element>" })+ ).rejects.toMatchObject({+ code: "invalid-mdx",+ sourceRange: {+ start: { line: 1, column: 1 },+ end: { line: 1, column: 1 },+ },+ } satisfies Partial<MdxDocumentError>);+ });+});++describe("replaceMdxFrontmatter", () => {+ test("updates only frontmatter and preserves the body byte-for-byte", async () => {+ const body = `# Heading\n\n<ws.element ws:name="Hero Card">\n Body\n</ws.element>\n`;+ const source = `---\ntitle: Before\n---\n\n${body}`;++ expect(+ await replaceMdxFrontmatter({+ source,+ properties: { nested: [1, true], title: "After" },+ })+ ).toBe(`---\nnested:\n - 1\n - true\ntitle: After\n---\n\n${body}`);+ });++ test("prepends frontmatter without rewriting a document body", async () => {+ const source = "Paragraph \nwith hard break\n";++ expect(+ await replaceMdxFrontmatter({ source, properties: { draft: false } })+ ).toBe(`---\ndraft: false\n---\n\n${source}`);+ });++ test("updates frontmatter even when the MDX body is structurally invalid", async () => {+ const body = '<ws.element ws:name="Hero">\n';+ const source = `---\ntitle: Before\n---\n\n${body}`;++ expect(+ await replaceMdxFrontmatter({ source, properties: { title: "After" } })+ ).toBe(`---\ntitle: After\n---\n\n${body}`);+ });++ test("preserves a byte-order mark and non-ASCII body", async () => {+ const source = `\uFEFF---\ntitle: Olá\n---\n\nOlá 👋\n`;++ expect(+ await replaceMdxFrontmatter({ source, properties: { title: "Até" } })+ ).toBe(`\uFEFF---\ntitle: Até\n---\n\nOlá 👋\n`);+ });+});++describe("parseMdxDocumentRecovering", () => {+ test("ignores invalid JSX properties without dropping the element", async () => {+ const source =+ '<ws.element ws:tag="a" href="/safe" onclick="alert(1)">Kept</ws.element>\n';++ const recovered = await parseMdxDocumentRecovering({ source });++ expect(recovered).toMatchObject({+ status: "parsed",+ document: {+ children: [+ {+ type: "element",+ tag: "a",+ props: [{ name: "href", value: "/safe" }],+ children: [{ type: "text", value: "Kept" }],+ },+ ],+ },+ diagnostics: [+ expect.objectContaining({+ code: "unsafe-mdx",+ reason: "MDX JSX prop onclick is not supported",+ }),+ ],+ });+ });++ test("preserves an unsafe subtree while continuing with valid siblings", async () => {+ const source = "# Before\n\n{danger()}\n\n# After\n";++ const result = await parseMdxDocumentRecovering({ source });++ expect(result.status).toBe("parsed");+ if (result.status !== "parsed") {+ throw new Error("Expected a recoverable document");+ }+ expect(result.diagnostics).toHaveLength(1);+ expect(result.document.children.map(({ type }) => type)).toEqual([+ "element",+ "opaque",+ "element",+ ]);+ expect(serializeMdxDocument(result.document)).toBe(source);+ });++ test("keeps a valid body available when frontmatter is invalid", async () => {+ const source = `---+title: [broken+---+# Visible body+`;++ const result = await parseMdxDocumentRecovering({ source });++ expect(result).toMatchObject({+ status: "parsed",+ document: {+ frontmatter: {+ properties: {},+ authoredSource: "---\ntitle: [broken\n---\n",+ },+ children: [+ {+ type: "element",+ syntax: "markdown",+ tag: "h1",+ children: [{ type: "text", value: "Visible body" }],+ },+ ],+ },+ diagnostics: [{ code: "invalid-mdx" }],+ });+ if (result.status !== "parsed") {+ throw new Error("Expected a recoverable body");+ }+ expect(serializeMdxDocument(result.document)).toBe(source);+ });++ test("reports structurally invalid MDX without inventing a document", async () => {+ const result = await parseMdxDocumentRecovering({+ source: "# Before\n\n<ws.element",+ });++ expect(result).toMatchObject({+ status: "unrecoverable",+ diagnostics: [{ code: "invalid-mdx" }],+ });+ });+});diff --git a/packages/content-engine/src/mdx.ts b/packages/content-engine/src/mdx.tsnew file mode 100644index 0000000000..6700def18d--- /dev/null+++ b/packages/content-engine/src/mdx.ts@@ -0,0 +1,1673 @@+import {+ defaultHandlers,+ toHast,+ type Handler,+ type Handlers,+} from "mdast-util-to-hast";+import { parse, postprocess, preprocess } from "micromark";+import { mdxjs } from "micromark-extension-mdxjs";+import {+ discoverAssetValueReferences,+ rewriteAssetValueReferences,+ type AssetValueReference,+} from "./asset-value-references";+import {+ createAssetReferenceResolver,+ createNamedAssetReferenceContext,+} from "./asset-reference-utils";+import { createUniqueAssetIdsByPath } from "./asset-path-resolution";+import { getInstancePropName } from "./jsx-attributes";+import { getUtf8ByteLength } from "./byte-stream";+import {+ extractMarkdownFrontmatter,+ replaceMarkdownFrontmatter,+} from "./frontmatter";+import { contentEngineLimits } from "./limits";+import {+ getSyntaxTreeChildren,+ isSyntaxTreeNode,+ parseMarkdownAst,+ type SyntaxTreeNode,+} from "./markdown-ast";+import { findMarkdownFrontmatter } from "./markdown-scanner";+import { serializeMdxDocument } from "./mdx-serialization";++export type MdxSourcePoint = Readonly<{+ line: number;+ column: number;+ offset?: number;+}>;++export type MdxSourceRange = Readonly<{+ start: MdxSourcePoint;+ end: MdxSourcePoint;+}>;++export type MdxAuthoredProp = Readonly<{+ name: string;+ value: string | true;+ sourceRange?: MdxSourceRange;+}>;++export type MdxMode = "flow" | "text";++export type MdxMarkdownListItem = Readonly<{+ checked?: boolean;+ spread: boolean;+}>;++export type MdxAuthoredNode =+ | Readonly<{+ type: "text";+ value: string;+ sourceRange?: MdxSourceRange;+ }>+ | Readonly<{+ type: "comment";+ value: string;+ mdxMode: MdxMode;+ sourceRange?: MdxSourceRange;+ }>+ | Readonly<{+ type: "opaque";+ value: string;+ mdxMode: MdxMode;+ sourceRange: MdxSourceRange;+ }>+ | Readonly<{+ type: "element";+ syntax: "markdown";+ tag: string;+ props: readonly MdxAuthoredProp[];+ children: readonly MdxAuthoredNode[];+ markdownListItem?: MdxMarkdownListItem;+ preserveTextWhitespace?: true;+ sourceRange?: MdxSourceRange;+ }>+ | Readonly<{+ type: "element";+ syntax: "mdx";+ tag: string;+ props: readonly MdxAuthoredProp[];+ children: readonly MdxAuthoredNode[];+ mdxMode: MdxMode;+ sourceRange?: MdxSourceRange;+ }>+ | Readonly<{+ type: "template";+ name: string;+ props: readonly MdxAuthoredProp[];+ children: readonly MdxAuthoredNode[];+ mdxMode: MdxMode;+ sourceRange?: MdxSourceRange;+ }>;++export type MdxDocument = Readonly<{+ frontmatter: Readonly<{+ properties: Readonly<Record<string, unknown>>;+ /** Exact authored frontmatter envelope, retained while only the body changes. */+ authoredSource?: string;+ sourceRange?: MdxSourceRange;+ }>;+ children: readonly MdxAuthoredNode[];+}>;++export const createMdxCodeBlock = ({+ value,+ language,+}: {+ value: string;+ language?: string;+}): MdxAuthoredNode => ({+ type: "element",+ syntax: "markdown",+ tag: "pre",+ props: [],+ children: [+ {+ type: "element",+ syntax: "markdown",+ tag: "code",+ props:+ language === undefined+ ? []+ : [{ name: "class", value: `language-${language}` }],+ children: [{ type: "text", value: `${value}\n` }],+ preserveTextWhitespace: true,+ },+ ],+});++export const readMdxCodeBlock = (node: MdxAuthoredNode) => {+ if (+ node.type !== "element" ||+ node.syntax !== "markdown" ||+ node.tag !== "pre" ||+ node.props.length !== 0 ||+ node.children.length !== 1+ ) {+ return;+ }+ const code = node.children[0];+ if (+ code?.type !== "element" ||+ code.syntax !== "markdown" ||+ code.tag !== "code" ||+ code.children.length !== 1 ||+ code.children[0]?.type !== "text" ||+ code.props.length > 1+ ) {+ return;+ }+ const className = code.props[0];+ if (+ className !== undefined &&+ (className.name !== "class" ||+ typeof className.value !== "string" ||+ className.value.startsWith("language-") === false)+ ) {+ return;+ }+ const language =+ typeof className?.value === "string"+ ? className.value.slice("language-".length)+ : undefined;+ if (language !== undefined && language.length === 0) {+ return;+ }+ const value = code.children[0].value;+ return {+ value: value.endsWith("\n") ? value.slice(0, -1) : value,+ language,+ };+};++export type MdxDocumentErrorCode = "invalid-mdx" | "unsafe-mdx";++export class MdxDocumentError extends Error {+ readonly code: MdxDocumentErrorCode;+ readonly nodeType?: string;+ readonly reason?: string;+ readonly sourceRange?: MdxSourceRange;++ constructor({+ code,+ message,+ nodeType,+ reason,+ sourceRange,+ cause,+ }: {+ code: MdxDocumentErrorCode;+ message: string;+ nodeType?: string;+ reason?: string;+ sourceRange?: MdxSourceRange;+ cause?: unknown;+ }) {+ super(message, { cause });+ this.name = "MdxDocumentError";+ this.code = code;+ this.nodeType = nodeType;+ this.reason = reason;+ this.sourceRange = sourceRange;+ }+}++export type MdxSourceDiagnostic =+ | Readonly<{+ code: "invalid-mdx";+ severity: "error";+ message: string;+ sourceRange?: MdxSourceRange;+ }>+ | Readonly<{+ code: "unsafe-mdx";+ severity: "warning";+ message: string;+ nodeType?: string;+ reason?: string;+ sourceRange?: MdxSourceRange;+ }>;++/** Maps parser failures to the shared diagnostics contract used by every MDX consumer. */+export const createMdxSourceDiagnostics = (+ errors: readonly MdxDocumentError[]+): MdxSourceDiagnostic[] =>+ errors.map((error) =>+ error.code === "invalid-mdx"+ ? {+ code: error.code,+ severity: "error",+ message: error.message,+ sourceRange: error.sourceRange,+ }+ : {+ code: error.code,+ severity: "warning",+ message: error.reason ?? error.message,+ nodeType: error.nodeType,+ reason: error.reason,+ sourceRange: error.sourceRange,+ }+ );++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === "object" && value !== null;++const toSourcePoint = (value: unknown): MdxSourcePoint | undefined => {+ if (+ isRecord(value) === false ||+ typeof value.line !== "number" ||+ typeof value.column !== "number" ||+ Number.isInteger(value.line) === false ||+ Number.isInteger(value.column) === false ||+ value.line < 1 ||+ value.column < 1+ ) {+ return;+ }+ const point: { line: number; column: number; offset?: number } = {+ line: value.line,+ column: value.column,+ };+ if (+ typeof value.offset === "number" &&+ Number.isInteger(value.offset) &&+ value.offset >= 0+ ) {+ point.offset = value.offset;+ }+ return point;+};++const toSourceRange = (position: unknown): MdxSourceRange | undefined => {+ if (isRecord(position) === false) {+ return;+ }+ const start = toSourcePoint(position.start);+ const end = toSourcePoint(position.end);+ if (start !== undefined && end !== undefined) {+ return { start, end };+ }+};++const addMdxJsxAttributePositions = (root: SyntaxTreeNode, source: string) => {+ if (source.includes("<ws.element") === false) {+ return;+ }+ let ranges: Array<{ start: unknown; end: unknown }>;+ try {+ ranges = postprocess(+ parse({ extensions: [mdxjs()] })+ .document()+ .write(preprocess()(source, undefined, true))+ ).flatMap(([phase, token]) => {+ const tokenType: string = token.type;+ return phase === "enter" &&+ (tokenType === "mdxJsxFlowTagAttribute" ||+ tokenType === "mdxJsxTextTagAttribute" ||+ tokenType === "mdxJsxFlowTagExpressionAttribute" ||+ tokenType === "mdxJsxTextTagExpressionAttribute")+ ? [{ start: token.start, end: token.end }]+ : [];+ });+ } catch {+ // Source validation remains owned by the document parser. Location+ // enrichment must not make otherwise recoverable MDX unrecoverable.+ return;+ }+ const visit = (node: SyntaxTreeNode) => {+ const nodeRange = toSourceRange(node.position);+ if (nodeRange !== undefined && Array.isArray(node.attributes)) {+ let rangeIndex = ranges.findIndex(({ start }) => {+ const point = toSourcePoint(start);+ return (point?.offset ?? -1) >= (nodeRange.start.offset ?? 0);+ });+ for (const attribute of node.attributes) {+ if (isSyntaxTreeNode(attribute) === false || rangeIndex < 0) {+ continue;+ }+ const range = ranges[rangeIndex];+ const end = toSourcePoint(range?.end);+ if (+ range === undefined ||+ end === undefined ||+ (end.offset ?? source.length + 1) >+ (nodeRange.end.offset ?? source.length)+ ) {+ break;+ }+ attribute.position = range;+ rangeIndex += 1;+ }+ }+ for (const child of getSyntaxTreeChildren(node)) {+ visit(child);+ }+ };+ visit(root);+};++const getParserErrorSourceRange = (error: unknown) => {+ if (isRecord(error) === false) {+ return;+ }+ const sourceRange = toSourceRange(error.position);+ if (sourceRange !== undefined) {+ return sourceRange;+ }+ if (typeof error.name !== "string") {+ return;+ }+ const [lineSource, columnSource] = error.name.split(":", 2);+ const line = Number(lineSource);+ const column = Number(columnSource);+ if (+ Number.isInteger(line) === false ||+ Number.isInteger(column) === false ||+ line < 1 ||+ column < 1+ ) {+ return;+ }+ const point = { line, column };+ return { start: point, end: point };+};++const getErrorMessage = (error: unknown) =>+ error instanceof Error ? error.message : String(error);++const throwUnsafeNode = (+ node: SyntaxTreeNode,+ reason: string,+ fallbackNode?: SyntaxTreeNode+): never => {+ throw new MdxDocumentError({+ code: "unsafe-mdx",+ message: reason,+ nodeType: node.type,+ reason,+ sourceRange:+ toSourceRange(node.position) ?? toSourceRange(fallbackNode?.position),+ });+};++const unsupportedElementTags = new Set([+ "base",+ "link",+ "meta",+ "noscript",+ "script",+ "style",+ "template",+ "title",+]);++const urlPropNames = new Set([+ "action",+ "cite",+ "data",+ "formaction",+ "href",+ "poster",+ "src",+ "xlink:href",+ "xlinkhref",+]);++const isSafeStaticUrl = (value: string, propName: string) => {+ let url: URL;+ try {+ url = new URL(value, "https://webstudio.invalid");+ } catch {+ return false;+ }+ if (url.protocol === "http:" || url.protocol === "https:") {+ return true;+ }+ return (+ propName === "href" &&+ (url.protocol === "mailto:" || url.protocol === "tel:")+ );+};++const validateStaticProp = (+ node: SyntaxTreeNode,+ prop: MdxAuthoredProp,+ fallbackNode?: SyntaxTreeNode+) => {+ const normalizedName = prop.name.toLowerCase();+ if (+ normalizedName.startsWith("on") ||+ normalizedName === "srcdoc" ||+ normalizedName === "dangerouslysetinnerhtml" ||+ normalizedName === "srcset"+ ) {+ throwUnsafeNode(+ node,+ `MDX JSX prop ${prop.name} is not supported`,+ fallbackNode+ );+ }+ if (+ urlPropNames.has(normalizedName) &&+ typeof prop.value === "string" &&+ isSafeStaticUrl(prop.value, normalizedName) === false+ ) {+ throwUnsafeNode(+ node,+ `MDX JSX prop ${prop.name} contains an unsafe URL`,+ fallbackNode+ );+ }+};++const validateAstLimits = (root: SyntaxTreeNode) => {+ const pending: Array<{ node: SyntaxTreeNode; depth: number }> = [+ { node: root, depth: 0 },+ ];+ let nodeCount = 0;+ let propCount = 0;+ while (pending.length > 0) {+ const current = pending.pop();+ if (current === undefined) {+ break;+ }+ nodeCount += 1;+ if (nodeCount > contentEngineLimits.mdxNodes) {+ throw new MdxDocumentError({+ code: "invalid-mdx",+ message: "MDX content exceeds the node limit",+ sourceRange: toSourceRange(current.node.position),+ });+ }+ if (current.depth > contentEngineLimits.mdxDepth) {+ throw new MdxDocumentError({+ code: "invalid-mdx",+ message: "MDX content exceeds the nesting limit",+ sourceRange: toSourceRange(current.node.position),+ });+ }+ if (Array.isArray(current.node.attributes)) {+ propCount += current.node.attributes.length;+ if (propCount > contentEngineLimits.mdxProps) {+ throw new MdxDocumentError({+ code: "invalid-mdx",+ message: "MDX content exceeds the prop limit",+ sourceRange: toSourceRange(current.node.position),+ });+ }+ }+ for (const child of getSyntaxTreeChildren(current.node)) {+ pending.push({ node: child, depth: current.depth + 1 });+ }+ }+};++const createElement = ({+ node,+ tag,+ props = [],+ children,+ mdxMode,+ markdownListItem,+ preserveTextWhitespace,+}: {+ node: SyntaxTreeNode;+ tag: string;+ props?: readonly MdxAuthoredProp[];+ children: readonly MdxAuthoredNode[];+ mdxMode?: MdxMode;+ markdownListItem?: MdxMarkdownListItem;+ preserveTextWhitespace?: true;+}): MdxAuthoredNode => {+ const sourceRange = toSourceRange(node.position);+ if (mdxMode !== undefined) {+ return {+ type: "element",+ syntax: "mdx",+ tag,+ props,+ children,+ mdxMode,+ sourceRange,+ };+ }+ return {+ type: "element",+ syntax: "markdown",+ tag,+ props,+ children,+ ...(markdownListItem === undefined ? {} : { markdownListItem }),+ ...(preserveTextWhitespace === undefined ? {} : { preserveTextWhitespace }),+ sourceRange,+ };+};++const getMdxMode = (node: SyntaxTreeNode): MdxMode =>+ node.type === "mdxJsxTextElement" || node.type === "mdxTextExpression"+ ? "text"+ : "flow";++const setHastData = (node: SyntaxTreeNode, data: Record<string, unknown>) => {+ node.data = { ...(isRecord(node.data) ? node.data : {}), ...data };+};++const isCommentExpression = (node: SyntaxTreeNode) => {+ if (isRecord(node.data) === false || isRecord(node.data.estree) === false) {+ return false;+ }+ const { body, comments } = node.data.estree;+ return (+ Array.isArray(body) &&+ body.length === 0 &&+ Array.isArray(comments) &&+ comments.length > 0+ );+};++type MapHastOptions = {+ shouldOmitUnsafePart?: (error: MdxDocumentError) => boolean;+};++const canOmitUnsafePart = (error: unknown, options: MapHastOptions) =>+ error instanceof MdxDocumentError &&+ error.code === "unsafe-mdx" &&+ options.shouldOmitUnsafePart?.(error) === true;++const mapStaticProps = (node: SyntaxTreeNode, options: MapHastOptions = {}) => {+ if (Array.isArray(node.attributes) === false) {+ return [];+ }+ const props: MdxAuthoredProp[] = [];+ const names = new Set<string>();+ for (const attribute of node.attributes) {+ try {+ if (isSyntaxTreeNode(attribute) === false) {+ throwUnsafeNode(node, "MDX JSX contains an invalid attribute");+ }+ if (attribute.type === "mdxJsxExpressionAttribute") {+ throwUnsafeNode(+ attribute,+ "MDX JSX attribute spreads are not supported",+ node+ );+ }+ if (+ attribute.type !== "mdxJsxAttribute" ||+ typeof attribute.name !== "string"+ ) {+ throwUnsafeNode(+ attribute,+ "MDX JSX contains an unsupported attribute",+ node+ );+ }+ if (names.has(attribute.name)) {+ throwUnsafeNode(attribute, "MDX JSX attributes must be unique", node);+ }+ if (isRecord(attribute.value)) {+ throwUnsafeNode(+ attribute.value.type === "mdxJsxAttributeValueExpression"+ ? (attribute.value as SyntaxTreeNode)+ : attribute,+ "MDX JSX attribute expressions are not supported",+ node+ );+ }+ if (attribute.value !== null && typeof attribute.value !== "string") {+ throwUnsafeNode(+ attribute,+ "MDX JSX attribute values must be static",+ node+ );+ }+ const prop = {+ name: attribute.name,+ value: attribute.value === null ? true : attribute.value,+ sourceRange: toSourceRange(attribute.position),+ } as const;+ validateStaticProp(attribute, prop, node);+ names.add(attribute.name);+ props.push(prop);+ } catch (error) {+ if (canOmitUnsafePart(error, options)) {+ continue;+ }+ throw error;+ }+ }+ return props;+};++const mapMdxExpression: Handler = (state, value) => {+ const node = value as SyntaxTreeNode;+ if (isCommentExpression(node) && typeof node.value === "string") {+ const comment = {+ type: "comment",+ value: node.value,+ data: { mdxMode: getMdxMode(node) },+ } as const;+ state.patch(value, comment);+ return comment;+ }+ return throwUnsafeNode(node, "Executable MDX expressions are not supported");+};++const createMdxJsxElementHandler =+ (options: MapHastOptions = {}): Handler =>+ (state, value) => {+ const node = value as SyntaxTreeNode;+ if (node.name !== "ws.element") {+ return throwUnsafeNode(+ node,+ "Only the ws.element component is supported in authored MDX"+ );+ }+ const staticProps = mapStaticProps(node, options);+ const properties = Object.fromEntries(+ staticProps.map((prop) => [prop.name, prop.value])+ );+ const result = state(value, "ws.element", properties, state.all(value));+ if (isSyntaxTreeNode(result)) {+ setHastData(result, {+ mdxMode: getMdxMode(node),+ mdxPropSourceRanges: Object.fromEntries(+ staticProps.flatMap((prop) =>+ prop.sourceRange === undefined+ ? []+ : [[prop.name, prop.sourceRange]]+ )+ ),+ });+ }+ return result;+ };++const mapMdxJsxElement = createMdxJsxElementHandler();++const mapListItem: Handler = (state, value, parent) => {+ const node = value as SyntaxTreeNode;+ const result = defaultHandlers.listItem(state, value, parent);+ if (isSyntaxTreeNode(result)) {+ setHastData(result, {+ markdownListItem: {+ ...(typeof node.checked === "boolean" ? { checked: node.checked } : {}),+ spread:+ node.spread === true ||+ (isSyntaxTreeNode(parent) && parent.spread === true),+ },+ });+ }+ return result;+};++const preserveWhitespace =+ (handler: Handler): Handler =>+ (state, value, parent) => {+ const result = handler(state, value, parent);+ if (isSyntaxTreeNode(result)) {+ setHastData(result, { preserveTextWhitespace: true });+ }+ return result;+ };++const mapParagraph: Handler = (state, value) => {+ const children = getSyntaxTreeChildren(value as SyntaxTreeNode);+ if (children.length === 1 && children[0].type === "mdxJsxTextElement") {+ return state.one(value.children[0], value);+ }+ return defaultHandlers.paragraph(state, value);+};++const rejectUnsupportedNode: Handler = (_state, value) => {+ const node = value as SyntaxTreeNode;+ return throwUnsafeNode(node, `MDX node type ${node.type} is not supported`);+};++const mdxHandlers: Handlers = {+ code: preserveWhitespace(defaultHandlers.code),+ html: rejectUnsupportedNode,+ inlineCode: preserveWhitespace(defaultHandlers.inlineCode),+ mdxFlowExpression: mapMdxExpression,+ mdxJsxFlowElement: mapMdxJsxElement,+ mdxJsxTextElement: mapMdxJsxElement,+ mdxTextExpression: mapMdxExpression,+ mdxjsEsm: rejectUnsupportedNode,+ listItem: mapListItem,+ paragraph: mapParagraph,+};++const createRecoveringHandlers = ({+ source,+ diagnostics,+}: {+ source: string;+ diagnostics: MdxDocumentError[];+}) => {+ const recover =+ (handler: Handler): Handler =>+ (state, value, parent) => {+ try {+ return handler(state, value, parent);+ } catch (error) {+ if (+ error instanceof MdxDocumentError === false ||+ error.code !== "unsafe-mdx"+ ) {+ throw error;+ }+ const node = value as SyntaxTreeNode;+ const sourceRange = error.sourceRange ?? toSourceRange(node.position);+ const start = sourceRange?.start.offset;+ const end = sourceRange?.end.offset;+ if (start === undefined || end === undefined) {+ throw error;+ }+ diagnostics.push(error);+ const opaque = {+ type: "opaque",+ value: source.slice(start, end),+ data: { mdxMode: getMdxMode(node) },+ } as const;+ state.patch(value, opaque as never);+ return opaque as never;+ }+ };+ const shouldOmitUnsafePart = (error: MdxDocumentError) => {+ diagnostics.push(error);+ return true;+ };+ const handlers = Object.fromEntries(+ Object.entries(mdxHandlers).map(([name, handler]) => [+ name,+ recover(handler),+ ])+ ) as Handlers;+ handlers.mdxJsxFlowElement = createMdxJsxElementHandler({+ shouldOmitUnsafePart,+ });+ handlers.mdxJsxTextElement = createMdxJsxElementHandler({+ shouldOmitUnsafePart,+ });+ return {+ handlers,+ unknownHandler: recover(rejectUnsupportedNode),+ shouldOmitUnsafePart,+ };+};++const createMarkdownHastForMdx = (root: SyntaxTreeNode) => {+ const hast = toHast(root as Parameters<typeof toHast>[0], {+ allowDangerousHtml: true,+ handlers: {+ code: mdxHandlers.code,+ inlineCode: mdxHandlers.inlineCode,+ listItem: mdxHandlers.listItem,+ },+ unknownHandler: rejectUnsupportedNode,+ });+ if (isSyntaxTreeNode(hast) === false) {+ return throwUnsafeNode(root, "Markdown did not produce an HTML document");+ }+ return hast;+};++const findHastMdxMode = (node: SyntaxTreeNode): MdxMode | undefined => {+ if (+ isRecord(node.data) &&+ (node.data.mdxMode === "flow" || node.data.mdxMode === "text")+ ) {+ return node.data.mdxMode;+ }+};++const mapHastProperties = (+ node: SyntaxTreeNode,+ options: MapHastOptions,+ preserveJsxNames: boolean,+ allowAliasedPropertyNames = false+) => {+ if (node.properties === undefined) {+ return { props: [], requiresMdxFallback: false };+ }+ if (isRecord(node.properties) === false) {+ return throwUnsafeNode(node, "HTML properties must be an object");+ }+ const props: MdxAuthoredProp[] = [];+ const propertyNames = new Set<string>();+ let requiresMdxFallback = false;+ const mdxPropSourceRanges =+ isRecord(node.data) && isRecord(node.data.mdxPropSourceRanges)+ ? node.data.mdxPropSourceRanges+ : undefined;+ for (const [propertyName, value] of Object.entries(node.properties)) {+ try {+ if (value === undefined || value === null || value === false) {+ continue;+ }+ let propValue: MdxAuthoredProp["value"];+ if (value === true) {+ propValue = true;+ } else if (typeof value === "string" || typeof value === "number") {+ propValue = String(value);+ } else if (+ Array.isArray(value) &&+ value.every(+ (item) => typeof item === "string" || typeof item === "number"+ )+ ) {+ propValue = value.join(" ");+ } else {+ return throwUnsafeNode(+ node,+ `HTML property ${propertyName} is invalid`+ );+ }+ const instancePropName = getInstancePropName({+ jsxPropName: propertyName,+ acceptsHtmlAttributes: true,+ });+ if (+ allowAliasedPropertyNames === false &&+ propertyNames.has(instancePropName)+ ) {+ return throwUnsafeNode(node, "HTML properties must be unique");+ }+ const name = preserveJsxNames ? propertyName : instancePropName;+ const sourceRange =+ mdxPropSourceRanges === undefined+ ? undefined+ : toSourceRange(mdxPropSourceRanges[propertyName]);+ const prop: MdxAuthoredProp = {+ name,+ value: propValue,+ ...(sourceRange === undefined ? {} : { sourceRange }),+ };+ validateStaticProp(node, prop);+ propertyNames.add(instancePropName);+ props.push(prop);+ } catch (error) {+ if (canOmitUnsafePart(error, options)) {+ requiresMdxFallback ||=+ (node.tagName === "a" && propertyName === "href") ||+ (node.tagName === "img" && propertyName === "src");+ continue;+ }+ throw error;+ }+ }+ return { props, requiresMdxFallback };+};++const mapHastChildren = (+ node: SyntaxTreeNode,+ options: MapHastOptions = {}+): MdxAuthoredNode[] => {+ const children: MdxAuthoredNode[] = [];+ for (const child of getSyntaxTreeChildren(node)) {+ if (+ child.position === undefined &&+ child.type === "text" &&+ child.value === "\n"+ ) {+ continue;+ }+ try {+ children.push(mapHastNode(child, options));+ } catch (error) {+ if (canOmitUnsafePart(error, options)) {+ continue;+ }+ throw error;+ }+ }+ return children;+};++const getHastMdxMode = (node: SyntaxTreeNode) => {+ const mode = findHastMdxMode(node);+ if (mode !== undefined) {+ return mode;+ }+ return throwUnsafeNode(node, "MDX node mode is missing");+};++const getMarkdownListItem = (+ node: SyntaxTreeNode+): MdxMarkdownListItem | undefined => {+ if (isRecord(node.data) === false) {+ return;+ }+ const value = node.data.markdownListItem;+ if (+ isRecord(value) === false ||+ typeof value.spread !== "boolean" ||+ (value.checked !== undefined && typeof value.checked !== "boolean")+ ) {+ return;+ }+ return {+ ...(typeof value.checked === "boolean" ? { checked: value.checked } : {}),+ spread: value.spread,+ };+};++const preservesTextWhitespace = (node: SyntaxTreeNode) =>+ isRecord(node.data) && node.data.preserveTextWhitespace === true+ ? true+ : undefined;++const mapWebstudioElement = (+ node: SyntaxTreeNode,+ props: readonly MdxAuthoredProp[],+ options: MapHastOptions+): MdxAuthoredNode => {+ const nameProp = props.find((prop) => prop.name === "ws:name");+ const tagProp = props.find((prop) => prop.name === "ws:tag");+ if (nameProp !== undefined && tagProp !== undefined) {+ return throwUnsafeNode(node, "ws:name and ws:tag cannot be used together");+ }+ if (nameProp !== undefined) {+ if (typeof nameProp.value !== "string" || nameProp.value.length === 0) {+ return throwUnsafeNode(node, "ws:name must be a non-empty static string");+ }+ return {+ type: "template",+ name: nameProp.value,+ props: props.filter((prop) => prop.name !== "ws:name"),+ children: mapHastChildren(node, options),+ mdxMode: getHastMdxMode(node),+ sourceRange: toSourceRange(node.position),+ };+ }++ let tag = "div";+ if (tagProp !== undefined) {+ if (typeof tagProp.value !== "string" || tagProp.value.length === 0) {+ return throwUnsafeNode(node, "ws:tag must be a non-empty static string");+ }+ tag = tagProp.value;+ }+ if (unsupportedElementTags.has(tag.toLowerCase())) {+ return throwUnsafeNode(+ node,+ `Webstudio element tag ${tag} is not supported`+ );+ }+ return createElement({+ node,+ tag,+ props: props+ .filter((prop) => prop.name !== "ws:tag")+ .map((prop) => ({+ ...prop,+ name: getInstancePropName({+ jsxPropName: prop.name,+ acceptsHtmlAttributes: true,+ }),+ })),+ children: mapHastChildren(node, options),+ mdxMode: getHastMdxMode(node),+ });+};++const mapHastNode = (+ node: SyntaxTreeNode,+ options: MapHastOptions+): MdxAuthoredNode => {+ if (node.type === "text") {+ if (typeof node.value !== "string") {+ return throwUnsafeNode(node, "HTML text must contain a string value");+ }+ return {+ type: "text",+ value: node.value,+ sourceRange: toSourceRange(node.position),+ };+ }+ if (node.type === "comment") {+ if (typeof node.value !== "string") {+ return throwUnsafeNode(node, "HTML comments must contain a string value");+ }+ return {+ type: "comment",+ value: node.value,+ mdxMode: getHastMdxMode(node),+ sourceRange: toSourceRange(node.position),+ };+ }+ if (+ node.type === "opaque" &&+ typeof node.value === "string" &&+ (node.data as { mdxMode?: unknown } | undefined)?.mdxMode !== undefined+ ) {+ return {+ type: "opaque",+ value: node.value,+ mdxMode: getHastMdxMode(node),+ sourceRange:+ toSourceRange(node.position) ??+ throwUnsafeNode(node, "Opaque MDX source location is missing"),+ };+ }+ if (node.type !== "element" || typeof node.tagName !== "string") {+ return throwUnsafeNode(+ node,+ `HTML node type ${node.type} is not supported`+ );+ }+ const authoredMdxMode = findHastMdxMode(node);+ if (+ node.tagName !== "ws.element" &&+ authoredMdxMode !== undefined &&+ unsupportedElementTags.has(node.tagName.toLowerCase())+ ) {+ return throwUnsafeNode(+ node,+ `Webstudio element tag ${node.tagName} is not supported`+ );+ }+ const { props, requiresMdxFallback } = mapHastProperties(+ node,+ options,+ node.tagName === "ws.element",+ node.tagName === "ws.element" &&+ isRecord(node.properties) &&+ Object.hasOwn(node.properties, "ws:name")+ );+ if (node.tagName === "ws.element") {+ return mapWebstudioElement(node, props, options);+ }+ let mdxMode = authoredMdxMode ?? (requiresMdxFallback ? "text" : undefined);+ const children = mapHastChildren(node, options);+ const onlyChild = children.length === 1 ? children[0] : undefined;+ if (+ mdxMode === undefined &&+ node.tagName === "p" &&+ onlyChild !== undefined &&+ ((onlyChild.type === "element" &&+ onlyChild.syntax === "mdx" &&+ onlyChild.mdxMode === "text") ||+ (onlyChild.type === "template" && onlyChild.mdxMode === "text") ||+ (onlyChild.type === "comment" && onlyChild.mdxMode === "text"))+ ) {+ mdxMode = "flow";+ }+ return createElement({+ node,+ tag: node.tagName,+ props,+ children,+ mdxMode,+ markdownListItem: getMarkdownListItem(node),+ preserveTextWhitespace: preservesTextWhitespace(node),+ });+};++const mapAuthoredChildren = (+ root: SyntaxTreeNode,+ options: {+ handlers?: Handlers;+ unknownHandler?: Handler;+ shouldOmitUnsafePart?: (error: MdxDocumentError) => boolean;+ } = {}+) => {+ const hast = toHast(root as Parameters<typeof toHast>[0], {+ handlers: options.handlers ?? mdxHandlers,+ unknownHandler: options.unknownHandler ?? rejectUnsupportedNode,+ });+ if (isSyntaxTreeNode(hast) === false || hast.type !== "root") {+ return throwUnsafeNode(root, "MDX did not produce an HTML document");+ }+ return mapHastChildren(hast, {+ shouldOmitUnsafePart: options.shouldOmitUnsafePart,+ });+};++const validateMdxSourceBytes = ({+ source,+ maximumBytes,+}: {+ source: string;+ maximumBytes: number;+}) => {+ if (+ Number.isInteger(maximumBytes) === false ||+ maximumBytes <= 0 ||+ maximumBytes > contentEngineLimits.hydratedFileBytes ||+ getUtf8ByteLength(source) > maximumBytes+ ) {+ throw new MdxDocumentError({+ code: "invalid-mdx",+ message: "MDX content exceeds the byte limit",+ });+ }+};++const getMdxFrontmatterAuthoredSource = (source: string) => {+ const bytes = new TextEncoder().encode(source);+ const located = findMarkdownFrontmatter(bytes, true);+ if (located === null || located === undefined) {+ return;+ }+ return new TextDecoder("utf-8", { ignoreBOM: true }).decode(+ bytes.subarray(0, located.blockEnd)+ );+};++const parseMdxFrontmatter = async (+ root: SyntaxTreeNode,+ source: string+): Promise<MdxDocument["frontmatter"]> => {+ const frontmatterNode = getSyntaxTreeChildren(root).find(+ (node) => node.type === "yaml"+ );+ try {+ return {+ properties: (await extractMarkdownFrontmatter(source)).properties,+ authoredSource: getMdxFrontmatterAuthoredSource(source),+ sourceRange: toSourceRange(frontmatterNode?.position),+ };+ } catch (cause) {+ throw new MdxDocumentError({+ code: "invalid-mdx",+ message: getErrorMessage(cause),+ sourceRange: toSourceRange(frontmatterNode?.position),+ cause,+ });+ }+};++/** Converts bounded Markdown through a caller-supplied structural HAST transform. */+export const createMdxDocumentFromMarkdown = async ({+ source,+ maximumBytes = contentEngineLimits.hydratedFileBytes,+ transformHast,+ shouldOmitUnsafePart,+}: {+ source: string;+ maximumBytes?: number;+ transformHast: (input: {+ sourceRoot: SyntaxTreeNode;+ hastRoot: SyntaxTreeNode;+ }) => SyntaxTreeNode | Promise<SyntaxTreeNode>;+ shouldOmitUnsafePart?: (error: MdxDocumentError) => boolean;+}): Promise<MdxDocument> => {+ validateMdxSourceBytes({ source, maximumBytes });+ const sourceRoot = parseMarkdownAst(source);+ validateAstLimits(sourceRoot);+ const hastRoot = await transformHast({+ sourceRoot,+ hastRoot: createMarkdownHastForMdx(sourceRoot),+ });+ validateAstLimits(hastRoot);+ return {+ frontmatter: await parseMdxFrontmatter(sourceRoot, source),+ children: mapHastChildren(hastRoot, { shouldOmitUnsafePart }),+ };+};++export const discoverMdxBodyAssetReferences = ({+ document,+ sourcePath,+ assetIdsByPath,+}: {+ document: MdxDocument;+ sourcePath: string;+ assetIdsByPath: ReadonlyMap<string, string>;+}): AssetValueReference[] => {+ const references: AssetValueReference[] = [];+ const resolveAssetReference = createAssetReferenceResolver({+ sourcePath,+ assetIdsByPath,+ });+ const visit = (+ nodes: readonly MdxAuthoredNode[],+ parentPath: Array<string | number>+ ) => {+ for (const [nodeIndex, node] of nodes.entries()) {+ if (+ node.type === "text" ||+ node.type === "comment" ||+ node.type === "opaque"+ ) {+ continue;+ }+ const nodePath = [...parentPath, nodeIndex];+ for (const [propIndex, prop] of node.props.entries()) {+ if (+ typeof prop.value !== "string" ||+ urlPropNames.has(prop.name.toLowerCase()) === false+ ) {+ continue;+ }+ const reference = resolveAssetReference(prop.value);+ if (reference !== undefined) {+ references.push({+ path: [...nodePath, "props", propIndex, "value"],+ ...reference,+ });+ }+ }+ visit(node.children, [...nodePath, "children"]);+ }+ };+ visit(document.children, ["children"]);+ return references;+};++export const discoverMdxAssetReferences = ({+ document,+ sourcePath,+ assetIdsByPath,+}: {+ document: MdxDocument;+ sourcePath: string;+ assetIdsByPath: ReadonlyMap<string, string>;+}): AssetValueReference[] => [+ ...discoverAssetValueReferences({+ properties: document.frontmatter.properties,+ sourcePath,+ assetIdsByPath,+ structuredAssetIds: new Set(assetIdsByPath.values()),+ rootPath: ["frontmatter", "properties"],+ }),+ ...discoverMdxBodyAssetReferences({+ document,+ sourcePath,+ assetIdsByPath,+ }),+];++export const discoverNamedMdxAssetReferences = ({+ document,+ source,+ assets,+}: {+ document: MdxDocument;+ source: { name: string; folderNames: readonly string[] };+ assets: Iterable<{+ id: string;+ name: string;+ folderNames: readonly string[];+ }>;+}) =>+ discoverMdxAssetReferences({+ document,+ ...createNamedAssetReferenceContext({ source, assets }),+ });++export const rewriteMdxAssetReferences = async ({+ source,+ sourcePath,+ assetPaths,+ replacementPaths,+}: {+ source: string;+ sourcePath: string;+ assetPaths: ReadonlyMap<string, string>;+ replacementPaths: ReadonlyMap<string, string>;+}) => {+ const document = await parseMdxDocument({ source });+ const references = discoverMdxAssetReferences({+ document,+ sourcePath,+ assetIdsByPath: createUniqueAssetIdsByPath(+ Array.from(assetPaths, ([id, path]) => ({ id, path }))+ ),+ });+ if (references.length === 0) {+ return source;+ }+ const resolved = rewriteAssetValueReferences({+ value: document,+ references,+ assetUrls: Object.fromEntries(replacementPaths),+ });+ const rewritesFrontmatter = references.some(+ ({ path }) => path[0] === "frontmatter"+ );+ return serializeMdxDocument({+ ...resolved,+ frontmatter: rewritesFrontmatter+ ? {+ ...resolved.frontmatter,+ // A rewritten frontmatter reference makes the authored spelling+ // stale. Body-only rewrites keep the exact authored frontmatter.+ authoredSource: undefined,+ }+ : resolved.frontmatter,+ });+};++export const parseMdxDocument = async ({+ source,+ maximumBytes = contentEngineLimits.hydratedFileBytes,+}: {+ source: string;+ maximumBytes?: number;+}): Promise<MdxDocument> => {+ validateMdxSourceBytes({ source, maximumBytes });++ let root: SyntaxTreeNode;+ try {+ root = parseMarkdownAst(source, "mdx");+ } catch (cause) {+ throw new MdxDocumentError({+ code: "invalid-mdx",+ message: getErrorMessage(cause),+ sourceRange: getParserErrorSourceRange(cause),+ cause,+ });+ }+ addMdxJsxAttributePositions(root, source);+ validateAstLimits(root);++ return {+ frontmatter: await parseMdxFrontmatter(root, source),+ children: mapAuthoredChildren(root),+ };+};++export type MdxDocumentRecoveryResult =+ | Readonly<{+ status: "parsed";+ document: MdxDocument;+ diagnostics: readonly MdxDocumentError[];+ }>+ | Readonly<{+ status: "unrecoverable";+ diagnostics: readonly MdxDocumentError[];+ }>;++export const parseMdxDocumentRecovering = async ({+ source,+ maximumBytes = contentEngineLimits.hydratedFileBytes,+}: {+ source: string;+ maximumBytes?: number;+}): Promise<MdxDocumentRecoveryResult> => {+ try {+ validateMdxSourceBytes({ source, maximumBytes });+ const root = parseMarkdownAst(source, "mdx");+ addMdxJsxAttributePositions(root, source);+ validateAstLimits(root);+ const diagnostics: MdxDocumentError[] = [];+ const recovery = createRecoveringHandlers({ source, diagnostics });+ let frontmatter: MdxDocument["frontmatter"];+ try {+ frontmatter = await parseMdxFrontmatter(root, source);+ } catch (error) {+ if (error instanceof MdxDocumentError === false) {+ throw error;+ }+ diagnostics.push(error);+ const frontmatterNode = getSyntaxTreeChildren(root).find(+ (node) => node.type === "yaml"+ );+ frontmatter = {+ properties: {},+ authoredSource: getMdxFrontmatterAuthoredSource(source),+ sourceRange: toSourceRange(frontmatterNode?.position),+ };+ }+ return {+ status: "parsed",+ document: {+ frontmatter,+ children: mapAuthoredChildren(root, recovery),+ },+ diagnostics,+ };+ } catch (cause) {+ const error =+ cause instanceof MdxDocumentError+ ? cause+ : new MdxDocumentError({+ code: "invalid-mdx",+ message: getErrorMessage(cause),+ sourceRange: getParserErrorSourceRange(cause),+ cause,+ });+ return { status: "unrecoverable", diagnostics: [error] };+ }+};++const withMarkdownSyntax = (node: MdxAuthoredNode): MdxAuthoredNode => {+ if (node.type !== "element" || node.syntax !== "mdx") {+ return node;+ }+ const { mdxMode: _mdxMode, ...element } = node;+ return {+ ...element,+ syntax: "markdown",+ };+};++const withMarkdownSyntaxDeep = (node: MdxAuthoredNode): MdxAuthoredNode => {+ if (+ node.type === "text" ||+ node.type === "comment" ||+ node.type === "opaque"+ ) {+ return node;+ }+ return withMarkdownSyntax({+ ...node,+ children: node.children.map(withMarkdownSyntaxDeep),+ });+};++const parseMarkdownCandidate = async (+ nodes: readonly MdxAuthoredNode[],+ cache?: Map<string, Promise<readonly MdxAuthoredNode[] | undefined>>+): Promise<readonly MdxAuthoredNode[] | undefined> => {+ const source = serializeMdxDocument({+ frontmatter: { properties: {} },+ children: nodes,+ });+ const cached = cache?.get(source);+ if (cached !== undefined) {+ return cached;+ }+ const result = parseMdxDocument({ source }).then(+ ({ children }) => children,+ () => undefined+ );+ cache?.set(source, result);+ return result;+};++const areAuthoredPropsEqual = (+ left: readonly MdxAuthoredProp[],+ right: readonly MdxAuthoredProp[]+) => {+ if (left.length !== right.length) {+ return false;+ }+ const leftByName = new Map(left.map((prop) => [prop.name, prop.value]));+ const rightByName = new Map(right.map((prop) => [prop.name, prop.value]));+ return (+ leftByName.size === left.length &&+ rightByName.size === right.length &&+ Array.from(leftByName).every(+ ([name, value]) => rightByName.get(name) === value+ )+ );+};++const unwrapSingleParagraph = (nodes: readonly MdxAuthoredNode[]) => {+ const onlyChild = nodes.length === 1 ? nodes[0] : undefined;+ return onlyChild?.type === "element" &&+ onlyChild.syntax === "markdown" &&+ onlyChild.tag === "p" &&+ onlyChild.props.length === 0+ ? onlyChild.children+ : nodes;+};++const areAuthoredNodesEquivalent = (+ left: MdxAuthoredNode,+ right: MdxAuthoredNode+): boolean => {+ if (left.type !== right.type) {+ return false;+ }+ if (left.type === "text" && right.type === "text") {+ return left.value === right.value;+ }+ if (left.type === "comment" && right.type === "comment") {+ return left.value === right.value;+ }+ if (left.type === "template" && right.type === "template") {+ return (+ left.name === right.name &&+ areAuthoredPropsEqual(left.props, right.props) &&+ areAuthoredNodeListsEquivalent(left.children, right.children, false)+ );+ }+ if (left.type === "element" && right.type === "element") {+ return (+ left.tag === right.tag &&+ areAuthoredPropsEqual(left.props, right.props) &&+ areAuthoredNodeListsEquivalent(+ left.children,+ right.children,+ left.tag !== "p"+ )+ );+ }+ return false;+};++const areAuthoredNodeListsEquivalent = (+ left: readonly MdxAuthoredNode[],+ right: readonly MdxAuthoredNode[],+ allowParagraphWrapper: boolean+) => {+ const normalizedLeft = allowParagraphWrapper+ ? unwrapSingleParagraph(left)+ : left;+ const normalizedRight = allowParagraphWrapper+ ? unwrapSingleParagraph(right)+ : right;+ return (+ normalizedLeft.length === normalizedRight.length &&+ normalizedLeft.every((node, index) => {+ const other = normalizedRight[index];+ return other !== undefined && areAuthoredNodesEquivalent(node, other);+ })+ );+};++const findCanonicalMarkdownElement = ({+ candidate,+ nodes,+}: {+ candidate: Extract<MdxAuthoredNode, { type: "element" }>;+ nodes: readonly MdxAuthoredNode[] | undefined;+}) => {+ const direct = nodes?.length === 1 ? nodes[0] : undefined;+ const wrapped =+ direct?.type === "element" &&+ direct.syntax === "markdown" &&+ direct.tag === "p" &&+ direct.props.length === 0 &&+ direct.children.length === 1+ ? direct.children[0]+ : undefined;+ for (const node of [direct, wrapped]) {+ if (+ node?.type === "element" &&+ node.syntax === "markdown" &&+ areAuthoredNodesEquivalent(candidate, node)+ ) {+ return node;+ }+ }+};++const preferMarkdownNode = async (+ node: MdxAuthoredNode,+ cache: Map<string, Promise<readonly MdxAuthoredNode[] | undefined>>+): Promise<MdxAuthoredNode> => {+ if (+ node.type === "text" ||+ node.type === "comment" ||+ node.type === "opaque"+ ) {+ return node;+ }+ const children = await preferMarkdownNodes(node.children, cache);+ const withChildren = { ...node, children };+ if (withChildren.type !== "element") {+ return withChildren;+ }+ if (+ withChildren.syntax === "markdown" &&+ withChildren.children.some(+ (child) => child.type === "element" && child.syntax === "mdx"+ ) === false+ ) {+ return withChildren;+ }++ const candidate = withMarkdownSyntaxDeep(withChildren);+ const parsed = await parseMarkdownCandidate([candidate], cache);+ const markdownElement = findCanonicalMarkdownElement({+ candidate: withChildren,+ nodes: parsed,+ });+ if (markdownElement !== undefined) {+ return markdownElement;+ }+ return withChildren;+};++const preferMarkdownNodes = async (+ nodes: readonly MdxAuthoredNode[],+ cache: Map<string, Promise<readonly MdxAuthoredNode[] | undefined>>+): Promise<MdxAuthoredNode[]> => {+ const result: MdxAuthoredNode[] = [];+ for (const node of nodes) {+ result.push(await preferMarkdownNode(node, cache));+ }+ return result;+};++/**+ * Canonicalizes generic elements through the Markdown serializer and parser.+ * Elements recognized by Markdown use Markdown syntax. Templates and elements+ * without a Markdown representation keep their MDX syntax.+ */+export const preferMarkdownSyntax = async (+ document: MdxDocument+): Promise<MdxDocument> => {+ const cache = new Map<+ string,+ Promise<readonly MdxAuthoredNode[] | undefined>+ >();+ const preferredChildren = await preferMarkdownNodes(document.children, cache);+ const reparsed = await parseMarkdownCandidate(preferredChildren, cache);+ if (reparsed !== undefined) {+ return { ...document, children: reparsed };+ }+ return document;+};++/** Updates frontmatter without canonicalizing or otherwise rewriting the body. */+export const replaceMdxFrontmatter = async ({+ source,+ properties,+}: {+ source: string;+ properties: Readonly<Record<string, unknown>>;+}) => {+ return replaceMarkdownFrontmatter({ source, properties });+};++export { serializeMdxDocument };+export { createCanonicalAssetPath } from "./asset-path";diff --git a/packages/content-engine/src/schema.ts b/packages/content-engine/src/schema.tsindex de9df5b56a..dea28db455 100644--- a/packages/content-engine/src/schema.ts+++ b/packages/content-engine/src/schema.ts@@ -271,6 +271,9 @@ export const contentArtifactV1 = strictObject({contentRef === undefined ? [] : [contentRef]));+ for (const node of index.documentGraph?.nodes ?? []) {+ contentRefs.add(node.contentRef);+ }for (const contentRef of Object.keys(index.contents ?? {})) {if (contentRefs.has(contentRef) === false) {context.addIssue({diff --git a/packages/content-engine/src/structured-query.test.ts b/packages/content-engine/src/structured-query.test.tsindex 1b88ecca52..568f9c1374 100644--- a/packages/content-engine/src/structured-query.test.ts+++ b/packages/content-engine/src/structured-query.test.ts@@ -8,6 +8,7 @@ import {executeAssetQuery,executeAssetQueries,getAssetQueryFieldValue,+ supportsAssetQueryContent,validateAssetQueryAgainstCatalog,} from "./structured-query";import { contentEngineLimits } from "./limits";@@ -73,6 +74,25 @@ const documents = [}),];+test("supports referenced bodies for Markdown and MDX documents", () => {+ const content = { mode: "markdown-body-ref" } as const;+ expect(supportsAssetQueryContent({ document: documents[0], content })).toBe(+ true+ );+ expect(+ supportsAssetQueryContent({+ document: {+ ...documents[0],+ name: "alpha.mdx",+ path: "blog/alpha.mdx",+ extension: "mdx",+ mimeType: "text/mdx",+ },+ content,+ })+ ).toBe(true);+});+const catalog: BuilderAssetFieldCatalog = {format: "webstudio-builder-asset-field-catalog",version: 1,diff --git a/packages/content-engine/src/structured-query.ts b/packages/content-engine/src/structured-query.tsindex 66ff3315ba..aad47c8a2a 100644--- a/packages/content-engine/src/structured-query.ts+++ b/packages/content-engine/src/structured-query.ts@@ -33,6 +33,7 @@ import {hydrateAssetResourceResult,type AssetResourceContentReader,} from "./hydration";+import { getDocumentFormatByContentType } from "./document-graph/document-format";import { appendAssetFieldPath } from "./canonical";import { selectAssetDocumentFields, selectAssetProperties } from "./projection";import { getUtf8ByteLength } from "./byte-stream";@@ -308,10 +309,20 @@ export const supportsAssetQueryContent = ({}: {document: ContentDatabaseDocument;content: AssetResourceContentOptions;-}) =>- content.mode !== "markdown-body-ref" ||- document.mimeType === "text/markdown" ||- document.extension === "md";+}) => {+ if (content.mode !== "markdown-body-ref") {+ return true;+ }+ const format =+ document.mimeType === undefined+ ? undefined+ : getDocumentFormatByContentType(document.mimeType);+ if (format === "markdown" || format === "mdx") {+ return true;+ }+ // Preserve extension fallback for legacy documents with missing MIME metadata.+ return document.extension === "md" || document.extension === "mdx";+};const compareAssetQuerySortValues = (left: unknown, right: unknown) => {const leftMissing = left === undefined || left === null;diff --git a/packages/expression/src/expression.test.ts b/packages/expression/src/expression.test.tsindex 2529af30ba..e8077816cb 100644--- a/packages/expression/src/expression.test.ts+++ b/packages/expression/src/expression.test.ts@@ -13,6 +13,7 @@ import {parseJsonExpression,parseExpressionObject,parseArrayExpression,+ parseDirectPathExpression,parseStaticMemberPath,parseStringLiteralExpression,allowedArrayMethods,@@ -41,6 +42,22 @@ describe("static member paths", () => {});});+describe("direct path expressions", () => {+ test("distinguishes a writable location from a derived expression", () => {+ expect(parseDirectPathExpression("document.frontmatter.title")).toEqual({+ type: "direct-path",+ expression: "document.frontmatter.title",+ path: ["document", "frontmatter", "title"],+ });+ expect(+ parseDirectPathExpression('document.frontmatter.title + "!"')+ ).toBeUndefined();+ expect(+ parseDirectPathExpression("document.frontmatter[fieldName]")+ ).toBeUndefined();+ });+});+describe("string literal expressions", () => {test.each([['"assets"', "assets"],diff --git a/packages/expression/src/index.ts b/packages/expression/src/index.tsindex 152c780fce..b129ba1e61 100644--- a/packages/expression/src/index.ts+++ b/packages/expression/src/index.ts@@ -482,17 +482,26 @@ export const parseStringLiteralExpression = (expression: string) => {}};-const getStaticMemberPath = (node: Expression): string[] | undefined => {+const getStaticMemberPath = (+ node: Expression,+ allowOptional = true+): string[] | undefined => {if (node.type === "Identifier") {return [node.name];}if (node.type === "ChainExpression") {- return getStaticMemberPath(node.expression);+ return allowOptional+ ? getStaticMemberPath(node.expression, allowOptional)+ : undefined;}- if (node.type !== "MemberExpression" || node.object.type === "Super") {+ if (+ node.type !== "MemberExpression" ||+ node.object.type === "Super" ||+ (allowOptional === false && node.optional)+ ) {return;}- const objectPath = getStaticMemberPath(node.object);+ const objectPath = getStaticMemberPath(node.object, allowOptional);if (objectPath === undefined) {return;}@@ -508,11 +517,42 @@ const getStaticMemberPath = (node: Expression): string[] | undefined => {return propertyName === undefined ? undefined : [...objectPath, propertyName];};+/**+ * An expression containing only an identifier and statically known member+ * access. Unlike an arbitrary expression, it identifies one data location.+ * The owner of that location must still explicitly support write-back before+ * callers may treat it as writable.+ */+export type DirectPathExpression = Readonly<{+ type: "direct-path";+ expression: string;+ path: readonly [root: string, ...segments: string[]];+}>;++export const parseDirectPathExpression = (+ expression: string+): DirectPathExpression | undefined => {+ try {+ const node = parseCompleteExpression(expression);+ const path = getStaticMemberPath(node, false);+ if (path === undefined || path.length === 0) {+ return;+ }+ return {+ type: "direct-path",+ expression,+ path: path as [string, ...string[]],+ };+ } catch {+ return;+ }+};+/** Parse an identifier/member expression whose complete property path is static. */export const parseStaticMemberPath = (expression: string) => {try {- const node = parseCompleteExpression(expression);- return getStaticMemberPath(node);+ const path = getStaticMemberPath(parseCompleteExpression(expression));+ return path === undefined || path.length === 0 ? undefined : path;} catch {return;}diff --git a/packages/generate-arg-types/package.json b/packages/generate-arg-types/package.jsonindex 4c38f755d8..c023e4bb93 100644--- a/packages/generate-arg-types/package.json+++ b/packages/generate-arg-types/package.json@@ -9,6 +9,7 @@"typecheck": "tsc --noEmit"},"dependencies": {+ "@webstudio-is/content-engine": "workspace:*","@webstudio-is/html-data": "workspace:*","@webstudio-is/react-sdk": "workspace:*","@webstudio-is/sdk": "workspace:*",diff --git a/packages/generate-arg-types/src/props/add-descriptions.ts b/packages/generate-arg-types/src/props/add-descriptions.tsindex 6ae5e2216c..356a9e1316 100644--- a/packages/generate-arg-types/src/props/add-descriptions.ts+++ b/packages/generate-arg-types/src/props/add-descriptions.ts@@ -1,7 +1,7 @@import {- reactPropsToStandardAttributes,- standardAttributesToReactProps,-} from "@webstudio-is/react-sdk";+ getInstancePropName,+ getJsxPropName,+} from "@webstudio-is/content-engine/jsx-attributes";import { ariaAttributes, attributesByTag } from "@webstudio-is/html-data";import { propsToArgTypes } from "../arg-types";@@ -54,10 +54,20 @@ export const getDescription = (currentDescription: string | undefined,customDescriptions: { [key in string]: string } = {}): string | undefined => {+ const jsxPropName = getJsxPropName({+ instancePropName: propName,+ acceptsHtmlAttributes: true,+ });+ const instancePropName = getInstancePropName({+ jsxPropName: propName,+ acceptsHtmlAttributes: true,+ });const name =- standardAttributesToReactProps[propName] ||- reactPropsToStandardAttributes[propName] ||- propName.toLowerCase();+ jsxPropName !== propName+ ? jsxPropName+ : instancePropName !== propName+ ? instancePropName+ : propName.toLowerCase();return (customDescriptions[propName] ||customDescriptions[name] ||diff --git a/packages/html-data/bin/attributes.ts b/packages/html-data/bin/attributes.tsindex 7e01f68627..b511ba952a 100644--- a/packages/html-data/bin/attributes.ts+++ b/packages/html-data/bin/attributes.ts@@ -496,8 +496,8 @@ let standardAttributesContent = "";standardAttributesContent += `export const standardAttributesToReactProps: Record<string, string> = ${JSON.stringify(standardAttributesToReactProps, null, 2)};\n\n`;standardAttributesContent += `export const reactPropsToStandardAttributes: Record<string, string> = ${JSON.stringify(reactPropsToStandardAttributes, null, 2)};\n`;-await mkdir("../react-sdk/src/__generated__", { recursive: true });+await mkdir("../content-engine/src/__generated__", { recursive: true });await writeFile(- "../react-sdk/src/__generated__/standard-attributes.ts",+ "../content-engine/src/__generated__/standard-attributes.ts",standardAttributesContent);diff --git a/packages/html-data/package.json b/packages/html-data/package.jsonindex f313d2c337..404f35d429 100644--- a/packages/html-data/package.json+++ b/packages/html-data/package.json@@ -8,7 +8,7 @@"scripts": {"typecheck": "tsc --noEmit -p tsconfig.typecheck.json","build:elements": "tsx --conditions=webstudio ./bin/elements.ts && oxfmt ./src/__generated__",- "build:attributes": "tsx --conditions=webstudio ./bin/attributes.ts && oxfmt ./src/__generated__ && (cd ../react-sdk && oxfmt src/__generated__)",+ "build:attributes": "tsx --conditions=webstudio ./bin/attributes.ts && oxfmt ./src/__generated__ && (cd ../content-engine && oxfmt src/__generated__/standard-attributes.ts)","build:aria": "tsx --conditions=webstudio ./bin/aria.ts && oxfmt ./src/__generated__"},"devDependencies": {diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.tsindex d8ac7bf45b..47c7169fd5 100644--- a/packages/http-client/src/index.ts+++ b/packages/http-client/src/index.ts@@ -4,8 +4,12 @@ import {getAssetContentHash,type AssetQueryResourceConfigurationInput,type AssetFolder,+ type ExpressionBindingMode,} from "@webstudio-is/sdk";import {+ assetContentDescriptor,+ assetContentDescriptorHeader,+ parseAssetContentDescriptor,type AssetFolderUpdateRequest,type AssetMetadataUpdate,type AssetQueryRequestInput,@@ -974,6 +978,66 @@ export const readProjectAssetContent = async (return response;};+export const createProjectAssetContentTransport = ({+ projectId,+ origin,+ requestOrigin = origin,+ authToken = () => undefined,+ headers,+ request = fetch,+}: {+ projectId: string;+ origin: string;+ requestOrigin?: string;+ authToken?: () => string | undefined;+ headers?: RequestHeaders;+ request?: typeof fetch;+}) => ({+ read: ({+ assetId,+ range,+ }: {+ assetId: string;+ range?: { offset: number; length: number };+ }) =>+ readProjectAssetContent({+ projectId,+ origin,+ requestOrigin,+ authToken: authToken(),+ headers,+ request,+ assetId,+ range,+ }),+ update: async ({+ assetId,+ expectedName,+ data,+ }: {+ assetId: string;+ expectedName: string;+ data: Uint8Array;+ }) => {+ const { asset } = await updateProjectAssetContent({+ projectId,+ origin,+ requestOrigin,+ authToken: authToken(),+ headers,+ request,+ assetId,+ expectedName,+ readAssetData: async () => Uint8Array.from(data),+ });+ return assetContentDescriptor.parse(asset);+ },+ parseAsset: (response: Response) =>+ parseAssetContentDescriptor(+ response.headers.get(assetContentDescriptorHeader)+ ),+});+export const listProjectAssetFolders = async (params: AuthProjectParams & {request?: typeof fetch;@@ -1447,6 +1511,38 @@ export const updateAsset = runtimeProjectMutation("update-asset");export const addAsset = runtimeProjectMutation("add-asset");+export const inspectContentBlockSource =+ projectQueryInput<RuntimeOperationParams>("inspect-content-block-source");++export const connectContentBlockSource = runtimeProjectMutation(+ "connect-content-block-source"+);++export const switchContentBlockSource = runtimeProjectMutation(+ "switch-content-block-source"+);++export const disconnectContentBlockSource = runtimeProjectMutation(+ "disconnect-content-block-source"+);++export const editContentBlockSource = runtimeProjectMutation(+ "edit-content-block-source"+);++export const updateContentBlockFrontmatter = runtimeProjectMutation(+ "update-content-block-frontmatter"+);++export const reloadContentBlockSource =+ projectQueryInput<RuntimeOperationParams>("reload-content-block-source");++export const migrateContentBlockTemplateReferences = runtimeProjectMutation(+ "migrate-content-block-template-references"+);++export const insertMdxText = runtimeProjectMutation("insert-mdx-text");+type ProjectSettingsInput = {meta?: {siteName?: string | null;@@ -1699,28 +1795,39 @@ export const deleteInstance = projectMutationInput<type PropValueInput = {instanceId: string;name: string;- type:- | "number"- | "string"- | "boolean"- | "json"- | "asset"- | "page"- | "string[]"- | "parameter"- | "resource"- | "expression"- | "action"- | "animationAction";- value: unknown;required?: boolean;-};+} & (+ | {+ type: "expression";+ value: string;+ mode?: ExpressionBindingMode;+ }+ | {+ type:+ | "number"+ | "string"+ | "boolean"+ | "json"+ | "asset"+ | "page"+ | "string[]"+ | "parameter"+ | "resource"+ | "action"+ | "animationAction";+ value: unknown;+ }+);type PropBindingInput = {instanceId: string;name: string;binding:- | { type: "expression"; value: string }+ | {+ type: "expression";+ value: string;+ mode?: ExpressionBindingMode;+ }| { type: "parameter"; value: string }| { type: "resource"; value: string }| {@@ -1762,8 +1869,13 @@ export const updateText = projectMutationInput<instanceId: string;childIndex: number;text: string;- mode?: "text" | "expression";- }+ } & (+ | {+ mode: "expression";+ expressionBindingMode?: ExpressionBindingMode;+ }+ | { mode?: "text"; expressionBindingMode?: never }+ )>("update-text");export const getStyleDeclarations = projectQueryInput<diff --git a/packages/project-build/src/build-integrity.test.ts b/packages/project-build/src/build-integrity.test.tsindex 50d2649715..fbd68d587b 100644--- a/packages/project-build/src/build-integrity.test.ts+++ b/packages/project-build/src/build-integrity.test.ts@@ -1,5 +1,12 @@import { describe, expect, test } from "vitest";-import type { DataSource, Prop, Resource } from "@webstudio-is/sdk";+import {+ blockComponent,+ type DataSource,+ type FileAsset,+ type Instance,+ type Prop,+ type Resource,+} from "@webstudio-is/sdk";import {assertBuildIntegrity,formatBuildIntegrityError,@@ -16,6 +23,55 @@ const resource: Resource = {};describe("getBuildIntegrityIssues", () => {+ test("reports invalid Content Block source references", () => {+ const block: Instance = {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [],+ };+ const source: Prop = {+ id: "source",+ instanceId: block.id,+ name: "src",+ type: "asset",+ value: "post",+ };+ const markdownAsset: FileAsset = {+ id: "post",+ projectId: "project",+ type: "file",+ name: "post_hash.md",+ filename: "post",+ format: "md",+ size: 1,+ meta: {},+ description: null,+ createdAt: "2026-08-14T00:00:00.000Z",+ };++ const issues = getBuildIntegrityIssues({+ dataSources: [],+ props: [source],+ resources: [],+ instances: [block],+ assets: [markdownAsset],+ });++ expect(issues).toEqual([+ {+ type: "incompatibleContentBlockSourceAsset",+ blockInstanceId: "block",+ propId: "source",+ assetId: "post",+ assetName: "post_hash.md",+ },+ ]);+ expect(formatBuildIntegrityIssue(issues[0])).toBe(+ 'Content Block source prop "source" references Asset "post" (post_hash.md), which is not an MDX file.'+ );+ });+test("reports resource variables referencing missing resources", () => {const dataSource: DataSource = {type: "resource",@@ -28,6 +84,7 @@ describe("getBuildIntegrityIssues", () => {dataSources: [dataSource],props: [],resources: [],+ instances: [],});expect(issues).toEqual([@@ -51,6 +108,7 @@ describe("getBuildIntegrityIssues", () => {dataSources: [dataSource],props: [],resources: [],+ instances: [],},{ messagePrefix: "Cannot publish" })@@ -72,6 +130,7 @@ describe("getBuildIntegrityIssues", () => {dataSources: [],props: [prop],resources: [],+ instances: [],});expect(issues).toEqual([@@ -108,6 +167,7 @@ describe("getBuildIntegrityIssues", () => {dataSources: [dataSource],props: [prop],resources: [resource],+ instances: [],})).toEqual([]);});diff --git a/packages/project-build/src/build-integrity.ts b/packages/project-build/src/build-integrity.tsindex d7b4ebc89b..97f86f7c57 100644--- a/packages/project-build/src/build-integrity.ts+++ b/packages/project-build/src/build-integrity.ts@@ -1,4 +1,13 @@-import type { DataSource, Prop, Resource } from "@webstudio-is/sdk";+import {+ formatContentBlockSourceIntegrityIssue,+ getContentBlockSourceIntegrityIssues,+ type Asset,+ type ContentBlockSourceIntegrityIssue,+ type DataSource,+ type Instance,+ type Prop,+ type Resource,+} from "@webstudio-is/sdk";export type BuildIntegrityIssue =| {@@ -14,18 +23,30 @@ export type BuildIntegrityIssue =propId: string;propName: string;resourceId: string;- };+ }+ | ContentBlockSourceIntegrityIssue;export const getBuildIntegrityIssues = ({dataSources,props,resources,+ instances = [],+ assets,}: {dataSources: Iterable<DataSource>;props: Iterable<Prop>;resources: Iterable<Resource>;+ instances?: Iterable<Instance>;+ assets?: Iterable<Asset>;}): BuildIntegrityIssue[] => {- const issues: BuildIntegrityIssue[] = [];+ const propsList = Array.from(props);+ const issues: BuildIntegrityIssue[] = [+ ...getContentBlockSourceIntegrityIssues({+ instances,+ props: propsList,+ assets,+ }),+ ];const resourceIds = new Set<string>();for (const resource of resources) {@@ -47,7 +68,7 @@ export const getBuildIntegrityIssues = ({}}- for (const prop of props) {+ for (const prop of propsList) {if (prop.type === "resource" && resourceIds.has(prop.value) === false) {issues.push({type: "missingResource",@@ -65,6 +86,9 @@ export const getBuildIntegrityIssues = ({export const formatBuildIntegrityIssue = (issue: BuildIntegrityIssue): string => {+ if (issue.type !== "missingResource") {+ return formatContentBlockSourceIntegrityIssue(issue);+ }if (issue.source === "dataSource") {return `resource variable "${issue.dataSourceName}" (${issue.dataSourceId}) references missing resource "${issue.resourceId}".`;}@@ -83,6 +107,8 @@ export const assertBuildIntegrity = (dataSources: Iterable<DataSource>;props: Iterable<Prop>;resources: Iterable<Resource>;+ instances?: Iterable<Instance>;+ assets?: Iterable<Asset>;},options: { messagePrefix?: string } = {}) => {@@ -94,3 +120,19 @@ export const assertBuildIntegrity = ();}};++export const assertContentBlockSourceIntegrity = (+ data: {+ instances: Iterable<Instance>;+ props: Iterable<Prop>;+ assets?: Iterable<Asset>;+ },+ options: { messagePrefix?: string } = {}+) => {+ const firstIssue = getContentBlockSourceIntegrityIssues(data)[0];+ if (firstIssue !== undefined) {+ throw new Error(+ formatBuildIntegrityError(firstIssue, options.messagePrefix)+ );+ }+};diff --git a/packages/project-build/src/content-database.test.ts b/packages/project-build/src/content-database.test.tsnew file mode 100644index 0000000000..13155d90cc--- /dev/null+++ b/packages/project-build/src/content-database.test.ts@@ -0,0 +1,424 @@+import { describe, expect, test } from "vitest";+import type { ContentArtifactV1 } from "@webstudio-is/content-engine";+import {+ createStructuredAssetQueryResourceBody,+ encodeDataVariableId,+ type DataSource,+ type Instance,+ type Pages,+ type Prop,+ type Resource,+} from "@webstudio-is/sdk";+import {+ createBuildContentCompilationPlan,+ createPublishedBuildContentCompilationPlan,+ getDynamicPublishedMdxSourceBlockIds,+ getPublishedMdxContentDatabaseMaxBytes,+ resolvePublishedMdxAssetCandidates,+ resolvePublishedMdxDependencyClosure,+} from "./content-database";++const createBuild = ({+ component = "ws:block",+ sourceType = "asset",+}: {+ component?: string;+ sourceType?: "asset" | "expression" | "string";+}): {+ instances: Instance[];+ props: Prop[];+ dataSources: DataSource[];+ resources: Resource[];+ pages: Pages;+} => ({+ instances: [+ {+ type: "instance" as const,+ id: "block",+ component,+ children: [],+ },+ ],+ props: [+ {+ id: "source",+ instanceId: "block",+ name: "src",+ type: sourceType,+ value: sourceType === "expression" ? '"article.mdx"' : "article.mdx",+ },+ ],+ dataSources: [],+ resources: [],+ pages: {+ meta: {},+ homePageId: "home",+ rootFolderId: "root-folder",+ pages: new Map([+ [+ "home",+ {+ id: "home",+ path: "",+ name: "Home",+ title: "Home",+ rootInstanceId: "block",+ meta: {},+ },+ ],+ ]),+ folders: new Map(),+ },+});++describe("Content Block MDX compilation", () => {+ test("adds a separately bounded MDX body budget", () => {+ expect(+ getPublishedMdxContentDatabaseMaxBytes({+ baseBytes: 500,+ assets: [+ { type: "file", format: "mdx", size: 10_000_000 },+ { type: "file", format: "mdx", size: 30_000_000 },+ { type: "file", format: "md", size: 10_000_000 },+ ],+ })+ ).toBe(32 * 1024 * 1024 + 500);+ });+ test.each(["asset", "expression"] as const)(+ "retains the exact MDX dependency for a %s source",+ (sourceType) => {+ const plan = createPublishedBuildContentCompilationPlan(+ createBuild({ sourceType })+ );++ expect(plan?.queries).toContainEqual({+ id: "__content-block-mdx__:article.mdx",+ result: "many",+ where: {+ all: [+ {+ field: ["extension"],+ operator: "eq",+ value: { type: "literal", value: "mdx" },+ },+ {+ field: ["id"],+ operator: "eq",+ value: { type: "literal", value: "article.mdx" },+ },+ ],+ },+ sort: [],+ limit: { type: "dynamic" },+ offset: { type: "literal", value: 0 },+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["url"], ["width"], ["height"]],+ },+ content: { mode: "full" },+ });+ }+ );++ test("does not retain MDX for unrelated src props", () => {+ expect(+ createPublishedBuildContentCompilationPlan(+ createBuild({ component: "ws:element" })+ )+ ).toBeUndefined();+ });++ test("does not retain MDX for an invalid Content Block source type", () => {+ expect(+ createPublishedBuildContentCompilationPlan(+ createBuild({ sourceType: "string" })+ )+ ).toBeUndefined();+ });++ test("does not retain conflicting duplicate Content Block sources", () => {+ const build = createBuild({});+ build.props.push({+ id: "duplicate-source",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "private.mdx",+ });++ expect(createPublishedBuildContentCompilationPlan(build)).toBeUndefined();+ expect(getDynamicPublishedMdxSourceBlockIds(build)).toEqual([]);+ expect(resolvePublishedMdxAssetCandidates({ build })).toEqual(new Map());+ });++ test("does not retain MDX used only by a draft page", () => {+ const build = createBuild({});+ build.instances.push({+ type: "instance",+ id: "draft-block",+ component: "ws:block",+ children: [],+ });+ build.props.push({+ id: "draft-source",+ instanceId: "draft-block",+ name: "src",+ type: "asset",+ value: "private-draft.mdx",+ });+ build.pages.pages.set("draft", {+ id: "draft",+ path: "draft",+ name: "Draft",+ title: "Draft",+ rootInstanceId: "draft-block",+ meta: {},+ isDraft: true,+ });++ const plan = createPublishedBuildContentCompilationPlan(build);++ expect(plan?.queries.map(({ id }) => id)).not.toContain(+ "__content-block-mdx__:private-draft.mdx"+ );+ });++ test("retains nested sources only through referenced templates", async () => {+ const build = createBuild({});+ build.instances[0].children = [{ type: "id", value: "templates" }];+ build.instances.push(+ {+ type: "instance",+ id: "templates",+ component: "ws:block-template",+ children: [+ { type: "id", value: "hero" },+ { type: "id", value: "unused" },+ ],+ },+ {+ type: "instance",+ id: "hero",+ component: "ws:element",+ tag: "section",+ label: "Hero",+ children: [{ type: "id", value: "nested" }],+ },+ {+ type: "instance",+ id: "nested",+ component: "ws:block",+ children: [],+ },+ {+ type: "instance",+ id: "unused",+ component: "ws:block",+ label: "Unused",+ children: [],+ }+ );+ build.props.push(+ {+ id: "nested-source",+ instanceId: "nested",+ name: "src",+ type: "asset",+ value: "nested.mdx",+ },+ {+ id: "unused-source",+ instanceId: "unused",+ name: "src",+ type: "asset",+ value: "private.mdx",+ }+ );+ const source = '{unsafe}\n\n<ws.element ws:name="Hero" />';+ const artifact = {+ format: "webstudio-content-database",+ version: 1,+ documents: [+ {+ _id: "article.mdx",+ _type: "asset.file",+ name: "article.mdx",+ path: "article.mdx",+ key: "article",+ extension: "mdx",+ mimeType: "text/mdx",+ size: source.length,+ revision: "article-revision",+ contentRef: "article.mdx",+ },+ ],+ contents: { "article.mdx": source },+ } as unknown as ContentArtifactV1;++ const plan = await resolvePublishedMdxDependencyClosure({+ build,+ artifact,+ });+ const queryIds = plan?.queries.map(({ id }) => id);++ expect(queryIds).toContain("__content-block-mdx__:nested.mdx");+ expect(queryIds).not.toContain("__content-block-mdx__:private.mdx");+ });++ test("keeps internal MDX retention out of Assets Resource plans", () => {+ expect(createBuildContentCompilationPlan(createBuild({}))).toBeUndefined();+ });++ test("omits an expression without a bounded publication dependency set", () => {+ const build = createBuild({ sourceType: "expression" });+ build.props[0].value = "post.body";++ expect(createPublishedBuildContentCompilationPlan(build)).toBeUndefined();+ });++ test.each(["detail", "collection"] as const)(+ "derives finite %s candidates while excluding unrelated MDX",+ (kind) => {+ const resourceVariable = encodeDataVariableId("posts-data");+ const itemVariable = encodeDataVariableId("collection-item");+ const build = createBuild({ sourceType: "expression" });+ build.instances.unshift({+ type: "instance",+ id: "collection",+ component: "ws:collection",+ children: [{ type: "id", value: "block" }],+ });+ build.props[0].value =+ kind === "detail"+ ? `${resourceVariable}.data.properties.mdx`+ : `${itemVariable}.properties.mdx`;+ if (kind === "collection") {+ build.props.push({+ id: "collection-data",+ instanceId: "collection",+ name: "data",+ type: "expression",+ value: `${resourceVariable}.data`,+ });+ build.props.push({+ id: "collection-item-prop",+ instanceId: "collection",+ name: "item",+ type: "parameter",+ value: "collection-item",+ });+ build.dataSources.push({+ type: "parameter",+ id: "collection-item",+ scopeInstanceId: "collection",+ name: "collectionItem",+ });+ }+ build.dataSources.push({+ type: "resource",+ id: "posts-data",+ scopeInstanceId: "collection",+ name: "posts",+ resourceId: "posts",+ });+ build.resources.push({+ id: "posts",+ name: "Posts",+ control: "system",+ method: "post",+ url: '"/$resources/assets"',+ headers: [],+ body: createStructuredAssetQueryResourceBody({+ where: {+ all: [+ {+ field: ["properties", "category"],+ operator: "eq",+ value: '"published"',+ },+ ],+ },+ sort: [],+ limit: "1",+ offset: "0",+ output: { mode: "all", includeMetadata: true },+ content: { mode: "none" },+ }),+ });+ const artifact = {+ documents: [+ {+ _id: "post",+ _type: "asset.file",+ name: "post.json",+ path: "post.json",+ key: "post",+ extension: "json",+ mimeType: "application/json",+ size: 1,+ properties: { category: "published", mdx: "article.mdx" },+ },+ {+ _id: "private-post",+ _type: "asset.file",+ name: "private.json",+ path: "private.json",+ key: "private",+ extension: "json",+ mimeType: "application/json",+ size: 1,+ properties: { category: "private", mdx: "private.mdx" },+ },+ {+ _id: "second-post",+ _type: "asset.file",+ name: "second.json",+ path: "second.json",+ key: "second",+ extension: "json",+ mimeType: "application/json",+ size: 1,+ properties: { category: "published", mdx: "second.mdx" },+ },+ ],+ } as unknown as ContentArtifactV1;++ const candidates = resolvePublishedMdxAssetCandidates({+ build,+ artifact,+ });+ const plan = createPublishedBuildContentCompilationPlan(+ build,+ candidates+ );++ expect(candidates.get("block")).toEqual(["article.mdx"]);+ expect(plan?.queries.map(({ id }) => id)).toContain(+ "__content-block-mdx__:article.mdx"+ );+ expect(plan?.queries.map(({ id }) => id)).not.toContain(+ "__content-block-mdx__:private.mdx"+ );+ expect(plan?.queries.map(({ id }) => id)).not.toContain(+ "__content-block-mdx__:second.mdx"+ );+ }+ );++ test("rejects a mutable project variable as an incomplete candidate set", () => {+ const build = createBuild({ sourceType: "expression" });+ build.props[0].value = encodeDataVariableId("article-source");+ build.dataSources.push({+ type: "variable",+ id: "article-source",+ scopeInstanceId: "block",+ name: "articleSource",+ value: { type: "string", value: "article.mdx" },+ });++ expect(() => resolvePublishedMdxAssetCandidates({ build })).toThrow(+ 'Content Block "block" has no finite dynamic MDX Asset candidates'+ );+ });+});diff --git a/packages/project-build/src/content-database.ts b/packages/project-build/src/content-database.tsindex cc67d0d778..c8bb2b5bee 100644--- a/packages/project-build/src/content-database.ts+++ b/packages/project-build/src/content-database.ts@@ -2,23 +2,94 @@ import {assetQuery,createContentDatabase,createContentCompilationPlan,+ createDocumentGraph,createLiteralContentCompilationQuery,+ getDocumentGraphQueryRootIds,hasDynamicContentCompilationValues,type AssetQueryInput,type ContentCompilationPlan,type ContentArtifactV1,+ defaultAssetResourceOutputSelection,+ getAssetQueryFieldValue,+ selectContentHydrationCandidates,+ type AssetFileDocument,} from "@webstudio-is/content-engine";import {+ blockComponent,+ collectionComponent,createReachableAssetContentCompilationPlan,+ decodeDataSourceVariable,+ findTreeInstanceIdsExcludingBlockTemplates,+ getContentBlockSource,+ getContentBlockSources,+ getStaticContentBlockSourceAssetId,+ isMdxFileAsset,+ getPublishablePages,type DataSource,+ type Instance,type Prop,type Resource,} from "@webstudio-is/sdk";-import type { Build, CompactBuild } from "./types";+import { parseStaticMemberPath } from "@webstudio-is/expression";+import type { Pages } from "@webstudio-is/sdk";+import { parseMdxDocumentRecovering } from "@webstudio-is/content-engine/mdx";+import { resolveMdxTemplates } from "./runtime/mdx-template-resolution";-type ContentDatabaseBuild =- | Pick<Build, "props" | "dataSources" | "resources">- | Pick<CompactBuild, "props" | "dataSources" | "resources">;+type BuildValues<Value> =+ | readonly Value[]+ | readonly (readonly [string, Value])[];++type ContentDatabaseBuild = {+ props: BuildValues<Prop>;+ dataSources: BuildValues<DataSource>;+ resources: BuildValues<Resource>;+};++type PublishedContentDatabaseBuild = ContentDatabaseBuild & {+ instances: BuildValues<Instance>;+ pages?: Pages;+};++const publishedMdxTotalBytes = 32 * 1024 * 1024;++export const getPublishedMdxContentDatabaseMaxBytes = ({+ baseBytes,+ assets,+}: {+ baseBytes: number;+ assets: readonly Readonly<{+ type: string;+ format: string;+ size: number;+ }>[];+}) =>+ baseBytes ++ Math.min(+ publishedMdxTotalBytes,+ assets.filter(isMdxFileAsset).reduce((total, { size }) => total + size, 0)+ );++const getPublishedInstanceIds = (build: PublishedContentDatabaseBuild) => {+ if (build.pages === undefined) {+ throw new Error("Published Content Block discovery requires page roots");+ }+ const instances = new Map(+ getBuildValues<Instance>(build.instances).map((instance) => [+ instance.id,+ instance,+ ])+ );+ const instanceIds = new Set<string>();+ for (const page of getPublishablePages(build.pages)) {+ for (const instanceId of findTreeInstanceIdsExcludingBlockTemplates(+ instances,+ page.rootInstanceId+ )) {+ instanceIds.add(instanceId);+ }+ }+ return instanceIds;+};const getBuildValues = <Item>(values: readonly Item[] | readonly (readonly [string, Item])[]@@ -36,6 +107,451 @@ export const createBuildContentCompilationPlan = (resources: getBuildValues<Resource>(build.resources),});+const getPublishedContentBlockSources = (+ build: PublishedContentDatabaseBuild,+ publishedInstanceIds: ReadonlySet<string> = getPublishedInstanceIds(build)+) => {+ const sources = getContentBlockSources({+ instances: getBuildValues<Instance>(build.instances).filter(({ id }) =>+ publishedInstanceIds.has(id)+ ),+ props: getBuildValues<Prop>(build.props),+ });+ return Array.from(sources, ([blockInstanceId, source]) => ({+ blockInstanceId,+ source,+ }));+};++export const getDynamicPublishedMdxSourceBlockIds = (+ build: PublishedContentDatabaseBuild,+ publishedInstanceIds: ReadonlySet<string> = getPublishedInstanceIds(build)+) =>+ getPublishedContentBlockSources(build, publishedInstanceIds).flatMap(+ ({ blockInstanceId, source }) =>+ source.type === "expression" &&+ source.value.length > 0 &&+ getStaticContentBlockSourceAssetId(source) === undefined+ ? [blockInstanceId]+ : []+ );++export const hasDynamicPublishedMdxSources = (+ build: PublishedContentDatabaseBuild,+ publishedInstanceIds?: ReadonlySet<string>+) =>+ getDynamicPublishedMdxSourceBlockIds(build, publishedInstanceIds).length > 0;++export const createPublishedBuildContentCompilationPlan = (+ build: PublishedContentDatabaseBuild,+ dynamicAssetIdsByBlock: ReadonlyMap<string, readonly string[]> = new Map(),+ publishedInstanceIds: ReadonlySet<string> = getPublishedInstanceIds(build)+) => {+ const sources = getPublishedContentBlockSources(build, publishedInstanceIds);+ const directAssetIds = new Set(+ sources.flatMap(({ blockInstanceId, source }) => {+ const assetId = getStaticContentBlockSourceAssetId(source);+ if (assetId !== undefined && assetId.length > 0) {+ return [assetId];+ }+ return dynamicAssetIdsByBlock.get(blockInstanceId) ?? [];+ })+ );+ const createMdxQuery = ({+ id,+ assetId,+ }: {+ id: string;+ assetId: string;+ }) => ({+ id,+ result: "many" as const,+ where: {+ all: [+ {+ field: ["extension"],+ operator: "eq" as const,+ value: { type: "literal" as const, value: "mdx" },+ },+ {+ field: ["id"],+ operator: "eq" as const,+ value: { type: "literal" as const, value: assetId },+ },+ ],+ },+ sort: [],+ // Keep content in the revisioned runtime artifact instead of folding it+ // into a materialized query result that the page compiler cannot consume.+ limit: { type: "dynamic" as const },+ offset: { type: "literal" as const, value: 0 },+ output: defaultAssetResourceOutputSelection,+ content: { mode: "full" as const },+ });+ return createContentCompilationPlan([+ ...(createBuildContentCompilationPlan(build)?.queries ?? []),+ ...Array.from(directAssetIds)+ .sort()+ .map((assetId) =>+ createMdxQuery({+ id: `__content-block-mdx__:${assetId}`,+ assetId,+ })+ ),+ ]);+};++/** Expands publication reachability through only the templates referenced by MDX. */+export const resolvePublishedMdxDependencyClosure = async ({+ build,+ artifact,+}: {+ build: PublishedContentDatabaseBuild;+ artifact: ContentArtifactV1;+}) => {+ const instances = new Map(+ getBuildValues<Instance>(build.instances).map((instance) => [+ instance.id,+ instance,+ ])+ );+ const props = getBuildValues<Prop>(build.props);+ const sourcesByBlockId = getContentBlockSources({+ instances: instances.values(),+ props,+ });+ const documentsById = new Map(+ artifact.documents.map((document) => [document._id, document])+ );+ const reachableIds = getPublishedInstanceIds(build);+ const pending = Array.from(reachableIds).filter(+ (id) => instances.get(id)?.component === blockComponent+ );+ const processed = new Set<string>();+ const visitTemplateSubtree = (rootInstanceId: string) => {+ for (const instanceId of findTreeInstanceIdsExcludingBlockTemplates(+ instances,+ rootInstanceId+ )) {+ if (reachableIds.has(instanceId)) {+ continue;+ }+ reachableIds.add(instanceId);+ if (instances.get(instanceId)?.component === blockComponent) {+ pending.push(instanceId);+ }+ }+ };++ while (pending.length > 0) {+ const blockId = pending.shift()!;+ if (processed.has(blockId)) {+ continue;+ }+ processed.add(blockId);+ const source = sourcesByBlockId.get(blockId);+ if (source === undefined) {+ continue;+ }+ const staticValue = getStaticContentBlockSourceAssetId(source);+ const assetIds =+ typeof staticValue === "string"+ ? [staticValue]+ : (resolvePublishedMdxAssetCandidates({+ build,+ artifact,+ blockInstanceIds: new Set([blockId]),+ }).get(blockId) ?? []);+ for (const assetId of assetIds) {+ const documentEntry = documentsById.get(assetId);+ const sourceText =+ documentEntry?.contentRef === undefined+ ? undefined+ : artifact.contents?.[documentEntry.contentRef];+ if (+ documentEntry?.revision === undefined ||+ documentEntry.contentRef === undefined ||+ sourceText === undefined+ ) {+ continue;+ }+ const parsed = await parseMdxDocumentRecovering({ source: sourceText });+ if (parsed.status === "unrecoverable") {+ continue;+ }+ const document = parsed.document;+ const resolution = resolveMdxTemplates({+ document,+ identity: {+ blockInstanceId: blockId,+ assetId,+ revision: documentEntry.revision,+ contentRef: documentEntry.contentRef,+ format: "mdx",+ renderScope: "publication-dependency-discovery",+ },+ instances,+ metas: new Map(),+ });+ for (const reference of resolution.references) {+ if (reference.type === "resolved-template") {+ visitTemplateSubtree(reference.templateInstanceId);+ }+ }+ }+ }+ const candidates = resolvePublishedMdxAssetCandidates({+ build,+ artifact,+ blockInstanceIds: reachableIds,+ allowUnresolved: true,+ });+ return createPublishedBuildContentCompilationPlan(+ build,+ candidates,+ reachableIds+ );+};++const candidateDocumentKey = Symbol("candidate-document");+type CandidateDocument = Readonly<{+ [candidateDocumentKey]: AssetFileDocument;+}>;++const isCandidateDocument = (value: unknown): value is CandidateDocument =>+ typeof value === "object" && value !== null && candidateDocumentKey in value;++const getValueAtPath = (+ value: unknown | CandidateDocument,+ path: readonly string[]+): unknown => {+ if (isCandidateDocument(value)) {+ return path.length === 0+ ? value[candidateDocumentKey]._id+ : getAssetQueryFieldValue(value[candidateDocumentKey], [...path]);+ }+ let current = value;+ for (const segment of path) {+ if (typeof current !== "object" || current === null) {+ return;+ }+ current = (current as Record<string, unknown>)[segment];+ }+ return current;+};++/** Resolves a finite dynamic src candidate set from compiled query records. */+export const resolvePublishedMdxAssetCandidates = ({+ build,+ artifact,+ allowUnresolved = false,+ blockInstanceIds = getPublishedInstanceIds(build),+}: {+ build: PublishedContentDatabaseBuild;+ artifact?: ContentArtifactV1;+ allowUnresolved?: boolean;+ blockInstanceIds?: ReadonlySet<string>;+}) => {+ const instances = new Map(+ getBuildValues<Instance>(build.instances).map((instance) => [+ instance.id,+ instance,+ ])+ );+ const props = getBuildValues<Prop>(build.props);+ const propsByInstance = new Map<string, Prop[]>();+ for (const prop of props) {+ const values = propsByInstance.get(prop.instanceId) ?? [];+ values.push(prop);+ propsByInstance.set(prop.instanceId, values);+ }+ const dataSources = new Map(+ getBuildValues<DataSource>(build.dataSources).map((dataSource) => [+ dataSource.id,+ dataSource,+ ])+ );+ const basePlan = createBuildContentCompilationPlan(build);+ const queriesById = new Map(+ (basePlan?.queries ?? []).map((query) => [query.id, query])+ );+ const documentGraph =+ artifact?.documentGraph === undefined+ ? undefined+ : createDocumentGraph(artifact.documentGraph);+ const documents = (artifact?.documents ?? []).filter(+ (document): document is AssetFileDocument => document._type === "asset.file"+ );++ const evaluateDataSource = (+ dataSourceId: string,+ path: readonly string[],+ visiting = new Set<string>()+ ): unknown[] => {+ if (visiting.has(dataSourceId)) {+ throw new Error("Dynamic MDX source data dependency is cyclic");+ }+ const dataSource = dataSources.get(dataSourceId);+ if (dataSource === undefined) {+ return [];+ }+ if (dataSource.type === "variable") {+ // Project variables can be changed by actions after publication. Their+ // initial value is therefore not a complete dependency set.+ return [];+ }+ if (dataSource.type === "resource") {+ if (artifact === undefined) {+ return [];+ }+ const includedDocumentCount =+ artifact.database?.includedDocumentCount ?? artifact.documents.length;+ const sourceDocumentCount =+ artifact.database?.sourceDocumentCount ?? includedDocumentCount;+ if (includedDocumentCount < sourceDocumentCount) {+ throw new Error(+ "Dynamic MDX source candidates cannot be proven from a truncated content database"+ );+ }+ const query = queriesById.get(dataSource.resourceId);+ if (query === undefined || basePlan === undefined) {+ return [];+ }+ if (documentGraph !== undefined) {+ if (+ getDocumentGraphQueryRootIds({ graph: documentGraph, query }).length >+ 0+ ) {+ throw new Error(+ "Dynamic MDX source candidates through resolved document references are not supported safely for publication"+ );+ }+ }+ const candidateIds = selectContentHydrationCandidates({+ documents,+ plan: {+ ...basePlan,+ queries: [+ {+ ...query,+ content: { mode: "full" },+ },+ ],+ },+ });+ const fieldPath = path[0] === "data" ? path.slice(1) : path;+ return documents+ .filter(({ _id }) => candidateIds.has(_id))+ .map((document) =>+ fieldPath.length === 0+ ? ({+ [candidateDocumentKey]: document,+ } satisfies CandidateDocument)+ : getAssetQueryFieldValue(document, [...fieldPath])+ );+ }+ const collection = instances.get(dataSource.scopeInstanceId ?? "");+ if (collection?.component !== collectionComponent) {+ return [];+ }+ const dataProp = propsByInstance+ .get(collection.id)+ ?.find((prop) => prop.name === "data");+ const parameterProp = propsByInstance+ .get(collection.id)+ ?.find(+ (prop) => prop.type === "parameter" && prop.value === dataSource.id+ );+ if (parameterProp?.name !== "item" && parameterProp?.name !== "itemKey") {+ return [];+ }+ let iterables: unknown[] = [];+ if (dataProp?.type === "json") {+ iterables = [dataProp.value];+ } else if (dataProp?.type === "expression") {+ const dataPath = parseStaticMemberPath(dataProp.value);+ const dependencyId =+ dataPath === undefined+ ? undefined+ : decodeDataSourceVariable(dataPath[0]);+ if (dependencyId !== undefined && dataPath !== undefined) {+ visiting.add(dataSourceId);+ iterables = evaluateDataSource(+ dependencyId,+ dataPath.slice(1),+ visiting+ );+ visiting.delete(dataSourceId);+ }+ }+ const items = iterables.flatMap((iterable) => {+ if (Array.isArray(iterable)) {+ return parameterProp.name === "itemKey"+ ? iterable.map((_, index) => index)+ : iterable;+ }+ if (+ typeof iterable === "object" &&+ iterable !== null &&+ isCandidateDocument(iterable) === false+ ) {+ return parameterProp.name === "itemKey"+ ? Object.keys(iterable)+ : Object.values(iterable);+ }+ return [iterable];+ });+ return items.map((item) => getValueAtPath(item, path));+ };++ const candidatesByBlock = new Map<string, readonly string[]>();+ for (const blockInstanceId of blockInstanceIds) {+ if (instances.get(blockInstanceId)?.component !== blockComponent) {+ continue;+ }+ const source = getContentBlockSource({+ blockInstanceId,+ props: propsByInstance.get(blockInstanceId) ?? [],+ });+ if (+ source?.type !== "expression" ||+ getStaticContentBlockSourceAssetId(source) !== undefined+ ) {+ continue;+ }+ const path = parseStaticMemberPath(source.value);+ const dataSourceId =+ path === undefined ? undefined : decodeDataSourceVariable(path[0]);+ let assetIds: string[] = [];+ try {+ assetIds =+ dataSourceId === undefined || path === undefined+ ? []+ : evaluateDataSource(dataSourceId, path.slice(1)).filter(+ (value): value is string =>+ typeof value === "string" && value.length > 0+ );+ } catch (error) {+ if (allowUnresolved === false) {+ throw error;+ }+ }+ if (assetIds.length === 0) {+ if (allowUnresolved) {+ continue;+ }+ throw new Error(+ `Content Block "${blockInstanceId}" has no finite dynamic MDX Asset candidates`+ );+ }+ candidatesByBlock.set(+ blockInstanceId,+ Array.from(new Set(assetIds)).sort()+ );+ }+ return candidatesByBlock;+};+export const createAssetQueryPreviewCompilationPlan = ({databasePlan,query,diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.tsindex 0246ec8597..b513ca21c5 100644--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts@@ -2,6 +2,3447 @@// Do not edit manually.export const runtimeOperationContractData = [+ {+ id: "contentBlocks.inspectSource",+ command: "inspect-content-block-source",+ client: "inspectContentBlockSource",+ permit: "view",+ kind: "read",+ inputSchema: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ variables: {+ type: "object",+ propertyNames: {+ type: "string",+ },+ additionalProperties: {},+ },+ },+ required: ["blockInstanceId", "renderScope"],+ },+ outputSchema: {+ type: "object",+ properties: {+ source: {+ type: "string",+ },+ sessionStatus: {+ type: "string",+ enum: ["saved", "pending", "saving", "failed", "conflicting"],+ },+ identity: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ },+ assetId: {+ type: "string",+ },+ revision: {+ type: "string",+ },+ contentRef: {+ type: "string",+ },+ format: {+ type: "string",+ const: "mdx",+ },+ renderScope: {+ type: "string",+ },+ },+ required: [+ "blockInstanceId",+ "assetId",+ "revision",+ "contentRef",+ "format",+ "renderScope",+ ],+ additionalProperties: {},+ },+ diagnostics: {+ type: "array",+ items: {+ oneOf: [+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "invalid-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ message: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["blockInstanceId", "code", "severity", "message"],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unsafe-mdx",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ nodeType: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "nodeType",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unresolved-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ignored-template-prop",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ propName: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ enum: ["unknown", "incompatible", "design-only", "stale"],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ "propName",+ "reason",+ ],+ additionalProperties: false,+ },+ ],+ },+ },+ },+ required: ["source", "sessionStatus", "identity", "diagnostics"],+ additionalProperties: {},+ },+ readNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ requiresAssets: true,+ },+ {+ id: "contentBlocks.connectSource",+ command: "connect-content-block-source",+ client: "connectContentBlockSource",+ permit: "edit",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ variables: {+ type: "object",+ propertyNames: {+ type: "string",+ },+ additionalProperties: {},+ },+ source: {+ oneOf: [+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "asset",+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["type", "assetId"],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "expression",+ },+ value: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["type", "value"],+ additionalProperties: false,+ },+ ],+ },+ },+ required: ["blockInstanceId", "renderScope", "source"],+ },+ outputSchema: {+ type: "object",+ properties: {+ action: {+ type: "string",+ const: "connect",+ },+ requiresConfirmation: {+ type: "boolean",+ },+ diagnostics: {+ type: "array",+ items: {+ oneOf: [+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "invalid-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ message: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["blockInstanceId", "code", "severity", "message"],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unsafe-mdx",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ nodeType: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "nodeType",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unresolved-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ignored-template-prop",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ propName: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ enum: ["unknown", "incompatible", "design-only", "stale"],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ "propName",+ "reason",+ ],+ additionalProperties: false,+ },+ ],+ },+ },+ },+ required: ["action", "requiresConfirmation", "diagnostics"],+ additionalProperties: {},+ },+ readNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ writeNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ invalidatesNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ retryOnConflict: false,+ requiresAssets: true,+ },+ {+ id: "contentBlocks.switchSource",+ command: "switch-content-block-source",+ client: "switchContentBlockSource",+ permit: "edit",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ variables: {+ type: "object",+ propertyNames: {+ type: "string",+ },+ additionalProperties: {},+ },+ source: {+ oneOf: [+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "asset",+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["type", "assetId"],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "expression",+ },+ value: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["type", "value"],+ additionalProperties: false,+ },+ ],+ },+ },+ required: ["blockInstanceId", "renderScope", "source"],+ },+ outputSchema: {+ type: "object",+ properties: {+ action: {+ type: "string",+ const: "switch",+ },+ requiresConfirmation: {+ type: "boolean",+ },+ diagnostics: {+ type: "array",+ items: {+ oneOf: [+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "invalid-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ message: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["blockInstanceId", "code", "severity", "message"],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unsafe-mdx",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ nodeType: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "nodeType",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unresolved-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ignored-template-prop",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ propName: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ enum: ["unknown", "incompatible", "design-only", "stale"],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ "propName",+ "reason",+ ],+ additionalProperties: false,+ },+ ],+ },+ },+ },+ required: ["action", "requiresConfirmation", "diagnostics"],+ additionalProperties: {},+ },+ readNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ writeNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ invalidatesNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ retryOnConflict: false,+ requiresAssets: true,+ },+ {+ id: "contentBlocks.disconnectSource",+ command: "disconnect-content-block-source",+ client: "disconnectContentBlockSource",+ permit: "edit",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ variables: {+ type: "object",+ propertyNames: {+ type: "string",+ },+ additionalProperties: {},+ },+ },+ required: ["blockInstanceId", "renderScope"],+ },+ outputSchema: {+ type: "object",+ properties: {+ action: {+ type: "string",+ const: "disconnect",+ },+ requiresConfirmation: {+ type: "boolean",+ },+ diagnostics: {+ type: "array",+ items: {+ oneOf: [+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "invalid-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ message: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["blockInstanceId", "code", "severity", "message"],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unsafe-mdx",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ nodeType: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "nodeType",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unresolved-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ignored-template-prop",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ propName: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ enum: ["unknown", "incompatible", "design-only", "stale"],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ "propName",+ "reason",+ ],+ additionalProperties: false,+ },+ ],+ },+ },+ },+ required: ["action", "requiresConfirmation", "diagnostics"],+ additionalProperties: {},+ },+ readNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ writeNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ invalidatesNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ retryOnConflict: false,+ requiresAssets: true,+ },+ {+ id: "contentBlocks.editSource",+ command: "edit-content-block-source",+ client: "editContentBlockSource",+ permit: "edit",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ variables: {+ type: "object",+ propertyNames: {+ type: "string",+ },+ additionalProperties: {},+ },+ source: {+ type: "string",+ },+ },+ required: ["blockInstanceId", "renderScope", "source"],+ },+ outputSchema: {+ type: "object",+ properties: {+ assetId: {+ type: "string",+ },+ source: {+ type: "string",+ },+ status: {+ type: "string",+ enum: ["saved", "pending", "saving", "failed", "conflicting"],+ },+ diagnostics: {+ type: "array",+ items: {+ oneOf: [+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "invalid-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ message: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["blockInstanceId", "code", "severity", "message"],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unsafe-mdx",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ nodeType: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "nodeType",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unresolved-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ignored-template-prop",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ propName: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ enum: ["unknown", "incompatible", "design-only", "stale"],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ "propName",+ "reason",+ ],+ additionalProperties: false,+ },+ ],+ },+ },+ },+ required: ["assetId", "source", "status", "diagnostics"],+ additionalProperties: {},+ },+ readNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ writeNamespaces: ["assets"],+ invalidatesNamespaces: ["assets"],+ retryOnConflict: false,+ requiresAssets: true,+ },+ {+ id: "contentBlocks.updateFrontmatter",+ command: "update-content-block-frontmatter",+ client: "updateContentBlockFrontmatter",+ permit: "edit",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ variables: {+ type: "object",+ propertyNames: {+ type: "string",+ },+ additionalProperties: {},+ },+ properties: {+ type: "object",+ propertyNames: {+ type: "string",+ },+ additionalProperties: {},+ },+ },+ required: ["blockInstanceId", "renderScope", "properties"],+ },+ outputSchema: {+ type: "object",+ properties: {+ assetId: {+ type: "string",+ },+ source: {+ type: "string",+ },+ status: {+ type: "string",+ enum: ["saved", "pending", "saving", "failed", "conflicting"],+ },+ diagnostics: {+ type: "array",+ items: {+ oneOf: [+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "invalid-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ message: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["blockInstanceId", "code", "severity", "message"],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unsafe-mdx",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ nodeType: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "nodeType",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unresolved-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ignored-template-prop",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ propName: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ enum: ["unknown", "incompatible", "design-only", "stale"],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ "propName",+ "reason",+ ],+ additionalProperties: false,+ },+ ],+ },+ },+ },+ required: ["assetId", "source", "status", "diagnostics"],+ additionalProperties: {},+ },+ readNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ writeNamespaces: ["assets"],+ invalidatesNamespaces: ["assets"],+ retryOnConflict: false,+ requiresAssets: true,+ },+ {+ id: "contentBlocks.reloadSource",+ command: "reload-content-block-source",+ client: "reloadContentBlockSource",+ permit: "view",+ kind: "read",+ inputSchema: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ variables: {+ type: "object",+ propertyNames: {+ type: "string",+ },+ additionalProperties: {},+ },+ },+ required: ["blockInstanceId", "renderScope"],+ },+ outputSchema: {+ type: "object",+ properties: {+ assetId: {+ type: "string",+ },+ source: {+ type: "string",+ },+ status: {+ type: "string",+ enum: ["saved", "pending", "saving", "failed", "conflicting"],+ },+ diagnostics: {+ type: "array",+ items: {+ oneOf: [+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "invalid-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ message: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["blockInstanceId", "code", "severity", "message"],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unsafe-mdx",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ nodeType: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "nodeType",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unresolved-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ignored-template-prop",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ propName: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ enum: ["unknown", "incompatible", "design-only", "stale"],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ "propName",+ "reason",+ ],+ additionalProperties: false,+ },+ ],+ },+ },+ },+ required: ["assetId", "source", "status", "diagnostics"],+ additionalProperties: {},+ },+ readNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ requiresAssets: true,+ },+ {+ id: "contentBlocks.migrateTemplateReferences",+ command: "migrate-content-block-template-references",+ client: "migrateContentBlockTemplateReferences",+ permit: "edit",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ assetIds: {+ minItems: 1,+ maxItems: 100,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ migration: {+ anyOf: [+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "rename",+ },+ from: {+ type: "string",+ minLength: 1,+ },+ to: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["type", "from", "to"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "remove",+ },+ name: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["type", "name"],+ },+ ],+ },+ confirmationToken: {+ type: "string",+ },+ },+ required: ["assetIds", "migration"],+ },+ outputSchema: {+ type: "object",+ properties: {+ status: {+ type: "string",+ enum: ["confirmation-required", "complete", "partial"],+ },+ updateCount: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ omissionCount: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ changedFileCount: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ files: {+ type: "array",+ items: {+ type: "object",+ properties: {+ assetId: {+ type: "string",+ },+ revision: {+ type: "string",+ },+ contentRef: {+ type: "string",+ },+ changed: {+ type: "boolean",+ },+ status: {+ type: "string",+ enum: ["updated", "unchanged", "failed"],+ },+ updateCount: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ omissionCount: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ diagnostics: {+ type: "array",+ items: {+ type: "object",+ properties: {+ code: {+ type: "string",+ },+ message: {+ type: "string",+ },+ },+ required: ["code", "message"],+ additionalProperties: {},+ },+ },+ },+ required: [+ "assetId",+ "revision",+ "contentRef",+ "changed",+ "updateCount",+ "omissionCount",+ "diagnostics",+ ],+ additionalProperties: {},+ },+ },+ confirmation: {+ type: "object",+ properties: {+ token: {+ type: "string",+ },+ expiresAt: {+ type: "string",+ },+ },+ required: ["token", "expiresAt"],+ additionalProperties: {},+ },+ },+ required: [+ "status",+ "updateCount",+ "omissionCount",+ "changedFileCount",+ "files",+ ],+ additionalProperties: {},+ },+ readNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ writeNamespaces: ["assets"],+ invalidatesNamespaces: ["assets"],+ retryOnConflict: false,+ requiresAssets: true,+ },{id: "pages.list",command: "list-pages",@@ -3577,6 +7018,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -3651,6 +7098,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -4513,6 +7966,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["id",@@ -6765,6 +10224,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -6839,6 +10304,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -7701,6 +11172,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["id",@@ -9964,6 +13441,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -10038,6 +13521,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -10900,6 +14389,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["id",@@ -13152,6 +16647,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -13226,6 +16727,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -14088,6 +17595,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["id",@@ -19041,6 +22554,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -19115,6 +22634,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -20005,6 +23530,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["id",@@ -22437,6 +25968,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -22511,6 +26048,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -23401,6 +26944,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["id",@@ -26074,6 +29623,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -26508,6 +30063,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["id", "instanceId", "name", "type", "value"],},@@ -28837,6 +32398,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["id", "instanceId", "name", "type", "value"],},@@ -37078,6 +40645,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -37152,6 +40725,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -38014,6 +41593,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["id",@@ -40345,6 +43930,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -40419,6 +44010,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -41281,6 +44878,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["id",@@ -43559,6 +47162,12 @@ export const runtimeOperationContractData = [description:"One Webstudio JavaScript expression. Read webstudio://project/expressions before using unfamiliar scope or syntax.",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -46544,6 +50153,36 @@ export const runtimeOperationContractData = [minimum: 0,maximum: 9007199254740991,},+ templateNameConfirmation: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["rename", "delete"],+ },+ templates: {+ type: "array",+ items: {+ type: "object",+ properties: {+ instanceId: {+ type: "string",+ },+ oldName: {+ type: "string",+ },+ newName: {+ type: "string",+ },+ },+ required: ["instanceId", "oldName"],+ },+ },+ },+ required: ["action", "templates"],+ description:+ "Retry with the exact confirmation example returned by template_name_change_requires_confirmation after user approval.",+ },},required: ["parentInstanceId", "component"],},@@ -46620,6 +50259,519 @@ export const runtimeOperationContractData = [retryOnConflict: false,requiresAssets: true,},+ {+ id: "instances.insertMdxText",+ command: "insert-mdx-text",+ client: "insertMdxText",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ parentInstanceId: {+ type: "string",+ minLength: 1,+ },+ source: {+ type: "string",+ minLength: 1,+ },+ mode: {+ type: "string",+ enum: ["append", "prepend", "replace"],+ },+ insertIndex: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ templateNameConfirmation: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["rename", "delete"],+ },+ templates: {+ type: "array",+ items: {+ type: "object",+ properties: {+ instanceId: {+ type: "string",+ },+ oldName: {+ type: "string",+ },+ newName: {+ type: "string",+ },+ },+ required: ["instanceId", "oldName"],+ },+ },+ },+ required: ["action", "templates"],+ description:+ "Retry with the exact confirmation example returned by template_name_change_requires_confirmation after user approval.",+ },+ },+ required: ["parentInstanceId", "source"],+ },+ outputSchema: {+ type: "object",+ properties: {+ instanceIds: {+ type: "array",+ items: {+ type: "string",+ },+ },+ rootInstanceIds: {+ type: "array",+ items: {+ type: "string",+ },+ },+ removedInstanceIds: {+ type: "array",+ items: {+ type: "string",+ },+ },+ parentInstanceId: {+ type: "string",+ },+ didMergeBreakpointsDueToLimit: {+ type: "boolean",+ const: true,+ },+ diagnostics: {+ type: "array",+ items: {+ oneOf: [+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "invalid-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ message: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["blockInstanceId", "code", "severity", "message"],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unsafe-mdx",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ nodeType: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "nodeType",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unresolved-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ignored-template-prop",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ propName: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ enum: ["unknown", "incompatible", "design-only", "stale"],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ "propName",+ "reason",+ ],+ additionalProperties: false,+ },+ ],+ },+ },+ },+ required: [+ "instanceIds",+ "rootInstanceIds",+ "removedInstanceIds",+ "parentInstanceId",+ "diagnostics",+ ],+ },+ readNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ writeNamespaces: [+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ invalidatesNamespaces: [+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ retryOnConflict: false,+ requiresAssets: true,+ },{id: "instances.insertCollection",command: "insert-collection",@@ -46724,6 +50876,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -46798,6 +50956,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -47607,6 +51771,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["id", "instanceId", "name", "type", "value"],},@@ -52601,6 +56771,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -52675,6 +56851,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -53484,6 +57666,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["id", "instanceId", "name", "type", "value"],},@@ -55621,6 +59809,36 @@ export const runtimeOperationContractData = [minimum: 0,maximum: 9007199254740991,},+ templateNameConfirmation: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["rename", "delete"],+ },+ templates: {+ type: "array",+ items: {+ type: "object",+ properties: {+ instanceId: {+ type: "string",+ },+ oldName: {+ type: "string",+ },+ newName: {+ type: "string",+ },+ },+ required: ["instanceId", "oldName"],+ },+ },+ },+ required: ["action", "templates"],+ description:+ "Retry with the exact confirmation example returned by template_name_change_requires_confirmation after user approval.",+ },},required: ["fragment"],$defs: {@@ -58753,6 +62971,36 @@ export const runtimeOperationContractData = [type: "string",minLength: 1,},+ templateNameConfirmation: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["rename", "delete"],+ },+ templates: {+ type: "array",+ items: {+ type: "object",+ properties: {+ instanceId: {+ type: "string",+ },+ oldName: {+ type: "string",+ },+ newName: {+ type: "string",+ },+ },+ required: ["instanceId", "oldName"],+ },+ },+ },+ required: ["action", "templates"],+ description:+ "Retry with the exact confirmation example returned by template_name_change_requires_confirmation after user approval.",+ },},required: ["instanceSelector", "component"],},@@ -58995,6 +63243,36 @@ export const runtimeOperationContractData = [type: "string",},},+ templateNameConfirmation: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["rename", "delete"],+ },+ templates: {+ type: "array",+ items: {+ type: "object",+ properties: {+ instanceId: {+ type: "string",+ },+ oldName: {+ type: "string",+ },+ newName: {+ type: "string",+ },+ },+ required: ["instanceId", "oldName"],+ },+ },+ },+ required: ["action", "templates"],+ description:+ "Retry with the exact confirmation example returned by template_name_change_requires_confirmation after user approval.",+ },},required: ["instanceIds"],},@@ -59059,6 +63337,36 @@ export const runtimeOperationContractData = [type: "string",},},+ templateNameConfirmation: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["rename", "delete"],+ },+ templates: {+ type: "array",+ items: {+ type: "object",+ properties: {+ instanceId: {+ type: "string",+ },+ oldName: {+ type: "string",+ },+ newName: {+ type: "string",+ },+ },+ required: ["instanceId", "oldName"],+ },+ },+ },+ required: ["action", "templates"],+ description:+ "Retry with the exact confirmation example returned by template_name_change_requires_confirmation after user approval.",+ },},required: ["instanceSelector"],},@@ -59395,6 +63703,12 @@ export const runtimeOperationContractData = [description:"One Webstudio JavaScript expression, not a statement or function. Read webstudio://project/expressions for syntax and scope rules.",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["instanceId", "name", "type", "value"],},@@ -61666,6 +65980,12 @@ export const runtimeOperationContractData = [description:"One Webstudio JavaScript expression. Read webstudio://project/expressions before using unfamiliar scope or syntax.",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -61981,6 +66301,12 @@ export const runtimeOperationContractData = [type: "string",enum: ["text", "expression"],},+ expressionBindingMode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["instanceId", "childIndex", "text"],},@@ -62060,7 +66386,7 @@ export const runtimeOperationContractData = [required: ["instanceId", "childIndex", "mode"],additionalProperties: {},},- readNamespaces: ["instances", "dataSources"],+ readNamespaces: ["instances", "props", "dataSources"],writeNamespaces: ["instances"],invalidatesNamespaces: ["instances"],retryOnConflict: true,@@ -62187,6 +66513,12 @@ export const runtimeOperationContractData = [type: "string",enum: ["text", "expression"],},+ expressionBindingMode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["operation", "instanceId", "text"],},@@ -62319,7 +66651,7 @@ export const runtimeOperationContractData = [required: ["instanceId", "operation"],additionalProperties: {},},- readNamespaces: ["instances", "dataSources"],+ readNamespaces: ["instances", "props", "dataSources"],writeNamespaces: ["instances"],invalidatesNamespaces: ["instances"],retryOnConflict: true,@@ -62405,6 +66737,12 @@ export const runtimeOperationContractData = [value: {type: "string",},+ mode: {+ type: "string",+ enum: ["read", "readwrite"],+ description:+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.',+ },},required: ["type", "value"],},@@ -62491,6 +66829,36 @@ export const runtimeOperationContractData = [legacyPropName: {type: "string",},+ templateNameConfirmation: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["rename", "delete"],+ },+ templates: {+ type: "array",+ items: {+ type: "object",+ properties: {+ instanceId: {+ type: "string",+ },+ oldName: {+ type: "string",+ },+ newName: {+ type: "string",+ },+ },+ required: ["instanceId", "oldName"],+ },+ },+ },+ required: ["action", "templates"],+ description:+ "Retry with the exact confirmation example returned by template_name_change_requires_confirmation after user approval.",+ },},required: ["instanceId", "tag"],},@@ -62527,6 +66895,36 @@ export const runtimeOperationContractData = [label: {type: "string",},+ templateNameConfirmation: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["rename", "delete"],+ },+ templates: {+ type: "array",+ items: {+ type: "object",+ properties: {+ instanceId: {+ type: "string",+ },+ oldName: {+ type: "string",+ },+ newName: {+ type: "string",+ },+ },+ required: ["instanceId", "oldName"],+ },+ },+ },+ required: ["action", "templates"],+ description:+ "Retry with the exact confirmation example returned by template_name_change_requires_confirmation after user approval.",+ },},required: ["instanceId", "label"],},diff --git a/packages/project-build/src/docs.generated.ts b/packages/project-build/src/docs.generated.tsindex be43bd9ec0..a88cea6aca 100644--- a/packages/project-build/src/docs.generated.ts+++ b/packages/project-build/src/docs.generated.ts@@ -4,7 +4,7 @@ export const projectBuildDocs = {"accessibility-review":'<!-- Adapted for Webstudio MCP from Community-Access/accessibility-agents, web-accessibility-wizard/SKILL.md (MIT): https://github.com/Community-Access/accessibility-agents/blob/main/codex-skills/web-accessibility-wizard/SKILL.md -->\n\n# Webstudio Accessibility Review\n\nUse this workflow when creating or reviewing a page, component, form, menu,\ndialog, or responsive layout. It is an LLM-assisted review, not proof of WCAG\nconformance. Do not claim that a page is accessible solely because this review\nhas no findings.\n\n## Evidence First\n\n1. Read `meta.index` and use focused project tools. Do not inspect Webstudio\n source code or generated files for normal project reviews.\n2. Run `audit` with `{"scopes":["accessibility"]}` before changing\n anything. It detects deterministic metadata issues such as labels, landmark\n structure, positive tabindex values, invalid static ARIA states, and unmuted\n autoplay. Fix confirmed static findings first.\n3. Ask whether the user wants visual verification unless they explicitly\n requested it. Only after they opt in, use `preview.start` and capture each\n changed route with `screenshot` at desktop, tablet, and mobile widths. Use\n `waitForSelector` or `waitForTimeout` only when the page has an actual\n delayed ready state. If they do not opt in, continue with static evidence\n and mark visual findings as manual verification items.\n4. Use `get-page-by-path`, `list-instances`, `inspect-instance`, and focused\n prop/style reads to verify semantics and authored state that screenshots\n cannot prove.\n5. Make only supported, evidence-based fixes with semantic MCP tools. Recheck\n the affected route and the static accessibility search after every fix.\n\n## Review Areas\n\nReview these areas in priority order. Record the evidence for every finding.\n\n### 1. Names, Semantics, and Structure\n\n- Every image has purposeful alternative text or an explicitly empty alt when\n decorative. Image-submit inputs need a non-empty alt label describing their\n action.\n- For `missing-image-description` findings, inspect the rendered image in its\n page context and call `set-image-descriptions` with either a concise generated\n description or `decorative: true`. Re-run the audit after saving the decision.\n- Buttons, links, icon-only controls, and form controls have accessible names.\n- Prefer native HTML semantics over ARIA roles.\n- Non-native elements using `role="button"` or `role="link"` must be\n keyboard-focusable.\n- Use one sensible page h1, ordered heading levels, meaningful link text, and\n a main landmark.\n- Iframes have titles. Static HTML ids are unique, ARIA reference props point\n to real ids, and static boolean/select/numeric ARIA values are valid.\n- Focusable controls must not be hidden from assistive technology with\n `aria-hidden`.\n\n### 2. Keyboard and Focus\n\n- Interactive controls should be native or have a documented keyboard model.\n- Visible focus must not be removed without a visible replacement.\n- Hover-only information or controls need a keyboard-accessible equivalent.\n- Do not use positive tabindex values.\n- Mark keyboard behavior as **manual verification required** when the available\n evidence cannot prove tab order, Escape handling, or focus restoration.\n\n### 3. Dialogs, Menus, and Other Overlays\n\n- Dialogs need an accessible name and a close action.\n- Opening an overlay should move focus into it, trap focus where appropriate,\n and restore focus to its trigger on close.\n- Menus, popovers, disclosures, and tabs must expose their expanded/selected\n state and remain usable without a pointer.\n- If the current MCP/browser tools cannot exercise the interaction, report it\n as a manual verification item instead of guessing.\n\n### 4. Forms and Errors\n\n- Inputs have labels, required state, helpers, and errors associated with the\n right control.\n- Invalid controls expose `aria-invalid` when applicable.\n- Error, loading, and success feedback is not conveyed only by color or a\n transient visual toast.\n- Submit controls do not become unexplained dead ends when disabled.\n\n### 5. Visual, Responsive, Media, and Motion\n\n- At each target width, text remains readable, controls remain reachable, and\n no content is clipped, overlapped, or dependent on hover alone.\n- Do not rely only on color, position, shape, or iconography to convey meaning.\n- Keep non-text contrast, text contrast, focus indicators, and small text as\n visual review items unless measured evidence is available.\n- Videos with meaningful speech need captions; non-essential motion should\n respect reduced-motion preferences. Do not autoplay sound.\n\n### 6. Dynamic Content and Data\n\n- Loading, empty, error, and success states have understandable visible text.\n- Important dynamic updates and validation feedback need an appropriate\n announcement strategy.\n- Check repeated resource-driven content for unique labels, headings, ids, and\n meaningful empty states.\n\n## Findings and Fixes\n\nClassify every item as one of:\n\n- **Confirmed:** directly shown by `audit`, project data, or a rendered\n screenshot.\n- **Likely:** a credible issue inferred from rendered evidence; explain what\n would confirm it.\n- **Manual verification required:** needs keyboard, screen-reader, contrast, or\n interaction testing that the available tools cannot prove.\n\nFor each item include: severity (`critical`, `high`, `medium`, or `low`), page\npath, affected element or instance id when known, evidence, short user impact,\nand the smallest supported fix. Fix critical and high items first. Do not add\nARIA attributes, alt text, labels, or live regions when their meaning cannot be\nknown from the project; ask the user or report the missing context.\n\nFinish with a concise summary of fixed findings, remaining findings, and manual\nverification items. Use screenshots as evidence of the rendered state, not as\nproof of accessibility compliance.\n',expressions:- '# Webstudio Expressions\n\nUse an expression only when a value must be computed at runtime from scoped\ndata. Use direct text and direct prop values for fixed content.\n\n## Source Format\n\nExpression-capable MCP fields receive JavaScript expression source as a JSON\nstring. Send one expression, without a `return` statement or surrounding\nfunction. For example:\n\n```json\n{ "binding": { "type": "expression", "value": "post.title ?? \\"Untitled\\"" } }\n```\n\nInside that string, use readable JavaScript syntax rather than serialized JSON.\nFor object expressions, leave identifier property names unquoted, for example\n`{ query: queryText, variables: { slug: system.params.slug } }`. Quote a property\nname only when JavaScript requires it, such as `{ "published-at": date }`. Do\nnot pass a JSON-stringified object as an expression.\n\nDo not send a fixed prop string as an expression. Use `update-props` with\n`type:"string"`. Page metadata and resource URLs accept plain fixed strings and\nnormalize them for storage. Expression-only resource headers, search parameters,\nand bodies accept `{ "type": "literal", "value": "fixed text" }` when the\nvalue is not dynamic.\n\n## Scope\n\n- Data variables are available on their scope instance and descendants.\n- An inner variable with the same name masks the outer variable.\n- A scoped resource result is a variable. Read its payload from its result\n wrapper, usually `resourceName.data`; APIs may nest the desired value deeper.\n- Collection creates internal `collectionItem` and `collectionItemKey`\n parameters. They are available only to that Collection\'s descendants.\n Preserve those generated parameters and do not reuse encoded parameter ids\n copied from another Collection.\n- Array Collection iteration exposes the current item. Object iteration exposes\n the current key and value.\n- The built-in `system` context is available only where supplied by the runtime.\n Its documented fields are `system.origin`, `system.pathname`, `system.params`,\n and `system.search`. There is no `system.path`.\n- Actions expose only their declared arguments, such as `event`, plus data that\n is in scope.\n\nRead `list-variables`, `list-resources`, `inspect-instance`, and existing\nbindings before writing an expression. Do not guess identifier names. Syntax is\nvalidated when a mutation is submitted. A valid expression that references an\nidentifier unavailable in that scope is accepted with a structured warning\ncontaining the field path, source range, affected record, and remediation.\n\n## Supported Syntax\n\nExpressions support literals, arrays, objects, property and index access, unary\nand arithmetic operators, comparisons, logical operators, nullish coalescing,\nternaries, and template literals.\n\nWebstudio automatically makes property and index access safe when an\nintermediate value is missing. Write direct access such as `post.author.name`.\nUse nullish coalescing when the expression needs a fallback value.\n\nSupported string methods:\n\n{{allowedStringMethods}}\n\nSupported array methods:\n\n{{allowedArrayMethods}}\n\nOther values support `toString`. Arbitrary global functions and arbitrary\nmethod calls are not supported.\n\n## Unsupported Syntax\n\nDo not use statements, declarations, functions, arrow functions, classes,\n`new`, `this`, `await`, imports, tagged templates, sequence expressions,\nincrement/decrement, or destructuring assignment. Assignment is allowed only\ninside actions. Use an explicit assignment there rather than `++` or `--`.\n\n## Common Examples\n\n- Text: `post.title ?? "Untitled"`\n- Prop: `post.url`\n- Nested API array for Collection: `posts.data.items`\n- Resource URL: `"https://api.example.com/posts?tag=" + filters.tag`\n- Header: `"Bearer " + auth.token`\n- Search parameter: `String(filters.page ?? 1)` is not supported because global\n function calls are forbidden; use `(filters.page ?? 1).toString()` instead.\n- Resource body: `{ query: queryText, variables: { slug: system.params.slug } }`\n- Conditional: `featured ? "Featured" : "Standard"`\n- Nested access with a fallback: `post.author.name ?? "Unknown author"`\n\n## Collections\n\nWhenever an array or object should render repeated UI, call `insert-collection`\nwith the complete iterable and one repeated-item JSX root. Do not pass the\nresponse wrapper or one indexed item. The command creates the Collection and\nits private item parameters atomically, then renders the item root once per\nentry. Bind descendants with expressions such as `collectionItem.name`; for\nobject iteration, `collectionItemKey` contains the current key. Wrap multiple\nrepeated siblings in one `ws.element` root.\n\n## Verification\n\nInspect every returned expression warning. Correct warnings that indicate a\nmisspelled or unavailable variable, then run `verify-bindings` for persisted\nsyntax, scope, and reference integrity. A warning does not roll back the\nmutation, and successful static verification does not prove runtime data has\nthe expected shape. `verify-bindings` never executes external resources or\nresolves rendered values. Preview representative data, empty/null data, and\nCollection item counts; use `audit` for relevant structural findings.\n',+ '# Webstudio Expressions\n\nUse an expression only when a value must be computed at runtime from scoped\ndata. Use direct text and direct prop values for fixed content.\n\n## Source Format\n\nExpression-capable MCP fields receive JavaScript expression source as a JSON\nstring. Send one expression, without a `return` statement or surrounding\nfunction. For example:\n\n```json\n{ "binding": { "type": "expression", "value": "post.title ?? \\"Untitled\\"" } }\n```\n\nInside that string, use readable JavaScript syntax rather than serialized JSON.\nFor object expressions, leave identifier property names unquoted, for example\n`{ query: queryText, variables: { slug: system.params.slug } }`. Quote a property\nname only when JavaScript requires it, such as `{ "published-at": date }`. Do\nnot pass a JSON-stringified object as an expression.\n\nDo not send a fixed prop string as an expression. Use `update-props` with\n`type:"string"`. Page metadata and resource URLs accept plain fixed strings and\nnormalize them for storage. Expression-only resource headers, search parameters,\nand bodies accept `{ "type": "literal", "value": "fixed text" }` when the\nvalue is not dynamic.\n\n## Read and read-write bindings\n\nExpression bindings use `mode:"read"` by default. Use `mode:"readwrite"` only\nfor an exact direct path into the frontmatter of an MDX source connected to the\ncontaining Content Block, for example:\n\n```json\n{\n "binding": {\n "type": "expression",\n "value": "document.frontmatter.title",\n "mode": "readwrite"\n }\n}\n```\n\nThis lets Content mode save a direct edit back to that frontmatter field.\nComputed expressions, including fallbacks and concatenation, are always\nread-only. The mutation is rejected when the expression is not a direct path or\ndoes not belong to a connected Content Block document. Use the variable name\nreturned by `inspect-instance`; do not assume it is `document`.\n\n## Scope\n\n- Data variables are available on their scope instance and descendants.\n- An inner variable with the same name masks the outer variable.\n- A scoped resource result is a variable. Read its payload from its result\n wrapper, usually `resourceName.data`; APIs may nest the desired value deeper.\n- Collection creates internal `collectionItem` and `collectionItemKey`\n parameters. They are available only to that Collection\'s descendants.\n Preserve those generated parameters and do not reuse encoded parameter ids\n copied from another Collection.\n- Array Collection iteration exposes the current item. Object iteration exposes\n the current key and value.\n- The built-in `system` context is available only where supplied by the runtime.\n Its documented fields are `system.origin`, `system.pathname`, `system.params`,\n and `system.search`. There is no `system.path`.\n- Actions expose only their declared arguments, such as `event`, plus data that\n is in scope.\n\nRead `list-variables`, `list-resources`, `inspect-instance`, and existing\nbindings before writing an expression. Do not guess identifier names. Syntax is\nvalidated when a mutation is submitted. A valid expression that references an\nidentifier unavailable in that scope is accepted with a structured warning\ncontaining the field path, source range, affected record, and remediation.\n\n## Supported Syntax\n\nExpressions support literals, arrays, objects, property and index access, unary\nand arithmetic operators, comparisons, logical operators, nullish coalescing,\nternaries, and template literals.\n\nWebstudio automatically makes property and index access safe when an\nintermediate value is missing. Write direct access such as `post.author.name`.\nUse nullish coalescing when the expression needs a fallback value.\n\nSupported string methods:\n\n{{allowedStringMethods}}\n\nSupported array methods:\n\n{{allowedArrayMethods}}\n\nOther values support `toString`. Arbitrary global functions and arbitrary\nmethod calls are not supported.\n\n## Unsupported Syntax\n\nDo not use statements, declarations, functions, arrow functions, classes,\n`new`, `this`, `await`, imports, tagged templates, sequence expressions,\nincrement/decrement, or destructuring assignment. Assignment is allowed only\ninside actions. Use an explicit assignment there rather than `++` or `--`.\n\n## Common Examples\n\n- Text: `post.title ?? "Untitled"`\n- Prop: `post.url`\n- Nested API array for Collection: `posts.data.items`\n- Resource URL: `"https://api.example.com/posts?tag=" + filters.tag`\n- Header: `"Bearer " + auth.token`\n- Search parameter: `String(filters.page ?? 1)` is not supported because global\n function calls are forbidden; use `(filters.page ?? 1).toString()` instead.\n- Resource body: `{ query: queryText, variables: { slug: system.params.slug } }`\n- Conditional: `featured ? "Featured" : "Standard"`\n- Nested access with a fallback: `post.author.name ?? "Unknown author"`\n\n## Collections\n\nWhenever an array or object should render repeated UI, call `insert-collection`\nwith the complete iterable and one repeated-item JSX root. Do not pass the\nresponse wrapper or one indexed item. The command creates the Collection and\nits private item parameters atomically, then renders the item root once per\nentry. Bind descendants with expressions such as `collectionItem.name`; for\nobject iteration, `collectionItemKey` contains the current key. Wrap multiple\nrepeated siblings in one `ws.element` root.\n\n## Verification\n\nInspect every returned expression warning. Correct warnings that indicate a\nmisspelled or unavailable variable, then run `verify-bindings` for persisted\nsyntax, scope, and reference integrity. A warning does not roll back the\nmutation, and successful static verification does not prove runtime data has\nthe expected shape. `verify-bindings` never executes external resources or\nresolves rendered values. Preview representative data, empty/null data, and\nCollection item counts; use `audit` for relevant structural findings.\n',"mcp-startup-guidance":'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output. Before editing a Webstudio project, do one small discovery step, then act. For delegated design-system or “use every component” tasks, the first MCP command is `workflow.next {"goal":"design-system-page"}`; report that returned checkpoint to the parent/user and stop until continued. For a simple authored/styled section, the intended path is literal: call `meta.index`, call `meta.get-more-tools` with `{"tools":["insert-fragment"]}`, read the target parent id with `list-pages`/`get-page-by-path`/`list-instances` only if needed, then call `insert-fragment`. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. Do not grep source files, dump full MCP resources, or write parser scripts before trying focused MCP calls. Good first calls are `meta.index` for orientation, `meta.guide` for a goal workflow, `workflow.next` for one bounded delegated phase, `meta.get-more-tools` for exact tool schemas, and `components.coverage-plan`, `components.coverage-insert-next`, `components.find`, or `components.get` for component work. Do not call every discovery tool up front. For delegated or non-streaming agents whose parent cannot see live stderr/stdout, 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 its command/result, and wait for the parent before the next MCP command. Do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands; they hide progress from the parent. Do not take a broad task such as creating a full design-system page as one execution unit. Instead call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint to the parent, 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 design-system or “use every component” tasks, start with `workflow.next`, acknowledge its checkpoint only after parent/user continuation, then run compact `components.coverage-plan`, checkpoint, create the page, checkpoint, then call `components.coverage-insert-next` once per coverage checkpoint, and finish with the `presentation-pass` workflow phase. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world design-system examples instead of raw unstyled component dumps. Request component coverage details with `components.coverage-plan {"detail":"roots"}` or `components.coverage-plan {"detail":"parts"}` only when needed. `list-pages` does not accept `detail`; use `list-pages {}` or `get-page-by-path` for page lookup. Read overview resources such as `webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview` only when focused tools are insufficient. Do not dump or parse full resources such as `webstudio://project/tools` or `webstudio://project/components` unless the focused tools are insufficient. Run one-shot shortcut or explicit `webstudio mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. For experiments, pass `--dry-run` to local-capable mutations. 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. If a one-shot call returns checkpoint.required, the CLI persists `CHECKPOINT_REQUIRED` across later one-shot calls until you report the checkpoint, wait until continued, and call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially. Complete one bounded phase and return a checkpoint before continuing. Follow the guide: read ids and Builder breakpoints first, use focused component discovery for component ids, props, and content model composition, prefer semantic tools over `apply-patch`, use direct value tools for fixed text/props, use bindings only for dynamic expressions/resources/actions, page metadata and fixed resource URLs accept plain strings, put page/resource update fields under `values`, and do not edit generated files for normal content/design changes. Never run visual verification automatically: ask first unless the user explicitly requested screenshots, visual verification, or a rendered audit, and only then use `preview.start` plus screenshot/vision.\n\nWhen `report-issue` is available and the user explicitly asks to report a problem, call it once without requiring a GitHub login. Also call it automatically after a Webstudio-controlled tool crash, hang, malformed result, misleading success, repeated failure of the same documented operation, failed documented recovery, or required undocumented workaround. Do not automatically report expected confirmation/checkpoint flow, a clearly explained invalid input, missing permissions, `PROJECT_SESSION_BUSY`, a recovered version conflict, rate limiting, cancellation, or an offline environment. The LLM must write a complete anonymous technical report with the generalized user story, summary, attempted workflow, expected behavior, actual result, recovery attempts, user impact, technical context, acceptance criteria, exact model identifier, and reasoning effort. Never include names, usernames, emails, phone numbers, organizations, project or resource ids, domains, URLs, IP addresses, local paths, credentials, tokens, customer content, or exact unique values. Do not copy raw tool inputs, outputs, or contextual errors; preserve only stable tool names, schema fields, error codes, CLI versions, and generalized input shapes. Use `unknown` instead of guessing unavailable model metadata.\n',} as const;diff --git a/packages/project-build/src/docs/expressions.md b/packages/project-build/src/docs/expressions.mdindex 2a3a7fdace..e78b17d15a 100644--- a/packages/project-build/src/docs/expressions.md+++ b/packages/project-build/src/docs/expressions.md@@ -25,6 +25,28 @@ normalize them for storage. Expression-only resource headers, search parameters,and bodies accept `{ "type": "literal", "value": "fixed text" }` when thevalue is not dynamic.+## Read and read-write bindings++Expression bindings use `mode:"read"` by default. Use `mode:"readwrite"` only+for an exact direct path into the frontmatter of an MDX source connected to the+containing Content Block, for example:++```json+{+ "binding": {+ "type": "expression",+ "value": "document.frontmatter.title",+ "mode": "readwrite"+ }+}+```++This lets Content mode save a direct edit back to that frontmatter field.+Computed expressions, including fallbacks and concatenation, are always+read-only. The mutation is rejected when the expression is not a direct path or+does not belong to a connected Content Block document. Use the variable name+returned by `inspect-instance`; do not assume it is `document`.+## Scope- Data variables are available on their scope instance and descendants.diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.tsindex 14d0afb800..07d7ae4c8e 100644--- a/packages/project-build/src/mcp.test.ts+++ b/packages/project-build/src/mcp.test.ts@@ -1045,6 +1045,7 @@ describe("project session mcp adapter", () => {"contentMode","mode","insertIndex",+ "templateNameConfirmation","dryRun",]);const fragmentSchema = insertFragmentTool?.inputSchema.properties?.fragment;@@ -1366,7 +1367,19 @@ describe("project session mcp adapter", () => {test("downloads assets through the MCP host", async () => {const downloadAsset = vi.fn(async ({ assetId }: { assetId: string }) => ({assetId,- path: `/workspace/.webstudio/assets/${assetId}.png`,+ path: `/workspace/.webstudio/assets/${assetId}.mdx`,+ source: "# Kept\n\n{danger()}\n",+ diagnostics: [+ {+ code: "unsafe-mdx" as const,+ severity: "warning" as const,+ message: "Executable MDX expressions are not supported",+ sourceRange: {+ start: { line: 3, column: 1, offset: 8 },+ end: { line: 3, column: 11, offset: 18 },+ },+ },+ ],}));const adapter = createProjectSessionMcpCore({operations: publicMcpOperations,@@ -1384,7 +1397,14 @@ describe("project session mcp adapter", () => {expect(result.structuredContent).toMatchObject({data: {assetId: "hero",- path: "/workspace/.webstudio/assets/hero.png",+ path: "/workspace/.webstudio/assets/hero.mdx",+ source: "# Kept\n\n{danger()}\n",+ diagnostics: [+ expect.objectContaining({+ code: "unsafe-mdx",+ severity: "warning",+ }),+ ],},});});diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.tsindex cdd3d76ffd..14f2d906be 100644--- a/packages/project-build/src/mcp.ts+++ b/packages/project-build/src/mcp.ts@@ -9,6 +9,7 @@ import {inputJsonSchemaAcceptsType,parseComponentName,toInputJsonSchemaObject,+ type ContentBlockDiagnostic,type InputJsonSchema,type InputJsonSchemaValue,} from "@webstudio-is/sdk";@@ -299,6 +300,21 @@ export type ProjectSessionDownloadAssetInput = {export type ProjectSessionDownloadAssetResult = {assetId: string;path: string;+ source?: string;+ diagnostics?: readonly (+ | ContentBlockDiagnostic+ | Readonly<{+ code: "invalid-mdx" | "unsafe-mdx";+ severity: "error" | "warning";+ message: string;+ nodeType?: string;+ reason?: string;+ sourceRange?: Readonly<{+ start: Readonly<{ line: number; column: number; offset?: number }>;+ end: Readonly<{ line: number; column: number; offset?: number }>;+ }>;+ }>+ )[];};type DownloadAsset = (@@ -1670,7 +1686,7 @@ const importInputSchema = {const downloadAssetInputSchema = {...emptyInputSchema,description:- "Download one project asset to the local filesystem and return its absolute path.",+ "Download one project Asset. MDX results also include source and diagnostics.",properties: {assetId: {type: "string",@@ -3346,13 +3362,52 @@ const importTool = createProjectSessionMcpTool({const downloadAssetTool = createProjectSessionMcpTool({name: "download-asset",description:- "Download one project asset into .webstudio/assets or a specified directory and return its local path.",+ "Download one project Asset. MDX includes source and diagnostics.",inputSchema: downloadAssetInputSchema,outputSchema: getMcpOutputSchema({type: "object",properties: {assetId: { type: "string" },path: { type: "string" },+ source: { type: "string" },+ diagnostics: {+ type: "array",+ items: {+ type: "object",+ properties: {+ code: { type: "string", enum: ["invalid-mdx", "unsafe-mdx"] },+ severity: { type: "string", enum: ["error", "warning"] },+ message: { type: "string" },+ nodeType: { type: "string" },+ reason: { type: "string" },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: { type: "number" },+ column: { type: "number" },+ offset: { type: "number" },+ },+ required: ["line", "column"],+ },+ end: {+ type: "object",+ properties: {+ line: { type: "number" },+ column: { type: "number" },+ offset: { type: "number" },+ },+ required: ["line", "column"],+ },+ },+ required: ["start", "end"],+ },+ },+ required: ["code", "severity", "message"],+ },+ },},required: ["assetId", "path"],additionalProperties: false,diff --git a/packages/project-build/src/project-session.ts b/packages/project-build/src/project-session.tsindex e7adfd4fb0..5fd06a4e90 100644--- a/packages/project-build/src/project-session.ts+++ b/packages/project-build/src/project-session.ts@@ -1401,6 +1401,7 @@ export class ProjectSession {context: {...this.#options.runtimeContext,projectVersion: snapshot.version,+ dryRun: options.dryRun,},});if (mutation.noop) {diff --git a/packages/project-build/src/runtime.ts b/packages/project-build/src/runtime.tsindex 899367a47b..5a0f04209e 100644--- a/packages/project-build/src/runtime.ts+++ b/packages/project-build/src/runtime.ts@@ -10,6 +10,8 @@ export * from "./runtime/component-catalog";export * from "./runtime/component-template";export * from "./runtime/content-mode-copy-policy";export * from "./runtime/content-mode-permissions";+export * from "./runtime/content-block-source-lifecycle";+export * from "./runtime/content-block-application";export * from "./runtime/content-model";export * from "./runtime/pre-publish-audit";export * from "./runtime/context";@@ -27,10 +29,19 @@ export * from "./runtime/instances";export * from "./runtime/lookup";export * from "./runtime/matcher";export * from "./runtime/mutation";+export * from "./runtime/mdx-authored-content";+export * from "./runtime/mdx-asset-references";+export * from "./runtime/mdx-diagnostics";+export * from "./runtime/mdx-materialization";+export * from "./runtime/mdx-paste";+export * from "./runtime/mdx-source";+export * from "./runtime/mdx-template-migration";+export * from "./runtime/mdx-template-resolution";export * from "./runtime/output";export * from "./runtime/page-copy";export * from "./runtime/pages";export * from "./runtime/project-settings";+export * from "./runtime/published-mdx";export * from "./runtime/props";export * from "./runtime/redirect-loop-detection";export * from "./runtime/redirect-parsers";diff --git a/packages/project-build/src/runtime/assets.ts b/packages/project-build/src/runtime/assets.tsindex 8e5e482452..d3a9a732c3 100644--- a/packages/project-build/src/runtime/assets.ts+++ b/packages/project-build/src/runtime/assets.ts@@ -819,7 +819,7 @@ const countResourceAssetReferences = (resource: Resource, assetId: string) =>assetId);-const countDataSourceAssetReferences = (+export const countDataSourceAssetReferences = (dataSource: DataSource,assetId: string) =>diff --git a/packages/project-build/src/runtime/block.test.ts b/packages/project-build/src/runtime/block.test.tsindex ac61fa1cf7..d6a954963e 100644--- a/packages/project-build/src/runtime/block.test.ts+++ b/packages/project-build/src/runtime/block.test.ts@@ -1,15 +1,23 @@import { describe, expect, test } from "vitest";import {blockComponent,+ blockBodyComponent,blockTemplateComponent,+ contentBlockSourceProp,type Instance,} from "@webstudio-is/sdk";import {+ assignUniqueBlockTemplateNamesMutable,canDeleteInstanceInContentMode,+ canMoveInstanceInContentMode,+ findBlockTemplateNameCollision,findBlockChildSelector,+ findBlockContentSelector,findBlockSelector,findBlockTemplates,getBlockTemplateInsertionIndex,+ getBlockTemplateNameConfirmation,+ resolveContentBlockSourceAssetId,} from "./block";const createInstance = (@@ -24,6 +32,25 @@ const createInstance = (});describe("block tree helpers", () => {+ test("resolves direct sources without expression values", () => {+ expect(+ resolveContentBlockSourceAssetId({+ source: { type: "asset", assetId: "post" },+ })+ ).toBe("post");+ expect(+ resolveContentBlockSourceAssetId({+ source: { type: "expression", value: "post" },+ })+ ).toBeUndefined();+ expect(+ resolveContentBlockSourceAssetId({+ source: { type: "expression", value: "post" },+ values: new Map([["post", "post-asset"]]),+ })+ ).toBe("post-asset");+ });+test("finds block and block child selectors from nested anchors", () => {const instances = new Map<Instance["id"], Instance>([["body", createInstance("body", "Body")],@@ -112,6 +139,63 @@ describe("block tree helpers", () => {).toBe(3);});+ test("uses an explicit Body as the editable content container", () => {+ const instances = new Map<Instance["id"], Instance>([+ ["page", createInstance("page", "Body")],+ [+ "block",+ createInstance("block", blockComponent, [+ { type: "id", value: "templates" },+ { type: "id", value: "header" },+ { type: "id", value: "content" },+ ]),+ ],+ ["templates", createInstance("templates", blockTemplateComponent)],+ ["header", createInstance("header", "Heading")],+ [+ "content",+ createInstance("content", blockBodyComponent, [+ { type: "id", value: "paragraph" },+ ]),+ ],+ ["paragraph", createInstance("paragraph", "Paragraph")],+ ]);++ expect(+ findBlockContentSelector({ anchor: ["block", "page"], instances })+ ).toEqual(["content", "block", "page"]);+ expect(+ findBlockContentSelector({+ anchor: ["paragraph", "content", "block", "page"],+ instances,+ })+ ).toEqual(["content", "block", "page"]);+ expect(+ findBlockContentSelector({+ anchor: ["header", "block", "page"],+ instances,+ })+ ).toBeUndefined();+ expect(+ findBlockChildSelector({+ instanceSelector: ["paragraph", "content", "block", "page"],+ instances,+ })+ ).toEqual(["paragraph", "content", "block", "page"]);+ expect(+ getBlockTemplateInsertionIndex({+ anchor: ["block", "page"],+ instances,+ })+ ).toBe(0);+ expect(+ getBlockTemplateInsertionIndex({+ anchor: ["paragraph", "content", "block", "page"],+ instances,+ })+ ).toBe(1);+ });+test("allows deleting direct content block children", () => {const instances = new Map<Instance["id"], Instance>([[@@ -158,4 +242,251 @@ describe("block tree helpers", () => {})).toBe(false);});++ test("allows moving authored content but not templates in content mode", () => {+ const instances = new Map<Instance["id"], Instance>([+ ["body", createInstance("body", "Body")],+ ["block", createInstance("block", blockComponent)],+ ["authored", createInstance("authored", "Box")],+ ["nested", createInstance("nested", "Box")],+ ["templates", createInstance("templates", blockTemplateComponent)],+ ["template-child", createInstance("template-child", "Box")],+ ]);++ expect(+ canMoveInstanceInContentMode({+ instanceSelector: ["nested", "authored", "block", "body"],+ parentSelector: ["block", "body"],+ instances,+ })+ ).toBe(true);+ expect(+ canMoveInstanceInContentMode({+ instanceSelector: ["templates", "block", "body"],+ parentSelector: ["block", "body"],+ instances,+ })+ ).toBe(false);+ expect(+ canMoveInstanceInContentMode({+ instanceSelector: ["template-child", "templates", "block", "body"],+ parentSelector: ["block", "body"],+ instances,+ })+ ).toBe(false);+ expect(+ canMoveInstanceInContentMode({+ instanceSelector: ["authored", "block", "body"],+ parentSelector: ["templates", "block", "body"],+ instances,+ })+ ).toBe(false);+ });++ test("only allows content-mode mutations inside an explicit Body", () => {+ const instances = new Map<Instance["id"], Instance>([+ [+ "block",+ createInstance("block", blockComponent, [+ { type: "id", value: "header" },+ { type: "id", value: "content" },+ ]),+ ],+ ["header", createInstance("header", "Heading")],+ [+ "content",+ createInstance("content", blockBodyComponent, [+ { type: "id", value: "first" },+ { type: "id", value: "second" },+ ]),+ ],+ ["first", createInstance("first", "Paragraph")],+ ["second", createInstance("second", "Paragraph")],+ ]);++ expect(+ canDeleteInstanceInContentMode({+ instanceSelector: ["first", "content", "block"],+ instances,+ })+ ).toBe(true);+ expect(+ canDeleteInstanceInContentMode({+ instanceSelector: ["header", "block"],+ instances,+ })+ ).toBe(false);+ expect(+ canMoveInstanceInContentMode({+ instanceSelector: ["first", "content", "block"],+ parentSelector: ["content", "block"],+ instances,+ })+ ).toBe(true);+ expect(+ canMoveInstanceInContentMode({+ instanceSelector: ["header", "block"],+ parentSelector: ["content", "block"],+ instances,+ })+ ).toBe(false);+ });+});++describe("block template names", () => {+ const createBlockInstances = () =>+ new Map<Instance["id"], Instance>([+ [+ "block",+ createInstance("block", blockComponent, [+ { type: "id", value: "templates" },+ ]),+ ],+ [+ "templates",+ createInstance("templates", blockTemplateComponent, [+ { type: "id", value: "hero" },+ { type: "id", value: "card" },+ ]),+ ],+ ["hero", { ...createInstance("hero", "Box"), label: "Hero Card" }],+ ["card", createInstance("card", "Box")],+ ]);+ test("assigns unique names to newly inserted template entries", () => {+ const instances = createBlockInstances();+ instances.set("card-copy", createInstance("card-copy", "Box"));+ instances.set("card-copy-2", createInstance("card-copy-2", "Box"));+ instances.get("card-copy-2")!.label = "Box 2";++ assignUniqueBlockTemplateNamesMutable({+ instanceIds: ["card-copy", "card-copy-2"],+ parent: instances.get("templates")!,+ instances,+ });++ expect(instances.get("card-copy")?.label).toBe("Box 2");+ expect(instances.get("card-copy-2")?.label).toBe("Box 3");+ });++ test("finds exact name collisions in the same flat list", () => {+ const instances = createBlockInstances();++ expect(+ findBlockTemplateNameCollision({+ instance: instances.get("card")!,+ nextInstance: { ...instances.get("card")!, label: "Hero Card" },+ instances,+ })?.instance.id+ ).toBe("hero");+ expect(+ findBlockTemplateNameCollision({+ instance: instances.get("card")!,+ nextInstance: { ...instances.get("card")!, label: "hero card" },+ instances,+ })+ ).toBeUndefined();+ });++ test.each([+ {+ source: {+ id: "src",+ instanceId: "block",+ name: contentBlockSourceProp,+ type: "asset" as const,+ value: "article.mdx",+ },+ label: "direct",+ },+ {+ source: {+ id: "src",+ instanceId: "block",+ name: contentBlockSourceProp,+ type: "expression" as const,+ value: "articleAssetId",+ },+ label: "dynamic",+ },+ ])("requires confirmation for a $label source", ({ source }) => {+ const instances = createBlockInstances();+ const instance = instances.get("card")!;+ const hero = instances.get("hero")!;++ expect(+ getBlockTemplateNameConfirmation({+ changes: [+ { instance, nextInstance: { ...instance, label: "Article Card" } },+ { instance: hero, nextInstance: { ...hero, label: "Article Hero" } },+ ],+ instances,+ props: new Map([[source.id, source]]).values(),+ })+ ).toEqual({+ action: "rename",+ templates: [+ { instanceId: "card", oldName: "Box", newName: "Article Card" },+ {+ instanceId: "hero",+ oldName: "Hero Card",+ newName: "Article Hero",+ },+ ],+ });+ expect(+ getBlockTemplateNameConfirmation({+ changes: [{ instance }],+ instances,+ props: [source],+ })+ ).toEqual({+ action: "delete",+ templates: [{ instanceId: "card", oldName: "Box" }],+ });+ });++ test("does not warn for nested, unchanged, or non-source templates", () => {+ const instances = createBlockInstances();+ const instance = instances.get("card")!;+ instances.set(+ "nested",+ createInstance("nested", "Box", [{ type: "id", value: "card" }])+ );+ instances.get("templates")!.children = [+ { type: "id", value: "hero" },+ { type: "id", value: "nested" },+ ];+ const source = {+ id: "src",+ instanceId: "block",+ name: contentBlockSourceProp,+ type: "asset" as const,+ value: "article.mdx",+ };++ expect(+ getBlockTemplateNameConfirmation({+ changes: [{ instance, nextInstance: { ...instance, label: "Card" } }],+ instances,+ props: [source],+ })+ ).toBeUndefined();+ instances.get("templates")!.children.push({ type: "id", value: "card" });+ expect(+ getBlockTemplateNameConfirmation({+ changes: [{ instance, nextInstance: { ...instance } }],+ instances,+ props: [source],+ })+ ).toBeUndefined();+ expect(+ getBlockTemplateNameConfirmation({+ changes: [+ { instance, nextInstance: { ...instance, label: "Article Card" } },+ ],+ instances,+ props: [],+ })+ ).toBeUndefined();+ });});diff --git a/packages/project-build/src/runtime/block.ts b/packages/project-build/src/runtime/block.tsindex b597be49ae..c13a6eeaa4 100644--- a/packages/project-build/src/runtime/block.ts+++ b/packages/project-build/src/runtime/block.ts@@ -1,11 +1,209 @@import {+ allocateUniqueContentBlockTemplateName,blockComponent,blockTemplateComponent,+ findContentBlockBodyContainerPaths,+ findParentInstanceReference,+ findContentBlockTemplateContainers,+ getContentBlockSource,+ getInstanceName,+ type ContentBlockSource,type Instance,type Instances,+ type Prop,} from "@webstudio-is/sdk";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";+import { computeStringExpression } from "./data";import type { InstanceSelector } from "./tree";+export const resolveContentBlockSourceAssetId = ({+ source,+ values,+}: {+ source: ContentBlockSource;+ values?: ReadonlyMap<string, unknown>;+}) =>+ source.type === "asset"+ ? source.assetId+ : values === undefined+ ? undefined+ : computeStringExpression(source.value, values);++export const assignUniqueBlockTemplateNamesMutable = ({+ instanceIds,+ parent,+ replacedInstanceIds = [],+ instances,+}: {+ instanceIds: readonly Instance["id"][];+ parent: Instance;+ replacedInstanceIds?: readonly Instance["id"][];+ instances: Instances;+}) => {+ if (parent.component !== blockTemplateComponent) {+ return;+ }+ const ignoredIds = new Set([...instanceIds, ...replacedInstanceIds]);+ const existingNames = new Set<string>();+ for (const child of parent.children) {+ const instance =+ child.type === "id" ? instances.get(child.value) : undefined;+ if (instance !== undefined && ignoredIds.has(instance.id) === false) {+ existingNames.add(getInstanceName({ instance, metas: componentMetas }));+ }+ }++ for (const instanceId of instanceIds) {+ const instance = instances.get(instanceId);+ if (instance === undefined) {+ continue;+ }+ const currentName = getInstanceName({ instance, metas: componentMetas });+ const uniqueName = allocateUniqueContentBlockTemplateName({+ name: currentName,+ existingNames,+ });+ if (uniqueName !== currentName) {+ instance.label = uniqueName;+ }+ existingNames.add(uniqueName);+ }+};++export const findBlockTemplateNameCollision = ({+ instance,+ nextInstance,+ instances,+}: {+ instance: Instance;+ nextInstance: Instance;+ instances: Instances;+}) => {+ const name = getInstanceName({+ instance: nextInstance,+ metas: componentMetas,+ });+ if (name === getInstanceName({ instance, metas: componentMetas })) {+ return;+ }+ const parent = findParentInstanceReference(instances, instance.id)?.instance;+ if (parent?.component !== blockTemplateComponent) {+ return;+ }+ for (const child of parent.children) {+ if (child.type !== "id" || child.value === instance.id) {+ continue;+ }+ const sibling = instances.get(child.value);+ if (+ sibling !== undefined &&+ getInstanceName({ instance: sibling, metas: componentMetas }) === name+ ) {+ return { instance: sibling, name };+ }+ }+};++export type BlockTemplateNameConfirmation = {+ action: "rename" | "delete";+ templates: Array<{+ instanceId: Instance["id"];+ oldName: string;+ newName?: string;+ }>;+};++export const getSourceBackedBlockTemplateContext = ({+ templateInstanceId,+ instances,+ props,+}: {+ templateInstanceId: Instance["id"];+ instances: Instances;+ props: Iterable<Prop>;+}) => {+ const template = instances.get(templateInstanceId);+ const templates = findParentInstanceReference(+ instances,+ templateInstanceId+ )?.instance;+ if (+ template === undefined ||+ templates?.component !== blockTemplateComponent+ ) {+ return;+ }+ const block = findParentInstanceReference(instances, templates.id)?.instance;+ if (block?.component !== blockComponent) {+ return;+ }+ const source = getContentBlockSource({+ blockInstanceId: block.id,+ props,+ });+ if (source === undefined) {+ return;+ }+ return {+ blockInstanceId: block.id,+ templatesInstanceId: templates.id,+ templateInstanceId,+ templateName: getInstanceName({+ instance: template,+ metas: componentMetas,+ }),+ source,+ };+};++export const getBlockTemplateNameConfirmation = ({+ changes,+ instances,+ props,+}: {+ changes: ReadonlyArray<{+ instance: Instance;+ nextInstance?: Instance;+ }>;+ instances: Instances;+ props: Iterable<Prop>;+}): BlockTemplateNameConfirmation | undefined => {+ const templates: BlockTemplateNameConfirmation["templates"] = [];+ const sourceProps = Array.from(props);+ for (const { instance, nextInstance } of changes) {+ const context = getSourceBackedBlockTemplateContext({+ templateInstanceId: instance.id,+ instances,+ props: sourceProps,+ });+ if (context === undefined) {+ continue;+ }+ const oldName = context.templateName;+ const newName =+ nextInstance === undefined+ ? undefined+ : getInstanceName({ instance: nextInstance, metas: componentMetas });+ if (newName === oldName) {+ continue;+ }+ templates.push({+ instanceId: instance.id,+ oldName,+ ...(newName === undefined ? {} : { newName }),+ });+ }+ if (templates.length === 0) {+ return;+ }+ return {+ action: changes.some(({ nextInstance }) => nextInstance === undefined)+ ? "delete"+ : "rename",+ templates,+ };+};+export const findBlockChildSelector = ({instanceSelector,instances,@@ -13,16 +211,18 @@ export const findBlockChildSelector = ({instanceSelector: InstanceSelector;instances: Instances;}) => {- for (let index = 1; index < instanceSelector.length; index += 1) {- const instance = instances.get(instanceSelector[index]);- if (instance?.component === blockComponent) {- return instanceSelector.slice(index - 1);- }+ const contentSelector = findBlockContentSelector({+ anchor: instanceSelector,+ instances,+ });+ if (contentSelector === undefined) {+ return;}-- if (instances.get(instanceSelector[0])?.component === blockComponent) {- return instanceSelector;+ const contentIndex = instanceSelector.length - contentSelector.length;+ if (contentIndex === 0) {+ return contentSelector;}+ return instanceSelector.slice(contentIndex - 1);};export const findBlockSelector = ({@@ -48,6 +248,80 @@ export const findBlockSelector = ({}};+/** Finds the container whose children are editable Content Block content. */+export const findBlockContentSelector = ({+ anchor,+ instances,+}: {+ anchor: InstanceSelector;+ instances: Instances;+}) => {+ const blockSelector = findBlockSelector({ anchor, instances });+ if (blockSelector === undefined) {+ return;+ }+ const block = instances.get(blockSelector[0]);+ if (block === undefined) {+ return;+ }+ const bodyPaths = findContentBlockBodyContainerPaths({+ blockInstance: block,+ instances,+ });+ if (bodyPaths.length === 0) {+ return blockSelector;+ }+ if (bodyPaths.length > 1) {+ return;+ }+ const bodyPath = bodyPaths[0];+ const body = bodyPath.at(-1)!;+ const bodyIndex = anchor.indexOf(body.id);+ if (bodyIndex !== -1) {+ return anchor.slice(bodyIndex);+ }+ if (anchor[0] === block.id) {+ return [...bodyPath.map(({ id }) => id).reverse(), ...blockSelector];+ }+};++export const canMoveInstanceInContentMode = ({+ instanceSelector,+ parentSelector,+ instances,+}: {+ instanceSelector: InstanceSelector;+ parentSelector: InstanceSelector;+ instances: Instances;+}) => {+ const sourceContent = findBlockContentSelector({+ anchor: instanceSelector,+ instances,+ });+ const targetContent = findBlockContentSelector({+ anchor: parentSelector,+ instances,+ });+ return (+ sourceContent !== undefined &&+ targetContent !== undefined &&+ sourceContent[0] === targetContent[0] &&+ instanceSelector.length > sourceContent.length &&+ instanceSelector+ .slice(0, instanceSelector.length - sourceContent.length)+ .every(+ (instanceId) =>+ instances.get(instanceId)?.component !== blockTemplateComponent+ ) &&+ parentSelector+ .slice(0, parentSelector.length - targetContent.length)+ .every(+ (instanceId) =>+ instances.get(instanceId)?.component !== blockTemplateComponent+ )+ );+};+export const canDeleteInstanceInContentMode = ({instanceSelector,instances,@@ -55,18 +329,17 @@ export const canDeleteInstanceInContentMode = ({instanceSelector: InstanceSelector;instances: Instances;}) => {- const blockSelector = findBlockSelector({+ const contentSelector = findBlockContentSelector({anchor: instanceSelector,instances,});- if (blockSelector === undefined) {+ if (contentSelector === undefined) {return false;}- if (instanceSelector.length - blockSelector.length !== 1) {+ if (instanceSelector.length - contentSelector.length !== 1) {return false;}-return (instances.get(instanceSelector[0])?.component !== blockTemplateComponent);@@ -89,24 +362,22 @@ export const findBlockTemplates = ({return;}- const templateInstanceId = blockInstance.children.find(- (child) =>- child.type === "id" &&- instances.get(child.value)?.component === blockTemplateComponent- )?.value;- if (templateInstanceId === undefined) {+ const templateInstance = findContentBlockTemplateContainers({+ blockInstance,+ instances,+ })[0];+ if (templateInstance === undefined) {return;}- return instances- .get(templateInstanceId)- ?.children.filter((child) => child.type === "id")+ return templateInstance.children+ .filter((child) => child.type === "id").map((child) => child.value).map((childId) => instances.get(childId)).filter((child): child is Instance => child !== undefined).map((child) =>- [child, [child.id, templateInstanceId, ...blockInstanceSelector]] as [+ [child, [child.id, templateInstance.id, ...blockInstanceSelector]] as [Instance,InstanceSelector,]@@ -127,15 +398,23 @@ export const getBlockTemplateInsertionIndex = ({return;}- const insertAtInitialPosition =- blockSelector.length === anchor.length &&- blockSelector.every((instanceId, index) => instanceId === anchor[index]);-const blockInstance = instances.get(blockSelector[0]);if (blockInstance === undefined) {return;}+ const contentSelector = findBlockContentSelector({ anchor, instances });+ if (contentSelector === undefined) {+ return;+ }+ const contentInstance = instances.get(contentSelector[0]);+ if (contentInstance === undefined) {+ return;+ }++ const insertAtInitialPosition =+ anchor[0] === blockInstance.id || anchor[0] === contentInstance.id;+const childBlockSelector = findBlockChildSelector({instanceSelector: anchor,instances,@@ -144,17 +423,26 @@ export const getBlockTemplateInsertionIndex = ({return;}- const index = blockInstance.children.findIndex((child) => {+ const templateContainerId =+ contentInstance === blockInstance+ ? findContentBlockTemplateContainers({+ blockInstance,+ instances,+ })[0]?.id+ : undefined;+ const index = contentInstance.children.findIndex((child) => {if (child.type !== "id") {return false;}if (insertAtInitialPosition) {- return instances.get(child.value)?.component === blockTemplateComponent;+ return child.value === templateContainerId;}return child.value === childBlockSelector[0];});if (index === -1) {- return;+ return insertAtInitialPosition && templateContainerId === undefined+ ? 0+ : undefined;}if (insertAtInitialPosition) {diff --git a/packages/project-build/src/runtime/collection.ts b/packages/project-build/src/runtime/collection.tsindex 39d4d70e41..e1c9c1a0c3 100644--- a/packages/project-build/src/runtime/collection.ts+++ b/packages/project-build/src/runtime/collection.ts@@ -230,6 +230,7 @@ export const createCollectionFragment = ({instances: state.instances,dataSources: state.dataSources,}),+ mode: "read",};const parameterDataSources = [item.dataSource, itemKey.dataSource];assertNoIdCollision(diff --git a/packages/project-build/src/runtime/components.test.ts b/packages/project-build/src/runtime/components.test.tsindex a15aeed63f..43f6cf1dc1 100644--- a/packages/project-build/src/runtime/components.test.ts+++ b/packages/project-build/src/runtime/components.test.ts@@ -1,5 +1,6 @@import { expect, test } from "vitest";import {+ blockTemplateComponent,collectionComponent,elementComponent,encodeDataVariableId,@@ -115,6 +116,37 @@ const createIdFactory = () => {return () => `generated-${index++}`;};+test("assigns a unique name when inserting into a Templates list", async () => {+ const parent: Instance = {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [{ type: "id", value: "existing" }],+ };+ const state = createState(parent);+ state.instances.set("existing", {+ type: "instance",+ id: "existing",+ component: "Box",+ children: [],+ });+ const fragment = await parseWebstudioJsxFragment("<$.Box />");++ const mutation = insertFragment(+ state,+ { parentInstanceId: parent.id, fragment },+ { createId: createIdFactory() }+ );++ expect(getAddedValues<Instance>(mutation, "instances")).toContainEqual(+ expect.objectContaining({+ id: "generated-0",+ component: "Box",+ label: "Box 2",+ })+ );+});+const getAddedValues = <Value>(mutation: { payload: Awaited<ReturnType<typeof insertComponent>>["payload"] },namespace: string@@ -414,6 +446,7 @@ test("binds object Collection keys to the generated itemKey parameter", async ()expect(itemRoot?.children).toContainEqual({type: "expression",value: encodeDataVariableId(mutation.result.itemKeyParameterId),+ mode: "read",});});@@ -821,6 +854,7 @@ test("remaps action data source references when inserting registered component tname: "state",type: "expression",value: "$ws$dataSource$generated__DASH__9",+ mode: "read",},{id: "generated-11",@@ -1558,14 +1592,27 @@ test("reports unsupported existing resource references in jsx", async () => {test("converts react prop aliases in webstudio jsx fragments", async () => {expect(- (await parseWebstudioJsxFragment(`<$.Box className="panel">Hello</$.Box>`))- .props+ (+ await parseWebstudioJsxFragment(+ `<$.Box className="panel" tabIndex={2} readOnly>Hello</$.Box>`+ )+ ).props).toEqual([expect.objectContaining({name: "class",type: "string",value: "panel",}),+ expect.objectContaining({+ name: "tabindex",+ type: "number",+ value: 2,+ }),+ expect.objectContaining({+ name: "readonly",+ type: "boolean",+ value: true,+ }),]);expect((diff --git a/packages/project-build/src/runtime/components.ts b/packages/project-build/src/runtime/components.tsindex 91a360363a..d0f89b581b 100644--- a/packages/project-build/src/runtime/components.ts+++ b/packages/project-build/src/runtime/components.ts@@ -1,5 +1,6 @@import equal from "fast-deep-equal";import {+ blockTemplateComponent,elementComponent,instanceComponent,ROOT_INSTANCE_ID,@@ -51,10 +52,12 @@ import {webstudioFragmentMutationInput,} from "./fragment";import {+ blockTemplateNameConfirmationInput,createInstanceAppendPayload,createInstanceChild,insertIndexInput,instanceInsertModeInput,+ requireBlockTemplateNameConfirmation,} from "./instances";import { createRuntimeMutation, type BuilderRuntimeMutation } from "./mutation";import { getSlotFragmentDropTargetMutable } from "./slot";@@ -66,6 +69,10 @@ import {getNewFragmentContentModelWarnings,} from "./matcher";import { z } from "zod";+import {+ assignUniqueBlockTemplateNamesMutable,+ getBlockTemplateNameConfirmation,+} from "./block";const conflictResolutionInput = z.enum(["ours", "theirs", "merge"])@@ -85,6 +92,7 @@ export const insertComponentInput = z.object({.describe('Required when component is "ws:element"; omit otherwise.'),mode: instanceInsertModeInput.optional(),insertIndex: insertIndexInput.optional(),+ templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),});export const insertFragmentInput = z@@ -102,6 +110,7 @@ export const insertFragmentInput = z),mode: instanceInsertModeInput.optional(),insertIndex: insertIndexInput.optional(),+ templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),}).superRefine((input, context) => {if (@@ -245,19 +254,39 @@ const getRequiredComponentInsertState = (state: ComponentInsertState) => {};};+export const getRequiredComponentInsertData = (+ state: ComponentInsertState+): Omit<WebstudioData, "pages"> => {+ const required = getRequiredComponentInsertState(state);+ return {+ instances: required.instances,+ props: required.props,+ dataSources: required.dataSources,+ resources: required.resources,+ styleSources: required.styleSources,+ styleSourceSelections: required.styleSourceSelections,+ styles: required.styles,+ breakpoints: required.breakpoints,+ assets: required.assets,+ };+};+const cloneFragmentData = (state: ReturnType<typeof getRequiredComponentInsertState>-): Omit<WebstudioData, "pages"> => ({- instances: cloneMap(state.instances),- props: cloneMap(state.props),- dataSources: cloneMap(state.dataSources),- resources: cloneMap(state.resources),- styleSources: cloneMap(state.styleSources),- styleSourceSelections: cloneMap(state.styleSourceSelections),- styles: cloneMap(state.styles),- breakpoints: cloneMap(state.breakpoints),- assets: cloneMap(state.assets),-});+): Omit<WebstudioData, "pages"> => {+ const data = getRequiredComponentInsertData(state);+ return {+ instances: cloneMap(data.instances),+ props: cloneMap(data.props),+ dataSources: cloneMap(data.dataSources),+ resources: cloneMap(data.resources),+ styleSources: cloneMap(data.styleSources),+ styleSourceSelections: cloneMap(data.styleSourceSelections),+ styles: cloneMap(data.styles),+ breakpoints: cloneMap(data.breakpoints),+ assets: cloneMap(data.assets),+ };+};const cloneMap = <Key, Value>(map: Map<Key, Value>) =>new Map(@@ -687,6 +716,7 @@ const createInsertFragmentMutation = <additionalAvailableVariables = [],getResultDetails,validateContentModel = true,+ confirm,context,}: {state: ComponentInsertState;@@ -703,6 +733,7 @@ const createInsertFragmentMutation = <newDataSourceIds: Map<string, string>;}) => Details;validateContentModel?: boolean;+ confirm?: z.infer<typeof blockTemplateNameConfirmationInput>;context: BuilderRuntimeContext;}) => {const mutationState = getRequiredComponentInsertState(state);@@ -787,6 +818,44 @@ const createInsertFragmentMutation = <return child;});+ assignUniqueBlockTemplateNamesMutable({+ instanceIds: insertedChildren.flatMap((child) =>+ child.type === "id" ? [child.value] : []+ ),+ parent,+ replacedInstanceIds:+ mode === "replace"+ ? parentChildren.flatMap((child) =>+ child.type === "id" ? [child.value] : []+ )+ : [],+ instances: nextData.instances,+ });+ const requiredTemplateNameConfirmation =+ mode === "replace" && parent.component === blockTemplateComponent+ ? getBlockTemplateNameConfirmation({+ changes: parentChildren.flatMap((child, index) => {+ if (child.type !== "id") {+ return [];+ }+ const instance = mutationState.instances.get(child.value);+ const inserted = insertedChildren[index];+ return instance === undefined+ ? []+ : [+ {+ instance,+ nextInstance:+ inserted?.type === "id"+ ? nextData.instances.get(inserted.value)+ : undefined,+ },+ ];+ }),+ instances: mutationState.instances,+ props: mutationState.props.values(),+ })+ : undefined;if (validateContentModel) {const validationInstances = new Map(nextData.instances);@@ -831,6 +900,11 @@ const createInsertFragmentMutation = <return throwBuilderRuntimeError("BAD_REQUEST", contentModelError.message);}}+ requireBlockTemplateNameConfirmation({+ required: requiredTemplateNameConfirmation,+ confirm,+ path: "mode",+ });const createResult = (parentInstanceId: string,@@ -1000,6 +1074,7 @@ export const insertComponent = (mode: input.mode,insertIndex: input.insertIndex,validateContentModel: false,+ confirm: input.templateNameConfirmation,context,});};@@ -1146,6 +1221,7 @@ export const insertFragment = (insertIndex: input.insertIndex,conflictResolution: input.conflictResolution,contentMode: input.contentMode,+ confirm: input.templateNameConfirmation,context,});};diff --git a/packages/project-build/src/runtime/content-block-application.test.ts b/packages/project-build/src/runtime/content-block-application.test.tsnew file mode 100644index 0000000000..bd66b4aa26--- /dev/null+++ b/packages/project-build/src/runtime/content-block-application.test.ts@@ -0,0 +1,349 @@+import { describe, expect, test } from "vitest";+import {+ blockBodyComponent,+ blockComponent,+ blockTemplateComponent,+ type Asset,+} from "@webstudio-is/sdk";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";+import { applyBuilderPatchTransactions } from "../state/patch";+import type { BuilderState } from "../state/builder-state";+import { createDefaultPages } from "../shared/pages-utils";+import {+ createContentBlockApplication,+ inspectMdxAssetSource,+} from "./content-block-application";++const createFixture = () => {+ let source = "# From file";+ let asset: Pick<+ Asset,+ | "id"+ | "projectId"+ | "name"+ | "type"+ | "format"+ | "size"+ | "createdAt"+ | "updatedAt"+ > = {+ id: "asset",+ projectId: "project",+ name: "article.mdx",+ type: "file",+ format: "mdx",+ size: new TextEncoder().encode(source).byteLength,+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+ };+ const session = {+ open: async () => ({ asset, source, status: "saved" as const }),+ reload: async () => ({ asset, source, status: "saved" as const }),+ save: (_assetId: string, nextSource: string) => {+ source = nextSource;+ },+ flush: async () => {+ asset = {+ ...asset,+ size: new TextEncoder().encode(source).byteLength,+ updatedAt: "2026-01-02T00:00:00.000Z",+ };+ return { asset, source, status: "saved" as const };+ },+ get: () => ({ asset, source, status: "saved" as const }),+ };+ const state: BuilderState = {+ pages: createDefaultPages({ rootInstanceId: "block" }),+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [+ { type: "id", value: "templates" },+ { type: "id", value: "old" },+ ],+ },+ ],+ [+ "templates",+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ [+ "old",+ {+ type: "instance",+ id: "old",+ component: "ws:element",+ tag: "p",+ children: [{ type: "text", value: "Old" }],+ },+ ],+ ]),+ props: new Map(),+ dataSources: new Map(),+ resources: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ breakpoints: new Map(),+ assets: new Map([[asset.id, asset as Asset]]),+ };+ return {+ session,+ state,+ getSource: () => source,+ application: createContentBlockApplication({+ projectId: "project",+ session,+ metas: componentMetas,+ }),+ };+};++describe("createContentBlockApplication", () => {+ test("inspects an Asset in each resolvable Content Block context", async () => {+ const fixture = createFixture();+ fixture.state.dataSources?.set("selectedAsset", {+ id: "selectedAsset",+ scopeInstanceId: "block",+ name: "selectedAsset",+ type: "variable",+ value: { type: "string", value: "asset" },+ });+ const connected = await fixture.application.connect({+ state: fixture.state,+ blockInstanceId: "block",+ renderScope: "page",+ source: { type: "expression", value: "selectedAsset" },+ });+ const connectedState = applyBuilderPatchTransactions(fixture.state, [+ { id: "connect", payload: [...connected.projectPayload] },+ ]).state;++ await expect(+ inspectMdxAssetSource({+ source: '<ws.element ws:name="Missing" />',+ assetId: "asset",+ state: connectedState,+ metas: componentMetas,+ projectId: "project",+ })+ ).resolves.toEqual([+ expect.objectContaining({+ code: "unresolved-template",+ blockInstanceId: "block",+ templateName: "Missing",+ }),+ ]);+ });++ test("reports content-model errors when inspecting a connected Asset", async () => {+ const fixture = createFixture();+ const connected = await fixture.application.connect({+ state: fixture.state,+ blockInstanceId: "block",+ renderScope: "page",+ source: { type: "asset", assetId: "asset" },+ });+ const connectedState = applyBuilderPatchTransactions(fixture.state, [+ { id: "connect", payload: [...connected.projectPayload] },+ ]).state;++ await expect(+ inspectMdxAssetSource({+ source: `1. test++ <ws.element ws:tag="li">nested item</ws.element>+`,+ assetId: "asset",+ state: connectedState,+ metas: componentMetas,+ projectId: "project",+ })+ ).resolves.toEqual([+ expect.objectContaining({+ code: "invalid-mdx",+ message: "Placing <li> element inside a <li> violates HTML spec.",+ }),+ ]);+ });++ test("connects with the normal lifecycle payload and disconnects to an empty block", async () => {+ const fixture = createFixture();+ const connected = await fixture.application.connect({+ state: fixture.state,+ blockInstanceId: "block",+ renderScope: "page",+ source: { type: "asset", assetId: "asset" },+ });+ expect(connected.requiresConfirmation).toBe(true);+ const connectedState = applyBuilderPatchTransactions(fixture.state, [+ { id: "connect", payload: [...connected.projectPayload] },+ ]).state;+ expect(connectedState.instances?.has("old")).toBe(false);++ const disconnected = await fixture.application.disconnect({+ state: connectedState,+ blockInstanceId: "block",+ });+ const disconnectedState = applyBuilderPatchTransactions(connectedState, [+ { id: "disconnect", payload: [...disconnected.projectPayload] },+ ]).state;+ const block = disconnectedState.instances?.get("block");+ expect(block?.children.at(0)).toEqual({ type: "id", value: "templates" });+ const bodyChild = block?.children.at(1);+ expect(bodyChild?.type).toBe("id");+ expect(+ bodyChild?.type === "id"+ ? disconnectedState.instances?.get(bodyChild.value)+ : undefined+ ).toMatchObject({ component: blockBodyComponent, children: [] });+ expect(disconnectedState.props?.has("src")).toBe(false);+ });++ test("edits and reloads the whole MDX source through the shared session", async () => {+ const fixture = createFixture();+ const connected = await fixture.application.connect({+ state: fixture.state,+ blockInstanceId: "block",+ renderScope: "page",+ source: { type: "asset", assetId: "asset" },+ });+ const connectedState = applyBuilderPatchTransactions(fixture.state, [+ { id: "connect", payload: [...connected.projectPayload] },+ ]).state;+ const saved = await fixture.application.editSource({+ state: connectedState,+ blockInstanceId: "block",+ renderScope: "page",+ source: "## Updated",+ });+ expect(saved.diagnostics).toEqual([]);+ expect(fixture.getSource()).toBe("## Updated");+ const inspected = await fixture.application.inspect({+ state: connectedState,+ blockInstanceId: "block",+ renderScope: "page",+ source: { type: "asset", assetId: "asset" },+ });+ expect(inspected.source).toBe("## Updated");++ const invalidSource = "# Kept\n\n<ws.element";+ const invalid = await fixture.application.editSource({+ state: connectedState,+ blockInstanceId: "block",+ renderScope: "page",+ source: invalidSource,+ });+ expect(fixture.getSource()).toBe(invalidSource);+ expect(invalid.diagnostics).toEqual([+ expect.objectContaining({+ code: "invalid-mdx",+ severity: "error",+ }),+ ]);+ });++ test("resolves expression sources from shared project variables", async () => {+ const fixture = createFixture();+ fixture.state.dataSources?.set("selectedAsset", {+ id: "selectedAsset",+ scopeInstanceId: "block",+ name: "selectedAsset",+ type: "variable",+ value: { type: "string", value: "asset" },+ });++ const inspected = await fixture.application.inspect({+ state: fixture.state,+ blockInstanceId: "block",+ renderScope: "page",+ source: { type: "expression", value: "selectedAsset" },+ });++ expect(inspected.identity.assetId).toBe("asset");+ expect(inspected.source).toBe("# From file");+ });++ test("previews frontmatter without mutating the Asset session", async () => {+ const fixture = createFixture();+ const connected = await fixture.application.connect({+ state: fixture.state,+ blockInstanceId: "block",+ renderScope: "page",+ source: { type: "asset", assetId: "asset" },+ });+ const connectedState = applyBuilderPatchTransactions(fixture.state, [+ { id: "connect", payload: [...connected.projectPayload] },+ ]).state;++ const preview = await fixture.application.previewFrontmatter({+ state: connectedState,+ blockInstanceId: "block",+ renderScope: "page",+ properties: { title: "Preview" },+ });++ expect(preview.source).toContain("title: Preview");+ expect(fixture.getSource()).toBe("# From file");+ });++ test("plans and confirms template reference migrations against exact revisions", async () => {+ const fixture = createFixture();+ await fixture.application.editSource({+ state: applyBuilderPatchTransactions(fixture.state, [+ {+ id: "connect",+ payload: [+ {+ namespace: "props",+ patches: [+ {+ op: "add",+ path: ["src"],+ value: {+ id: "src",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "asset",+ },+ },+ ],+ },+ ],+ },+ ]).state,+ blockInstanceId: "block",+ renderScope: "page",+ source: '<ws.element ws:name="Old" />',+ });+ const plan = await fixture.application.migrateTemplateReferences({+ assetIds: ["asset"],+ migration: { type: "rename", from: "Old", to: "New" },+ });+ expect(plan).toMatchObject({+ status: "confirmation-required",+ updateCount: 1,+ changedFileCount: 1,+ });+ if (plan.status !== "confirmation-required") {+ throw new Error("Expected a confirmation plan");+ }+ const result = await fixture.application.migrateTemplateReferences({+ assetIds: ["asset"],+ migration: { type: "rename", from: "Old", to: "New" },+ confirmationToken: plan.confirmationToken,+ });+ expect(result.status).toBe("complete");+ expect(fixture.getSource()).toContain('ws:name="New"');+ });+});diff --git a/packages/project-build/src/runtime/content-block-application.ts b/packages/project-build/src/runtime/content-block-application.tsnew file mode 100644index 0000000000..02022a1aa9--- /dev/null+++ b/packages/project-build/src/runtime/content-block-application.ts@@ -0,0 +1,532 @@+import {+ createMdxSourceDiagnostics,+ parseMdxDocumentRecovering,+ replaceMdxFrontmatter,+} from "@webstudio-is/content-engine/mdx";+import type { AssetContentSession } from "@webstudio-is/content-engine/asset-content-session";+import {+ getContentBlockSource,+ getContentBlockSources,+ createAssetContentRevision,+ createContentBlockExternalContentIdentity,+ isMdxFileAsset,+ type ContentBlockDiagnostic,+ type ContentBlockSource,+ type WebstudioData,+ type WsComponentMeta,+} from "@webstudio-is/sdk";+import type { BuilderState } from "../state/builder-state";+import {+ prepareContentBlockConnect,+ prepareContentBlockDisconnect,+ prepareContentBlockSwitch,+} from "./content-block-source-lifecycle";+import {+ componentInsertReadNamespaces,+ getRequiredComponentInsertData,+} from "./components";+import { resolveContentBlockSourceAssetId } from "./block";+import { materializeMdxSource } from "./mdx-source";+import {+ planMdxTemplateMigration,+ validateMdxTemplateMigrationConfirmation,+ type MdxTemplateMigration,+} from "./mdx-template-migration";++const getData = (state: BuilderState): Omit<WebstudioData, "pages"> => ({+ ...getRequiredComponentInsertData(state),+ ...(state.assetFolders === undefined+ ? {}+ : { assetFolders: state.assetFolders }),+});++export const mdxAssetInspectionNamespaces = componentInsertReadNamespaces;++export const inspectMdxAssetSource = async ({+ source,+ assetId,+ state,+ metas,+ projectId,+}: {+ source: string;+ assetId: string;+ state: BuilderState;+ metas: Map<string, WsComponentMeta>;+ projectId: string;+}) => {+ const parsed = await parseMdxDocumentRecovering({ source });+ const sourceDiagnostics = createMdxSourceDiagnostics(parsed.diagnostics);+ const diagnostics: Array<+ | ReturnType<typeof createMdxSourceDiagnostics>[number]+ | ContentBlockDiagnostic+ > = [...sourceDiagnostics];+ const sourceDiagnosticKeys = new Set(+ sourceDiagnostics.map((diagnostic) =>+ JSON.stringify([+ diagnostic.code,+ diagnostic.message,+ diagnostic.sourceRange,+ ])+ )+ );+ const asset = state.assets?.get(assetId);+ if (asset === undefined || isMdxFileAsset(asset) === false) {+ return diagnostics;+ }+ const data = getData(state);+ const values = new Map<string, unknown>();+ for (const dataSource of state.dataSources?.values() ?? []) {+ if (dataSource.type === "variable") {+ values.set(dataSource.name, dataSource.value.value);+ }+ }+ for (const [blockInstanceId, contentSource] of getContentBlockSources({+ instances: state.instances?.values() ?? [],+ props: state.props?.values() ?? [],+ })) {+ if (+ resolveContentBlockSourceAssetId({ source: contentSource, values }) !==+ assetId+ ) {+ continue;+ }+ const identity = createContentBlockExternalContentIdentity({+ blockInstanceId,+ asset,+ renderScope: `asset:${assetId}:block:${blockInstanceId}`,+ });+ const materialized = await materializeMdxSource({+ source,+ identity,+ data,+ metas,+ projectId,+ parsed: { source, result: parsed },+ });+ diagnostics.push(+ ...materialized.diagnostics.filter((diagnostic) => {+ if (+ diagnostic.code !== "invalid-mdx" &&+ diagnostic.code !== "unsafe-mdx"+ ) {+ return true;+ }+ const message =+ diagnostic.code === "invalid-mdx"+ ? diagnostic.message+ : diagnostic.reason;+ return (+ sourceDiagnosticKeys.has(+ JSON.stringify([diagnostic.code, message, diagnostic.sourceRange])+ ) === false+ );+ })+ );+ }+ return diagnostics;+};++export const createContentBlockApplication = ({+ projectId,+ session,+ metas,+ resolveSourceAssetId,+}: {+ projectId: string;+ session: Pick<AssetContentSession, "open" | "reload" | "save" | "flush">;+ metas: Map<string, WsComponentMeta>;+ resolveSourceAssetId?: (input: {+ source: ContentBlockSource;+ state: BuilderState;+ variables?: Readonly<Record<string, unknown>>;+ }) => string | undefined;+}) => {+ const resolveSource = ({+ source,+ state,+ variables,+ }: {+ source: ContentBlockSource;+ state: BuilderState;+ variables?: Readonly<Record<string, unknown>>;+ }) => {+ const resolved = resolveSourceAssetId?.({ source, state, variables });+ if (resolveSourceAssetId !== undefined) {+ if (resolved === undefined || resolved === "") {+ throw new Error("Content source does not resolve to an MDX Asset");+ }+ return resolved;+ }+ const values = new Map<string, unknown>();+ for (const dataSource of state.dataSources?.values() ?? []) {+ if (dataSource.type === "variable") {+ values.set(dataSource.name, dataSource.value.value);+ }+ }+ for (const [name, value] of Object.entries(variables ?? {})) {+ values.set(name, value);+ }+ const assetId = resolveContentBlockSourceAssetId({ source, values });+ if (assetId === undefined || assetId === "") {+ throw new Error("Content source does not resolve to an MDX Asset");+ }+ return assetId;+ };++ const open = async ({+ source,+ state,+ blockInstanceId,+ renderScope,+ variables,+ }: {+ source: ContentBlockSource;+ state: BuilderState;+ blockInstanceId: string;+ renderScope: string;+ variables?: Readonly<Record<string, unknown>>;+ }) => {+ const assetId = resolveSource({+ source,+ state,+ variables,+ });+ const sessionState = await session.open(assetId);+ if (+ sessionState.asset.id !== assetId ||+ sessionState.asset.projectId !== projectId ||+ isMdxFileAsset(sessionState.asset) === false+ ) {+ throw new Error("Content source must resolve to an MDX Asset");+ }+ const identity = createContentBlockExternalContentIdentity({+ blockInstanceId,+ asset: sessionState.asset,+ renderScope,+ });+ return { state: sessionState, identity };+ };++ const requireConfiguredSource = ({+ state,+ blockInstanceId,+ }: {+ state: BuilderState;+ blockInstanceId: string;+ }) => {+ const source = getContentBlockSource({+ blockInstanceId,+ props: state.props?.values() ?? [],+ });+ if (source === undefined) {+ throw new Error("Content Block is not connected to an MDX Asset");+ }+ return source;+ };++ const inspect = async ({+ state,+ blockInstanceId,+ renderScope,+ source = requireConfiguredSource({ state, blockInstanceId }),+ variables,+ }: {+ state: BuilderState;+ blockInstanceId: string;+ renderScope: string;+ source?: ContentBlockSource;+ variables?: Readonly<Record<string, unknown>>;+ }) => {+ const opened = await open({+ source,+ state,+ blockInstanceId,+ renderScope,+ variables,+ });+ const materialized = await materializeMdxSource({+ source: opened.state.source,+ identity: opened.identity,+ data: getData(state),+ metas,+ projectId,+ });+ return {+ sessionState: opened.state,+ source: opened.state.source,+ sessionStatus: opened.state.status,+ identity: opened.identity,+ diagnostics: materialized.diagnostics,+ fragment: materialized.root.fragment,+ };+ };++ const connect = async ({+ state,+ blockInstanceId,+ renderScope,+ source,+ variables,+ }: {+ state: BuilderState;+ blockInstanceId: string;+ renderScope: string;+ source: ContentBlockSource;+ variables?: Readonly<Record<string, unknown>>;+ }) => {+ const inspection = await inspect({+ state,+ blockInstanceId,+ renderScope,+ source,+ variables,+ });+ return {+ ...prepareContentBlockConnect({+ state,+ blockInstanceId,+ source,+ }),+ inspection,+ };+ };++ const switchSource = async ({+ state,+ blockInstanceId,+ renderScope,+ source,+ variables,+ }: Parameters<typeof connect>[0]) => {+ const inspection = await inspect({+ state,+ blockInstanceId,+ renderScope,+ source,+ variables,+ });+ return {+ ...prepareContentBlockSwitch({+ state,+ blockInstanceId,+ source,+ }),+ inspection,+ };+ };++ const disconnect = ({+ state,+ blockInstanceId,+ }: {+ state: BuilderState;+ blockInstanceId: string;+ }) =>+ prepareContentBlockDisconnect({+ state,+ blockInstanceId,+ });++ const prepareSourceUpdate = async ({+ state,+ blockInstanceId,+ renderScope,+ variables,+ update,+ }: {+ state: BuilderState;+ blockInstanceId: string;+ renderScope: string;+ variables?: Readonly<Record<string, unknown>>;+ update: (source: string) => string | Promise<string>;+ }) => {+ const configured = requireConfiguredSource({ state, blockInstanceId });+ const { state: opened, identity } = await open({+ source: configured,+ state,+ blockInstanceId,+ renderScope,+ variables,+ });+ const nextSource = await update(opened.source);+ const materialized = await materializeMdxSource({+ source: nextSource,+ identity,+ data: getData(state),+ metas,+ projectId,+ });+ return {+ state: opened,+ identity,+ source: nextSource,+ diagnostics: materialized.diagnostics,+ };+ };++ const updateSource = async (+ input: Parameters<typeof prepareSourceUpdate>[0]+ ) => {+ const prepared = await prepareSourceUpdate(input);+ session.save(prepared.identity.assetId, prepared.source);+ const saved = await session.flush(prepared.identity.assetId);+ return {+ state: saved,+ source: saved.source,+ diagnostics: prepared.diagnostics,+ };+ };++ const reload = async ({+ state,+ blockInstanceId,+ renderScope,+ variables,+ }: Omit<Parameters<typeof updateSource>[0], "update">) => {+ const source = requireConfiguredSource({ state, blockInstanceId });+ const opened = await open({+ source,+ state,+ blockInstanceId,+ renderScope,+ variables,+ });+ return session.reload(opened.identity.assetId, {+ expectedName: opened.state.asset.name,+ });+ };++ const migrateTemplateReferences = async ({+ assetIds,+ migration,+ confirmationToken,+ dryRun = false,+ }: {+ assetIds: readonly string[];+ migration: MdxTemplateMigration;+ confirmationToken?: string;+ dryRun?: boolean;+ }) => {+ const files = await Promise.all(+ assetIds.map(async (assetId) => {+ const opened = await session.open(assetId);+ if (+ opened.asset.projectId !== projectId ||+ isMdxFileAsset(opened.asset) === false+ ) {+ throw new Error(`Asset "${assetId}" is not an MDX Asset`);+ }+ return {+ assetId,+ revision: createAssetContentRevision({+ storageName: opened.asset.name,+ updatedAt: opened.asset.updatedAt ?? opened.asset.createdAt,+ size: opened.asset.size,+ }),+ contentRef: opened.asset.name,+ source: opened.source,+ };+ })+ );+ const plan = await planMdxTemplateMigration({+ projectId,+ migration,+ files,+ selectionAssetIds: assetIds,+ });+ if (+ dryRun ||+ (await validateMdxTemplateMigrationConfirmation({+ projectId,+ plan,+ confirmationToken,+ })) === false+ ) {+ return plan;+ }+ const results = [];+ for (const file of plan.files) {+ if (file.changed === false) {+ results.push({ ...file, status: "unchanged" as const });+ continue;+ }+ try {+ session.save(file.assetId, file.source);+ await session.flush(file.assetId);+ results.push({ ...file, status: "updated" as const });+ } catch (error) {+ results.push({+ ...file,+ status: "failed" as const,+ diagnostics: [+ ...file.diagnostics,+ {+ code: "asset-write-failed" as const,+ assetId: file.assetId,+ contentRef: file.contentRef,+ message:+ error instanceof Error+ ? error.message+ : "Unable to update MDX Asset",+ },+ ],+ });+ }+ }+ return {+ status: results.some(({ status }) => status === "failed")+ ? ("partial" as const)+ : ("complete" as const),+ migration,+ files: results,+ updateCount: results.reduce((sum, file) => sum + file.updateCount, 0),+ omissionCount: results.reduce((sum, file) => sum + file.omissionCount, 0),+ changedFileCount: results.filter(({ status }) => status === "updated")+ .length,+ };+ };++ return {+ inspect,+ connect,+ switchSource,+ disconnect,+ editSource: (+ input: Omit<Parameters<typeof updateSource>[0], "update"> & {+ source: string;+ }+ ) => updateSource({ ...input, update: () => input.source }),+ previewSource: (+ input: Omit<Parameters<typeof prepareSourceUpdate>[0], "update"> & {+ source: string;+ }+ ) => prepareSourceUpdate({ ...input, update: () => input.source }),+ updateFrontmatter: (+ input: Omit<Parameters<typeof updateSource>[0], "update"> & {+ properties: Readonly<Record<string, unknown>>;+ }+ ) =>+ updateSource({+ ...input,+ update: (source) =>+ replaceMdxFrontmatter({ source, properties: input.properties }),+ }),+ previewFrontmatter: (+ input: Omit<Parameters<typeof prepareSourceUpdate>[0], "update"> & {+ properties: Readonly<Record<string, unknown>>;+ }+ ) =>+ prepareSourceUpdate({+ ...input,+ update: (source) =>+ replaceMdxFrontmatter({ source, properties: input.properties }),+ }),+ reload,+ migrateTemplateReferences,+ };+};++export type ContentBlockApplication = ReturnType<+ typeof createContentBlockApplication+>;diff --git a/packages/project-build/src/runtime/content-block-source-lifecycle.test.ts b/packages/project-build/src/runtime/content-block-source-lifecycle.test.tsnew file mode 100644index 0000000000..45d7f82620--- /dev/null+++ b/packages/project-build/src/runtime/content-block-source-lifecycle.test.ts@@ -0,0 +1,226 @@+import { describe, expect, test } from "vitest";+import {+ blockBodyComponent,+ blockComponent,+ blockTemplateComponent,+ elementComponent,+ type Instance,+} from "@webstudio-is/sdk";+import type { BuilderState } from "../state/builder-state";+import { applyBuilderPatchTransactions } from "../state/patch";+import { createDefaultPages } from "../shared/pages-utils";+import {+ prepareContentBlockConnect,+ prepareContentBlockDisconnect,+ prepareContentBlockSwitch,+} from "./content-block-source-lifecycle";++const state = ({+ source = false,+ explicitBody = false,+}: { source?: boolean; explicitBody?: boolean } = {}): BuilderState => ({+ pages: createDefaultPages({ rootInstanceId: "block" }),+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [+ { type: "id", value: "templates" },+ ...(explicitBody+ ? [+ { type: "id" as const, value: "header" },+ { type: "id" as const, value: "body-outlet" },+ { type: "id" as const, value: "footer" },+ ]+ : [{ type: "id" as const, value: "body" }]),+ ],+ },+ ],+ ...(explicitBody+ ? [+ [+ "header",+ {+ type: "instance" as const,+ id: "header",+ component: elementComponent,+ tag: "header",+ children: [],+ },+ ] as [string, Instance],+ [+ "body-outlet",+ {+ type: "instance" as const,+ id: "body-outlet",+ component: blockBodyComponent,+ children: [{ type: "id" as const, value: "body" }],+ },+ ] as [string, Instance],+ [+ "footer",+ {+ type: "instance" as const,+ id: "footer",+ component: elementComponent,+ tag: "footer",+ children: [],+ },+ ] as [string, Instance],+ ]+ : []),+ [+ "templates",+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: elementComponent,+ tag: "p",+ children: [{ type: "text", value: "Existing" }],+ },+ ],+ ]),+ props: source+ ? new Map([+ [+ "src",+ {+ id: "src",+ instanceId: "block",+ name: "src",+ type: "asset" as const,+ value: "first",+ },+ ],+ ])+ : new Map(),+ dataSources: new Map(),+ resources: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ breakpoints: new Map(),+ assets: new Map(),+});++const apply = (+ current: BuilderState,+ payload: ReturnType<typeof prepareContentBlockConnect>["projectPayload"]+) =>+ applyBuilderPatchTransactions(current, [+ { id: "test", payload: [...payload] },+ ]).state;++describe("Content Block source lifecycle", () => {+ test("connect replaces ordinary body content without producing Asset writes", () => {+ const current = state();+ const prepared = prepareContentBlockConnect({+ state: current,+ blockInstanceId: "block",+ source: { type: "asset", assetId: "asset" },+ });+ const connected = apply(current, prepared.projectPayload);++ expect(prepared.requiresConfirmation).toBe(true);+ const connectedChildren = connected.instances?.get("block")?.children;+ expect(connectedChildren?.at(0)).toEqual({+ type: "id",+ value: "templates",+ });+ const bodyChild = connectedChildren?.at(1);+ expect(bodyChild?.type).toBe("id");+ expect(+ bodyChild?.type === "id"+ ? connected.instances?.get(bodyChild.value)?.component+ : undefined+ ).toBe(blockBodyComponent);+ expect(connected.instances?.has("body")).toBe(false);+ const sourceProp = Array.from(connected.props?.values() ?? []).find(+ ({ name }) => name === "src"+ );+ expect(sourceProp?.id).toMatch(/^[\w-]{21}$/);+ expect(sourceProp).toMatchObject({+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "asset",+ });+ const documentProp = Array.from(connected.props?.values() ?? []).find(+ ({ name }) => name === "document"+ );+ expect(documentProp).toMatchObject({+ instanceId: "block",+ name: "document",+ type: "parameter",+ });+ expect(+ connected.dataSources?.get(+ documentProp?.type === "parameter" ? documentProp.value : ""+ )+ ).toMatchObject({+ scopeInstanceId: "block",+ name: "document",+ type: "parameter",+ });+ });++ test("connect clears only the explicit Body outlet", () => {+ const current = state({ explicitBody: true });+ const prepared = prepareContentBlockConnect({+ state: current,+ blockInstanceId: "block",+ source: { type: "asset", assetId: "asset" },+ });+ const connected = apply(current, prepared.projectPayload);++ expect(prepared.requiresConfirmation).toBe(true);+ expect(connected.instances?.get("block")?.children).toEqual([+ { type: "id", value: "templates" },+ { type: "id", value: "header" },+ { type: "id", value: "body-outlet" },+ { type: "id", value: "footer" },+ ]);+ expect(connected.instances?.get("body-outlet")?.children).toEqual([]);+ expect(connected.instances?.has("body")).toBe(false);+ expect(connected.instances?.has("header")).toBe(true);+ expect(connected.instances?.has("footer")).toBe(true);+ });++ test("switch changes only the source contract", () => {+ const current = state({ source: true });+ const prepared = prepareContentBlockSwitch({+ state: current,+ blockInstanceId: "block",+ source: { type: "asset", assetId: "second" },+ });+ const switched = apply(current, prepared.projectPayload);++ expect(switched.instances).toEqual(current.instances);+ expect(switched.props?.get("src")).toMatchObject({ value: "second" });+ });++ test("disconnect removes only the source property", () => {+ const current = state({ source: true });+ const prepared = prepareContentBlockDisconnect({+ state: current,+ blockInstanceId: "block",+ });+ const disconnected = apply(current, prepared.projectPayload);++ expect(disconnected.instances).toEqual(current.instances);+ expect(disconnected.props?.has("src")).toBe(false);+ expect(prepared.requiresConfirmation).toBe(false);+ });+});diff --git a/packages/project-build/src/runtime/content-block-source-lifecycle.ts b/packages/project-build/src/runtime/content-block-source-lifecycle.tsnew file mode 100644index 0000000000..70dfa455ad--- /dev/null+++ b/packages/project-build/src/runtime/content-block-source-lifecycle.ts@@ -0,0 +1,356 @@+import {+ blockBodyComponent,+ blockComponent,+ contentBlockDocumentProp,+ contentBlockSourceProp,+ createId,+ findContentBlockBodyContainers,+ findContentBlockTemplateContainers,+ isEqualContentBlockSource,+ parseContentBlockSourceProp,+ type ContentBlockSource,+ type Prop,+} from "@webstudio-is/sdk";+import type { BuilderPatchChange } from "../contracts/patch";+import type { BuilderState } from "../state/builder-state";+import { createInstanceDeletePayload } from "./instances";+import { mergeBuilderPatchChanges } from "./mutation";++export type PreparedContentBlockSourceLifecycle = Readonly<{+ action: "connect" | "switch" | "disconnect";+ projectPayload: readonly BuilderPatchChange[];+ requiresConfirmation: boolean;+}>;++const getBlockParts = (state: BuilderState, blockInstanceId: string) => {+ const block = state.instances?.get(blockInstanceId);+ if (block?.component !== blockComponent) {+ throw new Error(`Content Block "${blockInstanceId}" does not exist`);+ }+ const templateContainers = findContentBlockTemplateContainers({+ blockInstance: block,+ instances: state.instances ?? new Map(),+ });+ if (templateContainers.length !== 1) {+ throw new Error("Content Block must contain exactly one Templates list");+ }+ const [templateContainer] = templateContainers;+ const templateChild = {+ type: "id" as const,+ value: templateContainer.id,+ };+ const bodyContainers = findContentBlockBodyContainers({+ blockInstance: block,+ instances: state.instances ?? new Map(),+ });+ if (bodyContainers.length > 1) {+ throw new Error("Content Block must contain at most one Body outlet");+ }+ const bodyContainer = bodyContainers[0] ?? block;+ return {+ block,+ bodyContainer,+ templateChild,+ bodyChildren:+ bodyContainer === block+ ? block.children.filter(+ (child) =>+ child.type !== "id" || child.value !== templateContainer.id+ )+ : bodyContainer.children,+ };+};++const getSourceProp = (state: BuilderState, blockInstanceId: string) => {+ const sourceProps = Array.from(state.props?.values() ?? []).filter(+ (prop) =>+ prop.instanceId === blockInstanceId &&+ prop.name === contentBlockSourceProp+ );+ if (sourceProps.length > 1) {+ throw new Error("Content Block has multiple source props");+ }+ return sourceProps[0];+};++const toSourceProp = ({+ id,+ blockInstanceId,+ source,+}: {+ id: string;+ blockInstanceId: string;+ source: ContentBlockSource;+}): Prop =>+ source.type === "asset"+ ? {+ id,+ instanceId: blockInstanceId,+ name: contentBlockSourceProp,+ type: "asset",+ value: source.assetId,+ }+ : {+ id,+ instanceId: blockInstanceId,+ name: contentBlockSourceProp,+ type: "expression",+ value: source.value,+ mode: "read",+ };++const createSourcePayload = ({+ state,+ blockInstanceId,+ source,+}: {+ state: BuilderState;+ blockInstanceId: string;+ source?: ContentBlockSource;+}): BuilderPatchChange[] => {+ const existing = getSourceProp(state, blockInstanceId);+ if (source === undefined) {+ return existing === undefined+ ? []+ : [+ {+ namespace: "props",+ patches: [{ op: "remove", path: [existing.id] }],+ },+ ];+ }+ const next = toSourceProp({+ id: existing?.id ?? createId("nano"),+ blockInstanceId,+ source,+ });+ if (+ existing !== undefined &&+ isEqualContentBlockSource(parseContentBlockSourceProp(existing), source)+ ) {+ return [];+ }+ return [+ {+ namespace: "props",+ patches: [+ existing === undefined+ ? { op: "add", path: [next.id], value: next }+ : { op: "replace", path: [existing.id], value: next },+ ],+ },+ ];+};++const createDocumentParameterPayload = (+ state: BuilderState,+ blockInstanceId: string+): BuilderPatchChange[] => {+ const existing = Array.from(state.props?.values() ?? []).find(+ (prop) =>+ prop.instanceId === blockInstanceId &&+ prop.name === contentBlockDocumentProp+ );+ if (existing?.type === "parameter") {+ return [];+ }+ if (existing !== undefined) {+ throw new Error("Content Block document prop must be a parameter");+ }+ const dataSourceId = createId("nano");+ const propId = createId("nano");+ return [+ {+ namespace: "dataSources",+ patches: [+ {+ op: "add",+ path: [dataSourceId],+ value: {+ type: "parameter",+ id: dataSourceId,+ scopeInstanceId: blockInstanceId,+ name: contentBlockDocumentProp,+ },+ },+ ],+ },+ {+ namespace: "props",+ patches: [+ {+ op: "add",+ path: [propId],+ value: {+ id: propId,+ instanceId: blockInstanceId,+ name: contentBlockDocumentProp,+ type: "parameter",+ value: dataSourceId,+ },+ },+ ],+ },+ ];+};++const createContentBlockBodyRemoval = ({+ state,+ blockInstanceId,+}: {+ state: BuilderState;+ blockInstanceId: string;+}) => {+ const { block, bodyContainer, templateChild, bodyChildren } = getBlockParts(+ state,+ blockInstanceId+ );+ const rootIds = bodyChildren.flatMap((child) =>+ child.type === "id" ? [child.value] : []+ );+ const cleanup =+ rootIds.length === 0+ ? []+ : createInstanceDeletePayload({+ instances: state.instances ?? new Map(),+ instanceIds: rootIds,+ props: state.props?.values() ?? [],+ dataSources: state.dataSources?.values() ?? [],+ styleSources: state.styleSources?.values() ?? [],+ styleSourceSelections: state.styleSourceSelections?.values() ?? [],+ styles: state.styles?.values() ?? [],+ });+ if (cleanup !== undefined && "errors" in cleanup && cleanup.errors.length) {+ throw new Error("Content Block body is not a valid instance tree");+ }+ const bodyInstanceId =+ bodyContainer === block ? createId("nano") : bodyContainer.id;+ const createBodyPayload: BuilderPatchChange[] =+ bodyContainer === block+ ? [+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: [bodyInstanceId],+ value: {+ type: "instance",+ id: bodyInstanceId,+ component: blockBodyComponent,+ children: [],+ },+ },+ ],+ },+ ]+ : [];+ return {+ hasBody: bodyChildren.length > 0,+ projectPayload: mergeBuilderPatchChanges(+ cleanup === undefined || Array.isArray(cleanup) ? [] : cleanup.payload,+ createBodyPayload,+ [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: [bodyContainer.id, "children"],+ value:+ bodyContainer === block+ ? [templateChild, { type: "id", value: bodyInstanceId }]+ : [],+ },+ ],+ },+ ]+ ),+ };+};++export const prepareContentBlockConnect = ({+ state,+ blockInstanceId,+ source,+}: {+ state: BuilderState;+ blockInstanceId: string;+ source: ContentBlockSource;+}): PreparedContentBlockSourceLifecycle => {+ const existing = getSourceProp(state, blockInstanceId);+ if (+ existing !== undefined &&+ isEqualContentBlockSource(parseContentBlockSourceProp(existing), source) ===+ false+ ) {+ throw new Error("Content Block is already connected; use switch instead");+ }+ const removal = createContentBlockBodyRemoval({ state, blockInstanceId });+ return {+ action: "connect",+ projectPayload: mergeBuilderPatchChanges(+ removal.projectPayload,+ createSourcePayload({+ state,+ blockInstanceId,+ source,+ }),+ createDocumentParameterPayload(state, blockInstanceId)+ ),+ requiresConfirmation: existing === undefined && removal.hasBody,+ };+};++export const prepareContentBlockSwitch = ({+ state,+ blockInstanceId,+ source,+}: {+ state: BuilderState;+ blockInstanceId: string;+ source: ContentBlockSource;+}): PreparedContentBlockSourceLifecycle => {+ getBlockParts(state, blockInstanceId);+ if (getSourceProp(state, blockInstanceId) === undefined) {+ throw new Error("Content Block is not connected; use connect instead");+ }+ return {+ action: "switch",+ projectPayload: mergeBuilderPatchChanges(+ createSourcePayload({+ state,+ blockInstanceId,+ source,+ }),+ createDocumentParameterPayload(state, blockInstanceId)+ ),+ requiresConfirmation: false,+ };+};++export const prepareContentBlockDisconnect = ({+ state,+ blockInstanceId,+}: {+ state: BuilderState;+ blockInstanceId: string;+}): PreparedContentBlockSourceLifecycle => {+ const source = getSourceProp(state, blockInstanceId);+ if (source === undefined) {+ return {+ action: "disconnect",+ projectPayload: [],+ requiresConfirmation: false,+ };+ }+ getBlockParts(state, blockInstanceId);+ return {+ action: "disconnect",+ projectPayload: createSourcePayload({+ state,+ blockInstanceId,+ }),+ requiresConfirmation: false,+ };+};diff --git a/packages/project-build/src/runtime/content-mode-permissions.test.ts b/packages/project-build/src/runtime/content-mode-permissions.test.tsindex 6aa23736f1..09f1893e74 100644--- a/packages/project-build/src/runtime/content-mode-permissions.test.ts+++ b/packages/project-build/src/runtime/content-mode-permissions.test.ts@@ -1,7 +1,12 @@import { describe, expect, test } from "vitest";import {blockComponent,+ blockBodyComponent,blockTemplateComponent,+ contentBlockDocumentProp,+ contentBlockSourceProp,+ encodeDataSourceVariable,+ elementComponent,getStyleDeclKey,} from "@webstudio-is/sdk";import type {@@ -15,6 +20,7 @@ import {applyContentModeTransaction,getContentModeCapabilities,getContentModeEditableInstanceIds,+ getContentModePropEligibility,getContentModePropNamesByTag,isContentModeCopyableProp,isContentModePagePath,@@ -49,6 +55,19 @@ const metas = new Map<string, WsComponentMeta>([},},],+ [+ "Heading",+ {+ props: {+ description: {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ },+ },+ },+ ],]);const instances = new Map<string, Instance>([@@ -99,6 +118,319 @@ const styleSources = new Map([["local", { type: "local" as const, id: "local" }],]);+test("limits an explicit Content Block to its Body and frontmatter bindings", () => {+ const document = encodeDataSourceVariable("document-data-source");+ const explicitInstances = new Map<string, Instance>([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [+ { type: "id", value: "shell" },+ { type: "id", value: "title" },+ { type: "id", value: "content" },+ ],+ },+ ],+ [+ "shell",+ {+ type: "instance",+ id: "shell",+ component: "Box",+ children: [],+ },+ ],+ [+ "title",+ {+ type: "instance",+ id: "title",+ component: "Heading",+ children: [+ {+ type: "expression",+ value: `${document}.frontmatter.title`,+ mode: "readwrite",+ },+ ],+ },+ ],+ [+ "content",+ {+ type: "instance",+ id: "content",+ component: blockBodyComponent,+ children: [{ type: "id", value: "paragraph" }],+ },+ ],+ [+ "paragraph",+ {+ type: "instance",+ id: "paragraph",+ component: "Paragraph",+ children: [],+ },+ ],+ ]);+ const explicitProps = new Map<string, Prop>([+ [+ "source-prop",+ {+ id: "source-prop",+ instanceId: "block",+ name: contentBlockSourceProp,+ type: "asset",+ value: "article",+ },+ ],+ [+ "document-prop",+ {+ id: "document-prop",+ instanceId: "block",+ name: contentBlockDocumentProp,+ type: "parameter",+ value: "document-data-source",+ },+ ],+ [+ "designed-description",+ {+ id: "designed-description",+ instanceId: "title",+ name: "description",+ type: "string",+ value: "Designed description",+ },+ ],+ ]);++ const capabilities = getContentModeCapabilities({+ instances: explicitInstances,+ metas,+ props: explicitProps,+ styleSources,+ });++ expect(capabilities.contentRootIds).toEqual(new Set(["content"]));+ expect(capabilities.editableInstanceIds.has("paragraph")).toBe(true);+ expect(capabilities.editableInstanceIds.has("title")).toBe(false);+ expect(capabilities.editablePropIds.has("designed-description")).toBe(false);+ expect(capabilities.editableInstanceIds.has("shell")).toBe(false);+ expect(capabilities.editableInstanceIds.has("block")).toBe(false);+ expect(capabilities.frontmatterBoundTextInstanceIds).toEqual(+ new Set(["title"])+ );++ const result = applyContentModeTransaction({+ capabilities,+ transaction: {+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: ["paragraph", "children"],+ value: [{ type: "text", value: "Updated" }],+ },+ ],+ },+ ],+ },+ });+ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.capabilities.editableInstanceIds.has("title")).toBe(false);+ }+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: ["title", "children"],+ value: [{ type: "text", value: "Bypassed frontmatter" }],+ },+ ],+ },+ ],+ },+ }).success+ ).toBe(false);+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ payload: [+ {+ namespace: "instances",+ patches: [{ op: "remove", path: ["title"] }],+ },+ ],+ },+ }).success+ ).toBe(false);++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ payload: [+ {+ namespace: "props",+ patches: [+ {+ op: "add",+ path: ["shell-content-prop"],+ value: {+ id: "shell-content-prop",+ instanceId: "title",+ name: "description",+ type: "string",+ value: "Changed in content mode",+ },+ },+ ],+ },+ ],+ },+ }).success+ ).toBe(false);++ explicitProps.delete("source-prop");+ const disconnected = getContentModeCapabilities({+ instances: explicitInstances,+ metas,+ props: explicitProps,+ styleSources,+ });+ expect(disconnected.editableInstanceIds.has("title")).toBe(false);+});++test("keeps direct frontmatter expressions read-only without readwrite mode", () => {+ const document = encodeDataSourceVariable("document-data-source");+ const directInstances = new Map<string, Instance>([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "title" }],+ },+ ],+ [+ "title",+ {+ type: "instance",+ id: "title",+ component: "Heading",+ children: [+ { type: "expression", value: `${document}.frontmatter.title` },+ ],+ },+ ],+ ]);+ const directProps = new Map<string, Prop>([+ [+ "source",+ {+ id: "source",+ instanceId: "block",+ name: contentBlockSourceProp,+ type: "asset",+ value: "article",+ },+ ],+ [+ "document",+ {+ id: "document",+ instanceId: "block",+ name: contentBlockDocumentProp,+ type: "parameter",+ value: "document-data-source",+ },+ ],+ ]);++ const capabilities = getContentModeCapabilities({+ instances: directInstances,+ metas,+ props: directProps,+ styleSources,+ });+ expect(capabilities.frontmatterBoundTextInstanceIds).toEqual(new Set());+});++test("does not loop while finding frontmatter bindings in recursive instances", () => {+ const document = encodeDataSourceVariable("document-data-source");+ const recursiveInstances = new Map<string, Instance>([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "recursive" }],+ },+ ],+ [+ "recursive",+ {+ type: "instance",+ id: "recursive",+ component: "Box",+ children: [+ { type: "expression", value: `${document}.frontmatter.title` },+ { type: "id", value: "recursive" },+ ],+ },+ ],+ ]);+ const recursiveProps = new Map<string, Prop>([+ [+ "source",+ {+ id: "source",+ instanceId: "block",+ name: contentBlockSourceProp,+ type: "asset",+ value: "article",+ },+ ],+ [+ "document",+ {+ id: "document",+ instanceId: "block",+ name: contentBlockDocumentProp,+ type: "parameter",+ value: "document-data-source",+ },+ ],+ ]);++ expect(() =>+ getContentModeCapabilities({+ instances: recursiveInstances,+ metas,+ props: recursiveProps,+ styleSources,+ })+ ).not.toThrow();+});+const transaction = (namespace: string,patches: ContentModePatchTransaction["payload"][number]["patches"]@@ -1074,6 +1406,69 @@ describe("content mode permissions", () => {).toBe(false);});+ test("explains why a prop is not editable in content mode", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ });+ const instance = instances.get("link")!;+ const getEligibility = (prop: Prop) =>+ getContentModePropEligibility({ capabilities, instance, prop });++ expect(getEligibility(props.get("href-prop")!)).toEqual({+ editable: true,+ });+ expect(+ getEligibility({+ id: "boolean-href",+ instanceId: "link",+ name: "href",+ type: "boolean",+ value: true,+ })+ ).toEqual({ editable: false, reason: "incompatible" });+ expect(getEligibility(props.get("target-prop")!)).toEqual({+ editable: false,+ reason: "design-only",+ });+ expect(+ getEligibility({+ id: "unknown-prop",+ instanceId: "link",+ name: "unknown",+ type: "string",+ value: "value",+ })+ ).toEqual({ editable: false, reason: "unknown" });+ });++ test("does not grant content-mode access to standard HTML attributes", () => {+ const instance: Instance = {+ type: "instance",+ id: "element",+ component: elementComponent,+ tag: "div",+ children: [],+ };+ const capabilities = getContentModeCapabilities({+ instances: new Map([[instance.id, instance]]),+ metas: new Map(),+ props: new Map(),+ styleSources: new Map(),+ contentRootIds: new Set([instance.id]),+ });++ expect(+ getContentModePropEligibility({+ capabilities,+ instance,+ prop: { name: "class", type: "string" },+ })+ ).toEqual({ editable: false, reason: "unknown" });+ });+test("supports content mode props derived from ws:element tag", () => {const capabilities = getContentModeCapabilities({instances: new Map([diff --git a/packages/project-build/src/runtime/content-mode-permissions.ts b/packages/project-build/src/runtime/content-mode-permissions.tsindex 817bd68738..eb6b9bba8d 100644--- a/packages/project-build/src/runtime/content-mode-permissions.ts+++ b/packages/project-build/src/runtime/content-mode-permissions.ts@@ -10,6 +10,8 @@ import {pagePath,blockComponent,blockTemplateComponent,+ findContentBlockBodyContainers,+ findWritableContentBlockDocumentBindings,getHtmlTagsFromProps,getHtmlTagFromInstance,isPathnamePattern,@@ -17,6 +19,7 @@ import {type Breakpoints,type Instance,type Prop,+ type PropMeta,type Props,type StyleDecl,type StyleSource,@@ -46,6 +49,8 @@ export type ContentModeCapabilities = {styles: Styles;breakpoints?: Breakpoints;contentRootIds: Set<Instance["id"]>;+ frontmatterBoundPropIds?: ReadonlySet<Prop["id"]>;+ frontmatterBoundTextInstanceIds?: ReadonlySet<Instance["id"]>;};type ContentModeTransactionContext = {@@ -177,12 +182,41 @@ const getDefaultContentRootIds = (instances: Map<Instance["id"], Instance>) => {const contentRootIds = new Set<Instance["id"]>();for (const instance of instances.values()) {if (instance.component === blockComponent) {- contentRootIds.add(instance.id);+ const bodies = findContentBlockBodyContainers({+ blockInstance: instance,+ instances,+ });+ if (bodies.length === 1) {+ contentRootIds.add(bodies[0].id);+ } else if (bodies.length === 0) {+ contentRootIds.add(instance.id);+ }}}return contentRootIds;};+export const getContentModeFrontmatterBoundTargets = ({+ instances,+ props,+}: {+ instances: Map<Instance["id"], Instance>;+ props: Props;+}) => {+ const bindings = findWritableContentBlockDocumentBindings({+ instances,+ props,+ });+ const propIds = new Set(bindings.props.map(({ propId }) => propId));+ const textInstanceIds = new Set<Instance["id"]>();+ for (const { instanceId, childIndex } of bindings.children) {+ if (childIndex === 0 && instances.get(instanceId)?.children.length === 1) {+ textInstanceIds.add(instanceId);+ }+ }+ return { propIds, textInstanceIds };+};+export const getContentModeEditableInstanceIds = ({contentRootIds,instances,@@ -254,7 +288,7 @@ const getBlockTemplateChildIdsByInstanceId = (return childIdsByInstanceId;};-const getContentModePropMeta = ({+const getInstancePropMetas = ({capabilities,instance,propName,@@ -263,10 +297,12 @@ const getContentModePropMeta = ({instance: Instance;propName: Prop["name"];}) => {- const meta = capabilities.metas.get(instance.component);- const propMeta = meta?.props?.[propName];- if (propMeta?.contentMode === true) {- return propMeta;+ const propMetas: PropMeta[] = [];+ const propMeta = capabilities.metas.get(instance.component)?.props?.[+ propName+ ];+ if (propMeta !== undefined) {+ propMetas.push(propMeta);}const tag = getHtmlTagFromInstance({@@ -276,34 +312,114 @@ const getContentModePropMeta = ({htmlTagsByInstanceId: capabilities.htmlTagsByInstanceId,});if (tag === undefined) {- return;+ return propMetas;}for (const componentMeta of capabilities.metas.values()) {if (Object.keys(componentMeta.presetStyle ?? {}).includes(tag) === false) {continue;}const propMeta = componentMeta.props?.[propName];- if (propMeta?.contentMode === true) {- return propMeta;+ if (propMeta !== undefined) {+ propMetas.push(propMeta);}}+ return propMetas;};-const isContentModePropForInstance = ({+export const getContentModeEditableStaticPropNames = ({+ capabilities,+ instance,+}: {+ capabilities: ContentModeCapabilities;+ instance: Instance;+}) => {+ const names = new Set<string>();+ for (const [name, propMeta] of Object.entries(+ capabilities.metas.get(instance.component)?.props ?? {}+ )) {+ if (+ propMeta.contentMode === true &&+ (propMeta.type === "string" ||+ propMeta.type === "number" ||+ propMeta.type === "boolean")+ ) {+ names.add(name);+ }+ }+ const tag = getHtmlTagFromInstance({+ instance,+ metas: capabilities.metas,+ props: capabilities.props,+ htmlTagsByInstanceId: capabilities.htmlTagsByInstanceId,+ });+ if (tag !== undefined) {+ for (const name of getContentModePropNamesByTag(capabilities.metas).get(+ tag+ ) ?? []) {+ if (+ getInstancePropMetas({ capabilities, instance, propName: name }).some(+ (propMeta) =>+ propMeta.contentMode === true &&+ (propMeta.type === "string" ||+ propMeta.type === "number" ||+ propMeta.type === "boolean")+ )+ ) {+ names.add(name);+ }+ }+ }+ return names;+};++export type ContentModePropEligibility =+ | { editable: true }+ | {+ editable: false;+ reason: "unknown" | "incompatible" | "design-only";+ };++export const getContentModePropEligibility = ({capabilities,instance,prop,}: {capabilities: ContentModeCapabilities;instance: Instance;- prop: Prop;-}) =>- prop.type === "asset" ||- getContentModePropMeta({+ prop: Pick<Prop, "name" | "type">;+}): ContentModePropEligibility => {+ if (prop.type === "asset") {+ return { editable: true };+ }+ const propMetas = getInstancePropMetas({capabilities,instance,propName: prop.name,- })?.type === prop.type;+ });+ const contentModePropMeta = propMetas.find(+ (propMeta) => propMeta.contentMode === true+ );+ if (contentModePropMeta === undefined) {+ return {+ editable: false,+ reason: propMetas.length === 0 ? "unknown" : "design-only",+ };+ }+ if (contentModePropMeta.type !== prop.type) {+ return { editable: false, reason: "incompatible" };+ }+ return { editable: true };+};++const isContentModePropForInstance = ({+ capabilities,+ instance,+ prop,+}: {+ capabilities: ContentModeCapabilities;+ instance: Instance;+ prop: Prop;+}) => getContentModePropEligibility({ capabilities, instance, prop }).editable;const contentModeNonCopyablePropTypes = new Set<Prop["type"]>(["resource",@@ -354,6 +470,10 @@ export const getContentModeCapabilities = ({contentRootIds,instances,});+ const frontmatterTargets = getContentModeFrontmatterBoundTargets({+ instances,+ props,+ });const capabilities = {editablePropIds,editableInstanceIds,@@ -366,6 +486,8 @@ export const getContentModeCapabilities = ({styles,breakpoints,contentRootIds,+ frontmatterBoundPropIds: frontmatterTargets.propIds,+ frontmatterBoundTextInstanceIds: frontmatterTargets.textInstanceIds,};for (const prop of props.values()) {const instance = instances.get(prop.instanceId);@@ -390,7 +512,7 @@ const isContentModePropPatchValue = ({value,}: {capabilities: ContentModeCapabilities;- editableInstanceIds: Set<Instance["id"]>;+ editableInstanceIds: ReadonlySet<Instance["id"]>;expectedPropId: Prop["id"];value: unknown;}) => {@@ -1544,7 +1666,14 @@ export const applyContentModeTransaction = ({contentRootIds: transactionCapabilities.contentRootIds,instances: transactionCapabilities.instances,});+ const frontmatterTargets = getContentModeFrontmatterBoundTargets({+ instances: transactionCapabilities.instances,+ props: transactionCapabilities.props,+ });transactionCapabilities.editableInstanceIds = context.editableInstanceIds;+ transactionCapabilities.frontmatterBoundPropIds = frontmatterTargets.propIds;+ transactionCapabilities.frontmatterBoundTextInstanceIds =+ frontmatterTargets.textInstanceIds;for (const change of transaction.payload) {if (change.namespace !== "styleSources") {diff --git a/packages/project-build/src/runtime/context.ts b/packages/project-build/src/runtime/context.tsindex bf10251f6f..391692bc57 100644--- a/packages/project-build/src/runtime/context.ts+++ b/packages/project-build/src/runtime/context.ts@@ -1,10 +1,13 @@import { nanoid } from "nanoid";+import type { ContentBlockApplication } from "./content-block-application";export type BuilderRuntimeContext = {createId: () => string;projectId?: string;projectVersion?: number;allowLegacyContentModelWarnings?: boolean;+ contentBlockApplication?: ContentBlockApplication;+ dryRun?: boolean;};export const builderRuntimeContext: BuilderRuntimeContext = {diff --git a/packages/project-build/src/runtime/cutover.ts b/packages/project-build/src/runtime/cutover.tsindex 0271e18df1..65fa392ec7 100644--- a/packages/project-build/src/runtime/cutover.ts+++ b/packages/project-build/src/runtime/cutover.ts@@ -135,6 +135,7 @@ export const builderRuntimeCutoverManifests = ["instances.insertComponent","instances.insertCollection","instances.insertFragment",+ "instances.insertMdxText","slots.attach","slots.extract",] as const,@@ -146,6 +147,23 @@ export const builderRuntimeCutoverManifests = ["Builder components panel",] as const,},+ {+ family: "content-block-source-operations",+ operationIds: [+ "contentBlocks.inspectSource",+ "contentBlocks.connectSource",+ "contentBlocks.switchSource",+ "contentBlocks.disconnectSource",+ "contentBlocks.editSource",+ "contentBlocks.updateFrontmatter",+ "contentBlocks.reloadSource",+ "contentBlocks.migrateTemplateReferences",+ ] as const,+ callers: [+ "Builder Content Block settings",+ "MCP/CLI Content Block authoring",+ ] as const,+ },{family: "runtime-ui-integration",operationIds: ["runtimeUi.integrate"] as const,diff --git a/packages/project-build/src/runtime/data-formats/instance-transfer.test.ts b/packages/project-build/src/runtime/data-formats/instance-transfer.test.tsindex 001f44484a..9ce24218b6 100644--- a/packages/project-build/src/runtime/data-formats/instance-transfer.test.ts+++ b/packages/project-build/src/runtime/data-formats/instance-transfer.test.ts@@ -47,6 +47,7 @@ test("accepts optional source origin metadata", () => {JSON.stringify({"@webstudio/instance/v0.1": {sourceOrigin: "https://source.example.com",+ assetPaths: { image: "media/hero.png" },instanceSelector: ["box", "body"],...fragment,},@@ -57,6 +58,9 @@ test("accepts optional source origin metadata", () => {owned: true,valid: true,type: "single-root",- data: { sourceOrigin: "https://source.example.com" },+ data: {+ sourceOrigin: "https://source.example.com",+ assetPaths: { image: "media/hero.png" },+ },});});diff --git a/packages/project-build/src/runtime/data-formats/instance-transfer.ts b/packages/project-build/src/runtime/data-formats/instance-transfer.tsindex b8290c9e1a..5c9f1a4a4b 100644--- a/packages/project-build/src/runtime/data-formats/instance-transfer.ts+++ b/packages/project-build/src/runtime/data-formats/instance-transfer.ts@@ -7,11 +7,13 @@ export const instancesTransferDataVersion = "@webstudio/instances/v0.1";export const instanceTransferData = webstudioFragment.extend({sourceOrigin: z.string().url().optional(),+ assetPaths: z.record(z.string(), z.string()).optional(),instanceSelector: z.array(z.string()),});export const instancesTransferData = z.object({sourceOrigin: z.string().url().optional(),+ assetPaths: z.record(z.string(), z.string()).optional(),rootInstanceIds: z.array(z.string()),fragment: webstudioFragment,});diff --git a/packages/project-build/src/runtime/data-formats/page-transfer.test.ts b/packages/project-build/src/runtime/data-formats/page-transfer.test.tsindex e3297d6c24..cc30bb4c18 100644--- a/packages/project-build/src/runtime/data-formats/page-transfer.test.ts+++ b/packages/project-build/src/runtime/data-formats/page-transfer.test.ts@@ -63,12 +63,13 @@ test("validates page transfer data", () => {});});-test("accepts optional source origin metadata", () => {+test("accepts optional source Asset metadata", () => {const result = parsePageTransferData(JSON.stringify({"@webstudio/page/v0.1": {...pageTransferItem,sourceOrigin: "https://source.example.com",+ assetPaths: { image: "media/hero.png" },},}));@@ -79,6 +80,7 @@ test("accepts optional source origin metadata", () => {data: {type: "page",sourceOrigin: "https://source.example.com",+ assetPaths: { image: "media/hero.png" },},});});diff --git a/packages/project-build/src/runtime/data-formats/page-transfer.ts b/packages/project-build/src/runtime/data-formats/page-transfer.tsindex 018fe1d6da..edb05c8151 100644--- a/packages/project-build/src/runtime/data-formats/page-transfer.ts+++ b/packages/project-build/src/runtime/data-formats/page-transfer.ts@@ -81,7 +81,10 @@ export const pageTransferItemInput = z.union([]);const pageClipboardTransferItemInput = pageTransferItemInput.and(- z.object({ sourceOrigin: z.string().url().optional() })+ z.object({+ sourceOrigin: z.string().url().optional(),+ assetPaths: z.record(z.string(), z.string()).optional(),+ }));export const pageTransferDataVersion = "@webstudio/page/v0.1";diff --git a/packages/project-build/src/runtime/data.test.tsx b/packages/project-build/src/runtime/data.test.tsxindex f2c63f64e5..d4024522a8 100644--- a/packages/project-build/src/runtime/data.test.tsx+++ b/packages/project-build/src/runtime/data.test.tsx@@ -1138,7 +1138,7 @@ test("restore tree variables in children", () => {const [_bodyVariableId, boxVariableId] = data.dataSources.keys();const boxIdentifier = encodeDataVariableId(boxVariableId);expect(data.instances.get("textId")?.children).toEqual([- { type: "expression", value: boxIdentifier },+ { type: "expression", value: boxIdentifier, mode: "read" },]);});@@ -1230,7 +1230,7 @@ test("rebind tree variables in props and children", () => {}),]);expect(data.instances.get("textId")?.children).toEqual([- { type: "expression", value: boxIdentifier },+ { type: "expression", value: boxIdentifier, mode: "read" },]);});@@ -1256,7 +1256,7 @@ test("preserve nested variables with the same name when rebind", () => {const [_bodyVariableId, textVariableId] = data.dataSources.keys();const textIdentifier = encodeDataVariableId(textVariableId);expect(data.instances.get("textId")?.children).toEqual([- { type: "expression", value: textIdentifier },+ { type: "expression", value: textIdentifier, mode: "read" },]);});@@ -1397,7 +1397,7 @@ test("rebind global variables in resources", () => {const [globalVariableId] = data.dataSources.keys();const globalIdentifier = encodeDataVariableId(globalVariableId);expect(data.instances.get("textId")?.children).toEqual([- { type: "expression", value: globalIdentifier },+ { type: "expression", value: globalIdentifier, mode: "read" },]);});@@ -1421,7 +1421,7 @@ test("preserve other variables when rebind", () => {const [_globalVariableId, textVariableId] = data.dataSources.keys();const textIdentifier = encodeDataVariableId(textVariableId);expect(data.instances.get("textId")?.children).toEqual([- { type: "expression", value: textIdentifier },+ { type: "expression", value: textIdentifier, mode: "read" },]);});@@ -1442,7 +1442,7 @@ test("prevent rebinding tree variables from slots", () => {...data,});expect(data.instances.get("boxId")?.children).toEqual([- { type: "expression", value: "myVariable" },+ { type: "expression", value: "myVariable", mode: "read" },]);});@@ -1496,7 +1496,11 @@ test("prevent rebinding with nested collection item", () => {}),]);expect(data.instances.get("divId")?.children).toEqual([- { type: "expression", value: encodeDataVariableId(nestedCollectionItemId) },+ {+ type: "expression",+ value: encodeDataVariableId(nestedCollectionItemId),+ mode: "read",+ },]);});@@ -1525,7 +1529,7 @@ test("delete variable and unset it in expressions", () => {}),]);expect(data.instances.get("boxId")?.children).toEqual([- { type: "expression", value: "bodyVariable" },+ { type: "expression", value: "bodyVariable", mode: "read" },]);});@@ -1627,7 +1631,11 @@ test("delete data variable payload reuses mutable cleanup semantics", () => {},]);expect(data.instances.get("boxId")?.children).toEqual([- { type: "expression", value: encodeDataVariableId(bodyVariableId) },+ {+ type: "expression",+ value: encodeDataVariableId(bodyVariableId),+ mode: "read",+ },]);});@@ -1698,7 +1706,7 @@ test("rebind expressions with parent variable when delete variable on child", ()deleteVariableMutable(data, boxVariableId);const bodyIdentifier = encodeDataVariableId(bodyVariableId);expect(data.instances.get("textId")?.children).toEqual([- { type: "expression", value: bodyIdentifier },+ { type: "expression", value: bodyIdentifier, mode: "read" },]);});@@ -1723,7 +1731,7 @@ test("prevent rebinding with variables outside of slot content scope", () => {const [_bodyVariableId, boxVariableId] = data.dataSources.keys();deleteVariableMutable(data, boxVariableId);expect(data.instances.get("textId")?.children).toEqual([- { type: "expression", value: "myVariable" },+ { type: "expression", value: "myVariable", mode: "read" },]);});@@ -1756,10 +1764,10 @@ test("unset global variables on all pages when delete", () => {const [globalVariableId] = data.dataSources.keys();deleteVariableMutable(data, globalVariableId);expect(data.instances.get("homeTextId")?.children).toEqual([- { type: "expression", value: "globalVariable" },+ { type: "expression", value: "globalVariable", mode: "read" },]);expect(data.instances.get("aboutTextId")?.children).toEqual([- { type: "expression", value: "globalVariable" },+ { type: "expression", value: "globalVariable", mode: "read" },]);});@@ -1837,7 +1845,7 @@ test("unset global variables in slots when delete", () => {const [globalVariableId] = data.dataSources.keys();deleteVariableMutable(data, globalVariableId);expect(data.instances.get("textId")?.children).toEqual([- { type: "expression", value: "globalVariable" },+ { type: "expression", value: "globalVariable", mode: "read" },]);});diff --git a/packages/project-build/src/runtime/data.ts b/packages/project-build/src/runtime/data.tsindex 848c342f1f..a121da9081 100644--- a/packages/project-build/src/runtime/data.ts+++ b/packages/project-build/src/runtime/data.ts@@ -480,7 +480,7 @@ export const replaceDataSourcesInExpression = (export const computeExpression = (expression: string,- variables: Map<DataSource["name"], unknown>+ variables: ReadonlyMap<DataSource["name"], unknown>) => {try {const proxiedVariables = new Map<DataSource["name"], unknown>();@@ -505,6 +505,14 @@ export const computeExpression = (}};+export const computeStringExpression = (+ expression: string,+ variables: ReadonlyMap<DataSource["name"], unknown>+) => {+ const value = computeExpression(expression, variables);+ return typeof value === "string" && value !== "" ? value : undefined;+};+export const computeExpressionWithinScope = (expression: string,scope: Record<string, unknown>diff --git a/packages/project-build/src/runtime/expression-validation.ts b/packages/project-build/src/runtime/expression-validation.tsindex 6557d49d7f..445cc11171 100644--- a/packages/project-build/src/runtime/expression-validation.ts+++ b/packages/project-build/src/runtime/expression-validation.ts@@ -12,6 +12,9 @@ export const getExpressionErrorMessages = (export const getExpressionErrors = (expression: string) =>getExpressionErrorMessages({ expression });+export const unsupportedReadwriteExpressionError =+ "Read-write expressions require a connected Content Block document frontmatter path";+export const addExpressionValidationIssues = (context: z.RefinementCtx,errors: readonly string[],diff --git a/packages/project-build/src/runtime/fragment.test.tsx b/packages/project-build/src/runtime/fragment.test.tsxindex 891b065ae1..90c0c4c548 100644--- a/packages/project-build/src/runtime/fragment.test.tsx+++ b/packages/project-build/src/runtime/fragment.test.tsx@@ -264,6 +264,31 @@ test("prevents pasting a portal fragment into one of its preserved children", ()).toEqual({ parentSelector: ["body"], position: "end" });});+test("includes assets referenced by copied variable values", () => {+ const data = createStub(<$.Box ws:id="boxId" />);+ data.assets.set("post", {+ id: "post",+ projectId: "source-project",+ type: "file",+ format: "mdx",+ name: "post.mdx",+ size: 1,+ createdAt: "2026-01-01T00:00:00.000Z",+ meta: {},+ });+ data.dataSources.set("items", {+ id: "items",+ scopeInstanceId: "boxId",+ type: "variable",+ name: "items",+ value: { type: "json", value: [{ source: "post" }] },+ });++ expect(extractWebstudioFragment(data, "boxId").assets).toEqual([+ data.assets.get("post"),+ ]);+});+const insertStyles = ({data,breakpointId,@@ -395,6 +420,30 @@ test("preserves legacy HtmlEmbed code when copying internal fragments", () => {);});+test("moves legacy Code Text properties into copied text content", () => {+ const data = renderData(<$.Body ws:id="bodyId" />);+ const fragment = renderTemplate(<$.CodeText code="const answer = 42;" />);++ insertWebstudioFragmentCopy({+ data,+ fragment,+ availableVariables: [],+ projectId: "",+ });++ const codeText = Array.from(data.instances.values()).find(+ (instance) => instance.component === "CodeText"+ );+ expect(codeText?.children).toEqual([+ { type: "text", value: "const answer = 42;" },+ ]);+ expect(+ Array.from(data.props.values()).find(+ (prop) => prop.instanceId === codeText?.id && prop.name === "code"+ )+ ).toBeUndefined();+});+test("insert instances with multiple roots", () => {const data = renderData(<$.Body ws:id="bodyId"></$.Body>);const fragment = renderTemplate(@@ -721,7 +770,13 @@ describe("variables", () => {expect(fragment.instances).toEqual([expect.objectContaining({id: "boxId",- children: [{ type: "expression", value: "Body$32$Variable" }],+ children: [+ {+ type: "expression",+ value: "Body$32$Variable",+ mode: "read",+ },+ ],}),]);});@@ -853,7 +908,7 @@ describe("variables", () => {const newInstanceId = Array.from(data.instances.keys()).at(-1) ?? "";expect(newInstanceId).not.toEqual("boxId");expect(data.instances.get(newInstanceId)?.children).toEqual([- { type: "expression", value: "$ws$dataSource$0" },+ { type: "expression", value: "$ws$dataSource$0", mode: "read" },]);expect(Array.from(data.props.values()).filter(diff --git a/packages/project-build/src/runtime/fragment.ts b/packages/project-build/src/runtime/fragment.tsindex 01dd9e523d..a07540e8e2 100644--- a/packages/project-build/src/runtime/fragment.ts+++ b/packages/project-build/src/runtime/fragment.ts@@ -2,6 +2,7 @@// Webstudio fragments. Put serialization-style instance subtree cloning and// fragment asset/style/data remapping here, not live tree placement decisions.import { nanoid } from "nanoid";+import { migrateCodeTextContentMutable } from "@webstudio-is/project-migrations";import {type Asset,type Breakpoints,@@ -19,6 +20,7 @@ import {findPageByIdOrPath,findTreeInstanceIds,findTreeInstanceIdsExcludingSlotDescendants,+ getStyleDeclKey,getHomePage,portalComponent,webstudioFragment,@@ -51,6 +53,7 @@ import {collectFontFamiliesFromStyleValue,traverseStyleValue,} from "./style-utils";+import { countDataSourceAssetReferences } from "./assets";export type ContentModeCopyableProp = (input: {prop: Prop;@@ -115,6 +118,22 @@ const mergeUniqueByJson = <Item>(items: Item[]) =>new Map(items.map((item) => [JSON.stringify(item), item])).values());+export const createWebstudioDataFromFragment = (+ fragment: WebstudioFragment+): Omit<WebstudioData, "pages"> => ({+ instances: new Map(fragment.instances.map((item) => [item.id, item])),+ props: new Map(fragment.props.map((item) => [item.id, item])),+ assets: new Map(fragment.assets.map((item) => [item.id, item])),+ dataSources: new Map(fragment.dataSources.map((item) => [item.id, item])),+ resources: new Map(fragment.resources.map((item) => [item.id, item])),+ breakpoints: new Map(fragment.breakpoints.map((item) => [item.id, item])),+ styleSourceSelections: new Map(+ fragment.styleSourceSelections.map((item) => [item.instanceId, item])+ ),+ styleSources: new Map(fragment.styleSources.map((item) => [item.id, item])),+ styles: new Map(fragment.styles.map((item) => [getStyleDeclKey(item), item])),+});+export const mergeWebstudioFragments = (rootInstanceIds: Instance["id"][],fragments: WebstudioFragment[]@@ -359,6 +378,11 @@ export const extractWebstudioFragment = (if (dataSource.type === "resource") {fragmentResourceIds.add(dataSource.resourceId);}+ for (const assetId of assets.keys()) {+ if (countDataSourceAssetReferences(dataSource, assetId) > 0) {+ fragmentAssetIds.add(assetId);+ }+ }} else {unsetNameById.set(dataSource.id, dataSource.name);}@@ -952,6 +976,7 @@ export const insertWebstudioFragmentCopy = ({});}+ migrateCodeTextContentMutable({ instances, props });return { ...newDataIds, didMergeBreakpointsDueToLimit };};diff --git a/packages/project-build/src/runtime/html-attribute-utils.ts b/packages/project-build/src/runtime/html-attribute-utils.tsnew file mode 100644index 0000000000..158700b678--- /dev/null+++ b/packages/project-build/src/runtime/html-attribute-utils.ts@@ -0,0 +1,49 @@+import { ariaAttributes, attributesByTag } from "@webstudio-is/html-data";++type HtmlAttribute = (typeof ariaAttributes)[number];++export type HtmlAttributeType = "string" | "boolean" | "number";++const toAttributeType = (attribute: HtmlAttribute): HtmlAttributeType => {+ if (+ attribute.type === "string" ||+ attribute.type === "select" ||+ attribute.type === "url"+ ) {+ return "string";+ }+ return attribute.type;+};++export const getHtmlAttributeType = ({+ tag,+ name,+}: {+ tag: string;+ name: string;+}): HtmlAttributeType | undefined => {+ const attribute =+ attributesByTag[tag]?.find((candidate) => candidate.name === name) ??+ attributesByTag["*"]?.find((candidate) => candidate.name === name) ??+ ariaAttributes.find((candidate) => candidate.name === name);+ return attribute === undefined ? undefined : toAttributeType(attribute);+};++export const getHtmlAttributeTypes = () => {+ const attributeTypes = new Map<string, HtmlAttributeType>();+ for (const attribute of ariaAttributes) {+ attributeTypes.set(attribute.name, toAttributeType(attribute));+ }+ for (const attribute of attributesByTag["*"] ?? []) {+ attributeTypes.set(attribute.name, toAttributeType(attribute));+ }+ for (const [tag, attributes] of Object.entries(attributesByTag)) {+ for (const attribute of attributes ?? []) {+ attributeTypes.set(+ `${tag}:${attribute.name}`,+ toAttributeType(attribute)+ );+ }+ }+ return attributeTypes;+};diff --git a/packages/project-build/src/runtime/html.ts b/packages/project-build/src/runtime/html.tsindex 7f9075c505..b3fdb36e2c 100644--- a/packages/project-build/src/runtime/html.ts+++ b/packages/project-build/src/runtime/html.ts@@ -14,7 +14,6 @@ import {type StyleSource,type StyleSourceSelection,} from "@webstudio-is/sdk";-import { ariaAttributes, attributesByTag } from "@webstudio-is/html-data";import {camelCaseProperty,parseCss,@@ -33,50 +32,13 @@ import {import { ROOT_INSTANCE_ID } from "@webstudio-is/sdk";import * as csstree from "css-tree";import { titleCase } from "title-case";+import { getHtmlAttributeTypes } from "./html-attribute-utils";type ElementNode = DefaultTreeAdapterMap["element"];const spaceRegex = /^\s*$/;const wsAttributePrefix = "data-ws-";-const getAttributeType = (- attribute: (typeof ariaAttributes)[number]-): "string" | "boolean" | "number" => {- if (- attribute.type === "string" ||- attribute.type === "select" ||- attribute.type === "url"- ) {- return "string";- }- if (attribute.type === "number" || attribute.type === "boolean") {- return attribute.type;- }- attribute.type satisfies never;- throw Error("Unknown type");-};--const getAttributeTypes = () => {- const attributeTypes = new Map<string, "string" | "number" | "boolean">();- for (const attribute of ariaAttributes) {- attributeTypes.set(attribute.name, getAttributeType(attribute));- }- for (const attribute of attributesByTag["*"] ?? []) {- attributeTypes.set(attribute.name, getAttributeType(attribute));- }- for (const [tag, attributes] of Object.entries(attributesByTag)) {- if (attributes) {- for (const attribute of attributes) {- attributeTypes.set(- `${tag}:${attribute.name}`,- getAttributeType(attribute)- );- }- }- }- return attributeTypes;-};-const findContentTags = (element: ElementNode, tags = new Set<string>()) => {for (const childNode of element.childNodes) {if (defaultTreeAdapter.isElementNode(childNode)) {@@ -462,7 +424,7 @@ const resolveOverlappingBreakpoints = (breakpoints: Breakpoint[]) => {export const generateFragmentFromHtml = (html: string): WebstudioFragment & { skippedSelectors: string[] } => {- const attributeTypes = getAttributeTypes();+ const attributeTypes = getHtmlAttributeTypes();const instances = new Map<Instance["id"], Instance>();const styleSourceSelections: StyleSourceSelection[] = [];const styleSources: StyleSource[] = [];diff --git a/packages/project-build/src/runtime/instances.test.ts b/packages/project-build/src/runtime/instances.test.tsindex 97ac87a28c..59e251fcda 100644--- a/packages/project-build/src/runtime/instances.test.ts+++ b/packages/project-build/src/runtime/instances.test.ts@@ -1,5 +1,9 @@import { describe, expect, test } from "vitest";import {+ blockComponent,+ blockTemplateComponent,+ contentBlockSourceProp,+ encodeDataSourceVariable,encodeDataVariableId,type DataSource,elementComponent,@@ -64,6 +68,51 @@ import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";const runtimeContext = { createId: () => "generated" };+test("rejects duplicate names and confirms source-backed template deletion", () => {+ const block = createInstance("block", blockComponent, [+ { type: "id", value: "templates" },+ ]);+ const templates = createInstance("templates", blockTemplateComponent, [+ { type: "id", value: "hero" },+ { type: "id", value: "card" },+ ]);+ const hero = { ...createInstance("hero", "Box"), label: "Hero" };+ const card = createInstance("card", "Box");+ const source: Prop = {+ id: "src",+ instanceId: block.id,+ name: contentBlockSourceProp,+ type: "asset",+ value: "article",+ };+ const instances = new Map([+ [block.id, block],+ [templates.id, templates],+ [hero.id, hero],+ [card.id, card],+ ]);++ expect(() =>+ setInstanceLabel(+ { instances, props: new Map([[source.id, source]]) },+ { instanceId: card.id, label: "Hero" }+ )+ ).toThrow("Template name must be unique");+ expect(() =>+ deleteInstances(+ {+ instances,+ props: new Map([[source.id, source]]),+ dataSources: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ },+ { instanceIds: [card.id] }+ )+ ).toThrow("Template name change requires confirmation");+});+test("rejects conflicting page selectors for text replacement", () => {expect(replaceTextInput.safeParse({@@ -374,9 +423,10 @@ test("creates instance clone payload with child references and props", () => {{id: "prop",instanceId: "source",- name: "className",- type: "string",- value: "card",+ name: "title",+ type: "expression",+ value: "document.frontmatter.title",+ mode: "readwrite",},];const ids = ["source-copy", "child-copy", "prop-copy"];@@ -388,6 +438,11 @@ test("creates instance clone payload with child references and props", () => {createCloneInstance("source", [{ type: "id", value: "child" },{ type: "text", value: "Text" },+ {+ type: "expression",+ value: "document.frontmatter.title",+ mode: "readwrite",+ },]),],["child", createCloneInstance("child")],@@ -416,6 +471,11 @@ test("creates instance clone payload with child references and props", () => {value: createCloneInstance("source-copy", [{ type: "id", value: "child-copy" },{ type: "text", value: "Text" },+ {+ type: "expression",+ value: "document.frontmatter.title",+ mode: "readwrite",+ },]),},{@@ -509,6 +569,7 @@ describe("text content utils", () => {).toEqual({type: "expression",value: "title",+ mode: "read",});});@@ -600,7 +661,9 @@ describe("text content utils", () => {setTextContentMutable(instance, "expression", "value");- expect(instance.children).toEqual([{ type: "expression", value: "value" }]);+ expect(instance.children).toEqual([+ { type: "expression", value: "value", mode: "read" },+ ]);});test("creates text content update payload", () => {@@ -879,6 +942,96 @@ describe("text content utils", () => {);});+ test("preserves explicit readwrite mode when setting expression content", () => {+ const instance = createInstance("instance", []);+ const block = createInstance("block", [{ type: "id", value: instance.id }]);+ block.component = blockComponent;+ const result = setTextContent(+ {+ instances: new Map([+ [block.id, block],+ [instance.id, instance],+ ]),+ props: new Map<string, Prop>([+ [+ "source",+ {+ id: "source",+ instanceId: block.id,+ name: "src",+ type: "asset",+ value: "article",+ },+ ],+ [+ "document",+ {+ id: "document",+ instanceId: block.id,+ name: "document",+ type: "parameter",+ value: "document",+ },+ ],+ ]),+ },+ {+ operation: "set",+ instanceId: "instance",+ text: `${encodeDataSourceVariable("document")}.frontmatter.title`,+ mode: "expression",+ expressionBindingMode: "readwrite",+ }+ );++ expect(result.payload).toEqual(+ createTextContentSetPayload({+ instanceId: "instance",+ child: {+ type: "expression",+ value: `${encodeDataSourceVariable("document")}.frontmatter.title`,+ mode: "readwrite",+ },+ })+ );+ });++ test("rejects readwrite expression content outside a connected Content Block document", () => {+ expect(() =>+ setTextContent(+ {+ instances: new Map([["instance", createInstance("instance", [])]]),+ },+ {+ operation: "set",+ instanceId: "instance",+ text: "document.frontmatter.title",+ mode: "expression",+ expressionBindingMode: "readwrite",+ }+ )+ ).toThrow(+ "Read-write expressions require a connected Content Block document frontmatter path"+ );+ });++ test("rejects readwrite mode for derived expression content", () => {+ expect(() =>+ setTextContent(+ {+ instances: new Map([["instance", createInstance("instance", [])]]),+ },+ {+ operation: "set",+ instanceId: "instance",+ text: 'document.frontmatter.title + "!"',+ mode: "expression",+ expressionBindingMode: "readwrite",+ }+ )+ ).toThrow("Read-write expressions must be a direct static path");+ });+test("resets text content", () => {const result = setTextContent({@@ -1344,6 +1497,50 @@ describe("convertInstance", () => {]);});+ test("rejects prop aliases that collide when converting to an element", () => {+ expect(() =>+ convertInstance(+ {+ instances: new Map([+ [+ "body",+ createInstance("body", "Body", [{ type: "id", value: "box" }]),+ ],+ ["box", createInstance("box", "Box")],+ ]),+ props: new Map([+ [+ "class",+ {+ id: "class",+ instanceId: "box",+ name: "class",+ type: "string",+ value: "one",+ },+ ],+ [+ "className",+ {+ id: "className",+ instanceId: "box",+ name: "className",+ type: "string",+ value: "two",+ },+ ],+ ]),+ },+ {+ instanceSelector: ["box", "body"],+ component: elementComponent,+ tag: "div",+ },+ runtimeContext+ )+ ).toThrow('Multiple properties map to "class"');+ });+test("converts selected instance inside shared Slot content", () => {const result = convertInstance({diff --git a/packages/project-build/src/runtime/instances.ts b/packages/project-build/src/runtime/instances.tsindex a013bf9211..ddafb685df 100644--- a/packages/project-build/src/runtime/instances.ts+++ b/packages/project-build/src/runtime/instances.ts@@ -1,11 +1,18 @@import {+ blockTemplateComponent,elementComponent,+ findChildReferenceIndex,+ findParentInstanceReference,+ findWritableContentBlockDocumentBindings,findTreeInstanceIds,getHtmlTagsFromProps,+ getExpressionBindingError,+ expressionBindingMode,getStyleDeclKey,instance as instanceInput,tags,type DataSource,+ type ExpressionBindingMode,type Instance,type Instances,type Prop,@@ -16,6 +23,9 @@ import {type WebstudioData,type WsComponentMeta,} from "@webstudio-is/sdk";++// Preserve the runtime API while the shared tree utilities are owned by SDK.+export { findChildReferenceIndex, findParentInstanceReference };import {compactBuilderPatchPayload,type BuilderPatchChange,@@ -33,7 +43,10 @@ import {throwBuilderValidationError,} from "./errors";import { replaceTextValue } from "./text-replacement";-import { getExpressionErrors } from "./expression-validation";+import {+ getExpressionErrors,+ unsupportedReadwriteExpressionError,+} from "./expression-validation";import { createRuntimeMutation } from "./mutation";import { findSerializedPageByInput, getSerializedPages } from "./pages";import { validatePageSelector } from "./page-selector";@@ -69,9 +82,79 @@ import {serializeStyleDeclarations,} from "./style-utils";import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";-import { reactPropsToStandardAttributes } from "@webstudio-is/react-sdk/standard-attributes";+import { mapAttributeNames } from "@webstudio-is/content-engine/jsx-attributes";import equal from "fast-deep-equal";import { z } from "zod";+import {+ assignUniqueBlockTemplateNamesMutable,+ type BlockTemplateNameConfirmation,+ findBlockTemplateNameCollision,+ getBlockTemplateNameConfirmation,+} from "./block";++const throwDuplicateBlockTemplateName = ({+ name,+ path,+}: {+ name: string;+ path: "component" | "label" | "tag";+}): never =>+ throwBuilderValidationError("Template name must be unique", [+ {+ code: "duplicate_template_name",+ path: [path],+ message: `Template name "${name}" is already in use.`,+ constraint: "unique_within:block_templates",+ example: `${name} 2`,+ },+ ]);++export const blockTemplateNameConfirmationInput = z+ .object({+ action: z.enum(["rename", "delete"]),+ templates: z.array(+ z.object({+ instanceId: z.string(),+ oldName: z.string(),+ newName: z.string().optional(),+ })+ ),+ })+ .describe(+ "Retry with the exact confirmation example returned by template_name_change_requires_confirmation after user approval."+ );++export const requireBlockTemplateNameConfirmation = ({+ required,+ confirm,+ path,+}: {+ required: BlockTemplateNameConfirmation | undefined;+ confirm: BlockTemplateNameConfirmation | undefined;+ path:+ | "component"+ | "instanceIds"+ | "instanceSelector"+ | "label"+ | "mode"+ | "tag";+}) => {+ if (required === undefined || equal(required, confirm)) {+ return;+ }+ throwBuilderValidationError("Template name change requires confirmation", [+ {+ code: "template_name_change_requires_confirmation",+ path: [path],+ message:+ required.action === "delete"+ ? "Deleting this template may disconnect references in MDX files."+ : "Renaming this template may disconnect references in MDX files.",+ constraint: "requires_confirmation:template_name_references",+ example: required,+ },+ ]);+};export const insertIndexInput = z.number().int().nonnegative();const instanceEndPositionInput = z.literal("end");@@ -127,10 +210,12 @@ export const cloneInstanceInput = z.object({export const deleteInstancesInput = z.object({instanceIds: z.array(z.string()).min(1),+ templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),});export const deleteInstanceBySelectorInput = z.object({instanceSelector: z.array(z.string()).min(2),+ templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),});export const fillGridInput = z.object({@@ -160,6 +245,7 @@ export const convertInstanceInput = z.object({component: instanceInput.shape.component,tag: z.string().min(1).optional(),currentTag: z.string().min(1).optional(),+ templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),});export const unwrapInstanceInput = z.object({@@ -175,74 +261,125 @@ export const setInstanceTagInput = z.object({instanceId: z.string(),tag: z.string(),legacyPropName: z.string().optional(),+ templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),});export const setInstanceLabelInput = z.object({instanceId: z.string(),label: z.string(),+ templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),});-export const updateTextInstanceInput = z.object({- instanceId: z- .string()- .describe("Instance id containing the child to update."),- childIndex: z- .number()- .int()- .nonnegative()- .describe("Zero-based child index from list-texts or inspect-instance."),- text: z- .string()- .describe(- "Replacement visible text when mode is text, or one Webstudio JavaScript expression when mode is expression. Read webstudio://project/expressions for syntax and scope rules."- ),- mode: z- .enum(["text", "expression"])- .optional()- .describe(- 'Optional expected child type. Use "text" for plain visible text and "expression" for JavaScript expression children. There is no "replace" mode.'- ),-});--export const setTextContentInput = z.discriminatedUnion("operation", [- z.object({- operation: z.literal("set"),- instanceId: z.string().describe("Instance id to receive text content."),+export const updateTextInstanceInput = z+ .object({+ instanceId: z+ .string()+ .describe("Instance id containing the child to update."),+ childIndex: z+ .number()+ .int()+ .nonnegative()+ .describe("Zero-based child index from list-texts or inspect-instance."),text: z.string().describe(- "Visible text, or one Webstudio JavaScript expression when mode is expression. Read webstudio://project/expressions for syntax and scope rules."+ "Replacement visible text when mode is text, or one Webstudio JavaScript expression when mode is expression. Read webstudio://project/expressions for syntax and scope rules."),mode: z.enum(["text", "expression"])- .default("text")+ .optional().describe(- 'Use "text" for plain visible text and "expression" for JavaScript expression children.'+ 'Optional expected child type. Use "text" for plain visible text and "expression" for JavaScript expression children. There is no "replace" mode.'),- }),- z.object({- operation: z.literal("reset"),- instanceId: z.string().describe("Instance id to reset to no text content."),- }),- z.object({- operation: z.literal("inlineExpressions"),- instanceId: z- .string()- .describe("Instance id whose expression children will become text."),- replacements: z- .array(- z.object({- childIndex: z.number().int().nonnegative(),- expression: z.string(),- text: z.string(),- })- )- .min(1)- .describe(- "Evaluated text for every expression child. The index and original expression must match the current instance."- ),- }),-]);+ expressionBindingMode: expressionBindingMode.optional(),+ })+ .superRefine((input, context) => {+ if (+ input.mode !== "expression" &&+ input.expressionBindingMode !== undefined+ ) {+ context.addIssue({+ code: "custom",+ path: ["expressionBindingMode"],+ message: "Expression binding mode requires an expression child",+ });+ return;+ }+ if (input.mode === "expression") {+ const error = getExpressionBindingError({+ value: input.text,+ mode: input.expressionBindingMode,+ });+ if (error !== undefined) {+ context.addIssue({ code: "custom", path: ["text"], message: error });+ }+ }+ });++export const setTextContentInput = z+ .discriminatedUnion("operation", [+ z.object({+ operation: z.literal("set"),+ instanceId: z.string().describe("Instance id to receive text content."),+ text: z+ .string()+ .describe(+ "Visible text, or one Webstudio JavaScript expression when mode is expression. Read webstudio://project/expressions for syntax and scope rules."+ ),+ mode: z+ .enum(["text", "expression"])+ .default("text")+ .describe(+ 'Use "text" for plain visible text and "expression" for JavaScript expression children.'+ ),+ expressionBindingMode: expressionBindingMode.optional(),+ }),+ z.object({+ operation: z.literal("reset"),+ instanceId: z+ .string()+ .describe("Instance id to reset to no text content."),+ }),+ z.object({+ operation: z.literal("inlineExpressions"),+ instanceId: z+ .string()+ .describe("Instance id whose expression children will become text."),+ replacements: z+ .array(+ z.object({+ childIndex: z.number().int().nonnegative(),+ expression: z.string(),+ text: z.string(),+ })+ )+ .min(1)+ .describe(+ "Evaluated text for every expression child. The index and original expression must match the current instance."+ ),+ }),+ ])+ .superRefine((input, context) => {+ if (input.operation !== "set") {+ return;+ }+ const error = getExpressionBindingError({+ value: input.text,+ mode: input.expressionBindingMode,+ });+ if (+ input.mode !== "expression" &&+ input.expressionBindingMode !== undefined+ ) {+ context.addIssue({+ code: "custom",+ path: ["expressionBindingMode"],+ message: "Expression binding mode requires an expression child",+ });+ } else if (error !== undefined) {+ context.addIssue({ code: "custom", path: ["text"], message: error });+ }+ });export const updateTextTreeInput = z.object({rootInstanceId: z.string(),@@ -486,14 +623,6 @@ const getRequiredInstances = (return state.instances;};-export const findChildReferenceIndex = (- children: Instance["children"],- instanceId: Instance["id"]-) =>- children.findIndex(- (child) => child.type === "id" && child.value === instanceId- );-export const createInstanceChild = (instanceId: Instance["id"]) =>({ type: "id", value: instanceId }) as const;@@ -665,18 +794,6 @@ export const getSameParentAdjustedInsertIndex = ({requestedIndex: number;}) => (requestedIndex > currentIndex ? requestedIndex - 1 : requestedIndex);-export const findParentInstanceReference = (- instances: Instances,- instanceId: Instance["id"]-) => {- for (const instance of instances.values()) {- const childIndex = findChildReferenceIndex(instance.children, instanceId);- if (childIndex !== -1) {- return { instance, childIndex };- }- }-};-export const getInstanceDepths = (instances: Pick<Instances, "get" | "values">,rootInstanceIds?: Instance["id"][]@@ -1066,6 +1183,27 @@ export const createInstanceMovePatches = ({requestedIndex: requestedInsertIndex,}): requestedInsertIndex;+ if (+ parent.instance.id === nextParent.id &&+ insertIndex === parent.childIndex+ ) {+ continue;+ }+ if (parent.instance.id !== nextParent.id) {+ const previousLabel = instance.label;+ assignUniqueBlockTemplateNamesMutable({+ instanceIds: [instance.id],+ parent: nextParent,+ instances: mutableInstances,+ });+ if (instance.label !== previousLabel && instance.label !== undefined) {+ patches.push({+ op: previousLabel === undefined ? "add" : "replace",+ path: [instance.id, "label"],+ value: instance.label,+ });+ }+ }patches.push({op: "remove" as const,path: [parent.instance.id, "children", parent.childIndex] as [@@ -1459,6 +1597,15 @@ export const createInstanceClonePayload = ({if (clonedRootId === undefined) {return;}+ const instancesWithClones = new Map(instances);+ for (const [instanceId, instance] of clonedInstances) {+ instancesWithClones.set(instanceId, instance);+ }+ assignUniqueBlockTemplateNamesMutable({+ instanceIds: [clonedRootId],+ parent: targetParent,+ instances: instancesWithClones,+ });const propPatches = createPropClonePatches({nextIdById,props,@@ -1773,6 +1920,13 @@ const moveInstanceToParentMutable = (const [newParentId] = dropTarget.parentSelector;const newParent = data.instances.get(newParentId);const newChild = createInstanceChild(rootInstanceId);+ if (newParent !== undefined) {+ assignUniqueBlockTemplateNamesMutable({+ instanceIds: [rootInstanceId],+ parent: newParent,+ instances: data.instances,+ });+ }if (dropTarget.position === "end") {newParent?.children.push(newChild);} else {@@ -1954,6 +2108,11 @@ export const wrapInstance = (selectedItem.instance.id,wrapperInstanceId);+ assignUniqueBlockTemplateNamesMutable({+ instanceIds: [wrapperInstanceId],+ parent: parentInstance,+ instances: nextInstances,+ });const wrapperSelector = [wrapperInstanceId, ...parentItem.instanceSelector];const isSatisfying = isTreeSatisfyingContentModel({instances: nextInstances,@@ -2027,6 +2186,12 @@ export const wrapInstance = (createInstanceChild(wrapperInstanceId);nextInstances.set(parentInstanceId, nextParentInstance);nextInstances.set(wrapperInstanceId, wrapperInstance);+ assignUniqueBlockTemplateNamesMutable({+ instanceIds: [wrapperInstanceId],+ parent: nextParentInstance,+ replacedInstanceIds: [instanceId],+ instances: nextInstances,+ });const wrapperSelector = [wrapperInstanceId,...input.instanceSelector.slice(1),@@ -2251,6 +2416,13 @@ const unwrapInstanceMutable = ({parentInstance.children,selectedItem.instance.id);+ assignUniqueBlockTemplateNamesMutable({+ instanceIds: [selectedInstance.id],+ parent: grandparentInstance,+ replacedInstanceIds:+ parentInstance.children.length === 0 ? [parentInstance.id] : [],+ instances,+ });if (parentInstance.children.length === 0) {instances.delete(parentItem.instance.id);}@@ -2285,6 +2457,25 @@ const unwrapInstanceMutable = ({: { success: false, error: "Cannot unwrap instance" };};+const getStandardPropRenames = ({+ props,+ instanceId,+}: {+ props: Iterable<Prop>;+ instanceId: Instance["id"];+}) =>+ mapAttributeNames({+ attributes: Array.from(props)+ .filter((prop) => prop.instanceId === instanceId)+ .map((prop) => ({ ...prop, originalName: prop.name })),+ direction: "jsx-to-instance",+ acceptsHtmlAttributes: true,+ }).flatMap((prop) =>+ prop.name === prop.originalName+ ? []+ : [{ propId: prop.id, name: prop.name, propIdPrefix: prop.instanceId }]+ );+export const convertInstance = (state: Pick<BuilderState, "instances" | "props"> &Partial<FullInstanceMutationState>,@@ -2331,6 +2522,7 @@ export const convertInstance = ();const [selectedItem] = nextInstancePath;const selectedInstance = selectedItem.instance;+ const previousInstance = { ...selectedInstance };if (selectedInstance.component === "Slot" && input.component !== "Slot") {detachSharedSlotChildrenMutable({data: draft,@@ -2355,14 +2547,9 @@ export const convertInstance = (props: draft.props.values(),}).payload);- const renames = Array.from(draft.props.values()).flatMap((prop) => {- if (prop.instanceId !== selectedInstance.id) {- return [];- }- const name = reactPropsToStandardAttributes[prop.name];- return name === undefined- ? []- : [{ propId: prop.id, name, propIdPrefix: prop.instanceId }];+ const renames = getStandardPropRenames({+ props: draft.props.values(),+ instanceId: selectedInstance.id,});if (renames.length > 0) {applyBuilderPatchPayloadMutable(@@ -2379,6 +2566,17 @@ export const convertInstance = (nextInstance.tag = defaultTag;}}+ const collision = findBlockTemplateNameCollision({+ instance: previousInstance,+ nextInstance,+ instances: draft.instances,+ });+ if (collision !== undefined) {+ return throwDuplicateBlockTemplateName({+ name: collision.name,+ path: "component",+ });+ }const isSatisfying = isTreeSatisfyingContentModel({instances: draft.instances,props: draft.props,@@ -2391,6 +2589,15 @@ export const convertInstance = ("Converted tree violates content model");}+ requireBlockTemplateNameConfirmation({+ required: getBlockTemplateNameConfirmation({+ changes: [{ instance: previousInstance, nextInstance }],+ instances: draft.instances,+ props: draft.props.values(),+ }),+ confirm: input.templateNameConfirmation,+ path: "component",+ });});return createRuntimeMutation({payload,@@ -2450,14 +2657,9 @@ export const convertInstance = (props: state.props.values(),}).payload);- const renames = Array.from(state.props.values()).flatMap((prop) => {- if (prop.instanceId !== instanceId) {- return [];- }- const name = reactPropsToStandardAttributes[prop.name];- return name === undefined- ? []- : [{ propId: prop.id, name, propIdPrefix: prop.instanceId }];+ const renames = getStandardPropRenames({+ props: state.props.values(),+ instanceId,});if (renames.length > 0) {payload.push(@@ -2489,6 +2691,17 @@ export const convertInstance = (}}+ const collision = findBlockTemplateNameCollision({+ instance,+ nextInstance,+ instances,+ });+ if (collision !== undefined) {+ return throwDuplicateBlockTemplateName({+ name: collision.name,+ path: "component",+ });+ }const isSatisfying = canConvertInstance({instanceId,instanceSelector: input.instanceSelector,@@ -2505,6 +2718,15 @@ export const convertInstance = ("Converted tree violates content model");}+ requireBlockTemplateNameConfirmation({+ required: getBlockTemplateNameConfirmation({+ changes: [{ instance, nextInstance }],+ instances,+ props: state.props.values(),+ }),+ confirm: input.templateNameConfirmation,+ path: "component",+ });payload.push({ namespace: "instances", patches: instancePatches });return createRuntimeMutation({@@ -2714,6 +2936,18 @@ export const unwrapInstance = ();}nextInstances.set(grandparentInstanceId, nextGrandparentInstance);+ let nextSelectedInstance = selectedInstance;+ if (nextGrandparentInstance.component === blockTemplateComponent) {+ nextSelectedInstance = { ...selectedInstance };+ nextInstances.set(instanceId, nextSelectedInstance);+ assignUniqueBlockTemplateNamesMutable({+ instanceIds: [instanceId],+ parent: nextGrandparentInstance,+ replacedInstanceIds:+ nextParentInstance.children.length === 0 ? [parentInstanceId] : [],+ instances: nextInstances,+ });+ }const nextInstanceSelector = [instanceId, ...input.instanceSelector.slice(2)];const isSatisfying = isTreeSatisfyingContentModel({instances: nextInstances,@@ -2726,6 +2960,13 @@ export const unwrapInstance = (}const patches: BuilderPatchChange["patches"] = [];+ if (nextSelectedInstance.label !== selectedInstance.label) {+ patches.push({+ op: selectedInstance.label === undefined ? "add" : "replace",+ path: [instanceId, "label"],+ value: nextSelectedInstance.label,+ });+ }if (nextParentInstance.children.length === 0) {patches.push({ op: "remove", path: [parentInstanceId] });} else {@@ -2883,6 +3124,27 @@ export const setInstanceTag = (if (instance === undefined) {return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");}+ const nextInstance = { ...instance, tag: input.tag };+ const collision = findBlockTemplateNameCollision({+ instance,+ nextInstance,+ instances,+ });+ if (collision !== undefined) {+ return throwDuplicateBlockTemplateName({+ name: collision.name,+ path: "tag",+ });+ }+ requireBlockTemplateNameConfirmation({+ required: getBlockTemplateNameConfirmation({+ changes: [{ instance, nextInstance }],+ instances,+ props: state.props.values(),+ }),+ confirm: input.templateNameConfirmation,+ path: "tag",+ });const payload: BuilderPatchChange[] = [];if (input.legacyPropName !== undefined) {@@ -2920,7 +3182,7 @@ export const setInstanceTag = (};export const setInstanceLabel = (- state: Pick<BuilderState, "instances">,+ state: Pick<BuilderState, "instances"> & Partial<Pick<BuilderState, "props">>,input: z.infer<typeof setInstanceLabelInput>) => {const instances = getRequiredInstances(state);@@ -2940,6 +3202,36 @@ export const setInstanceLabel = (): [instance];+ const prospectiveInstances = new Map(instances);+ for (const targetInstance of targetInstances) {+ prospectiveInstances.set(targetInstance.id, { ...targetInstance, label });+ }+ for (const targetInstance of targetInstances) {+ const collision = findBlockTemplateNameCollision({+ instance: targetInstance,+ nextInstance: prospectiveInstances.get(targetInstance.id)!,+ instances: prospectiveInstances,+ });+ if (collision !== undefined) {+ return throwDuplicateBlockTemplateName({+ name: collision.name,+ path: "label",+ });+ }+ }+ requireBlockTemplateNameConfirmation({+ required: getBlockTemplateNameConfirmation({+ changes: targetInstances.map((targetInstance) => ({+ instance: targetInstance,+ nextInstance: prospectiveInstances.get(targetInstance.id),+ })),+ instances,+ props: state.props?.values() ?? [],+ }),+ confirm: input.templateNameConfirmation,+ path: "label",+ });+const patches: BuilderPatchChange["patches"] = [];for (const targetInstance of targetInstances) {if (targetInstance.label === label) {@@ -2995,6 +3287,18 @@ export const deleteInstances = (if (error?.type === "parent-not-found") {return throwBuilderRuntimeError("NOT_FOUND", "Parent instance not found");}+ requireBlockTemplateNameConfirmation({+ required: getBlockTemplateNameConfirmation({+ changes: input.instanceIds.flatMap((instanceId) => {+ const instance = mutationState.instances.get(instanceId);+ return instance === undefined ? [] : [{ instance }];+ }),+ instances: mutationState.instances,+ props: mutationState.props.values(),+ }),+ confirm: input.templateNameConfirmation,+ path: "instanceIds",+ });return createRuntimeMutation({payload,result: { instanceIds },@@ -3054,6 +3358,15 @@ export const deleteInstanceBySelector = (if (error?.type === "parent-not-found") {return throwBuilderRuntimeError("NOT_FOUND", "Parent instance not found");}+ requireBlockTemplateNameConfirmation({+ required: getBlockTemplateNameConfirmation({+ changes: [{ instance: targetInstance }],+ instances: draft.instances,+ props: draft.props.values(),+ }),+ confirm: input.templateNameConfirmation,+ path: "instanceSelector",+ });instanceIds = deletePayload.instanceIds;applyBuilderPatchPayloadMutable((namespace) => getWebstudioDataNamespace(draft, namespace),@@ -3337,22 +3650,71 @@ export const findTextContentChild = (export const createTextContentChild = ({type,value,+ expressionBindingMode,}: {type: TextContentChild["type"];value: string;-}): TextContentChild => ({ type, value });+ expressionBindingMode?: ExpressionBindingMode;+}): TextContentChild =>+ type === "expression"+ ? { type, value, mode: expressionBindingMode ?? "read" }+ : { type, value };export const getTextContentErrors = ({type,value,+ expressionBindingMode,}: {type: TextContentChild["type"];value: string;+ expressionBindingMode?: ExpressionBindingMode;}) => {if (type === "text") {return [];}- return getExpressionErrors(value);+ const bindingError = getExpressionBindingError({+ value,+ mode: expressionBindingMode,+ });+ return [+ ...(bindingError === undefined ? [] : [bindingError]),+ ...getExpressionErrors(value),+ ];+};++const assertReadwriteTextBindingSupported = ({+ state,+ instance,+ childIndex,+ child,+}: {+ state: Pick<BuilderState, "instances" | "props">;+ instance: Instance;+ childIndex: number;+ child: Extract<Instance["children"][number], { type: "expression" }>;+}) => {+ if (child.mode !== "readwrite") {+ return;+ }+ const instances = getRequiredInstances(state);+ const nextInstances = new Map(instances);+ const children = [...instance.children];+ children[childIndex] = child;+ nextInstances.set(instance.id, { ...instance, children });+ const isWritable = findWritableContentBlockDocumentBindings({+ instances: nextInstances,+ props: state.props ?? new Map(),+ }).children.some(+ (candidate) =>+ candidate.instanceId === instance.id &&+ candidate.childIndex === childIndex+ );+ if (isWritable === false) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ unsupportedReadwriteExpressionError+ );+ }};const throwTextExpressionValidationError = (errors: readonly string[]): never =>@@ -3717,7 +4079,7 @@ export const inspectInstance = (};export const updateTextInstance = (- state: Pick<BuilderState, "instances">,+ state: Pick<BuilderState, "instances" | "props">,input: z.infer<typeof updateTextInstanceInput>) => {const instances = getRequiredInstances(state);@@ -3735,7 +4097,19 @@ export const updateTextInstance = ();}const mode = input.mode ?? "text";- const errors = getTextContentErrors({ type: mode, value: input.text });+ const expressionBindingMode =+ mode === "expression" ? (input.expressionBindingMode ?? "read") : undefined;+ if (mode !== "expression" && input.expressionBindingMode !== undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Expression binding mode requires an expression child"+ );+ }+ const errors = getTextContentErrors({+ type: mode,+ value: input.text,+ expressionBindingMode,+ });if (errors.length > 0) {return throwTextExpressionValidationError(errors);}@@ -3748,6 +4122,19 @@ export const updateTextInstance = (if (instance === undefined) {return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");}+ const child = createTextContentChild({+ type: mode,+ value: input.text,+ expressionBindingMode,+ });+ if (child.type === "expression") {+ assertReadwriteTextBindingSupported({+ state,+ instance,+ childIndex: input.childIndex,+ child,+ });+ }const previousChild = instance.children[input.childIndex - 1];const nextChild = instance.children[input.childIndex + 1];const shouldMergePrevious = mode === "text" && previousChild?.type === "text";@@ -3755,6 +4142,8 @@ export const updateTextInstance = (if (result.child.type === mode &&result.child.value === input.text &&+ (result.child.type !== "expression" ||+ result.child.mode === expressionBindingMode) &&shouldMergePrevious === false &&shouldMergeNext === false) {@@ -3798,7 +4187,7 @@ export const updateTextInstance = (payload: createTextContentUpdatePayload({instanceId: input.instanceId,childIndex: input.childIndex,- child: createTextContentChild({ type: mode, value: input.text }),+ child,}),result: mutationResult,invalidatesNamespaces: ["instances"],@@ -3887,7 +4276,7 @@ export const replaceText = (};export const setTextContent = (- state: Pick<BuilderState, "instances">,+ state: Pick<BuilderState, "instances" | "props">,input: z.infer<typeof setTextContentInput>) => {const instances = getRequiredInstances(state);@@ -3964,9 +4353,23 @@ export const setTextContent = (});}+ if (+ input.mode !== "expression" &&+ input.expressionBindingMode !== undefined+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Expression binding mode requires an expression child"+ );+ }+ const expressionBindingMode =+ input.mode === "expression"+ ? (input.expressionBindingMode ?? "read")+ : undefined;const errors = getTextContentErrors({type: input.mode,value: input.text,+ expressionBindingMode,});if (errors.length > 0) {return throwTextExpressionValidationError(errors);@@ -3975,12 +4378,24 @@ export const setTextContent = (const child = createTextContentChild({type: input.mode,value: input.text,+ expressionBindingMode,});+ if (child.type === "expression") {+ assertReadwriteTextBindingSupported({+ state,+ instance,+ childIndex: 0,+ child,+ });+ }return createRuntimeMutation({payload:instance.children.length === 1 &&instance.children[0]?.type === child.type &&- instance.children[0].value === child.value+ instance.children[0].value === child.value &&+ (child.type !== "expression" ||+ (instance.children[0].type === "expression" &&+ instance.children[0].mode === child.mode))? []: createTextContentSetPayload({instanceId: input.instanceId,diff --git a/packages/project-build/src/runtime/mdx-asset-references.ts b/packages/project-build/src/runtime/mdx-asset-references.tsnew file mode 100644index 0000000000..f37980cd82--- /dev/null+++ b/packages/project-build/src/runtime/mdx-asset-references.ts@@ -0,0 +1,78 @@+import { createCanonicalAssetPath } from "@webstudio-is/content-engine/mdx";+import {+ createAssetFolderHierarchy,+ formatAssetName,+ type Asset,+ type AssetFolders,+} from "@webstudio-is/sdk";++export const getMdxPropValuePathKey = ({+ nodePath,+ propIndex,+}: {+ nodePath: readonly number[];+ propIndex: number;+}) =>+ ["children", ...nodePath.flatMap((segment) => [segment, "children"])]+ .slice(0, -1)+ .concat("props", propIndex, "value")+ .map(String)+ .join("/");++const getRelativeAssetPath = ({+ sourcePath,+ targetPath,+}: {+ sourcePath: string;+ targetPath: string;+}) => {+ const source = sourcePath.split("/").slice(0, -1);+ const target = targetPath.split("/");+ let commonLength = 0;+ while (+ source[commonLength] !== undefined &&+ source[commonLength] === target[commonLength]+ ) {+ commonLength += 1;+ }+ const segments = [+ ...source.slice(commonLength).map(() => ".."),+ ...target.slice(commonLength),+ ];+ const relative = segments.join("/");+ return relative.startsWith(".") ? relative : `./${relative}`;+};++export const createMdxAssetReferenceValues = ({+ source,+ assets,+ assetFolders,+}: {+ source: Asset;+ assets: Iterable<Asset>;+ assetFolders: AssetFolders;+}) => {+ const hierarchy = createAssetFolderHierarchy(assetFolders);+ const getPath = (asset: Asset) =>+ createCanonicalAssetPath({+ name: formatAssetName(asset),+ folderNames: hierarchy.getPath(asset.folderId).map(({ name }) => name),+ });+ const sourcePath = getPath(source);+ const paths = Array.from(assets, (asset) => ({+ asset,+ path: getPath(asset),+ }));+ const counts = new Map<string, number>();+ for (const { path } of paths) {+ counts.set(path, (counts.get(path) ?? 0) + 1);+ }+ return new Map(+ paths.map(({ asset, path }) => [+ asset.id,+ counts.get(path) === 1+ ? getRelativeAssetPath({ sourcePath, targetPath: path })+ : asset.id,+ ])+ );+};diff --git a/packages/project-build/src/runtime/mdx-authored-content.test.ts b/packages/project-build/src/runtime/mdx-authored-content.test.tsnew file mode 100644index 0000000000..052660b316--- /dev/null+++ b/packages/project-build/src/runtime/mdx-authored-content.test.ts@@ -0,0 +1,2004 @@+import { describe, expect, test } from "vitest";+import {+ discoverMdxBodyAssetReferences,+ parseMdxDocument,+ serializeMdxDocument,+} from "@webstudio-is/content-engine/mdx";+import {+ elementComponent,+ type ContentBlockExternalContentIdentity,+ type WebstudioFragment,+} from "@webstudio-is/sdk";+import {+ materializeMdxAuthoredContent,+ MdxAuthoredContentConflictError,+ rebaseMdxAuthoredContent,+ reconcileMdxAuthoredContent,+ serializeMdxAuthoredContent,+ serializeMdxTemplateInsertion,+} from "./mdx-authored-content";++const identity: ContentBlockExternalContentIdentity = {+ blockInstanceId: "block",+ assetId: "article",+ revision: "sha256:article",+ contentRef: "posts/article.mdx",+ format: "mdx",+ renderScope: "page:/article",+};++const emptyTemplates = {+ templates: [],+ diagnostics: [],+ dependencies: { templateNames: [], templates: [] },+} as const;++const htmlJsxPropContext = {+ acceptsHtmlAttributes: true,+ componentPropNames: [],+ htmlTag: "div",+ propTypes: [],+} as const;++const createCodeTextFragment = (theme = "github-light"): WebstudioFragment => ({+ children: [{ type: "id", value: "code" }],+ instances: [+ {+ type: "instance",+ id: "code",+ component: "CodeText",+ children: [{ type: "text", value: "const ready = true;" }],+ },+ ],+ props: [+ {+ id: "code-language",+ instanceId: "code",+ name: "language",+ type: "string",+ value: "javascript",+ },+ {+ id: "code-theme",+ instanceId: "code",+ name: "theme",+ type: "string",+ value: theme,+ },+ ],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+});++describe("MDX authored content", () => {+ test("rejects a canvas edit prepared from a stale Asset document", async () => {+ const document = await parseMdxDocument({ source: "Original\n" });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const latest = await parseMdxDocument({ source: "Changed in file\n" });++ await expect(+ rebaseMdxAuthoredContent({+ root,+ fragment: root.fragment,+ latest,+ })+ ).rejects.toBeInstanceOf(MdxAuthoredContentConflictError);++ await expect(+ rebaseMdxAuthoredContent({+ root,+ fragment: root.fragment,+ latest: document,+ latestRevision: "sha256:new-revision",+ })+ ).rejects.toBeInstanceOf(MdxAuthoredContentConflictError);+ });++ test("combines ordered local edits from two occurrences of one Asset", async () => {+ const document = await parseMdxDocument({+ source: "# Heading\n\nParagraph\n",+ });+ const firstRoot = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const secondRoot = materializeMdxAuthoredContent({+ identity: { ...identity, blockInstanceId: "second-block" },+ document,+ templateMaterialization: emptyTemplates,+ });+ const edit = (+ fragment: WebstudioFragment,+ tag: string,+ text: string+ ): WebstudioFragment => ({+ ...fragment,+ instances: fragment.instances.map((instance) =>+ instance.tag === tag+ ? { ...instance, children: [{ type: "text", value: text }] }+ : instance+ ),+ });+ const first = await rebaseMdxAuthoredContent({+ root: firstRoot,+ fragment: edit(firstRoot.fragment, "h1", "First edit"),+ latest: document,+ });+ const combined = await rebaseMdxAuthoredContent({+ root: secondRoot,+ fragment: edit(secondRoot.fragment, "p", "Second edit"),+ latest: first,+ latestIsLocal: true,+ });++ expect(serializeMdxDocument(combined)).toBe(+ "# First edit\n\nSecond edit\n"+ );+ });++ test("applies the later local edit when two occurrences edit the same node", async () => {+ const document = await parseMdxDocument({ source: "Original\n" });+ const firstRoot = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const secondRoot = materializeMdxAuthoredContent({+ identity: { ...identity, blockInstanceId: "second-block" },+ document,+ templateMaterialization: emptyTemplates,+ });+ const editText = (+ fragment: WebstudioFragment,+ value: string+ ): WebstudioFragment => ({+ ...fragment,+ instances: fragment.instances.map((instance) => ({+ ...instance,+ children: [{ type: "text", value }],+ })),+ });+ const first = await rebaseMdxAuthoredContent({+ root: firstRoot,+ fragment: editText(firstRoot.fragment, "First"),+ latest: document,+ });+ const combined = await rebaseMdxAuthoredContent({+ root: secondRoot,+ fragment: editText(secondRoot.fragment, "Second"),+ latest: first,+ latestIsLocal: true,+ });++ expect(serializeMdxDocument(combined)).toBe("Second\n");+ });++ test("combines an earlier edit with a later sibling reorder", async () => {+ const document = await parseMdxDocument({+ source: "First\n\nSecond\n\nThird\n",+ });+ const firstRoot = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const secondRoot = materializeMdxAuthoredContent({+ identity: { ...identity, blockInstanceId: "second-block" },+ document,+ templateMaterialization: emptyTemplates,+ });+ const firstInstanceId = firstRoot.fragment.children[0];+ const firstEdit: WebstudioFragment = {+ ...firstRoot.fragment,+ instances: firstRoot.fragment.instances.map((instance) =>+ firstInstanceId?.type === "id" && instance.id === firstInstanceId.value+ ? {+ ...instance,+ children: [{ type: "text", value: "Edited first" }],+ }+ : instance+ ),+ };+ const reordered: WebstudioFragment = {+ ...secondRoot.fragment,+ children: [+ secondRoot.fragment.children[2],+ secondRoot.fragment.children[0],+ secondRoot.fragment.children[1],+ ],+ };+ const first = await rebaseMdxAuthoredContent({+ root: firstRoot,+ fragment: firstEdit,+ latest: document,+ });+ const combined = await rebaseMdxAuthoredContent({+ root: secondRoot,+ fragment: reordered,+ latest: first,+ latestIsLocal: true,+ });++ expect(serializeMdxDocument(combined)).toBe(+ "Third\n\nEdited first\n\nSecond\n"+ );+ });++ test("preserves an earlier insertion when a later occurrence edits existing content", async () => {+ const document = await parseMdxDocument({ source: "Original\n" });+ const firstRoot = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const secondRoot = materializeMdxAuthoredContent({+ identity: { ...identity, blockInstanceId: "second-block" },+ document,+ templateMaterialization: emptyTemplates,+ });+ const inserted: WebstudioFragment = {+ ...firstRoot.fragment,+ children: [+ ...firstRoot.fragment.children,+ { type: "id", value: "inserted" },+ ],+ instances: [+ ...firstRoot.fragment.instances,+ {+ type: "instance",+ id: "inserted",+ component: elementComponent,+ tag: "p",+ children: [{ type: "text", value: "Inserted" }],+ },+ ],+ };+ const edited: WebstudioFragment = {+ ...secondRoot.fragment,+ instances: secondRoot.fragment.instances.map((instance) => ({+ ...instance,+ children: [{ type: "text", value: "Edited" }],+ })),+ };+ const first = await rebaseMdxAuthoredContent({+ root: firstRoot,+ fragment: inserted,+ latest: document,+ });+ const combined = await rebaseMdxAuthoredContent({+ root: secondRoot,+ fragment: edited,+ latest: first,+ latestIsLocal: true,+ });++ expect(serializeMdxDocument(combined)).toBe("Edited\n\nInserted\n");+ });++ test("serializes standard inserted content as Markdown and omits draft paragraphs", async () => {+ const document = await parseMdxDocument({ source: "" });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const fragment: WebstudioFragment = {+ ...root.fragment,+ children: [+ { type: "id", value: "paragraph" },+ { type: "id", value: "list" },+ { type: "id", value: "draft" },+ ],+ instances: [+ {+ type: "instance",+ id: "paragraph",+ component: elementComponent,+ tag: "p",+ children: [+ { type: "text", value: "Read the " },+ { type: "id", value: "link" },+ { type: "text", value: "." },+ ],+ },+ {+ type: "instance",+ id: "link",+ component: elementComponent,+ tag: "a",+ children: [{ type: "text", value: "guide" }],+ },+ {+ type: "instance",+ id: "list",+ component: elementComponent,+ tag: "ul",+ children: [+ { type: "id", value: "first-item" },+ { type: "id", value: "second-item" },+ ],+ },+ {+ type: "instance",+ id: "first-item",+ component: elementComponent,+ tag: "li",+ children: [{ type: "text", value: "First" }],+ },+ {+ type: "instance",+ id: "second-item",+ component: elementComponent,+ tag: "li",+ children: [{ type: "text", value: "Second" }],+ },+ {+ type: "instance",+ id: "draft",+ component: elementComponent,+ tag: "p",+ children: [],+ },+ ],+ props: [+ {+ id: "href",+ instanceId: "link",+ name: "href",+ type: "string",+ value: "https://wstd.us/content-block",+ },+ ],+ };++ await expect(serializeMdxAuthoredContent({ root, fragment })).resolves.toBe(+ "Read the [guide](https://wstd.us/content-block).\n\n- First\n- Second\n"+ );+ });++ test("serializes a sibling inserted into an authored list as a Markdown item", async () => {+ const document = await parseMdxDocument({ source: "1. First\n" });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const fragment = structuredClone(root.fragment);+ const list = fragment.instances.find(({ tag }) => tag === "ol");+ if (list === undefined) {+ throw new Error("Expected an ordered list");+ }+ list.children.push({ type: "id", value: "second-item" });+ fragment.instances.push({+ type: "instance",+ id: "second-item",+ component: elementComponent,+ tag: "li",+ children: [{ type: "text", value: "Second" }],+ });++ await expect(serializeMdxAuthoredContent({ root, fragment })).resolves.toBe(+ "1. First\n2. Second\n"+ );+ });++ test("does not persist newly inserted empty Markdown drafts", async () => {+ const document = await parseMdxDocument({ source: "" });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const fragment: WebstudioFragment = {+ ...root.fragment,+ children: [+ { type: "id", value: "heading" },+ { type: "id", value: "empty-list" },+ { type: "id", value: "list" },+ ],+ instances: [+ {+ type: "instance",+ id: "heading",+ component: elementComponent,+ tag: "h6",+ children: [],+ },+ {+ type: "instance",+ id: "empty-list",+ component: elementComponent,+ tag: "ul",+ children: [{ type: "id", value: "empty-list-item" }],+ },+ {+ type: "instance",+ id: "empty-list-item",+ component: elementComponent,+ tag: "li",+ children: [],+ },+ {+ type: "instance",+ id: "list",+ component: elementComponent,+ tag: "ul",+ children: [+ { type: "id", value: "empty-item" },+ { type: "id", value: "kept-item" },+ ],+ },+ {+ type: "instance",+ id: "empty-item",+ component: elementComponent,+ tag: "li",+ children: [],+ },+ {+ type: "instance",+ id: "kept-item",+ component: elementComponent,+ tag: "li",+ children: [{ type: "text", value: "Kept" }],+ },+ ],+ };++ await expect(serializeMdxAuthoredContent({ root, fragment })).resolves.toBe(+ "- Kept\n"+ );+ });++ test("preserves empty Markdown nodes authored in the file", async () => {+ const document = await parseMdxDocument({ source: "######\n\n-\n" });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });++ await expect(+ serializeMdxAuthoredContent({ root, fragment: root.fragment })+ ).resolves.toBe("######\n\n-\n");+ });++ test("serializes a lossless template insertion as Markdown", async () => {+ const fragment: WebstudioFragment = {+ children: [{ type: "id", value: "heading" }],+ instances: [+ {+ type: "instance",+ id: "heading",+ component: elementComponent,+ tag: "h1",+ label: "Heading 1",+ children: [{ type: "text", value: "Test" }],+ },+ ],+ props: [],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ };++ expect(+ serializeMdxDocument(+ await serializeMdxTemplateInsertion({+ identity,+ fragment,+ templateName: "Heading 1",+ })+ )+ ).toBe("# Test\n");+ });++ test("serializes Markdown-compatible Image props as an image", async () => {+ const fragment: WebstudioFragment = {+ children: [{ type: "id", value: "image" }],+ instances: [+ {+ type: "instance",+ id: "image",+ component: "Image",+ children: [],+ },+ ],+ props: [+ {+ id: "image-src",+ instanceId: "image",+ name: "src",+ type: "string",+ value: "/hero.png",+ },+ {+ id: "image-alt",+ instanceId: "image",+ name: "alt",+ type: "string",+ value: "Hero",+ },+ {+ id: "image-title",+ instanceId: "image",+ name: "title",+ type: "string",+ value: "Cover",+ },+ ],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ };++ expect(+ serializeMdxDocument(+ await serializeMdxTemplateInsertion({+ identity,+ fragment,+ templateName: "Image",+ })+ )+ ).toBe('\n');+ });++ test("uses JSX when an Image has props Markdown cannot express", async () => {+ const fragment: WebstudioFragment = {+ children: [{ type: "id", value: "image" }],+ instances: [+ {+ type: "instance",+ id: "image",+ component: "Image",+ children: [],+ },+ ],+ props: [+ {+ id: "image-src",+ instanceId: "image",+ name: "src",+ type: "string",+ value: "/hero.png",+ },+ {+ id: "image-width",+ instanceId: "image",+ name: "width",+ type: "number",+ value: 640,+ },+ ],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ };++ expect(+ serializeMdxDocument(+ await serializeMdxTemplateInsertion({+ identity,+ fragment,+ templateName: "Image",+ })+ )+ ).toBe('<ws.element ws:name="Image" src="/hero.png" width="640" />\n');+ });++ test("uses canonical JSX names in a generic template insertion", async () => {+ const fragment: WebstudioFragment = {+ children: [{ type: "id", value: "widget" }],+ instances: [+ {+ type: "instance",+ id: "widget",+ component: "Widget",+ children: [],+ },+ ],+ props: [+ {+ id: "widget:class",+ instanceId: "widget",+ name: "class",+ type: "string",+ value: "featured",+ },+ ],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ };++ expect(+ serializeMdxDocument(+ await serializeMdxTemplateInsertion({+ identity,+ fragment,+ templateName: "Widget",+ })+ )+ ).toBe('<ws.element ws:name="Widget" className="featured" />\n');+ });++ test("preserves unknown component props in a generic template insertion", async () => {+ const fragment: WebstudioFragment = {+ children: [{ type: "id", value: "widget" }],+ instances: [+ {+ type: "instance",+ id: "widget",+ component: "Widget",+ children: [],+ },+ ],+ props: [+ {+ id: "widget:for",+ instanceId: "widget",+ name: "for",+ type: "string",+ value: "custom-target",+ },+ ],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ };++ expect(+ serializeMdxDocument(+ await serializeMdxTemplateInsertion({+ identity,+ fragment,+ templateName: "Widget",+ })+ )+ ).toBe('<ws.element ws:name="Widget" for="custom-target" />\n');+ });++ test("rebases a styled template insertion as a template reference", async () => {+ const document = await parseMdxDocument({ source: "" });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const fragment: WebstudioFragment = {+ children: [{ type: "id", value: "heading" }],+ instances: [+ {+ type: "instance",+ id: "heading",+ component: elementComponent,+ tag: "h1",+ label: "Styled Heading",+ children: [{ type: "text", value: "Test" }],+ },+ ],+ props: [+ {+ id: "title",+ instanceId: "heading",+ name: "title",+ type: "string",+ value: "Updated",+ },+ ],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [{ id: "base", label: "Base" }],+ styleSourceSelections: [+ { instanceId: "heading", values: ["heading-style"] },+ ],+ styleSources: [{ type: "local", id: "heading-style" }],+ styles: [+ {+ breakpointId: "base",+ styleSourceId: "heading-style",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ };++ expect(+ serializeMdxDocument(+ await rebaseMdxAuthoredContent({+ root,+ fragment,+ latest: document,+ insertedTemplateNames: new Map([["heading", "Styled Heading"]]),+ })+ )+ ).toBe(+ '<ws.element ws:name="Styled Heading" title="Updated">Test</ws.element>\n'+ );+ });++ test("serializes explicitly configured Code Text presentation as JSX", async () => {+ const document = await serializeMdxTemplateInsertion({+ identity,+ fragment: createCodeTextFragment(),+ templateName: "CodeText",+ });++ expect(serializeMdxDocument(document)).toBe(+ '<ws.element ws:name="CodeText" language="javascript" theme="github-light">const ready = true;</ws.element>\n'+ );+ });++ test("serializes Code Text without presentation props as fenced Markdown", async () => {+ const fragment = createCodeTextFragment();+ fragment.props = [];+ const code = fragment.instances[0]?.children[0];+ if (code?.type !== "text") {+ throw new Error("Expected code text");+ }+ code.value = "a = 1\nb=2\nc=5";++ const document = await serializeMdxTemplateInsertion({+ identity,+ fragment,+ templateName: "CodeText",+ });++ expect(serializeMdxDocument(document)).toBe("```\na = 1\nb=2\nc=5\n```\n");+ });++ test("serializes the legacy Code Text code property as text content", async () => {+ const fragment = createCodeTextFragment();+ const instance = fragment.instances[0];+ if (instance === undefined) {+ throw new Error("Expected Code Text instance");+ }+ const [code] = instance.children.splice(0);+ if (code?.type !== "text") {+ throw new Error("Expected code text");+ }+ fragment.props.push({+ id: "legacy-code",+ instanceId: instance.id,+ name: "code",+ type: "string",+ value: code.value,+ });++ const document = await serializeMdxTemplateInsertion({+ identity,+ fragment,+ templateName: "Code Text",+ });++ expect(serializeMdxDocument(document)).toBe(+ '<ws.element ws:name="Code Text" language="javascript" theme="github-light">const ready = true;</ws.element>\n'+ );+ });++ test("materializes fenced Markdown as editable Code Text", async () => {+ const document = await parseMdxDocument({+ source: "```javascript\nconst ready = true;\n```\n",+ });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const instance = root.fragment.instances[0];++ expect(instance).toMatchObject({+ component: "CodeText",+ children: [{ type: "text", value: "const ready = true;" }],+ });+ expect(+ Object.fromEntries(+ root.fragment.props.map((prop) => [prop.name, prop.value])+ )+ ).toEqual({+ language: "javascript",+ });+ expect(+ await serializeMdxAuthoredContent({ root, fragment: root.fragment })+ ).toBe("```javascript\nconst ready = true;\n```\n");+ });++ test("keeps defaults implicit when rematerializing a plain code fence", async () => {+ const source = "```\na = 1\nb=2\nc=5\n```\n";+ const document = await parseMdxDocument({ source });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });++ expect(root.fragment.props).toEqual([]);+ expect(+ await serializeMdxAuthoredContent({ root, fragment: root.fragment })+ ).toBe(source);+ });++ test("removes a reset language from a fenced code block", async () => {+ const document = await parseMdxDocument({+ source: "```javascript\nconst ready = true;\n```\n",+ });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const reset = structuredClone(root.fragment);+ reset.props = reset.props.filter(({ name }) => name !== "language");++ expect(await serializeMdxAuthoredContent({ root, fragment: reset })).toBe(+ "```\nconst ready = true;\n```\n"+ );+ });++ test("keeps Code Text with non-default presentation as JSX", async () => {+ const document = await serializeMdxTemplateInsertion({+ identity,+ fragment: createCodeTextFragment("nord"),+ templateName: "Code Text",+ });+ const source = serializeMdxDocument(document);++ expect(source).toContain('<ws.element ws:name="Code Text"');+ expect(source).toContain('theme="nord"');+ });++ test("keeps Code Text with additional props as JSX", async () => {+ const fragment = createCodeTextFragment();+ fragment.props.push({+ id: "code-id",+ instanceId: "code",+ name: "id",+ type: "string",+ value: "example",+ });++ const document = await serializeMdxTemplateInsertion({+ identity,+ fragment,+ templateName: "Code Text",+ });+ const source = serializeMdxDocument(document);++ expect(source).toContain('<ws.element ws:name="Code Text"');+ expect(source).toContain('id="example"');+ });++ test("serializes static number and false props in component JSX", async () => {+ const fragment = createCodeTextFragment();+ fragment.props = [+ {+ id: "code-tabindex",+ instanceId: "code",+ name: "tabindex",+ type: "number",+ value: 2,+ },+ {+ id: "code-hidden",+ instanceId: "code",+ name: "hidden",+ type: "boolean",+ value: false,+ },+ ];++ const document = await serializeMdxTemplateInsertion({+ identity,+ fragment,+ templateName: "CodeText",+ });++ expect(serializeMdxDocument(document)).toBe(+ '<ws.element ws:name="CodeText" tabIndex="2" hidden="false">const ready = true;</ws.element>\n'+ );+ });++ test("keeps Code Text whitespace that Markdown cannot preserve as JSX", async () => {+ const fragment = createCodeTextFragment();+ const code = fragment.instances[0]?.children[0];+ if (code?.type !== "text") {+ throw new Error("Expected code text");+ }+ code.value += "\n";++ const document = await serializeMdxTemplateInsertion({+ identity,+ fragment,+ templateName: "Code Text",+ });++ expect(serializeMdxDocument(document)).toContain("const ready = true;\n");+ });++ test("switches materialized Code Text to JSX when it gains unsupported props", async () => {+ const document = await parseMdxDocument({+ source: "```javascript\nconst ready = true;\n```\n",+ });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const fragment = structuredClone(root.fragment);+ fragment.props.push({+ id: "authored-theme",+ instanceId: fragment.instances[0]!.id,+ name: "theme",+ type: "string",+ value: "nord",+ });++ expect(await serializeMdxAuthoredContent({ root, fragment })).toContain(+ '<ws.element ws:name="CodeText" language="javascript" theme="nord">const ready = true;</ws.element>'+ );+ });++ test("round-trips Code Text through JSX and back to a fence", async () => {+ const fence = await parseMdxDocument({+ source: "```\nconst ready = true;\n```\n",+ });+ const fenceRoot = materializeMdxAuthoredContent({+ identity,+ document: fence,+ templateMaterialization: emptyTemplates,+ });+ const withClass = structuredClone(fenceRoot.fragment);+ withClass.props.push({+ id: "code-class",+ instanceId: withClass.instances[0]!.id,+ name: "class",+ type: "string",+ value: "example",+ });+ const jsxSource = await serializeMdxAuthoredContent({+ root: fenceRoot,+ fragment: withClass,+ });+ expect(jsxSource).toBe(+ '<ws.element ws:name="CodeText" className="example">const ready = true;</ws.element>\n'+ );++ const jsx = await parseMdxDocument({ source: jsxSource });+ const authoredTemplate = jsx.children[0];+ if (authoredTemplate?.type !== "template") {+ throw new Error("Expected Code Text template reference");+ }+ const templateFragment = createCodeTextFragment();+ templateFragment.props = [+ {+ id: "template-class",+ instanceId: "code",+ name: "class",+ type: "string",+ value: "example",+ },+ ];+ const jsxRoot = materializeMdxAuthoredContent({+ identity,+ document: jsx,+ templateMaterialization: {+ templates: [+ {+ type: "resolved-template",+ reference: {+ type: "resolved-template",+ path: [0],+ templateName: "CodeText",+ templateInstanceId: "code-template",+ props: authoredTemplate.props,+ },+ fragment: templateFragment,+ editablePropNames: ["class", "language", "theme"],+ jsxPropContext: htmlJsxPropContext,+ propNameMappings: [+ { jsxPropName: "className", instancePropName: "class" },+ ],+ ignoredJsxPropNames: [],+ },+ ],+ diagnostics: [],+ dependencies: { templateNames: ["CodeText"], templates: [] },+ },+ });+ const reset = structuredClone(jsxRoot.fragment);+ reset.props = reset.props.filter(({ name }) => name !== "class");++ expect(+ await serializeMdxAuthoredContent({ root: jsxRoot, fragment: reset })+ ).toBe("```\nconst ready = true;\n```\n");+ });++ test("persists a newly authored prop on an existing template reference", async () => {+ const document = await parseMdxDocument({+ source: '<ws.element ws:name="CodeText">const ready = true;</ws.element>',+ });+ const authoredTemplate = document.children[0];+ if (authoredTemplate?.type !== "template") {+ throw new Error("Expected Code Text template reference");+ }+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: {+ templates: [+ {+ type: "resolved-template",+ reference: {+ type: "resolved-template",+ path: [0],+ templateName: "CodeText",+ templateInstanceId: "code-template",+ props: authoredTemplate.props,+ },+ fragment: createCodeTextFragment(),+ editablePropNames: ["language", "theme"],+ jsxPropContext: htmlJsxPropContext,+ propNameMappings: [],+ ignoredJsxPropNames: [],+ },+ ],+ diagnostics: [],+ dependencies: { templateNames: ["CodeText"], templates: [] },+ },+ });+ const next = structuredClone(root.fragment);+ const theme = next.props.find(({ name }) => name === "theme");+ if (theme?.type !== "string") {+ throw new Error("Expected theme prop");+ }+ theme.value = "nord";++ expect(+ serializeMdxDocument(+ reconcileMdxAuthoredContent({ root, fragment: next })+ )+ ).toBe(+ '<ws.element ws:name="CodeText" language="javascript" theme="nord">const ready = true;</ws.element>\n'+ );+ });++ test("switches a Code Text template reference to a fence after resetting presentation props", async () => {+ const document = await parseMdxDocument({+ source:+ '<ws.element ws:name="CodeText" language="javascript" theme="github-light">const ready = true;</ws.element>',+ });+ const authoredTemplate = document.children[0];+ if (authoredTemplate?.type !== "template") {+ throw new Error("Expected Code Text template reference");+ }+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: {+ templates: [+ {+ type: "resolved-template",+ reference: {+ type: "resolved-template",+ path: [0],+ templateName: "CodeText",+ templateInstanceId: "code-template",+ props: authoredTemplate.props,+ },+ fragment: createCodeTextFragment(),+ editablePropNames: ["language", "theme"],+ jsxPropContext: htmlJsxPropContext,+ propNameMappings: [+ { jsxPropName: "language", instancePropName: "language" },+ { jsxPropName: "theme", instancePropName: "theme" },+ ],+ ignoredJsxPropNames: [],+ },+ ],+ diagnostics: [],+ dependencies: { templateNames: ["CodeText"], templates: [] },+ },+ });+ const next = structuredClone(root.fragment);+ next.props = next.props.filter(+ ({ name }) => name !== "language" && name !== "theme"+ );++ expect(+ serializeMdxDocument(+ reconcileMdxAuthoredContent({ root, fragment: next })+ )+ ).toBe("```\nconst ready = true;\n```\n");+ });++ test("materializes deterministic nested Markdown and MDX elements", async () => {+ const document = await parseMdxDocument({+ source: `# Heading\n\n<ws.element ws:tag="section" data-kind="intro"><ws.element ws:tag="strong">Body</ws.element></ws.element>`,+ });+ const first = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const second = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const otherScope = materializeMdxAuthoredContent({+ identity: { ...identity, renderScope: "page:/other" },+ document,+ templateMaterialization: emptyTemplates,+ });+ const otherRevision = materializeMdxAuthoredContent({+ identity: { ...identity, revision: "sha256:next" },+ document,+ templateMaterialization: emptyTemplates,+ });++ expect(second.fragment).toEqual(first.fragment);+ expect(otherScope.fragment.instances[0].id).not.toBe(+ first.fragment.instances[0].id+ );+ expect(otherRevision.fragment.instances[0].id).toBe(+ first.fragment.instances[0].id+ );+ expect(+ first.fragment.instances.map(({ component, tag }) => [component, tag])+ ).toEqual([+ [elementComponent, "h1"],+ [elementComponent, "strong"],+ [elementComponent, "section"],+ ]);+ });++ test("round-trips typed static props on generic MDX elements", async () => {+ const source =+ '<ws.element ws:tag="input" tabIndex="2" hidden="false" />\n';+ const document = await parseMdxDocument({ source });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });++ expect(root.fragment.props).toEqual([+ expect.objectContaining({+ name: "tabindex",+ type: "number",+ value: 2,+ }),+ expect.objectContaining({+ name: "hidden",+ type: "boolean",+ value: false,+ }),+ ]);+ expect(+ await serializeMdxAuthoredContent({ root, fragment: root.fragment })+ ).toBe(source);+ });++ test("reconciles text, props, insertion, deletion, and reorder semantically", async () => {+ const document = await parseMdxDocument({+ source: `---\ntitle: Example\n---\n\n{/* before */}\n\n# First\n\n<ws.element ws:tag="p" class="lead">Second</ws.element>`,+ });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const [headingId, paragraphId] = root.fragment.children.flatMap((child) =>+ child.type === "id" ? [child.value] : []+ );+ const next = structuredClone(root.fragment);+ next.children = [+ { type: "id", value: paragraphId },+ { type: "id", value: "inserted" },+ ];+ next.instances = [+ ...next.instances.filter(({ id }) => id !== headingId),+ {+ type: "instance",+ id: "inserted",+ component: elementComponent,+ tag: "aside",+ children: [{ type: "text", value: "New" }],+ },+ ];+ const paragraph = next.instances.find(({ id }) => id === paragraphId)!;+ paragraph.children = [{ type: "text", value: "Changed" }];+ const paragraphProp = next.props.find(+ ({ instanceId, name }) => instanceId === paragraphId && name === "class"+ )!;+ paragraphProp.value = "summary";+ const nextBeforeReconcile = structuredClone(next);+ const documentBeforeReconcile = structuredClone(document);++ const reconciled = reconcileMdxAuthoredContent({ root, fragment: next });+ expect(next).toEqual(nextBeforeReconcile);+ expect(document).toEqual(documentBeforeReconcile);+ expect(reconcileMdxAuthoredContent({ root, fragment: next })).toEqual(+ reconciled+ );+ const reparsed = await parseMdxDocument({+ source: serializeMdxDocument(reconciled),+ });++ expect(reparsed.frontmatter.properties).toEqual({ title: "Example" });+ expect(reparsed.children.map((node) => node.type)).toEqual([+ "comment",+ "element",+ "element",+ ]);+ expect(reparsed.children[1]).toMatchObject({+ type: "element",+ tag: "p",+ props: [{ name: "class", value: "summary" }],+ children: [{ type: "text", value: "Changed" }],+ });+ expect(reparsed.children[2]).toMatchObject({+ type: "element",+ syntax: "mdx",+ tag: "aside",+ children: [{ type: "text", value: "New" }],+ });+ });++ test("round-trips Markdown lists, tables, code whitespace, links, and marks", async () => {+ const document = await parseMdxDocument({+ source: `- First\n- Second with **bold** and [guide](./guide.pdf)\n\n| Name | Value |\n| --- | ---: |\n| Alpha | 1 |\n\n\`\`\`js\n const value = 1;\n\`\`\``,+ });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const next = structuredClone(root.fragment);+ const code = next.instances.find(+ ({ component }) => component === "CodeText"+ );+ if (code === undefined) {+ throw new Error("Expected code instance");+ }+ const codeText = code.children[0];+ if (codeText?.type !== "text") {+ throw new Error("Expected code text");+ }+ codeText.value = " const value = 2;";++ const reconciled = reconcileMdxAuthoredContent({ root, fragment: next });+ const serialized = serializeMdxDocument(reconciled);+ const reparsed = await parseMdxDocument({ source: serialized });+ const rematerialized = materializeMdxAuthoredContent({+ identity,+ document: reparsed,+ templateMaterialization: emptyTemplates,+ });++ expect(+ rematerialized.fragment.instances.map(({ component, tag }) => ({+ component,+ tag,+ }))+ ).toEqual(+ root.fragment.instances.map(({ component, tag }) => ({ component, tag }))+ );+ const rematerializedCode = rematerialized.fragment.instances.find(+ ({ component }) => component === "CodeText"+ );+ expect(rematerializedCode?.children).toEqual([+ { type: "text", value: " const value = 2;" },+ ]);+ expect(serialized).toContain("**bold**");+ });++ test("synthesizes nested block and inline JSX with stable modes", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:tag="section"><ws.element ws:tag="p">Before</ws.element></ws.element>`,+ });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const next = structuredClone(root.fragment);+ const section = next.instances.find(({ tag }) => tag === "section")!;+ section.children.push({ type: "id", value: "aside" });+ next.instances.push(+ {+ type: "instance",+ id: "aside",+ component: elementComponent,+ tag: "aside",+ children: [{ type: "id", value: "inserted-paragraph" }],+ },+ {+ type: "instance",+ id: "inserted-paragraph",+ component: elementComponent,+ tag: "p",+ children: [{ type: "id", value: "strong" }],+ },+ {+ type: "instance",+ id: "strong",+ component: elementComponent,+ tag: "strong",+ children: [{ type: "text", value: "Nested" }],+ }+ );++ const serialized = serializeMdxDocument(+ reconcileMdxAuthoredContent({ root, fragment: next })+ );+ const reparsed = await parseMdxDocument({ source: serialized });+ const rematerialized = materializeMdxAuthoredContent({+ identity,+ document: reparsed,+ templateMaterialization: emptyTemplates,+ });++ expect(rematerialized.fragment.instances.map(({ tag }) => tag)).toEqual([+ "p",+ "strong",+ "p",+ "aside",+ "section",+ ]);+ const reparsedSection = reparsed.children[0];+ expect(+ reparsedSection.type === "element"+ ? reparsedSection.children.find(+ (node) => node.type === "element" && node.tag === "aside"+ )+ : undefined+ ).toMatchObject({ type: "element", syntax: "mdx", mdxMode: "flow" });+ expect(serializeMdxDocument(reparsed)).toBe(serialized);+ });++ test("preserves unresolved templates, comments, and ignored authored props", async () => {+ const document = await parseMdxDocument({+ source: `{/* note */}\n\n<ws.element ws:name="Missing" obsolete="yes">Keep me</ws.element>\n\nParagraph`,+ });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: {+ ...emptyTemplates,+ templates: [+ {+ type: "unresolved-template",+ reference: {+ type: "unresolved-template",+ path: [1],+ templateName: "Missing",+ },+ markerId: "missing",+ },+ ],+ },+ });+ const next = structuredClone(root.fragment);+ next.instances[0].children = [{ type: "text", value: "Changed" }];++ expect(root.provenance.unresolvedTemplates).toEqual([+ {+ path: [1],+ markerId: "missing",+ templateName: "Missing",+ },+ ]);++ const reconciled = reconcileMdxAuthoredContent({ root, fragment: next });++ expect(reconciled.children).toMatchObject([+ { type: "comment", value: "/* note */" },+ {+ type: "template",+ name: "Missing",+ props: [{ name: "obsolete", value: "yes" }],+ children: [{ type: "text", value: "Keep me" }],+ },+ {+ type: "element",+ children: [{ type: "text", value: "Changed" }],+ },+ ]);+ });++ test("places an unresolved-template placeholder at its authored nesting point", async () => {+ const document = await parseMdxDocument({+ source:+ '<ws.element ws:tag="section">Before<ws.element ws:name="Missing" />After</ws.element>',+ });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: {+ ...emptyTemplates,+ templates: [+ {+ type: "unresolved-template",+ reference: {+ type: "unresolved-template",+ path: [0, 1],+ templateName: "Missing",+ },+ markerId: "missing",+ },+ ],+ },+ createUnresolvedTemplateInstance: ({ markerId }) => ({+ type: "instance",+ id: markerId,+ component: elementComponent,+ tag: "div",+ children: [{ type: "text", value: "Missing template" }],+ }),+ });+ const section = root.fragment.instances.find(+ ({ tag }) => tag === "section"+ );++ expect(section?.children).toEqual([+ { type: "text", value: "Before" },+ { type: "id", value: "missing" },+ { type: "text", value: "After" },+ ]);+ });++ test("keeps an inline comment anchored when adjacent text is deleted", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:tag="p">Before{/* note */}After</ws.element>`,+ });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const next = structuredClone(root.fragment);+ next.instances[0].children = [{ type: "text", value: "After" }];++ const reconciled = reconcileMdxAuthoredContent({ root, fragment: next });+ const paragraph = reconciled.children[0];+ expect(+ paragraph.type === "element" ? paragraph.children : []+ ).toMatchObject([+ { type: "comment", value: "/* note */" },+ { type: "text", value: "After" },+ ]);+ });++ test("rejects changes to unsupported authored namespaces", async () => {+ const document = await parseMdxDocument({ source: "Paragraph" });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const next = structuredClone(root.fragment);+ next.styles.push({+ breakpointId: "base",+ styleSourceId: "local",+ property: "color",+ value: { type: "keyword", value: "red" },+ });++ expect(() => reconcileMdxAuthoredContent({ root, fragment: next })).toThrow(+ "cannot be represented losslessly in MDX"+ );+ });++ test("rejects duplicate props and reused instances instead of losing them", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:tag="p" class="first">Text</ws.element>`,+ });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const duplicateProp = structuredClone(root.fragment);+ const originalProp = duplicateProp.props[0];+ if (originalProp?.type !== "string") {+ throw new Error("Expected string prop");+ }+ duplicateProp.props.push({+ ...originalProp,+ id: "duplicate-prop",+ value: "second",+ });+ expect(() =>+ reconcileMdxAuthoredContent({ root, fragment: duplicateProp })+ ).toThrow('Duplicate authored prop "class"');++ const reusedInstance = structuredClone(root.fragment);+ reusedInstance.children.push(reusedInstance.children[0]);+ expect(() =>+ reconcileMdxAuthoredContent({ root, fragment: reusedInstance })+ ).toThrow("is reused");+ });++ test("preserves authored Asset references while changing content", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:tag="figure"><ws.element ws:tag="img" src="./hero.png" /><ws.element ws:tag="a" href="../files/guide.pdf">Read</ws.element></ws.element>`,+ });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ assetReferences: discoverMdxBodyAssetReferences({+ document,+ sourcePath: "posts/article.mdx",+ assetIdsByPath: new Map([+ ["posts/hero.png", "hero-asset"],+ ["files/guide.pdf", "guide-asset"],+ ]),+ }),+ });+ expect(root.fragment.props.map(({ type, value }) => [type, value])).toEqual(+ [+ ["asset", "hero-asset"],+ ["asset", "guide-asset"],+ ]+ );+ const next = structuredClone(root.fragment);+ next.instances.find(({ tag }) => tag === "a")!.children = [+ { type: "text", value: "Download" },+ ];++ const source = serializeMdxDocument(+ reconcileMdxAuthoredContent({ root, fragment: next })+ );+ expect(source).toContain('src="./hero.png"');+ expect(source).toContain('href="../files/guide.pdf"');+ expect(source).toContain("Download");++ const changedAsset = next.props.find(({ name }) => name === "src");+ if (changedAsset?.type !== "asset") {+ throw new Error("Expected Asset prop");+ }+ changedAsset.value = "other-asset";+ expect(() => reconcileMdxAuthoredContent({ root, fragment: next })).toThrow(+ 'Asset prop "src" cannot be represented losslessly in MDX'+ );+ });++ test("updates template shell props without serializing expanded internals", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:name="Card" tone="quiet" legacy="authored" />`,+ });+ const templateFragment: WebstudioFragment = {+ children: [{ type: "id", value: "template-root" }],+ instances: [+ {+ type: "instance",+ id: "template-root",+ component: elementComponent,+ tag: "article",+ children: [{ type: "id", value: "template-heading" }],+ },+ {+ type: "instance",+ id: "template-heading",+ component: elementComponent,+ tag: "h2",+ children: [{ type: "text", value: "Template heading" }],+ },+ ],+ props: [+ {+ id: "tone",+ instanceId: "template-root",+ name: "tone",+ type: "string",+ value: "quiet",+ },+ {+ id: "legacy",+ instanceId: "template-root",+ name: "legacy",+ type: "string",+ value: "template default",+ },+ ],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [{ id: "base", label: "Base" }],+ styleSourceSelections: [+ { instanceId: "template-root", values: ["template-local"] },+ ],+ styleSources: [{ type: "local", id: "template-local" }],+ styles: [+ {+ breakpointId: "base",+ styleSourceId: "template-local",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ };+ const authoredTemplate = document.children[0];+ if (authoredTemplate?.type !== "template") {+ throw new Error("Expected authored template");+ }+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: {+ templates: [+ {+ type: "resolved-template",+ reference: {+ type: "resolved-template",+ path: [0],+ templateName: "Card",+ templateInstanceId: "card-template",+ props: authoredTemplate.props,+ },+ fragment: templateFragment,+ editablePropNames: ["tone"],+ jsxPropContext: {+ ...htmlJsxPropContext,+ componentPropNames: ["tone", "legacy"],+ },+ propNameMappings: [+ { jsxPropName: "tone", instancePropName: "tone" },+ { jsxPropName: "legacy", instancePropName: "legacy" },+ ],+ ignoredJsxPropNames: ["legacy"],+ },+ ],+ diagnostics: [+ {+ code: "ignored-template-prop",+ severity: "warning",+ blockInstanceId: "block",+ assetId: "article",+ contentRef: "posts/article.mdx",+ renderScope: "page:/article",+ templateName: "Card",+ propName: "legacy",+ reason: "stale",+ },+ ],+ dependencies: { templateNames: ["Card"], templates: [] },+ },+ });+ const next = structuredClone(root.fragment);+ const tone = next.props.find(({ id }) => id === "tone");+ if (tone?.type !== "string") {+ throw new Error("Expected tone prop");+ }+ tone.value = "loud";++ expect(+ reconcileMdxAuthoredContent({ root, fragment: next }).children[0]+ ).toMatchObject({+ type: "template",+ name: "Card",+ props: [+ { name: "tone", value: "loud" },+ { name: "legacy", value: "authored" },+ ],+ });++ next.instances.find(({ id }) => id === "template-heading")!.children = [+ { type: "text", value: "Changed internal" },+ ];+ expect(() => reconcileMdxAuthoredContent({ root, fragment: next })).toThrow(+ "Expanded template internals"+ );++ expect(+ reconcileMdxAuthoredContent({+ root,+ fragment: {+ ...root.fragment,+ children: [],+ instances: [],+ props: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ },+ }).children+ ).toEqual([]);+ });++ test("canonicalizes a legacy JSX prop name during serialization", async () => {+ const document = await parseMdxDocument({+ source: '<ws.element ws:name="Card" class="old" />',+ });+ const authoredTemplate = document.children[0];+ if (authoredTemplate?.type !== "template") {+ throw new Error("Expected authored template");+ }+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: {+ templates: [+ {+ type: "resolved-template",+ reference: {+ type: "resolved-template",+ path: [0],+ templateName: "Card",+ templateInstanceId: "card-template",+ props: authoredTemplate.props,+ },+ fragment: {+ children: [{ type: "id", value: "card" }],+ instances: [+ {+ type: "instance",+ id: "card",+ component: "Card",+ children: [],+ },+ ],+ props: [+ {+ id: "card:class",+ instanceId: "card",+ name: "class",+ type: "string",+ value: "old",+ },+ ],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ },+ editablePropNames: ["class"],+ jsxPropContext: htmlJsxPropContext,+ propNameMappings: [+ { jsxPropName: "class", instancePropName: "class" },+ ],+ ignoredJsxPropNames: [],+ },+ ],+ diagnostics: [],+ dependencies: { templateNames: ["Card"], templates: [] },+ },+ });+ const next = structuredClone(root.fragment);+ const classProp = next.props[0];+ if (classProp?.type !== "string") {+ throw new Error("Expected class prop");+ }+ classProp.value = "new";++ expect(await serializeMdxAuthoredContent({ root, fragment: next })).toBe(+ '<ws.element ws:name="Card" className="new" />\n'+ );+ });++ test("persists a new arbitrary static prop with its canonical JSX name", async () => {+ const document = await parseMdxDocument({+ source: '<ws.element ws:name="Card" />',+ });+ const authoredTemplate = document.children[0];+ if (authoredTemplate?.type !== "template") {+ throw new Error("Expected authored template");+ }+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: {+ templates: [+ {+ type: "resolved-template",+ reference: {+ type: "resolved-template",+ path: [0],+ templateName: "Card",+ templateInstanceId: "card-template",+ props: [],+ },+ fragment: {+ children: [{ type: "id", value: "card" }],+ instances: [+ {+ type: "instance",+ id: "card",+ component: "Card",+ tag: "div",+ children: [],+ },+ ],+ props: [],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ },+ editablePropNames: [],+ jsxPropContext: htmlJsxPropContext,+ propNameMappings: [],+ ignoredJsxPropNames: [],+ },+ ],+ diagnostics: [],+ dependencies: { templateNames: ["Card"], templates: [] },+ },+ });+ const next = structuredClone(root.fragment);+ next.props.push({+ id: "card:class",+ instanceId: next.instances[0]!.id,+ name: "class",+ type: "string",+ value: "new",+ });++ expect(await serializeMdxAuthoredContent({ root, fragment: next })).toBe(+ '<ws.element ws:name="Card" className="new" />\n'+ );++ const invalid = structuredClone(root.fragment);+ invalid.props.push({+ id: "card:class",+ instanceId: invalid.instances[0]!.id,+ name: "class",+ type: "number",+ value: 1,+ });+ await expect(+ serializeMdxAuthoredContent({ root, fragment: invalid })+ ).rejects.toThrow(+ "Expanded template props cannot be represented losslessly in MDX"+ );+ });++ test("rejects props that collide after JSX name conversion", async () => {+ const fragment = createCodeTextFragment();+ const instanceId = fragment.instances[0]!.id;+ fragment.props.push(+ {+ id: "code-class",+ instanceId,+ name: "class",+ type: "string",+ value: "standard",+ },+ {+ id: "code-class-name",+ instanceId,+ name: "className",+ type: "string",+ value: "custom",+ }+ );++ await expect(+ serializeMdxTemplateInsertion({+ identity,+ fragment,+ templateName: "CodeText",+ })+ ).rejects.toThrow('Multiple properties map to "className"');+ });++ test("persists direct text edits on a template root", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:name="Heading" />`,+ });+ const authoredTemplate = document.children[0];+ if (authoredTemplate?.type !== "template") {+ throw new Error("Expected authored template");+ }+ const templateFragment: WebstudioFragment = {+ children: [{ type: "id", value: "template-heading" }],+ instances: [+ {+ type: "instance",+ id: "template-heading",+ component: elementComponent,+ tag: "h2",+ children: [{ type: "text", value: "Default heading" }],+ },+ ],+ props: [],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ };+ const templateMaterialization = {+ templates: [+ {+ type: "resolved-template" as const,+ reference: {+ type: "resolved-template" as const,+ path: [0],+ templateName: "Heading",+ templateInstanceId: "heading-template",+ props: authoredTemplate.props,+ },+ fragment: templateFragment,+ editablePropNames: [],+ jsxPropContext: htmlJsxPropContext,+ propNameMappings: [],+ ignoredJsxPropNames: [],+ },+ ],+ diagnostics: [],+ dependencies: { templateNames: ["Heading"], templates: [] },+ };+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization,+ });+ const next = structuredClone(root.fragment);+ next.instances[0]!.children = [{ type: "text", value: "Authored heading" }];++ const nextDocument = reconcileMdxAuthoredContent({+ root,+ fragment: next,+ });+ expect(nextDocument.children[0]).toMatchObject({+ type: "template",+ name: "Heading",+ children: [{ type: "text", value: "Authored heading" }],+ });+ const persistedDocument = await parseMdxDocument({+ source: serializeMdxDocument(nextDocument),+ });++ const rematerialized = materializeMdxAuthoredContent({+ identity,+ document: persistedDocument,+ templateMaterialization,+ });+ expect(rematerialized.fragment.instances[0]?.children).toEqual([+ { type: "text", value: "Authored heading" },+ ]);+ });+});diff --git a/packages/project-build/src/runtime/mdx-authored-content.ts b/packages/project-build/src/runtime/mdx-authored-content.tsnew file mode 100644index 0000000000..ba77c0efd0--- /dev/null+++ b/packages/project-build/src/runtime/mdx-authored-content.ts@@ -0,0 +1,2265 @@+import equal from "fast-deep-equal";+import { elementsByTag } from "@webstudio-is/html-data";+import type { AssetValueReference } from "@webstudio-is/content-engine";+import type {+ MdxAuthoredNode,+ MdxAuthoredProp,+ MdxDocument,+ MdxMode,+} from "@webstudio-is/content-engine/mdx";+import {+ preferMarkdownSyntax,+ serializeMdxDocument,+} from "@webstudio-is/content-engine/mdx";+import {+ assertUniqueAttributeNames,+ mapAttributeNames,+} from "@webstudio-is/content-engine/jsx-attributes";+import {+ elementComponent,+ getStyleDeclKey,+ type ContentBlockExternalContentIdentity,+ type Instance,+ type Prop,+ type WebstudioFragment,+} from "@webstudio-is/sdk";+import {+ createMdxScopeIdGenerator,+ type MaterializedMdxTemplate,+ type MdxJsxPropContext,+ type MdxTemplateMaterialization,+} from "./mdx-materialization";+import { createEmptyWebstudioFragment } from "./component-template";+import {+ createWebstudioDataFromFragment,+ extractWebstudioFragment,+} from "./fragment";+import {+ getDerivedMdxComponentPropIds,+ materializeMdxComponent,+ normalizeMdxComponentProps,+ serializeMdxComponent,+ serializeMdxComponentFallback,+} from "./mdx-component-adapters";+import {+ parseMdxStaticProp,+ serializeMdxStaticProp,+ type MdxStaticPropType,+} from "./mdx-static-props";+import { getHtmlAttributeType } from "./html-attribute-utils";+import { getMdxPropValuePathKey } from "./mdx-asset-references";++type AuthoredElementProvenance = Readonly<{+ type: "element";+ path: readonly number[];+ instanceId: Instance["id"];+ assetProps: readonly Readonly<{+ propId: Prop["id"];+ assetId: string;+ authoredValue: string;+ }>[];+}>;++type AuthoredComponentProvenance = Readonly<{+ type: "component";+ path: readonly number[];+ instanceId: Instance["id"];+ assetProps: AuthoredElementProvenance["assetProps"];+}>;++type TemplateProvenance = Readonly<{+ type: "template";+ path: readonly number[];+ instanceId: Instance["id"];+ editableTextChildren: boolean;+ editablePropNames: readonly string[];+ jsxPropContext: MdxJsxPropContext;+ propNameMappings: readonly Readonly<{+ jsxPropName: string;+ instancePropName: string;+ }>[];+ preservedJsxPropNames?: readonly string[];+ ignoredJsxPropNames: readonly string[];+ expandedInstanceIds: readonly Instance["id"][];+ assetProps: AuthoredElementProvenance["assetProps"];+ namespaceKeys: readonly Readonly<{+ namespace: UnsupportedNamespace;+ key: string;+ }>[];+}>;++type UnsupportedNamespace = (typeof unsupportedNamespaces)[number];++const isStaticProp = (+ prop: Prop+): prop is Prop & { type: "string" | "number" | "boolean" } =>+ prop.type === "string" || prop.type === "number" || prop.type === "boolean";++const isEditableTemplateProp = ({+ provenance,+ prop,+}: {+ provenance: TemplateProvenance;+ prop: Prop;+}) => {+ const expectedTypes = provenance.jsxPropContext.propTypes.flatMap(+ ({ name, type }) => (name === prop.name ? [type] : [])+ );+ if (provenance.editablePropNames.includes(prop.name)) {+ if (prop.type === "asset") {+ return true;+ }+ return (+ expectedTypes.length === 0 ||+ (isStaticProp(prop) && expectedTypes.includes(prop.type))+ );+ }+ if (+ isStaticProp(prop) === false ||+ provenance.jsxPropContext.componentPropNames.includes(prop.name)+ ) {+ return false;+ }+ const { htmlTag } = provenance.jsxPropContext;+ const htmlType =+ htmlTag === undefined+ ? undefined+ : getHtmlAttributeType({ tag: htmlTag, name: prop.name });+ return htmlType === undefined || htmlType === prop.type;+};++const unsupportedNamespaces = [+ "assets",+ "dataSources",+ "resources",+ "breakpoints",+ "styleSourceSelections",+ "styleSources",+ "styles",+] as const;++const getNamespaceRecordKey = (+ namespace: UnsupportedNamespace,+ record: WebstudioFragment[UnsupportedNamespace][number]+) => {+ if (namespace === "styleSourceSelections") {+ return (record as WebstudioFragment["styleSourceSelections"][number])+ .instanceId;+ }+ if (namespace === "styles") {+ return getStyleDeclKey(record as WebstudioFragment["styles"][number]);+ }+ return (record as { id: string }).id;+};++const getUnsupportedNamespaceKeys = (fragments: readonly WebstudioFragment[]) =>+ Object.fromEntries(+ unsupportedNamespaces.map((namespace) => [+ namespace,+ new Set(+ fragments.flatMap((fragment) =>+ fragment[namespace].map((record) =>+ getNamespaceRecordKey(namespace, record)+ )+ )+ ),+ ])+ ) as Record<UnsupportedNamespace, Set<string>>;++export type MdxAuthoredContentProvenance = Readonly<{+ nodes: readonly (+ | AuthoredComponentProvenance+ | AuthoredElementProvenance+ | TemplateProvenance+ )[];+ unresolvedTemplates: readonly Readonly<{+ path: readonly number[];+ markerId: string;+ templateName: string;+ }>[];+}>;++export type MaterializedMdxAuthoredContentRoot = Readonly<{+ identity: ContentBlockExternalContentIdentity;+ fragment: WebstudioFragment;+ document: MdxDocument;+ resolvedFrontmatter?: Readonly<Record<string, unknown>>;+ provenance: MdxAuthoredContentProvenance;+ assetReferenceValues?: ReadonlyMap<string, string>;+}>;++const isMdxValueEqual = (left: unknown, right: unknown): boolean => {+ if (left === right) {+ return true;+ }+ if (Array.isArray(left) || Array.isArray(right)) {+ return (+ Array.isArray(left) &&+ Array.isArray(right) &&+ left.length === right.length &&+ left.every((value, index) => isMdxValueEqual(value, right[index]))+ );+ }+ if (+ typeof left === "object" &&+ left !== null &&+ typeof right === "object" &&+ right !== null+ ) {+ const leftRecord = left as Record<string, unknown>;+ const rightRecord = right as Record<string, unknown>;+ const keys = new Set([+ ...Object.keys(leftRecord),+ ...Object.keys(rightRecord),+ ]);+ keys.delete("sourceRange");+ return Array.from(keys).every(+ (key) =>+ key in leftRecord &&+ key in rightRecord &&+ isMdxValueEqual(leftRecord[key], rightRecord[key])+ );+ }+ return false;+};++const getSourceRangeKey = (node: MdxAuthoredNode) => {+ const range = node.sourceRange;+ if (range === undefined) {+ return;+ }+ const pointKey = (point: typeof range.start) =>+ point.offset === undefined+ ? `${point.line}:${point.column}`+ : String(point.offset);+ return `${pointKey(range.start)}-${pointKey(range.end)}`;+};++const mergeLocalProps = ({+ base,+ local,+ latest,+}: {+ base: readonly MdxAuthoredProp[];+ local: readonly MdxAuthoredProp[];+ latest: readonly MdxAuthoredProp[];+}) => {+ const baseByName = new Map(base.map((prop) => [prop.name, prop]));+ const localByName = new Map(local.map((prop) => [prop.name, prop]));+ const result = latest.flatMap((prop) => {+ const baseProp = baseByName.get(prop.name);+ if (baseProp === undefined) {+ return [prop];+ }+ const localProp = localByName.get(prop.name);+ if (localProp === undefined) {+ return [];+ }+ localByName.delete(prop.name);+ return [isMdxValueEqual(baseProp, localProp) ? prop : localProp];+ });+ for (const prop of localByName.values()) {+ const baseProp = baseByName.get(prop.name);+ if (baseProp === undefined || isMdxValueEqual(baseProp, prop) === false) {+ result.push(prop);+ }+ }+ return result;+};++const mergeLocalNode = ({+ base,+ local,+ latest,+}: {+ base: MdxAuthoredNode;+ local: MdxAuthoredNode;+ latest: MdxAuthoredNode;+}): MdxAuthoredNode => {+ if (isMdxValueEqual(base, local)) {+ return latest;+ }+ if (+ base.type !== local.type ||+ base.type !== latest.type ||+ (base.type === "element" &&+ (local.type !== "element" ||+ latest.type !== "element" ||+ base.syntax !== local.syntax ||+ base.syntax !== latest.syntax))+ ) {+ return local;+ }+ if (+ base.type === "text" ||+ base.type === "comment" ||+ base.type === "opaque"+ ) {+ return local;+ }+ if (local.type === "text" || latest.type === "text") {+ return local;+ }+ if (+ "children" in base === false ||+ "children" in local === false ||+ "children" in latest === false+ ) {+ return local;+ }+ const children = mergeLocalChildren({+ base: base.children,+ local: local.children,+ latest: latest.children,+ });+ const props = mergeLocalProps({+ base: base.props,+ local: local.props,+ latest: latest.props,+ });+ const merged = { ...latest, props, children } as MdxAuthoredNode;+ const mutableFields = [+ "tag",+ "name",+ "mdxMode",+ "markdownListItem",+ "preserveTextWhitespace",+ ] as const;+ const baseRecord = base as unknown as Record<string, unknown>;+ const localRecord = local as unknown as Record<string, unknown>;+ const mergedRecord = merged as unknown as Record<string, unknown>;+ for (const field of mutableFields) {+ if (isMdxValueEqual(baseRecord[field], localRecord[field]) === false) {+ mergedRecord[field] = localRecord[field];+ }+ }+ return merged;+};++const getNodeShape = (node: MdxAuthoredNode) => {+ if (node.type === "element") {+ return `${node.type}:${node.syntax}:${node.tag}`;+ }+ if (node.type === "template") {+ return `${node.type}:${node.name}`;+ }+ return node.type;+};++const alignNodesToBase = (+ base: readonly MdxAuthoredNode[],+ candidates: readonly MdxAuthoredNode[]+) => {+ const aligned = new Map<number, number>();+ const used = new Set<number>();+ const align = (+ accept: (baseIndex: number, candidateIndex: number) => boolean+ ) => {+ for (const [baseIndex] of base.entries()) {+ if (aligned.has(baseIndex)) {+ continue;+ }+ const candidateIndex = candidates+ .map((_, index) => index)+ .filter((index) => used.has(index) === false)+ .filter((index) => accept(baseIndex, index))+ .sort(+ (left, right) =>+ Math.abs(left - baseIndex) - Math.abs(right - baseIndex)+ )[0];+ if (candidateIndex !== undefined) {+ aligned.set(baseIndex, candidateIndex);+ used.add(candidateIndex);+ }+ }+ };+ align((baseIndex, candidateIndex) =>+ isMdxValueEqual(base[baseIndex], candidates[candidateIndex])+ );+ align(+ (baseIndex, candidateIndex) =>+ getSourceRangeKey(base[baseIndex]) !== undefined &&+ getSourceRangeKey(base[baseIndex]) ===+ getSourceRangeKey(candidates[candidateIndex])+ );+ align(+ (baseIndex, candidateIndex) =>+ getNodeShape(base[baseIndex]) === getNodeShape(candidates[candidateIndex])+ );+ align(+ (baseIndex, candidateIndex) =>+ base[baseIndex].type === candidates[candidateIndex].type+ );+ return { aligned, used };+};++const mergeLocalChildren = ({+ base,+ local,+ latest,+}: {+ base: readonly MdxAuthoredNode[];+ local: readonly MdxAuthoredNode[];+ latest: readonly MdxAuthoredNode[];+}): MdxAuthoredNode[] => {+ const localAlignment = alignNodesToBase(base, local);+ const latestAlignment = alignNodesToBase(base, latest);+ const localBaseIndexes = Array.from(localAlignment.aligned)+ .sort((left, right) => left[1] - right[1])+ .map(([baseIndex]) => baseIndex);+ const localStructureIsUnchanged =+ localAlignment.used.size === local.length &&+ localBaseIndexes.length === base.length &&+ localBaseIndexes.every((baseIndex, index) => baseIndex === index);++ if (localStructureIsUnchanged) {+ const latestBaseByIndex = new Map(+ Array.from(latestAlignment.aligned, ([baseIndex, latestIndex]) => [+ latestIndex,+ baseIndex,+ ])+ );+ return latest.flatMap((node, latestIndex) => {+ const baseIndex = latestBaseByIndex.get(latestIndex);+ if (baseIndex === undefined) {+ return [node];+ }+ const localIndex = localAlignment.aligned.get(baseIndex);+ if (localIndex === undefined) {+ return [];+ }+ return [+ mergeLocalNode({+ base: base[baseIndex],+ local: local[localIndex],+ latest: node,+ }),+ ];+ });+ }++ const latestByBaseIndex = new Map(+ Array.from(latestAlignment.aligned, ([baseIndex, latestIndex]) => [+ baseIndex,+ latest[latestIndex],+ ])+ );+ const localBaseByIndex = new Map(+ Array.from(localAlignment.aligned, ([baseIndex, localIndex]) => [+ localIndex,+ baseIndex,+ ])+ );+ const entries: Array<{ node: MdxAuthoredNode; baseIndex?: number }> = [];+ for (const [localIndex, localNode] of local.entries()) {+ const baseIndex = localBaseByIndex.get(localIndex);+ if (baseIndex === undefined) {+ entries.push({ node: localNode });+ continue;+ }+ const latestNode = latestByBaseIndex.get(baseIndex);+ if (latestNode === undefined) {+ if (isMdxValueEqual(base[baseIndex], localNode) === false) {+ entries.push({ node: localNode, baseIndex });+ }+ continue;+ }+ entries.push({+ baseIndex,+ node: mergeLocalNode({+ base: base[baseIndex],+ local: localNode,+ latest: latestNode,+ }),+ });+ }++ const latestBaseByIndex = new Map(+ Array.from(latestAlignment.aligned, ([baseIndex, latestIndex]) => [+ latestIndex,+ baseIndex,+ ])+ );+ for (const [latestIndex, node] of latest.entries()) {+ if (latestAlignment.used.has(latestIndex)) {+ continue;+ }+ const nextBaseIndex = Array.from(latestBaseByIndex)+ .filter(([index]) => index > latestIndex)+ .sort((left, right) => left[0] - right[0])+ .map(([, baseIndex]) => baseIndex)+ .find((baseIndex) =>+ entries.some((entry) => entry.baseIndex === baseIndex)+ );+ const insertionIndex =+ nextBaseIndex === undefined+ ? entries.length+ : entries.findIndex((entry) => entry.baseIndex === nextBaseIndex);+ entries.splice(insertionIndex === -1 ? entries.length : insertionIndex, 0, {+ node,+ });+ }+ return entries.map(({ node }) => node);+};++const mergeLocalMdxDocument = ({+ base,+ local,+ latest,+}: {+ base: MdxDocument;+ local: MdxDocument;+ latest: MdxDocument;+}): MdxDocument => ({+ frontmatter: isMdxValueEqual(base.frontmatter, local.frontmatter)+ ? latest.frontmatter+ : local.frontmatter,+ children: mergeLocalChildren({+ base: base.children,+ local: local.children,+ latest: latest.children,+ }),+});++export class MdxAuthoredContentConflictError extends Error {+ name = "MdxAuthoredContentConflictError";+}++const pathKey = (path: readonly number[]) => path.join(".");++const mergeRecords = <Record extends { id: string }>(+ target: Record[],+ source: readonly Record[],+ namespace: string,+ allowEqual = false+) => {+ const records = new Map(target.map((record) => [record.id, record]));+ for (const record of source) {+ const existing = records.get(record.id);+ if (existing !== undefined && (!allowEqual || !equal(existing, record))) {+ throw new Error(+ `Materialized MDX ${namespace} id "${record.id}" collides`+ );+ }+ if (existing === undefined) {+ records.set(record.id, record);+ target.push(record);+ }+ }+};++const mergeTemplateFragment = (+ target: WebstudioFragment,+ source: WebstudioFragment+) => {+ mergeRecords(target.instances, source.instances, "instance");+ mergeRecords(target.props, source.props, "prop");+ mergeRecords(target.assets, source.assets, "asset", true);+ mergeRecords(target.dataSources, source.dataSources, "data source");+ mergeRecords(target.resources, source.resources, "resource");+ mergeRecords(target.breakpoints, source.breakpoints, "breakpoint", true);+ mergeRecords(target.styleSources, source.styleSources, "style source", true);+ const selectedInstanceIds = new Set(+ target.styleSourceSelections.map(({ instanceId }) => instanceId)+ );+ for (const selection of source.styleSourceSelections) {+ if (selectedInstanceIds.has(selection.instanceId)) {+ throw new Error(+ `Materialized MDX style selection id "${selection.instanceId}" collides`+ );+ }+ selectedInstanceIds.add(selection.instanceId);+ target.styleSourceSelections.push(selection);+ }+ const styles = new Map(+ target.styles.map((style) => [getStyleDeclKey(style), style])+ );+ for (const style of source.styles) {+ const key = getStyleDeclKey(style);+ const existing = styles.get(key);+ if (existing !== undefined && !equal(existing, style)) {+ throw new Error(`Materialized MDX style "${key}" collides`);+ }+ if (existing === undefined) {+ styles.set(key, style);+ target.styles.push(style);+ }+ }+};++const createLiteralProp = ({+ id,+ instanceId,+ prop,+ assetId,+ type,+}: {+ id: string;+ instanceId: string;+ prop: MdxAuthoredProp;+ assetId?: string;+ type?: MdxStaticPropType;+}): Prop => {+ if (assetId !== undefined) {+ return {+ id,+ instanceId,+ name: prop.name,+ type: "asset",+ value: assetId,+ };+ }+ const parsed =+ type === undefined ? undefined : parseMdxStaticProp({ prop, type });+ if (parsed !== undefined) {+ return { id, instanceId, name: prop.name, ...parsed };+ }+ return prop.value === true+ ? {+ id,+ instanceId,+ name: prop.name,+ type: "boolean",+ value: true,+ }+ : {+ id,+ instanceId,+ name: prop.name,+ type: "string",+ value: prop.value,+ };+};++const getSingleTemplateRootId = (template: MaterializedMdxTemplate) => {+ if (+ template.type !== "resolved-template" ||+ template.fragment.children.length !== 1 ||+ template.fragment.children[0]?.type !== "id"+ ) {+ throw new Error("Resolved MDX template must materialize one root instance");+ }+ return template.fragment.children[0].value;+};++export const materializeMdxAuthoredContent = ({+ identity,+ document,+ templateMaterialization,+ assetReferences = [],+ assetReferenceValues,+ createUnresolvedTemplateInstance,+}: {+ identity: ContentBlockExternalContentIdentity;+ document: MdxDocument;+ templateMaterialization: MdxTemplateMaterialization;+ assetReferences?: readonly AssetValueReference[];+ assetReferenceValues?: ReadonlyMap<string, string>;+ createUnresolvedTemplateInstance?: (input: {+ markerId: string;+ templateName: string;+ }) => Instance;+}): MaterializedMdxAuthoredContentRoot => {+ const fragment = createEmptyWebstudioFragment();+ const nodes: MdxAuthoredContentProvenance["nodes"][number][] = [];+ const templatesByPath = new Map(+ templateMaterialization.templates.map((template) => [+ pathKey(template.reference.path),+ template,+ ])+ );+ const assetReferenceByPath = new Map(+ assetReferences.map((reference) => [+ reference.path.map(String).join("/"),+ reference,+ ])+ );+ const visit = (+ authoredNodes: readonly MdxAuthoredNode[],+ parentPath: readonly number[]+ ): Instance["children"] => {+ const children: Instance["children"] = [];+ for (const [index, node] of authoredNodes.entries()) {+ const path = [...parentPath, index];+ if (node.type === "text") {+ children.push({ type: "text", value: node.value });+ continue;+ }+ if (node.type === "comment") {+ continue;+ }+ if (node.type === "opaque") {+ continue;+ }+ if (node.type === "template") {+ const template = templatesByPath.get(pathKey(path));+ if (template === undefined) {+ continue;+ }+ if (template.type === "unresolved-template") {+ const placeholder = createUnresolvedTemplateInstance?.({+ markerId: template.markerId,+ templateName: template.reference.templateName,+ });+ if (placeholder !== undefined) {+ fragment.instances.push(placeholder);+ children.push({ type: "id", value: placeholder.id });+ }+ continue;+ }+ const rootId = getSingleTemplateRootId(template);+ mergeTemplateFragment(fragment, template.fragment);+ const rootInstance = fragment.instances.find(({ id }) => id === rootId);+ if (rootInstance === undefined) {+ throw new Error("Resolved MDX template root is missing");+ }+ const editableTextChildren = rootInstance.children.every(+ (child) => child.type === "text"+ );+ if (+ editableTextChildren &&+ node.children.length > 0 &&+ node.children.every(+ (child) => child.type === "text" || child.type === "comment"+ )+ ) {+ rootInstance.children = visit(node.children, path);+ }+ const ignored = new Set(template.ignoredJsxPropNames);+ const instancePropNameByJsxName = new Map(+ template.propNameMappings.map((mapping) => [+ mapping.jsxPropName,+ mapping.instancePropName,+ ])+ );+ const editablePropNames = new Set([+ ...node.props.flatMap(({ name }) => {+ const instancePropName = instancePropNameByJsxName.get(name);+ return instancePropName === undefined ? [] : [instancePropName];+ }),+ ...template.editablePropNames,+ ]);+ const assetProps: AuthoredElementProvenance["assetProps"][number][] =+ [];+ node.props.forEach((prop, propIndex) => {+ const assetReference = assetReferenceByPath.get(+ getMdxPropValuePathKey({ nodePath: path, propIndex })+ );+ if (assetReference === undefined) {+ return;+ }+ const instancePropName =+ instancePropNameByJsxName.get(prop.name) ?? prop.name;+ const materializedProp = fragment.props.find(+ (candidate) =>+ candidate.instanceId === rootId &&+ candidate.name === instancePropName &&+ candidate.type === "asset" &&+ candidate.value === assetReference.assetId+ );+ if (+ materializedProp !== undefined &&+ typeof prop.value === "string"+ ) {+ assetProps.push({+ propId: materializedProp.id,+ assetId: assetReference.assetId,+ authoredValue: prop.value,+ });+ }+ });+ nodes.push({+ type: "template",+ path,+ instanceId: rootId,+ editableTextChildren,+ editablePropNames: Array.from(editablePropNames).filter(+ (name) =>+ Array.from(instancePropNameByJsxName).some(+ ([jsxName, instanceName]) =>+ instanceName === name && ignored.has(jsxName)+ ) === false+ ),+ jsxPropContext: template.jsxPropContext,+ propNameMappings: template.propNameMappings,+ preservedJsxPropNames: template.preservedJsxPropNames,+ ignoredJsxPropNames: template.ignoredJsxPropNames,+ expandedInstanceIds: template.fragment.instances.map(({ id }) => id),+ assetProps,+ namespaceKeys: unsupportedNamespaces.flatMap((namespace) =>+ template.fragment[namespace].map((record) => ({+ namespace,+ key: getNamespaceRecordKey(namespace, record),+ }))+ ),+ });+ children.push({ type: "id", value: rootId });+ continue;+ }++ const materializedComponent = materializeMdxComponent(node);+ if (materializedComponent !== undefined) {+ const createId = createMdxScopeIdGenerator({ identity, path });+ const instanceId = createId();+ fragment.instances.push({+ type: "instance",+ id: instanceId,+ component: materializedComponent.component,+ children: materializedComponent.children,+ });+ const assetProps: AuthoredElementProvenance["assetProps"][number][] =+ [];+ for (const {+ prop,+ source,+ requiresAssetReference,+ } of materializedComponent.props) {+ const propId = createId();+ const assetReference =+ source === undefined+ ? undefined+ : assetReferenceByPath.get(+ getMdxPropValuePathKey({+ nodePath: [...path, ...source.nodePath],+ propIndex: source.propIndex,+ })+ );+ if (requiresAssetReference && assetReference === undefined) {+ continue;+ }+ fragment.props.push(+ createLiteralProp({+ id: propId,+ instanceId,+ prop,+ assetId: assetReference?.assetId,+ })+ );+ if (assetReference !== undefined && typeof prop.value === "string") {+ assetProps.push({+ propId,+ assetId: assetReference.assetId,+ authoredValue: prop.value,+ });+ }+ }+ nodes.push({ type: "component", path, instanceId, assetProps });+ children.push({ type: "id", value: instanceId });+ continue;+ }++ const createId = createMdxScopeIdGenerator({ identity, path });+ const instanceId = createId();+ const instance: Instance = {+ type: "instance",+ id: instanceId,+ component: elementComponent,+ tag: node.tag,+ children: visit(node.children, path),+ };+ fragment.instances.push(instance);+ const assetProps: AuthoredElementProvenance["assetProps"][number][] = [];+ node.props.forEach((prop, propIndex) => {+ const propId = createId();+ const assetReference = assetReferenceByPath.get(+ getMdxPropValuePathKey({ nodePath: path, propIndex })+ );+ fragment.props.push(+ createLiteralProp({+ id: propId,+ instanceId,+ prop,+ assetId: assetReference?.assetId,+ type: getHtmlAttributeType({ tag: node.tag, name: prop.name }),+ })+ );+ if (assetReference !== undefined && typeof prop.value === "string") {+ assetProps.push({+ propId,+ assetId: assetReference.assetId,+ authoredValue: prop.value,+ });+ }+ });+ nodes.push({ type: "element", path, instanceId, assetProps });+ children.push({ type: "id", value: instanceId });+ }+ return children;+ };++ fragment.children = visit(document.children, []);+ const unresolvedTemplates = templateMaterialization.templates.flatMap(+ (template) =>+ template.type === "unresolved-template"+ ? [+ {+ path: template.reference.path,+ markerId: template.markerId,+ templateName: template.reference.templateName,+ },+ ]+ : []+ );+ return {+ identity,+ fragment,+ document,+ provenance: { nodes, unresolvedTemplates },+ assetReferenceValues,+ };+};++/**+ * Advances an authored root to a newly materialized document without replacing+ * the equivalent fragment that is already being edited. The materialized root+ * supplies the new document provenance; the live fragment supplies stable IDs.+ */+export const adoptMdxAuthoredContentFragment = ({+ root,+ fragment,+}: {+ root: MaterializedMdxAuthoredContentRoot;+ fragment: WebstudioFragment;+}): MaterializedMdxAuthoredContentRoot => {+ const sourceInstances = new Map(+ root.fragment.instances.map((instance) => [instance.id, instance])+ );+ const targetInstances = new Map(+ fragment.instances.map((instance) => [instance.id, instance])+ );+ const instanceIds = new Map<string, string>();++ const pairChildren = (+ source: Instance["children"],+ target: Instance["children"]+ ) => {+ if (source.length !== target.length) {+ throw new Error(+ `Live MDX fragment has ${target.length} children where its authored document has ${source.length}`+ );+ }+ source.forEach((child, index) => {+ const targetChild = target[index];+ if (targetChild === undefined || child.type !== targetChild.type) {+ throw new Error(+ "Live MDX fragment does not match its authored document"+ );+ }+ if (child.type === "id" && targetChild.type === "id") {+ pairInstance(child.value, targetChild.value);+ }+ });+ };+ const pairInstance = (sourceId: string, targetId: string) => {+ const mappedId = instanceIds.get(sourceId);+ if (mappedId !== undefined) {+ if (mappedId !== targetId) {+ throw new Error("Live MDX fragment reuses an authored instance");+ }+ return;+ }+ const source = sourceInstances.get(sourceId);+ const target = targetInstances.get(targetId);+ if (+ source === undefined ||+ target === undefined ||+ source.component !== target.component ||+ source.tag !== target.tag+ ) {+ throw new Error("Live MDX fragment does not match its authored document");+ }+ instanceIds.set(sourceId, targetId);+ pairChildren(source.children, target.children);+ };+ pairChildren(root.fragment.children, fragment.children);+ if (+ instanceIds.size !== root.fragment.instances.length ||+ instanceIds.size !== fragment.instances.length+ ) {+ throw new Error("Live MDX fragment contains unreachable instances");+ }++ const propIds = new Map<string, string>();+ const unusedTargetProps = new Set(fragment.props.map(({ id }) => id));+ for (const source of root.fragment.props) {+ const targetInstanceId = instanceIds.get(source.instanceId);+ const target = fragment.props.find(+ (candidate) =>+ unusedTargetProps.has(candidate.id) &&+ candidate.instanceId === targetInstanceId &&+ candidate.name === source.name &&+ candidate.type === source.type+ );+ if (target === undefined) {+ throw new Error("Live MDX fragment props do not match its document");+ }+ propIds.set(source.id, target.id);+ unusedTargetProps.delete(target.id);+ }+ if (unusedTargetProps.size > 0) {+ throw new Error("Live MDX fragment contains unexpected props");+ }++ const namespaceKeys = new Map<string, string>();+ for (const namespace of unsupportedNamespaces) {+ const sourceRecords = root.fragment[namespace];+ const targetRecords = fragment[namespace];+ if (sourceRecords.length !== targetRecords.length) {+ throw new Error(+ `Live MDX fragment ${namespace} do not match its document`+ );+ }+ sourceRecords.forEach((source, index) => {+ const target = targetRecords[index];+ if (target === undefined) {+ throw new Error(+ `Live MDX fragment ${namespace} do not match its document`+ );+ }+ namespaceKeys.set(+ `${namespace}:${getNamespaceRecordKey(namespace, source)}`,+ getNamespaceRecordKey(namespace, target)+ );+ });+ }++ const mapInstanceId = (id: string) => {+ const mapped = instanceIds.get(id);+ if (mapped === undefined) {+ throw new Error(`Live MDX fragment is missing instance "${id}"`);+ }+ return mapped;+ };+ const mapAssetProps = (assetProps: AuthoredElementProvenance["assetProps"]) =>+ assetProps.map((assetProp) => {+ const propId = propIds.get(assetProp.propId);+ if (propId === undefined) {+ throw new Error(+ `Live MDX fragment is missing prop "${assetProp.propId}"`+ );+ }+ return { ...assetProp, propId };+ });+ return {+ ...root,+ fragment,+ provenance: {+ ...root.provenance,+ nodes: root.provenance.nodes.map((node) =>+ node.type === "element"+ ? {+ ...node,+ instanceId: mapInstanceId(node.instanceId),+ assetProps: mapAssetProps(node.assetProps),+ }+ : node.type === "template"+ ? {+ ...node,+ instanceId: mapInstanceId(node.instanceId),+ assetProps: mapAssetProps(node.assetProps),+ expandedInstanceIds:+ node.expandedInstanceIds.map(mapInstanceId),+ namespaceKeys: node.namespaceKeys.map((entry) => {+ const key = namespaceKeys.get(+ `${entry.namespace}:${entry.key}`+ );+ if (key === undefined) {+ throw new Error(+ `Live MDX fragment is missing ${entry.namespace} "${entry.key}"`+ );+ }+ return { ...entry, key };+ }),+ }+ : {+ ...node,+ instanceId: mapInstanceId(node.instanceId),+ assetProps: mapAssetProps(node.assetProps),+ }+ ),+ },+ };+};++const assertSupportedNamespaces = ({+ root,+ fragment,+ deletedTemplateRootIds,+}: {+ root: MaterializedMdxAuthoredContentRoot;+ fragment: WebstudioFragment;+ deletedTemplateRootIds: ReadonlySet<string>;+}) => {+ for (const namespace of unsupportedNamespaces) {+ if (namespace === "assets" && root.assetReferenceValues !== undefined) {+ const originalById = new Map(+ root.fragment.assets.map((asset) => [asset.id, asset])+ );+ const referencedAssetIds = new Set(+ fragment.props.flatMap((prop) =>+ prop.type === "asset" ? [prop.value] : []+ )+ );+ const assetIds = new Set<string>();+ for (const asset of fragment.assets) {+ const original = originalById.get(asset.id);+ if (+ assetIds.has(asset.id) ||+ (original === undefined+ ? referencedAssetIds.has(asset.id) === false ||+ root.assetReferenceValues.has(asset.id) === false+ : equal(original, asset) === false)+ ) {+ throw new Error(+ "Changes to assets cannot be represented losslessly in MDX"+ );+ }+ assetIds.add(asset.id);+ }+ if (+ Array.from(referencedAssetIds).some(+ (assetId) => assetIds.has(assetId) === false+ )+ ) {+ throw new Error(+ "Changes to assets cannot be represented losslessly in MDX"+ );+ }+ continue;+ }+ const removableKeys = new Set<string>();+ const requiredKeys = new Set<string>();+ for (const node of root.provenance.nodes) {+ if (node.type !== "template") {+ continue;+ }+ const keys = node.namespaceKeys.flatMap((entry) =>+ entry.namespace === namespace ? [entry.key] : []+ );+ const target = deletedTemplateRootIds.has(node.instanceId)+ ? removableKeys+ : requiredKeys;+ for (const key of keys) {+ target.add(key);+ }+ }+ for (const key of requiredKeys) {+ removableKeys.delete(key);+ }+ const originalByKey = new Map(+ root.fragment[namespace].map((record) => [+ getNamespaceRecordKey(namespace, record),+ record,+ ])+ );+ const nextKeys = fragment[namespace].map((record) => {+ const key = getNamespaceRecordKey(namespace, record);+ if (!equal(originalByKey.get(key), record)) {+ throw new Error(+ `Changes to ${namespace} cannot be represented losslessly in MDX`+ );+ }+ return key;+ });+ const nextKeySet = new Set(nextKeys);+ if (+ nextKeys.length !== nextKeySet.size ||+ Array.from(originalByKey.keys()).some(+ (key) => !nextKeySet.has(key) && !removableKeys.has(key)+ ) ||+ !equal(+ nextKeys,+ Array.from(originalByKey.keys()).filter((key) => nextKeySet.has(key))+ )+ ) {+ throw new Error(+ `Changes to ${namespace} cannot be represented losslessly in MDX`+ );+ }+ }+};++const toAuthoredProps = ({+ original,+ props,+ assetProps = [],+ assetReferenceValues,+}: {+ original: readonly MdxAuthoredProp[];+ props: readonly Prop[];+ assetProps?: AuthoredElementProvenance["assetProps"];+ assetReferenceValues?: ReadonlyMap<string, string>;+}) => {+ const values = new Map<string, string | true>();+ const assetPropsById = new Map(assetProps.map((prop) => [prop.propId, prop]));+ for (const prop of props) {+ if (values.has(prop.name)) {+ throw new Error(+ `Duplicate authored prop "${prop.name}" is not supported`+ );+ }+ const authoredProp = serializeMdxStaticProp(prop);+ if (authoredProp !== undefined) {+ values.set(authoredProp.name, authoredProp.value);+ } else if (prop.type === "asset") {+ const assetProp = assetPropsById.get(prop.id);+ if (assetProp?.assetId === prop.value) {+ values.set(prop.name, assetProp.authoredValue);+ continue;+ }+ const authoredValue = assetReferenceValues?.get(prop.value);+ if (authoredValue !== undefined) {+ values.set(prop.name, authoredValue);+ continue;+ }+ throw new Error(+ `Asset prop "${prop.name}" cannot be represented losslessly in MDX`+ );+ } else {+ throw new Error(+ `Prop "${prop.name}" cannot be represented losslessly in MDX`+ );+ }+ }+ const result: MdxAuthoredProp[] = [];+ for (const prop of original) {+ const value = values.get(prop.name);+ if (value !== undefined) {+ result.push({ name: prop.name, value });+ values.delete(prop.name);+ }+ }+ for (const [name, value] of values) {+ result.push({ name, value });+ }+ return result;+};++export const reconcileMdxAuthoredContent = ({+ root,+ fragment,+}: {+ root: MaterializedMdxAuthoredContentRoot;+ fragment: WebstudioFragment;+}): MdxDocument => {+ const deletedTemplateRootIds = new Set(+ root.provenance.nodes.flatMap((node) =>+ node.type === "template" &&+ fragment.instances.some(({ id }) => id === node.instanceId) === false+ ? [node.instanceId]+ : []+ )+ );+ assertSupportedNamespaces({ root, fragment, deletedTemplateRootIds });+ for (const [namespace, records] of [+ ["instance", fragment.instances],+ ["prop", fragment.props],+ ] as const) {+ const ids = new Set<string>();+ for (const { id } of records) {+ if (ids.has(id)) {+ throw new Error(`Duplicate authored ${namespace} id "${id}"`);+ }+ ids.add(id);+ }+ }+ const instanceById = new Map(+ fragment.instances.map((instance) => [instance.id, instance])+ );+ const originalInstanceById = new Map(+ root.fragment.instances.map((instance) => [instance.id, instance])+ );+ const indexPropsByInstanceId = (props: readonly Prop[]) => {+ const index = new Map<Instance["id"], Prop[]>();+ for (const prop of props) {+ const instanceProps = index.get(prop.instanceId) ?? [];+ instanceProps.push(prop);+ index.set(prop.instanceId, instanceProps);+ }+ return index;+ };+ const propsByInstanceId = indexPropsByInstanceId(fragment.props);+ const originalPropsByInstanceId = indexPropsByInstanceId(root.fragment.props);+ const provenanceById = new Map(+ root.provenance.nodes.map((node) => [node.instanceId, node])+ );+ const provenanceByPath = new Map(+ root.provenance.nodes.map((node) => [pathKey(node.path), node])+ );+ const originalNodeByPath = new Map<string, MdxAuthoredNode>();+ const originalPathByNode = new Map<MdxAuthoredNode, string>();+ const indexOriginal = (+ nodes: readonly MdxAuthoredNode[],+ parentPath: readonly number[]+ ) => {+ nodes.forEach((node, index) => {+ const path = [...parentPath, index];+ originalNodeByPath.set(pathKey(path), node);+ originalPathByNode.set(node, pathKey(path));+ if (+ node.type !== "text" &&+ node.type !== "comment" &&+ node.type !== "opaque"+ ) {+ indexOriginal(node.children, path);+ }+ });+ };+ indexOriginal(root.document.children, []);++ const templateByExpandedInstanceId = new Map(+ root.provenance.nodes.flatMap((node) =>+ node.type === "template"+ ? node.expandedInstanceIds.map((id) => [id, node] as const)+ : []+ )+ );+ const templateInternalIds = new Set(templateByExpandedInstanceId.keys());+ const derivedTemplatePropIds = new Set<Prop["id"]>();+ for (const node of root.provenance.nodes) {+ if (node.type !== "template") {+ continue;+ }+ for (const [instance, props] of [+ [+ instanceById.get(node.instanceId),+ propsByInstanceId.get(node.instanceId) ?? [],+ ],+ [+ originalInstanceById.get(node.instanceId),+ originalPropsByInstanceId.get(node.instanceId) ?? [],+ ],+ ] as const) {+ if (instance === undefined) {+ continue;+ }+ for (const propId of getDerivedMdxComponentPropIds({+ instance,+ instanceProps: props,+ })) {+ derivedTemplatePropIds.add(propId);+ }+ }+ }+ const editableTemplatePropIds = new Set<string>();+ for (const node of root.provenance.nodes) {+ if (node.type !== "template") {+ continue;+ }+ if (instanceById.has(node.instanceId) === false) {+ const expandedIds = new Set(node.expandedInstanceIds);+ if (+ fragment.instances.some(({ id }) => expandedIds.has(id)) ||+ fragment.props.some(({ instanceId }) => expandedIds.has(instanceId))+ ) {+ throw new Error(+ "A partially deleted template cannot be represented losslessly in MDX"+ );+ }+ continue;+ }+ for (const prop of root.fragment.props) {+ if (+ prop.instanceId === node.instanceId &&+ isEditableTemplateProp({ provenance: node, prop })+ ) {+ editableTemplatePropIds.add(prop.id);+ }+ }+ }+ for (const original of root.fragment.instances) {+ const template = templateByExpandedInstanceId.get(original.id);+ const next = instanceById.get(original.id);+ const isEditableTemplateText =+ template?.instanceId === original.id &&+ template.editableTextChildren &&+ next !== undefined &&+ next.children.every((child) => child.type === "text") &&+ equal({ ...next, children: original.children }, original);+ if (+ templateInternalIds.has(original.id) &&+ (template?.type !== "template" ||+ deletedTemplateRootIds.has(template.instanceId) === false) &&+ isEditableTemplateText === false+ ) {+ if (next === undefined || !equal(next, original)) {+ throw new Error(+ "Expanded template internals cannot be represented losslessly in MDX"+ );+ }+ }+ }+ const originalPropsById = new Map(+ root.fragment.props.map((prop) => [prop.id, prop])+ );+ const templateByRootId = new Map(+ root.provenance.nodes.flatMap((node) =>+ node.type === "template" ? [[node.instanceId, node] as const] : []+ )+ );+ for (const prop of fragment.props) {+ const original = originalPropsById.get(prop.id);+ if (+ original !== undefined &&+ templateInternalIds.has(original.instanceId) &&+ !editableTemplatePropIds.has(prop.id) &&+ !derivedTemplatePropIds.has(prop.id) &&+ !equal(prop, original)+ ) {+ throw new Error(+ "Expanded template props cannot be represented losslessly in MDX"+ );+ }+ const template = templateByRootId.get(prop.instanceId);+ if (+ template !== undefined &&+ isEditableTemplateProp({ provenance: template, prop }) === false &&+ derivedTemplatePropIds.has(prop.id) === false &&+ (original === undefined || !equal(original, prop))+ ) {+ throw new Error(+ "Expanded template props cannot be represented losslessly in MDX"+ );+ }+ }+ for (const original of root.fragment.props) {+ if (+ templateInternalIds.has(original.instanceId) &&+ deletedTemplateRootIds.has(+ templateByExpandedInstanceId.get(original.instanceId)?.instanceId ?? ""+ ) === false &&+ !editableTemplatePropIds.has(original.id) &&+ !derivedTemplatePropIds.has(original.id) &&+ fragment.props.some(({ id }) => id === original.id) === false+ ) {+ throw new Error(+ "Expanded template props cannot be represented losslessly in MDX"+ );+ }+ }+ const serializedInstanceIds = new Set<string>();+ const usesPhrasingContent = (tag: string) =>+ elementsByTag[tag]?.categories.includes("phrasing") === true;+ const getInsertedNodeMode = (children: Instance["children"]): MdxMode =>+ children.every(+ (child) =>+ child.type === "text" ||+ (child.type === "id" &&+ instanceById.get(child.value)?.tag !== undefined &&+ usesPhrasingContent(instanceById.get(child.value)?.tag ?? ""))+ )+ ? "text"+ : "flow";+ const getChildrenMode = ({+ original,+ tag,+ }: {+ original: MdxAuthoredNode | undefined;+ tag: string;+ }): MdxMode => {+ if (original?.type === "element" && original.syntax === "mdx") {+ return original.mdxMode;+ }+ return elementsByTag[tag]?.children.includes("phrasing") === true+ ? "text"+ : "flow";+ };++ const toNode = (+ instanceId: string,+ mode: MdxMode,+ active: Set<string>+ ): MdxAuthoredNode => {+ if (active.has(instanceId)) {+ throw new Error("Cyclic authored MDX instance tree");+ }+ const instance = instanceById.get(instanceId);+ if (instance === undefined) {+ throw new Error(`Authored MDX instance "${instanceId}" is missing`);+ }+ const provenance = provenanceById.get(instanceId);+ if (provenance?.type === "template") {+ if (serializedInstanceIds.has(instanceId)) {+ throw new Error(`Authored MDX instance "${instanceId}" is reused`);+ }+ for (const expandedId of provenance.expandedInstanceIds) {+ serializedInstanceIds.add(expandedId);+ }+ const original = originalNodeByPath.get(pathKey(provenance.path));+ if (original?.type !== "template") {+ throw new Error("Authored MDX template provenance is invalid");+ }+ const editableProps = (propsByInstanceId.get(instanceId) ?? []).filter(+ (prop) => isEditableTemplateProp({ provenance, prop })+ );+ if (+ new Set(editableProps.map(({ name }) => name)).size !==+ editableProps.length+ ) {+ throw new Error("Duplicate authored template props are not supported");+ }+ const editableNames = new Set([+ ...provenance.editablePropNames,+ ...editableProps.map(({ name }) => name),+ ]);+ const instancePropNameByJsxName = new Map(+ provenance.propNameMappings.map((mapping) => [+ mapping.jsxPropName,+ mapping.instancePropName,+ ])+ );+ const toInstancePropName = (jsxPropName: string) =>+ instancePropNameByJsxName.get(jsxPropName) ?? jsxPropName;+ const ignoredJsxPropNames = new Set(provenance.ignoredJsxPropNames);+ const componentPropNames = new Set(+ provenance.jsxPropContext.componentPropNames+ );+ const authoredJsxPropNameByInstanceName = new Map(+ provenance.propNameMappings.flatMap((mapping) =>+ provenance.preservedJsxPropNames?.includes(mapping.jsxPropName)+ ? [[mapping.instancePropName, mapping.jsxPropName] as const]+ : []+ )+ );+ const jsxPropNameByInstanceName = new Map(+ mapAttributeNames({+ attributes: editableProps.map(({ name }) => ({+ name,+ instancePropName: name,+ })),+ direction: "instance-to-jsx",+ acceptsHtmlAttributes:+ provenance.jsxPropContext.acceptsHtmlAttributes,+ componentPropNames,+ }).map((mapping) => [mapping.instancePropName, mapping.name])+ );+ const toJsxName = (instancePropName: string) => {+ const jsxPropName =+ authoredJsxPropNameByInstanceName.get(instancePropName) ??+ jsxPropNameByInstanceName.get(instancePropName);+ if (jsxPropName === undefined) {+ throw new Error(+ `Template prop "${instancePropName}" has no JSX name mapping`+ );+ }+ return jsxPropName;+ };+ const nextEditable = toAuthoredProps({+ original: original.props.flatMap((prop) => {+ if (ignoredJsxPropNames.has(prop.name)) {+ return [];+ }+ const name = toInstancePropName(prop.name);+ return editableNames.has(name) ? [{ ...prop, name }] : [];+ }),+ props: editableProps,+ assetProps: provenance.assetProps,+ assetReferenceValues: root.assetReferenceValues,+ });+ const nextByName = new Map(nextEditable.map((prop) => [prop.name, prop]));+ const props = original.props.flatMap((prop) => {+ if (ignoredJsxPropNames.has(prop.name)) {+ return [prop];+ }+ const instancePropName = toInstancePropName(prop.name);+ if (editableNames.has(instancePropName) === false) {+ return [prop];+ }+ const next = nextByName.get(instancePropName);+ nextByName.delete(instancePropName);+ return next === undefined+ ? []+ : [{ ...next, name: toJsxName(next.name) }];+ });+ props.push(+ ...Array.from(nextByName.values(), (prop) => ({+ ...prop,+ name: toJsxName(prop.name),+ }))+ );+ const normalizedProps = normalizeMdxComponentProps({+ instance,+ props,+ instanceProps: editableProps,+ });+ assertUniqueAttributeNames(normalizedProps);+ let children = original.children;+ const originalInstance = originalInstanceById.get(instanceId);+ if (+ provenance.editableTextChildren &&+ originalInstance !== undefined &&+ (original.children.length > 0 ||+ equal(instance.children, originalInstance.children) === false)+ ) {+ children = reconcileChildren({+ original: original.children,+ children: instance.children,+ mode: original.mdxMode,+ active,+ });+ if (children.length === 0) {+ throw new Error(+ "Empty template text cannot be represented losslessly in MDX"+ );+ }+ }+ if (+ provenance.namespaceKeys.length === 0 &&+ normalizedProps.every(+ ({ name }) =>+ ignoredJsxPropNames.has(name) === false &&+ editableNames.has(toInstancePropName(name))+ )+ ) {+ const componentNode = serializeMdxComponent({+ instance,+ props: nextEditable,+ instanceProps: editableProps,+ original,+ });+ if (componentNode !== undefined) {+ return componentNode;+ }+ }+ return mode === "text" ||+ (provenance.editableTextChildren && children.length > 0)+ ? { ...original, props: normalizedProps, children, mdxMode: "text" }+ : { ...original, props: normalizedProps, children };+ }+ const instanceProps = propsByInstanceId.get(instanceId) ?? [];+ const authoredComponentProps =+ instance.component === elementComponent+ ? []+ : toAuthoredProps({+ original: [],+ props: instanceProps,+ assetProps:+ provenance?.type === "component"+ ? provenance.assetProps+ : undefined,+ assetReferenceValues: root.assetReferenceValues,+ });+ const componentNode =+ instance.component === elementComponent+ ? undefined+ : serializeMdxComponent({+ instance,+ props: authoredComponentProps,+ instanceProps,+ original:+ provenance?.type === "component"+ ? originalNodeByPath.get(pathKey(provenance.path))+ : undefined,+ });+ const serializedComponent =+ componentNode ??+ (provenance?.type === "component"+ ? serializeMdxComponentFallback({+ instance,+ props: authoredComponentProps,+ instanceProps,+ })+ : undefined);+ if (serializedComponent !== undefined) {+ if (serializedInstanceIds.has(instanceId)) {+ throw new Error(`Authored MDX instance "${instanceId}" is reused`);+ }+ if (+ provenance !== undefined &&+ (provenance.type !== "component" ||+ originalInstanceById.get(instanceId)?.component !==+ instance.component)+ ) {+ throw new Error("Authored MDX component provenance is invalid");+ }+ serializedInstanceIds.add(instanceId);+ return serializedComponent;+ }+ if (instance.component !== elementComponent || instance.tag === undefined) {+ throw new Error(+ `Instance "${instanceId}" cannot be represented losslessly in MDX`+ );+ }+ if (serializedInstanceIds.has(instanceId)) {+ throw new Error(`Authored MDX instance "${instanceId}" is reused`);+ }+ serializedInstanceIds.add(instanceId);+ const original =+ provenance?.type === "element"+ ? originalNodeByPath.get(pathKey(provenance.path))+ : undefined;+ if (+ original !== undefined &&+ (original.type === "text" ||+ original.type === "comment" ||+ original.type === "opaque" ||+ original.type === "template")+ ) {+ throw new Error("Authored MDX element provenance is invalid");+ }+ if (original !== undefined) {+ const originalInstance = originalInstanceById.get(instanceId);+ if (+ originalInstance?.component !== instance.component ||+ originalInstance.tag !== instance.tag ||+ originalInstance.label !== instance.label+ ) {+ throw new Error(+ "Element metadata cannot be represented losslessly in MDX"+ );+ }+ }+ active.add(instanceId);+ const children = reconcileChildren({+ original: original?.children ?? [],+ children: instance.children,+ mode: getChildrenMode({ original, tag: instance.tag }),+ active,+ });+ active.delete(instanceId);+ const props = toAuthoredProps({+ original: original?.props ?? [],+ props: propsByInstanceId.get(instanceId) ?? [],+ assetProps:+ provenance?.type === "element" ? provenance.assetProps : undefined,+ assetReferenceValues: root.assetReferenceValues,+ });+ if (original !== undefined) {+ if (original.syntax === "mdx") {+ const contentMode = getInsertedNodeMode(instance.children);+ if (contentMode === "flow" && mode === "text") {+ throw new Error(+ "Block content cannot be represented inside inline MDX"+ );+ }+ return {+ ...original,+ props,+ children,+ mdxMode:+ original.mdxMode === "flow" && mode === "flow"+ ? "flow"+ : contentMode,+ };+ }+ return { ...original, props, children };+ }+ const element = {+ type: "element",+ syntax: "mdx",+ tag: instance.tag,+ props,+ children,+ mdxMode: getInsertedNodeMode(instance.children),+ } as const;+ return element;+ };++ const reconcileChildren = ({+ original,+ children,+ mode,+ active,+ }: {+ original: readonly MdxAuthoredNode[];+ children: Instance["children"];+ mode: MdxMode;+ active: Set<string>;+ }): MdxAuthoredNode[] => {+ const textPaths = original+ .map((node, index) => ({ node, key: `text:${index}` }))+ .filter(({ node }) => node.type === "text");+ const unusedTextPaths = [...textPaths];+ const rendered = children.map((child) => {+ if (child.type === "expression") {+ throw new Error(+ "Expression text cannot be represented losslessly in MDX"+ );+ }+ if (child.type === "text") {+ const exactIndex = unusedTextPaths.findIndex(+ ({ node }) => node.type === "text" && node.value === child.value+ );+ const [entry] = unusedTextPaths.splice(+ exactIndex === -1 ? 0 : exactIndex,+ 1+ );+ const node: MdxAuthoredNode =+ entry?.node.type === "text"+ ? { ...entry.node, value: child.value }+ : { type: "text", value: child.value };+ return { key: entry?.key, node };+ }+ const provenance = provenanceById.get(child.value);+ return {+ key:+ provenance === undefined+ ? undefined+ : `node:${pathKey(provenance.path)}`,+ node: toNode(child.value, mode, active),+ };+ });+ const surviving = new Set(+ rendered.flatMap(({ key }) => (key ? [key] : []))+ );+ const anchorsByKey = new Map<string, MdxAuthoredNode[]>();+ const tail: MdxAuthoredNode[] = [];+ let pending: MdxAuthoredNode[] = [];+ for (const [index, node] of original.entries()) {+ const originalPath = originalPathByNode.get(node);+ const provenance =+ originalPath === undefined+ ? undefined+ : provenanceByPath.get(originalPath);+ const key =+ node.type === "text"+ ? `text:${index}`+ : provenance === undefined+ ? undefined+ : `node:${pathKey(provenance.path)}`;+ if (key !== undefined && surviving.has(key)) {+ anchorsByKey.set(key, pending);+ pending = [];+ } else if (key === undefined) {+ pending.push(node);+ }+ }+ tail.push(...pending);+ return [+ ...rendered.flatMap(({ key, node }) => [+ ...(key === undefined ? [] : (anchorsByKey.get(key) ?? [])),+ node,+ ]),+ ...tail,+ ];+ };++ const children = reconcileChildren({+ original: root.document.children,+ children: fragment.children,+ mode: "flow",+ active: new Set(),+ });+ if (+ fragment.instances.some(({ id }) => serializedInstanceIds.has(id) === false)+ ) {+ throw new Error(+ "Unreachable instances cannot be represented losslessly in MDX"+ );+ }+ if (+ fragment.props.some(+ ({ instanceId }) => serializedInstanceIds.has(instanceId) === false+ )+ ) {+ throw new Error("Orphan props cannot be represented losslessly in MDX");+ }+ return {+ ...root.document,+ children,+ };+};++const transientEmptyMarkdownTags = new Set([+ "p",+ "h1",+ "h2",+ "h3",+ "h4",+ "h5",+ "h6",+ "blockquote",+ "ul",+ "ol",+ "li",+]);++/**+ * Markdown cannot distinguish an empty editable draft from authored empty+ * syntax. Keep newly inserted empty Markdown containers in memory until they+ * contain content, while preserving empty nodes that already came from MDX.+ */+export const omitTransientEmptyMarkdownDrafts = ({+ root,+ fragment,+}: {+ root: MaterializedMdxAuthoredContentRoot;+ fragment: WebstudioFragment;+}): WebstudioFragment => {+ const authoredInstanceIds = new Set(+ root.provenance.nodes.flatMap((node) =>+ node.type === "template" ? node.expandedInstanceIds : [node.instanceId]+ )+ );+ const instanceIdsWithProps = new Set(+ fragment.props.map(({ instanceId }) => instanceId)+ );+ const instanceIdsWithStyleSources = new Set(+ fragment.styleSourceSelections.map(({ instanceId }) => instanceId)+ );+ const referenceCountByInstanceId = new Map<string, number>();+ for (const child of [+ ...fragment.children,+ ...fragment.instances.flatMap(({ children }) => children),+ ]) {+ if (child.type === "id") {+ referenceCountByInstanceId.set(+ child.value,+ (referenceCountByInstanceId.get(child.value) ?? 0) + 1+ );+ }+ }+ const instancesById = new Map(+ fragment.instances.map((instance) => [instance.id, instance])+ );+ const omittedIds = new Set<string>();+ const visiting = new Set<string>();+ const isTransientEmpty = (instanceId: string): boolean => {+ if (omittedIds.has(instanceId)) {+ return true;+ }+ const instance = instancesById.get(instanceId);+ if (+ instance === undefined ||+ instance.component !== elementComponent ||+ transientEmptyMarkdownTags.has(instance.tag ?? "") === false ||+ referenceCountByInstanceId.get(instance.id) !== 1 ||+ authoredInstanceIds.has(instance.id) ||+ instanceIdsWithProps.has(instance.id) ||+ instanceIdsWithStyleSources.has(instance.id) ||+ visiting.has(instance.id)+ ) {+ return false;+ }+ visiting.add(instance.id);+ const isEmpty = instance.children.every(+ (child) => child.type === "id" && isTransientEmpty(child.value)+ );+ visiting.delete(instance.id);+ if (isEmpty) {+ omittedIds.add(instance.id);+ }+ return isEmpty;+ };+ for (const instance of fragment.instances) {+ isTransientEmpty(instance.id);+ }+ if (omittedIds.size === 0) {+ return fragment;+ }+ const omitChildren = (children: WebstudioFragment["children"]) =>+ children.filter(+ (child) => child.type !== "id" || omittedIds.has(child.value) === false+ );+ return {+ ...fragment,+ children: omitChildren(fragment.children),+ instances: fragment.instances+ .filter(({ id }) => omittedIds.has(id) === false)+ .map((instance) => ({+ ...instance,+ children: omitChildren(instance.children),+ })),+ };+};++export const serializeMdxAuthoredContent = async ({+ root,+ fragment,+}: {+ root: MaterializedMdxAuthoredContentRoot;+ fragment: WebstudioFragment;+}) =>+ serializeMdxDocument(+ await preferMarkdownSyntax(+ reconcileMdxAuthoredContent({+ root,+ fragment: omitTransientEmptyMarkdownDrafts({ root, fragment }),+ })+ )+ );++export const serializeMdxTemplateInsertion = async ({+ identity,+ fragment,+ templateName,+ assetReferenceValues,+}: {+ identity: ContentBlockExternalContentIdentity;+ fragment: WebstudioFragment;+ templateName: string;+ assetReferenceValues?: ReadonlyMap<string, string>;+}) => {+ const emptyDocument: MdxDocument = {+ frontmatter: { properties: {} },+ children: [],+ };+ const emptyRoot = materializeMdxAuthoredContent({+ identity,+ document: emptyDocument,+ templateMaterialization: {+ templates: [],+ diagnostics: [],+ dependencies: { templateNames: [], templates: [] },+ },+ assetReferenceValues,+ });+ try {+ return preferMarkdownSyntax(+ reconcileMdxAuthoredContent({ root: emptyRoot, fragment })+ );+ } catch {+ const rootChild = fragment.children[0];+ const rootInstance =+ rootChild?.type === "id"+ ? fragment.instances.find(({ id }) => id === rootChild.value)+ : undefined;+ const componentFallback =+ rootInstance === undefined+ ? undefined+ : serializeMdxComponentFallback({+ instance: rootInstance,+ props: toAuthoredProps({+ original: [],+ props: fragment.props.filter(+ ({ instanceId }) => instanceId === rootInstance.id+ ),+ assetReferenceValues,+ }),+ instanceProps: fragment.props.filter(+ ({ instanceId }) => instanceId === rootInstance.id+ ),+ templateName,+ });+ if (componentFallback !== undefined) {+ return {+ frontmatter: { properties: {} },+ children: [componentFallback],+ };+ }+ const props =+ rootInstance === undefined+ ? []+ : mapAttributeNames({+ attributes: toAuthoredProps({+ original: [],+ props: fragment.props.filter(+ (prop) =>+ prop.instanceId === rootInstance.id &&+ (prop.type === "string" ||+ prop.type === "number" ||+ prop.type === "boolean")+ ),+ }),+ direction: "instance-to-jsx",+ acceptsHtmlAttributes: false,+ });+ const children =+ rootInstance?.children.every((child) => child.type === "text") === true+ ? rootInstance.children.flatMap((child) =>+ child.type === "text" && child.value !== ""+ ? [{ type: "text" as const, value: child.value }]+ : []+ )+ : [];+ return {+ frontmatter: { properties: {} },+ children: [+ {+ type: "template" as const,+ name: templateName,+ props,+ children,+ mdxMode:+ children.length === 0 ? ("flow" as const) : ("text" as const),+ },+ ],+ };+ }+};++const reconcileMdxAuthoredContentWithTemplateInsertions = async ({+ root,+ fragment,+ insertedTemplateNames,+}: {+ root: MaterializedMdxAuthoredContentRoot;+ fragment: WebstudioFragment;+ insertedTemplateNames: ReadonlyMap<string, string>;+}) => {+ if (insertedTemplateNames.size === 0) {+ return preferMarkdownSyntax(+ reconcileMdxAuthoredContent({ root, fragment })+ );+ }+ const fragmentData = createWebstudioDataFromFragment(fragment);+ const insertions = await Promise.all(+ fragment.children.flatMap((child) => {+ if (child.type !== "id") {+ return [];+ }+ const templateName = insertedTemplateNames.get(child.value);+ if (templateName === undefined) {+ return [];+ }+ const insertionFragment = extractWebstudioFragment(+ fragmentData,+ child.value+ );+ return [+ serializeMdxTemplateInsertion({+ identity: root.identity,+ fragment: insertionFragment,+ templateName,+ assetReferenceValues: root.assetReferenceValues,+ }).then((document) => ({+ rootInstanceId: child.value,+ fragment: insertionFragment,+ document,+ })),+ ];+ })+ );+ if (insertions.length === 0) {+ return preferMarkdownSyntax(+ reconcileMdxAuthoredContent({ root, fragment })+ );+ }++ const originalKeys = getUnsupportedNamespaceKeys([root.fragment]);+ const removedInstanceIds = new Set(+ insertions.flatMap(({ fragment: insertion }) =>+ insertion.instances.map(({ id }) => id)+ )+ );+ const removedPropIds = new Set(+ insertions.flatMap(({ fragment: insertion }) =>+ insertion.props.map(({ id }) => id)+ )+ );+ const removedKeys = getUnsupportedNamespaceKeys(+ insertions.map(({ fragment }) => fragment)+ );+ const reservedInstanceIds = new Set(fragment.instances.map(({ id }) => id));+ const markerByRootId = new Map(+ insertions.map(({ rootInstanceId }, index) => {+ let markerId = `mdx-template-insertion-${index}`;+ while (reservedInstanceIds.has(markerId)) {+ markerId = `${markerId}-next`;+ }+ reservedInstanceIds.add(markerId);+ return [rootInstanceId, markerId];+ })+ );+ const markerInstances = Array.from(markerByRootId.values(), (id) => ({+ type: "instance" as const,+ id,+ component: elementComponent,+ tag: "div",+ children: [],+ }));+ const reservedPropIds = new Set(fragment.props.map(({ id }) => id));+ const markerProps = Array.from(markerByRootId.values(), (instanceId) => {+ let id = `${instanceId}-prop`;+ while (reservedPropIds.has(id)) {+ id = `${id}-next`;+ }+ reservedPropIds.add(id);+ return {+ id,+ instanceId,+ name: "data-ws-mdx-template-insertion",+ type: "string" as const,+ value: instanceId,+ };+ });+ const normalized = {+ ...fragment,+ children: fragment.children.map((child) =>+ child.type === "id" && markerByRootId.has(child.value)+ ? { type: "id" as const, value: markerByRootId.get(child.value)! }+ : child+ ),+ instances: [+ ...fragment.instances.filter(({ id }) => !removedInstanceIds.has(id)),+ ...markerInstances,+ ],+ props: [+ ...fragment.props.filter(({ id }) => !removedPropIds.has(id)),+ ...markerProps,+ ],+ ...Object.fromEntries(+ unsupportedNamespaces.map((namespace) => [+ namespace,+ fragment[namespace].filter((record) => {+ const key = getNamespaceRecordKey(namespace, record);+ return (+ removedKeys[namespace].has(key) === false ||+ originalKeys[namespace].has(key)+ );+ }),+ ])+ ),+ } as WebstudioFragment;+ const reconciled = reconcileMdxAuthoredContent({+ root,+ fragment: normalized,+ });+ const insertionByMarker = new Map(+ insertions.map((insertion) => [+ markerByRootId.get(insertion.rootInstanceId),+ insertion.document.children,+ ])+ );+ return preferMarkdownSyntax({+ ...reconciled,+ children: reconciled.children.flatMap((node) => {+ if (node.type !== "element") {+ return [node];+ }+ const marker = node.props.find(+ ({ name }) => name === "data-ws-mdx-template-insertion"+ )?.value;+ return typeof marker === "string" && insertionByMarker.has(marker)+ ? insertionByMarker.get(marker)!+ : [node];+ }),+ });+};++export const rebaseMdxAuthoredContent = async ({+ root,+ fragment,+ latest,+ latestRevision,+ latestIsLocal = false,+ insertedTemplateNames = new Map(),+}: {+ root: MaterializedMdxAuthoredContentRoot;+ fragment: WebstudioFragment;+ latest: MdxDocument;+ latestRevision?: string;+ latestIsLocal?: boolean;+ insertedTemplateNames?: ReadonlyMap<string, string>;+}) => {+ if (+ (latestRevision !== undefined &&+ root.identity.revision !== latestRevision) ||+ (latestIsLocal === false &&+ isMdxValueEqual(root.document, latest) === false)+ ) {+ throw new MdxAuthoredContentConflictError(+ "The MDX content source changed before the edit was saved. Reload to continue."+ );+ }+ const local = await reconcileMdxAuthoredContentWithTemplateInsertions({+ root,+ fragment: omitTransientEmptyMarkdownDrafts({ root, fragment }),+ insertedTemplateNames,+ });+ return preferMarkdownSyntax(+ latestIsLocal+ ? mergeLocalMdxDocument({ base: root.document, local, latest })+ : local+ );+};diff --git a/packages/project-build/src/runtime/mdx-component-adapters.ts b/packages/project-build/src/runtime/mdx-component-adapters.tsnew file mode 100644index 0000000000..f433220d19--- /dev/null+++ b/packages/project-build/src/runtime/mdx-component-adapters.ts@@ -0,0 +1,359 @@+import {+ createMdxCodeBlock,+ readMdxCodeBlock,+ type MdxAuthoredNode,+ type MdxAuthoredProp,+} from "@webstudio-is/content-engine/mdx";+import { mapAttributeNames } from "@webstudio-is/content-engine/jsx-attributes";+import type { Instance, Prop } from "@webstudio-is/sdk";++type MaterializedComponentProp = Readonly<{+ prop: MdxAuthoredProp;+ source?: Readonly<{+ nodePath: readonly number[];+ propIndex: number;+ }>;+ requiresAssetReference?: boolean;+}>;++type MaterializedComponent = Readonly<{+ children: Instance["children"];+ props: readonly MaterializedComponentProp[];+}>;++type MdxComponentAdapter = Readonly<{+ component: Instance["component"];+ toMdx: (input: {+ instance: Instance;+ props: readonly MdxAuthoredProp[];+ instanceProps: readonly Prop[];+ original?: MdxAuthoredNode;+ }) => MdxAuthoredNode | undefined;+ fromMdx: (node: MdxAuthoredNode) => MaterializedComponent | undefined;+}>;++const codeTextComponent = "CodeText";+const imageComponent = "Image";+const derivedImageAssetPropNames = new Set(["width", "height", "alt"]);++const getStringProps = (props: readonly MdxAuthoredProp[]) => {+ const values = new Map<string, string>();+ for (const prop of props) {+ if (typeof prop.value !== "string" || values.has(prop.name)) {+ return;+ }+ values.set(prop.name, prop.value);+ }+ return values;+};++const codeTextAdapter: MdxComponentAdapter = {+ component: codeTextComponent,+ toMdx: ({ instance, props }) => {+ const values = getStringProps(props);+ if (values === undefined) {+ return;+ }+ const unsupportedProps = Array.from(values.keys()).filter(+ (name) => name !== "code" && name !== "language" && name !== "theme"+ );+ const language = values.get("language");+ const theme = values.get("theme");+ if (unsupportedProps.length > 0 || theme !== undefined) {+ return;+ }++ const textChildren =+ instance.children.length > 0 &&+ instance.children.every((child) => child.type === "text")+ ? instance.children.map((child) => child.value).join("")+ : undefined;+ const code = textChildren ?? values.get("code") ?? "";+ if (+ (textChildren === undefined && values.has("code") === false) ||+ code.endsWith("\n")+ ) {+ return;+ }++ return createMdxCodeBlock({+ value: code,+ language,+ });+ },+ fromMdx: (node) => {+ const code = readMdxCodeBlock(node);+ if (code === undefined) {+ return;+ }+ return {+ children: [{ type: "text", value: code.value }],+ props:+ code.language === undefined+ ? []+ : [{ prop: { name: "language", value: code.language } }],+ };+ },+};++const readMdxImage = (node: MdxAuthoredNode) => {+ if (+ node.type !== "element" ||+ node.syntax !== "markdown" ||+ node.tag !== "p" ||+ node.props.length > 0 ||+ node.children.length !== 1+ ) {+ return;+ }+ const image = node.children[0];+ if (+ image?.type !== "element" ||+ image.syntax !== "markdown" ||+ image.tag !== "img" ||+ image.children.length > 0+ ) {+ return;+ }+ return image;+};++const getDerivedImageAssetPropIds = (instanceProps: readonly Prop[]) => {+ const source = instanceProps.find(+ (prop) => prop.name === "src" && prop.type === "asset"+ );+ const derivedAssetProps = instanceProps.filter(+ (prop) => prop.type === "asset" && derivedImageAssetPropNames.has(prop.name)+ );+ const derivedAssetIds = new Set(derivedAssetProps.map(({ value }) => value));+ const assetId =+ source?.type === "asset"+ ? source.value+ : derivedAssetProps.length >= 2 && derivedAssetIds.size === 1+ ? derivedAssetProps[0]?.value+ : undefined;+ return new Set(+ instanceProps.flatMap((prop) =>+ prop.type === "asset" &&+ prop.value === assetId &&+ derivedImageAssetPropNames.has(prop.name)+ ? [prop.id]+ : []+ )+ );+};++export const getDerivedMdxComponentPropIds = ({+ instance,+ instanceProps,+}: {+ instance: Instance;+ instanceProps: readonly Prop[];+}) =>+ instance.component === imageComponent+ ? getDerivedImageAssetPropIds(instanceProps)+ : new Set<Prop["id"]>();++export const normalizeMdxComponentProps = ({+ instance,+ props,+ instanceProps,+}: {+ instance: Instance;+ props: readonly MdxAuthoredProp[];+ instanceProps: readonly Prop[];+}) => {+ const derivedPropIds = getDerivedMdxComponentPropIds({+ instance,+ instanceProps,+ });+ if (derivedPropIds.size === 0) {+ return props;+ }+ const derivedPropNames = new Set(+ instanceProps.flatMap((prop) =>+ derivedPropIds.has(prop.id) ? [prop.name] : []+ )+ );+ return props.filter(({ name }) => derivedPropNames.has(name) === false);+};++const imageAdapter: MdxComponentAdapter = {+ component: imageComponent,+ toMdx: ({ instance, props, instanceProps }) => {+ if (instance.children.length > 0) {+ return;+ }+ const values = getStringProps(+ normalizeMdxComponentProps({ instance, props, instanceProps })+ );+ if (+ values === undefined ||+ Array.from(values.keys()).some(+ (name) => name !== "src" && name !== "alt" && name !== "title"+ )+ ) {+ return;+ }+ const imageProps: MdxAuthoredProp[] = [+ { name: "src", value: values.get("src") ?? "" },+ { name: "alt", value: values.get("alt") ?? "" },+ ];+ const title = values.get("title");+ if (title !== undefined) {+ imageProps.push({ name: "title", value: title });+ }+ return {+ type: "element",+ syntax: "mdx",+ tag: "p",+ props: [],+ children: [+ {+ type: "element",+ syntax: "mdx",+ tag: "img",+ props: imageProps,+ children: [],+ mdxMode: "text",+ },+ ],+ mdxMode: "flow",+ };+ },+ fromMdx: (node) => {+ const image = readMdxImage(node);+ if (image === undefined) {+ return;+ }+ const props: MaterializedComponentProp[] = [];+ const names = new Set<string>();+ for (const [propIndex, prop] of image.props.entries()) {+ if (+ typeof prop.value !== "string" ||+ (prop.name !== "src" && prop.name !== "alt" && prop.name !== "title") ||+ names.has(prop.name)+ ) {+ return;+ }+ names.add(prop.name);+ if (prop.value !== "") {+ props.push({+ prop,+ source: { nodePath: [0], propIndex },+ });+ }+ }+ const sourceIndex = image.props.findIndex(({ name }) => name === "src");+ const source = image.props[sourceIndex];+ if (sourceIndex !== -1 && typeof source?.value === "string") {+ const sourceLocation = { nodePath: [0], propIndex: sourceIndex };+ for (const name of ["width", "height"] as const) {+ props.push({+ prop: { name, value: source.value },+ source: sourceLocation,+ requiresAssetReference: true,+ });+ }+ if (+ image.props.some(({ name, value }) => name === "alt" && value !== "")+ ) {+ return { children: [], props };+ }+ props.push({+ prop: { name: "alt", value: source.value },+ source: sourceLocation,+ requiresAssetReference: true,+ });+ }+ return { children: [], props };+ },+};++const componentAdapters = new Map<Instance["component"], MdxComponentAdapter>([+ [codeTextAdapter.component, codeTextAdapter],+ [imageAdapter.component, imageAdapter],+]);++export const serializeMdxComponent = ({+ instance,+ props,+ instanceProps,+ original,+}: {+ instance: Instance;+ props: readonly MdxAuthoredProp[];+ instanceProps: readonly Prop[];+ original?: MdxAuthoredNode;+}) =>+ componentAdapters+ .get(instance.component)+ ?.toMdx({ instance, props, instanceProps, original });++export const serializeMdxComponentFallback = ({+ instance,+ props,+ instanceProps,+ templateName,+}: {+ instance: Instance;+ props: readonly MdxAuthoredProp[];+ instanceProps: readonly Prop[];+ templateName?: string;+}): MdxAuthoredNode | undefined => {+ const adapter = componentAdapters.get(instance.component);+ if (adapter === undefined) {+ return;+ }+ const authoredProps: MdxAuthoredProp[] = [];+ const propNames = new Set<string>();+ let legacyCode: string | undefined;+ const componentProps = normalizeMdxComponentProps({+ instance,+ props,+ instanceProps,+ });+ for (const prop of componentProps) {+ if (adapter.component === codeTextComponent && prop.name === "code") {+ if (typeof prop.value !== "string" || legacyCode !== undefined) {+ return;+ }+ legacyCode = prop.value;+ continue;+ }+ if (propNames.has(prop.name)) {+ return;+ }+ propNames.add(prop.name);+ authoredProps.push(prop);+ }+ let children = instance.children.flatMap((child) =>+ child.type === "text" ? [{ type: "text" as const, value: child.value }] : []+ );+ if (children.length !== instance.children.length) {+ return;+ }+ if (children.length === 0 && legacyCode !== undefined) {+ children = [{ type: "text", value: legacyCode }];+ }+ return {+ type: "template",+ name: templateName ?? adapter.component,+ props: mapAttributeNames({+ attributes: authoredProps,+ direction: "instance-to-jsx",+ acceptsHtmlAttributes: true,+ }),+ children,+ mdxMode: children.length === 0 ? "flow" : "text",+ };+};++export const materializeMdxComponent = (node: MdxAuthoredNode) => {+ for (const adapter of componentAdapters.values()) {+ const component = adapter.fromMdx(node);+ if (component !== undefined) {+ return { ...component, component: adapter.component };+ }+ }+};diff --git a/packages/project-build/src/runtime/mdx-diagnostics.ts b/packages/project-build/src/runtime/mdx-diagnostics.tsnew file mode 100644index 0000000000..d7e8010412--- /dev/null+++ b/packages/project-build/src/runtime/mdx-diagnostics.ts@@ -0,0 +1,93 @@+import {+ createMdxSourceDiagnostics,+ type MdxAuthoredNode,+ type MdxDocumentError,+} from "@webstudio-is/content-engine/mdx";+import type {+ ContentBlockDiagnostic,+ ContentBlockExternalContentIdentity,+ WsComponentMeta,+} from "@webstudio-is/sdk";+import type { MaterializedMdxAuthoredContentRoot } from "./mdx-authored-content";+import { getFragmentContentModelWarnings } from "./matcher";++export const createMdxDiagnostics = ({+ identity,+ diagnostics,+}: {+ identity: ContentBlockExternalContentIdentity;+ diagnostics: readonly MdxDocumentError[];+}): ContentBlockDiagnostic[] =>+ createMdxSourceDiagnostics(diagnostics).map((diagnostic) =>+ diagnostic.code === "unsafe-mdx"+ ? {+ code: "unsafe-mdx",+ severity: diagnostic.severity,+ blockInstanceId: identity.blockInstanceId,+ assetId: identity.assetId,+ contentRef: identity.contentRef,+ renderScope: identity.renderScope,+ nodeType: diagnostic.nodeType ?? "unknown",+ reason: diagnostic.reason ?? diagnostic.message,+ sourceRange: diagnostic.sourceRange,+ }+ : {+ code: "invalid-mdx",+ severity: diagnostic.severity,+ blockInstanceId: identity.blockInstanceId,+ assetId: identity.assetId,+ contentRef: identity.contentRef,+ renderScope: identity.renderScope,+ message: diagnostic.message,+ sourceRange: diagnostic.sourceRange,+ }+ );++const getMdxNodeAtPath = (+ root: MaterializedMdxAuthoredContentRoot,+ path: readonly number[]+): MdxAuthoredNode | undefined => {+ let children = root.document.children;+ let node: MdxAuthoredNode | undefined;+ for (const index of path) {+ node = children[index];+ if (node === undefined) {+ return;+ }+ children = "children" in node ? node.children : [];+ }+ return node;+};++export const createMdxContentModelDiagnostics = ({+ root,+ metas,+}: {+ root: MaterializedMdxAuthoredContentRoot;+ metas: Map<string, WsComponentMeta>;+}): ContentBlockDiagnostic[] => {+ const provenanceByInstanceId = new Map(+ root.provenance.nodes.map((node) => [node.instanceId, node])+ );+ return getFragmentContentModelWarnings({+ fragment: root.fragment,+ metas,+ }).flatMap((warning) => {+ const provenance = provenanceByInstanceId.get(warning.instanceId);+ if (provenance === undefined) {+ return [];+ }+ return [+ {+ code: "invalid-mdx" as const,+ severity: "error" as const,+ blockInstanceId: root.identity.blockInstanceId,+ assetId: root.identity.assetId,+ contentRef: root.identity.contentRef,+ renderScope: root.identity.renderScope,+ message: warning.message,+ sourceRange: getMdxNodeAtPath(root, provenance.path)?.sourceRange,+ },+ ];+ });+};diff --git a/packages/project-build/src/runtime/mdx-materialization.test.ts b/packages/project-build/src/runtime/mdx-materialization.test.tsnew file mode 100644index 0000000000..13382ac2d1--- /dev/null+++ b/packages/project-build/src/runtime/mdx-materialization.test.ts@@ -0,0 +1,1192 @@+import { describe, expect, test } from "vitest";+import {+ parseMdxDocument,+ serializeMdxDocument,+} from "@webstudio-is/content-engine/mdx";+import {+ blockComponent,+ blockTemplateComponent,+ encodeDataVariableId,+ type Asset,+ type ContentBlockExternalContentIdentity,+ type Instance,+ type Prop,+ type WebstudioData,+ type WsComponentMeta,+} from "@webstudio-is/sdk";+import {+ materializeMdxTemplates,+ type MaterializedMdxTemplate,+} from "./mdx-materialization";+import {+ materializeMdxAuthoredContent,+ serializeMdxAuthoredContent,+} from "./mdx-authored-content";+import {+ resolveMdxTemplates,+ type MdxTemplateResolution,+} from "./mdx-template-resolution";++const identity: ContentBlockExternalContentIdentity = {+ blockInstanceId: "block",+ assetId: "article",+ revision: "revision-1",+ contentRef: "articles/hello.mdx",+ format: "mdx",+ renderScope: "route:/hello",+};++const resolution: MdxTemplateResolution = {+ templateNames: ["Hero Card"],+ references: [+ {+ type: "resolved-template",+ path: [0],+ templateName: "Hero Card",+ props: [],+ templateInstanceId: "hero",+ },+ {+ type: "unresolved-template",+ path: [1],+ templateName: "Missing",+ },+ ],+ diagnostics: [+ {+ code: "unresolved-template",+ severity: "warning",+ blockInstanceId: "block",+ assetId: "article",+ contentRef: "articles/hello.mdx",+ renderScope: "route:/hello",+ templateName: "Missing",+ },+ ],+};++const metas = new Map<string, WsComponentMeta>([+ [+ "Card",+ {+ props: {+ tone: {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ },+ featured: {+ type: "boolean",+ control: "boolean",+ required: false,+ contentMode: true,+ },+ title: {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ },+ count: {+ type: "number",+ control: "number",+ required: false,+ contentMode: true,+ },+ layout: {+ type: "string",+ control: "text",+ required: false,+ },+ },+ },+ ],+]);++const createData = (): Omit<WebstudioData, "pages"> => {+ const hero: Instance = {+ type: "instance",+ id: "hero",+ component: "Card",+ children: [{ type: "id", value: "heading" }],+ };+ const heading: Instance = {+ type: "instance",+ id: "heading",+ component: "ws:element",+ tag: "h2",+ children: [{ type: "text", value: "Template title" }],+ };+ const prop: Prop = {+ id: "hero:tone",+ instanceId: "hero",+ name: "tone",+ type: "string",+ value: "strong",+ };+ const duplicateToneProp: Prop = {+ ...prop,+ id: "hero:tone-duplicate",+ value: "duplicate",+ };+ const imageProp: Prop = {+ id: "hero:image",+ instanceId: "hero",+ name: "image",+ type: "asset",+ value: "image",+ };+ const expressionProp: Prop = {+ id: "hero:title",+ instanceId: "hero",+ name: "title",+ type: "expression",+ value: encodeDataVariableId("site-title"),+ };+ const countProp: Prop = {+ id: "hero:count",+ instanceId: "hero",+ name: "count",+ type: "number",+ value: 1,+ };+ const layoutProp: Prop = {+ id: "hero:layout",+ instanceId: "hero",+ name: "layout",+ type: "string",+ value: "contained",+ };+ const legacyProp: Prop = {+ id: "hero:legacy",+ instanceId: "hero",+ name: "legacy",+ type: "string",+ value: "Template legacy",+ };+ const asset: Asset = {+ id: "image",+ projectId: "source-project",+ name: "hero.png",+ type: "image",+ format: "png",+ size: 100,+ meta: { width: 10, height: 10 },+ createdAt: "2026-01-01T00:00:00.000Z",+ };+ return {+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "templates" }],+ },+ ],+ [+ "templates",+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [{ type: "id", value: hero.id }],+ },+ ],+ [hero.id, hero],+ [heading.id, heading],+ ]),+ props: new Map<Prop["id"], Prop>([+ [prop.id, prop],+ [duplicateToneProp.id, duplicateToneProp],+ [imageProp.id, imageProp],+ [expressionProp.id, expressionProp],+ [countProp.id, countProp],+ [layoutProp.id, layoutProp],+ [legacyProp.id, legacyProp],+ ]),+ dataSources: new Map([+ [+ "site-title",+ {+ type: "variable",+ id: "site-title",+ name: "Site Title",+ value: { type: "string", value: "Webstudio" },+ },+ ],+ ]),+ resources: new Map(),+ styleSources: new Map([+ ["token", { type: "token", id: "token", name: "Card" }],+ ["hero-local", { type: "local", id: "hero-local" }],+ ]),+ styleSourceSelections: new Map([+ ["hero", { instanceId: "hero", values: ["token", "hero-local"] }],+ ]),+ styles: new Map([+ [+ "hero-local:base:color:",+ {+ styleSourceId: "hero-local",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ [+ "token:base:display:",+ {+ styleSourceId: "token",+ breakpointId: "base",+ property: "display",+ value: { type: "keyword", value: "block" },+ },+ ],+ ]),+ breakpoints: new Map([["base", { id: "base", label: "" }]]),+ assets: new Map([[asset.id, asset]]),+ };+};++const getResolvedTemplate = (+ templates: readonly MaterializedMdxTemplate[]+): Extract<MaterializedMdxTemplate, { type: "resolved-template" }> => {+ for (const template of templates) {+ if (template.type === "resolved-template") {+ return template;+ }+ }+ throw new Error("Expected a resolved template");+};++const getUnresolvedTemplate = (+ templates: readonly MaterializedMdxTemplate[]+): Extract<MaterializedMdxTemplate, { type: "unresolved-template" }> => {+ for (const template of templates) {+ if (template.type === "unresolved-template") {+ return template;+ }+ }+ throw new Error("Expected an unresolved template");+};++describe("materializeMdxTemplates", () => {+ test("copies resolved fragments and represents unresolved usages", async () => {+ const data = createData();+ const originalData = structuredClone(data);+ const materialization = await materializeMdxTemplates({+ identity,+ resolution,+ data,+ metas,+ projectId: "target-project",+ });+ const materializedTemplates = materialization.templates;+ const materialized = getResolvedTemplate(materializedTemplates);++ expect(materializedTemplates).toHaveLength(2);+ expect(materialized.reference.templateName).toBe("Hero Card");+ expect(materialized.fragment.children).toEqual([+ { type: "id", value: expect.stringMatching(/^mdx-/) },+ ]);+ expect(materialized.fragment.instances).toEqual([+ expect.objectContaining({+ component: "Card",+ children: [{ type: "id", value: expect.stringMatching(/^mdx-/) }],+ }),+ expect.objectContaining({+ component: "ws:element",+ tag: "h2",+ children: [{ type: "text", value: "Template title" }],+ }),+ ]);+ expect(materialized.fragment.props).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ name: "tone", value: "strong" }),+ expect.objectContaining({+ name: "image",+ type: "asset",+ value: "image",+ }),+ expect.objectContaining({+ name: "title",+ type: "expression",+ value: encodeDataVariableId("site-title"),+ }),+ ])+ );+ expect(materialized.fragment.styleSources).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ type: "token", name: "Card" }),+ expect.objectContaining({ type: "local" }),+ ])+ );+ expect(materialized.fragment.styles).toHaveLength(2);+ expect(materialized.fragment.assets).toEqual([+ expect.objectContaining({ id: "image", projectId: "target-project" }),+ ]);+ expect(data).toEqual(originalData);+ expect(materializedTemplates[1]).toEqual(+ expect.objectContaining({+ type: "unresolved-template",+ markerId: expect.stringMatching(/^mdx-/),+ reference: expect.objectContaining({+ type: "unresolved-template",+ templateName: "Missing",+ }),+ })+ );+ expect(materialization.diagnostics).toEqual([+ expect.objectContaining({+ code: "unresolved-template",+ templateName: "Missing",+ }),+ ]);+ });++ test("rejects a resolved reference when its template was removed", async () => {+ const data = createData();+ data.instances.delete("hero");++ await expect(+ materializeMdxTemplates({+ identity,+ resolution,+ data,+ metas,+ projectId: "target-project",+ })+ ).rejects.toThrow('Resolved MDX template instance "hero" is missing');+ });++ test("generates stable IDs scoped by Asset, render scope, and usage path", async () => {+ const materialize = (+ nextIdentity: ContentBlockExternalContentIdentity,+ nextResolution: MdxTemplateResolution = resolution+ ) =>+ materializeMdxTemplates({+ identity: nextIdentity,+ resolution: nextResolution,+ data: createData(),+ metas,+ projectId: "target-project",+ });+ const materializeRootId = async (+ nextIdentity: ContentBlockExternalContentIdentity,+ nextResolution: MdxTemplateResolution = resolution+ ) =>+ getResolvedTemplate(+ (await materialize(nextIdentity, nextResolution)).templates+ ).fragment.children[0];+ const materializeMarkerId = async (+ nextIdentity: ContentBlockExternalContentIdentity+ ) =>+ getUnresolvedTemplate((await materialize(nextIdentity)).templates)+ .markerId;++ const first = await materializeRootId(identity);+ expect(await materializeRootId(identity)).toEqual(first);+ expect(+ await materializeRootId({ ...identity, revision: "revision-2" })+ ).toEqual(first);+ expect(+ await materializeRootId({ ...identity, assetId: "other-asset" })+ ).not.toEqual(first);+ expect(+ await materializeRootId({ ...identity, renderScope: "route:/other" })+ ).not.toEqual(first);+ const markerId = await materializeMarkerId(identity);+ expect(await materializeMarkerId(identity)).toBe(markerId);+ expect(+ await materializeMarkerId({ ...identity, revision: "revision-2" })+ ).toBe(markerId);+ expect(+ await materializeMarkerId({ ...identity, renderScope: "route:/other" })+ ).not.toBe(markerId);+ expect(+ await materializeRootId(identity, {+ references: [+ {+ type: "resolved-template",+ path: [2],+ templateName: "Hero Card",+ props: [],+ templateInstanceId: "hero",+ },+ ],+ diagnostics: [],+ templateNames: ["Hero Card"],+ })+ ).not.toEqual(first);+ });++ test("applies valid props and preserves ignored authored props", async () => {+ const source = `<ws.element ws:name="Card" tone="quiet" featured title="Authored title" count="2" layout="wide" legacy="Authored legacy" missing="preserved" customCount="2" customFlag="false" />`;+ const document = await parseMdxDocument({ source });+ const authoredDocument = structuredClone(document);+ const data = createData();+ data.props.set("hero:custom-count", {+ id: "hero:custom-count",+ instanceId: "hero",+ name: "customCount",+ type: "number",+ value: 1,+ });+ data.props.set("hero:custom-flag", {+ id: "hero:custom-flag",+ instanceId: "hero",+ name: "customFlag",+ type: "boolean",+ value: true,+ });+ const originalData = structuredClone(data);+ const materialization = await materializeMdxTemplates({+ identity,+ resolution: resolveMdxTemplates({+ document,+ identity,+ instances: data.instances,+ metas,+ }),+ data,+ metas,+ projectId: "target-project",+ });+ const materialized = getResolvedTemplate(materialization.templates);++ expect(materialized.editablePropNames).toEqual([+ "tone",+ "featured",+ "title",+ "count",+ "legacy",+ "customCount",+ "customFlag",+ "missing",+ ]);+ expect(materialized.fragment.props).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ name: "tone", value: "quiet" }),+ expect.objectContaining({ name: "featured", value: true }),+ expect.objectContaining({+ name: "title",+ type: "string",+ value: "Authored title",+ }),+ expect.objectContaining({ name: "count", type: "number", value: 2 }),+ expect.objectContaining({ name: "layout", value: "contained" }),+ expect.objectContaining({+ name: "legacy",+ value: "Authored legacy",+ }),+ expect.objectContaining({+ name: "customCount",+ type: "number",+ value: 2,+ }),+ expect.objectContaining({+ name: "customFlag",+ type: "boolean",+ value: false,+ }),+ ])+ );+ expect(materialized.fragment.dataSources).toEqual([]);+ expect(+ materialized.fragment.props.filter((prop) => prop.name === "tone")+ ).toEqual([expect.objectContaining({ type: "string", value: "quiet" })]);+ expect(+ materialized.fragment.props.find((prop) => prop.name === "missing")+ ).toEqual(expect.objectContaining({ type: "string", value: "preserved" }));+ expect(document).toEqual(authoredDocument);+ expect(data).toEqual(originalData);+ expect(+ (await parseMdxDocument({ source: serializeMdxDocument(document) }))+ .children[0]+ ).toMatchObject({+ type: "template",+ props: [+ { name: "tone", value: "quiet" },+ { name: "featured", value: true },+ { name: "title", value: "Authored title" },+ { name: "count", value: "2" },+ { name: "layout", value: "wide" },+ { name: "legacy", value: "Authored legacy" },+ { name: "missing", value: "preserved" },+ { name: "customCount", value: "2" },+ { name: "customFlag", value: "false" },+ ],+ });+ expect(materialization.diagnostics).toEqual([+ expect.objectContaining({+ code: "ignored-template-prop",+ propName: "layout",+ reason: "design-only",+ }),+ ]);+ });++ test("moves the legacy Code Text property into text content", async () => {+ const data = createData();+ const codeText = data.instances.get("hero");+ if (codeText === undefined) {+ throw new Error("Expected template instance");+ }+ codeText.component = "CodeText";+ codeText.children = [{ type: "text", value: "template code" }];+ data.props.clear();+ const materialization = await materializeMdxTemplates({+ identity,+ resolution: {+ templateNames: ["Code Text"],+ diagnostics: [],+ references: [+ {+ type: "resolved-template",+ path: [0],+ templateName: "Code Text",+ templateInstanceId: "hero",+ props: [{ name: "code", value: "const answer = 42;" }],+ },+ ],+ },+ data,+ metas: new Map([+ [+ "CodeText",+ {+ contentModel: { category: "instance", children: ["text"] },+ },+ ],+ ]),+ projectId: "target-project",+ });+ const materialized = getResolvedTemplate(materialization.templates);+ const rootId = materialized.fragment.children[0]?.value;+ const root = materialized.fragment.instances.find(+ (instance) => instance.id === rootId+ );++ expect(root?.children).toEqual([+ { type: "text", value: "const answer = 42;" },+ ]);+ expect(materialized.fragment.props).toEqual([]);+ expect(materialization.diagnostics).toEqual([]);+ });++ test("materializes JSX aliases as standard Webstudio HTML props", async () => {+ const data = createData();+ const codeText = data.instances.get("hero");+ if (codeText === undefined) {+ throw new Error("Expected template instance");+ }+ codeText.component = "CodeText";+ codeText.children = [{ type: "text", value: "const ready = true;" }];+ data.props.clear();+ const document = await parseMdxDocument({+ source:+ '<ws.element ws:name="CodeText" className="example" tabIndex="2" hidden="false">const ready = true;</ws.element>',+ });+ const codeTextMetas = new Map<string, WsComponentMeta>([+ ["CodeText", { presetStyle: { code: [] } }],+ ]);+ const materialization = await materializeMdxTemplates({+ identity,+ resolution: resolveMdxTemplates({+ document,+ identity,+ instances: data.instances,+ metas: codeTextMetas,+ }),+ data,+ metas: codeTextMetas,+ projectId: "target-project",+ });+ const materialized = getResolvedTemplate(materialization.templates);++ expect(materialized.fragment.props).toEqual([+ expect.objectContaining({+ name: "class",+ type: "string",+ value: "example",+ }),+ expect.objectContaining({+ name: "tabindex",+ type: "number",+ value: 2,+ }),+ expect.objectContaining({+ name: "hidden",+ type: "boolean",+ value: false,+ }),+ ]);+ expect(materialized.editablePropNames).toContain("class");+ expect(materialization.diagnostics).toEqual([]);+ });++ test("normalizes class even when component metadata uses className", async () => {+ const data = createData();+ const card = data.instances.get("hero");+ if (card === undefined) {+ throw new Error("Expected template instance");+ }+ card.tag = "div";+ data.props.set("hero:className", {+ id: "hero:className",+ instanceId: card.id,+ name: "className",+ type: "string",+ value: "template",+ });+ const cardMetas = new Map<string, WsComponentMeta>([+ [+ "Card",+ {+ presetStyle: { div: [] },+ props: {+ className: {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ },+ },+ },+ ],+ ]);+ const document = await parseMdxDocument({+ source: '<ws.element ws:name="Card" className="authored" />',+ });+ const materialization = await materializeMdxTemplates({+ identity,+ resolution: resolveMdxTemplates({+ document,+ identity,+ instances: data.instances,+ metas: cardMetas,+ }),+ data,+ metas: cardMetas,+ projectId: "target-project",+ });+ const materialized = getResolvedTemplate(materialization.templates);++ expect(materialized.fragment.props).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ name: "class",+ type: "string",+ value: "authored",+ }),+ ])+ );+ expect(+ materialized.fragment.props.some(({ name }) => name === "className")+ ).toBe(false);+ expect(materialized.propNameMappings).toContainEqual({+ jsxPropName: "className",+ instancePropName: "class",+ });+ });++ test("normalizes a stored JSX-form alias when it is authored", async () => {+ const data = createData();+ const card = data.instances.get("hero");+ if (card === undefined) {+ throw new Error("Expected template instance");+ }+ card.tag = "div";+ data.props.set("hero:tabIndex", {+ id: "hero:tabIndex",+ instanceId: card.id,+ name: "tabIndex",+ type: "number",+ value: 1,+ });+ const materialization = await materializeMdxTemplates({+ identity,+ resolution: {+ ...resolution,+ references: [+ {+ type: "resolved-template",+ path: [0],+ templateName: "Hero Card",+ templateInstanceId: "hero",+ props: [{ name: "tabIndex", value: "2" }],+ },+ ],+ },+ data,+ metas,+ projectId: "target-project",+ });+ const materialized = getResolvedTemplate(materialization.templates);++ expect(materialized.fragment.props).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ name: "tabindex",+ type: "number",+ value: 2,+ }),+ ])+ );+ expect(+ materialized.fragment.props.some(({ name }) => name === "tabIndex")+ ).toBe(false);+ });++ test("normalizes a stored JSX-form alias without an authored override", async () => {+ const data = createData();+ const card = data.instances.get("hero");+ if (card === undefined) {+ throw new Error("Expected template instance");+ }+ card.tag = "div";+ data.props.set("hero:tabIndex", {+ id: "hero:tabIndex",+ instanceId: card.id,+ name: "tabIndex",+ type: "number",+ value: 1,+ });+ const materialization = await materializeMdxTemplates({+ identity,+ resolution,+ data,+ metas,+ projectId: "target-project",+ });+ const materialized = getResolvedTemplate(materialization.templates);++ expect(materialized.fragment.props).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ name: "tabindex", type: "number", value: 1 }),+ ])+ );+ expect(+ materialized.fragment.props.some(({ name }) => name === "tabIndex")+ ).toBe(false);+ });++ test("maps stored standard props to canonical JSX names", async () => {+ const data = createData();+ const card = data.instances.get("hero");+ if (card === undefined) {+ throw new Error("Expected template instance");+ }+ card.tag = "div";+ data.props.set("hero:class", {+ id: "hero:class",+ instanceId: card.id,+ name: "class",+ type: "string",+ value: "featured",+ });+ const materialization = await materializeMdxTemplates({+ identity,+ resolution,+ data,+ metas,+ projectId: "target-project",+ });+ const materialized = getResolvedTemplate(materialization.templates);++ expect(materialized.propNameMappings).toContainEqual({+ jsxPropName: "className",+ instancePropName: "class",+ });+ });++ test("does not let standard attributes bypass design-only component props", async () => {+ const data = createData();+ const link = data.instances.get("hero");+ if (link === undefined) {+ throw new Error("Expected template instance");+ }+ link.component = "Link";+ data.props.clear();+ const document = await parseMdxDocument({+ source: '<ws.element ws:name="Link" target="_blank" />',+ });+ const linkMetas = new Map<string, WsComponentMeta>([+ [+ "Link",+ {+ presetStyle: { a: [] },+ props: {+ target: {+ type: "string",+ control: "text",+ required: false,+ },+ },+ },+ ],+ ]);+ const materialization = await materializeMdxTemplates({+ identity,+ resolution: resolveMdxTemplates({+ document,+ identity,+ instances: data.instances,+ metas: linkMetas,+ }),+ data,+ metas: linkMetas,+ projectId: "target-project",+ });+ const materialized = getResolvedTemplate(materialization.templates);++ expect(+ materialized.fragment.props.find(({ name }) => name === "target")+ ).toBeUndefined();+ expect(materialization.diagnostics).toEqual([+ expect.objectContaining({+ code: "ignored-template-prop",+ propName: "target",+ reason: "design-only",+ }),+ ]);+ });++ test("does not let JSX aliases bypass design-only component props", async () => {+ const data = createData();+ const card = data.instances.get("hero");+ if (card === undefined) {+ throw new Error("Expected template instance");+ }+ card.tag = "div";+ data.props.clear();+ const document = await parseMdxDocument({+ source: '<ws.element ws:name="Card" className="authored" />',+ });+ const cardMetas = new Map<string, WsComponentMeta>([+ [+ "Card",+ {+ presetStyle: { div: [] },+ props: {+ className: {+ type: "string",+ control: "text",+ required: false,+ },+ },+ },+ ],+ ]);+ const materialization = await materializeMdxTemplates({+ identity,+ resolution: resolveMdxTemplates({+ document,+ identity,+ instances: data.instances,+ metas: cardMetas,+ }),+ data,+ metas: cardMetas,+ projectId: "target-project",+ });+ const materialized = getResolvedTemplate(materialization.templates);++ expect(+ materialized.fragment.props.some(({ name }) => name === "class")+ ).toBe(false);+ expect(materialization.diagnostics).toEqual([+ expect.objectContaining({+ code: "ignored-template-prop",+ propName: "className",+ reason: "design-only",+ }),+ ]);+ });++ test("renders the canonical prop and preserves a conflicting authored alias", async () => {+ const data = createData();+ const card = data.instances.get("hero");+ if (card === undefined) {+ throw new Error("Expected template instance");+ }+ card.tag = "div";+ data.props.clear();+ const document = await parseMdxDocument({+ source:+ '<ws.element ws:name="Card" class="legacy" className="canonical" />',+ });+ const cardMetas = new Map<string, WsComponentMeta>([+ [+ "Card",+ {+ presetStyle: { div: [] },+ props: {+ className: {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ },+ },+ },+ ],+ ]);+ const templateMaterialization = await materializeMdxTemplates({+ identity,+ resolution: resolveMdxTemplates({+ document,+ identity,+ instances: data.instances,+ metas: cardMetas,+ }),+ data,+ metas: cardMetas,+ projectId: "target-project",+ });+ const materialized = getResolvedTemplate(templateMaterialization.templates);++ expect(materialized.fragment.props).toEqual([+ expect.objectContaining({ name: "class", value: "canonical" }),+ ]);+ expect(materialized.ignoredJsxPropNames).toEqual(["class"]);+ expect(templateMaterialization.diagnostics).toEqual([+ expect.objectContaining({+ code: "ignored-template-prop",+ propName: "class",+ reason: "incompatible",+ sourceRange: {+ start: expect.objectContaining({ line: 1, column: 28 }),+ end: expect.objectContaining({ line: 1, column: 42 }),+ },+ }),+ ]);++ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization,+ });+ const next = structuredClone(root.fragment);+ const classProp = next.props.find(({ name }) => name === "class");+ if (classProp?.type !== "string") {+ throw new Error("Expected class prop");+ }+ classProp.value = "changed";++ expect(await serializeMdxAuthoredContent({ root, fragment: next })).toBe(+ '<ws.element ws:name="Card" class="legacy" className="changed" />\n'+ );+ });++ test("uses a valid alias when the canonical authored prop is invalid", async () => {+ const data = createData();+ const card = data.instances.get("hero");+ if (card === undefined) {+ throw new Error("Expected template instance");+ }+ card.tag = "div";+ data.props.clear();+ const document = await parseMdxDocument({+ source: '<ws.element ws:name="Card" class="valid" className />',+ });+ const cardMetas = new Map<string, WsComponentMeta>([+ [+ "Card",+ {+ presetStyle: { div: [] },+ props: {+ className: {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ },+ },+ },+ ],+ ]);+ const templateMaterialization = await materializeMdxTemplates({+ identity,+ resolution: resolveMdxTemplates({+ document,+ identity,+ instances: data.instances,+ metas: cardMetas,+ }),+ data,+ metas: cardMetas,+ projectId: "target-project",+ });+ const materialized = getResolvedTemplate(templateMaterialization.templates);++ expect(materialized.fragment.props).toEqual([+ expect.objectContaining({ name: "class", value: "valid" }),+ ]);+ expect(materialized.ignoredJsxPropNames).toEqual(["className"]);++ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization,+ });+ const next = structuredClone(root.fragment);+ const classProp = next.props.find(({ name }) => name === "class");+ if (classProp?.type !== "string") {+ throw new Error("Expected class prop");+ }+ classProp.value = "changed";++ expect(await serializeMdxAuthoredContent({ root, fragment: next })).toBe(+ '<ws.element ws:name="Card" class="changed" className />\n'+ );+ });++ test("prefers a stored canonical prop over a conflicting JSX alias", async () => {+ const data = createData();+ const card = data.instances.get("hero");+ if (card === undefined) {+ throw new Error("Expected template instance");+ }+ card.tag = "div";+ data.props.clear();+ data.props.set("hero:className", {+ id: "hero:className",+ instanceId: card.id,+ name: "className",+ type: "string",+ value: "legacy",+ });+ data.props.set("hero:class", {+ id: "hero:class",+ instanceId: card.id,+ name: "class",+ type: "string",+ value: "canonical",+ });+ const materialization = await materializeMdxTemplates({+ identity,+ resolution,+ data,+ metas,+ projectId: "target-project",+ });+ const materialized = getResolvedTemplate(materialization.templates);++ expect(+ materialized.fragment.props.filter(({ name }) => name === "class")+ ).toEqual([expect.objectContaining({ value: "canonical" })]);+ expect(+ materialized.fragment.props.some(({ name }) => name === "className")+ ).toBe(false);+ expect(materialization.diagnostics).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ code: "ignored-template-prop",+ propName: "className",+ reason: "incompatible",+ }),+ ])+ );+ });++ test("isolates ignored props to the invalid template occurrence", async () => {+ const data = createData();+ const document = await parseMdxDocument({+ source:+ '<ws.element ws:name="Card" count="invalid" />\n\n<ws.element ws:name="Card" count="2" />',+ });+ const templateMaterialization = await materializeMdxTemplates({+ identity,+ resolution: resolveMdxTemplates({+ document,+ identity,+ instances: data.instances,+ metas,+ }),+ data,+ metas,+ projectId: "target-project",+ });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization,+ });+ const templates = root.provenance.nodes.filter(+ (node) => node.type === "template"+ );++ expect(templates).toHaveLength(2);+ expect(templates[0]?.editablePropNames).not.toContain("count");+ expect(templates[1]?.editablePropNames).toContain("count");+ });++ test("tracks effective names and deduplicated template revisions", async () => {+ const data = createData();+ const originalData = structuredClone(data);+ const materialize = (sourceData = data) =>+ materializeMdxTemplates({+ identity,+ resolution: {+ ...resolution,+ references: [+ resolution.references[0],+ {+ type: "resolved-template",+ path: [2],+ templateName: "Hero Card",+ templateInstanceId: "hero",+ props: [],+ },+ ],+ diagnostics: [],+ },+ data: sourceData,+ metas,+ projectId: "target-project",+ });++ const firstMaterialization = await materialize();+ expect(data).toEqual(originalData);+ const first = firstMaterialization.dependencies;+ expect(first.templateNames).toEqual(["Hero Card"]);+ expect(first.templates).toEqual([+ {+ templateInstanceId: "hero",+ templateName: "Hero Card",+ revision: expect.stringMatching(/^sha256:[0-9a-f]{64}$/),+ },+ ]);+ const rootIds = firstMaterialization.templates.flatMap((template) =>+ template.type === "resolved-template"+ ? template.fragment.children.map((child) => child.value)+ : []+ );+ expect(new Set(rootIds).size).toBe(2);++ const reorderedData = createData();+ const reorderedAsset = reorderedData.assets.get("image");+ if (reorderedAsset?.type !== "image") {+ throw new Error("Expected image Asset");+ }+ reorderedData.assets.set("image", {+ ...reorderedAsset,+ meta: { height: 10, width: 10 },+ });+ expect(+ (await materialize(reorderedData)).dependencies.templates[0].revision+ ).toBe(first.templates[0].revision);++ data.instances.get("heading")?.children.push({+ type: "text",+ value: "Changed",+ });+ expect((await materialize()).dependencies.templates[0].revision).not.toBe(+ first.templates[0].revision+ );+ });+});diff --git a/packages/project-build/src/runtime/mdx-materialization.ts b/packages/project-build/src/runtime/mdx-materialization.tsnew file mode 100644index 0000000000..9b61783b67--- /dev/null+++ b/packages/project-build/src/runtime/mdx-materialization.ts@@ -0,0 +1,702 @@+import hash from "@emotion/hash";+import { migrateCodeTextPropMutable } from "@webstudio-is/project-migrations";+import type { AssetValueReference } from "@webstudio-is/content-engine";+import { serializeJsonDeterministically } from "@webstudio-is/content-engine/compiler";+import {+ getInstancePropName,+ getJsxPropName,+ mapAttributeNames,+} from "@webstudio-is/content-engine/jsx-attributes";+import type { MdxAuthoredProp } from "@webstudio-is/content-engine/mdx";+import {+ getAssetContentHash,+ getHtmlTagFromInstance,+ type ContentBlockDiagnostic,+ type ContentBlockExternalContentIdentity,+ type Instance,+ type Prop,+ type WebstudioData,+ type WebstudioFragment,+ type WsComponentMeta,+} from "@webstudio-is/sdk";+import {+ getContentModeCapabilities,+ getContentModeEditableStaticPropNames,+ getContentModePropEligibility,+} from "./content-mode-permissions";+import { findAvailableVariables } from "./data";+import {+ createWebstudioDataFromFragment,+ extractWebstudioFragment,+ insertWebstudioFragmentCopy,+} from "./fragment";+import { createEmptyWebstudioFragment } from "./component-template";+import type {+ MdxTemplateReference,+ MdxTemplateResolution,+} from "./mdx-template-resolution";+import { createPropValue, findProp } from "./props";+import { getHtmlAttributeType } from "./html-attribute-utils";+import { parseMdxStaticProp, type MdxStaticPropType } from "./mdx-static-props";+import { getMdxPropValuePathKey } from "./mdx-asset-references";++const getMdxPropEligibility = ({+ capabilities,+ instance,+ prop,+ jsxPropName,+}: {+ capabilities: ReturnType<typeof getContentModeCapabilities>;+ instance: Instance;+ prop: Pick<Prop, "name" | "type">;+ jsxPropName?: string;+}) => {+ const contentModeEligibility = getContentModePropEligibility({+ capabilities,+ instance,+ prop: jsxPropName === undefined ? prop : { ...prop, name: jsxPropName },+ });+ if (contentModeEligibility.editable) {+ return contentModeEligibility;+ }+ if (contentModeEligibility.reason !== "unknown") {+ return contentModeEligibility;+ }+ const tag = getHtmlTagFromInstance({+ instance,+ metas: capabilities.metas,+ props: capabilities.props,+ htmlTagsByInstanceId: capabilities.htmlTagsByInstanceId,+ });+ if (tag === undefined) {+ return { editable: true } as const;+ }+ const attributeType = getHtmlAttributeType({ tag, name: prop.name });+ if (attributeType === undefined) {+ // The props panel can author arbitrary static properties. MDX accepts the+ // same names while explicit component metadata still protects design-only+ // and incompatible properties above.+ return { editable: true } as const;+ }+ return attributeType === prop.type+ ? ({ editable: true } as const)+ : ({ editable: false, reason: "incompatible" } as const);+};++const getMdxPropBinding = ({+ capabilities,+ instance,+ prop,+ existingType,+ jsxPropName,+}: {+ capabilities: ReturnType<typeof getContentModeCapabilities>;+ instance: Instance;+ prop: MdxAuthoredProp;+ existingType?: MdxStaticPropType;+ jsxPropName?: string;+}) => {+ const types: readonly MdxStaticPropType[] =+ existingType !== undefined+ ? [existingType]+ : prop.value === true+ ? ["boolean"]+ : ["string", "number", "boolean"];+ for (const type of types) {+ const binding = parseMdxStaticProp({ prop, type });+ if (+ binding !== undefined &&+ getMdxPropEligibility({+ capabilities,+ instance,+ prop: { name: prop.name, type: binding.type },+ jsxPropName,+ }).editable+ ) {+ return binding;+ }+ }+};++export type MdxJsxPropContext = Readonly<{+ acceptsHtmlAttributes: boolean;+ componentPropNames: readonly string[];+ htmlTag?: string;+ propTypes: readonly Readonly<{+ name: string;+ type: MdxStaticPropType;+ }>[];+}>;++export type MaterializedMdxTemplate =+ | Readonly<{+ type: "resolved-template";+ reference: Extract<MdxTemplateReference, { type: "resolved-template" }>;+ fragment: WebstudioFragment;+ editablePropNames: readonly string[];+ jsxPropContext: MdxJsxPropContext;+ propNameMappings: readonly Readonly<{+ jsxPropName: string;+ instancePropName: string;+ }>[];+ preservedJsxPropNames?: readonly string[];+ ignoredJsxPropNames: readonly string[];+ }>+ | Readonly<{+ type: "unresolved-template";+ reference: Extract<MdxTemplateReference, { type: "unresolved-template" }>;+ markerId: string;+ }>;++export type MdxTemplateDependency = Readonly<{+ templateInstanceId: Instance["id"];+ templateName: string;+ revision: `sha256:${string}`;+}>;++export type MdxTemplateMaterialization = Readonly<{+ templates: readonly MaterializedMdxTemplate[];+ diagnostics: readonly ContentBlockDiagnostic[];+ dependencies: Readonly<{+ templateNames: readonly string[];+ templates: readonly MdxTemplateDependency[];+ }>;+}>;++export const createMdxScopeIdGenerator = ({+ identity,+ path,+}: {+ identity: ContentBlockExternalContentIdentity;+ path: readonly number[];+}) => {+ const scope = hash(+ JSON.stringify([+ identity.blockInstanceId,+ identity.assetId,+ identity.renderScope,+ path,+ ])+ );+ let index = 0;+ return () => `mdx-${scope}-${index++}`;+};++export const materializeMdxTemplates = async ({+ identity,+ resolution,+ data,+ metas,+ projectId,+ assetReferences = [],+}: {+ identity: ContentBlockExternalContentIdentity;+ resolution: MdxTemplateResolution;+ data: Omit<WebstudioData, "pages">;+ metas: Map<string, WsComponentMeta>;+ projectId: string;+ assetReferences?: readonly AssetValueReference[];+}): Promise<MdxTemplateMaterialization> => {+ const materializedTemplates: MaterializedMdxTemplate[] = [];+ const diagnostics: ContentBlockDiagnostic[] = [...resolution.diagnostics];+ const sourceTemplates = new Map<+ Instance["id"],+ {+ fragment: WebstudioFragment;+ dependency: MdxTemplateDependency;+ }+ >();+ const assetReferenceByPath = new Map(+ assetReferences.map((reference) => [+ reference.path.map(String).join("/"),+ reference,+ ])+ );+ for (const reference of resolution.references) {+ if (reference.type === "unresolved-template") {+ materializedTemplates.push({+ type: "unresolved-template",+ reference,+ markerId: createMdxScopeIdGenerator({+ identity,+ path: reference.path,+ })(),+ });+ continue;+ }+ if (data.instances.has(reference.templateInstanceId) === false) {+ throw new Error(+ `Resolved MDX template instance "${reference.templateInstanceId}" is missing`+ );+ }++ let sourceTemplate = sourceTemplates.get(reference.templateInstanceId);+ if (sourceTemplate === undefined) {+ const fragment = extractWebstudioFragment(+ data,+ reference.templateInstanceId+ );+ sourceTemplate = {+ fragment,+ dependency: {+ templateInstanceId: reference.templateInstanceId,+ templateName: reference.templateName,+ revision: `sha256:${await getAssetContentHash(+ new TextEncoder().encode(serializeJsonDeterministically(fragment))+ )}`,+ },+ };+ sourceTemplates.set(reference.templateInstanceId, sourceTemplate);+ }+ const sourceFragment = sourceTemplate.fragment;+ const materializedData = createWebstudioDataFromFragment(+ createEmptyWebstudioFragment()+ );+ const createId = createMdxScopeIdGenerator({+ identity,+ path: reference.path,+ });+ const { newInstanceIds } = insertWebstudioFragmentCopy({+ data: materializedData,+ fragment: sourceFragment,+ availableVariables: findAvailableVariables({+ startingInstanceId: reference.templateInstanceId,+ instances: data.instances,+ dataSources: data.dataSources,+ }),+ projectId,+ createId,+ });+ const materializedRootId = newInstanceIds.get(reference.templateInstanceId);+ if (materializedRootId === undefined) {+ throw new Error(+ `Materialized MDX template instance "${reference.templateInstanceId}" is missing`+ );+ }+ const rootInstance = materializedData.instances.get(materializedRootId);+ if (rootInstance === undefined) {+ throw new Error(+ `Materialized MDX template root "${materializedRootId}" is missing`+ );+ }+ const declaredJsxPropNames = new Set(+ Object.keys(metas.get(rootInstance.component)?.props ?? {})+ );+ const htmlTag = getHtmlTagFromInstance({+ instance: rootInstance,+ metas,+ props: materializedData.props,+ });+ const acceptsHtmlAttributes = htmlTag !== undefined;+ const addIgnoredPropDiagnostic = (+ propName: string,+ reason: Extract<+ ContentBlockDiagnostic,+ { code: "ignored-template-prop" }+ >["reason"],+ sourceRange = reference.sourceRange+ ) => {+ diagnostics.push({+ code: "ignored-template-prop",+ severity: "warning",+ blockInstanceId: identity.blockInstanceId,+ assetId: identity.assetId,+ contentRef: identity.contentRef,+ renderScope: identity.renderScope,+ templateName: reference.templateName,+ propName,+ reason,+ sourceRange,+ });+ };+ const mappedRootProps = Array.from(materializedData.props.values())+ .filter((prop) => prop.instanceId === materializedRootId)+ .map((prop) => ({+ prop,+ name: getInstancePropName({+ jsxPropName: prop.name,+ componentPropNames: declaredJsxPropNames,+ acceptsHtmlAttributes,+ }),+ }));+ const canonicalRootPropNames = new Set(+ mappedRootProps.flatMap(({ prop, name }) =>+ prop.name === name ? [name] : []+ )+ );+ const normalizedAliasNames = new Set<string>();+ for (const { prop, name } of mappedRootProps) {+ if (name === prop.name) {+ continue;+ }+ if (canonicalRootPropNames.has(name) || normalizedAliasNames.has(name)) {+ materializedData.props.delete(prop.id);+ addIgnoredPropDiagnostic(prop.name, "incompatible");+ continue;+ }+ prop.name = name;+ normalizedAliasNames.add(name);+ }+ const capabilities = getContentModeCapabilities({+ instances: materializedData.instances,+ metas,+ props: materializedData.props,+ styleSources: materializedData.styleSources,+ styleSourceSelections: materializedData.styleSourceSelections,+ styles: materializedData.styles,+ breakpoints: materializedData.breakpoints,+ contentRootIds: new Set([materializedRootId]),+ });+ const declaredPropMappings = mapAttributeNames({+ attributes: Array.from(declaredJsxPropNames, (jsxPropName) => ({+ name: jsxPropName,+ jsxPropName,+ })),+ direction: "jsx-to-instance",+ componentPropNames: declaredJsxPropNames,+ acceptsHtmlAttributes,+ });+ const declaredInstancePropNames = new Set(+ declaredPropMappings.map(({ name }) => name)+ );+ const declaredInstancePropNameByJsxName = new Map(+ declaredPropMappings.map(({ name, jsxPropName }) => [jsxPropName, name])+ );+ const declaredJsxPropNameByInstanceName = new Map(+ declaredPropMappings.map(({ name, jsxPropName }) => [name, jsxPropName])+ );+ const mappedReferenceProps = reference.props.map((prop) => ({+ ...prop,+ name: getInstancePropName({+ jsxPropName: prop.name,+ componentPropNames: declaredJsxPropNames,+ acceptsHtmlAttributes,+ }),+ }));+ const propIndexesByInstanceName = new Map<string, number[]>();+ for (const [index, prop] of mappedReferenceProps.entries()) {+ const indexes = propIndexesByInstanceName.get(prop.name) ?? [];+ indexes.push(index);+ propIndexesByInstanceName.set(prop.name, indexes);+ }+ const conflictingPropIndexes = new Set<number>();+ const collidedInstancePropNames = new Set<string>();+ for (const [instancePropName, indexes] of propIndexesByInstanceName) {+ if (indexes.length < 2) {+ continue;+ }+ collidedInstancePropNames.add(instancePropName);+ const canonicalJsxName = getJsxPropName({+ instancePropName,+ componentPropNames: declaredJsxPropNames,+ acceptsHtmlAttributes,+ });+ const orderedIndexes = indexes.toSorted((left, right) => {+ const leftIsCanonical =+ reference.props[left]?.name === canonicalJsxName;+ const rightIsCanonical =+ reference.props[right]?.name === canonicalJsxName;+ return Number(rightIsCanonical) - Number(leftIsCanonical);+ });+ const existingProp = findProp(+ materializedData.props.values(),+ materializedRootId,+ instancePropName+ );+ const selectedIndex =+ orderedIndexes.find((index) => {+ const authoredProp = reference.props[index];+ const instanceProp = mappedReferenceProps[index];+ if (authoredProp === undefined || instanceProp === undefined) {+ return false;+ }+ return (+ getMdxPropBinding({+ capabilities,+ instance: rootInstance,+ prop: instanceProp,+ jsxPropName: authoredProp.name,+ existingType:+ existingProp?.type === "string" ||+ existingProp?.type === "number" ||+ existingProp?.type === "boolean"+ ? existingProp.type+ : undefined,+ }) !== undefined+ );+ }) ?? orderedIndexes[0];+ for (const index of indexes) {+ if (index !== selectedIndex) {+ conflictingPropIndexes.add(index);+ }+ }+ }+ const propNameMappings: Array<{+ jsxPropName: string;+ instancePropName: string;+ }> = [];+ const ignoredJsxPropNames = new Set<string>();+ for (const [index, authoredProp] of reference.props.entries()) {+ const instanceProp = mappedReferenceProps[index];+ if (instanceProp === undefined) {+ throw new Error("Mapped MDX template prop is missing");+ }+ const instancePropName = instanceProp.name;+ if (conflictingPropIndexes.has(index)) {+ ignoredJsxPropNames.add(authoredProp.name);+ addIgnoredPropDiagnostic(+ authoredProp.name,+ "incompatible",+ authoredProp.sourceRange+ );+ continue;+ }+ const canonicalExistingProp = findProp(+ materializedData.props.values(),+ materializedRootId,+ instancePropName+ );+ const aliasedExistingProp =+ authoredProp.name === instancePropName+ ? undefined+ : findProp(+ materializedData.props.values(),+ materializedRootId,+ authoredProp.name+ );+ if (+ canonicalExistingProp !== undefined &&+ aliasedExistingProp !== undefined &&+ canonicalExistingProp.id !== aliasedExistingProp.id+ ) {+ throw new Error(+ `Multiple template properties map to "${instancePropName}"`+ );+ }+ const existingProp = canonicalExistingProp ?? aliasedExistingProp;+ const assetReference = assetReferenceByPath.get(+ getMdxPropValuePathKey({+ nodePath: reference.path,+ propIndex: index,+ })+ );+ const rawBinding =+ assetReference !== undefined+ ? ({ type: "asset", value: assetReference.assetId } as const)+ : authoredProp.value === true+ ? ({ type: "boolean", value: true } as const)+ : ({ type: "string", value: authoredProp.value } as const);+ if (+ migrateCodeTextPropMutable({+ instance: rootInstance,+ prop: createPropValue({+ id: existingProp?.id ?? "legacy-code",+ instanceId: materializedRootId,+ name: instancePropName,+ ...rawBinding,+ required: existingProp?.required,+ }),+ })+ ) {+ if (existingProp !== undefined) {+ materializedData.props.delete(existingProp.id);+ }+ continue;+ }+ const binding =+ rawBinding.type === "asset" &&+ getMdxPropEligibility({+ capabilities,+ instance: rootInstance,+ prop: { name: instancePropName, type: rawBinding.type },+ jsxPropName: authoredProp.name,+ }).editable+ ? rawBinding+ : getMdxPropBinding({+ capabilities,+ instance: rootInstance,+ prop: instanceProp,+ jsxPropName: authoredProp.name,+ existingType:+ existingProp?.type === "string" ||+ existingProp?.type === "number" ||+ existingProp?.type === "boolean"+ ? existingProp.type+ : undefined,+ });+ if (binding !== undefined) {+ const prop = createPropValue({+ id: existingProp?.id ?? createId(),+ instanceId: materializedRootId,+ name: instancePropName,+ ...binding,+ required: existingProp?.required,+ });+ materializedData.props.set(prop.id, prop);+ for (const candidate of materializedData.props.values()) {+ if (+ candidate.id !== prop.id &&+ candidate.instanceId === materializedRootId &&+ candidate.name === instancePropName+ ) {+ materializedData.props.delete(candidate.id);+ }+ }+ propNameMappings.push({+ jsxPropName: authoredProp.name,+ instancePropName,+ });+ continue;+ }+ const eligibility = getMdxPropEligibility({+ capabilities,+ instance: rootInstance,+ prop: { name: instancePropName, type: rawBinding.type },+ jsxPropName: authoredProp.name,+ });+ propNameMappings.push({+ jsxPropName: authoredProp.name,+ instancePropName,+ });+ // A persisted prop that is no longer recognized by the root's current+ // component/tag contract is stale in this template revision. An+ // authored name with no persisted history remains unknown.+ const reason = eligibility.editable+ ? "incompatible"+ : eligibility.reason === "unknown" && existingProp !== undefined+ ? "stale"+ : eligibility.reason;+ addIgnoredPropDiagnostic(+ authoredProp.name,+ reason,+ authoredProp.sourceRange+ );+ ignoredJsxPropNames.add(authoredProp.name);+ }++ const declaredEditablePropNames = Array.from(+ getContentModeEditableStaticPropNames({+ capabilities,+ instance: rootInstance,+ }),+ (name) => declaredInstancePropNameByJsxName.get(name) ?? name+ );+ const editablePropNames = Array.from(+ new Set([+ ...declaredEditablePropNames,+ ...Array.from(materializedData.props.values()).flatMap((prop) =>+ prop.instanceId === rootInstance.id &&+ (prop.type === "string" ||+ prop.type === "number" ||+ prop.type === "boolean") &&+ getMdxPropEligibility({+ capabilities,+ instance: rootInstance,+ prop,+ jsxPropName:+ declaredJsxPropNameByInstanceName.get(prop.name) ?? prop.name,+ }).editable+ ? [prop.name]+ : []+ ),+ ])+ );+ const editablePropNameSet = new Set(editablePropNames);+ const canonicalPropNameMappings = mapAttributeNames({+ attributes: editablePropNames.map((instancePropName) => ({+ name: instancePropName,+ instancePropName,+ })),+ direction: "instance-to-jsx",+ componentPropNames: declaredInstancePropNames,+ acceptsHtmlAttributes,+ });+ for (let index = propNameMappings.length - 1; index >= 0; index--) {+ const mapping = propNameMappings[index];+ if (+ mapping !== undefined &&+ editablePropNameSet.has(mapping.instancePropName) &&+ collidedInstancePropNames.has(mapping.instancePropName) === false+ ) {+ propNameMappings.splice(index, 1);+ }+ }+ for (const mappedProp of canonicalPropNameMappings) {+ if (collidedInstancePropNames.has(mappedProp.instancePropName)) {+ continue;+ }+ propNameMappings.push({+ jsxPropName: mappedProp.name,+ instancePropName: mappedProp.instancePropName,+ });+ }+ const propTypes = new Map<string, MdxStaticPropType>();+ for (const name of editablePropNames) {+ const propMeta = metas.get(rootInstance.component)?.props?.[+ declaredJsxPropNameByInstanceName.get(name) ?? name+ ];+ if (+ propMeta?.contentMode === true &&+ (propMeta.type === "string" ||+ propMeta.type === "number" ||+ propMeta.type === "boolean")+ ) {+ propTypes.set(name, propMeta.type);+ continue;+ }+ const existingProp = findProp(+ materializedData.props.values(),+ materializedRootId,+ name+ );+ if (+ existingProp?.type === "string" ||+ existingProp?.type === "number" ||+ existingProp?.type === "boolean"+ ) {+ propTypes.set(name, existingProp.type);+ continue;+ }+ if (htmlTag !== undefined) {+ const type = getHtmlAttributeType({ tag: htmlTag, name });+ if (type !== undefined) {+ propTypes.set(name, type);+ }+ }+ }++ materializedTemplates.push({+ type: "resolved-template",+ reference,+ fragment: extractWebstudioFragment(materializedData, materializedRootId),+ editablePropNames,+ jsxPropContext: {+ acceptsHtmlAttributes,+ componentPropNames: Array.from(declaredInstancePropNames),+ htmlTag,+ propTypes: Array.from(propTypes, ([name, type]) => ({ name, type })),+ },+ propNameMappings,+ preservedJsxPropNames: reference.props.flatMap((prop, index) => {+ const mapped = mappedReferenceProps[index];+ return mapped !== undefined &&+ collidedInstancePropNames.has(mapped.name) &&+ conflictingPropIndexes.has(index) === false+ ? [prop.name]+ : [];+ }),+ ignoredJsxPropNames: Array.from(ignoredJsxPropNames),+ });+ }+ return {+ templates: materializedTemplates,+ diagnostics,+ dependencies: {+ templateNames: resolution.templateNames,+ templates: Array.from(+ sourceTemplates.values(),+ ({ dependency }) => dependency+ ),+ },+ };+};diff --git a/packages/project-build/src/runtime/mdx-paste.test.ts b/packages/project-build/src/runtime/mdx-paste.test.tsnew file mode 100644index 0000000000..5afd67f5eb--- /dev/null+++ b/packages/project-build/src/runtime/mdx-paste.test.ts@@ -0,0 +1,94 @@+import { describe, expect, test } from "vitest";+import {+ blockComponent,+ blockTemplateComponent,+ elementComponent,+} from "@webstudio-is/sdk";+import { createDefaultPages } from "../shared/pages-utils";+import type { BuilderState } from "../state/builder-state";+import { executeBuilderRuntimeOperation } from "./registry";+import type { BuilderRuntimeMutation } from "./mutation";+import type { MdxPasteResult } from "./mdx-paste";++const createState = (): BuilderState => ({+ pages: createDefaultPages({ rootInstanceId: "block" }),+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "templates" }],+ },+ ],+ [+ "templates",+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [{ type: "id", value: "hero" }],+ },+ ],+ [+ "hero",+ {+ type: "instance",+ id: "hero",+ component: elementComponent,+ tag: "article",+ label: "Hero Card",+ children: [{ type: "text", value: "Template" }],+ },+ ],+ ]),+ props: new Map(),+ dataSources: new Map(),+ resources: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ breakpoints: new Map(),+ assets: new Map(),+});++const createId = () => {+ let index = 0;+ return () => `generated-${index++}`;+};++describe("instances.insertMdxText", () => {+ test("inserts Markdown and resolves destination template names", async () => {+ const mutation = await executeBuilderRuntimeOperation<+ BuilderRuntimeMutation<MdxPasteResult>+ >({+ id: "instances.insertMdxText",+ state: createState(),+ input: {+ parentInstanceId: "block",+ source: '# Heading\n\n<ws.element ws:name="Hero Card" />',+ },+ context: { createId: createId(), projectId: "project" },+ });++ expect(mutation.result.diagnostics).toEqual([]);+ expect(mutation.result.rootInstanceIds).toHaveLength(2);+ expect(mutation.payload).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ namespace: "instances" }),+ ])+ );+ });++ test("rejects invalid or executable MDX", async () => {+ await expect(+ executeBuilderRuntimeOperation({+ id: "instances.insertMdxText",+ state: createState(),+ input: { parentInstanceId: "block", source: '{alert("unsafe")}' },+ context: { createId: createId(), projectId: "project" },+ })+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });+ });+});diff --git a/packages/project-build/src/runtime/mdx-paste.ts b/packages/project-build/src/runtime/mdx-paste.tsnew file mode 100644index 0000000000..8d32c6521d--- /dev/null+++ b/packages/project-build/src/runtime/mdx-paste.ts@@ -0,0 +1,152 @@+import { parseMdxDocument } from "@webstudio-is/content-engine/mdx";+import {+ blockComponent,+ contentBlockDiagnostic,+ findParentInstanceReference,+ getAssetContentHash,+ type ContentBlockExternalContentIdentity,+ type Instance,+ type WebstudioData,+} from "@webstudio-is/sdk";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";+import { z } from "zod";+import type { BuilderState } from "../state/builder-state";+import { componentInsertResult } from "./component-insert-contract";+import { getRequiredComponentInsertData, insertFragment } from "./components";+import type { BuilderRuntimeContext } from "./context";+import { throwBuilderRuntimeError } from "./errors";+import {+ blockTemplateNameConfirmationInput,+ instanceInsertModeInput,+ insertIndexInput,+} from "./instances";+import { materializeMdxAuthoredContent } from "./mdx-authored-content";+import { materializeMdxTemplates } from "./mdx-materialization";+import { resolveMdxTemplates } from "./mdx-template-resolution";+import type { BuilderRuntimeMutation } from "./mutation";++export const insertMdxTextInput = z.object({+ parentInstanceId: z.string().min(1),+ source: z.string().min(1),+ mode: instanceInsertModeInput.optional(),+ insertIndex: insertIndexInput.optional(),+ templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),+});++export const mdxPasteResult = componentInsertResult.extend({+ diagnostics: z.array(contentBlockDiagnostic),+});++export type MdxPasteResult = z.infer<typeof mdxPasteResult>;++const findDestinationBlock = ({+ parentInstanceId,+ instances,+}: {+ parentInstanceId: Instance["id"];+ instances: WebstudioData["instances"];+}) => {+ let instance = instances.get(parentInstanceId);+ const visited = new Set<Instance["id"]>();+ while (instance !== undefined) {+ if (visited.has(instance.id)) {+ return;+ }+ visited.add(instance.id);+ if (instance.component === blockComponent) {+ return instance;+ }+ instance = findParentInstanceReference(instances, instance.id)?.instance;+ }+};++const createPasteIdentity = async ({+ blockInstanceId,+ parentInstanceId,+ source,+}: {+ blockInstanceId: Instance["id"];+ parentInstanceId: Instance["id"];+ source: string;+}): Promise<ContentBlockExternalContentIdentity> => ({+ blockInstanceId,+ assetId: "clipboard",+ revision: `sha256:${await getAssetContentHash(+ new TextEncoder().encode(source)+ )}`,+ contentRef: "clipboard.mdx",+ format: "mdx",+ renderScope: `paste:${parentInstanceId}`,+});++const parsePastedMdx = async (source: string) => {+ try {+ return await parseMdxDocument({ source });+ } catch {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Pasted text is not valid safe MDX."+ );+ }+};++export const insertMdxText = async ({+ state,+ input,+ context,+}: {+ state: BuilderState;+ input: z.infer<typeof insertMdxTextInput>;+ context: BuilderRuntimeContext;+}): Promise<BuilderRuntimeMutation<MdxPasteResult>> => {+ const data = getRequiredComponentInsertData(state);+ const destinationBlock = findDestinationBlock({+ parentInstanceId: input.parentInstanceId,+ instances: data.instances,+ });+ const identity = await createPasteIdentity({+ blockInstanceId: destinationBlock?.id ?? input.parentInstanceId,+ parentInstanceId: input.parentInstanceId,+ source: input.source,+ });+ const document = await parsePastedMdx(input.source);+ const resolution = resolveMdxTemplates({+ document,+ identity,+ instances: data.instances,+ metas: componentMetas,+ });+ const templateMaterialization = await materializeMdxTemplates({+ identity,+ resolution,+ data,+ metas: componentMetas,+ projectId: context.projectId ?? "",+ });+ const authored = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization,+ });+ const mutation = insertFragment(+ state,+ {+ parentInstanceId: input.parentInstanceId,+ fragment: authored.fragment,+ contentMode: destinationBlock !== undefined,+ mode: input.mode,+ insertIndex: input.insertIndex,+ templateNameConfirmation: input.templateNameConfirmation,+ },+ context+ );+ return {+ ...mutation,+ result: {+ ...mutation.result,+ parentInstanceId:+ mutation.result.parentInstanceId ?? input.parentInstanceId,+ diagnostics: [...templateMaterialization.diagnostics],+ },+ };+};diff --git a/packages/project-build/src/runtime/mdx-source.test.ts b/packages/project-build/src/runtime/mdx-source.test.tsnew file mode 100644index 0000000000..a8a94b229c--- /dev/null+++ b/packages/project-build/src/runtime/mdx-source.test.ts@@ -0,0 +1,306 @@+import { describe, expect, test } from "vitest";+import {+ type Asset,+ blockComponent,+ blockTemplateComponent,+ type ContentBlockExternalContentIdentity,+ type WebstudioData,+} from "@webstudio-is/sdk";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";+import { serializeMdxAuthoredContent } from "./mdx-authored-content";+import { materializeMdxSource } from "./mdx-source";++const identity: ContentBlockExternalContentIdentity = {+ blockInstanceId: "block",+ assetId: "article",+ revision: "sha256:revision",+ contentRef: "article.mdx",+ format: "mdx",+ renderScope: "page",+};++const data: Omit<WebstudioData, "pages"> = {+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "templates" }],+ },+ ],+ [+ "templates",+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ ]),+ props: new Map(),+ dataSources: new Map(),+ resources: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ breakpoints: new Map(),+ assets: new Map(),+};++describe("materializeMdxSource", () => {+ test("uses the shared recovery result and materializes valid siblings", async () => {+ const result = await materializeMdxSource({+ source: "# Hello\n\n{dangerous()}\n\nAfter",+ identity,+ data,+ metas: componentMetas,+ projectId: "project",+ });++ expect(result.root.fragment.instances.map(({ tag }) => tag)).toEqual([+ "h1",+ "p",+ ]);+ expect(result.diagnostics).toHaveLength(1);+ expect(result.diagnostics[0]).toMatchObject({+ code: "unsafe-mdx",+ contentRef: "article.mdx",+ renderScope: "page",+ });+ });++ test("reports authored elements that violate the HTML content model", async () => {+ const result = await materializeMdxSource({+ source: `1. test++ <ws.element ws:tag="li">nested item</ws.element>+`,+ identity,+ data,+ metas: componentMetas,+ projectId: "project",+ });++ expect(result.diagnostics).toEqual([+ expect.objectContaining({+ code: "invalid-mdx",+ severity: "error",+ message: "Placing <li> element inside a <li> violates HTML spec.",+ sourceRange: expect.objectContaining({+ start: expect.objectContaining({ line: 3 }),+ }),+ }),+ ]);+ });++ test("resolves relative authored Asset references with canonical Asset names", async () => {+ const sourceData: Omit<WebstudioData, "pages"> = {+ ...data,+ assetFolders: new Map(),+ assets: new Map<string, Asset>([+ [+ "article",+ {+ id: "article",+ projectId: "project",+ type: "file",+ format: "mdx",+ name: "article_hash.mdx",+ filename: "article",+ size: 0,+ createdAt: "2026-01-01T00:00:00.000Z",+ description: null,+ meta: {},+ },+ ],+ [+ "hero",+ {+ id: "hero",+ projectId: "project",+ type: "image",+ format: "png",+ name: "hero_hash.png",+ filename: "hero",+ size: 0,+ createdAt: "2026-01-01T00:00:00.000Z",+ description: null,+ meta: { width: 100, height: 100 },+ },+ ],+ ]),+ };++ const result = await materializeMdxSource({+ source: `---+featureImage:+ $ref: ./hero.png+---++`,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });++ expect(result.root.fragment.props).toContainEqual(+ expect.objectContaining({ name: "src", type: "asset", value: "hero" })+ );+ expect(result.root.fragment.assets).toEqual([+ expect.objectContaining({ id: "hero" }),+ ]);+ expect(result.root.resolvedFrontmatter).toMatchObject({+ featureImage: {+ id: "hero",+ src: expect.stringContaining("hero_hash.png"),+ width: 100,+ height: 100,+ },+ });+ });++ test("serializes an Asset selected on an inserted Image template", async () => {+ const sourceData: Omit<WebstudioData, "pages"> = {+ ...data,+ instances: new Map(data.instances),+ assetFolders: new Map(),+ assets: new Map<string, Asset>([+ [+ "article",+ {+ id: "article",+ projectId: "project",+ type: "file",+ format: "mdx",+ name: "article_hash.mdx",+ filename: "article",+ size: 0,+ createdAt: "2026-01-01T00:00:00.000Z",+ description: null,+ meta: {},+ },+ ],+ [+ "hero",+ {+ id: "hero",+ projectId: "project",+ type: "image",+ format: "png",+ name: "hero_hash.png",+ filename: "hero",+ size: 0,+ createdAt: "2026-01-01T00:00:00.000Z",+ description: null,+ meta: { width: 100, height: 100 },+ },+ ],+ ]),+ };+ sourceData.instances.set("image-template", {+ type: "instance",+ id: "image-template",+ component: "Image",+ children: [],+ });+ sourceData.instances.get("templates")?.children.push({+ type: "id",+ value: "image-template",+ });+ const result = await materializeMdxSource({+ source: '<ws.element ws:name="Image" />',+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const fragment = structuredClone(result.root.fragment);+ const image = fragment.instances.find(+ ({ component }) => component === "Image"+ );+ if (image === undefined) {+ throw new Error("Expected materialized Image");+ }+ for (const name of ["src", "width", "height", "alt"]) {+ fragment.props.push({+ id: `image-${name}`,+ instanceId: image.id,+ name,+ type: "asset",+ value: "hero",+ });+ }+ const hero = sourceData.assets.get("hero");+ if (hero === undefined) {+ throw new Error("Expected hero Asset");+ }+ fragment.assets.push(hero);++ const source = await serializeMdxAuthoredContent({+ root: result.root,+ fragment,+ });+ expect(source).toBe("\n");++ const customized = structuredClone(fragment);+ customized.props.push({+ id: "image-class",+ instanceId: image.id,+ name: "class",+ type: "string",+ value: "hero",+ });+ expect(+ await serializeMdxAuthoredContent({+ root: result.root,+ fragment: customized,+ })+ ).toBe(+ '<ws.element ws:name="Image" src="./hero.png" className="hero" />\n'+ );++ const reloaded = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ expect(+ reloaded.root.fragment.props.map(({ name, type, value }) => ({+ name,+ type,+ value,+ }))+ ).toEqual(+ ["src", "width", "height", "alt"].map((name) => ({+ name,+ type: "asset",+ value: "hero",+ }))+ );+ expect(reloaded.root.fragment.instances).toEqual([+ expect.objectContaining({ component: "Image" }),+ ]);++ const reset = structuredClone(reloaded.root.fragment);+ reset.props = reset.props.filter(({ name }) => name !== "src");+ const resetSource = await serializeMdxAuthoredContent({+ root: reloaded.root,+ fragment: reset,+ });+ expect(resetSource).toBe("![]()\n");+ const resetReloaded = await materializeMdxSource({+ source: resetSource,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ expect(resetReloaded.root.fragment.props).toEqual([]);+ });+});diff --git a/packages/project-build/src/runtime/mdx-source.ts b/packages/project-build/src/runtime/mdx-source.tsnew file mode 100644index 0000000000..97418915b8--- /dev/null+++ b/packages/project-build/src/runtime/mdx-source.ts@@ -0,0 +1,151 @@+import {+ discoverNamedMdxAssetReferences,+ parseMdxDocumentRecovering,+ type MdxDocument,+} from "@webstudio-is/content-engine/mdx";+import { resolveAssetValueReferences } from "@webstudio-is/content-engine";+import type {+ Asset,+ ContentBlockDiagnostic,+ ContentBlockExternalContentIdentity,+ WebstudioData,+ WsComponentMeta,+} from "@webstudio-is/sdk";+import {+ createAssetFolderHierarchy,+ formatAssetName,+ toAssetReferenceRuntimeData,+} from "@webstudio-is/sdk";+import {+ materializeMdxAuthoredContent,+ type MaterializedMdxAuthoredContentRoot,+} from "./mdx-authored-content";+import {+ createMdxContentModelDiagnostics,+ createMdxDiagnostics,+} from "./mdx-diagnostics";+import { createMdxAssetReferenceValues } from "./mdx-asset-references";+import { materializeMdxTemplates } from "./mdx-materialization";+import { resolveMdxTemplates } from "./mdx-template-resolution";++const emptyMdxDocument: MdxDocument = {+ frontmatter: { properties: {} },+ children: [],+};++export const materializeMdxSource = async ({+ source,+ identity,+ data,+ metas,+ projectId,+ parsed,+ createUnresolvedTemplateInstance,+}: {+ source: string;+ identity: ContentBlockExternalContentIdentity;+ data: Omit<WebstudioData, "pages">;+ metas: Map<string, WsComponentMeta>;+ projectId: string;+ parsed?: Readonly<{+ source: string;+ result: Awaited<ReturnType<typeof parseMdxDocumentRecovering>>;+ }>;+ createUnresolvedTemplateInstance?: Parameters<+ typeof materializeMdxAuthoredContent+ >[0]["createUnresolvedTemplateInstance"];+}): Promise<{+ root: MaterializedMdxAuthoredContentRoot;+ diagnostics: readonly ContentBlockDiagnostic[];+}> => {+ const parsedSource =+ parsed?.source === source+ ? parsed.result+ : await parseMdxDocumentRecovering({ source });+ const document =+ parsedSource.status === "parsed" ? parsedSource.document : emptyMdxDocument;+ const resolution = resolveMdxTemplates({+ document,+ identity,+ instances: data.instances,+ metas,+ });+ const sourceAsset = data.assets.get(identity.assetId);+ const hierarchy = createAssetFolderHierarchy(data.assetFolders ?? new Map());+ const getNamedAsset = (asset: Asset) => ({+ id: asset.id,+ name: formatAssetName(asset),+ folderNames: hierarchy.getPath(asset.folderId).map(({ name }) => name),+ });+ const assetReferences =+ sourceAsset === undefined+ ? []+ : discoverNamedMdxAssetReferences({+ document,+ source: getNamedAsset(sourceAsset),+ assets: Array.from(data.assets.values(), getNamedAsset),+ });+ const templates = await materializeMdxTemplates({+ identity,+ resolution,+ data,+ metas,+ projectId,+ assetReferences,+ });+ const authoredRoot = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: templates,+ assetReferences,+ assetReferenceValues:+ sourceAsset === undefined+ ? undefined+ : createMdxAssetReferenceValues({+ source: sourceAsset,+ assets: data.assets.values(),+ assetFolders: data.assetFolders ?? new Map(),+ }),+ createUnresolvedTemplateInstance,+ });+ const resolvedDocument = resolveAssetValueReferences({+ value: document,+ references: assetReferences.filter(({ assetId, structured }) => {+ const asset = data.assets.get(assetId);+ return !(+ structured === true &&+ asset?.type === "file" &&+ ["json", "md", "mdx"].includes(asset.format.toLowerCase())+ );+ }),+ runtimeAssets: Object.fromEntries(+ Array.from(data.assets.values(), (asset) => [+ asset.id,+ toAssetReferenceRuntimeData(asset, "https://webstudio.local"),+ ])+ ),+ });+ const root: MaterializedMdxAuthoredContentRoot = {+ ...authoredRoot,+ resolvedFrontmatter: resolvedDocument.frontmatter.properties,+ };+ const includedAssetIds = new Set(root.fragment.assets.map(({ id }) => id));+ for (const { assetId } of assetReferences) {+ const asset = data.assets.get(assetId);+ if (asset !== undefined && includedAssetIds.has(asset.id) === false) {+ includedAssetIds.add(asset.id);+ root.fragment.assets.push(asset);+ }+ }+ return {+ root,+ diagnostics: [+ ...createMdxDiagnostics({+ identity,+ diagnostics: parsedSource.diagnostics,+ }),+ ...templates.diagnostics,+ ...createMdxContentModelDiagnostics({ root, metas }),+ ],+ };+};diff --git a/packages/project-build/src/runtime/mdx-static-props.ts b/packages/project-build/src/runtime/mdx-static-props.tsnew file mode 100644index 0000000000..ccd4e6c117--- /dev/null+++ b/packages/project-build/src/runtime/mdx-static-props.ts@@ -0,0 +1,57 @@+import type { MdxAuthoredProp } from "@webstudio-is/content-engine/mdx";+import type { Prop } from "@webstudio-is/sdk";++export type MdxStaticPropType = "string" | "number" | "boolean";++type MdxStaticPropBinding =+ | { type: "string"; value: string }+ | { type: "number"; value: number }+ | { type: "boolean"; value: boolean };++export const serializeMdxStaticProp = (+ prop: Prop+): MdxAuthoredProp | undefined => {+ if (prop.type === "string") {+ return { name: prop.name, value: prop.value };+ }+ if (prop.type === "number" && Number.isFinite(prop.value)) {+ return { name: prop.name, value: String(prop.value) };+ }+ if (prop.type === "boolean") {+ return { name: prop.name, value: prop.value ? true : "false" };+ }+};++export const parseMdxStaticProp = ({+ prop,+ type,+}: {+ prop: MdxAuthoredProp;+ type: MdxStaticPropType;+}): MdxStaticPropBinding | undefined => {+ if (type === "string" && typeof prop.value === "string") {+ return { type, value: prop.value };+ }+ if (type === "number" && typeof prop.value === "string") {+ if (prop.value.trim() === "") {+ return;+ }+ try {+ const value: unknown = JSON.parse(prop.value);+ if (typeof value === "number" && Number.isFinite(value)) {+ return { type, value };+ }+ } catch {+ return;+ }+ return;+ }+ if (type === "boolean") {+ if (prop.value === true || prop.value === "true") {+ return { type, value: true };+ }+ if (prop.value === "false") {+ return { type, value: false };+ }+ }+};diff --git a/packages/project-build/src/runtime/mdx-template-migration.test.ts b/packages/project-build/src/runtime/mdx-template-migration.test.tsnew file mode 100644index 0000000000..05ee1ef7b5--- /dev/null+++ b/packages/project-build/src/runtime/mdx-template-migration.test.ts@@ -0,0 +1,105 @@+import { parseMdxDocument } from "@webstudio-is/content-engine/mdx";+import { describe, expect, test } from "vitest";+import { planMdxTemplateMigration } from "./mdx-template-migration";++const files = [+ {+ assetId: "article",+ revision: "revision-1",+ contentRef: "article.mdx-revision-1",+ source: `---\ntitle: Article\n---\n\n{/* keep */}\n\n<ws.element ws:name="Card">\n <ws.element ws:name="Card" />\n</ws.element>\n\n<ws.element ws:name="Other" />`,+ },+];++describe("MDX template migration", () => {+ test("rejects duplicate, excessive, and oversized file selections", async () => {+ const input = {+ projectId: "project",+ migration: { type: "remove", name: "Card" } as const,+ };+ await expect(+ planMdxTemplateMigration({ ...input, files: [files[0], files[0]] })+ ).rejects.toThrow('Duplicate MDX Asset "article"');+ await expect(+ planMdxTemplateMigration({+ ...input,+ files: Array.from({ length: 101 }, (_, index) => ({+ ...files[0],+ assetId: `article-${index}`,+ })),+ })+ ).rejects.toThrow("limited to 100 files");+ await expect(+ planMdxTemplateMigration({+ ...input,+ files: [+ {+ ...files[0],+ source: "x".repeat(10 * 1024 * 1024 + 1),+ },+ ],+ })+ ).rejects.toThrow("exceeds the 10 MiB limit");+ });++ test("previews nested AST renames while preserving frontmatter and comments", async () => {+ const plan = await planMdxTemplateMigration({+ projectId: "project",+ migration: { type: "rename", from: "Card", to: "Feature Card" },+ files,+ });++ expect(plan).toMatchObject({+ status: "confirmation-required",+ updateCount: 2,+ omissionCount: 0,+ changedFileCount: 1,+ files: [{ assetId: "article", changed: true, updateCount: 2 }],+ });+ const document = await parseMdxDocument({ source: plan.files[0].source });+ expect(document.frontmatter.properties).toEqual({ title: "Article" });+ expect(document.children[0]).toMatchObject({+ type: "comment",+ value: "/* keep */",+ });+ expect(document.children[1]).toMatchObject({+ type: "template",+ name: "Feature Card",+ children: [{ type: "template", name: "Feature Card" }],+ });+ expect(document.children[2]).toMatchObject({+ type: "template",+ name: "Other",+ });+ });++ test("omits the complete matching subtree and reports invalid files", async () => {+ const plan = await planMdxTemplateMigration({+ projectId: "project",+ migration: { type: "remove", name: "Card" },+ files: [+ ...files,+ { ...files[0], assetId: "invalid", source: "<ws.element>" },+ ],+ });++ expect(plan).toMatchObject({+ updateCount: 0,+ omissionCount: 1,+ changedFileCount: 1,+ files: [+ { assetId: "article", omissionCount: 1, diagnostics: [] },+ {+ assetId: "invalid",+ changed: false,+ diagnostics: [{ code: "invalid-mdx" }],+ },+ ],+ });+ const document = await parseMdxDocument({ source: plan.files[0].source });+ expect(document.children).toEqual([+ expect.objectContaining({ type: "comment" }),+ expect.objectContaining({ type: "template", name: "Other" }),+ ]);+ });+});diff --git a/packages/project-build/src/runtime/mdx-template-migration.ts b/packages/project-build/src/runtime/mdx-template-migration.tsnew file mode 100644index 0000000000..6c27fdaaa3--- /dev/null+++ b/packages/project-build/src/runtime/mdx-template-migration.ts@@ -0,0 +1,280 @@+import {+ parseMdxDocument,+ serializeMdxDocument,+ type MdxAuthoredNode,+ type MdxDocumentError,+ type MdxSourceRange,+} from "@webstudio-is/content-engine/mdx";+import {+ createConfirmationToken,+ validateConfirmationToken,+} from "../confirmation-token";++export const mdxTemplateMigrationFileLimit = 100;+const mdxTemplateMigrationByteLimit = 10 * 1024 * 1024;++export type MdxTemplateMigration = Readonly<+ | { type: "rename"; from: string; to: string }+ | { type: "remove"; name: string }+>;++export type MdxTemplateMigrationFile = Readonly<{+ assetId: string;+ revision: string;+ contentRef: string;+ source: string;+}>;++export type MdxTemplateMigrationDiagnostic = Readonly<{+ code:+ | "invalid-mdx"+ | "unsafe-mdx"+ | "asset-revision-conflict"+ | "asset-authorization-failed"+ | "asset-write-failed";+ assetId: string;+ contentRef: string;+ message: string;+ sourceRange?: MdxSourceRange;+}>;++export type MdxTemplateMigrationFilePlan = Readonly<{+ assetId: string;+ revision: string;+ contentRef: string;+ source: string;+ changed: boolean;+ updateCount: number;+ omissionCount: number;+ diagnostics: readonly MdxTemplateMigrationDiagnostic[];+}>;++export type MdxTemplateMigrationPlan = Readonly<{+ status: "confirmation-required";+ migration: MdxTemplateMigration;+ files: readonly MdxTemplateMigrationFilePlan[];+ updateCount: number;+ omissionCount: number;+ changedFileCount: number;+ selectionAssetIds: readonly string[];+ confirmationScope?: Readonly<Record<string, unknown>>;+ confirmationToken: string;+ confirmationExpiresAt: string;+}>;++const updateNodes = (+ nodes: readonly MdxAuthoredNode[],+ migration: MdxTemplateMigration+): {+ nodes: readonly MdxAuthoredNode[];+ updateCount: number;+ omissionCount: number;+} => {+ let updateCount = 0;+ let omissionCount = 0;+ let changed = false;+ const nextNodes: MdxAuthoredNode[] = [];+ for (const node of nodes) {+ const matches =+ node.type === "template" &&+ (migration.type === "rename"+ ? node.name === migration.from+ : node.name === migration.name);+ if (node.type === "template" && matches && migration.type === "remove") {+ omissionCount += 1;+ changed = true;+ continue;+ }+ if (+ node.type === "text" ||+ node.type === "comment" ||+ node.type === "opaque"+ ) {+ nextNodes.push(node);+ continue;+ }+ const children = updateNodes(node.children, migration);+ updateCount += children.updateCount;+ omissionCount += children.omissionCount;+ if (node.type === "template" && matches && migration.type === "rename") {+ updateCount += 1;+ changed = true;+ nextNodes.push({+ ...node,+ name: migration.to,+ children: children.nodes,+ });+ continue;+ }+ if (children.nodes !== node.children) {+ changed = true;+ nextNodes.push({ ...node, children: children.nodes });+ continue;+ }+ nextNodes.push(node);+ }+ return {+ nodes: changed ? nextNodes : nodes,+ updateCount,+ omissionCount,+ };+};++const toParseDiagnostic = (+ file: MdxTemplateMigrationFile,+ error: unknown+): MdxTemplateMigrationDiagnostic => ({+ code:+ typeof error === "object" &&+ error !== null &&+ "code" in error &&+ error.code === "unsafe-mdx"+ ? "unsafe-mdx"+ : "invalid-mdx",+ assetId: file.assetId,+ contentRef: file.contentRef,+ message: error instanceof Error ? error.message : "Unable to parse MDX",+ sourceRange: (error as MdxDocumentError | undefined)?.sourceRange,+});++const getConfirmationPayload = ({+ projectId,+ migration,+ files,+ selectionAssetIds,+ confirmationScope,+}: {+ projectId: string;+ migration: MdxTemplateMigration;+ files: readonly MdxTemplateMigrationFilePlan[];+ selectionAssetIds?: readonly string[];+ confirmationScope?: Readonly<Record<string, unknown>>;+}) => ({+ operation: "mdx-template-migration",+ projectId,+ migration,+ confirmationScope,+ selectionAssetIds:+ selectionAssetIds === undefined+ ? files.map(({ assetId }) => assetId).sort()+ : [...selectionAssetIds].sort(),+ files: files.map(({ assetId, revision, contentRef, source, changed }) => ({+ assetId,+ revision,+ contentRef,+ source,+ changed,+ })),+});++export const validateMdxTemplateMigrationConfirmation = ({+ projectId,+ plan,+ confirmationToken,+}: {+ projectId: string;+ plan: MdxTemplateMigrationPlan;+ confirmationToken?: string;+}) =>+ validateConfirmationToken(+ confirmationToken,+ getConfirmationPayload({+ projectId,+ migration: plan.migration,+ files: plan.files,+ selectionAssetIds: plan.selectionAssetIds,+ confirmationScope: plan.confirmationScope,+ })+ );++export const planMdxTemplateMigration = async ({+ projectId,+ migration,+ files,+ selectionAssetIds,+ confirmationScope,+ confirmationTtlMs = 5 * 60_000,+}: {+ projectId: string;+ migration: MdxTemplateMigration;+ files: readonly MdxTemplateMigrationFile[];+ selectionAssetIds?: readonly string[];+ confirmationScope?: Readonly<Record<string, unknown>>;+ confirmationTtlMs?: number;+}): Promise<MdxTemplateMigrationPlan> => {+ if (files.length > mdxTemplateMigrationFileLimit) {+ throw new Error("MDX template migration is limited to 100 files");+ }+ const selected = selectionAssetIds ?? files.map(({ assetId }) => assetId);+ if (+ selected.length > mdxTemplateMigrationFileLimit ||+ (selectionAssetIds !== undefined &&+ new Set(selected).size !== selected.length)+ ) {+ throw new Error("MDX template migration selection is invalid");+ }+ const seenAssetIds = new Set<string>();+ let totalBytes = 0;+ const encoder = new TextEncoder();+ const plannedFiles: MdxTemplateMigrationFilePlan[] = [];+ for (const file of files) {+ if (seenAssetIds.has(file.assetId)) {+ throw new Error(`Duplicate MDX Asset "${file.assetId}"`);+ }+ seenAssetIds.add(file.assetId);+ totalBytes += encoder.encode(file.source).byteLength;+ if (totalBytes > mdxTemplateMigrationByteLimit) {+ throw new Error("MDX template migration exceeds the 10 MiB limit");+ }+ try {+ const document = await parseMdxDocument({ source: file.source });+ const result = updateNodes(document.children, migration);+ plannedFiles.push({+ assetId: file.assetId,+ revision: file.revision,+ contentRef: file.contentRef,+ source:+ result.nodes === document.children+ ? file.source+ : serializeMdxDocument({ ...document, children: result.nodes }),+ changed: result.nodes !== document.children,+ updateCount: result.updateCount,+ omissionCount: result.omissionCount,+ diagnostics: [],+ });+ } catch (error) {+ plannedFiles.push({+ ...file,+ changed: false,+ updateCount: 0,+ omissionCount: 0,+ diagnostics: [toParseDiagnostic(file, error)],+ });+ }+ }+ const confirmation = await createConfirmationToken(+ getConfirmationPayload({+ projectId,+ migration,+ files: plannedFiles,+ selectionAssetIds: selected,+ confirmationScope,+ }),+ confirmationTtlMs+ );+ return {+ status: "confirmation-required",+ migration,+ files: plannedFiles,+ updateCount: plannedFiles.reduce((sum, file) => sum + file.updateCount, 0),+ omissionCount: plannedFiles.reduce(+ (sum, file) => sum + file.omissionCount,+ 0+ ),+ changedFileCount: plannedFiles.filter((file) => file.changed).length,+ selectionAssetIds: [...selected].sort(),+ confirmationScope,+ confirmationToken: confirmation.token,+ confirmationExpiresAt: new Date(confirmation.expiresAt).toISOString(),+ };+};diff --git a/packages/project-build/src/runtime/mdx-template-resolution.test.ts b/packages/project-build/src/runtime/mdx-template-resolution.test.tsnew file mode 100644index 0000000000..2301fa0b5b--- /dev/null+++ b/packages/project-build/src/runtime/mdx-template-resolution.test.ts@@ -0,0 +1,218 @@+import { describe, expect, test } from "vitest";+import { parseMdxDocument } from "@webstudio-is/content-engine/mdx";+import {+ blockComponent,+ blockTemplateComponent,+ elementComponent,+ type ContentBlockExternalContentIdentity,+ type Instance,+ type Instances,+ type WsComponentMeta,+} from "@webstudio-is/sdk";+import { resolveMdxTemplates } from "./mdx-template-resolution";++const createInstance = (+ id: string,+ component: string,+ values: Partial<Pick<Instance, "children" | "label" | "tag">> = {}+): Instance => ({ type: "instance", id, component, children: [], ...values });++const identity: ContentBlockExternalContentIdentity = {+ blockInstanceId: "block",+ assetId: "article",+ revision: "revision-1",+ contentRef: "articles/hello.mdx",+ format: "mdx",+ renderScope: "route:/hello",+};++const metas = new Map<string, WsComponentMeta>([+ ["Card", { label: "Card" }],+ ["Badge", { label: "Badge" }],+]);++const createInstances = (): Instances =>+ new Map([+ [+ "block",+ createInstance("block", blockComponent, {+ children: [{ type: "id", value: "templates" }],+ }),+ ],+ [+ "templates",+ createInstance("templates", blockTemplateComponent, {+ children: [+ { type: "id", value: "hero" },+ { type: "id", value: "card" },+ ],+ }),+ ],+ [+ "hero",+ createInstance("hero", elementComponent, {+ label: "Hero Card",+ tag: "section",+ }),+ ],+ [+ "card",+ createInstance("card", "Card", {+ children: [{ type: "id", value: "badge" }],+ }),+ ],+ ["badge", createInstance("badge", "Badge", { label: "Nested" })],+ ]);++describe("resolveMdxTemplates", () => {+ test("resolves exact displayed names from the direct flat Templates list", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:name="Hero Card" tone="quiet" />++<ws.element ws:tag="section">+ <ws.element ws:name="Card" />+</ws.element>`,+ });++ const result = resolveMdxTemplates({+ document,+ identity,+ instances: createInstances(),+ metas,+ });++ expect(result.references).toEqual([+ expect.objectContaining({+ type: "resolved-template",+ path: [0],+ templateName: "Hero Card",+ props: [expect.objectContaining({ name: "tone", value: "quiet" })],+ templateInstanceId: "hero",+ }),+ expect.objectContaining({+ type: "resolved-template",+ path: [1, 0],+ templateName: "Card",+ props: [],+ templateInstanceId: "card",+ }),+ ]);+ expect(result.diagnostics).toEqual([]);+ expect(result.templateNames).toEqual(["Hero Card", "Card"]);+ });++ test("does not resolve descendants of a template entry or inexact names", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:name="Nested" />++<ws.element ws:name=" Hero Card " />`,+ });++ const result = resolveMdxTemplates({+ document,+ identity,+ instances: createInstances(),+ metas,+ });++ expect(result.references).toEqual([+ expect.objectContaining({+ type: "unresolved-template",+ path: [0],+ templateName: "Nested",+ }),+ expect.objectContaining({+ type: "unresolved-template",+ path: [1],+ templateName: " Hero Card ",+ }),+ ]);+ expect(result.diagnostics).toEqual([+ expect.objectContaining({+ code: "unresolved-template",+ blockInstanceId: "block",+ assetId: "article",+ contentRef: "articles/hello.mdx",+ renderScope: "route:/hello",+ templateName: "Nested",+ }),+ expect.objectContaining({+ code: "unresolved-template",+ templateName: " Hero Card ",+ }),+ ]);+ expect(result.templateNames).toEqual(["Hero Card", "Card"]);+ });++ test("keeps ambiguous duplicate displayed names unresolved", async () => {+ const instances = createInstances();+ instances.set(+ "duplicate",+ createInstance("duplicate", "Card", { label: "Hero Card" })+ );+ instances.get("templates")?.children.push({+ type: "id",+ value: "duplicate",+ });+ const document = await parseMdxDocument({+ source: `<ws.element ws:name="Hero Card">Preserved</ws.element>`,+ });++ const result = resolveMdxTemplates({+ document,+ identity,+ instances,+ metas,+ });++ expect(result.references).toEqual([+ expect.objectContaining({+ type: "unresolved-template",+ path: [0],+ templateName: "Hero Card",+ }),+ ]);+ expect(result.diagnostics).toEqual([+ expect.objectContaining({+ code: "unresolved-template",+ templateName: "Hero Card",+ }),+ ]);+ expect(result.templateNames).toEqual(["Hero Card", "Card", "Hero Card"]);+ expect(document.children[0]).toMatchObject({+ type: "template",+ name: "Hero Card",+ children: [{ type: "text", value: "Preserved" }],+ });+ });++ test("does not resolve or diagnose descendants of an unresolved subtree", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:name="Missing">+ <ws.element ws:name="Card" />+ <ws.element ws:name="Also Missing" />+</ws.element>`,+ });++ const result = resolveMdxTemplates({+ document,+ identity,+ instances: createInstances(),+ metas,+ });++ expect(result.references).toEqual([+ expect.objectContaining({+ type: "unresolved-template",+ path: [0],+ templateName: "Missing",+ }),+ ]);+ expect(result.diagnostics).toEqual([+ expect.objectContaining({+ code: "unresolved-template",+ templateName: "Missing",+ }),+ ]);+ });+});diff --git a/packages/project-build/src/runtime/mdx-template-resolution.ts b/packages/project-build/src/runtime/mdx-template-resolution.tsnew file mode 100644index 0000000000..b1c85dc138--- /dev/null+++ b/packages/project-build/src/runtime/mdx-template-resolution.ts@@ -0,0 +1,118 @@+import type {+ MdxAuthoredProp,+ MdxAuthoredNode,+ MdxDocument,+} from "@webstudio-is/content-engine/mdx";+import {+ getInstanceName,+ type ContentBlockDiagnostic,+ type ContentBlockExternalContentIdentity,+ type ContentBlockSourceRange,+ type Instance,+ type Instances,+ type WsComponentMeta,+} from "@webstudio-is/sdk";+import { findBlockTemplates } from "./block";++export type MdxTemplateReference = Readonly<{+ path: readonly number[];+ templateName: string;+ sourceRange?: ContentBlockSourceRange;+}> &+ (+ | Readonly<{+ type: "resolved-template";+ templateInstanceId: Instance["id"];+ props: readonly MdxAuthoredProp[];+ }>+ | Readonly<{+ type: "unresolved-template";+ }>+ );++export type MdxTemplateResolution = Readonly<{+ templateNames: readonly string[];+ references: readonly MdxTemplateReference[];+ diagnostics: readonly ContentBlockDiagnostic[];+}>;++export const resolveMdxTemplates = ({+ document,+ identity,+ instances,+ metas,+}: {+ document: MdxDocument;+ identity: ContentBlockExternalContentIdentity;+ instances: Instances;+ metas: ReadonlyMap<Instance["component"], WsComponentMeta>;+}): MdxTemplateResolution => {+ const templateIdsByName = new Map<string, Instance["id"][]>();+ const templateNames: string[] = [];+ for (const [template] of findBlockTemplates({+ anchor: [identity.blockInstanceId],+ instances,+ }) ?? []) {+ const name = getInstanceName({ instance: template, metas });+ templateNames.push(name);+ const templateIds = templateIdsByName.get(name) ?? [];+ templateIds.push(template.id);+ templateIdsByName.set(name, templateIds);+ }++ const references: MdxTemplateReference[] = [];+ const diagnostics: ContentBlockDiagnostic[] = [];++ const visit = (+ nodes: readonly MdxAuthoredNode[],+ parentPath: readonly number[]+ ) => {+ for (const [index, node] of nodes.entries()) {+ const path = [...parentPath, index];+ if (node.type === "template") {+ const templateIds = templateIdsByName.get(node.name);+ if (templateIds?.length === 1) {+ references.push({+ type: "resolved-template",+ path,+ templateName: node.name,+ props: node.props,+ templateInstanceId: templateIds[0],+ sourceRange: node.sourceRange,+ });+ } else {+ references.push({+ type: "unresolved-template",+ path,+ templateName: node.name,+ sourceRange: node.sourceRange,+ });+ diagnostics.push({+ code: "unresolved-template",+ severity: "warning",+ blockInstanceId: identity.blockInstanceId,+ assetId: identity.assetId,+ contentRef: identity.contentRef,+ renderScope: identity.renderScope,+ templateName: node.name,+ sourceRange: node.sourceRange,+ });+ // The unresolved marker replaces the complete subtree in the Builder,+ // and publication omits it, so descendant references are not actionable.+ continue;+ }+ }++ if (+ node.type !== "text" &&+ node.type !== "comment" &&+ node.type !== "opaque"+ ) {+ visit(node.children, path);+ }+ }+ };++ visit(document.children, []);+ return { templateNames, references, diagnostics };+};diff --git a/packages/project-build/src/runtime/mutation.ts b/packages/project-build/src/runtime/mutation.tsindex 71d68a6051..832b9302b8 100644--- a/packages/project-build/src/runtime/mutation.ts+++ b/packages/project-build/src/runtime/mutation.ts@@ -31,6 +31,33 @@ export const createRuntimeMutation = <noop: payload.length === 0,});+const appendBuilderPatchChanges = (+ changes: Map<BuilderNamespace, BuilderPatchChange>,+ payload: readonly BuilderPatchChange[]+) => {+ for (const change of payload) {+ const accumulated = changes.get(change.namespace);+ if (accumulated === undefined) {+ changes.set(change.namespace, {+ namespace: change.namespace,+ patches: [...change.patches],+ });+ } else {+ accumulated.patches.push(...change.patches);+ }+ }+};++export const mergeBuilderPatchChanges = (+ ...payloads: readonly (readonly BuilderPatchChange[])[]+) => {+ const changes = new Map<BuilderNamespace, BuilderPatchChange>();+ for (const payload of payloads) {+ appendBuilderPatchChanges(changes, payload);+ }+ return Array.from(changes.values());+};+export const createRuntimeMutationAccumulator = (initialState: BuilderState) => {@@ -41,17 +68,7 @@ export const createRuntimeMutationAccumulator = (const stage = <Result extends Record<string, unknown>>(mutation: BuilderRuntimeMutation<Result>) => {- for (const change of mutation.payload) {- const accumulated = changes.get(change.namespace);- if (accumulated === undefined) {- changes.set(change.namespace, {- namespace: change.namespace,- patches: [...change.patches],- });- } else {- accumulated.patches.push(...change.patches);- }- }+ appendBuilderPatchChanges(changes, mutation.payload);for (const namespace of mutation.invalidatesNamespaces) {invalidatesNamespaces.add(namespace);}diff --git a/packages/project-build/src/runtime/output-schemas.ts b/packages/project-build/src/runtime/output-schemas.tsindex 49d7750f40..186275c7f8 100644--- a/packages/project-build/src/runtime/output-schemas.ts+++ b/packages/project-build/src/runtime/output-schemas.ts@@ -11,6 +11,7 @@ import {projectMeta,prop,instance,+ contentBlockDiagnostic,} from "@webstudio-is/sdk";import {assetQueryResultMode,@@ -32,6 +33,7 @@ import {} from "./component-insert-contract";import { expressionWarningSchema } from "./expression-validation";import { designTokenImportPlanEntrySchema } from "./design-token-import";+import { mdxPasteResult } from "./mdx-paste";const looseObject = <Shape extends z.ZodRawShape>(shape: Shape) =>z.looseObject(shape);@@ -323,7 +325,73 @@ const unsupportedRuntimeConversion = looseObject({reason: z.string(),});+const assetContentSessionStatus = z.enum([+ "saved",+ "pending",+ "saving",+ "failed",+ "conflicting",+]);+const assetContentSourceResult = looseObject({+ assetId: id,+ source: z.string(),+ status: assetContentSessionStatus,+ diagnostics: z.array(contentBlockDiagnostic),+});+const contentBlockSourceLifecycleResult = (+ action: "connect" | "switch" | "disconnect"+) =>+ looseObject({+ action: z.literal(action),+ requiresConfirmation: z.boolean(),+ diagnostics: z.array(contentBlockDiagnostic),+ });+export const runtimeOutputSchemas = {+ "contentBlocks.inspectSource": looseObject({+ source: z.string(),+ sessionStatus: assetContentSessionStatus,+ identity: looseObject({+ blockInstanceId: id,+ assetId: id,+ revision: z.string(),+ contentRef: z.string(),+ format: z.literal("mdx"),+ renderScope: z.string(),+ }),+ diagnostics: z.array(contentBlockDiagnostic),+ }),+ "contentBlocks.connectSource": contentBlockSourceLifecycleResult("connect"),+ "contentBlocks.switchSource": contentBlockSourceLifecycleResult("switch"),+ "contentBlocks.disconnectSource":+ contentBlockSourceLifecycleResult("disconnect"),+ "contentBlocks.editSource": assetContentSourceResult,+ "contentBlocks.updateFrontmatter": assetContentSourceResult,+ "contentBlocks.reloadSource": assetContentSourceResult,+ "contentBlocks.migrateTemplateReferences": looseObject({+ status: z.enum(["confirmation-required", "complete", "partial"]),+ updateCount: z.number().int().nonnegative(),+ omissionCount: z.number().int().nonnegative(),+ changedFileCount: z.number().int().nonnegative(),+ files: z.array(+ looseObject({+ assetId: id,+ revision: z.string(),+ contentRef: z.string(),+ changed: z.boolean(),+ status: z.enum(["updated", "unchanged", "failed"]).optional(),+ updateCount: z.number().int().nonnegative(),+ omissionCount: z.number().int().nonnegative(),+ diagnostics: z.array(+ looseObject({ code: z.string(), message: z.string() })+ ),+ })+ ),+ confirmation: looseObject({+ token: z.string(),+ expiresAt: z.string(),+ }).optional(),+ }),"assetFolders.list": looseObject({ folders: z.array(assetFolder) }),"assetFolders.create": folderIdResult,"assetFolders.update": folderIdResult,@@ -500,6 +568,7 @@ export const runtimeOutputSchemas = {warnings: expressionWarnings.optional(),}),"instances.insertFragment": fragmentInsertResult,+ "instances.insertMdxText": mdxPasteResult,"slots.attach": looseObject({ slotId: id, fragmentId: id }),"slots.extract": looseObject({ slotId: id, fragmentId: id, instanceId: id }),"instances.move": instanceIdsResult,diff --git a/packages/project-build/src/runtime/page-copy.test.tsx b/packages/project-build/src/runtime/page-copy.test.tsxindex db22ff4ff0..303e840f65 100644--- a/packages/project-build/src/runtime/page-copy.test.tsx+++ b/packages/project-build/src/runtime/page-copy.test.tsx@@ -1276,7 +1276,11 @@ describe("insert page copy", () => {]);const newBox = Array.from(data.instances.values()).at(-1);expect(newBox?.children).toEqual([- { type: "expression", value: encodeDataVariableId(globalVariableId) },+ {+ type: "expression",+ value: encodeDataVariableId(globalVariableId),+ mode: "read",+ },]);});@@ -1324,7 +1328,11 @@ describe("insert page copy", () => {]);const newBox = Array.from(targetData.instances.values()).at(-1);expect(newBox?.children).toEqual([- { type: "expression", value: encodeDataVariableId(globalVariableId) },+ {+ type: "expression",+ value: encodeDataVariableId(globalVariableId),+ mode: "read",+ },]);});@@ -1366,7 +1374,11 @@ describe("insert page copy", () => {]);const newBox = Array.from(targetData.instances.values()).at(-1);expect(newBox?.children).toEqual([- { type: "expression", value: encodeDataVariableId(globalVariableId) },+ {+ type: "expression",+ value: encodeDataVariableId(globalVariableId),+ mode: "read",+ },]);});@@ -1402,7 +1414,7 @@ describe("insert page copy", () => {]);const newBox = Array.from(data.instances.values()).at(-1);expect(newBox?.children).toEqual([- { type: "expression", value: "$ws$system" },+ { type: "expression", value: "$ws$system", mode: "read" },]);const copiedPage = getCopiedPages(data)[0];expect(copiedPage.title).toEqual(`$ws$system`);diff --git a/packages/project-build/src/runtime/pre-publish-audit.test.tsx b/packages/project-build/src/runtime/pre-publish-audit.test.tsxindex 6bdbec4c8e..0556e543d6 100644--- a/packages/project-build/src/runtime/pre-publish-audit.test.tsx+++ b/packages/project-build/src/runtime/pre-publish-audit.test.tsx@@ -1,6 +1,7 @@import { expect, test } from "vitest";import {ROOT_FOLDER_ID,+ blockComponent,type Folder,type Page,type Pages,@@ -49,6 +50,7 @@ const runAudit = ({...data,dataSources: new Map(),resources: new Map(),+ assets: new Map(),metas: componentMetas,});@@ -218,6 +220,7 @@ test("blocks publishing when required audit input is unavailable", () => {props,dataSources: new Map(),resources: new Map(),+ assets: new Map(),metas: componentMetas,});@@ -250,6 +253,7 @@ test("includes existing resource integrity checks in the audit pipeline", () =>],]),resources: new Map(),+ assets: new Map(),metas: componentMetas,});@@ -266,3 +270,32 @@ test("includes existing resource integrity checks in the audit pipeline", () =>},]);});++test("includes Content Block source integrity checks in the audit pipeline", () => {+ const { instances, props } = renderData(<$.Body ws:id="body"></$.Body>);+ instances.set("block", {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [],+ });+ props.set("source", {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "missing-post",+ });++ expect(runAudit({ instances, props })).toContainEqual({+ ruleId: "content-block-source-integrity",+ severity: "error",+ message:+ 'Content Block source prop "source" references missing Asset "missing-post".',+ location: {+ instanceId: "block",+ propId: "source",+ assetId: "missing-post",+ },+ });+});diff --git a/packages/project-build/src/runtime/pre-publish-audit.ts b/packages/project-build/src/runtime/pre-publish-audit.tsindex 01fbbaea1f..0821164963 100644--- a/packages/project-build/src/runtime/pre-publish-audit.ts+++ b/packages/project-build/src/runtime/pre-publish-audit.ts@@ -1,6 +1,7 @@import {getPagePath,getPublishablePages,+ type Assets,type DataSources,type Instances,type Pages,@@ -26,6 +27,7 @@ export type PrePublishAuditFinding = {dataSourceId?: string;propId?: string;resourceId?: string;+ assetId?: string;};};@@ -35,6 +37,7 @@ type PrePublishAuditContext = {props: Props;dataSources: DataSources;resources: Resources;+ assets: Assets;metas: Map<string, WsComponentMeta>;};@@ -49,6 +52,17 @@ const checkHtmlContentModel: PrePublishAuditCheck = ({metas,}) => {const findings: PrePublishAuditFinding[] = [];+ const codeTextMeta = metas.get("CodeText");+ const auditMetas = new Map(metas);+ if (codeTextMeta !== undefined) {+ // Older Code Text instances could contain component children. Keep those+ // projects publishable while insertion and editing use the current+ // plain-text-only content model.+ auditMetas.set("CodeText", {+ ...codeTextMeta,+ contentModel: { category: "instance", children: ["text", "instance"] },+ });+ }for (const page of getPublishablePages(pages)) {let message: string | undefined;@@ -56,7 +70,7 @@ const checkHtmlContentModel: PrePublishAuditCheck = ({const isValid = isTreeSatisfyingContentModel({instances,props,- metas,+ metas: auditMetas,instanceSelector: [page.rootInstanceId],onError: (error, instanceSelector) => {message ??= error;@@ -82,30 +96,50 @@ const checkHtmlContentModel: PrePublishAuditCheck = ({return findings;};-const checkResourceIntegrity: PrePublishAuditCheck = ({+const checkBuildIntegrity: PrePublishAuditCheck = ({dataSources,props,resources,+ instances,+ assets,}) =>getBuildIntegrityIssues({dataSources: dataSources.values(),props: props.values(),resources: resources.values(),+ instances: instances.values(),+ assets: assets.values(),}).map((issue) => ({- ruleId: "resource-integrity",+ ruleId:+ issue.type === "missingResource"+ ? "resource-integrity"+ : "content-block-source-integrity",severity: "error",message: formatBuildIntegrityIssue(issue),location: {- ...(issue.source === "dataSource"- ? { dataSourceId: issue.dataSourceId }- : { propId: issue.propId }),- resourceId: issue.resourceId,+ ...(issue.type === "missingResource"+ ? {+ ...(issue.source === "dataSource"+ ? { dataSourceId: issue.dataSourceId }+ : { propId: issue.propId }),+ resourceId: issue.resourceId,+ }+ : {+ instanceId: issue.blockInstanceId,+ ...(issue.type === "duplicateContentBlockSource"+ ? { propId: issue.propIds[0] }+ : { propId: issue.propId }),+ ...(issue.type === "missingContentBlockSourceAsset" ||+ issue.type === "incompatibleContentBlockSourceAsset"+ ? { assetId: issue.assetId }+ : {}),+ }),},}));const prePublishAuditChecks: PrePublishAuditCheck[] = [checkHtmlContentModel,- checkResourceIntegrity,+ checkBuildIntegrity,];export const runPrePublishAudit = ({diff --git a/packages/project-build/src/runtime/props.test.ts b/packages/project-build/src/runtime/props.test.tsindex bcdc79be52..515a76c48d 100644--- a/packages/project-build/src/runtime/props.test.ts+++ b/packages/project-build/src/runtime/props.test.ts@@ -1,6 +1,13 @@import { describe, expect, test } from "vitest";-import type { Instance, Prop } from "@webstudio-is/sdk";import {+ blockComponent,+ contentBlockSourceProp,+ encodeDataSourceVariable,+ type Instance,+ type Prop,+} from "@webstudio-is/sdk";+import {+ bindProps,clonePropForInstance,createPropDeletePayload,createPropBindingFromInput,@@ -11,6 +18,7 @@ import {createValidatedPropBindingFromInput,createValidatedPropValueFromInput,createPropValue,+ deleteProps,findProp,getDefaultPropMetaForType,getPropDeletePlan,@@ -327,6 +335,7 @@ describe("prop input creators", () => {name: "value",type: "expression",value: "value",+ mode: "read",});});});@@ -501,6 +510,70 @@ describe("createPropUpsertPayload", () => {});describe("updateProps", () => {+ test("requires Content Block source lifecycle operations", () => {+ const contentBlock: Instance = {+ type: "instance",+ id: "content-block-id",+ component: blockComponent,+ children: [],+ };+ const source: Prop = {+ id: "source-id",+ instanceId: contentBlock.id,+ name: contentBlockSourceProp,+ type: "asset",+ value: "asset-id",+ };+ const state = {+ instances: new Map([[contentBlock.id, contentBlock]]),+ props: new Map([[source.id, source]]),+ };++ expect(() =>+ updateProps(+ state,+ {+ updates: [+ {+ instanceId: contentBlock.id,+ name: contentBlockSourceProp,+ type: "asset",+ value: "next-asset-id",+ },+ ],+ },+ { createId: () => "next-source-id" }+ )+ ).toThrow("Content Block source operations");++ expect(() =>+ bindProps(+ state,+ {+ bindings: [+ {+ instanceId: contentBlock.id,+ name: contentBlockSourceProp,+ binding: { type: "expression", value: "selectedAssetId" },+ },+ ],+ },+ { createId: () => "next-source-id" }+ )+ ).toThrow("Content Block source operations");++ expect(() =>+ deleteProps(state, {+ deletions: [+ {+ instanceId: contentBlock.id,+ name: contentBlockSourceProp,+ },+ ],+ })+ ).toThrow("Content Block source operations");+ });+test("parses CSS strings in animation action keyframes", () => {const input = propUpdatesInput.parse({updates: [@@ -932,9 +1005,109 @@ describe("getPropValueErrors", () => {expect(getPropValueErrors({ type: "expression", value: "invalid {" })).not.toEqual([]);+ expect(+ getPropValueErrors({+ type: "expression",+ value: 'document.frontmatter.title + "!"',+ mode: "readwrite",+ })+ ).toContain("Read-write expressions must be a direct static path");});});+test("rejects readwrite prop bindings outside a connected Content Block document", () => {+ expect(() =>+ bindProps(+ {+ instances: new Map([[image.id, image]]),+ props: new Map(),+ },+ {+ bindings: [+ {+ instanceId: image.id,+ name: "alt",+ binding: {+ type: "expression",+ value: "document.frontmatter.alt",+ mode: "readwrite",+ },+ },+ ],+ },+ { createId: () => "alt-id" }+ )+ ).toThrow(+ "Read-write expressions require a connected Content Block document frontmatter path"+ );+});++test("accepts readwrite prop bindings into connected Content Block frontmatter", () => {+ const block: Instance = {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: image.id }],+ };+ const result = bindProps(+ {+ instances: new Map([+ [block.id, block],+ [image.id, image],+ ]),+ props: new Map<string, Prop>([+ [+ "source",+ {+ id: "source",+ instanceId: block.id,+ name: "src",+ type: "asset",+ value: "article",+ },+ ],+ [+ "document",+ {+ id: "document",+ instanceId: block.id,+ name: "document",+ type: "parameter",+ value: "document",+ },+ ],+ ]),+ },+ {+ bindings: [+ {+ instanceId: image.id,+ name: "alt",+ binding: {+ type: "expression",+ value: `${encodeDataSourceVariable("document")}.frontmatter.alt`,+ mode: "readwrite",+ },+ },+ ],+ },+ { createId: () => "alt-id" }+ );++ expect(result.payload).toEqual([+ {+ namespace: "props",+ patches: [+ {+ op: "add",+ path: ["alt-id"],+ value: expect.objectContaining({ mode: "readwrite" }),+ },+ ],+ },+ ]);+});+describe("getPropIdsToDelete", () => {const imageProps = new Map<Prop["name"], Prop>([["src", prop("src")],diff --git a/packages/project-build/src/runtime/props.ts b/packages/project-build/src/runtime/props.tsindex cd6b311437..9ae1583dc2 100644--- a/packages/project-build/src/runtime/props.ts+++ b/packages/project-build/src/runtime/props.ts@@ -1,7 +1,12 @@import { z } from "zod";import { parseCssValue } from "@webstudio-is/css-data";import {+ blockComponent,+ contentBlockSourceProp,createAnimationActionInput,+ findWritableContentBlockDocumentBindings,+ getExpressionBindingError,+ expressionBindingMode,prop as propSchema,type Instance,type Prop,@@ -15,6 +20,7 @@ import {addExpressionValidationIssues,getExpressionErrorMessages,getExpressionErrors,+ unsupportedReadwriteExpressionError,} from "./expression-validation";import { runtimeGeneratedIdInput } from "./generated-id-input";import { validateHtmlEmbedCode } from "./html-embed";@@ -50,6 +56,7 @@ export const createPropValue = ({type,value,required,+ mode,}: {id: Prop["id"];instanceId: Instance["id"];@@ -57,15 +64,20 @@ export const createPropValue = ({type: Prop["type"];value: unknown;required?: boolean;-}): Prop =>- propSchema.parse({+ mode?: Extract<Prop, { type: "expression" }>["mode"];+}): Prop => {+ const expressionMode = type === "expression" ? (mode ?? "read") : undefined;+ const input = {id,instanceId,name,type,value,- required,- });+ ...(required === undefined ? {} : { required }),+ ...(expressionMode === undefined ? {} : { mode: expressionMode }),+ };+ return propSchema.parse(input);+};export const createPropBindingFromInput = ({id,@@ -76,7 +88,12 @@ export const createPropBindingFromInput = ({id: Prop["id"];instanceId: Instance["id"];name: Prop["name"];- binding: Pick<Prop, "type" | "value">;+ binding:+ | Pick<Extract<Prop, { type: "expression" }>, "type" | "value" | "mode">+ | Pick<+ Extract<Prop, { type: "parameter" | "resource" | "action" }>,+ "type" | "value"+ >;}): Prop =>createPropValue({id,@@ -84,6 +101,7 @@ export const createPropBindingFromInput = ({name,type: binding.type,value: binding.value,+ mode: binding.type === "expression" ? binding.mode : undefined,});export const listPropExpressions = ({@@ -118,9 +136,11 @@ export const listPropExpressions = ({export const getPropValueErrors = ({type,value,+ mode,}: {type: Prop["type"];value?: unknown;+ mode?: Extract<Prop, { type: "expression" }>["mode"];}) => {if (type !== "expression") {return listPropExpressions({ type, value }).flatMap(@@ -132,7 +152,14 @@ export const getPropValueErrors = ({}));}- return getExpressionErrors(String(value));+ const bindingError = getExpressionBindingError({+ value: String(value),+ mode,+ });+ return [+ ...(bindingError === undefined ? [] : [bindingError]),+ ...getExpressionErrors(String(value)),+ ];};export const isPrimitiveValue = (value: unknown) => {@@ -218,6 +245,7 @@ const propValueInputVariants = [.describe("One Webstudio JavaScript expression, not a statement or function. Read webstudio://project/expressions for syntax and scope rules."),+ mode: expressionBindingMode.optional(),}),z.object({...propValueBaseInput,@@ -258,6 +286,7 @@ export const dataPropBindingInput = z.discriminatedUnion("type", [.describe("One Webstudio JavaScript expression. Read webstudio://project/expressions before using unfamiliar scope or syntax."),+ mode: expressionBindingMode.optional(),}),z.object({ type: z.literal("parameter"), value: z.string() }),z.object({ type: z.literal("resource"), value: z.string() }),@@ -290,6 +319,8 @@ export const propBindingInput = zgetPropValueErrors({type: value.binding.type,value: value.binding.value,+ mode:+ value.binding.type === "expression" ? value.binding.mode : undefined,}),["binding", "value"]);@@ -341,7 +372,7 @@ export type PropValueUpdate =| Pick<Extract<Prop, { type: "boolean" }>, "type" | "value">| Pick<Extract<Prop, { type: "json" }>, "type" | "value">| Pick<Extract<Prop, { type: "string[]" }>, "type" | "value">- | Pick<Extract<Prop, { type: "expression" }>, "type" | "value">+ | Pick<Extract<Prop, { type: "expression" }>, "type" | "value" | "mode">| Pick<Extract<Prop, { type: "asset" }>, "type" | "value">| Pick<Extract<Prop, { type: "page" }>, "type" | "value">| Pick<Extract<Prop, { type: "action" }>, "type" | "value">@@ -447,7 +478,12 @@ export const createPropValueInputFromProp = (prop: Prop): PropValueInput => {case "resource":return { ...base, type: prop.type, value: prop.value };case "expression":- return { ...base, type: prop.type, value: prop.value };+ return {+ ...base,+ type: prop.type,+ value: prop.value,+ mode: prop.mode,+ };case "action":return { ...base, type: prop.type, value: prop.value };case "animationAction":@@ -472,9 +508,11 @@ type ValidatedPropInputResult =| { success: true; prop: Prop }| { success: false; errors: string[] };-type PropValueInputWithId = Omit<z.infer<typeof propValueInput>, "propId"> & {- propId?: Prop["id"];-};+type WithOptionalPropId<Input> = Input extends unknown+ ? Omit<Input, "propId"> & { propId?: Prop["id"] }+ : never;++type PropValueInputWithId = WithOptionalPropId<z.infer<typeof propValueInput>>;type PropBindingInputWithId = Omit<z.infer<typeof propBindingInput>,@@ -504,6 +542,7 @@ export const createValidatedPropValueFromInput = (type: value.type,value: value.value,required: value.required,+ mode: value.type === "expression" ? value.mode : undefined,}),};};@@ -515,6 +554,8 @@ export const createValidatedPropBindingFromInput = (const errors = getPropValueErrors({type: binding.binding.type,value: binding.binding.value,+ mode:+ binding.binding.type === "expression" ? binding.binding.mode : undefined,});if (errors.length > 0) {return { success: false, errors };@@ -801,6 +842,58 @@ const assertRuntimeInstance = (const throwPropErrors = (errors: string[]) =>throwBuilderRuntimeError("BAD_REQUEST", errors.join("\n"));+const assertReadwritePropBindingsSupported = ({+ instances,+ props,+ nextProps,+}: {+ instances: Map<Instance["id"], Instance>;+ props: Map<Prop["id"], Prop>;+ nextProps: readonly Prop[];+}) => {+ const readwritePropIds = new Set(+ nextProps.flatMap((prop) =>+ prop.type === "expression" && prop.mode === "readwrite" ? [prop.id] : []+ )+ );+ if (readwritePropIds.size === 0) {+ return;+ }+ const nextPropsById = new Map(props);+ for (const prop of nextProps) {+ nextPropsById.set(prop.id, prop);+ }+ const writablePropIds = new Set(+ findWritableContentBlockDocumentBindings({+ instances,+ props: nextPropsById,+ }).props.map(({ propId }) => propId)+ );+ for (const propId of readwritePropIds) {+ if (writablePropIds.has(propId) === false) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ unsupportedReadwriteExpressionError+ );+ }+ }+};++const assertGenericPropMutationAllowed = (+ instance: Instance,+ name: Prop["name"]+) => {+ if (+ instance.component === blockComponent &&+ name === contentBlockSourceProp+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Use Content Block source operations to connect, switch, or disconnect its source."+ );+ }+};+const getHtmlEmbedCodeErrors = (instance: Instance, update: PropValueInput) => {if (instance.component !== "HtmlEmbed" ||@@ -838,6 +931,7 @@ export const updateProps = (const nextProps = input.updates.map((update) => {assertRuntimeInstance(instances, update.instanceId);const instance = instances.get(update.instanceId)!;+ assertGenericPropMutationAllowed(instance, update.name);const htmlEmbedCodeErrors = getHtmlEmbedCodeErrors(instance, update);const codeErrors = [...htmlEmbedCodeErrors,@@ -856,6 +950,7 @@ export const updateProps = (}return nextProp.prop;});+ assertReadwritePropBindingsSupported({ instances, props, nextProps });const { payload, propIds } = createPropUpsertPayload({props: props.values(),nextProps,@@ -962,6 +1057,8 @@ export const bindProps = (const { instances, props } = getRequiredPropState(state);const nextProps = input.bindings.map((binding) => {assertRuntimeInstance(instances, binding.instanceId);+ const instance = instances.get(binding.instanceId)!;+ assertGenericPropMutationAllowed(instance, binding.name);const existing = findProp(props.values(), binding.instanceId, binding.name);const nextProp = createValidatedPropBindingFromInput({ ...binding, propId: binding.propId ?? existing?.id },@@ -972,6 +1069,7 @@ export const bindProps = (}return nextProp.prop;});+ assertReadwritePropBindingsSupported({ instances, props, nextProps });const { payload, propIds } = createPropUpsertPayload({props: props.values(),nextProps,@@ -988,6 +1086,12 @@ export const deleteProps = (input: z.infer<typeof propDeletionsInput>) => {const { instances, props } = getRequiredPropState(state);+ for (const deletion of input.deletions) {+ const instance = instances.get(deletion.instanceId);+ if (instance !== undefined) {+ assertGenericPropMutationAllowed(instance, deletion.name);+ }+ }const { missingInstanceId, payload, propIds } = createPropDeletePayload({instances,props: props.values(),diff --git a/packages/project-build/src/runtime/published-mdx.test.ts b/packages/project-build/src/runtime/published-mdx.test.tsnew file mode 100644index 0000000000..bba788d605--- /dev/null+++ b/packages/project-build/src/runtime/published-mdx.test.ts@@ -0,0 +1,759 @@+import { describe, expect, test } from "vitest";+import type { ContentArtifactV1 } from "@webstudio-is/content-engine";+import {+ discoverMdxBodyAssetReferences,+ parseMdxDocument,+} from "@webstudio-is/content-engine/mdx";+import type { Instance, WebstudioData } from "@webstudio-is/sdk";+import {+ getUnsafeDynamicPublishedMdxDiagnostic,+ materializePublishedMdx,+ type PublishedMdxRoot,+} from "./published-mdx";++const revision = (value: string) => `sha256:${value.repeat(64)}` as const;++const createData = ({+ sourceType = "asset",+ expression = '"article"',+ withTemplate = false,+}: {+ sourceType?: "asset" | "expression";+ expression?: string;+ withTemplate?: boolean;+}) => {+ const block: Instance = {+ type: "instance",+ id: "block",+ component: "ws:block",+ children: withTemplate ? [{ type: "id", value: "templates" }] : [],+ };+ const instances: Instance[] = [block];+ if (withTemplate) {+ instances.push(+ {+ type: "instance",+ id: "templates",+ component: "ws:block-template",+ children: [{ type: "id", value: "hero" }],+ },+ {+ type: "instance",+ id: "hero",+ component: "ws:element",+ tag: "section",+ label: "Hero",+ children: [{ type: "text", value: "Template body" }],+ }+ );+ }+ return {+ instances: new Map(instances.map((instance) => [instance.id, instance])),+ props: new Map([+ [+ "source",+ {+ id: "source",+ instanceId: "block",+ name: "src",+ type: sourceType,+ value: sourceType === "asset" ? "article" : expression,+ },+ ],+ ]),+ dataSources: new Map(),+ resources: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ breakpoints: new Map(),+ assets: new Map(),+ } as Omit<WebstudioData, "pages">;+};++const createArtifact = (+ files: readonly { id: string; source: string; revision?: string }[],+ assetValueReferences?: ContentArtifactV1["assetValueReferences"]+) =>+ ({+ format: "webstudio-content-database",+ version: 1,+ assetRevision: revision("a"),+ documents: files.map(({ id, source, revision: fileRevision }) => ({+ _id: id,+ _type: "asset.file",+ name: `${id}.mdx`,+ path: `${id}.mdx`,+ key: id,+ extension: "mdx",+ mimeType: "text/mdx",+ size: source.length,+ revision: fileRevision ?? revision(id === "article" ? "b" : "c"),+ contentRef: `${id}.mdx`,+ })),+ contents: Object.fromEntries(+ files.map(({ id, source }) => [`${id}.mdx`, source])+ ),+ assetValueReferences,+ fieldCatalog: { canonicalRevision: revision("a"), fields: {} },+ integrity: { algorithm: "sha256", checksum: revision("d") },+ }) as ContentArtifactV1;++const getFragmentText = (+ fragment: Awaited<+ ReturnType<typeof materializePublishedMdx>+ >["roots"][number]["fragment"]+) =>+ JSON.stringify(fragment.instances.flatMap((instance) => instance.children));++describe("published MDX materialization", () => {+ test("materializes a direct source before rendering", async () => {+ const result = await materializePublishedMdx({+ route: "/blog/article",+ data: createData({}),+ artifact: createArtifact([{ id: "article", source: "# Published" }]),+ metas: new Map(),+ projectId: "project",+ });++ expect(result.roots).toHaveLength(1);+ expect(result.roots[0].identity).toMatchObject({+ blockInstanceId: "block",+ assetId: "article",+ contentRef: "article.mdx",+ renderScope: "route:/blog/article:block:block",+ });+ expect(getFragmentText(result.roots[0].fragment)).toContain("Published");+ });++ test("resolves referenced document frontmatter for the designed shell", async () => {+ const artifact = createArtifact([+ {+ id: "article",+ source: `---+author:+ $ref: ./author.mdx#frontmatter+---++# Article`,+ },+ {+ id: "author",+ source: `---+name: Ada+---+`,+ },+ ]);+ artifact.documentGraph = {+ format: "webstudio-document-graph",+ version: 1,+ nodes: artifact.documents.map((document) => ({+ id: document._id,+ revision: document.revision!,+ contentRef: document.contentRef!,+ format: "mdx" as const,+ })),+ edges: [+ {+ sourceId: "article",+ referenceId: "#frontmatter/author",+ reference: {+ documentId: "author",+ revision: revision("c"),+ representation: { type: "markdown-frontmatter" },+ },+ },+ ],+ integrity: { algorithm: "sha256", checksum: revision("d") },+ };++ const result = await materializePublishedMdx({+ route: "/blog/article",+ data: createData({}),+ artifact,+ metas: new Map(),+ projectId: "project",+ });++ expect(result.roots[0].resolvedFrontmatter).toEqual({+ author: { name: "Ada" },+ });+ });++ test("uses deployment Asset URLs in resolved frontmatter", async () => {+ const result = await materializePublishedMdx({+ route: "/blog/article",+ data: createData({}),+ artifact: createArtifact(+ [+ {+ id: "article",+ source: `---+featureImage:+ $ref: ./hero.png+---+`,+ },+ ],+ {+ article: [+ {+ path: ["properties", "featureImage"],+ assetId: "hero",+ structured: true,+ },+ ],+ }+ ),+ metas: new Map(),+ projectId: "project",+ runtimeAssets: {+ hero: {+ url: "/assets/hero_v1.png",+ name: "hero.png",+ width: 1600,+ height: 900,+ },+ },+ });++ expect(result.roots[0].resolvedFrontmatter).toEqual({+ featureImage: {+ id: "hero",+ src: "/assets/hero_v1.png",+ name: "hero.png",+ width: 1600,+ height: 900,+ },+ });+ });++ test("warns about authored elements that violate the HTML content model", async () => {+ const result = await materializePublishedMdx({+ route: "/blog/article",+ data: createData({}),+ artifact: createArtifact([+ {+ id: "article",+ source: `1. test++ <ws.element ws:tag="li">nested item</ws.element>+`,+ },+ ]),+ metas: new Map(),+ projectId: "project",+ });++ expect(result.warnings).toEqual([+ {+ route: "/blog/article",+ diagnostic: expect.objectContaining({+ code: "invalid-mdx",+ message: "Placing <li> element inside a <li> violates HTML spec.",+ sourceRange: expect.objectContaining({+ start: expect.objectContaining({ line: 3 }),+ }),+ }),+ },+ ]);+ });++ test("materializes only rendered blocks and ignores template definitions", async () => {+ const data = createData({});+ data.instances.set("template-block", {+ type: "instance",+ id: "template-block",+ component: "ws:block",+ children: [],+ });+ data.props.set("template-source", {+ id: "template-source",+ instanceId: "template-block",+ name: "src",+ type: "asset",+ value: "template-article",+ });++ const result = await materializePublishedMdx({+ route: "/",+ data,+ artifact: createArtifact([+ { id: "article", source: "# Rendered" },+ { id: "template-article", source: "# Definition only" },+ ]),+ metas: new Map(),+ projectId: "project",+ blockInstanceIds: new Set(["block"]),+ });++ expect(+ result.roots.map(({ identity }) => identity.blockInstanceId)+ ).toEqual(["block"]);+ });++ test("ignores src props on instances that are not Content Blocks", async () => {+ const data = createData({});+ const block = data.instances.get("block");+ if (block === undefined) {+ throw new Error("Expected Content Block");+ }+ data.instances.set("block", { ...block, component: "ws:element" });++ const result = await materializePublishedMdx({+ route: "/",+ data,+ artifact: createArtifact([{ id: "article", source: "# Private" }]),+ metas: new Map(),+ projectId: "project",+ });++ expect(result.roots).toEqual([]);+ });++ test("materializes the exact candidate for a static expression source", async () => {+ const result = await materializePublishedMdx({+ route: "/blog/:slug",+ data: createData({ sourceType: "expression" }),+ artifact: createArtifact([+ { id: "article", source: "# Article" },+ { id: "other", source: "# Other" },+ ]),+ metas: new Map(),+ projectId: "project",+ });++ expect(result.roots.map(({ identity }) => identity.assetId)).toEqual([+ "article",+ ]);+ });++ test("warns and skips an unbounded dynamic source without exposing unrelated MDX", async () => {+ const result = await materializePublishedMdx({+ route: "/blog/:slug",+ data: createData({ sourceType: "expression", expression: "post.body" }),+ artifact: createArtifact([+ { id: "article", source: "# Article" },+ { id: "private", source: "# Private" },+ ]),+ metas: new Map(),+ projectId: "project",+ });++ expect(result.roots).toEqual([]);+ expect(result.warnings).toEqual([+ expect.objectContaining({+ route: "/blog/:slug",+ diagnostic: expect.objectContaining({+ code: "invalid-mdx",+ blockInstanceId: "block",+ message: expect.stringContaining(+ "no bounded dynamic MDX dependency set"+ ),+ }),+ }),+ ]);+ });++ test("materializes only the bounded dynamic candidates with isolated variants", async () => {+ const materialize = (articleRevision?: string) =>+ materializePublishedMdx({+ route: "/blog/:slug",+ data: createData({ sourceType: "expression", expression: "post.mdx" }),+ artifact: createArtifact([+ { id: "article", source: "# Article", revision: articleRevision },+ { id: "other", source: "# Other" },+ { id: "private", source: "# Private" },+ ]),+ metas: new Map(),+ projectId: "project",+ dynamicAssetIdsByBlock: new Map([["block", ["article", "other"]]]),+ });+ const result = await materialize();+ const changed = await materialize(revision("g"));++ expect(result.roots.map(({ identity }) => identity.assetId)).toEqual([+ "article",+ "other",+ ]);+ expect(result.roots.map(({ identity }) => identity.renderScope)).toEqual([+ "route:/blog/:slug:block:block:asset:article",+ "route:/blog/:slug:block:block:asset:other",+ ]);+ expect(result.roots[0].dependencyRevision).not.toBe(+ changed.roots[0].dependencyRevision+ );+ });++ test("materializes more sources than the bounded parse cache retains", async () => {+ const files = Array.from({ length: 21 }, (_, index) => ({+ id: `article-${index}`,+ source: `# Article ${index}`,+ }));+ const result = await materializePublishedMdx({+ route: "/articles",+ data: createData({ sourceType: "expression", expression: "post.mdx" }),+ artifact: createArtifact(files),+ metas: new Map(),+ projectId: "project",+ dynamicAssetIdsByBlock: new Map([["block", files.map(({ id }) => id)]]),+ });++ expect(result.roots).toHaveLength(21);+ });++ test("omits an unresolved template subtree and keeps valid siblings", async () => {+ const result = await materializePublishedMdx({+ route: "/",+ data: createData({}),+ artifact: createArtifact([+ {+ id: "article",+ source:+ '<ws.element ws:name="Missing">\n\n## Hidden\n\n</ws.element>\n\n# Visible',+ },+ ]),+ metas: new Map(),+ projectId: "project",+ });++ expect(getFragmentText(result.roots[0].fragment)).not.toContain("Hidden");+ expect(getFragmentText(result.roots[0].fragment)).toContain("Visible");+ expect(result.warnings).toEqual([+ expect.objectContaining({+ route: "/",+ diagnostic: expect.objectContaining({+ code: "unresolved-template",+ templateName: "Missing",+ blockInstanceId: "block",+ renderScope: "route:/:block:block",+ sourceRange: expect.objectContaining({}),+ }),+ }),+ ]);+ });++ test("includes template revisions in dependency identity", async () => {+ const materialize = (templateText: string) => {+ const data = createData({ withTemplate: true });+ data.instances.get("hero")!.children = [+ { type: "text", value: templateText },+ ];+ return materializePublishedMdx({+ route: "/",+ data,+ artifact: createArtifact([+ {+ id: "article",+ source: '<ws.element ws:name="Hero" />',+ },+ ]),+ metas: new Map(),+ projectId: "project",+ });+ };++ const first = await materialize("First");+ const second = await materialize("Second");++ expect(first.roots[0].dependencyRevision).not.toBe(+ second.roots[0].dependencyRevision+ );+ });++ test("includes unresolved template names and referenced Asset revisions in dependency identity", async () => {+ const references = {+ article: [{ path: ["unmatched"], assetId: "image", suffix: "#hero" }],+ };+ const materialize = (imageRevision: string, withTemplate: boolean) =>+ materializePublishedMdx({+ route: "/",+ data: createData({ withTemplate }),+ artifact: createArtifact(+ [+ {+ id: "article",+ source: '<ws.element ws:name="Hero" />',+ },+ { id: "image", source: "image", revision: imageRevision },+ ],+ references+ ),+ metas: new Map(),+ projectId: "project",+ });++ const unresolved = await materialize(revision("e"), false);+ const resolved = await materialize(revision("e"), true);+ const replacedAsset = await materialize(revision("f"), false);++ expect(unresolved.roots[0].templateNames).toEqual(["Hero"]);+ expect(unresolved.roots[0].dependencyRevision).not.toBe(+ resolved.roots[0].dependencyRevision+ );+ expect(unresolved.roots[0].dependencyRevision).not.toBe(+ replacedAsset.roots[0].dependencyRevision+ );+ });++ test("emits ignored authored prop warnings with publication context", async () => {+ const data = createData({ withTemplate: true });+ const hero = data.instances.get("hero");+ if (hero === undefined) {+ throw new Error("Expected template instance");+ }+ hero.component = "HeroComponent";+ const result = await materializePublishedMdx({+ route: "/articles/:slug",+ data,+ artifact: createArtifact([+ {+ id: "article",+ source: '<ws.element ws:name="Hero" mystery="preserved" />',+ },+ ]),+ metas: new Map([+ [+ "HeroComponent",+ {+ presetStyle: { section: [] },+ props: {+ mystery: {+ type: "string",+ control: "text",+ required: false,+ },+ },+ },+ ],+ ]),+ projectId: "project",+ });++ expect(result.warnings).toEqual([+ expect.objectContaining({+ route: "/articles/:slug",+ diagnostic: expect.objectContaining({+ code: "ignored-template-prop",+ reason: "design-only",+ propName: "mystery",+ assetId: "article",+ contentRef: "article.mdx",+ renderScope: "route:/articles/:slug:block:block",+ }),+ }),+ ]);+ });++ test("materializes referenced Assets for the published URL rewrite pipeline", async () => {+ const source =+ '<ws.element ws:tag="img" src="./images/hero.png" alt="Hero" />';+ const document = await parseMdxDocument({ source });+ const result = await materializePublishedMdx({+ route: "/",+ data: createData({}),+ artifact: createArtifact([{ id: "article", source }], {+ article: discoverMdxBodyAssetReferences({+ document,+ sourcePath: "article.mdx",+ assetIdsByPath: new Map([["images/hero.png", "hero-image"]]),+ }),+ }),+ metas: new Map(),+ projectId: "project",+ });++ expect(result.roots[0].fragment.props).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ name: "src",+ type: "asset",+ value: "hero-image",+ }),+ ])+ );+ });++ test("warns for a missing source but recovers unsafe authored content", async () => {+ const missing = await materializePublishedMdx({+ route: "/",+ data: createData({}),+ artifact: createArtifact([]),+ metas: new Map(),+ projectId: "project",+ });+ expect(missing.roots).toEqual([]);+ expect(missing.warnings).toEqual([+ expect.objectContaining({+ diagnostic: expect.objectContaining({+ code: "invalid-mdx",+ assetId: "article",+ message: expect.stringContaining(+ 'requires unavailable MDX Asset "article"'+ ),+ }),+ }),+ ]);++ const recovered = await materializePublishedMdx({+ route: "/",+ data: createData({}),+ artifact: createArtifact([+ { id: "article", source: "# Before\n\n{unsafe}\n\n# After\n" },+ ]),+ metas: new Map(),+ projectId: "project",+ });+ expect(recovered.roots).toHaveLength(1);+ expect(+ recovered.roots[0].fragment.instances.map((instance) =>+ instance.children[0]?.type === "text"+ ? instance.children[0].value+ : undefined+ )+ ).toEqual(["Before", "After"]);+ expect(recovered.warnings).toEqual([+ expect.objectContaining({+ route: "/",+ diagnostic: expect.objectContaining({+ code: "unsafe-mdx",+ assetId: "article",+ sourceRange: expect.objectContaining({+ start: expect.objectContaining({ line: 3, column: 1 }),+ }),+ }),+ }),+ ]);+ });++ test("rejects an invalid document dependency graph", async () => {+ const artifact = createArtifact([{ id: "article", source: "# Article" }]);+ artifact.documentGraph = {+ format: "webstudio-document-graph",+ version: 1,+ nodes: [+ {+ id: "article",+ revision: revision("b"),+ contentRef: "article.mdx",+ format: "mdx",+ },+ ],+ edges: [+ {+ sourceId: "missing",+ referenceId: "#frontmatter/author",+ reference: {+ documentId: "article",+ revision: revision("b"),+ representation: { type: "markdown-frontmatter" },+ },+ },+ ],+ integrity: { algorithm: "sha256", checksum: revision("d") },+ };++ await expect(+ materializePublishedMdx({+ route: "/",+ data: createData({}),+ artifact,+ metas: new Map(),+ projectId: "project",+ })+ ).rejects.toThrow("Document graph source missing does not exist");+ });+});++describe("getUnsafeDynamicPublishedMdxDiagnostic", () => {+ const createRoot = (): PublishedMdxRoot => ({+ source: {+ type: "expression",+ value: "$ws$dataSource$item.file",+ },+ dynamic: true,+ identity: {+ blockInstanceId: "block",+ assetId: "article",+ revision: revision("a"),+ contentRef: "article.mdx",+ format: "mdx",+ renderScope: "route:/:block:block",+ },+ document: { frontmatter: { properties: {} }, children: [] },+ resolvedFrontmatter: {},+ fragment: {+ children: [],+ instances: [],+ props: [],+ dataSources: [],+ resources: [],+ styleSources: [],+ styleSourceSelections: [],+ styles: [],+ breakpoints: [],+ assets: [],+ },+ templateDependencies: [],+ templateNames: [],+ dependencyRevision: revision("b"),+ });++ test("rejects resources selected by a Collection-scoped dynamic source", () => {+ const root = createRoot();+ root.fragment.resources.push({+ id: "query",+ name: "query",+ method: "get",+ url: '"/posts"',+ headers: [],+ });++ expect(+ getUnsafeDynamicPublishedMdxDiagnostic({+ root,+ route: "/",+ dataSources: new Map([+ [+ "item",+ {+ type: "parameter",+ id: "item",+ scopeInstanceId: "collection",+ name: "item",+ },+ ],+ ]),+ props: new Map(),+ })+ ).toMatchObject({ code: "invalid-mdx", assetId: "article" });+ });++ test("rejects action Resources inside dynamic MDX", () => {+ const root = createRoot();+ root.fragment.resources.push({+ id: "submit",+ name: "submit",+ method: "post",+ url: '"/submit"',+ headers: [],+ });+ root.fragment.props.push({+ id: "action",+ instanceId: "form",+ name: "action",+ type: "resource",+ value: "submit",+ });++ expect(+ getUnsafeDynamicPublishedMdxDiagnostic({+ root,+ route: "/",+ dataSources: new Map(),+ props: new Map(),+ })+ ).toMatchObject({ code: "invalid-mdx", assetId: "article" });+ });+});diff --git a/packages/project-build/src/runtime/published-mdx.ts b/packages/project-build/src/runtime/published-mdx.tsnew file mode 100644index 0000000000..b69f03b893--- /dev/null+++ b/packages/project-build/src/runtime/published-mdx.ts@@ -0,0 +1,504 @@+import {+ parseMdxDocumentRecovering,+ type MdxDocument,+} from "@webstudio-is/content-engine/mdx";+import type {+ AssetRuntimeData,+ AssetValueReference,+ ContentArtifactV1,+} from "@webstudio-is/content-engine";+import {+ contentEngineLimits,+ createDocumentGraph,+ getDocumentGraphClosure,+ resolveAssetValueReferences,+ resolveDocumentGraphProperties,+} from "@webstudio-is/content-engine";+import {+ blockComponent,+ decodeDataSourceVariable,+ getAssetContentHash,+ getContentBlockSources,+ getStaticContentBlockSourceAssetId,+ toAssetReferenceRuntimeData,+ type DataSource,+ type Prop,+ type ContentBlockDiagnostic,+ type ContentBlockExternalContentIdentity,+ type ContentBlockSource,+ type WebstudioData,+ type WsComponentMeta,+} from "@webstudio-is/sdk";+import { parseStaticMemberPath } from "@webstudio-is/expression";+import { materializeMdxAuthoredContent } from "./mdx-authored-content";+import {+ materializeMdxTemplates,+ type MdxTemplateDependency,+} from "./mdx-materialization";+import { resolveMdxTemplates } from "./mdx-template-resolution";+import {+ createMdxContentModelDiagnostics,+ createMdxDiagnostics,+} from "./mdx-diagnostics";++export type PublishedMdxWarning = Readonly<{+ route: string;+ diagnostic: ContentBlockDiagnostic;+}>;++export type PublishedMdxRoot = Readonly<{+ source: ContentBlockSource;+ dynamic: boolean;+ identity: ContentBlockExternalContentIdentity;+ document: MdxDocument;+ resolvedFrontmatter: Readonly<Record<string, unknown>>;+ fragment: ReturnType<typeof materializeMdxAuthoredContent>["fragment"];+ templateDependencies: readonly MdxTemplateDependency[];+ templateNames: readonly string[];+ dependencyRevision: `sha256:${string}`;+}>;++export const getUnsafeDynamicPublishedMdxDiagnostic = ({+ root,+ route,+ dataSources,+ props,+}: {+ root: PublishedMdxRoot;+ route: string;+ dataSources: ReadonlyMap<DataSource["id"], DataSource>;+ props: ReadonlyMap<Prop["id"], Prop>;+}): ContentBlockDiagnostic | undefined => {+ if (root.dynamic === false) {+ return;+ }+ const sourcePath =+ root.source.type === "expression"+ ? parseStaticMemberPath(root.source.value)+ : undefined;+ const sourceDataSourceId =+ sourcePath === undefined+ ? undefined+ : decodeDataSourceVariable(sourcePath[0]);+ if (+ root.fragment.resources.length > 0 &&+ sourceDataSourceId !== undefined &&+ dataSources.get(sourceDataSourceId)?.type === "parameter"+ ) {+ return {+ code: "invalid-mdx",+ severity: "error",+ blockInstanceId: root.identity.blockInstanceId,+ assetId: root.identity.assetId,+ renderScope: `route:${route}:block:${root.identity.blockInstanceId}`,+ message:+ "Dynamic MDX selected by a Collection item cannot contain Resources because a single Resource cannot be selected safely for the whole route.",+ };+ }+ const actionResourceIds = new Set(+ [...props.values(), ...root.fragment.props].flatMap((prop) =>+ prop.type === "resource" ? [prop.value] : []+ )+ );+ if (root.fragment.resources.some(({ id }) => actionResourceIds.has(id))) {+ return {+ code: "invalid-mdx",+ severity: "error",+ blockInstanceId: root.identity.blockInstanceId,+ assetId: root.identity.assetId,+ renderScope: `route:${route}:block:${root.identity.blockInstanceId}`,+ message:+ "Dynamic MDX cannot contain action Resources because the submitted action cannot be selected safely at runtime.",+ };+ }+};++const publishedMdxMaterializerRevision = 1;++export const createPublishedMdxMaterializationCache = () => ({+ documents: new Map<+ string,+ Promise<Awaited<ReturnType<typeof parseMdxDocumentRecovering>>>+ >(),+ frontmatter: new Map<string, Promise<Readonly<Record<string, unknown>>>>(),+});++type PublishedMdxMaterializationCache = ReturnType<+ typeof createPublishedMdxMaterializationCache+>;++const getMdxDocuments = (artifact: ContentArtifactV1) =>+ artifact.documents.filter(+ (document) =>+ document.extension?.toLowerCase() === "mdx" ||+ document.mimeType === "text/mdx"+ );++const getNestedDocumentDependencies = ({+ graph,+ assetId,+}: {+ graph: ReturnType<typeof createDocumentGraph> | undefined;+ assetId: string;+}) => {+ if (+ graph === undefined ||+ graph.nodes.some(({ id }) => id === assetId) === false+ ) {+ return [];+ }+ return getDocumentGraphClosure({ graph, rootIds: [assetId] })+ .map(({ id, revision, contentRef }) => ({ id, revision, contentRef }))+ .sort((left, right) => left.id.localeCompare(right.id));+};++const createDependencyRevision = async ({+ identity,+ nestedDocuments,+ assetReferences,+ assetDependencies,+ templateNames,+ templateDependencies,+}: {+ identity: ContentBlockExternalContentIdentity;+ nestedDocuments: ReturnType<typeof getNestedDocumentDependencies>;+ assetReferences: readonly AssetValueReference[];+ assetDependencies: readonly Readonly<{+ id: string;+ contentRef: string;+ revision?: string;+ }>[];+ templateNames: readonly string[];+ templateDependencies: readonly MdxTemplateDependency[];+}) =>+ `sha256:${await getAssetContentHash(+ new TextEncoder().encode(+ JSON.stringify({+ materializerRevision: publishedMdxMaterializerRevision,+ identity,+ nestedDocuments,+ assetReferences: [...assetReferences]+ .map(({ assetId, suffix }) => ({ assetId, suffix }))+ .sort((left, right) =>+ `${left.assetId}${left.suffix ?? ""}`.localeCompare(+ `${right.assetId}${right.suffix ?? ""}`+ )+ ),+ assetDependencies: [...assetDependencies].sort((left, right) =>+ left.id.localeCompare(right.id)+ ),+ templateNames: [...templateNames].sort(),+ templateDependencies: [...templateDependencies].sort((left, right) =>+ left.templateInstanceId.localeCompare(right.templateInstanceId)+ ),+ })+ )+ )}` as const;++export const materializePublishedMdx = async ({+ route,+ data,+ artifact,+ metas,+ projectId,+ cache = createPublishedMdxMaterializationCache(),+ dynamicAssetIdsByBlock = new Map(),+ blockInstanceIds,+ runtimeAssets: providedRuntimeAssets,+}: {+ route: string;+ data: Omit<WebstudioData, "pages">;+ artifact: ContentArtifactV1;+ metas: Map<string, WsComponentMeta>;+ projectId: string;+ cache?: PublishedMdxMaterializationCache;+ dynamicAssetIdsByBlock?: ReadonlyMap<string, readonly string[]>;+ blockInstanceIds?: ReadonlySet<string>;+ runtimeAssets?: Readonly<Record<string, AssetRuntimeData>>;+}): Promise<{+ roots: readonly PublishedMdxRoot[];+ warnings: readonly PublishedMdxWarning[];+}> => {+ const documentsById = new Map(+ artifact.documents.map((document) => [document._id, document])+ );+ const mdxDocumentsById = new Map(+ getMdxDocuments(artifact).map((document) => [document._id, document])+ );+ const documentGraph =+ artifact.documentGraph === undefined+ ? undefined+ : createDocumentGraph(artifact.documentGraph);+ const runtimeAssets =+ providedRuntimeAssets ??+ Object.fromEntries(+ Array.from(data.assets.values(), (asset) => [+ asset.id,+ toAssetReferenceRuntimeData(asset, "https://webstudio.local"),+ ])+ );+ const resolveFrontmatter = (+ assetId: string,+ document: MdxDocument+ ): Promise<Readonly<Record<string, unknown>>> => {+ const cached = cache.frontmatter.get(assetId);+ if (cached !== undefined) {+ return cached;+ }+ const resolving = (async () => {+ if (+ documentGraph !== undefined &&+ documentGraph.nodes.some(({ id }) => id === assetId)+ ) {+ return (+ (await resolveDocumentGraphProperties({+ graph: documentGraph,+ rootId: assetId,+ assetValueReferences: artifact.assetValueReferences,+ runtimeAssets,+ load: async (node) => {+ const source = artifact.contents?.[node.contentRef];+ if (source === undefined || node.format === undefined) {+ throw new Error(`Published document ${node.id} is unavailable`);+ }+ return {+ format: node.format,+ revision: node.revision,+ source,+ };+ },+ })) ?? document.frontmatter.properties+ );+ }+ return resolveAssetValueReferences({+ value: { properties: document.frontmatter.properties },+ references: artifact.assetValueReferences?.[assetId],+ runtimeAssets,+ }).properties;+ })();+ cache.frontmatter.set(assetId, resolving);+ return resolving;+ };+ const sourcesByBlockId = getContentBlockSources({+ instances: data.instances.values(),+ props: data.props.values(),+ });+ const roots: PublishedMdxRoot[] = [];+ const warnings: PublishedMdxWarning[] = [];+ const warnUnavailableSource = ({+ blockInstanceId,+ assetId,+ message,+ }: {+ blockInstanceId: string;+ assetId?: string;+ message: string;+ }) => {+ warnings.push({+ route,+ diagnostic: {+ code: "invalid-mdx",+ severity: "error",+ blockInstanceId,+ ...(assetId === undefined ? {} : { assetId }),+ renderScope: `route:${route}:block:${blockInstanceId}`,+ message,+ },+ });+ };+ for (const block of data.instances.values()) {+ if (+ block.component !== blockComponent ||+ (blockInstanceIds !== undefined &&+ blockInstanceIds.has(block.id) === false)+ ) {+ continue;+ }+ const source = sourcesByBlockId.get(block.id);+ if (source === undefined) {+ continue;+ }+ const staticAssetId = getStaticContentBlockSourceAssetId(source);+ const isDynamicSource = typeof staticAssetId !== "string";+ const resolvedAssetIds =+ typeof staticAssetId === "string" && staticAssetId.length > 0+ ? [staticAssetId]+ : (dynamicAssetIdsByBlock.get(block.id) ?? []);+ if (resolvedAssetIds.length > contentEngineLimits.candidateDocuments) {+ warnUnavailableSource({+ blockInstanceId: block.id,+ message: `Published Content Block "${block.id}" exceeds the safe MDX candidate limit`,+ });+ continue;+ }+ if (resolvedAssetIds.length === 0) {+ warnUnavailableSource({+ blockInstanceId: block.id,+ message: `Published Content Block "${block.id}" has no bounded dynamic MDX dependency set`,+ });+ continue;+ }+ const candidates = Array.from(new Set(resolvedAssetIds))+ .flatMap((assetId) => {+ const document = mdxDocumentsById.get(assetId);+ return document === undefined ? [] : [document];+ })+ .sort((left, right) => left._id.localeCompare(right._id));+ for (const assetId of resolvedAssetIds) {+ if (mdxDocumentsById.has(assetId)) {+ continue;+ }+ warnUnavailableSource({+ blockInstanceId: block.id,+ assetId,+ message: `Published Content Block "${block.id}" requires unavailable MDX Asset "${assetId}"`,+ });+ }+ for (const candidate of candidates) {+ if (+ candidate.revision === undefined ||+ candidate.contentRef === undefined+ ) {+ warnUnavailableSource({+ blockInstanceId: block.id,+ assetId: candidate._id,+ message: `Published MDX Asset "${candidate._id}" has no revision identity`,+ });+ continue;+ }+ const sourceText = artifact.contents?.[candidate.contentRef];+ if (sourceText === undefined) {+ warnUnavailableSource({+ blockInstanceId: block.id,+ assetId: candidate._id,+ message: `Published MDX Asset "${candidate._id}" content is unavailable`,+ });+ continue;+ }+ const identity: ContentBlockExternalContentIdentity = {+ blockInstanceId: block.id,+ assetId: candidate._id,+ revision: candidate.revision,+ contentRef: candidate.contentRef,+ format: "mdx",+ renderScope: `route:${route}:block:${block.id}${+ isDynamicSource ? `:asset:${candidate._id}` : ""+ }`,+ };+ const documentKey = `${candidate._id}:${candidate.revision}:${candidate.contentRef}`;+ let parsedDocument = cache.documents.get(documentKey);+ if (parsedDocument === undefined) {+ if (cache.documents.size >= contentEngineLimits.hydratedFileCount) {+ const oldestKey = cache.documents.keys().next().value;+ if (oldestKey !== undefined) {+ cache.documents.delete(oldestKey);+ }+ }+ parsedDocument = parseMdxDocumentRecovering({ source: sourceText });+ cache.documents.set(documentKey, parsedDocument);+ }+ const parsed = await parsedDocument;+ const recoveryDiagnostics = createMdxDiagnostics({+ identity,+ diagnostics: parsed.diagnostics,+ });+ for (const diagnostic of recoveryDiagnostics) {+ warnings.push({ route, diagnostic });+ }+ if (parsed.status === "unrecoverable") {+ continue;+ }+ const document = parsed.document;+ const resolution = resolveMdxTemplates({+ document,+ identity,+ instances: data.instances,+ metas,+ });+ const templates = await materializeMdxTemplates({+ identity,+ resolution,+ data,+ metas,+ projectId,+ });+ const referencedTemplateNames = Array.from(+ new Set(+ resolution.references.map((reference) => reference.templateName)+ )+ );+ const assetReferences =+ artifact.assetValueReferences?.[candidate._id] ?? [];+ const materialized = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: templates,+ assetReferences,+ });+ if (+ materialized.fragment.instances.length > contentEngineLimits.mdxNodes ||+ materialized.fragment.props.length > contentEngineLimits.mdxProps+ ) {+ warnUnavailableSource({+ blockInstanceId: block.id,+ assetId: candidate._id,+ message: `Published MDX Asset "${candidate._id}" materialization exceeds safe limits`,+ });+ continue;+ }+ for (const diagnostic of templates.diagnostics) {+ warnings.push({ route, diagnostic });+ }+ for (const diagnostic of createMdxContentModelDiagnostics({+ root: materialized,+ metas,+ })) {+ warnings.push({ route, diagnostic });+ }+ roots.push({+ source,+ dynamic: isDynamicSource,+ identity,+ document,+ resolvedFrontmatter: await resolveFrontmatter(candidate._id, document),+ fragment: materialized.fragment,+ templateDependencies: templates.dependencies.templates,+ templateNames: referencedTemplateNames,+ dependencyRevision: await createDependencyRevision({+ identity,+ nestedDocuments: getNestedDocumentDependencies({+ graph: documentGraph,+ assetId: candidate._id,+ }),+ assetReferences,+ assetDependencies: assetReferences.map(({ assetId }) => {+ const asset = data.assets.get(assetId);+ const documentDependency = documentsById.get(assetId);+ return {+ id: assetId,+ contentRef:+ asset?.name ?? documentDependency?.contentRef ?? "unavailable",+ ...(documentDependency?.revision === undefined+ ? {}+ : { revision: documentDependency.revision }),+ };+ }),+ templateNames: referencedTemplateNames,+ templateDependencies: templates.dependencies.templates,+ }),+ });+ }+ }+ const warningKeys = new Set<string>();+ return {+ roots,+ warnings: warnings.filter(({ route: warningRoute, diagnostic }) => {+ const key = JSON.stringify([warningRoute, diagnostic]);+ if (warningKeys.has(key)) {+ return false;+ }+ warningKeys.add(key);+ return true;+ }),+ };+};diff --git a/packages/project-build/src/runtime/registry.test.ts b/packages/project-build/src/runtime/registry.test.tsindex 420eb28db1..49d7d96ad0 100644--- a/packages/project-build/src/runtime/registry.test.ts+++ b/packages/project-build/src/runtime/registry.test.ts@@ -41,6 +41,7 @@ import {state,} from "./runtime.test-fixtures";import { createResourceCollectionIntegrationFixture } from "./runtime-ui.test-fixture";+import type { ContentBlockApplication } from "./content-block-application";const hasDirectInputProperty = (schema: InputJsonSchema | undefined,@@ -132,6 +133,48 @@ const getMutationResult = (operation: unknown): unknown => {return (operation as { result: unknown }).result;};+test("contentBlocks.editSource preserves invalid MDX and returns diagnostics", async () => {+ const source = "# Kept\n\n<ws.element";+ const diagnostic = {+ code: "invalid-mdx" as const,+ severity: "error" as const,+ blockInstanceId: "block",+ assetId: "asset",+ contentRef: "article.mdx",+ renderScope: "page",+ message: "Unexpected end of file",+ sourceRange: {+ start: { line: 3, column: 12, offset: source.length },+ end: { line: 3, column: 12, offset: source.length },+ },+ };+ const result = await executeBuilderRuntimeOperation({+ id: "contentBlocks.editSource",+ state,+ input: { blockInstanceId: "block", renderScope: "page", source },+ context: {+ ...context,+ contentBlockApplication: {+ editSource: async () => ({+ state: {+ asset: { id: "asset" },+ status: "saved" as const,+ },+ source,+ diagnostics: [diagnostic],+ }),+ } as unknown as ContentBlockApplication,+ },+ });++ expect(getMutationResult(result)).toEqual({+ assetId: "asset",+ source,+ status: "saved",+ diagnostics: [diagnostic],+ });+});+test.each([{family: "page",@@ -2321,6 +2364,12 @@ describe("builder runtime registry", () => {test("validates every mutation input at the runtime boundary", () => {const invalidInputByOperation = new Map<string, unknown>([+ ["contentBlocks.connectSource", {}],+ ["contentBlocks.switchSource", {}],+ ["contentBlocks.disconnectSource", {}],+ ["contentBlocks.editSource", {}],+ ["contentBlocks.updateFrontmatter", {}],+ ["contentBlocks.migrateTemplateReferences", {}],["pages.create", {}],["pages.update", {}],["pages.updateSettings", {}],@@ -2354,6 +2403,7 @@ describe("builder runtime registry", () => {["pageTree.reparentOrphans", "invalid"],["runtimeUi.integrate", {}],["instances.insertComponent", { parentInstanceId: "body" }],+ ["instances.insertMdxText", { parentInstanceId: "body" }],["instances.insertCollection", { parentInstanceId: "body" }],["instances.insertFragment", { parentInstanceId: "body" }],["slots.attach", {}],@@ -2522,7 +2572,7 @@ describe("builder runtime registry", () => {);});- test("does not mutate caller state across representative public mutation surfaces", () => {+ test("does not mutate caller state across representative public mutation surfaces", async () => {const inputs = new Map<string, unknown>([["pages.create", { projectId: "project-1", name: "Docs", path: "/docs" }],[@@ -2714,8 +2764,29 @@ describe("builder runtime registry", () => {],["assets.delete", { assetIdsOrPrefixes: ["asset"] }],["assets.replace", { fromAssetId: "asset", toAssetId: "next" }],+ [+ "contentBlocks.migrateTemplateReferences",+ {+ assetIds: ["asset"],+ migration: { type: "rename", from: "Old", to: "New" },+ },+ ],]);+ const immutabilityContext = {+ ...context,+ contentBlockApplication: {+ migrateTemplateReferences: async () => ({+ status: "complete" as const,+ migration: { type: "rename" as const, from: "Old", to: "New" },+ files: [],+ updateCount: 0,+ omissionCount: 0,+ changedFileCount: 0,+ }),+ } as unknown as ContentBlockApplication,+ };+const mutationIds = new Set(mutationOperationIds);for (const manifest of builderRuntimeCutoverManifests) {const familyMutationIds = manifest.operationIds.filter((id) =>@@ -2732,11 +2803,14 @@ describe("builder runtime registry", () => {for (const [id, input] of inputs) {const before = structuredClone(state);let nextId = 0;- executeBuilderRuntimeOperation({+ await executeBuilderRuntimeOperation({id,state,input,- context: { createId: () => `runtime-id-${++nextId}` },+ context: {+ ...immutabilityContext,+ createId: () => `runtime-id-${++nextId}`,+ },});expect(state).toEqual(before);}diff --git a/packages/project-build/src/runtime/registry.ts b/packages/project-build/src/runtime/registry.tsindex 1f430d0d5c..83c8ed27ec 100644--- a/packages/project-build/src/runtime/registry.ts+++ b/packages/project-build/src/runtime/registry.ts@@ -11,6 +11,7 @@ import {} from "../contracts/input-schema";import {assetType,+ contentBlockSource as contentBlockSourceSchema,instanceFilterInput,type InputJsonSchema,} from "@webstudio-is/sdk";@@ -28,6 +29,8 @@ import * as fonts from "./fonts";import * as instanceDuplicate from "./instance-duplicate";import * as instances from "./instances";import * as migrations from "./migrations";+import * as mdxPaste from "./mdx-paste";+import { mdxTemplateMigrationFileLimit } from "./mdx-template-migration";import * as pageCopy from "./page-copy";import * as pages from "./pages";import * as projectSettings from "./project-settings";@@ -38,14 +41,18 @@ import * as slot from "./slot";import * as designTokenImport from "./design-token-import";import * as audit from "./audit";import * as styles from "./styles";-import { getZodValidationIssues, throwBuilderValidationError } from "./errors";+import {+ getZodValidationIssues,+ throwBuilderRuntimeError,+ throwBuilderValidationError,+} from "./errors";import {createRuntimeMutationExecutionSchema,getRuntimeOutputSchema,type RuntimeOperationOutput,type RuntimeOutputSchemaId,} from "./output-schemas";-import type { BuilderRuntimeMutation } from "./mutation";+import { createRuntimeMutation, type BuilderRuntimeMutation } from "./mutation";import { listFragmentExpressions } from "./fragment";import {bindExpressionInput,@@ -333,6 +340,59 @@ const assetUsageNamespaces = ["dataSources",] as const;const emptyInput = z.object({});+const contentBlockOperationInput = z.object({+ blockInstanceId: z.string().min(1),+ renderScope: z.string().min(1),+ variables: z.record(z.string(), z.unknown()).optional(),+});+const contentBlockSourceInput = contentBlockOperationInput.extend({+ source: contentBlockSourceSchema,+ confirm: z.boolean().optional(),+});+const contentBlockEditSourceInput = contentBlockOperationInput.extend({+ source: z.string(),+});+const contentBlockFrontmatterInput = contentBlockOperationInput.extend({+ properties: z.record(z.string(), z.unknown()),+});+const contentBlockTemplateMigrationInput = z.object({+ assetIds: z+ .array(z.string().min(1))+ .min(1)+ .max(mdxTemplateMigrationFileLimit),+ migration: z.union([+ z.object({+ type: z.literal("rename"),+ from: z.string().min(1),+ to: z.string().min(1),+ }),+ z.object({ type: z.literal("remove"), name: z.string().min(1) }),+ ]),+ confirmationToken: z.string().optional(),+});++const requireContentBlockApplication = (context: BuilderRuntimeContext) => {+ if (context.contentBlockApplication === undefined) {+ return throwBuilderRuntimeError(+ "CONFLICT",+ "Content Block source operations require an Asset content session"+ );+ }+ return context.contentBlockApplication;+};++const contentBlockNamespaces = [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+] as const;const pageListInput = z.object({...paginatedOutputInputSchema.shape,});@@ -416,6 +476,273 @@ const assetUsageInput = z.object({});export const builderRuntimeOperations = [+ runtimeOperation(+ "contentBlocks.inspectSource",+ api("inspect-content-block-source", "inspectContentBlockSource", "view"),+ readContract(contentBlockNamespaces, { requiresAssets: true }),+ contentBlockOperationInput,+ async ({ state, input, context }) => {+ const inspected = await requireContentBlockApplication(context).inspect({+ state,+ ...input,+ });+ return {+ source: inspected.source,+ sessionStatus: inspected.sessionStatus,+ identity: inspected.identity,+ diagnostics: [...inspected.diagnostics],+ };+ }+ ),+ runtimeOperation(+ "contentBlocks.connectSource",+ api("connect-content-block-source", "connectContentBlockSource", "edit"),+ mutationContract({+ readNamespaces: contentBlockNamespaces,+ writeNamespaces: contentBlockNamespaces,+ requiresAssets: true,+ requiresConfirm: false,+ }),+ contentBlockSourceInput,+ async ({ state, input, context }) => {+ const prepared = await requireContentBlockApplication(context).connect({+ state,+ ...input,+ });+ return createRuntimeMutation({+ payload:+ prepared.requiresConfirmation && input.confirm !== true+ ? []+ : [...prepared.projectPayload],+ result: {+ action: "connect" as const,+ requiresConfirmation:+ prepared.requiresConfirmation && input.confirm !== true,+ diagnostics: [...prepared.inspection.diagnostics],+ },+ invalidatesNamespaces: contentBlockNamespaces,+ });+ }+ ),+ runtimeOperation(+ "contentBlocks.switchSource",+ api("switch-content-block-source", "switchContentBlockSource", "edit"),+ mutationContract({+ readNamespaces: contentBlockNamespaces,+ writeNamespaces: contentBlockNamespaces,+ requiresAssets: true,+ requiresConfirm: false,+ }),+ contentBlockSourceInput,+ async ({ state, input, context }) => {+ const prepared = await requireContentBlockApplication(+ context+ ).switchSource({+ state,+ ...input,+ });+ return createRuntimeMutation({+ payload: [...prepared.projectPayload],+ result: {+ action: "switch" as const,+ requiresConfirmation: false,+ diagnostics: [...prepared.inspection.diagnostics],+ },+ invalidatesNamespaces: contentBlockNamespaces,+ });+ }+ ),+ runtimeOperation(+ "contentBlocks.disconnectSource",+ api(+ "disconnect-content-block-source",+ "disconnectContentBlockSource",+ "edit"+ ),+ mutationContract({+ readNamespaces: contentBlockNamespaces,+ writeNamespaces: contentBlockNamespaces,+ requiresAssets: true,+ requiresConfirm: false,+ }),+ contentBlockOperationInput.extend({ confirm: z.boolean().optional() }),+ async ({ state, input, context }) => {+ const prepared = await requireContentBlockApplication(context).disconnect(+ {+ state,+ ...input,+ }+ );+ return createRuntimeMutation({+ payload: [...prepared.projectPayload],+ result: {+ action: "disconnect" as const,+ requiresConfirmation: false,+ diagnostics: [],+ },+ invalidatesNamespaces: contentBlockNamespaces,+ });+ }+ ),+ runtimeOperation(+ "contentBlocks.editSource",+ api("edit-content-block-source", "editContentBlockSource", "edit"),+ mutationContract({+ readNamespaces: contentBlockNamespaces,+ writeNamespaces: ["assets"],+ requiresAssets: true,+ requiresConfirm: false,+ }),+ contentBlockEditSourceInput,+ async ({ state, input, context }) => {+ const application = requireContentBlockApplication(context);+ if (context.dryRun === true) {+ const inspected = await application.previewSource({ state, ...input });+ return createRuntimeMutation({+ payload: [],+ result: {+ assetId: inspected.identity.assetId,+ source: input.source,+ status: inspected.state.status,+ diagnostics: [...inspected.diagnostics],+ },+ invalidatesNamespaces: [],+ });+ }+ const saved = await application.editSource({ state, ...input });+ return createRuntimeMutation({+ payload: [],+ result: {+ assetId: saved.state.asset.id,+ source: saved.source,+ status: saved.state.status,+ diagnostics: [...saved.diagnostics],+ },+ invalidatesNamespaces: [],+ });+ }+ ),+ runtimeOperation(+ "contentBlocks.updateFrontmatter",+ api(+ "update-content-block-frontmatter",+ "updateContentBlockFrontmatter",+ "edit"+ ),+ mutationContract({+ readNamespaces: contentBlockNamespaces,+ writeNamespaces: ["assets"],+ requiresAssets: true,+ requiresConfirm: false,+ }),+ contentBlockFrontmatterInput,+ async ({ state, input, context }) => {+ const application = requireContentBlockApplication(context);+ if (context.dryRun === true) {+ const preview = await application.previewFrontmatter({+ state,+ ...input,+ });+ return createRuntimeMutation({+ payload: [],+ result: {+ assetId: preview.identity.assetId,+ source: preview.source,+ status: preview.state.status,+ diagnostics: [...preview.diagnostics],+ },+ invalidatesNamespaces: [],+ });+ }+ const saved = await application.updateFrontmatter({ state, ...input });+ return createRuntimeMutation({+ payload: [],+ result: {+ assetId: saved.state.asset.id,+ source: saved.source,+ status: saved.state.status,+ diagnostics: [...saved.diagnostics],+ },+ invalidatesNamespaces: [],+ });+ }+ ),+ runtimeOperation(+ "contentBlocks.reloadSource",+ api("reload-content-block-source", "reloadContentBlockSource", "view"),+ readContract(contentBlockNamespaces, { requiresAssets: true }),+ contentBlockOperationInput,+ async ({ state, input, context }) => {+ const reloaded = await requireContentBlockApplication(context).reload({+ state,+ ...input,+ });+ const inspected = await requireContentBlockApplication(context).inspect({+ state,+ ...input,+ });+ return {+ assetId: reloaded.asset.id,+ source: reloaded.source,+ status: reloaded.status,+ diagnostics: [...inspected.diagnostics],+ };+ }+ ),+ runtimeOperation(+ "contentBlocks.migrateTemplateReferences",+ api(+ "migrate-content-block-template-references",+ "migrateContentBlockTemplateReferences",+ "edit"+ ),+ mutationContract({+ readNamespaces: contentBlockNamespaces,+ writeNamespaces: ["assets"],+ requiresAssets: true,+ requiresConfirm: false,+ }),+ contentBlockTemplateMigrationInput,+ async ({ input, context }) => {+ const result = await requireContentBlockApplication(+ context+ ).migrateTemplateReferences({+ ...input,+ dryRun: context.dryRun,+ });+ return createRuntimeMutation({+ payload: [],+ result: {+ status: result.status,+ updateCount: result.updateCount,+ omissionCount: result.omissionCount,+ changedFileCount: result.changedFileCount,+ files: result.files.map((file) => ({+ assetId: file.assetId,+ revision: file.revision,+ contentRef: file.contentRef,+ changed: file.changed,+ ...("status" in file ? { status: file.status } : {}),+ updateCount: file.updateCount,+ omissionCount: file.omissionCount,+ diagnostics: file.diagnostics.map(({ code, message }) => ({+ code,+ message,+ })),+ })),+ ...(result.status === "confirmation-required"+ ? {+ confirmation: {+ token: result.confirmationToken,+ expiresAt: result.confirmationExpiresAt,+ },+ }+ : {}),+ },+ invalidatesNamespaces: [],+ });+ }+ ),runtimeOperation("pages.list",api("list-pages", "listPages"),@@ -903,6 +1230,17 @@ export const builderRuntimeOperations = [({ state, input, context }) =>components.insertComponent(state, input, context)),+ runtimeOperation(+ "instances.insertMdxText",+ api("insert-mdx-text", "insertMdxText"),+ mutationContract({+ readNamespaces: components.componentInsertReadNamespaces,+ writeNamespaces: components.componentInsertNamespaces,+ }),+ mdxPaste.insertMdxTextInput,+ ({ state, input, context }) =>+ mdxPaste.insertMdxText({ state, input, context })+ ),runtimeOperation("instances.insertCollection",api("insert-collection", "insertCollection"),@@ -1248,7 +1586,7 @@ export const builderRuntimeOperations = ["instances.updateText",api("update-text", "updateText", "edit"),mutationContract({- readNamespaces: ["instances", "dataSources"],+ readNamespaces: ["instances", "props", "dataSources"],writeNamespaces: ["instances"],retryOnConflict: true,}),@@ -1292,7 +1630,7 @@ export const builderRuntimeOperations = ["instances.setTextContent",api("set-text-content", "setTextContent", "edit"),mutationContract({- readNamespaces: ["instances", "dataSources"],+ readNamespaces: ["instances", "props", "dataSources"],writeNamespaces: ["instances"],retryOnConflict: true,}),diff --git a/packages/project-build/src/runtime/tree.test.ts b/packages/project-build/src/runtime/tree.test.tsindex 9df33f7d5d..30327995b4 100644--- a/packages/project-build/src/runtime/tree.test.ts+++ b/packages/project-build/src/runtime/tree.test.ts@@ -356,7 +356,11 @@ describe("drop targets", () => {]),],["first", createInstance("first", "Box")],- ["second", createInstance("second", "Box")],+ [+ "second",+ createInstance("second", "Box", [{ type: "id", value: "nested" }]),+ ],+ ["nested", createInstance("nested", "Box")],["other-block", createInstance("other-block", blockComponent)],]);@@ -371,6 +375,17 @@ describe("drop targets", () => {})).toBe(true);+ expect(+ canDropInstanceSelector({+ dragSelector: ["first", "block", "body"],+ dropSelector: ["second", "block", "body"],+ instances,+ props,+ metas: componentMetas,+ contentMode: true,+ })+ ).toBe(true);+expect(canDropInstanceSelector({dragSelector: ["first", "block", "body"],diff --git a/packages/project-build/src/runtime/tree.ts b/packages/project-build/src/runtime/tree.tsindex 2e65742cca..a59364dd2d 100644--- a/packages/project-build/src/runtime/tree.ts+++ b/packages/project-build/src/runtime/tree.ts@@ -1,5 +1,4 @@import {- blockComponent,collectionComponent,elementComponent,type Instance,@@ -16,6 +15,7 @@ import {import { findClosestInstanceMatchingFragment } from "./matcher";import { getSlotFragmentDropTargetMutable } from "./slot";import type { InstancePath, InstanceSelector } from "./instance-path";+import { canMoveInstanceInContentMode } from "./block";export type { InstanceSelector } from "./instance-path";@@ -211,14 +211,15 @@ export const canDropInstanceSelector = ({htmlTagsByInstanceId?: Map<Instance["id"], string>;contentMode?: boolean;}) => {- if (contentMode) {- const parentInstance = instances.get(dropSelector[0]);- if (parentInstance?.component !== blockComponent) {- return false;- }- if (dropSelector[0] !== dragSelector[1]) {- return false;- }+ if (+ contentMode &&+ canMoveInstanceInContentMode({+ instanceSelector: dragSelector,+ parentSelector: dropSelector,+ instances,+ }) === false+ ) {+ return false;}const containerSelector = findClosestContainer({metas,diff --git a/packages/project-build/src/runtime/webflow/instances-properties.ts b/packages/project-build/src/runtime/webflow/instances-properties.tsindex 3736107e54..09e2c04730 100644--- a/packages/project-build/src/runtime/webflow/instances-properties.ts+++ b/packages/project-build/src/runtime/webflow/instances-properties.ts@@ -208,8 +208,10 @@ const toFragment = (const component = "CodeText";const data = wfNode.data;addProp("lang", data.language);- addProp("code", data.code);- addInstance({ component });+ addInstance({+ component,+ children: [{ type: "text", value: data.code }],+ });return fragment;}case "HtmlEmbed": {diff --git a/packages/project-migrations/src/index.test.ts b/packages/project-migrations/src/index.test.tsindex 340df9bc86..2ed19a82b4 100644--- a/packages/project-migrations/src/index.test.ts+++ b/packages/project-migrations/src/index.test.ts@@ -136,3 +136,256 @@ test("migrates styles inside webstudio data", () => {},]);});++test("moves legacy Code Text properties into text content", () => {+ const data = structuredClone(emptyData);+ data.instances.set("literal", {+ type: "instance",+ id: "literal",+ component: "CodeText",+ children: [{ type: "text", value: "ignored legacy child" }],+ });+ data.instances.set("bound", {+ type: "instance",+ id: "bound",+ component: "CodeText",+ children: [],+ });+ data.props.set("literal-code", {+ id: "literal-code",+ instanceId: "literal",+ name: "code",+ type: "string",+ value: "const answer = 42;",+ });+ data.props.set("bound-code", {+ id: "bound-code",+ instanceId: "bound",+ name: "code",+ type: "expression",+ value: "$ws$dataSource$code",+ });++ migrateWebstudioDataMutable(data);+ migrateWebstudioDataMutable(data);++ expect(data.instances.get("literal")?.children).toEqual([+ { type: "text", value: "const answer = 42;" },+ ]);+ expect(data.instances.get("bound")?.children).toEqual([+ { type: "expression", value: "$ws$dataSource$code" },+ ]);+ expect(Array.from(data.props.values())).toEqual([]);+});++test("removes redundant Code Text defaults and preserves custom selections", () => {+ const data = structuredClone(emptyData);+ data.instances.set("defaults", {+ type: "instance",+ id: "defaults",+ component: "CodeText",+ children: [],+ });+ data.instances.set("custom", {+ type: "instance",+ id: "custom",+ component: "CodeText",+ children: [],+ });+ data.props.set("default-language", {+ id: "default-language",+ instanceId: "defaults",+ name: "language",+ type: "string",+ value: "javascript",+ });+ data.props.set("default-theme", {+ id: "default-theme",+ instanceId: "defaults",+ name: "theme",+ type: "string",+ value: "github-light",+ });+ data.props.set("custom-language", {+ id: "custom-language",+ instanceId: "custom",+ name: "language",+ type: "string",+ value: "css",+ });+ data.props.set("custom-theme", {+ id: "custom-theme",+ instanceId: "custom",+ name: "theme",+ type: "string",+ value: "nord",+ });++ migrateWebstudioDataMutable(data);+ migrateWebstudioDataMutable(data);++ expect(Array.from(data.props.values())).toEqual([+ expect.objectContaining({ name: "language", value: "css" }),+ expect.objectContaining({ name: "theme", value: "nord" }),+ ]);+});++test("removes the legacy local styles from Content Block Image templates", () => {+ const data = structuredClone(emptyData);+ data.instances.set("templates", {+ type: "instance",+ id: "templates",+ component: "ws:block-template",+ children: [{ type: "id", value: "image" }],+ });+ data.instances.set("image", {+ type: "instance",+ id: "image",+ component: "Image",+ children: [],+ });+ data.styleSources.set("image-local", {+ type: "local",+ id: "image-local",+ });+ data.styleSources.set("custom-local", {+ type: "local",+ id: "custom-local",+ });+ data.styleSourceSelections.set("image", {+ instanceId: "image",+ values: ["image-local", "custom-local"],+ });+ for (const [property, value] of [+ ["marginRight", { type: "keyword", value: "auto" }],+ ["marginLeft", { type: "keyword", value: "auto" }],+ ["width", { type: "unit", unit: "%", value: 100 }],+ ["height", { type: "keyword", value: "auto" }],+ ] as const) {+ data.styles.set(`image-local:base:${property}:`, {+ breakpointId: "base",+ styleSourceId: "image-local",+ property,+ value,+ });+ }+ data.styles.set("custom-local:base:color:", {+ breakpointId: "base",+ styleSourceId: "custom-local",+ property: "color",+ value: { type: "keyword", value: "red" },+ });++ migrateWebstudioDataMutable(data);+ migrateWebstudioDataMutable(data);++ expect(data.styleSourceSelections.get("image")?.values).toEqual([+ "custom-local",+ ]);+ expect(data.styleSources.has("image-local")).toBe(false);+ expect(data.styleSources.has("custom-local")).toBe(true);+ expect(Array.from(data.styles.values())).toEqual([+ expect.objectContaining({ styleSourceId: "custom-local" }),+ ]);+});++test("marks legacy direct Content Block document bindings as readwrite", () => {+ const data = structuredClone(emptyData);+ data.instances.set("block", {+ type: "instance",+ id: "block",+ component: "ws:block",+ children: [{ type: "id", value: "title" }],+ });+ data.instances.set("title", {+ type: "instance",+ id: "title",+ component: "Heading",+ children: [+ {+ type: "expression",+ value: "$ws$dataSource$document.frontmatter.title",+ },+ ],+ });+ data.props.set("source", {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "article",+ });+ data.props.set("document", {+ id: "document",+ instanceId: "block",+ name: "document",+ type: "parameter",+ value: "document",+ });+ data.props.set("label", {+ id: "label",+ instanceId: "title",+ name: "aria-label",+ type: "expression",+ value: "$ws$dataSource$document.frontmatter.title",+ });+ data.props.set("read-only-label", {+ id: "read-only-label",+ instanceId: "title",+ name: "title",+ type: "expression",+ value: "$ws$dataSource$document.frontmatter.title",+ mode: "read",+ });++ migrateWebstudioDataMutable(data);+ migrateWebstudioDataMutable(data);++ expect(data.instances.get("title")?.children).toEqual([+ {+ type: "expression",+ value: "$ws$dataSource$document.frontmatter.title",+ mode: "readwrite",+ },+ ]);+ expect(data.props.get("label")).toMatchObject({ mode: "readwrite" });+ expect(data.props.get("read-only-label")).toMatchObject({ mode: "read" });+});++test("marks legacy document bindings before a Content Block is connected", () => {+ const data = structuredClone(emptyData);+ data.instances.set("block", {+ type: "instance",+ id: "block",+ component: "ws:block",+ children: [{ type: "id", value: "title" }],+ });+ data.instances.set("title", {+ type: "instance",+ id: "title",+ component: "Heading",+ children: [+ {+ type: "expression",+ value: "$ws$dataSource$document.frontmatter.title",+ },+ ],+ });+ data.props.set("document", {+ id: "document",+ instanceId: "block",+ name: "document",+ type: "parameter",+ value: "document",+ });++ migrateWebstudioDataMutable(data);++ expect(data.instances.get("title")?.children).toEqual([+ {+ type: "expression",+ value: "$ws$dataSource$document.frontmatter.title",+ mode: "readwrite",+ },+ ]);+});diff --git a/packages/project-migrations/src/index.ts b/packages/project-migrations/src/index.tsindex 5711ccff76..8587b7d2de 100644--- a/packages/project-migrations/src/index.ts+++ b/packages/project-migrations/src/index.ts@@ -1,10 +1,175 @@-import type { WebstudioData } from "@webstudio-is/sdk";+import {+ blockTemplateComponent,+ codeTextDefaultLanguage,+ codeTextDefaultTheme,+ findWritableContentBlockDocumentBindings,+ type Instance,+ type Prop,+ type StyleDecl,+ type WebstudioData,+} from "@webstudio-is/sdk";import { migratePages } from "./pages";import { migrateResourcesMutable } from "./resources";import { migrateStylesMutable } from "./styles";export { migratePages, serializePages, type SerializedPages } from "./pages";+export const migrateCodeTextPropMutable = ({+ instance,+ prop,+}: {+ instance: Instance | undefined;+ prop: Prop;+}) => {+ if (instance?.component !== "CodeText") {+ return false;+ }+ if (+ prop.type === "string" &&+ ((prop.name === "language" && prop.value === codeTextDefaultLanguage) ||+ (prop.name === "theme" && prop.value === codeTextDefaultTheme))+ ) {+ return true;+ }+ if (+ prop.name !== "code" ||+ (prop.type !== "string" && prop.type !== "expression")+ ) {+ return false;+ }+ instance.children = [+ prop.type === "string"+ ? { type: "text", value: prop.value }+ : {+ type: "expression",+ value: prop.value,+ ...(prop.mode === undefined ? {} : { mode: prop.mode }),+ },+ ];+ return true;+};++export const migrateContentBlockDocumentBindingsMutable = (+ data: Pick<WebstudioData, "instances" | "props">+) => {+ const bindings = findWritableContentBlockDocumentBindings({+ instances: data.instances,+ props: data.props,+ compatibility: "legacy",+ });+ for (const { binding } of bindings.children) {+ binding.mode = "readwrite";+ }+ for (const { binding } of bindings.props) {+ binding.mode = "readwrite";+ }+};++export const migrateCodeTextContentMutable = (+ data: Pick<WebstudioData, "instances" | "props">+) => {+ for (const [propId, prop] of data.props) {+ const instance = data.instances.get(prop.instanceId);+ if (migrateCodeTextPropMutable({ instance, prop }) === false) {+ continue;+ }+ data.props.delete(propId);+ }+};++const isLegacyContentBlockImageStyle = (declarations: StyleDecl[]) => {+ if (+ declarations.length !== 4 ||+ declarations.some(+ ({ breakpointId, state, listed }) =>+ breakpointId !== declarations[0]?.breakpointId ||+ state !== undefined ||+ listed !== undefined+ )+ ) {+ return false;+ }+ const byProperty = new Map(+ declarations.map((declaration) => [declaration.property, declaration.value])+ );+ const isKeyword = (property: "marginRight" | "marginLeft" | "height") => {+ const value = byProperty.get(property);+ return value?.type === "keyword" && value.value === "auto";+ };+ const width = byProperty.get("width");+ return (+ byProperty.size === 4 &&+ isKeyword("marginRight") &&+ isKeyword("marginLeft") &&+ isKeyword("height") &&+ width?.type === "unit" &&+ width.unit === "%" &&+ width.value === 100+ );+};++const migrateContentBlockImageStylesMutable = (+ data: Pick<+ WebstudioData,+ "instances" | "styleSourceSelections" | "styleSources" | "styles"+ >+) => {+ const templateImageIds = new Set<string>();+ for (const instance of data.instances.values()) {+ if (instance.component !== blockTemplateComponent) {+ continue;+ }+ for (const child of instance.children) {+ const image =+ child.type === "id" ? data.instances.get(child.value) : undefined;+ if (image?.component === "Image") {+ templateImageIds.add(image.id);+ }+ }+ }+ const sourceReferenceCounts = new Map<string, number>();+ for (const selection of data.styleSourceSelections.values()) {+ for (const styleSourceId of selection.values) {+ sourceReferenceCounts.set(+ styleSourceId,+ (sourceReferenceCounts.get(styleSourceId) ?? 0) + 1+ );+ }+ }+ for (const imageId of templateImageIds) {+ const selection = data.styleSourceSelections.get(imageId);+ if (selection === undefined) {+ continue;+ }+ for (const styleSourceId of selection.values) {+ if (+ data.styleSources.get(styleSourceId)?.type !== "local" ||+ sourceReferenceCounts.get(styleSourceId) !== 1+ ) {+ continue;+ }+ const declarations = Array.from(data.styles.values()).filter(+ (declaration) => declaration.styleSourceId === styleSourceId+ );+ if (isLegacyContentBlockImageStyle(declarations) === false) {+ continue;+ }+ selection.values = selection.values.filter(+ (candidate) => candidate !== styleSourceId+ );+ if (selection.values.length === 0) {+ data.styleSourceSelections.delete(imageId);+ }+ data.styleSources.delete(styleSourceId);+ for (const [key, declaration] of data.styles) {+ if (declaration.styleSourceId === styleSourceId) {+ data.styles.delete(key);+ }+ }+ }+ }+};+/*** Normalizes persisted project data after loading.*@@ -15,4 +180,7 @@ export const migrateWebstudioDataMutable = (data: WebstudioData) => {data.pages = migratePages(data.pages);migrateResourcesMutable(data.resources.values());migrateStylesMutable(data.styles);+ migrateCodeTextContentMutable(data);+ migrateContentBlockImageStylesMutable(data);+ migrateContentBlockDocumentBindingsMutable(data);};diff --git a/packages/protocol/src/asset-resource-api.test.ts b/packages/protocol/src/asset-resource-api.test.tsindex 65888c674e..1010dbbe35 100644--- a/packages/protocol/src/asset-resource-api.test.ts+++ b/packages/protocol/src/asset-resource-api.test.ts@@ -10,6 +10,7 @@ import { assetResourceLimits } from "@webstudio-is/sdk/asset-resource-limits";import {assetFolderCreateRequest,assetFolderUpdateRequest,+ assetContentDescriptorHeader,assetMetadataUpdate,assetResourceApiOperations,assetUploadReservationRequest,@@ -343,6 +344,14 @@ describe("Assets OpenAPI description", () => {document.paths[assetResourceApiOperations.downloadAssetContent.path].get.responses[200].content).toHaveProperty("*/*");+ expect(+ document.paths[assetResourceApiOperations.downloadAssetContent.path].get+ .responses[200].headers+ ).toHaveProperty(assetContentDescriptorHeader);+ expect(+ document.paths[assetResourceApiOperations.replaceAssetContent.path].put+ .requestBody.content+ ).toHaveProperty("text/mdx", { schema: { type: "string" } });expect(document.paths[assetResourceApiOperations.createAssetFolder.path].post.responses[201]diff --git a/packages/protocol/src/asset-resource-api.ts b/packages/protocol/src/asset-resource-api.tsindex 6b3e1740f0..e05324def1 100644--- a/packages/protocol/src/asset-resource-api.ts+++ b/packages/protocol/src/asset-resource-api.ts@@ -35,6 +35,38 @@ const assetItemApiPath = `${assetsApiUrl}/{assetId}`;const assetContentApiPath = `${assetItemApiPath}/content`;const assetFolderItemApiPath = `${assetsFoldersApiUrl}/{folderId}`;+export const assetContentDescriptorHeader =+ "x-webstudio-asset-content-descriptor";++export const assetContentDescriptor = z.object({+ id: z.string(),+ projectId: z.string(),+ name: z.string(),+ type: assetType,+ format: z.string(),+ size: z.number().nonnegative(),+ createdAt: z.string(),+ updatedAt: z.string().optional(),+});+export type AssetContentDescriptor = z.infer<typeof assetContentDescriptor>;++export const serializeAssetContentDescriptor = (+ value: AssetContentDescriptor+) => encodeURIComponent(JSON.stringify(assetContentDescriptor.parse(value)));++export const parseAssetContentDescriptor = (value: string | null) => {+ if (value === null) {+ throw new Error("Asset content response is missing its revision identity");+ }+ try {+ return assetContentDescriptor.parse(JSON.parse(decodeURIComponent(value)));+ } catch (cause) {+ throw new Error("Asset content response has an invalid revision identity", {+ cause,+ });+ }+};+const operation = <OperationId extends string,Method extends string,@@ -862,6 +894,13 @@ const assetFolderParameters = [projectIdParameter,];const binarySchema = { type: "string", format: "binary" } as const;+const assetContentResponseHeaders = {+ [assetContentDescriptorHeader]: {+ description:+ "URI-encoded JSON identity of the exact Asset revision in this response",+ schema: { type: "string" },+ },+};/*** OpenAPI is both the transport description and the sole query-authoring@@ -1082,6 +1121,7 @@ export const createAssetResourceOpenApi = ({responses: {200: {description: "Complete asset content",+ headers: assetContentResponseHeaders,content: {"*/*": {schema: binarySchema,@@ -1091,6 +1131,7 @@ export const createAssetResourceOpenApi = ({206: {description: "Partial asset content",headers: {+ ...assetContentResponseHeaders,"Content-Range": { schema: { type: "string" } },},content: {@@ -1131,6 +1172,7 @@ export const createAssetResourceOpenApi = ({schema: binarySchema,},"text/markdown": { schema: { type: "string" } },+ "text/mdx": { schema: { type: "string" } },"application/json": { schema: {} },},},diff --git a/packages/protocol/src/builder-api/operation-docs.ts b/packages/protocol/src/builder-api/operation-docs.tsindex 3e29182f38..d42043b456 100644--- a/packages/protocol/src/builder-api/operation-docs.ts+++ b/packages/protocol/src/builder-api/operation-docs.ts@@ -831,7 +831,7 @@ const curatedPublicApiOperationDocumentation = [{command: "update-asset-content",description:- "Replace a text asset's content or extension while preserving its stable asset id; provide exactly one of path or content and use the current asset name as expectedName",+ "Replace a text Asset's content or extension without changing its ID. Provide path or content and its current name as expectedName. Invalid MDX is saved with diagnostics",examples: [`MCP/API: update-asset-content {"assetId":"asset-id","expectedName":"settings_hash.json","content":"{theme:'dark'}"}`,`MCP/API: update-asset-content {"assetId":"asset-id","expectedName":"settings_hash.md","extension":"json","content":"{theme:'dark'}"}`,diff --git a/packages/react-sdk/package.json b/packages/react-sdk/package.jsonindex df0829dfdd..6e1add495d 100644--- a/packages/react-sdk/package.json+++ b/packages/react-sdk/package.json@@ -6,7 +6,7 @@"homepage": "https://webstudio.is","type": "module","scripts": {- "build": "rm -rf lib && esbuild src/index.ts src/runtime.ts --outdir=lib --bundle --format=esm --packages=external",+ "build": "rm -rf lib && esbuild src/index.ts src/runtime.ts src/standard-attributes.ts --outdir=lib --bundle --format=esm --packages=external","dts": "tsc --project tsconfig.dts.json","typecheck": "tsc --noEmit","test": "vitest run"@@ -30,6 +30,7 @@"zod": "^4.4.3"},"dependencies": {+ "@webstudio-is/content-engine": "workspace:*","@webstudio-is/css-engine": "workspace:*","@webstudio-is/expression": "workspace:*","@webstudio-is/fonts": "workspace:*",@@ -51,9 +52,9 @@"import": "./lib/runtime.js"},"./standard-attributes": {- "webstudio": "./src/__generated__/standard-attributes.ts",- "types": "./lib/types/__generated__/standard-attributes.d.ts",- "import": "./lib/__generated__/standard-attributes.js"+ "webstudio": "./src/standard-attributes.ts",+ "types": "./lib/types/standard-attributes.d.ts",+ "import": "./lib/standard-attributes.js"},"./placeholder": {"types": "./placeholder.d.ts"diff --git a/packages/react-sdk/placeholder.d.ts b/packages/react-sdk/placeholder.d.tsindex 572686dc06..b925be91bb 100644--- a/packages/react-sdk/placeholder.d.ts+++ b/packages/react-sdk/placeholder.d.ts@@ -37,9 +37,13 @@ declare module "__CLIENT__" {declare module "__SERVER__" {import type { PageMeta, System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources: (props: { system: System }) => {+ export const getResources: (props: {+ system: System;+ resources?: Record<string, any>;+ }) => {data: Map<string, ResourceRequest>;action: Map<string, ResourceRequest>;+ contentData?: Map<string, ResourceRequest>;};export const getPageMeta: (props: {diff --git a/packages/react-sdk/src/component-generator.test.tsx b/packages/react-sdk/src/component-generator.test.tsxindex d70cf8e6ef..d8d1204367 100644--- a/packages/react-sdk/src/component-generator.test.tsx+++ b/packages/react-sdk/src/component-generator.test.tsx@@ -1408,6 +1408,146 @@ test("ignore ws:block-template when generate index attribute", () => {);});+test("renders pre-materialized dynamic Content Block candidates without loading", () => {+ const instances = new Map([+ [+ "body",+ {+ type: "instance" as const,+ id: "body",+ component: elementComponent,+ tag: "main",+ children: [{ type: "id" as const, value: "block" }],+ },+ ],+ [+ "block",+ {+ type: "instance" as const,+ id: "block",+ component: "ws:block",+ children: [],+ },+ ],+ [+ "article-heading",+ {+ type: "instance" as const,+ id: "article-heading",+ component: elementComponent,+ tag: "h1",+ children: [{ type: "text" as const, value: "Article" }],+ },+ ],+ [+ "other-heading",+ {+ type: "instance" as const,+ id: "other-heading",+ component: elementComponent,+ tag: "h1",+ children: [{ type: "text" as const, value: "Other" }],+ },+ ],+ ]);+ const generated = generateWebstudioComponent({+ classesMap: new Map(),+ scope: createScope(),+ name: "Page",+ rootInstanceId: "body",+ parameters: [],+ metas: new Map(),+ instances,+ props: new Map(),+ dataSources: new Map(),+ publishedContentBlocks: new Map([+ [+ "block",+ {+ sourceExpression: '"article"',+ candidates: [+ {+ assetId: "article",+ dependencyRevision: "article-revision",+ children: [{ type: "id", value: "article-heading" }],+ frontmatter: {},+ },+ {+ assetId: "other",+ dependencyRevision: "other-revision",+ children: [{ type: "id", value: "other-heading" }],+ frontmatter: {},+ },+ ],+ },+ ],+ ]),+ });++ expect(generated).toContain('contentSource === "article"');+ expect(generated).toContain('contentSource === "other"');+ expect(generated.split('("article")')).toHaveLength(2);+ expect(generated).toContain("<h1>");+ expect(generated).not.toContain("fetch(");+ expect(isValidJSX(generated)).toBe(true);+});++test("renders a Content Block shell with candidate frontmatter and body", () => {+ const document = new Parameter("document");+ const Block = ws.block;+ const BlockBody = ws["content-block-body"];+ const data = renderData(+ <$.Body ws:id="page">+ <Block ws:id="block" document={document}>+ <$.Heading ws:id="title">+ {expression`${document}.frontmatter.title`}+ </$.Heading>+ <BlockBody ws:id="content" />+ <$.Text ws:id="footer">Designed footer</$.Text>+ </Block>+ </$.Body>+ );+ data.instances.set("article-body", {+ type: "instance",+ id: "article-body",+ component: elementComponent,+ tag: "p",+ children: [{ type: "text", value: "MDX body" }],+ });++ const generated = generateWebstudioComponent({+ classesMap: new Map(),+ scope: createScope(),+ name: "Page",+ rootInstanceId: "page",+ parameters: [],+ metas: new Map(),+ ...data,+ publishedContentBlocks: new Map([+ [+ "block",+ {+ bodyInstanceId: "content",+ candidates: [+ {+ assetId: "article",+ dependencyRevision: "revision",+ children: [{ type: "id", value: "article-body" }],+ frontmatter: { title: "Frontmatter title" },+ },+ ],+ },+ ],+ ]),+ });++ expect(generated).toContain("Frontmatter title");+ expect(generated).toContain("document?.frontmatter?.title");+ expect(generated).toContain("MDX body");+ expect(generated).toContain("Designed footer");+ expect(isValidJSX(generated)).toBe(true);+});+test("render empty component when no instances found", () => {expect(generateWebstudioComponent({@@ -1459,6 +1599,42 @@ test("render tag property on components", () => {);});+test("converts instance attributes when tag enables HTML attributes", () => {+ expect(+ generateWebstudioComponent({+ classesMap: new Map(),+ scope: createScope(),+ name: "Page",+ rootInstanceId: "bodyId",+ parameters: [],+ metas: new Map(),+ ...renderData(+ <$.Body ws:id="bodyId">+ <$.Box+ ws:id="labelId"+ ws:tag="label"+ tabindex={0}+ readonly={true}+ ></$.Box>+ </$.Body>+ ),+ })+ ).toEqual(+ validateJSX(+ clear(`+ const Page = () => {+ return <Body>+ <Box+ data-ws-tag="label"+ tabIndex={0}+ readOnly={true} />+ </Body>+ }+ `)+ )+ );+});+test("render ws:element component with div tag by default", () => {expect(generateWebstudioComponent({@@ -1678,7 +1854,7 @@ test("ignore props similar to standard attributes when react components defines);});-test("ignore props similar to standard attributes on react components without tags", () => {+test("only converts the universal class alias on components without tags", () => {expect(generateWebstudioComponent({classesMap: new Map(),@@ -1703,9 +1879,9 @@ test("ignore props similar to standard attributes on react components without taconst Page = () => {return <Body><HeadSlot- class={"my-class"}for={"my-id"}- autocomplete={"off"} />+ autocomplete={"off"}+ className={\`\${"my-class"}\`} /></Body>}`)diff --git a/packages/react-sdk/src/component-generator.ts b/packages/react-sdk/src/component-generator.tsindex 2565ca9ad5..0c171476ae 100644--- a/packages/react-sdk/src/component-generator.ts+++ b/packages/react-sdk/src/component-generator.ts@@ -14,7 +14,9 @@ import {parseComponentName,generateExpression,decodeDataSourceVariable,+ contentBlockDocumentProp,blockComponent,+ blockBodyComponent,blockTemplateComponent,collectionComponent,descendantComponent,@@ -23,10 +25,25 @@ import {} from "@webstudio-is/sdk";import { transpileExpression } from "@webstudio-is/expression";import { indexProperty, tagProperty } from "@webstudio-is/sdk/runtime";+import {+ getJsxPropName,+ mapAttributeNames,+} from "@webstudio-is/content-engine/jsx-attributes";import { isAttributeNameSafe, showAttribute } from "./props";-import { standardAttributesToReactProps } from "./__generated__/standard-attributes";import { generateCollectionIterationCode } from "./collection-utils";+export type PublishedContentBlock = Readonly<{+ bodyInstanceId?: Instance["id"];+ sourceExpression?: string;+ candidates: readonly Readonly<{+ assetId: string;+ dependencyRevision: string;+ children: Instance["children"];+ frontmatter: Readonly<Record<string, unknown>>;+ resourceIds?: readonly string[];+ }>[];+}>;+/*** (arg1) => {* myVar = myVar + arg1@@ -202,13 +219,25 @@ export const generateJsxElement = ({);const instancePropNames = new Set(instanceProps.map((prop) => prop.name));const projectedResourceProps = new Map<string, unknown>();-- const getGeneratedPropName = (name: string) => {- if (hasTags && !meta?.props?.[name]) {- return standardAttributesToReactProps[name] ?? name;- }- return name;- };+ const componentPropNames = new Set(Object.keys(meta?.props ?? {}));+ const acceptsHtmlAttributes =+ hasTags ||+ instance.tag !== undefined ||+ instance.component === elementComponent;+ const getGeneratedPropName = (instancePropName: string) =>+ getJsxPropName({+ instancePropName,+ componentPropNames,+ acceptsHtmlAttributes,+ });+ const generatedPropNames = new Map(+ mapAttributeNames({+ attributes: instanceProps.filter(({ name }) => isAttributeNameSafe(name)),+ direction: "instance-to-jsx",+ componentPropNames,+ acceptsHtmlAttributes,+ }).map(({ id, name }) => [id, name])+ );for (const prop of instanceProps) {const propValue = generatePropValue({@@ -237,7 +266,7 @@ export const generateJsxElement = ({}}- const name = getGeneratedPropName(prop.name);+ const name = generatedPropNames.get(prop.id) ?? prop.name;// show prop controls conditional rendering and need to be handled separatelyif (prop.name === showAttribute) {@@ -265,13 +294,9 @@ export const generateJsxElement = ({}continue;}- // We need to merge atomic classes with user-defined className props.- // Webstudio JSX stores className as "class"; keep explicit component APIs- // without tag metadata intact so their "class" prop is not rewritten.- if (- (name === "className" || (name === "class" && meta === undefined)) &&- propValue !== undefined- ) {+ // Merge atomic classes with the JSX className produced by the shared+ // instance-to-JSX property adapter.+ if (name === "className" && propValue !== undefined) {classNameValue = propValue;continue;}@@ -329,7 +354,10 @@ export const generateJsxElement = ({generatedElement += `)\n`;generatedElement += `})\n`;generatedElement += `}\n`;- } else if (instance.component === blockComponent) {+ } else if (+ instance.component === blockComponent ||+ instance.component === blockBodyComponent+ ) {generatedElement += children;} else {let componentVariable;@@ -398,6 +426,8 @@ export const generateJsxChildren = ({indexesWithinAncestors,classesMap,excludePlaceholders,+ publishedContentBlocks,+ contentBodyOverride,}: {scope: Scope;metas: Map<Instance["component"], WsComponentMeta>;@@ -412,6 +442,11 @@ export const generateJsxChildren = ({indexesWithinAncestors: IndexesWithinAncestors;classesMap?: Map<string, Array<string>>;excludePlaceholders?: boolean;+ publishedContentBlocks?: ReadonlyMap<Instance["id"], PublishedContentBlock>;+ contentBodyOverride?: Readonly<{+ instanceId: Instance["id"];+ children: Instance["children"];+ }>;}) => {let generatedChildren = "";for (const child of children) {@@ -443,19 +478,26 @@ export const generateJsxChildren = ({if (instance === undefined) {continue;}- generatedChildren += generateJsxElement({- context: "jsx",- scope,- metas,- tagsOverrides,- instance,- props,- resources,- dataSources,- usedDataSources,- indexesWithinAncestors,- classesMap,- children: generateJsxChildren({+ const publishedContent = publishedContentBlocks?.get(instance.id);+ let generatedInstanceChildren: string;+ if (contentBodyOverride?.instanceId === instance.id) {+ generatedInstanceChildren = generateJsxChildren({+ classesMap,+ scope,+ metas,+ tagsOverrides,+ children: contentBodyOverride.children,+ instances,+ props,+ resources,+ dataSources,+ usedDataSources,+ indexesWithinAncestors,+ excludePlaceholders,+ publishedContentBlocks,+ });+ } else if (publishedContent === undefined) {+ generatedInstanceChildren = generateJsxChildren({classesMap,scope,metas,@@ -468,7 +510,115 @@ export const generateJsxChildren = ({usedDataSources,indexesWithinAncestors,excludePlaceholders,- }),+ publishedContentBlocks,+ contentBodyOverride,+ });+ } else {+ const sourceExpression =+ publishedContent.sourceExpression === undefined+ ? undefined+ : generateExpression({+ expression: publishedContent.sourceExpression,+ dataSources,+ usedDataSources,+ scope,+ });+ const documentParameter = Array.from(props.values()).find(+ (prop): prop is Extract<Prop, { type: "parameter" }> =>+ prop.instanceId === instance.id &&+ prop.name === contentBlockDocumentProp &&+ prop.type === "parameter"+ );+ const documentDataSource =+ documentParameter === undefined+ ? undefined+ : dataSources.get(documentParameter.value);+ if (documentDataSource !== undefined) {+ usedDataSources.set(documentDataSource.id, documentDataSource);+ }+ const documentName =+ documentDataSource === undefined+ ? undefined+ : scope.getName(documentDataSource.id, documentDataSource.name);+ const generatedCandidates = publishedContent.candidates.map(+ ({+ assetId,+ dependencyRevision,+ children: candidateChildren,+ frontmatter,+ }) => {+ const generated = generateJsxChildren({+ classesMap,+ scope,+ metas,+ tagsOverrides,+ children:+ publishedContent.bodyInstanceId === undefined+ ? candidateChildren+ : instance.children,+ instances,+ props,+ resources,+ dataSources,+ usedDataSources,+ indexesWithinAncestors,+ excludePlaceholders,+ publishedContentBlocks,+ contentBodyOverride:+ publishedContent.bodyInstanceId === undefined+ ? undefined+ : {+ instanceId: publishedContent.bodyInstanceId,+ children: candidateChildren,+ },+ });+ const withDocument =+ documentName === undefined+ ? generated+ : `{((${documentName}) => <Fragment>\n${generated}</Fragment>)(${JSON.stringify({ frontmatter })})}\n`;+ return {+ assetId,+ dependencyRevision,+ generated: withDocument,+ };+ }+ );+ if (sourceExpression === undefined) {+ generatedInstanceChildren = generatedCandidates+ .map(+ ({ dependencyRevision, generated }) =>+ `<Fragment key=${JSON.stringify(dependencyRevision)}>\n${generated}</Fragment>\n`+ )+ .join("");+ } else {+ const sourceName = scope.getName(+ `${instance.id}-published-source`,+ "contentSource"+ );+ const branches = generatedCandidates+ .map(+ ({ assetId, dependencyRevision, generated }) =>+ `${sourceName} === ${JSON.stringify(assetId)} ? <Fragment key=${JSON.stringify(dependencyRevision)}>\n${generated}</Fragment>`+ )+ .join(" : ");+ generatedInstanceChildren = `{((${sourceName}) => ${+ branches.length === 0 ? "null" : `${branches} : null`+ })(${sourceExpression})}\n`;+ }+ }+ generatedChildren += generateJsxElement({+ context: "jsx",+ scope,+ metas,+ tagsOverrides,+ instance,+ props,+ resources,+ dataSources,+ usedDataSources,+ indexesWithinAncestors,+ classesMap,+ children: generatedInstanceChildren,});continue;}@@ -489,6 +639,7 @@ export const generateWebstudioComponent = ({metas,tagsOverrides,classesMap,+ publishedContentBlocks,}: {scope: Scope;name: string;@@ -499,6 +650,7 @@ export const generateWebstudioComponent = ({resources?: Resources;dataSources: DataSources;classesMap: Map<string, Array<string>>;+ publishedContentBlocks?: ReadonlyMap<Instance["id"], PublishedContentBlock>;metas: Map<Instance["component"], WsComponentMeta>;/*** Record<tag, componentDescriptor>@@ -538,6 +690,7 @@ export const generateWebstudioComponent = ({usedDataSources,indexesWithinAncestors,classesMap,+ publishedContentBlocks,}),});}diff --git a/packages/react-sdk/src/index.ts b/packages/react-sdk/src/index.tsindex 37033d1feb..79041651c1 100644--- a/packages/react-sdk/src/index.ts+++ b/packages/react-sdk/src/index.ts@@ -8,5 +8,6 @@ export {generateWebstudioComponent,generateJsxElement,generateJsxChildren,+ type PublishedContentBlock,} from "./component-generator";-export * from "./__generated__/standard-attributes";+export * from "./standard-attributes";diff --git a/packages/react-sdk/src/standard-attributes.ts b/packages/react-sdk/src/standard-attributes.tsnew file mode 100644index 0000000000..2856d45c19--- /dev/null+++ b/packages/react-sdk/src/standard-attributes.ts@@ -0,0 +1,7 @@+// Compatibility export. JSX attribute conversion is owned by content-engine.+export {+ getInstancePropName,+ getJsxPropName,+ reactPropsToStandardAttributes,+ standardAttributesToReactProps,+} from "@webstudio-is/content-engine/jsx-attributes";diff --git a/packages/react-sdk/tsconfig.dts.json b/packages/react-sdk/tsconfig.dts.jsonindex 5ec7a91b4a..e91d398186 100644--- a/packages/react-sdk/tsconfig.dts.json+++ b/packages/react-sdk/tsconfig.dts.json@@ -1,6 +1,6 @@{"extends": "./tsconfig.json",- "include": ["src/index.ts", "src/runtime.ts"],+ "include": ["src/index.ts", "src/runtime.ts", "src/standard-attributes.ts"],"compilerOptions": {"declarationDir": "lib/types","rootDir": "./src"diff --git a/packages/sdk-components-react/src/__generated__/code-text.stories.tsx b/packages/sdk-components-react/src/__generated__/code-text.stories.tsxindex 89fc790cc1..091a85414b 100644--- a/packages/sdk-components-react/src/__generated__/code-text.stories.tsx+++ b/packages/sdk-components-react/src/__generated__/code-text.stories.tsx@@ -3,12 +3,7 @@ import { Box as Box, CodeText as CodeText } from "../components";const Component = () => {return (<Box className={`w-box`}>- <CodeText- code={'const status = "ready";'}- language={"javascript"}- theme={"github-light"}- className={`w-code-text`}- />+ <CodeText className={`w-code-text`}>{'const status = "ready";'}</CodeText></Box>);};diff --git a/packages/sdk-components-react/src/button.ws.ts b/packages/sdk-components-react/src/button.ws.tsindex 66f94f96f4..10cd11c023 100644--- a/packages/sdk-components-react/src/button.ws.ts+++ b/packages/sdk-components-react/src/button.ws.ts@@ -5,5 +5,13 @@ import { props } from "./__generated__/button.props";export const meta: WsComponentMeta = {presetStyle: { button },initialProps: ["id", "class", "type", "aria-label"],- props,+ props: {+ ...props,+ "aria-label": {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ },+ },};diff --git a/packages/sdk-components-react/src/code-text/base.tsx b/packages/sdk-components-react/src/code-text/base.tsxindex 780515eeec..70e1c77cba 100644--- a/packages/sdk-components-react/src/code-text/base.tsx+++ b/packages/sdk-components-react/src/code-text/base.tsx@@ -3,9 +3,11 @@ import { type ElementRef, type ComponentProps, forwardRef } from "react";export const defaultTag = "code";type CodeTextProps = ComponentProps<typeof defaultTag> & {+ /** @deprecated Use children (Text Content) instead. */code?: string;language?: string;theme?: string;+ "data-ws-text-editing"?: string;};export const CodeText = forwardRef<@@ -14,7 +16,7 @@ export const CodeText = forwardRef<>(({- code,+ code: legacyCode,children,language: _language,theme: _theme,@@ -22,21 +24,9 @@ export const CodeText = forwardRef<}: CodeTextProps,ref) => {- // Children are supported for Code Text instances created before the- // editable code property was introduced.- if (- (children === undefined && code === undefined) ||- String(code).trim().length === 0- ) {- return (- <code {...props} style={{ padding: 20 }} ref={ref}>- {`Open the "Settings" panel to edit the code.`}- </code>- );- }return (<code {...props} ref={ref}>- {code ?? children}+ {children ?? legacyCode}</code>);}diff --git a/packages/sdk-components-react/src/code-text/build.test.ts b/packages/sdk-components-react/src/code-text/build.test.tsindex 3af52795db..e767e33259 100644--- a/packages/sdk-components-react/src/code-text/build.test.ts+++ b/packages/sdk-components-react/src/code-text/build.test.ts@@ -95,11 +95,16 @@ test("collects the deduplicated union of configured Code Text assets", () => {});});-test("keeps legacy Code Text instances on the plain renderer", () => {- expect(collect(new Map())).toBeUndefined();+test("collects default assets for Code Text without authored props", () => {+ expect(collect(new Map())).toEqual({+ staticLanguages: ["javascript"],+ staticThemes: ["github-light"],+ dynamicLanguages: false,+ dynamicThemes: false,+ });});-test("keeps legacy HTML language instances on the plain renderer", () => {+test("does not confuse the HTML lang attribute with the code language", () => {const props = new Map([["code-1-lang",@@ -113,10 +118,15 @@ test("keeps legacy HTML language instances on the plain renderer", () => {],]) satisfies Props;- expect(collect(props)).toBeUndefined();+ expect(collect(props)).toEqual({+ staticLanguages: ["javascript"],+ staticThemes: ["github-light"],+ dynamicLanguages: false,+ dynamicThemes: false,+ });});-test("rejects incomplete highlighting selections", () => {+test("uses the implicit language for a theme-only selection", () => {const props = new Map([["code-1-theme",@@ -130,9 +140,34 @@ test("rejects incomplete highlighting selections", () => {],]) satisfies Props;- expect(() => collect(props)).toThrow(- 'Code Text "code-1" requires both Language and Theme selections.'- );+ expect(collect(props)).toEqual({+ staticLanguages: ["javascript"],+ staticThemes: ["github-light"],+ dynamicLanguages: false,+ dynamicThemes: false,+ });+});++test("uses the implicit theme for a language-only selection", () => {+ const props = new Map([+ [+ "code-1-language",+ {+ id: "code-1-language",+ instanceId: "code-1",+ name: "language",+ type: "string" as const,+ value: "javascript",+ },+ ],+ ]) satisfies Props;++ expect(collect(props)).toEqual({+ staticLanguages: ["javascript"],+ staticThemes: ["github-light"],+ dynamicLanguages: false,+ dynamicThemes: false,+ });});test("marks expression-bound selections as dynamic", () => {@@ -160,7 +195,7 @@ test("marks expression-bound selections as dynamic", () => {]) satisfies Props;expect(collect(props)).toEqual({- staticLanguages: [],+ staticLanguages: ["javascript"],staticThemes: ["github-light"],dynamicLanguages: true,dynamicThemes: false,diff --git a/packages/sdk-components-react/src/code-text/build.ts b/packages/sdk-components-react/src/code-text/build.tsindex e71cb8d8ab..fba1db957e 100644--- a/packages/sdk-components-react/src/code-text/build.ts+++ b/packages/sdk-components-react/src/code-text/build.ts@@ -1,9 +1,11 @@-import type {- ComponentBuildHook,- Instances,- Prop,- Props,- WsComponentMeta,+import {+ codeTextDefaultLanguage,+ codeTextDefaultTheme,+ type ComponentBuildHook,+ type Instances,+ type Prop,+ type Props,+ type WsComponentMeta,} from "@webstudio-is/sdk";export const codeTextComponent = "CodeText";@@ -61,6 +63,11 @@ export const collectCodeTextAssets = ({meta: WsComponentMeta | undefined;}) => {const selections = new Map<string, Selection>();+ for (const instance of instances.values()) {+ if (instance.component === codeTextComponent) {+ selections.set(instance.id, {});+ }+ }for (const prop of props.values()) {if (prop.name !== "language" && prop.name !== "theme") {continue;@@ -69,9 +76,11 @@ export const collectCodeTextAssets = ({if (instance?.component !== codeTextComponent) {continue;}- const selection = selections.get(instance.id) ?? {};+ const selection = selections.get(instance.id);+ if (selection === undefined) {+ continue;+ }selection[prop.name] = prop;- selections.set(instance.id, selection);}if (selections.size === 0) {@@ -85,23 +94,24 @@ export const collectCodeTextAssets = ({let dynamicLanguages = false;let dynamicThemes = false;for (const [instanceId, selection] of selections) {- if (selection.language === undefined || selection.theme === undefined) {- throw new Error(- `Code Text "${instanceId}" requires both Language and Theme selections.`- );- }- const language = readSelection({- instanceId,- label: "Language",- prop: selection.language,- supportedValues: supportedLanguages,- });- const theme = readSelection({- instanceId,- label: "Theme",- prop: selection.theme,- supportedValues: supportedThemes,- });+ const language =+ selection.language === undefined+ ? codeTextDefaultLanguage+ : readSelection({+ instanceId,+ label: "Language",+ prop: selection.language,+ supportedValues: supportedLanguages,+ });+ const theme =+ selection.theme === undefined+ ? codeTextDefaultTheme+ : readSelection({+ instanceId,+ label: "Theme",+ prop: selection.theme,+ supportedValues: supportedThemes,+ });if (language === undefined) {dynamicLanguages = true;} else if (language !== "plaintext") {diff --git a/packages/sdk-components-react/src/code-text/bundle.test.ts b/packages/sdk-components-react/src/code-text/bundle.test.tsindex 14ff6190f6..487615f220 100644--- a/packages/sdk-components-react/src/code-text/bundle.test.ts+++ b/packages/sdk-components-react/src/code-text/bundle.test.ts@@ -54,7 +54,7 @@ test("bundles only directly selected Shiki assets", async () => {test("keeps Shiki out of plain Code Text bundles", async () => {const inputs = await getBundleInputs(`import { CodeText } from "@webstudio-is/sdk-components-react/components";- export const code = <CodeText code="plain" />;+ export const code = <CodeText>plain</CodeText>;`);expect(inputs.filter((path) => path.includes("shiki"))).toEqual([]);diff --git a/packages/sdk-components-react/src/code-text/canvas.test.tsx b/packages/sdk-components-react/src/code-text/canvas.test.tsxindex e0128c46e1..cb5fc919a2 100644--- a/packages/sdk-components-react/src/code-text/canvas.test.tsx+++ b/packages/sdk-components-react/src/code-text/canvas.test.tsx@@ -8,12 +8,9 @@ const CanvasCodeText = canvasComponents.CodeText;test("loads highlighting without replacing the code element", async () => {const { container, rerender } = render(- <CanvasCodeText- code="const answer = 42;"- language="javascript"- theme="github-light"- tabIndex={0}- />+ <CanvasCodeText language="javascript" theme="github-light" tabIndex={0}>+ const answer = 42;+ </CanvasCodeText>);const codeElement = container.querySelector("code");@@ -26,12 +23,9 @@ test("loads highlighting without replacing the code element", async () => {expect(document.activeElement).toBe(codeElement);rerender(- <CanvasCodeText- code="const answer = 42;"- language="javascript"- theme="nord"- tabIndex={0}- />+ <CanvasCodeText language="javascript" theme="nord" tabIndex={0}>+ const answer = 42;+ </CanvasCodeText>);await waitFor(() => {const updatedCodeElement = container.querySelector("code");@@ -45,3 +39,22 @@ test("loads highlighting without replacing the code element", async () => {expect(container.querySelector("code")).toBe(codeElement);expect(document.activeElement).toBe(codeElement);});++test("renders stable plain text while editing", async () => {+ const { container } = render(+ <CanvasCodeText+ data-ws-text-editing=""+ language="javascript"+ theme="github-light"+ >+ const answer = 42;+ </CanvasCodeText>+ );++ await waitFor(() =>+ expect(container.querySelector("code")?.textContent).toBe(+ "const answer = 42;"+ )+ );+ expect(container.querySelector("code span")).toBeNull();+});diff --git a/packages/sdk-components-react/src/code-text/index.test.tsx b/packages/sdk-components-react/src/code-text/index.test.tsxindex fc8865da5c..45211e895d 100644--- a/packages/sdk-components-react/src/code-text/index.test.tsx+++ b/packages/sdk-components-react/src/code-text/index.test.tsx@@ -21,10 +21,11 @@ test("renders highlighted HAST inside the semantic code root", () => {const markup = renderToStaticMarkup(<HighlightedCodeTextclassName="custom-code"- code="const answer = 42;"language="javascript"theme="github-light"- />+ >+ const answer = 42;+ </HighlightedCodeText>);expect(markup).toMatch(/^<code/);@@ -38,9 +39,22 @@ test("renders highlighted HAST inside the semantic code root", () => {expect(codeElement?.getAttribute("tabindex")).toBeNull();});+test("uses the implicit theme for a language-only code fence", () => {+ const markup = renderToStaticMarkup(+ <HighlightedCodeText language="javascript">+ const answer = 42;+ </HighlightedCodeText>+ );++ expect(markup).toContain("<span");+ expect(markup).not.toContain('theme="github-light"');+});+test("keeps theme colors without changing typography", () => {const markup = renderToStaticMarkup(- <HighlightedCodeText code="// answer" language="javascript" theme="nord" />+ <HighlightedCodeText language="javascript" theme="nord">+ // answer+ </HighlightedCodeText>);const container = document.createElement("div");container.innerHTML = markup;@@ -81,7 +95,7 @@ test("allows a failed asset load to retry after remount", async () => {},});const props = {- code: "const answer = 42;",+ children: "const answer = 42;",language: "javascript",theme: "github-light",} as const;@@ -100,11 +114,9 @@ test("allows a failed asset load to retry after remount", async () => {test("keeps source code escaped", () => {const source = '<img src=x onerror="unsafe()">';const markup = renderToStaticMarkup(- <HighlightedCodeText- code={source}- language="javascript"- theme="github-light"- />+ <HighlightedCodeText language="javascript" theme="github-light">+ {source}+ </HighlightedCodeText>);expect(markup).toContain("<");@@ -117,10 +129,14 @@ test("keeps source code escaped", () => {expect(container.querySelector("img")).toBeNull();});-test("renders legacy content without highlighting configuration", () => {- expect(- renderToStaticMarkup(<HighlightedCodeText>legacy code</HighlightedCodeText>)- ).toBe("<code>legacy code</code>");+test("uses default highlighting without authored props", () => {+ const markup = renderToStaticMarkup(+ <HighlightedCodeText>const ready = true;</HighlightedCodeText>+ );++ expect(markup).toContain("<span");+ expect(markup).not.toContain('language="javascript"');+ expect(markup).not.toContain('theme="github-light"');});test("falls back to plain code for an unavailable selection", () => {@@ -131,25 +147,35 @@ test("falls back to plain code for an unavailable selection", () => {).toBe("<code>puts :hello</code>");});-test("preserves the empty-code placeholder", () => {+test("renders empty text content without inserting authored text", () => {+ expect(+ renderToStaticMarkup(+ <HighlightedCodeText language="javascript" theme="github-light">+ {" "}+ </HighlightedCodeText>+ )+ ).toBe("<code> </code>");+});++test("prefers text content over the legacy code property", () => {expect(renderToStaticMarkup(<HighlightedCodeText- code=" "+ code="legacy"language="javascript"theme="github-light"- />+ >+ current+ </HighlightedCodeText>)- ).toContain("Open the "Settings" panel to edit the code.");+ ).toContain("current");});test("hydrates the server markup without changing the DOM", async () => {const element = (- <HighlightedCodeText- code="const answer = 42;"- language="javascript"- theme="github-light"- />+ <HighlightedCodeText language="javascript" theme="github-light">+ const answer = 42;+ </HighlightedCodeText>);const container = document.createElement("div");container.innerHTML = renderToString(element);@@ -181,7 +207,7 @@ test("preserves server highlighting while client assets load", async () => {suspense: true,});const props = {- code: "const answer = 42;",+ children: "const answer = 42;",language: "javascript",theme: "github-light",} as const;diff --git a/packages/sdk-components-react/src/code-text/index.tsx b/packages/sdk-components-react/src/code-text/index.tsxindex 203860d24b..9fc0d8ee84 100644--- a/packages/sdk-components-react/src/code-text/index.tsx+++ b/packages/sdk-components-react/src/code-text/index.tsx@@ -21,6 +21,10 @@ import {type ThemeRegistrationAny,} from "shiki/core";import { createJavaScriptRegexEngine } from "shiki/engine/javascript";+import {+ codeTextDefaultLanguage,+ codeTextDefaultTheme,+} from "@webstudio-is/sdk";import { CodeText, defaultTag } from "./base";import {codeTextThemeBackgroundVariable,@@ -206,7 +210,16 @@ export const createCodeText = ({const CodeTextContent = forwardRef<ElementRef<typeof defaultTag>,CodeTextProps- >(({ code, children, language, theme, className, style, ...props }, ref) => {+ >((allProps, ref) => {+ const {+ code: legacyCode,+ children,+ language,+ theme,+ className,+ style,+ ...props+ } = allProps;const [, rerender] = useState(0);const didCommit = useRef(false);@@ -214,35 +227,33 @@ export const createCodeText = ({didCommit.current = true;}, []);- const hasSelection =- typeof language === "string" && typeof theme === "string";- const assetsReady = hasSelection && isSelectionLoaded(language, theme);+ const effectiveLanguage = language ?? codeTextDefaultLanguage;+ const effectiveTheme = theme ?? codeTextDefaultTheme;+ const assetsReady = isSelectionLoaded(effectiveLanguage, effectiveTheme);if (suspense && didCommit.current === false && assetsReady === false) {- if (hasSelection) {- const key = JSON.stringify([language, theme]);- let promise = suspenseLoads.get(key);- if (promise === undefined) {- const assets = loadAssets(language, theme);- if (assets !== undefined) {- promise = assets.then((loaded) => {- if (loaded === false) {- return new Promise<void>(() => {});- }- });- suspenseLoads.set(key, promise);- }- }- if (promise !== undefined) {- throw promise;+ const key = JSON.stringify([effectiveLanguage, effectiveTheme]);+ let promise = suspenseLoads.get(key);+ if (promise === undefined) {+ const assets = loadAssets(effectiveLanguage, effectiveTheme);+ if (assets !== undefined) {+ promise = assets.then((loaded) => {+ if (loaded === false) {+ return new Promise<void>(() => {});+ }+ });+ suspenseLoads.set(key, promise);}}+ if (promise !== undefined) {+ throw promise;+ }}useEffect(() => {- if (hasSelection === false || assetsReady) {+ if (assetsReady) {return;}- const promise = loadAssets(language, theme);+ const promise = loadAssets(effectiveLanguage, effectiveTheme);if (promise === undefined) {return;}@@ -256,20 +267,26 @@ export const createCodeText = ({return () => {active = false;};- }, [assetsReady, hasSelection, language, theme]);+ }, [assetsReady, effectiveLanguage, effectiveTheme]);+ const source = typeof children === "string" ? children : legacyCode;+ const isTextEditing = props["data-ws-text-editing"] !== undefined;const highlighted = useMemo(() => {if (+ isTextEditing ||assetsReady === false ||- typeof code !== "string" ||- code.trim().length === 0 ||- typeof language !== "string" ||- typeof theme !== "string"+ typeof source !== "string" ||+ source.trim().length === 0) {return;}- return highlightCode({ highlighter, code, language, theme });- }, [assetsReady, code, language, theme]);+ return highlightCode({+ highlighter,+ code: source,+ language: effectiveLanguage,+ theme: effectiveTheme,+ });+ }, [assetsReady, effectiveLanguage, effectiveTheme, isTextEditing, source]);if (highlighted === undefined) {return (@@ -278,7 +295,7 @@ export const createCodeText = ({ref={ref}className={className}style={style}- code={code}+ code={legacyCode}>{children}</CodeText>diff --git a/packages/sdk-components-react/src/code-text/meta.test.ts b/packages/sdk-components-react/src/code-text/meta.test.tsindex 4aeadf7212..5bd563593b 100644--- a/packages/sdk-components-react/src/code-text/meta.test.ts+++ b/packages/sdk-components-react/src/code-text/meta.test.ts@@ -3,27 +3,38 @@ import { themeNames } from "@shikijs/themes";import { bundledLanguagesInfo } from "shiki/langs";import { meta } from "./meta";-test("exposes static language and theme selections", () => {+test("exposes code content and language without exposing its design theme", () => {expect(meta.deprecated).toBeUndefined();- expect(meta.initialProps).toEqual([- "id",- "class",- "code",- "language",- "theme",- ]);+ expect(meta.initialProps).toEqual(["id", "class", "language", "theme"]);+ expect(meta.contentModel).toEqual({+ category: "instance",+ children: ["text"],+ });+ expect(meta.textContent).toEqual({+ control: "textContent",+ type: "string",+ required: false,+ editor: {+ control: "code",+ languageProp: "language",+ },+ });+ expect(meta.props?.code).toBeUndefined();expect(meta.props?.language).toEqual({label: "Language",- required: true,+ required: false,control: "select",type: "string",+ contentMode: true,+ defaultValue: "javascript",options: ["plaintext", ...bundledLanguagesInfo.map(({ id }) => id)],});expect(meta.props?.theme).toEqual({label: "Theme",- required: true,+ required: false,control: "select",type: "string",+ defaultValue: "github-light",options: [...themeNames],});expect(meta.presetStyle?.code).toEqual(diff --git a/packages/sdk-components-react/src/code-text/meta.ts b/packages/sdk-components-react/src/code-text/meta.tsindex d2a64f4d7f..164cc3a9af 100644--- a/packages/sdk-components-react/src/code-text/meta.ts+++ b/packages/sdk-components-react/src/code-text/meta.ts@@ -1,5 +1,10 @@import { BracesIcon } from "@webstudio-is/icons/svg";-import type { PresetStyle, WsComponentMeta } from "@webstudio-is/sdk";+import {+ codeTextDefaultLanguage,+ codeTextDefaultTheme,+ type PresetStyle,+ type WsComponentMeta,+} from "@webstudio-is/sdk";import { code } from "@webstudio-is/sdk/normalize.css";import type { defaultTag } from "./base";import { codeTextLanguageNames, codeTextThemeNames } from "./options";@@ -51,25 +56,36 @@ export const meta: WsComponentMeta = {description:"Display source code with syntax highlighting for a selected language and theme.",presetStyle,- initialProps: ["id", "class", "code", "language", "theme"],- props: {- code: {- required: true,- control: "codetext",- type: "string",+ contentModel: {+ category: "instance",+ children: ["text"],+ },+ textContent: {+ control: "textContent",+ type: "string",+ required: false,+ editor: {+ control: "code",+ languageProp: "language",},+ },+ initialProps: ["id", "class", "language", "theme"],+ props: {language: {label: "Language",- required: true,+ required: false,control: "select",type: "string",+ contentMode: true,+ defaultValue: codeTextDefaultLanguage,options: codeTextLanguageNames,},theme: {label: "Theme",- required: true,+ required: false,control: "select",type: "string",+ defaultValue: codeTextDefaultTheme,options: codeTextThemeNames,},},diff --git a/packages/sdk-components-react/src/code-text/template.tsx b/packages/sdk-components-react/src/code-text/template.tsxindex 76e5138b08..cf046b667f 100644--- a/packages/sdk-components-react/src/code-text/template.tsx+++ b/packages/sdk-components-react/src/code-text/template.tsx@@ -2,11 +2,5 @@ import { $, type TemplateMeta } from "@webstudio-is/template";export const CodeText: TemplateMeta = {category: "typography",- template: (- <$.CodeText- code={'const status = "ready";'}- language="javascript"- theme="github-light"- />- ),+ template: <$.CodeText>{'const status = "ready";'}</$.CodeText>,};diff --git a/packages/sdk-components-react/src/content-mode-props.test.ts b/packages/sdk-components-react/src/content-mode-props.test.tsnew file mode 100644index 0000000000..68a3fc59fe--- /dev/null+++ b/packages/sdk-components-react/src/content-mode-props.test.ts@@ -0,0 +1,40 @@+import { expect, test } from "vitest";+import type { WsComponentMeta } from "@webstudio-is/sdk";+import * as metas from "./metas";++test("exposes only authored component content in Content mode", () => {+ const contentModeProps = Object.entries(metas).flatMap(+ ([component, meta]: [string, WsComponentMeta]) =>+ Object.entries(meta.props ?? {}).flatMap(([propName, propMeta]) =>+ propMeta.contentMode === true ? [`${component}.${propName}`] : []+ )+ );++ expect(contentModeProps.sort()).toEqual(+ [+ "Button.aria-label",+ "CodeText.language",+ "HtmlEmbed.code",+ "Image.alt",+ "Image.src",+ "Input.aria-label",+ "Input.placeholder",+ "JsonLd.code",+ "Link.download",+ "Link.href",+ "Link.target",+ "MarkdownEmbed.code",+ "Option.label",+ "RichTextLink.download",+ "RichTextLink.href",+ "RichTextLink.target",+ "Textarea.aria-label",+ "Textarea.placeholder",+ "Time.datetime",+ "Video.src",+ "Vimeo.url",+ "VimeoPreviewImage.src",+ "YouTube.url",+ ].sort()+ );+});diff --git a/packages/sdk-components-react/src/html-embed.ws.test.ts b/packages/sdk-components-react/src/html-embed.ws.test.tsnew file mode 100644index 0000000000..c0d1bc1b6a--- /dev/null+++ b/packages/sdk-components-react/src/html-embed.ws.test.ts@@ -0,0 +1,6 @@+import { expect, test } from "vitest";+import { meta } from "./html-embed.ws";++test("exposes embed code in content mode", () => {+ expect(meta.props?.code?.contentMode).toBe(true);+});diff --git a/packages/sdk-components-react/src/html-embed.ws.ts b/packages/sdk-components-react/src/html-embed.ws.tsindex 20f739ab9e..6e510d106b 100644--- a/packages/sdk-components-react/src/html-embed.ws.ts+++ b/packages/sdk-components-react/src/html-embed.ws.ts@@ -43,6 +43,7 @@ export const meta: WsComponentMeta = {control: "code",language: "html",type: "string",+ contentMode: true,},},};diff --git a/packages/sdk-components-react/src/image.ws.ts b/packages/sdk-components-react/src/image.ws.tsindex a90322718c..9965e69f07 100644--- a/packages/sdk-components-react/src/image.ws.ts+++ b/packages/sdk-components-react/src/image.ws.ts@@ -59,13 +59,13 @@ export const meta: WsComponentMeta = {type: "number",control: "number",required: false,- contentMode: true,+ contentMode: false,},height: {type: "number",control: "number",required: false,- contentMode: true,+ contentMode: false,},alt: {type: "string",diff --git a/packages/sdk-components-react/src/input.ws.ts b/packages/sdk-components-react/src/input.ws.tsindex 31324f1f5c..91bafb7783 100644--- a/packages/sdk-components-react/src/input.ws.ts+++ b/packages/sdk-components-react/src/input.ws.ts@@ -25,5 +25,19 @@ export const meta: WsComponentMeta = {"required","autofocus",],- props,+ props: {+ ...props,+ placeholder: {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ },+ "aria-label": {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ },+ },};diff --git a/packages/sdk-components-react/src/json-ld.ws.ts b/packages/sdk-components-react/src/json-ld.ws.tsindex 2a26be9645..781c9343a0 100644--- a/packages/sdk-components-react/src/json-ld.ws.ts+++ b/packages/sdk-components-react/src/json-ld.ws.ts@@ -20,6 +20,7 @@ export const meta: WsComponentMeta = {required: true,control: "json-code",type: "string",+ contentMode: true,},},};diff --git a/packages/sdk-components-react/src/link.ws.test.ts b/packages/sdk-components-react/src/link.ws.test.tsnew file mode 100644index 0000000000..4fc090bd34--- /dev/null+++ b/packages/sdk-components-react/src/link.ws.test.ts@@ -0,0 +1,8 @@+import { expect, test } from "vitest";+import { meta } from "./link.ws";++test("exposes navigation behavior in content mode", () => {+ expect(meta.props?.href?.contentMode).toBe(true);+ expect(meta.props?.target?.contentMode).toBe(true);+ expect(meta.props?.download?.contentMode).toBe(true);+});diff --git a/packages/sdk-components-react/src/link.ws.ts b/packages/sdk-components-react/src/link.ws.tsindex b0d9db55b8..1df2a4bb41 100644--- a/packages/sdk-components-react/src/link.ws.ts+++ b/packages/sdk-components-react/src/link.ws.ts@@ -26,5 +26,13 @@ export const meta: WsComponentMeta = {required: false,contentMode: true,},+ target: {+ ...props.target!,+ contentMode: true,+ },+ download: {+ ...props.download!,+ contentMode: true,+ },},};diff --git a/packages/sdk-components-react/src/option.ws.ts b/packages/sdk-components-react/src/option.ws.tsindex dade59d8f3..0c790ea76e 100644--- a/packages/sdk-components-react/src/option.ws.ts+++ b/packages/sdk-components-react/src/option.ws.ts@@ -36,6 +36,14 @@ export const meta: WsComponentMeta = {{ selector: ":hover", label: "Hover" },{ selector: ":disabled", label: "Disabled" },],- initialProps: ["label", "value", "label", "disabled"],- props,+ initialProps: ["label", "value", "disabled"],+ props: {+ ...props,+ label: {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ },+ },};diff --git a/packages/sdk-components-react/src/textarea.ws.ts b/packages/sdk-components-react/src/textarea.ws.tsindex d63a56d08a..a18e244314 100644--- a/packages/sdk-components-react/src/textarea.ws.ts+++ b/packages/sdk-components-react/src/textarea.ws.ts@@ -30,5 +30,19 @@ export const meta: WsComponentMeta = {"required","autofocus",],- props,+ props: {+ ...props,+ placeholder: {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ },+ "aria-label": {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ },+ },};diff --git a/packages/sdk-components-react/src/time.ws.ts b/packages/sdk-components-react/src/time.ws.tsindex 1b52ac9708..f09b5d97dd 100644--- a/packages/sdk-components-react/src/time.ws.ts+++ b/packages/sdk-components-react/src/time.ws.ts@@ -32,19 +32,15 @@ export const meta: WsComponentMeta = {},language: {...props.language,- contentMode: true,},country: {...props.country,- contentMode: true,},dateStyle: {...props.dateStyle,- contentMode: true,},timeStyle: {...props.timeStyle,- contentMode: true,},timeZone: {required: false,@@ -54,11 +50,9 @@ export const meta: WsComponentMeta = {options: ["UTC", "visitor"],description:'Timezone used to display the date. Use "visitor" to display each visitor’s browser timezone after the page loads, or select/type an IANA timezone like "Europe/Berlin".',- contentMode: true,},format: {...props.format,- contentMode: true,},},};diff --git a/packages/sdk-components-react/src/video.ws.ts b/packages/sdk-components-react/src/video.ws.tsindex 804d5590bf..f77565454b 100644--- a/packages/sdk-components-react/src/video.ws.ts+++ b/packages/sdk-components-react/src/video.ws.ts@@ -41,13 +41,13 @@ export const meta: WsComponentMeta = {type: "number",control: "number",required: false,- contentMode: true,+ contentMode: false,},height: {type: "number",control: "number",required: false,- contentMode: true,+ contentMode: false,},},};diff --git a/packages/sdk/package.json b/packages/sdk/package.jsonindex 284ecb358f..faab48ca9d 100644--- a/packages/sdk/package.json+++ b/packages/sdk/package.json@@ -79,6 +79,7 @@"@webstudio-is/wsauth": "workspace:*","change-case": "^5.4.4","json-schema-typed": "^8.0.2",+ "nanoid": "^5.1.5","reserved-identifiers": "^1.0.0","type-fest": "^4.37.0","warn-once": "^0.1.1",diff --git a/packages/sdk/src/assets.test.ts b/packages/sdk/src/assets.test.tsindex 7837ddf3a5..df0fc14ca5 100644--- a/packages/sdk/src/assets.test.ts+++ b/packages/sdk/src/assets.test.ts@@ -139,6 +139,7 @@ describe("allowed-file-types", () => {["txt", "plain"],["csv", "plain"],["md", "markdown"],+ ["mdx", "markdown"],["js", "javascript"],["css", "css"],["json", "json"],@@ -163,12 +164,14 @@ describe("allowed-file-types", () => {expect(getMimeTypeByExtension("png")).toBe("image/png");expect(getMimeTypeByExtension("pdf")).toBe("application/pdf");expect(getMimeTypeByExtension("mp4")).toBe("video/mp4");+ expect(getMimeTypeByExtension("mdx")).toBe("text/mdx");});test("is case-insensitive", () => {expect(getMimeTypeByExtension("JPG")).toBe("image/jpeg");expect(getMimeTypeByExtension("PNG")).toBe("image/png");expect(getMimeTypeByExtension("PDF")).toBe("application/pdf");+ expect(getMimeTypeByExtension("MDX")).toBe("text/mdx");});test("returns undefined for invalid extension", () => {diff --git a/packages/sdk/src/assets.ts b/packages/sdk/src/assets.tsindex 9e15d2070a..bcbbe04d7f 100644--- a/packages/sdk/src/assets.ts+++ b/packages/sdk/src/assets.ts@@ -56,6 +56,26 @@ export const getAssetContentHash = async ().join("");};+const contentHashPattern = /^[0-9a-f]{64}$/;++export const isContentHash = (value: unknown): value is string =>+ typeof value === "string" && contentHashPattern.test(value);++export const createAssetContentRevision = ({+ storageName,+ updatedAt,+ size,+ contentHash,+}: {+ storageName: string;+ updatedAt: string;+ size: number;+ contentHash?: string | null;+}) =>+ isContentHash(contentHash)+ ? `sha256:${contentHash}`+ : `file:${encodeURIComponent(storageName)}:${updatedAt}:${size}`;+export type ParsedAssetName = {basename: string;hash: string;@@ -139,6 +159,7 @@ const assetFileTypes = {// Codetxt: textFile("text/plain", "plain"),md: textFile("text/markdown", "markdown"),+ mdx: textFile("text/mdx", "markdown"),js: textFile("text/javascript", "javascript"),css: textFile("text/css", "css"),json: textFile("application/json", "json"),@@ -312,6 +333,10 @@ export const getAssetTextEditorLanguage = (export const isTextFileAsset = (asset: Pick<Asset, "format">): boolean =>getAssetTextEditorLanguage(asset) !== undefined;+export const isMdxFileAsset = (+ asset: Readonly<{ type: string; format: string }>+) => asset.type === "file" && asset.format.toLowerCase() === "mdx";+/*** Get MIME type from a filename*/diff --git a/packages/sdk/src/code-text.ts b/packages/sdk/src/code-text.tsnew file mode 100644index 0000000000..6eebb51795--- /dev/null+++ b/packages/sdk/src/code-text.ts@@ -0,0 +1,2 @@+export const codeTextDefaultLanguage = "javascript";+export const codeTextDefaultTheme = "github-light";diff --git a/packages/sdk/src/content-block.test.ts b/packages/sdk/src/content-block.test.tsnew file mode 100644index 0000000000..f4733fa62a--- /dev/null+++ b/packages/sdk/src/content-block.test.ts@@ -0,0 +1,478 @@+import { describe, expect, test } from "vitest";+import {+ blockComponent,+ blockBodyComponent,+ blockTemplateComponent,+ coreMetas,+} from "./core-metas";+import type { FileAsset } from "./schema/assets";+import type { Instance } from "./schema/instances";+import type { Prop } from "./schema/props";+import {+ allocateUniqueContentBlockTemplateName,+ findContentBlockBodyContainerPaths,+ findContentBlockTemplateContainers,+ getWritableContentBlockDocumentBinding,+ findWritableContentBlockDocumentBindings,+ getContentBlockSourceIntegrityIssues,+ isEqualContentBlockSource,+ parseContentBlockSourceProp,+} from "./content-block";+import { encodeDataSourceVariable } from "./expression";++test("declares the Content Block source as a Design-mode MDX property", () => {+ expect(coreMetas[blockComponent]).toMatchObject({+ initialProps: ["src"],+ props: {+ src: {+ type: "string",+ control: "file",+ label: "Source",+ description:+ "Create an .mdx file in Assets, then select or bind it here.",+ accept: ".mdx",+ contentMode: false,+ },+ },+ });+});++const block: Instance = {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [],+};++const sourceProp = (values: Partial<Prop> = {}): Prop =>+ ({+ id: "source-prop",+ instanceId: block.id,+ name: "src",+ type: "asset",+ value: "post",+ ...values,+ }) as Prop;++const mdxAsset: FileAsset = {+ id: "post",+ projectId: "project",+ type: "file",+ name: "post_hash.mdx",+ filename: "post",+ format: "mdx",+ size: 1,+ meta: {},+ description: null,+ createdAt: "2026-08-14T00:00:00.000Z",+};++describe("Content Block source", () => {+ test("finds every Templates container without hiding invalid duplicates", () => {+ const first: Instance = {+ type: "instance",+ id: "templates-1",+ component: blockTemplateComponent,+ children: [],+ };+ const second: Instance = { ...first, id: "templates-2" };+ const other: Instance = {+ type: "instance",+ id: "other",+ component: "ws:element",+ tag: "div",+ children: [],+ };+ const contentBlock = {+ ...block,+ children: [first, other, second].map(({ id }) => ({+ type: "id" as const,+ value: id,+ })),+ };+ const instances = new Map(+ [contentBlock, first, other, second].map((instance) => [+ instance.id,+ instance,+ ])+ );++ expect(+ findContentBlockTemplateContainers({+ blockInstance: contentBlock,+ instances,+ })+ ).toEqual([first, second]);+ });++ test("finds a Body outlet nested in the designed shell", () => {+ const body: Instance = {+ type: "instance",+ id: "body",+ component: blockBodyComponent,+ children: [],+ };+ const shell: Instance = {+ type: "instance",+ id: "shell",+ component: "ws:element",+ tag: "article",+ children: [{ type: "id", value: body.id }],+ };+ const contentBlock: Instance = {+ ...block,+ children: [{ type: "id", value: shell.id }],+ };+ const instances = new Map(+ [contentBlock, shell, body].map((instance) => [instance.id, instance])+ );++ expect(+ findContentBlockBodyContainerPaths({+ blockInstance: contentBlock,+ instances,+ })+ ).toEqual([[shell, body]]);+ });++ test("recognizes only direct document frontmatter bindings", () => {+ const document = encodeDataSourceVariable("document-id");+ expect(+ getWritableContentBlockDocumentBinding({+ binding: {+ type: "expression",+ value: `${document}.frontmatter.author.name`,+ mode: "readwrite",+ },+ documentDataSourceId: "document-id",+ })+ ).toEqual({+ type: "writable-content-block-document-binding",+ expression: {+ type: "direct-path",+ expression: `${document}.frontmatter.author.name`,+ path: [document, "frontmatter", "author", "name"],+ },+ frontmatterPath: ["author", "name"],+ });+ expect(+ getWritableContentBlockDocumentBinding({+ binding: {+ type: "expression",+ value: `${document}.frontmatter.title ?? "Untitled"`,+ mode: "readwrite",+ },+ documentDataSourceId: "document-id",+ })+ ).toBeUndefined();+ expect(+ getWritableContentBlockDocumentBinding({+ binding: {+ type: "expression",+ value: `${document}.frontmatter.title`,+ },+ documentDataSourceId: "document-id",+ })+ ).toBeUndefined();+ expect(+ getWritableContentBlockDocumentBinding({+ binding: {+ type: "expression",+ value: `${document}.frontmatter["__proto__"].polluted`,+ mode: "readwrite",+ },+ documentDataSourceId: "document-id",+ })+ ).toBeUndefined();+ });++ test("finds direct document bindings inside a connected Content Block", () => {+ const document = encodeDataSourceVariable("document-id");+ const title: Instance = {+ type: "instance",+ id: "title",+ component: "Heading",+ children: [+ {+ type: "expression",+ value: `${document}.frontmatter.title`,+ mode: "readwrite",+ },+ ],+ };+ const contentBlock: Instance = {+ ...block,+ children: [{ type: "id", value: title.id }],+ };+ const titleProp: Prop = {+ id: "title-prop",+ instanceId: title.id,+ name: "aria-label",+ type: "expression",+ value: `${document}.frontmatter.title`,+ mode: "readwrite",+ };+ const instances = new Map(+ [contentBlock, title].map((instance) => [instance.id, instance])+ );+ const props = new Map<string, Prop>([+ ["source", sourceProp()],+ [+ "document",+ {+ id: "document",+ instanceId: block.id,+ name: "document",+ type: "parameter",+ value: "document-id",+ },+ ],+ [titleProp.id, titleProp],+ ]);++ expect(+ findWritableContentBlockDocumentBindings({ instances, props })+ ).toEqual({+ children: [+ expect.objectContaining({ instanceId: title.id, childIndex: 0 }),+ ],+ props: [expect.objectContaining({ propId: titleProp.id })],+ });+ });++ test("keeps the source optional for existing Content Blocks", () => {+ expect(+ getContentBlockSourceIntegrityIssues({+ instances: [block],+ props: [],+ assets: [],+ })+ ).toEqual([]);+ });++ test("maps persisted Asset and expression props to the source contract", () => {+ expect(parseContentBlockSourceProp(sourceProp())).toEqual({+ type: "asset",+ assetId: "post",+ });+ expect(+ parseContentBlockSourceProp(+ sourceProp({ type: "expression", value: "post.body" })+ )+ ).toEqual({ type: "expression", value: "post.body" });+ expect(+ parseContentBlockSourceProp(sourceProp({ type: "string", value: "post" }))+ ).toBeUndefined();+ });++ test("compares source bindings by their persisted identity", () => {+ expect(isEqualContentBlockSource(undefined, undefined)).toBe(true);+ expect(+ isEqualContentBlockSource(+ { type: "asset", assetId: "post" },+ { type: "asset", assetId: "post" }+ )+ ).toBe(true);+ expect(+ isEqualContentBlockSource(+ { type: "expression", value: "post.body" },+ { type: "expression", value: "post.body" }+ )+ ).toBe(true);+ expect(+ isEqualContentBlockSource(+ { type: "asset", assetId: "post" },+ { type: "expression", value: "post" }+ )+ ).toBe(false);+ });++ test("diagnoses duplicate, invalid, missing, and incompatible sources", () => {+ expect(+ getContentBlockSourceIntegrityIssues({+ instances: [block],+ props: [sourceProp(), sourceProp({ id: "other-source" })],+ assets: [mdxAsset],+ })+ ).toEqual([+ {+ type: "duplicateContentBlockSource",+ blockInstanceId: "block",+ propIds: ["source-prop", "other-source"],+ },+ ]);+ expect(+ getContentBlockSourceIntegrityIssues({+ instances: [block],+ props: [sourceProp({ type: "string" })],+ assets: [mdxAsset],+ })+ ).toEqual([+ {+ type: "invalidContentBlockSource",+ blockInstanceId: "block",+ propId: "source-prop",+ propType: "string",+ },+ ]);+ expect(+ getContentBlockSourceIntegrityIssues({+ instances: [block],+ props: [sourceProp()],+ assets: [],+ })+ ).toEqual([+ {+ type: "missingContentBlockSourceAsset",+ blockInstanceId: "block",+ propId: "source-prop",+ assetId: "post",+ },+ ]);+ expect(+ getContentBlockSourceIntegrityIssues({+ instances: [block],+ props: [sourceProp()],+ assets: [{ ...mdxAsset, name: "post_hash.md", format: "md" }],+ })+ ).toEqual([+ {+ type: "incompatibleContentBlockSourceAsset",+ blockInstanceId: "block",+ propId: "source-prop",+ assetId: "post",+ assetName: "post_hash.md",+ },+ ]);+ expect(+ getContentBlockSourceIntegrityIssues({+ instances: [block],+ props: [sourceProp()],+ assets: [mdxAsset],+ })+ ).toEqual([]);+ });+});++describe("allocateUniqueContentBlockTemplateName", () => {+ test.each([+ {+ name: "Card",+ existingNames: [],+ expected: "Card",+ reason: "keeps an unused name",+ },+ {+ name: " Card ",+ existingNames: [],+ expected: "Card",+ reason: "trims an unused name",+ },+ {+ name: "Card",+ existingNames: ["Card"],+ expected: "Card 2",+ reason: "adds the first suffix",+ },+ {+ name: "Card",+ existingNames: ["Card", "Card 2"],+ expected: "Card 3",+ reason: "skips a consecutive collision",+ },+ {+ name: "Card",+ existingNames: ["Card", "Card 3"],+ expected: "Card 2",+ reason: "fills the first available suffix",+ },+ {+ name: "Card 2",+ existingNames: ["Card 2"],+ expected: "Card 3",+ reason: "increments an existing suffix",+ },+ {+ name: "Card 2",+ existingNames: ["Card 2", "Card 3", "Card 5"],+ expected: "Card 4",+ reason: "fills a gap after an existing suffix",+ },+ {+ name: "Card 20",+ existingNames: ["Card 20"],+ expected: "Card 21",+ reason: "increments a multi-digit suffix",+ },+ {+ name: "Card 1",+ existingNames: ["Card 1"],+ expected: "Card 1 2",+ reason: "treats one as part of the base name",+ },+ {+ name: "Card 0",+ existingNames: ["Card 0"],+ expected: "Card 0 2",+ reason: "treats zero as part of the base name",+ },+ {+ name: "Card -2",+ existingNames: ["Card -2"],+ expected: "Card -2 2",+ reason: "does not interpret a negative suffix",+ },+ {+ name: "Card 2.5",+ existingNames: ["Card 2.5"],+ expected: "Card 2.5 2",+ reason: "does not interpret a decimal suffix",+ },+ {+ name: "Card 9007199254740992",+ existingNames: ["Card 9007199254740992"],+ expected: "Card 9007199254740992 2",+ reason: "does not increment an unsafe integer suffix",+ },+ {+ name: "Card 9007199254740991",+ existingNames: ["Card 9007199254740991"],+ expected: "Card 9007199254740991 2",+ reason: "does not increment past the safe integer range",+ },+ {+ name: "Card 9007199254740990",+ existingNames: ["Card 9007199254740990", "Card 9007199254740991"],+ expected: "Card 9007199254740991 2",+ reason: "falls back after colliding at the safe integer boundary",+ },+ {+ name: "Card 02",+ existingNames: ["Card 02"],+ expected: "Card 3",+ reason: "normalizes an incremented numeric suffix",+ },+ {+ name: "card",+ existingNames: ["Card"],+ expected: "card",+ reason: "matches names case-sensitively",+ },+ {+ name: "Héro 🦸",+ existingNames: ["Héro 🦸"],+ expected: "Héro 🦸 2",+ reason: "preserves Unicode names",+ },+ ])("$reason", ({ name, existingNames, expected }) => {+ const names = new Set(existingNames);++ expect(+ allocateUniqueContentBlockTemplateName({+ name,+ existingNames: names,+ })+ ).toBe(expected);+ expect(names).toEqual(new Set(existingNames));+ });+});diff --git a/packages/sdk/src/content-block.ts b/packages/sdk/src/content-block.tsnew file mode 100644index 0000000000..de3f361081--- /dev/null+++ b/packages/sdk/src/content-block.ts@@ -0,0 +1,558 @@+import { createAssetContentRevision, isMdxFileAsset } from "./assets";+import {+ parseJsonExpression,+ parseDirectPathExpression,+ type DirectPathExpression,+} from "@webstudio-is/expression";+import {+ blockBodyComponent,+ blockComponent,+ blockTemplateComponent,+} from "./core-metas";+import {+ contentBlockDocumentProp,+ contentBlockSourceProp,+ contentBlockSourcePropSchema,+ type ContentBlockExternalContentIdentity,+ type ContentBlockSource,+} from "./schema/content-block";+import type { Asset } from "./schema/assets";+import type { ExpressionChild, Instance, Instances } from "./schema/instances";+import type { ExpressionBinding } from "./schema/expression";+import type { Prop, Props } from "./schema/props";+import { decodeDataSourceVariable } from "./expression";++export const createContentBlockExternalContentIdentity = ({+ blockInstanceId,+ asset,+ renderScope,+}: {+ blockInstanceId: Instance["id"];+ asset: Readonly<{+ id: string;+ name: string;+ size: number;+ createdAt: string;+ updatedAt?: string;+ contentHash?: string | null;+ }>;+ renderScope: string;+}): ContentBlockExternalContentIdentity => ({+ blockInstanceId,+ assetId: asset.id,+ revision: createAssetContentRevision({+ storageName: asset.name,+ updatedAt: asset.updatedAt ?? asset.createdAt,+ size: asset.size,+ contentHash: asset.contentHash,+ }),+ contentRef: asset.name,+ format: "mdx",+ renderScope,+});++export const parseContentBlockSourceProp = (+ prop: Prop+): ContentBlockSource | undefined => {+ const result = contentBlockSourcePropSchema.safeParse(prop);+ if (result.success === false) {+ return;+ }+ if (result.data.type === "asset") {+ return { type: "asset", assetId: result.data.value };+ }+ if (result.data.type === "expression") {+ return { type: "expression", value: result.data.value };+ }+};++export const getContentBlockSource = ({+ blockInstanceId,+ props,+}: {+ blockInstanceId: Instance["id"];+ props: Iterable<Prop>;+}) => {+ let sourceProp: Prop | undefined;+ for (const prop of props) {+ if (+ prop.instanceId !== blockInstanceId ||+ prop.name !== contentBlockSourceProp+ ) {+ continue;+ }+ if (sourceProp !== undefined) {+ return;+ }+ sourceProp = prop;+ }+ return sourceProp === undefined+ ? undefined+ : parseContentBlockSourceProp(sourceProp);+};++const groupContentBlockSourceProps = (props: Iterable<Prop>) => {+ const sourcePropsByInstanceId = new Map<Instance["id"], Prop[]>();+ for (const prop of props) {+ if (prop.name !== contentBlockSourceProp) {+ continue;+ }+ const sourceProps = sourcePropsByInstanceId.get(prop.instanceId) ?? [];+ sourceProps.push(prop);+ sourcePropsByInstanceId.set(prop.instanceId, sourceProps);+ }+ return sourcePropsByInstanceId;+};++export const getContentBlockSources = ({+ instances,+ props,+}: {+ instances: Iterable<Instance>;+ props: Iterable<Prop>;+}) => {+ const sourcePropsByInstanceId = groupContentBlockSourceProps(props);+ const sources = new Map<Instance["id"], ContentBlockSource>();+ for (const instance of instances) {+ if (instance.component !== blockComponent) {+ continue;+ }+ const source = getContentBlockSource({+ blockInstanceId: instance.id,+ props: sourcePropsByInstanceId.get(instance.id) ?? [],+ });+ if (source !== undefined) {+ sources.set(instance.id, source);+ }+ }+ return sources;+};++export const isEqualContentBlockSource = (+ left: ContentBlockSource | undefined,+ right: ContentBlockSource | undefined+) => {+ if (left?.type !== right?.type) {+ return false;+ }+ if (left?.type === "asset" && right?.type === "asset") {+ return left.assetId === right.assetId;+ }+ return left?.type === "expression" && right?.type === "expression"+ ? left.value === right.value+ : left === undefined && right === undefined;+};++export const getStaticContentBlockSourceAssetId = (+ source: ContentBlockSource+) => {+ if (source.type === "asset") {+ return source.assetId;+ }+ const value = parseJsonExpression(source.value);+ return typeof value === "string" ? value : undefined;+};++export type WritableContentBlockDocumentBinding = Readonly<{+ type: "writable-content-block-document-binding";+ expression: DirectPathExpression;+ frontmatterPath: readonly [string, ...string[]];+}>;++const unsafeContentBlockDocumentPathSegments = new Set([+ "__proto__",+ "constructor",+ "prototype",+]);++export const isSafeContentBlockDocumentPath = (path: readonly string[]) =>+ path.every(+ (segment) => unsafeContentBlockDocumentPathSegments.has(segment) === false+ );++/**+ * Recognizes a direct path into a Content Block document's frontmatter.+ * Arbitrary expressions remain read-only even when they reference frontmatter.+ */+export const getWritableContentBlockDocumentBinding = ({+ binding,+ documentDataSourceId,+}: {+ binding: ExpressionBinding;+ documentDataSourceId: string;+}): WritableContentBlockDocumentBinding | undefined => {+ if (binding.mode !== "readwrite") {+ return;+ }+ const directPathExpression = parseDirectPathExpression(binding.value);+ if (directPathExpression === undefined) {+ return;+ }+ const path = directPathExpression.path;+ if (+ decodeDataSourceVariable(path[0]) !== documentDataSourceId ||+ path[1] !== "frontmatter" ||+ path.length < 3 ||+ isSafeContentBlockDocumentPath(path.slice(2)) === false+ ) {+ return;+ }+ return {+ type: "writable-content-block-document-binding",+ expression: directPathExpression,+ frontmatterPath: path.slice(2) as [string, ...string[]],+ };+};++export type WritableContentBlockDocumentBindings = Readonly<{+ children: ReadonlyArray<{+ instanceId: Instance["id"];+ childIndex: number;+ binding: ExpressionChild;+ target: WritableContentBlockDocumentBinding;+ }>;+ props: ReadonlyArray<{+ propId: Prop["id"];+ binding: Extract<Prop, { type: "expression" }>;+ target: WritableContentBlockDocumentBinding;+ }>;+}>;++export const findWritableContentBlockDocumentBindings = ({+ instances,+ props,+ compatibility,+}: {+ instances: Pick<Instances, "get" | "values">;+ props: Pick<Props, "values">;+ /** Migrates compatible bindings created before explicit modes and sources existed. */+ compatibility?: "legacy";+}): WritableContentBlockDocumentBindings => {+ const isLegacyMigration = compatibility === "legacy";+ const propsByInstanceId = new Map<Instance["id"], Prop[]>();+ for (const prop of props.values()) {+ const instanceProps = propsByInstanceId.get(prop.instanceId) ?? [];+ instanceProps.push(prop);+ propsByInstanceId.set(prop.instanceId, instanceProps);+ }+ const result: {+ children: Array<WritableContentBlockDocumentBindings["children"][number]>;+ props: Array<WritableContentBlockDocumentBindings["props"][number]>;+ } = { children: [], props: [] };+ for (const block of instances.values()) {+ if (+ block.component !== blockComponent ||+ (isLegacyMigration === false &&+ getContentBlockSource({+ blockInstanceId: block.id,+ props: propsByInstanceId.get(block.id) ?? [],+ }) === undefined)+ ) {+ continue;+ }+ const documentProp = propsByInstanceId+ .get(block.id)+ ?.find(+ (prop) =>+ prop.name === contentBlockDocumentProp && prop.type === "parameter"+ );+ if (documentProp?.type !== "parameter") {+ continue;+ }+ const documentDataSourceId = documentProp.value;+ const visiting = new Set<Instance["id"]>();+ const visit = (instanceId: Instance["id"]) => {+ const instance = instances.get(instanceId);+ if (+ instance === undefined ||+ visiting.has(instanceId) ||+ instance.component === blockTemplateComponent ||+ (instance.component === blockComponent && instance.id !== block.id)+ ) {+ return;+ }+ visiting.add(instanceId);+ for (const [childIndex, child] of instance.children.entries()) {+ if (child.type === "expression") {+ const binding =+ isLegacyMigration && child.mode === undefined+ ? { ...child, mode: "readwrite" as const }+ : child;+ const target = getWritableContentBlockDocumentBinding({+ binding,+ documentDataSourceId,+ });+ if (target !== undefined) {+ result.children.push({+ instanceId: instance.id,+ childIndex,+ binding: child,+ target,+ });+ }+ }+ if (child.type === "id") {+ visit(child.value);+ }+ }+ for (const prop of propsByInstanceId.get(instance.id) ?? []) {+ if (prop.type !== "expression") {+ continue;+ }+ const binding =+ isLegacyMigration && prop.mode === undefined+ ? { ...prop, mode: "readwrite" as const }+ : prop;+ const target = getWritableContentBlockDocumentBinding({+ binding,+ documentDataSourceId,+ });+ if (target !== undefined) {+ result.props.push({ propId: prop.id, binding: prop, target });+ }+ }+ visiting.delete(instanceId);+ };+ visit(block.id);+ }+ return result;+};++export const findContentBlockTemplateContainers = ({+ blockInstance,+ instances,+}: {+ blockInstance: Instance;+ instances: Pick<Instances, "get">;+}) => {+ if (blockInstance.component !== blockComponent) {+ return [];+ }+ return (blockInstance.children ?? []).flatMap((child) => {+ const instance =+ child.type === "id" ? instances.get(child.value) : undefined;+ return instance?.component === blockTemplateComponent ? [instance] : [];+ });+};++export const findContentBlockBodyContainers = ({+ blockInstance,+ instances,+}: {+ blockInstance: Instance;+ instances: Pick<Instances, "get">;+}) => {+ return findContentBlockBodyContainerPaths({+ blockInstance,+ instances,+ }).map((path) => path.at(-1)!);+};++/** Finds descendant paths from a Content Block child to each Body outlet. */+export const findContentBlockBodyContainerPaths = ({+ blockInstance,+ instances,+}: {+ blockInstance: Instance;+ instances: Pick<Instances, "get">;+}) => {+ if (blockInstance.component !== blockComponent) {+ return [];+ }+ const paths: Instance[][] = [];+ const visiting = new Set<Instance["id"]>();+ const visit = (instance: Instance, path: Instance[]) => {+ if (visiting.has(instance.id)) {+ return;+ }+ if (instance.component === blockBodyComponent) {+ paths.push([...path, instance]);+ return;+ }+ if (+ instance.component === blockTemplateComponent ||+ instance.component === blockComponent+ ) {+ return;+ }+ visiting.add(instance.id);+ for (const child of instance.children ?? []) {+ const childInstance =+ child.type === "id" ? instances.get(child.value) : undefined;+ if (childInstance !== undefined) {+ visit(childInstance, [...path, instance]);+ }+ }+ visiting.delete(instance.id);+ };+ for (const child of blockInstance.children ?? []) {+ const childInstance =+ child.type === "id" ? instances.get(child.value) : undefined;+ if (childInstance !== undefined) {+ visit(childInstance, []);+ }+ }+ return paths;+};++/**+ * Returns the container whose children represent document.body. Existing+ * Content Blocks without an explicit Body outlet keep using the block itself.+ */+export const getContentBlockBodyContainer = ({+ blockInstance,+ instances,+}: {+ blockInstance: Instance;+ instances: Pick<Instances, "get">;+}) => {+ const bodies = findContentBlockBodyContainers({ blockInstance, instances });+ if (bodies.length > 1) {+ return;+ }+ return bodies[0] ?? blockInstance;+};++export type ContentBlockSourceIntegrityIssue =+ | {+ type: "duplicateContentBlockSource";+ blockInstanceId: Instance["id"];+ propIds: Prop["id"][];+ }+ | {+ type: "invalidContentBlockSource";+ blockInstanceId: Instance["id"];+ propId: Prop["id"];+ propType: Prop["type"];+ }+ | {+ type: "missingContentBlockSourceAsset";+ blockInstanceId: Instance["id"];+ propId: Prop["id"];+ assetId: Asset["id"];+ }+ | {+ type: "incompatibleContentBlockSourceAsset";+ blockInstanceId: Instance["id"];+ propId: Prop["id"];+ assetId: Asset["id"];+ assetName: Asset["name"];+ };++export const formatContentBlockSourceIntegrityIssue = (+ issue: ContentBlockSourceIntegrityIssue+) => {+ if (issue.type === "duplicateContentBlockSource") {+ return `Content Block "${issue.blockInstanceId}" has multiple source props: ${issue.propIds.map((id) => `"${id}"`).join(", ")}.`;+ }+ if (issue.type === "invalidContentBlockSource") {+ return `Content Block source prop "${issue.propId}" must use an Asset or expression binding.`;+ }+ if (issue.type === "missingContentBlockSourceAsset") {+ return `Content Block source prop "${issue.propId}" references missing Asset "${issue.assetId}".`;+ }+ return `Content Block source prop "${issue.propId}" references Asset "${issue.assetId}" (${issue.assetName}), which is not an MDX file.`;+};++export const getContentBlockSourceIntegrityIssues = ({+ instances,+ props,+ assets,+}: {+ instances: Iterable<Instance>;+ props: Iterable<Prop>;+ assets?: Iterable<Asset>;+}): ContentBlockSourceIntegrityIssue[] => {+ const sourcePropsByInstanceId = groupContentBlockSourceProps(props);+ const assetsById =+ assets === undefined+ ? undefined+ : new Map(Array.from(assets, (asset) => [asset.id, asset]));+ const issues: ContentBlockSourceIntegrityIssue[] = [];+ for (const instance of instances) {+ if (instance.component !== blockComponent) {+ continue;+ }+ const sourceProps = sourcePropsByInstanceId.get(instance.id) ?? [];+ if (sourceProps.length > 1) {+ issues.push({+ type: "duplicateContentBlockSource",+ blockInstanceId: instance.id,+ propIds: sourceProps.map((prop) => prop.id),+ });+ continue;+ }+ const [prop] = sourceProps;+ if (prop === undefined) {+ continue;+ }+ const source = parseContentBlockSourceProp(prop);+ if (source === undefined) {+ issues.push({+ type: "invalidContentBlockSource",+ blockInstanceId: instance.id,+ propId: prop.id,+ propType: prop.type,+ });+ continue;+ }+ if (source.type !== "asset" || assetsById === undefined) {+ continue;+ }+ const asset = assetsById.get(source.assetId);+ if (asset === undefined) {+ issues.push({+ type: "missingContentBlockSourceAsset",+ blockInstanceId: instance.id,+ propId: prop.id,+ assetId: source.assetId,+ });+ continue;+ }+ if (isMdxFileAsset(asset) === false) {+ issues.push({+ type: "incompatibleContentBlockSourceAsset",+ blockInstanceId: instance.id,+ propId: prop.id,+ assetId: asset.id,+ assetName: asset.name,+ });+ }+ }+ return issues;+};++export const allocateUniqueContentBlockTemplateName = ({+ name,+ existingNames,+}: {+ name: string;+ existingNames: ReadonlySet<string>;+}) => {+ const normalizedName = name.trim();+ if (existingNames.has(normalizedName) === false) {+ return normalizedName;+ }++ const suffixMatch = /^(.*) (\d+)$/.exec(normalizedName);+ let baseName = normalizedName;+ let index = 2;+ if (suffixMatch !== null) {+ const suffix = Number(suffixMatch[2]);+ if (suffix >= 2 && Number.isSafeInteger(suffix + 1)) {+ baseName = suffixMatch[1];+ index = suffix + 1;+ }+ }+ let candidate = `${baseName} ${index}`;+ while (existingNames.has(candidate)) {+ if (Number.isSafeInteger(index + 1) === false) {+ baseName = candidate;+ index = 2;+ } else {+ index += 1;+ }+ candidate = `${baseName} ${index}`;+ }+ return candidate;+};diff --git a/packages/sdk/src/core-metas.ts b/packages/sdk/src/core-metas.tsindex 3159b8af88..e1fbfdd24c 100644--- a/packages/sdk/src/core-metas.ts+++ b/packages/sdk/src/core-metas.ts@@ -11,6 +11,7 @@ import type { WsComponentMeta } from "./schema/component-meta";import type { Instance } from "./schema/instances";import { tagProperty } from "./runtime";import { tags } from "./__generated__/tags";+import { contentBlockSourceProp } from "./schema/content-block";export const rootComponent = "ws:root";@@ -115,8 +116,19 @@ const descendantMeta: WsComponentMeta = {export const blockComponent = "ws:block";+export const blockBodyComponent = "ws:content-block-body";+export const blockTemplateComponent = "ws:block-template";+export const blockBodyMeta: WsComponentMeta = {+ category: "hidden",+ label: "Content Block Body",+ contentModel: {+ category: "none",+ children: ["instance"],+ },+};+export const blockTemplateMeta: WsComponentMeta = {icon: AddTemplateInstanceIcon,contentModel: {@@ -130,7 +142,21 @@ const blockMeta: WsComponentMeta = {icon: ContentBlockIcon,contentModel: {category: "instance",- children: [blockTemplateComponent, "instance"],+ children: [blockBodyComponent, blockTemplateComponent, "instance"],+ descendants: [blockBodyComponent],+ },+ initialProps: [contentBlockSourceProp],+ props: {+ [contentBlockSourceProp]: {+ type: "string",+ control: "file",+ label: "Source",+ description:+ "Create an .mdx file in Assets, then select or bind it here.",+ required: false,+ accept: ".mdx",+ contentMode: false,+ },},};@@ -140,6 +166,7 @@ export const coreMetas = {[collectionComponent]: collectionMeta,[descendantComponent]: descendantMeta,[blockComponent]: blockMeta,+ [blockBodyComponent]: blockBodyMeta,[blockTemplateComponent]: blockTemplateMeta,};@@ -151,9 +178,11 @@ export const isCoreComponent = (component: Instance["component"]) =>component === collectionComponent ||component === descendantComponent ||component === blockComponent ||+ component === blockBodyComponent ||component === blockTemplateComponent;export const isComponentDetachable = (component: Instance["component"]) =>component !== rootComponent &&+ component !== blockBodyComponent &&component !== blockTemplateComponent &&component !== descendantComponent;diff --git a/packages/sdk/src/core-templates.test.tsx b/packages/sdk/src/core-templates.test.tsxnew file mode 100644index 0000000000..d754cabd2a--- /dev/null+++ b/packages/sdk/src/core-templates.test.tsx@@ -0,0 +1,52 @@+import { expect, test } from "vitest";+import { renderTemplate, type TemplateMeta } from "@webstudio-is/template";+import { blockComponent } from "./core-metas";+import { coreTemplates } from "./core-templates";++const expectCodeTextDefaultsToStayImplicit = (+ template: TemplateMeta | undefined+) => {+ if (template === undefined) {+ throw new Error("Expected Code Text template");+ }+ const fragment = renderTemplate(template.template);+ const codeText = fragment.instances.find(+ ({ component }) => component === "CodeText"+ );+ expect(codeText?.children).toEqual([+ { type: "text", value: 'const status = "ready";' },+ ]);+ expect(+ fragment.props.filter(({ instanceId }) => instanceId === codeText?.id)+ ).toEqual([]);+};++test("keeps standalone Code Text defaults out of instance props", () => {+ expectCodeTextDefaultsToStayImplicit(+ (coreTemplates as Record<string, TemplateMeta>).code_text+ );+});++test("keeps Content Block Code Text defaults out of template props", () => {+ expectCodeTextDefaultsToStayImplicit(coreTemplates[blockComponent]);+});++test("keeps the Content Block Image template representable as Markdown", () => {+ const template = coreTemplates[blockComponent];+ if (template === undefined) {+ throw new Error("Expected Content Block template");+ }+ const fragment = renderTemplate(template.template);+ const image = fragment.instances.find(+ ({ component }) => component === "Image"+ );+ if (image === undefined) {+ throw new Error("Expected Image template");+ }++ expect(+ fragment.styleSourceSelections.filter(+ ({ instanceId }) => instanceId === image.id+ )+ ).toEqual([]);+});diff --git a/packages/sdk/src/core-templates.tsx b/packages/sdk/src/core-templates.tsxindex 4915325b74..0c113151ef 100644--- a/packages/sdk/src/core-templates.tsx+++ b/packages/sdk/src/core-templates.tsx@@ -19,6 +19,7 @@ import {descendantComponent,elementComponent,} from "./core-metas";+import { contentBlockDocumentProp } from "./schema/content-block";const elementMeta: TemplateMeta = {category: "general",@@ -69,11 +70,13 @@ const descendantMeta: TemplateMeta = {};const BlockTemplate = ws["block-template"];+const BlockBody = ws["content-block-body"];+const blockDocument = new Parameter(contentBlockDocumentProp);const blockMeta: TemplateMeta = {category: "general",template: (- <ws.block>+ <ws.block document={blockDocument}><BlockTemplate ws:label="Templates"><ws.element ws:label="Paragraph" ws:tag="p"></ws.element><ws.element ws:label="Heading 1" ws:tag="h1"></ws.element>@@ -89,51 +92,42 @@ const blockMeta: TemplateMeta = {<ws.element ws:label="List Item" ws:tag="li"></ws.element></ws.element><ws.element ws:label="Link" ws:tag="a"></ws.element>- <$.Image- ws:style={css`- margin-right: auto;- margin-left: auto;- width: 100%;- height: auto;- `}- />+ <$.Image /><ws.element ws:label="Separator" ws:tag="hr" /><ws.element ws:label="Blockquote" ws:tag="blockquote"></ws.element><$.HtmlEmbed />- <$.CodeText- code={'const status = "ready";'}- language="javascript"- theme="github-light"- />+ <$.CodeText>{'const status = "ready";'}</$.CodeText></BlockTemplate>- <ws.element ws:label="Paragraph" ws:tag="p">- The Content Block component designates regions on the page where- pre-styled instances can be inserted in{" "}- <ws.element- ws:label="Link"- ws:tag="a"- href="https://wstd.us/content-block"- >- Content mode- </ws.element>- .- </ws.element>- <ws.element ws:label="Unordered List" ws:tag="ul">- <ws.element ws:label="List Item" ws:tag="li">- In Content mode, you can edit content inside this Content Block and- add new instances predefined in templates. Content outside Content- Blocks is read-only.+ <BlockBody>+ <ws.element ws:label="Paragraph" ws:tag="p">+ The Content Block component designates regions on the page where+ pre-styled instances can be inserted in{" "}+ <ws.element+ ws:label="Link"+ ws:tag="a"+ href="https://wstd.us/content-block"+ >+ Content mode+ </ws.element>+ .</ws.element>- <ws.element ws:label="List Item" ws:tag="li">- To predefine instances for insertion in Content mode, switch to Design- mode and add them to the Templates container.- </ws.element>- <ws.element ws:label="List Item" ws:tag="li">- To insert predefined instances in Content mode, click the + button- while hovering over the Content Block on the canvas and choose an- instance from the list.+ <ws.element ws:label="Unordered List" ws:tag="ul">+ <ws.element ws:label="List Item" ws:tag="li">+ In Content mode, you can edit content inside this Content Block and+ add new instances predefined in templates. Content outside Content+ Blocks is read-only.+ </ws.element>+ <ws.element ws:label="List Item" ws:tag="li">+ To predefine instances for insertion in Content mode, switch to+ Design mode and add them to the Templates container.+ </ws.element>+ <ws.element ws:label="List Item" ws:tag="li">+ To insert predefined instances in Content mode, click the + button+ while hovering over the Content Block on the canvas and choose an+ instance from the list.+ </ws.element></ws.element>- </ws.element>+ </BlockBody></ws.block>),};@@ -189,13 +183,7 @@ const typography: Record<string, TemplateMeta> = {code_text: {category: "typography",- template: (- <$.CodeText- code={'const status = "ready";'}- language="javascript"- theme="github-light"- />- ),+ template: <$.CodeText>{'const status = "ready";'}</$.CodeText>,},thematic_break: {diff --git a/packages/sdk/src/id.test.ts b/packages/sdk/src/id.test.tsnew file mode 100644index 0000000000..eb39ef3a0d--- /dev/null+++ b/packages/sdk/src/id.test.ts@@ -0,0 +1,16 @@+import { describe, expect, test } from "vitest";+import { createId } from "./id";++describe("createId", () => {+ test("creates UUIDs by default without requiring a bound receiver", () => {+ const generate = createId;++ expect(generate()).toMatch(+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/+ );+ });++ test("creates compact NanoIDs when requested", () => {+ expect(createId("nano")).toMatch(/^[\w-]{21}$/);+ });+});diff --git a/packages/sdk/src/id.ts b/packages/sdk/src/id.tsnew file mode 100644index 0000000000..5ebe21ac15--- /dev/null+++ b/packages/sdk/src/id.ts@@ -0,0 +1,8 @@+import { nanoid } from "nanoid";++/**+ * Generates a UUID by default. Use `"nano"` for records in an existing+ * NanoID-based schema, such as Builder data and Assets.+ */+export const createId = (format?: "nano") =>+ format === "nano" ? nanoid() : crypto.randomUUID();diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.tsindex 5c40e2e7d7..0342cf14ac 100644--- a/packages/sdk/src/index.ts+++ b/packages/sdk/src/index.ts@@ -3,6 +3,7 @@ export * from "./schema/asset-resource";export * from "./schema/asset-folders";export * from "./schema/pages";export * from "./schema/instances";+export * from "./schema/expression";export * from "./schema/data-sources";export * from "./schema/resources";export * from "./schema/props";@@ -14,12 +15,15 @@ export * from "./schema/deployment";export * from "./schema/webstudio";export * from "./schema/prop-meta";export * from "./schema/component-meta";+export * from "./schema/content-block";export * from "./assets";export * from "./asset-folder-hierarchy";export * from "./asset-folder-normalization";export * from "./asset-resource-config";export * from "./core-metas";+export * from "./content-block";+export * from "./code-text";export * from "./instances-utils";export * from "./page-utils";export * from "./scope";@@ -34,6 +38,7 @@ export * from "./page-meta-generator";export * from "./url-pattern";export * from "./link-utils";export * from "./json-ld";+export * from "./id";export * from "./css";export * from "./__generated__/tags";export {diff --git a/packages/sdk/src/instances-utils.test.tsx b/packages/sdk/src/instances-utils.test.tsxindex 44f3e97051..0038598ee9 100644--- a/packages/sdk/src/instances-utils.test.tsx+++ b/packages/sdk/src/instances-utils.test.tsx@@ -1,12 +1,16 @@import { expect, test } from "vitest";import { $, renderData, ws } from "@webstudio-is/template";import {+ findChildReferenceIndex,findTreeInstanceIds,+ findTreeInstanceIdsExcludingBlockTemplates,findTreeInstanceIdsExcludingSubtrees,findTreeInstanceIdsExcludingSlotDescendants,+ findParentInstanceReference,getHtmlTagsFromProps,getHtmlTagFromInstance,getIndexesWithinAncestors,+ getInstanceName,parseComponentName,} from "./instances-utils";import type { WsComponentMeta } from "./schema/component-meta";@@ -59,6 +63,54 @@ test("find all tree instances excluding slot descendants", () => {).toEqual(new Set(["box1", "slot", "box2"]));});+test("finds rendered tree instances without traversing block templates", () => {+ const instances = new Map<Instance["id"], Instance>([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: "ws:block",+ children: [+ { type: "id", value: "templates" },+ { type: "id", value: "body" },+ ],+ },+ ],+ [+ "templates",+ {+ type: "instance",+ id: "templates",+ component: "ws:block-template",+ children: [{ type: "id", value: "template" }],+ },+ ],+ [+ "template",+ {+ type: "instance",+ id: "template",+ component: "ws:element",+ children: [],+ },+ ],+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "ws:element",+ children: [{ type: "id", value: "block" }],+ },+ ],+ ]);++ expect(+ findTreeInstanceIdsExcludingBlockTemplates(instances, "block")+ ).toEqual(new Set(["block", "body"]));+});+test("include not existing/virtual instance", () => {const { instances } = renderData(<$.Body ws:id="1"></$.Body>);expect(findTreeInstanceIds(instances, ":root")).toEqual(new Set([":root"]));@@ -67,11 +119,79 @@ test("include not existing/virtual instance", () => {).toEqual(new Set([":root"]));});+test("finds the direct parent instance reference", () => {+ const instances = new Map<Instance["id"], Instance>([+ [+ "parent",+ {+ type: "instance",+ id: "parent",+ component: "Box",+ children: [+ { type: "text", value: "before" },+ { type: "id", value: "child" },+ ],+ },+ ],+ [+ "child",+ {+ type: "instance",+ id: "child",+ component: "Box",+ children: [],+ },+ ],+ ]);++ expect(findParentInstanceReference(instances, "child")).toEqual({+ instance: instances.get("parent"),+ childIndex: 1,+ });+ expect(findParentInstanceReference(instances, "missing")).toBeUndefined();+});++test("finds child reference index", () => {+ expect(+ findChildReferenceIndex(+ [+ { type: "text", value: "before" },+ { type: "id", value: "child" },+ { type: "text", value: "after" },+ ],+ "child"+ )+ ).toBe(1);+ expect(+ findChildReferenceIndex([{ type: "text", value: "only" }], "child")+ ).toBe(-1);+});+test("extract short name and namespace from component name", () => {expect(parseComponentName("Box")).toEqual([undefined, "Box"]);expect(parseComponentName("radix:Box")).toEqual(["radix", "Box"]);});+test("gets the instance name from user label, element tag, or component", () => {+ expect(+ getInstanceName({+ instance: { component: "Box", label: "Hero Card" },+ metas: new Map([["Box", { label: "Box" }]]),+ })+ ).toBe("Hero Card");+ expect(+ getInstanceName({+ instance: { component: "ws:element", tag: "article" },+ metas: new Map([["ws:element", { label: "Element" }]]),+ })+ ).toBe("<article>");+ expect(+ getInstanceName({+ instance: { component: "custom:HeroCard" },+ })+ ).toBe("HeroCard");+});+test("get html tag from instance", () => {const metas = new Map<Instance["component"], WsComponentMeta>([["Box", { presetStyle: { section: [] } }],diff --git a/packages/sdk/src/instances-utils.ts b/packages/sdk/src/instances-utils.tsindex a18a1b507e..653de8b2ad 100644--- a/packages/sdk/src/instances-utils.ts+++ b/packages/sdk/src/instances-utils.ts@@ -1,15 +1,20 @@import type { WsComponentMeta } from "./schema/component-meta";import type { Instance, Instances } from "./schema/instances";import type { Props } from "./schema/props";-import { blockTemplateComponent } from "./core-metas";+import { blockTemplateComponent, elementComponent } from "./core-metas";export const ROOT_INSTANCE_ID = ":root";const traverseInstances = (instances: Instances,instanceId: Instance["id"],- callback: (instance: Instance) => false | void+ callback: (instance: Instance) => false | void,+ visited = new Set<Instance["id"]>()) => {+ if (visited.has(instanceId)) {+ return;+ }+ visited.add(instanceId);const instance = instances.get(instanceId);if (instance === undefined) {return;@@ -20,7 +25,7 @@ const traverseInstances = (}for (const child of instance.children) {if (child.type === "id") {- traverseInstances(instances, child.value, callback);+ traverseInstances(instances, child.value, callback, visited);}}};@@ -66,6 +71,40 @@ export const findTreeInstanceIdsExcludingSlotDescendants = (return ids;};+export const findTreeInstanceIdsExcludingBlockTemplates = (+ instances: Instances,+ rootInstanceId: Instance["id"]+) => {+ const ids = new Set<Instance["id"]>();+ traverseInstances(instances, rootInstanceId, (instance) => {+ if (instance.component === blockTemplateComponent) {+ return false;+ }+ ids.add(instance.id);+ });+ return ids;+};++export const findChildReferenceIndex = (+ children: Instance["children"],+ instanceId: Instance["id"]+) =>+ children.findIndex(+ (child) => child.type === "id" && child.value === instanceId+ );++export const findParentInstanceReference = (+ instances: Instances,+ instanceId: Instance["id"]+) => {+ for (const instance of instances.values()) {+ const childIndex = findChildReferenceIndex(instance.children, instanceId);+ if (childIndex !== -1) {+ return { instance, childIndex };+ }+ }+};+export const parseComponentName = (componentName: string) => {const parts = componentName.split(":");let namespace: undefined | string;@@ -78,6 +117,32 @@ export const parseComponentName = (componentName: string) => {return [namespace, name] as const;};+/**+ * Returns the instance name shown to users. The component or tag supplies the+ * default name; instance.label is the user-defined name created by renaming.+ */+export const getInstanceName = ({+ instance,+ metas,+ fallbackName,+}: {+ instance: Pick<Instance, "component" | "label" | "tag">;+ metas?: ReadonlyMap<Instance["component"], Pick<WsComponentMeta, "label">>;+ fallbackName?: string;+}) => {+ if (instance.label) {+ return instance.label;+ }+ if (instance.component === elementComponent && instance.tag) {+ return `<${instance.tag}>`;+ }+ return (+ metas?.get(instance.component)?.label ||+ fallbackName ||+ parseComponentName(instance.component)[1]+ );+};+export const getHtmlTagsFromProps = (props: Props) => {const tags = new Map<Instance["id"], string>();for (const prop of props.values()) {diff --git a/packages/sdk/src/resources-generator.test.tsx b/packages/sdk/src/resources-generator.test.tsxindex ee1e0950a4..b196cf6dde 100644--- a/packages/sdk/src/resources-generator.test.tsx+++ b/packages/sdk/src/resources-generator.test.tsx@@ -7,6 +7,7 @@ import {} from "@webstudio-is/template";import type { Page } from "./schema/pages";import { createScope } from "./scope";+import { encodeDataSourceVariable } from "./expression";import {generateResources,replaceFormActionsWithResources,@@ -44,7 +45,7 @@ test("generate resources loader", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const resourceName: ResourceRequest = {name: "resourceName",url: "https://my-json.com",@@ -59,14 +60,111 @@ test("generate resources loader", () => {const _data = new Map<string, ResourceRequest>([["resourceName", resourceName],])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);});+test("selects only Resources used by the resolved dynamic MDX candidate", () => {+ const generated = generateResources({+ scope: createScope(),+ page: { rootInstanceId: "body" } as Page,+ dataSources: toMap([+ {+ id: "selectedAsset",+ scopeInstanceId: "body",+ type: "variable",+ name: "Selected Asset",+ value: { type: "string", value: "article" },+ },+ {+ id: "articleVariable",+ scopeInstanceId: "article",+ type: "resource",+ name: "Article API",+ resourceId: "articleResource",+ },+ {+ id: "otherVariable",+ scopeInstanceId: "other",+ type: "resource",+ name: "Other API",+ resourceId: "otherResource",+ },+ ]),+ resources: toMap([+ {+ id: "articleResource",+ name: "Article API",+ url: '"https://example.com/article"',+ method: "get",+ headers: [],+ },+ {+ id: "otherResource",+ name: "Other API",+ url: '"https://example.com/other"',+ method: "get",+ headers: [],+ },+ ]),+ props: new Map(),+ contentBlockResourceSelections: [+ {+ sourceExpression: encodeDataSourceVariable("selectedAsset"),+ candidates: [+ { assetId: "article", resourceIds: ["articleResource"] },+ { assetId: "other", resourceIds: ["otherResource"] },+ ],+ },+ ],+ });++ expect(generated).toContain('if (SelectedAsset === "article")');+ expect(generated).toContain('_contentData.set("ArticleAPI", ArticleAPI)');+ expect(generated).toContain('if (SelectedAsset === "other")');+ expect(generated).toContain('_contentData.set("OtherAPI", OtherAPI)');+});++test("does not add dynamic selection inputs to ordinary Resources", () => {+ const generated = generateResources({+ scope: createScope(),+ page: { rootInstanceId: "body" } as Page,+ dataSources: toMap([+ {+ id: "sourceVariable",+ scopeInstanceId: "body",+ type: "resource",+ name: "Source",+ resourceId: "sourceResource",+ },+ ]),+ resources: toMap([+ {+ id: "sourceResource",+ name: "Source",+ url: '"https://example.com/source"',+ method: "get",+ headers: [],+ },+ {+ id: "dependentResource",+ name: "Dependent",+ url: `${encodeDataSourceVariable("sourceVariable")}.url`,+ method: "get",+ headers: [],+ },+ ]),+ props: new Map(),+ });++ expect(generated).not.toContain(" = _props.resources");+});+test("generates a configured Assets request on the standard endpoint", () => {const generated = generateResources({scope: createScope(),@@ -140,7 +238,7 @@ test("generate variable and use in resources loader", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {let AccessToken = "my-token"const resourceName: ResourceRequest = {name: "resourceName",@@ -156,9 +254,10 @@ test("generate variable and use in resources loader", () => {const _data = new Map<string, ResourceRequest>([["resourceName", resourceName],])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);@@ -202,7 +301,7 @@ test("generate page system variable and use in resources loader", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const system = _props.systemconst resourceName: ResourceRequest = {name: "resourceName",@@ -218,9 +317,10 @@ test("generate page system variable and use in resources loader", () => {const _data = new Map<string, ResourceRequest>([["resourceName", resourceName],])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);@@ -246,7 +346,7 @@ test("generate global system variable and use in resources loader", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const system = _props.systemconst MyResource: ResourceRequest = {name: "My Resource",@@ -263,9 +363,10 @@ test("generate global system variable and use in resources loader", () => {const _data = new Map<string, ResourceRequest>([["MyResource", MyResource],])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);@@ -282,12 +383,13 @@ test("generate empty resources loader", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);@@ -333,7 +435,7 @@ test("generate resource loader with search params", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {let term = "my-term"const resourceName: ResourceRequest = {name: "resourceName",@@ -348,9 +450,10 @@ test("generate resource loader with search params", () => {const _data = new Map<string, ResourceRequest>([["resourceName", resourceName],])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);@@ -375,12 +478,13 @@ test("prevent generating unused variables", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);@@ -407,12 +511,13 @@ test("prevent generating unused system variable", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);@@ -456,7 +561,7 @@ test("generate action resource without loading a stale data source", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const resourceName: ResourceRequest = {name: "resourceName",url: "https://my-url.com",@@ -468,10 +573,11 @@ test("generate action resource without loading a stale data source", () => {}const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([["resourceName", resourceName],])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);@@ -496,12 +602,13 @@ test("skip missing resource referenced by data source", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);@@ -526,12 +633,13 @@ test("skip missing resource referenced by action prop", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);diff --git a/packages/sdk/src/resources-generator.ts b/packages/sdk/src/resources-generator.tsindex 4ff40c149f..64a724b0ea 100644--- a/packages/sdk/src/resources-generator.ts+++ b/packages/sdk/src/resources-generator.ts@@ -12,19 +12,32 @@ export const generateResources = ({dataSources,props,resources,+ contentBlockResourceSelections = [],}: {scope: Scope;page: Page;dataSources: DataSources;props: Props;resources: Resources;+ contentBlockResourceSelections?: readonly {+ sourceExpression: string;+ candidates: readonly {+ assetId: string;+ resourceIds: readonly string[];+ }[];+ }[];}) => {const usedDataSources: DataSources = new Map();- const generatedResourceIds = new Set<string>();+ const contentSelectionDataSourceIds = new Set<string>();+ const generatedResourceIds = new Set(resources.keys());+ const selectedResourceIds = new Set(+ contentBlockResourceSelections.flatMap(({ candidates }) =>+ candidates.flatMap(({ resourceIds }) => resourceIds)+ )+ );let generatedRequests = "";for (const resource of resources.values()) {- generatedResourceIds.add(resource.id);let generatedRequest = "";// call resource by bound variable nameconst resourceName = scope.getName(resource.id, resource.name);@@ -77,6 +90,38 @@ export const generateResources = ({generatedRequests += generatedRequest;}+ const generatedContentSelections = contentBlockResourceSelections.map(+ ({ sourceExpression, candidates }) => {+ const selectionDataSources: DataSources = new Map();+ const source = generateExpression({+ expression: sourceExpression,+ dataSources,+ usedDataSources: selectionDataSources,+ scope,+ });+ if (candidates.some(({ resourceIds }) => resourceIds.length > 0)) {+ for (const dataSource of selectionDataSources.values()) {+ if (+ (dataSource.type === "parameter" &&+ dataSource.id !== page.systemDataSourceId &&+ dataSource.id !== SYSTEM_VARIABLE_ID) ||+ (dataSource.type === "resource" &&+ selectedResourceIds.has(dataSource.resourceId))+ ) {+ throw new Error(+ "Dynamic Content Block Resources require a source available after base Resources load"+ );+ }+ }+ }+ for (const dataSource of selectionDataSources.values()) {+ contentSelectionDataSourceIds.add(dataSource.id);+ usedDataSources.set(dataSource.id, dataSource);+ }+ return { source, candidates };+ }+ );+let generatedVariables = "";for (const dataSource of usedDataSources.values()) {if (dataSource.type === "variable") {@@ -95,11 +140,22 @@ export const generateResources = ({generatedVariables += ` const ${name} = _props.system\n`;}}+ if (+ dataSource.type === "resource" &&+ contentSelectionDataSourceIds.has(dataSource.id)+ ) {+ const name = scope.getName(dataSource.id, dataSource.name);+ const resourceName = scope.getName(+ dataSource.resourceId,+ dataSource.name+ );+ generatedVariables += ` const ${name} = _props.resources?.[${JSON.stringify(resourceName)}]\n`;+ }}let generated = "";generated += `import type { System, ResourceRequest } from "@webstudio-is/sdk";\n`;- generated += `export const getResources = (_props: { system: System }) => {\n`;+ generated += `export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {\n`;generated += generatedVariables;generated += generatedRequests;@@ -115,6 +171,7 @@ export const generateResources = ({if (dataSource.type === "resource" &&generatedResourceIds.has(dataSource.resourceId) &&+ selectedResourceIds.has(dataSource.resourceId) === false &&actionResourceIds.has(dataSource.resourceId) === false) {const name = scope.getName(dataSource.resourceId, dataSource.name);@@ -123,6 +180,28 @@ export const generateResources = ({}generated += ` ])\n`;+ generated += ` const _contentData = new Map<string, ResourceRequest>()\n`;+ if (contentBlockResourceSelections.length > 0) {+ for (const { source, candidates } of generatedContentSelections) {+ for (const { assetId, resourceIds } of candidates) {+ generated += ` if (${source} === ${JSON.stringify(assetId)}) {\n`;+ for (const dataSource of dataSources.values()) {+ if (+ dataSource.type !== "resource" ||+ resourceIds.includes(dataSource.resourceId) === false ||+ generatedResourceIds.has(dataSource.resourceId) === false ||+ actionResourceIds.has(dataSource.resourceId)+ ) {+ continue;+ }+ const name = scope.getName(dataSource.resourceId, dataSource.name);+ generated += ` _contentData.set(${JSON.stringify(name)}, ${name})\n`;+ }+ generated += ` }\n`;+ }+ }+ }+generated += ` const _action = new Map<string, ResourceRequest>([\n`;for (const prop of props.values()) {if (prop.type === "resource" && generatedResourceIds.has(prop.value)) {@@ -132,7 +211,7 @@ export const generateResources = ({}generated += ` ])\n`;- generated += ` return { data: _data, action: _action }\n`;+ generated += ` return { data: _data, action: _action, contentData: _contentData }\n`;generated += `}\n`;return generated;diff --git a/packages/sdk/src/schema.ts b/packages/sdk/src/schema.tsindex 2a921b57c7..3b04ba524c 100644--- a/packages/sdk/src/schema.ts+++ b/packages/sdk/src/schema.ts@@ -5,9 +5,11 @@ export * from "./schema/assets";export * from "./schema/asset-resource";export * from "./schema/asset-folders";export * from "./schema/breakpoints";+export * from "./schema/content-block";export * from "./schema/data-sources";export * from "./schema/deployment";export * from "./schema/instances";+export * from "./schema/expression";export * from "./schema/pages";export * from "./schema/props";export * from "./schema/resources";diff --git a/packages/sdk/src/schema/component-meta.test.ts b/packages/sdk/src/schema/component-meta.test.tsindex 95acb4857f..60257096dd 100644--- a/packages/sdk/src/schema/component-meta.test.ts+++ b/packages/sdk/src/schema/component-meta.test.ts@@ -31,3 +31,22 @@ test("allows only safe resource fields in generated component props", () => {expect(wsComponentMeta.safeParse(createMeta("method")).success).toBe(true);expect(wsComponentMeta.safeParse(createMeta("url")).success).toBe(false);});++test("accepts component text content editor metadata", () => {+ const textContent = {+ control: "textContent" as const,+ type: "string" as const,+ required: false,+ editor: {+ control: "code" as const,+ languageProp: "language",+ },+ };+ expect(+ wsComponentMeta.parse({+ textContent: {+ ...textContent,+ },+ }).textContent+ ).toEqual(textContent);+});diff --git a/packages/sdk/src/schema/component-meta.ts b/packages/sdk/src/schema/component-meta.tsindex 596f6f44a7..80c65e9b41 100644--- a/packages/sdk/src/schema/component-meta.ts+++ b/packages/sdk/src/schema/component-meta.ts@@ -2,7 +2,7 @@ import { z } from "zod";import type { HtmlTags } from "html-tags";import type { Simplify } from "type-fest";import { styleValue, type CssProperty } from "@webstudio-is/css-engine";-import { propMeta } from "./prop-meta";+import { propMeta, textContentPropMeta } from "./prop-meta";export const presetStyleDecl = z.object({// State selector, e.g. :hover@@ -109,6 +109,8 @@ export const wsComponentMeta = z.object({// properties and html attributes that will be always visible in properties panelinitialProps: z.array(z.string()).optional(),props: z.record(z.string(), propMeta).optional(),+ // Editing metadata for authored text children; this is not a persisted prop.+ textContent: textContentPropMeta.optional(),});export type WsComponentMeta = Omit<diff --git a/packages/sdk/src/schema/content-block.test.ts b/packages/sdk/src/schema/content-block.test.tsnew file mode 100644index 0000000000..4a6aee2604--- /dev/null+++ b/packages/sdk/src/schema/content-block.test.ts@@ -0,0 +1,133 @@+import { describe, expect, test } from "vitest";+import {+ contentBlockDiagnostic,+ contentBlockExternalContentIdentity,+ contentBlockSource,+ contentBlockSourcePropSchema,+} from "./content-block";++describe("content block source", () => {+ test("accepts direct assets and dynamic expressions", () => {+ expect(+ contentBlockSource.parse({ type: "asset", assetId: "asset-id" })+ ).toEqual({ type: "asset", assetId: "asset-id" });+ expect(+ contentBlockSource.parse({ type: "expression", value: "post.body" })+ ).toEqual({ type: "expression", value: "post.body" });+ });++ test("rejects empty and mixed source identities", () => {+ expect(+ contentBlockSource.safeParse({ type: "asset", assetId: "" }).success+ ).toBe(false);+ expect(+ contentBlockSource.safeParse({+ type: "asset",+ assetId: "asset-id",+ value: "post.body",+ }).success+ ).toBe(false);+ });++ test("parses persisted source props without accepting other prop types", () => {+ expect(+ contentBlockSourcePropSchema.parse({+ id: "source-prop",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "asset-id",+ })+ ).toMatchObject({ type: "asset", value: "asset-id" });+ expect(+ contentBlockSourcePropSchema.parse({+ id: "source-prop",+ instanceId: "block",+ name: "src",+ type: "expression",+ value: "post.body",+ })+ ).toMatchObject({ type: "expression", value: "post.body" });+ expect(+ contentBlockSourcePropSchema.safeParse({+ id: "source-prop",+ instanceId: "block",+ name: "src",+ type: "string",+ value: "asset-id",+ }).success+ ).toBe(false);+ });+});++test("validates resolved external content identity", () => {+ expect(+ contentBlockExternalContentIdentity.parse({+ blockInstanceId: "block",+ assetId: "asset",+ revision: "revision-1",+ contentRef: "assets/post.mdx",+ format: "mdx",+ renderScope: "route:/posts/hello",+ })+ ).toEqual({+ blockInstanceId: "block",+ assetId: "asset",+ revision: "revision-1",+ contentRef: "assets/post.mdx",+ format: "mdx",+ renderScope: "route:/posts/hello",+ });+ expect(+ contentBlockExternalContentIdentity.safeParse({+ blockInstanceId: "block",+ assetId: "asset",+ revision: "revision-1",+ contentRef: "assets/post.mdx",+ format: "md",+ renderScope: "route:/posts/hello",+ }).success+ ).toBe(false);+});++describe("content block diagnostics", () => {+ test("accepts typed template diagnostics with source locations", () => {+ expect(+ contentBlockDiagnostic.parse({+ code: "unresolved-template",+ severity: "warning",+ blockInstanceId: "block",+ assetId: "asset",+ templateName: "Hero Card",+ sourceRange: {+ start: { line: 3, column: 1, offset: 20 },+ end: { line: 5, column: 14, offset: 80 },+ },+ })+ ).toMatchObject({+ code: "unresolved-template",+ templateName: "Hero Card",+ });+ });++ test("rejects mismatched severities and payloads", () => {+ expect(+ contentBlockDiagnostic.safeParse({+ code: "unresolved-template",+ severity: "error",+ blockInstanceId: "block",+ templateName: "Hero Card",+ }).success+ ).toBe(false);+ expect(+ contentBlockDiagnostic.safeParse({+ code: "ignored-template-prop",+ severity: "warning",+ blockInstanceId: "block",+ templateName: "Hero Card",+ propName: "tone",+ reason: "unsupported",+ }).success+ ).toBe(false);+ });+});diff --git a/packages/sdk/src/schema/content-block.ts b/packages/sdk/src/schema/content-block.tsnew file mode 100644index 0000000000..049351ebc9--- /dev/null+++ b/packages/sdk/src/schema/content-block.ts@@ -0,0 +1,91 @@+import { z } from "zod";+import { prop } from "./props";++export const contentBlockSourceProp = "src";+export const contentBlockDocumentProp = "document";++export const contentBlockSource = z.discriminatedUnion("type", [+ z.strictObject({+ type: z.literal("asset"),+ assetId: z.string().min(1),+ }),+ z.strictObject({+ type: z.literal("expression"),+ value: z.string().min(1),+ }),+]);++export type ContentBlockSource = z.infer<typeof contentBlockSource>;++export const contentBlockSourcePropSchema = prop.refine(+ (value) =>+ value.name === contentBlockSourceProp &&+ (value.type === "asset" || value.type === "expression") &&+ value.value.length > 0+);++export const contentBlockExternalContentIdentity = z.strictObject({+ blockInstanceId: z.string().min(1),+ assetId: z.string().min(1),+ revision: z.string().min(1),+ contentRef: z.string().min(1),+ format: z.literal("mdx"),+ renderScope: z.string().min(1),+});++export type ContentBlockExternalContentIdentity = z.infer<+ typeof contentBlockExternalContentIdentity+>;++const sourcePoint = z.strictObject({+ line: z.number().int().positive(),+ column: z.number().int().positive(),+ offset: z.number().int().nonnegative().optional(),+});++const contentBlockSourceRange = z.strictObject({+ start: sourcePoint,+ end: sourcePoint,+});++export type ContentBlockSourceRange = z.infer<typeof contentBlockSourceRange>;++const diagnosticContext = {+ blockInstanceId: z.string().min(1),+ assetId: z.string().min(1).optional(),+ contentRef: z.string().min(1).optional(),+ renderScope: z.string().min(1).optional(),+ sourceRange: contentBlockSourceRange.optional(),+};++export const contentBlockDiagnostic = z.discriminatedUnion("code", [+ z.strictObject({+ ...diagnosticContext,+ code: z.literal("invalid-mdx"),+ severity: z.literal("error"),+ message: z.string().min(1),+ }),+ z.strictObject({+ ...diagnosticContext,+ code: z.literal("unsafe-mdx"),+ severity: z.literal("warning"),+ nodeType: z.string().min(1),+ reason: z.string().min(1),+ }),+ z.strictObject({+ ...diagnosticContext,+ code: z.literal("unresolved-template"),+ severity: z.literal("warning"),+ templateName: z.string().min(1),+ }),+ z.strictObject({+ ...diagnosticContext,+ code: z.literal("ignored-template-prop"),+ severity: z.literal("warning"),+ templateName: z.string().min(1),+ propName: z.string().min(1),+ reason: z.enum(["unknown", "incompatible", "design-only", "stale"]),+ }),+]);++export type ContentBlockDiagnostic = z.infer<typeof contentBlockDiagnostic>;diff --git a/packages/sdk/src/schema/expression.test.ts b/packages/sdk/src/schema/expression.test.tsnew file mode 100644index 0000000000..1c78dac287--- /dev/null+++ b/packages/sdk/src/schema/expression.test.ts@@ -0,0 +1,59 @@+import { describe, expect, test } from "vitest";+import { expressionChild } from "./instances";+import { prop } from "./props";++const expressionProp = {+ id: "prop",+ instanceId: "instance",+ name: "title",+ type: "expression" as const,+};++describe("expression binding mode", () => {+ test("keeps ordinary expressions read-only by default", () => {+ expect(+ prop.parse({ ...expressionProp, value: "document.title + '!'" })+ ).toEqual({ ...expressionProp, value: "document.title + '!'" });+ expect(+ expressionChild.parse({ type: "expression", value: "value" })+ ).toEqual({ type: "expression", value: "value" });+ expect(+ expressionChild.parse({+ type: "expression",+ value: "document.frontmatter.title",+ mode: "read",+ })+ ).toMatchObject({ mode: "read" });+ });++ test("accepts readwrite mode only for direct static paths", () => {+ expect(+ prop.parse({+ ...expressionProp,+ value: "document.frontmatter.title",+ mode: "readwrite",+ })+ ).toMatchObject({ mode: "readwrite" });+ expect(+ expressionChild.parse({+ type: "expression",+ value: 'document.frontmatter["title"]',+ mode: "readwrite",+ })+ ).toMatchObject({ mode: "readwrite" });+ expect(+ prop.safeParse({+ ...expressionProp,+ value: "document.frontmatter.title + '!'",+ mode: "readwrite",+ }).success+ ).toBe(false);+ expect(+ expressionChild.safeParse({+ type: "expression",+ value: "document?.frontmatter.title",+ mode: "readwrite",+ }).success+ ).toBe(false);+ });+});diff --git a/packages/sdk/src/schema/expression.ts b/packages/sdk/src/schema/expression.tsnew file mode 100644index 0000000000..b92d50e0b8--- /dev/null+++ b/packages/sdk/src/schema/expression.ts@@ -0,0 +1,38 @@+import { parseDirectPathExpression } from "@webstudio-is/expression";+import { z } from "zod";++export const expressionBindingMode = z+ .enum(["read", "readwrite"])+ .describe(+ 'Use "readwrite" only for a direct path into a source that supports writes; use "read" for every other expression.'+ );++export type ExpressionBindingMode = z.infer<typeof expressionBindingMode>;++export const expressionBindingShape = {+ type: z.literal("expression"),+ value: z.string(),+ // Optional only for persisted bindings created before modes existed. New+ // bindings must always choose an explicit mode.+ mode: expressionBindingMode.optional(),+};++export type ExpressionBinding = z.infer<typeof expressionBinding>;++export const getExpressionBindingError = ({+ value,+ mode,+}: Pick<ExpressionBinding, "value" | "mode">) => {+ if (mode === "readwrite" && parseDirectPathExpression(value) === undefined) {+ return "Read-write expressions must be a direct static path";+ }+};++export const expressionBinding = z+ .object(expressionBindingShape)+ .superRefine((binding, context) => {+ const error = getExpressionBindingError(binding);+ if (error !== undefined) {+ context.addIssue({ code: "custom", path: ["value"], message: error });+ }+ });diff --git a/packages/sdk/src/schema/instances.ts b/packages/sdk/src/schema/instances.tsindex a9418db586..a6ade64cb0 100644--- a/packages/sdk/src/schema/instances.ts+++ b/packages/sdk/src/schema/instances.ts@@ -1,4 +1,5 @@import { z } from "zod";+import { expressionBinding } from "./expression";export const textChildValue = z.string();@@ -21,6 +22,8 @@ export const instanceTag = zexport const instanceAttributes = z.object({component: instanceComponent,tag: instanceTag.optional(),+ // The component or tag provides the default instance name. Renaming stores+ // the user-defined name in label without changing the component identity.label: z.string().optional(),});@@ -41,10 +44,7 @@ export const idChild = z.object({});export type IdChild = z.infer<typeof idChild>;-export const expressionChild = z.object({- type: z.literal("expression"),- value: z.string(),-});+export const expressionChild = expressionBinding;export type ExpressionChild = z.infer<typeof expressionChild>;export const instanceChild = z.union([idChild, textChild, expressionChild]);diff --git a/packages/sdk/src/schema/prop-meta.ts b/packages/sdk/src/schema/prop-meta.tsindex a64369f8ad..fde2b9b5f0 100644--- a/packages/sdk/src/schema/prop-meta.ts+++ b/packages/sdk/src/schema/prop-meta.ts@@ -197,11 +197,17 @@ const action = z.object({defaultValue: z.undefined().optional(),});-const textContent = z.object({+export const textContentPropMeta = z.object({...common,control: z.literal("textContent"),type: z.literal("string"),defaultValue: z.string().optional(),+ editor: z+ .object({+ control: z.literal("code"),+ languageProp: z.string().optional(),+ })+ .optional(),});const animationAction = z.object({@@ -234,7 +240,7 @@ export const propMeta = z.union([json,date,action,- textContent,+ textContentPropMeta,animationAction,]);diff --git a/packages/sdk/src/schema/props.ts b/packages/sdk/src/schema/props.tsindex 648bf14c93..5061d8014b 100644--- a/packages/sdk/src/schema/props.ts+++ b/packages/sdk/src/schema/props.ts@@ -1,5 +1,9 @@import { z } from "zod";import { animationAction } from "./animation-schema";+import {+ expressionBindingShape,+ getExpressionBindingError,+} from "./expression";const propId = z.string();@@ -64,12 +68,17 @@ export const prop = z.union([// resource idvalue: z.string(),}),- z.object({- ...baseProp,- type: z.literal("expression"),- // expression code- value: z.string(),- }),+ z+ .object({+ ...baseProp,+ ...expressionBindingShape,+ })+ .superRefine((binding, context) => {+ const error = getExpressionBindingError(binding);+ if (error !== undefined) {+ context.addIssue({ code: "custom", path: ["value"], message: error });+ }+ }),z.object({...baseProp,type: z.literal("action"),diff --git a/packages/template/package.json b/packages/template/package.jsonindex 50687f1f93..a807fd7c1d 100644--- a/packages/template/package.json+++ b/packages/template/package.json@@ -16,6 +16,7 @@"test": "vitest run"},"dependencies": {+ "@webstudio-is/content-engine": "workspace:*","@webstudio-is/css-data": "workspace:*","@webstudio-is/css-engine": "workspace:*","@webstudio-is/react-sdk": "workspace:*",diff --git a/packages/template/src/jsx.test.tsx b/packages/template/src/jsx.test.tsxindex ac734d8e31..b0693473f2 100644--- a/packages/template/src/jsx.test.tsx+++ b/packages/template/src/jsx.test.tsx@@ -775,6 +775,7 @@ test("render variable used in prop expression", () => {name: "data-count",type: "expression",value: "$ws$dataSource$0",+ mode: "read",},]);expect(dataSources).toEqual([@@ -798,7 +799,9 @@ test("render variable used in child expression", () => {type: "instance",id: "body",component: "Body",- children: [{ type: "expression", value: "$ws$dataSource$0" }],+ children: [+ { type: "expression", value: "$ws$dataSource$0", mode: "read" },+ ],},]);expect(dataSources).toEqual([@@ -828,6 +831,7 @@ test("compose expression from multiple variables", () => {name: "data-count",type: "expression",value: "Count is $ws$dataSource$0 + $ws$dataSource$1",+ mode: "read",},]);expect(dataSources).toEqual([@@ -862,6 +866,7 @@ test("preserve same variable on multiple instances", () => {name: "data-count",type: "expression",value: "$ws$dataSource$0",+ mode: "read",},{id: "box:data-count",@@ -869,6 +874,7 @@ test("preserve same variable on multiple instances", () => {name: "data-count",type: "expression",value: "$ws$dataSource$0",+ mode: "read",},]);expect(dataSources).toEqual([@@ -898,6 +904,7 @@ test("render variable inside of action", () => {name: "data-count",type: "expression",value: "$ws$dataSource$0",+ mode: "read",},{id: "body:onInc",@@ -947,6 +954,7 @@ test("render parameter bound to prop expression", () => {name: "data-value",type: "expression",value: "$ws$dataSource$0",+ mode: "read",},]);expect(dataSources).toEqual([@@ -1116,6 +1124,29 @@ test("render ws:tag property", () => {expect(props).toEqual([]);});+test("converts JSX attributes when ws:tag enables HTML attributes", () => {+ const { props } = renderTemplate(+ <$.Box ws:tag="label" tabIndex={0} readOnly={true}></$.Box>+ );++ expect(props).toEqual([+ {+ id: "0:tabindex",+ instanceId: "0",+ name: "tabindex",+ type: "number",+ value: 0,+ },+ {+ id: "0:readonly",+ instanceId: "0",+ name: "readonly",+ type: "boolean",+ value: true,+ },+ ]);+});+test("preserves empty ws:tag for schema validation", () => {const { instances } = renderTemplate(<$.Box ws:tag=""></$.Box>);expect(instances[0]?.tag).toEqual("");diff --git a/packages/template/src/jsx.ts b/packages/template/src/jsx.tsindex 234b4b7f73..0a9abfc7bf 100644--- a/packages/template/src/jsx.ts+++ b/packages/template/src/jsx.ts@@ -20,6 +20,7 @@ import type {WsComponentMeta,} from "@webstudio-is/sdk";import { showAttribute } from "@webstudio-is/react-sdk";+import { mapAttributeNames } from "@webstudio-is/content-engine/jsx-attributes";import { parseTemplateCss, type TemplateStyleDecl } from "./css";import { camelCaseProperty, parseMediaQuery } from "@webstudio-is/css-data";@@ -545,19 +546,27 @@ export const renderTemplate = ();}const instanceId = element.props?.["ws:id"] ?? getIdByKey(element);+ const componentMeta = options.componentMetas?.get(component);+ const componentPropNames = new Set(Object.keys(componentMeta?.props ?? {}));+ const acceptsHtmlAttributes =+ component === "ws:element" ||+ typeof element.props?.["ws:tag"] === "string" ||+ Object.keys(componentMeta?.presetStyle ?? {}).length > 0;let tag: string | undefined;- for (const entry of Object.entries({ ...element.props })) {- const [_name, value] = entry;- let [name] = entry;- if (name === "ws:id" || name === "ws:label" || name === "children") {- continue;- }- if (name === "className") {- name = "class";- }- if (name === "htmlFor") {- name = "for";- }+ const mappedProps = mapAttributeNames({+ attributes: Object.entries({ ...element.props }).flatMap(+ ([name, value]) =>+ name === "ws:id" || name === "ws:label" || name === "children"+ ? []+ : [{ name, value }]+ ),+ direction: "jsx-to-instance",+ componentPropNames,+ acceptsHtmlAttributes,+ });+ for (const mappedProp of mappedProps) {+ let { name } = mappedProp;+ const { value } = mappedProp;if (name === "ws:tag") {tag = value as string;continue;@@ -606,6 +615,7 @@ export const renderTemplate = (...base,type: "expression",value: compileExpression(instanceId, value),+ mode: "read",});continue;}@@ -636,7 +646,7 @@ export const renderTemplate = (props.push({ ...base, type: "page", value: value.value });continue;}- const propMeta = options.componentMetas?.get(component)?.props?.[name];+ const propMeta = componentMeta?.props?.[name];if (propMeta?.type === "animationAction") {const result = animationAction.safeParse(value);if (result.success === false) {@@ -693,7 +703,7 @@ export const renderTemplate = (}if (child instanceof Expression) {const expression = compileExpression(instanceId, child);- return { type: "expression", value: expression };+ return { type: "expression", value: expression, mode: "read" };}return convertElementToInstance(child);}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 9dd9d360a4..001272a562 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1544,15 +1544,45 @@ importers:canonicalize:specifier: 3.0.0version: 3.0.0+ hast-util-to-mdast:+ specifier: 9.0.0+ version: 9.0.0lru-cache:specifier: 10.4.3version: 10.4.3+ mdast-util-gfm:+ specifier: 2.0.2+ version: 2.0.2+ mdast-util-mdx-expression:+ specifier: 1.3.2+ version: 1.3.2+ mdast-util-mdx-jsx:+ specifier: 2.1.4+ version: 2.1.4+ mdast-util-to-hast:+ specifier: 12.3.0+ version: 12.3.0+ mdast-util-to-markdown:+ specifier: 1.5.0+ version: 1.5.0micromark:specifier: 4.0.2version: 4.0.2+ micromark-extension-mdxjs:+ specifier: 3.0.0+ version: 3.0.0micromark-util-decode-string:specifier: 2.0.1version: 2.0.1+ remark-frontmatter:+ specifier: 4.0.1+ version: 4.0.1+ remark-gfm:+ specifier: 3.0.1+ version: 3.0.1+ remark-mdx:+ specifier: 2.3.0+ version: 2.3.0remark-parse:specifier: 10.0.2version: 10.0.2@@ -1926,6 +1956,9 @@ importers:packages/generate-arg-types:dependencies:+ '@webstudio-is/content-engine':+ specifier: workspace:*+ version: link:../content-engine'@webstudio-is/html-data':specifier: workspace:*version: link:../html-data@@ -2437,6 +2470,9 @@ importers:packages/react-sdk:dependencies:+ '@webstudio-is/content-engine':+ specifier: workspace:*+ version: link:../content-engine'@webstudio-is/css-engine':specifier: workspace:*version: link:../css-engine@@ -2528,6 +2564,9 @@ importers:json-schema-typed:specifier: ^8.0.2version: 8.0.2+ nanoid:+ specifier: ^5.1.5+ version: 5.1.5reserved-identifiers:specifier: ^1.0.0version: 1.0.0@@ -2993,6 +3032,9 @@ importers:packages/template:dependencies:+ '@webstudio-is/content-engine':+ specifier: workspace:*+ version: link:../content-engine'@webstudio-is/css-data':specifier: workspace:*version: link:../css-data@@ -6744,6 +6786,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-ejlPM315qwLpaQlQDTjPdsUFSc6ZsP4AN6AlWnogPjQ7CVi7PYF3YVz+CY3jE2pwYf7E/7HlDAN0rV2GxTG0HQ==}+ '@types/[email protected]':+ resolution: {integrity: sha512-ArMouDUTJEz1SQRpFsT2rIw7DeqICFv5aaVzLSIYMYQSLcwcGOfT3VyglQs/p7K3F7fT4zxr0NWxYZIdifD6dA==}+'@types/[email protected]':resolution: {integrity: sha512-wN+8bYxIpJf+5oZdrdtaX04qUuWHcKxcDEgRS9Qm9ZClSHjzEn13SxUC+5eRM+4yXIeTYk8mTzLAWGF64847ew==}@@ -6780,6 +6825,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-gFnFp/JMzLHCwRf7tQHrNnfhN4eYBVYYI897CGX4MY1tzY9l2aLkVyx2IlKZ/SAqDbB3I1AOZW5gTMGGsqWliA==}+ '@types/[email protected]':+ resolution: {integrity: sha512-SuT16Q1K51EAVPz1K29DJ/sXjhSQ0zjvsypYJ6tlwVsRV9jwW5Adq2ch8Dq8kDBCkYnELS7N7VNCSB5nC56t/g==}+'@types/[email protected]':resolution: {integrity: sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w==}@@ -8160,6 +8208,9 @@ packages:resolution: {integrity: sha512-xbgqcrkIVbIG+lI/gzbvd9SGTJL4zqJKBFttUl5pP27KhAjtMKbX/mQXJ7qgyXpMgVy/zvpm0xoQQaGL8OloOw==}+ resolution: {integrity: sha512-m5KgiH85xAhhW8Wta0vShLcUvOsh3LLPI2YVwcbio1l7E09NTLL1EyMZFM1OyWowoH0skScNbhOPl4kcBgzTww==}+resolution: {integrity: sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w==}@@ -8584,21 +8635,60 @@ packages:resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-QUdSOP1/o+/TxXtpPFXR2mUg2P+ySrmlX7QjwHZCXqMFyYk7YmcGSvqRW+4XgXAoHifdE1t2PwFaQK33TqVjSw==}++ resolution: {integrity: sha512-Nz7FfPBuljzsN3tCQ4kCBKqdNhQE2l0Tn+X1ubgKBPRoiDIu1mL08Cfw4k7q71+Duyaw7DXDN+VTAp4Vh3oCOw==}++ resolution: {integrity: sha512-X2+RwZIMTMKpXUzlotatPzWj8bspCymtXH3cfG3iQKV+wPF53Vgaqxi/eLqGck0wKq1kS9nvoB1wchbCPEL8sg==}++ resolution: {integrity: sha512-S58hCexyKdD31vMsErvgLfflW6vYWo/ixRLPJTtkOvLld24vyI8vmYmkgLA5LG3la2ME7nm7dLGdm48gfLRBfw==}++ resolution: {integrity: sha512-O1bKah6mhgEq2WtVMk+Ta5K7pPMqsBBlmzysLdcwKVrqzZQ0CHqUPiIVspNhAG1rvxpvJjtGee17XfauZYKqVA==}++ resolution: {integrity: sha512-jdlwBjEexy1oGz0aJ2f4GKMaVKkA9jwjr4MjAAI22E5fM/TXVZHuS5OpONtdeIkRKqAaryQ2E9xNQxijoThSZA==}++ resolution: {integrity: sha512-yGkCfPkkfCyiLfK6KEl/orMDr/zgCnq/NaO9HfULx6/Zga5fso5eqQA5Ov/JZVqACygvw9shRYWgXNcG2ilo7w==}++ resolution: {integrity: sha512-RujVQfVsOrxzPOPSzZFiwofMArbQke6DJjnFfceiEbFh7S05CbPt0cYN+A5YeD3pso0JQk6O1aHBnx9+Pm2uqg==}+resolution: {integrity: sha512-kiGD9WIW3gRKK8Gao3n1f+ahUeTMeJUJILnIT2QNrPigDNdH7rJxzhEbh81UajGeAdAHFecT1a+fLVOCTq9B4Q==}+ resolution: {integrity: sha512-4tpQTUOr9BMjtYyNlt0P50mH7xj0Ks2xpo8M943Vykljf99HW6EzulIoJP1N3eKOSScEHzyzi9dm7/cn0RfGwA==}+resolution: {integrity: sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==}resolution: {integrity: sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==}+ resolution: {integrity: sha512-7Pl4mWA3JCSHx0s3A1CgJaFirkISDUJsu+DeJd/cHUAlVDgs1sITzg9HZAidSf9LUE7kl8Hf2ZJr1HZTfhV/Yw==}++ resolution: {integrity: sha512-YNRgAJkH2Jky5ySkIqFXTQiaqcAtJyVE+D5lkN6CdtOqrnkLfGYYrEcKuHOJZlp+MwjSwuD3fZuawI+sic/RBw==}++ resolution: {integrity: sha512-tcllLfp23dJJ+ju5wCCZHVpzsQQ43+moJbqVX3jNWPB7z/KFC4FyZD6R7y94cHL6MQ33YtMZL8Z0aIXXI4XFTw==}+resolution: {integrity: sha512-nAxA0v8+vXSBDt3AnRUNjyRIQ0rD+ntpbAp4LnPkumc5M9yUbSMa4XDU9Q6etY4f1Wp4bNgvc1yjiZtsTTrSng==}resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==}+ resolution: {integrity: sha512-TtYPq24IldU8iKoJQqvZOuhi5CyCQRAbvDOX0x1eW6rsHSxa/1i2CCiptNTotGHJ3VoHRGmqiv6/D3q113ikkw==}+resolution: {integrity: sha512-Wv7UgbOswBXYMWQCrzuf5j6Yxs3Dz4Gm3hdrrMV88mD1bbL4khX5aojJvMRLOe30bj6eRo5TYRdcDwTEWl4Wbg==}@@ -8627,6 +8717,9 @@ packages:resolution: {integrity: sha512-KM1SNmemQtsD+OTInZTYKZNbyPzzVrjMR2Iz1Np+Y+bcxUh0dgKF4NtylJVkGZRLe3NklHizJ5k1Vd3ug1uTPA==}engines: {node: '>=18.20'}+ resolution: {integrity: sha512-0quDb7s97CfemeJAnW9wC0hw78MtW7NU3hqtCD75g2vFlDLt36llsYD7uB7SUzojLMP24N5IatXf7ylGXiGG9A==}+resolution: {integrity: sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==}@@ -9254,6 +9347,9 @@ packages:resolution: {integrity: sha512-WWC0ZuMzCyDHYCasEGs4IPvLyTGftYwh6wIEOULOF0HXcqZlhwRzrK0w2VUlxWA98xnvb/jszw4ZSkJ6ADpM6Q==}engines: {node: '>=0.10.0'}+ resolution: {integrity: sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==}+resolution: {integrity: sha512-ocnPZQLNpvbedwTy9kNrQEsknEfgvcLMvOtz3sFeWApDq1MXH1TqkCIx58xlpESsfwQOnuBO9beyQuNGzVvuhQ==}@@ -9270,6 +9366,9 @@ packages:resolution: {integrity: sha512-I3fNFt+DHmpWCYAT7quoM6lHf9wuqtI+oCOfvILnoicNIqjh5E3dEJWiXuYME2gNe8vl1iMQwyUHa7bgFmak6Q==}+ resolution: {integrity: sha512-MTtdFRz/eMDHXzeK6W3dO7mXUlF82Gom4y0oOgvHhh/HXZAGvIQDUvQ0SuUx+j2tv44b8xTHOm8K/9OoRFnXKw==}+resolution: {integrity: sha512-4xTO/M8c82qBcnQc1tgpNtubGUW/Y1tBQ1B0i5CtSoelOLKFYlElIr3bvgREYYO5iRqbMY1YuqZng0GVOI8Qww==}@@ -9282,6 +9381,24 @@ packages:resolution: {integrity: sha512-LRqI9+wdgC25P0URIJY9vwocIzCcksduHQ9OF2joxQoyTNVduwLAFUzjoopuRJbJAReaKrNQKAZKL3uCMugWJA==}+ resolution: {integrity: sha512-My8KJ57FYEy2W2LyNom4n3E7hKTuQk/0SES0u16tjA9Z3oFkF4RrC/hPAPgjlSpezsOvI8ObcXcElo92wn5IGA==}++ resolution: {integrity: sha512-56D19KOGbE00uKVj3sgIykpwKL179QsVFwx/DCW0u/0+URsryacI4MAdNJl0dh+u2PSsD9FtxPFbHCzJ78qJFQ==}++ resolution: {integrity: sha512-DAPhYzTYrRcXdMjUtUjKvW9z/FNAMTdU0ORyMcbmkwYNbKocDpdk+PX1L1dQgOID/+vVs1uBQ7ElrBQfZ0cuiQ==}++ resolution: {integrity: sha512-jjcpmNnQvrmN5Vx7y7lEc2iIOEytYv7rTvu+MeyAsSHTASGCCRA79Igg2uKssgOs1i1po8s3plW0sTu1wkkLGg==}++ resolution: {integrity: sha512-PFTA1gzfp1B1UaiJVyhJZA1rm0+Tzn690frc/L8vNX1Jop4STZgOE6bxUhnzdVSB+vm2GU1tIsuQcA9bxTQpMQ==}++ resolution: {integrity: sha512-qvZ608nBppZ4icQlhQQIAdc6S3Ffj9RGmzwUKUWuEICFnd1LVkN3EktF7ZHAgfcEdvZB5owU9tQgt99e2TlLjg==}+resolution: {integrity: sha512-xIPmR5ReJDu/DHH1OoIT1HkuybIfRGYRywC+gJtI7qHjCJp/M9jrmBEJW22O8lskDWm562BX2W8TiAwRTb0rKA==}@@ -9390,42 +9507,78 @@ packages:resolution: {integrity: sha512-C4AkuM3dA58cgZha7zVnuVxBhDsbttIMiytjgsM2XbHAB2faRVaHRle40558FBN+DJcrLNCoqG5mlrpdU4cRtg==}+ resolution: {integrity: sha512-z3wJSLrDf8kRDOh2qBtoTRD53vJ+CWIyo7uyZuxf/JAbNJjiHsOpG1y5wxk8drtv3ETAHutCu6N3thkOOgueWg==}+resolution: {integrity: sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==}+ resolution: {integrity: sha512-Yxn7z7SxgyGWRNa4wzf8AhYYWNrwl5q1Z8ii+CSTTIqVkmGZF1CElX2JI8g5yGoM3GAman9/PVCUFUSJ0kB/8Q==}+resolution: {integrity: sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==}+ resolution: {integrity: sha512-sX0FawVE1o3abGk3vRjOH50L5TTLr3b5XMqnP9YDRb34M0v5OoZhG+OHFz1OffZ9dlwgpTBKaT4XW/AsUVnSDw==}+resolution: {integrity: sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==}+ resolution: {integrity: sha512-3ZORTHtcSnMQEKtAOsBQ9/oHp9096pI/UvdPtN7ehKvrmZZ2+bbWhi0ln+I9drmwXMt5boocn6OlwQzNXeVeqw==}+resolution: {integrity: sha512-t2OU/dXXioARrC6yWfJ4hqB7rct14e8f7m0cbI5hUmDyyIlwv5vEtooptH8INkbLzOatzKuVbQmAYcbWoyz6Dg==}+ resolution: {integrity: sha512-5XWB9GbAUSHTn8VPU8/1DBXMuKYT5uOgEjJb8gN3mW0PNW5OPHpSdojoqf+iq1xo7vWzw/P8bAHY0n6ijpXF7g==}+resolution: {integrity: sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==}+ resolution: {integrity: sha512-RMFXl2uQ0pNQy6Lun2YBYT9g9INXtWJULgbt01D/x8/6yJ2qpKyzdZD3pi6UIkzF++Da49xAelVKUeUMqd5eIQ==}+resolution: {integrity: sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==}+ resolution: {integrity: sha512-vb9OoHqrhCmbRidQv/2+Bc6pkP0FrtlhurxZofvOEy5o8RtuuvTq+RQ1Vw5ZDNrVraQZu3HixESqbG+0iKk/MQ==}+resolution: {integrity: sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==}resolution: {integrity: sha512-zZpeQtc5wfWKdzDsHRBY003H2Smg+PUi2REhqgIhdzAa5xonhP03FcXxqFSerFiNUr5AWmHpaNPQTBVOS4lrXw==}+ resolution: {integrity: sha512-dD/ADLJ1AeMvSAKBwO22zG22N4ybhe7kFIZ3LsDI0GlsNr2A3KYxb0LdC1u5rj4Nw+CHKY0RVdnHX8vj8ejm4Q==}+resolution: {integrity: sha512-gPH+9ZdmDflbu19Xkb8+gheqEDqkSpdCEubQyxuz/Hn8DOXiXvrXeikOoBA71+e8Pfi0/UYmU3wW3H58kr7akA==}+ resolution: {integrity: sha512-e5+q1DjMh62LZAJOnDraSSbDMvGJ8x3cbjygy2qFEi7HCeUT4BDKCvMozPozcD6WmOt6sVvYDNBKhFSz3kjOVQ==}+resolution: {integrity: sha512-7MSuj2S7xjOQXAjjkbjBsHkMtb+mDGVW6uI2dBL9snOBCbZmoNgDAeZ0nSn9j3T42UE/g2xVNMn18PJxZvkBEA==}+ resolution: {integrity: sha512-EpAiszsB3blw4Rpba7xTOUptcFeBFi+6PY8VnJ2hhimH+vCQDirWgsMpz7w1XcZE7LVrSAUGb9VJpG9ghlYvYQ==}+resolution: {integrity: sha512-xNRBw4aoURcyz/S69B19WnZAkWJMxHMT5hE36GtDAyhoyn/8TuAeqjFJQlwk+MKQsUD7b3l7kFX+vlfVWgcX1w==}+ resolution: {integrity: sha512-DJFl4ZqkErRpq/dAPyeWp15tGrcrrJho1hKK5uBS70BCtfrIFg81sqcTVu3Ta+KD1Tk5vAtBNElWxtAa+m8K9A==}+resolution: {integrity: sha512-7YA7hF6i5eKOfFUzZ+0z6avRG52GpWR8DL+kN47y3f2KhxbBZMhmxe7auOeaTBrW2DenbbZTf1ea9tA2hDpC2Q==}+ resolution: {integrity: sha512-A873fJfhnJ2siZyUrJ31l34Uqwy4xIFmvPY1oj+Ean5PHcPBYzEsvqvWGaWcfEIr11O5Dlw3p2y0tZWpKHDejQ==}+resolution: {integrity: sha512-XaNDROBgx9SgSChd69pjiGKbV+nfHGDPVYFs5dOoDd7ZnMAE+Cuu91BCpsY8RT2NP9vo/B8pds2VQNCLiu0zhg==}@@ -9441,6 +9594,9 @@ packages:resolution: {integrity: sha512-jGIWzSmNfdnkJq05c7b0+Wv0Kfz3NJ3N4cBjnbO4zjXIlxJr+f8lk+5ZmwFvqdAbUy2q6B5rCY//g0QAAaXDWA==}+ resolution: {integrity: sha512-kQnEtA3vzucU2BkrIa8/VaSAsP+EJ3CKOvhMuJgOEGg9KDC6OAY6nSnNDVRiVNRqj7Y4SlSzcStaH/5jge8JdQ==}+resolution: {integrity: sha512-cRzEj7c0OL4Mw2v6nwzttyOZe8XY/Z8G0rzmWQZTBi/jjwyw/U4uqKtUORXQrR5bAZZnbTI/feRV/R7hc4jQYQ==}@@ -9504,6 +9660,9 @@ packages:resolution: {integrity: sha512-ij4X7Wuc4fED6UoLWkmo0xJQhsktfNh1J0m8g4PbIMPlx+ek/4YdW5mvbye8z/aZvAPUoxgXHrwVlXAPKMRp1w==}+ resolution: {integrity: sha512-jmsiEIiZ1n7X1Rr5k8wVExBQCg5jy4UXVADItHmNk1zkwEVhBuIUKRu3fqv+hs4nxLISi2DQGlqIOGiFxgbfHg==}+resolution: {integrity: sha512-VTQzcuQgFUD7yYztuQFKXT49KghjtETQ+Wv/zUjGSGBioZnkA4P1XXZPT1FHeJA6RwRXSF47yvJ1tsJdoxwO+Q==}@@ -10010,6 +10169,9 @@ packages:resolution: {integrity: sha512-/2qh0lav6CmI15FzA3i/2Bzk2zCgQhGMkvhOhKNcBVQ1ldgpbfiNTVslmooUmWJcADi1f1kIeynbDRVzNlfR6Q==}+ resolution: {integrity: sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==}+resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==}@@ -10521,9 +10683,15 @@ packages:resolution: {integrity: sha512-RSYAtP31mvYLkAHrOlh25pCNQ5hWnT106VukGaaFfuJrZFkGRX5GhUAdPqpSDXxOhA2c4akmRuplv1mRqnBn6Q==}engines: {node: '>=8'}+ resolution: {integrity: sha512-PPp4lWJiBPlePI/dv1BeYktbwkfgXkrK59MUa+tYbMPgleod+4DvFK2PLU0O0O60/xuhHfiR9GUIUlXTU8sRIQ==}+resolution: {integrity: sha512-38fJrB0KnmD3E33a5jZC/5+gGAC2WKNiPw1/fdXJvijBlhA7RCsvJklrYJakS0HedninvaCYW8lQGf9C918GfA==}+ resolution: {integrity: sha512-lEFDoi2PICJyNrACFOfDD3JlLkuSbOa5Wd8EPt06HUdptv8Gn0bxYTdbU/XXQ3swAPkEaGxxPN9cbnMHvVu1Ig==}+resolution: {integrity: sha512-7teX9DW4tI2WZkXS4DBxneYSY7NHiXl4AKdWDO9LXVweULlCT8OPWsOjLEnMIXViN1j+QcY8mfbq3k0EK6x3uA==}engines: {node: '>=12.2.0'}@@ -11117,6 +11285,9 @@ packages:resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==}+ resolution: {integrity: sha512-5UR5Biq4VlVOtzqkm2AZlgvSlDJtME46uV0br0gENbwN4l5+mMKT4b9gJKqWtuL2zAIqajGJGuvbCbcAJUZqBg==}+resolution: {integrity: sha512-AqTiAOLcj85xS7vQ8QkAV41hPDIJ71XJB4RCUrzo/1GM2CQwhkJGaf9Hgr7BOugMRpgGUrqRg/DrBDl4H40+8g==}@@ -11255,6 +11426,9 @@ packages:resolution: {integrity: sha512-WrcA6AyEfqDX5bWige/4NQfPZMtASNVxdmWR76WESYQVAACSgWcR6e9i0mofqqBxYFtL4oAxPIptY73/0YE1DQ==}engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}+ resolution: {integrity: sha512-QO/PuPMm2ERxC6vFXEPtmAutOopy5PknD+Oq64gGwxKtk4xwo9Z97t9Av1obPmGU0IyTa6EKYUfTrK2QJS3Ozw==}+resolution: {integrity: sha512-qF72kLmPxAw0oN2fwpWIqbXAVyEqUzDHMsbtPvOudIlUzXYFIeQIuxXQCRCFh22B7cixvU0MG7m3MW8FTq/S+A==}@@ -11267,6 +11441,9 @@ packages:resolution: {integrity: sha512-poZa0eXpS+/XpoQwGwl79UUdea4ol2ZuCYguVaJS4qzIOMDzbqz8a3erUCOmubSZkaOuGamb3tX790iwOIROww==}+ resolution: {integrity: sha512-KaFVRjoqLyF6YXCbVLNad/eS4+OfPQQn2yOd7zF/h5T/CSL2v8NpN6a5TPvtbXthAGw5nG+PuTtq+DdIZr+cRQ==}+resolution: {integrity: sha512-kUBE91efOWfIVBo8xzh/uZQ7p9ffYRtUbMRZBNFYwf0RK8koUMx6dGUfwylLOKmaT2cs4wSW96QoYUSXAyEtpg==}@@ -11490,6 +11667,9 @@ packages:resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}engines: {node: '>= 0.8'}+ resolution: {integrity: sha512-YF23YMyASIIJXpktBa4vIGLJ5Gs88UB/XePgqPmTa7cDA+JeO3yclbpheQYCHjVHBn/yePzrXuygIL+xbvRYHw==}+resolution: {integrity: sha512-0yaU+rj2gKAyEk12ffdSbBfjnnj+b1zqTBv3OQCTn8yEB02bsPizwdBPrLJjHnK+cU9EMMcUnNv938XcZIkmdA==}@@ -11614,6 +11794,9 @@ packages:resolution: {integrity: sha512-HYLeVCdJ0+lBYV2FvNZmv3HJ2Nt0QYXqZojk3d9FJOLkwnuhzM9tmamh8d7HPM8QqjKH8DeHkFTx+CFlWpZZDA==}+ resolution: {integrity: sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==}+resolution: {integrity: sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==}engines: {node: '>= 8'}@@ -16003,6 +16186,8 @@ snapshots:'@types/qs': 6.15.1'@types/serve-static': 1.15.10+ '@types/[email protected]': {}+'@types/[email protected]':dependencies:'@types/node': 22.13.10@@ -16041,6 +16226,8 @@ snapshots:dependencies:'@types/node': 22.13.10+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]': {}@@ -17494,6 +17681,11 @@ snapshots:'@types/estree-jsx': 1.0.0'@types/unist': 2.0.6+ dependencies:+ '@types/estree-jsx': 1.0.0+ '@types/unist': 3.0.3+@@ -18040,6 +18232,59 @@ snapshots:function-bind: 1.1.2optional: true+ dependencies:+ hast-util-is-element: 2.1.3++ dependencies:+ '@types/hast': 2.3.4+ '@types/unist': 2.0.6+ hastscript: 7.2.0+ property-information: 6.2.0+ vfile: 5.3.6+ vfile-location: 4.1.0+ web-namespaces: 2.0.1++ [email protected]: {}++ dependencies:+ '@types/hast': 2.3.4+ hast-util-has-property: 2.0.1+ hast-util-is-element: 2.1.3++ dependencies:+ '@types/hast': 2.3.4+ '@types/unist': 2.0.6++ dependencies:+ '@types/hast': 2.3.4++ dependencies:+ '@types/hast': 2.3.4+ hast-util-embedded: 2.0.1+ hast-util-has-property: 2.0.1+ hast-util-is-body-ok-link: 2.0.0+ hast-util-is-element: 2.1.3++ dependencies:+ '@types/hast': 2.3.4+ '@types/parse5': 6.0.3+ hast-util-from-parse5: 7.1.2+ hast-util-to-parse5: 7.1.0+ html-void-elements: 2.0.1+ parse5: 6.0.1+ unist-util-position: 4.0.4+ unist-util-visit: 4.1.2+ vfile: 5.3.6+ web-namespaces: 2.0.1+ zwitch: 2.0.4+dependencies:'@types/estree': 1.0.7@@ -18060,6 +18305,20 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ '@types/hast': 2.3.4+ '@types/unist': 2.0.6+ ccount: 2.0.1+ comma-separated-tokens: 2.0.3+ hast-util-raw: 7.2.3+ hast-util-whitespace: 2.0.1+ html-void-elements: 2.0.1+ property-information: 6.2.0+ space-separated-tokens: 2.0.2+ stringify-entities: 4.0.3+ zwitch: 2.0.4+dependencies:'@types/hast': 3.0.5@@ -18094,12 +18353,54 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ '@types/extend': 3.0.4+ '@types/hast': 2.3.4+ '@types/mdast': 3.0.15+ '@types/unist': 2.0.6+ extend: 3.0.2+ hast-util-phrasing: 2.0.2+ hast-util-to-html: 8.0.4+ hast-util-to-text: 3.1.2+ hast-util-whitespace: 2.0.1+ mdast-util-phrasing: 3.0.1+ mdast-util-to-string: 3.2.0+ rehype-minify-whitespace: 5.0.1+ trim-trailing-lines: 2.1.0+ unist-util-position: 4.0.4+ unist-util-visit: 4.1.2++ dependencies:+ '@types/hast': 2.3.4+ comma-separated-tokens: 2.0.3+ property-information: 6.2.0+ space-separated-tokens: 2.0.2+ web-namespaces: 2.0.1+ zwitch: 2.0.4++ dependencies:+ '@types/hast': 2.3.4+ '@types/unist': 2.0.6+ hast-util-is-element: 2.1.3+ unist-util-find-after: 4.0.1+dependencies:'@types/hast': 3.0.5+ dependencies:+ '@types/hast': 2.3.4+ comma-separated-tokens: 2.0.3+ hast-util-parse-selector: 3.1.1+ property-information: 6.2.0+ space-separated-tokens: 2.0.2+dependencies:'@preact/signals-core': 1.14.0@@ -18124,6 +18425,8 @@ snapshots:+ [email protected]: {}+@@ -18734,6 +19037,8 @@ snapshots:+ [email protected]: {}+@@ -18763,6 +19068,13 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ '@types/mdast': 3.0.15+ escape-string-regexp: 5.0.0+ unist-util-is: 5.2.0+ unist-util-visit-parents: 5.1.3+dependencies:'@types/mdast': 3.0.15@@ -18814,6 +19126,50 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ '@types/mdast': 3.0.15+ ccount: 2.0.1+ mdast-util-find-and-replace: 2.2.2+ micromark-util-character: 1.2.0++ dependencies:+ '@types/mdast': 3.0.15+ mdast-util-to-markdown: 1.5.0+ micromark-util-normalize-identifier: 1.1.0++ dependencies:+ '@types/mdast': 3.0.15+ mdast-util-to-markdown: 1.5.0++ dependencies:+ '@types/mdast': 3.0.15+ markdown-table: 3.0.4+ mdast-util-from-markdown: 1.3.1+ mdast-util-to-markdown: 1.5.0+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/mdast': 3.0.15+ mdast-util-to-markdown: 1.5.0++ dependencies:+ mdast-util-from-markdown: 1.3.1+ mdast-util-gfm-autolink-literal: 1.0.3+ mdast-util-gfm-footnote: 1.0.2+ mdast-util-gfm-strikethrough: 1.0.3+ mdast-util-gfm-table: 1.0.7+ mdast-util-gfm-task-list-item: 1.0.2+ mdast-util-to-markdown: 1.5.0+ transitivePeerDependencies:+ - supports-color+dependencies:'@types/estree-jsx': 1.0.0@@ -19060,6 +19416,13 @@ snapshots:micromark-util-symbol: 2.0.1micromark-util-types: 2.0.2+ dependencies:+ micromark-util-character: 1.2.0+ micromark-util-sanitize-uri: 1.2.0+ micromark-util-symbol: 1.1.0+ micromark-util-types: 1.1.0+dependencies:micromark-util-character: 2.1.1@@ -19067,6 +19430,17 @@ snapshots:micromark-util-symbol: 2.0.1micromark-util-types: 2.0.2+ dependencies:+ micromark-core-commonmark: 1.1.0+ micromark-factory-space: 1.1.0+ micromark-util-character: 1.2.0+ micromark-util-normalize-identifier: 1.1.0+ micromark-util-sanitize-uri: 1.2.0+ micromark-util-symbol: 1.1.0+ micromark-util-types: 1.1.0+ uvu: 0.5.6+dependencies:devlop: 1.1.0@@ -19078,6 +19452,15 @@ snapshots:micromark-util-symbol: 2.0.1micromark-util-types: 2.0.2+ dependencies:+ micromark-util-chunked: 1.1.0+ micromark-util-classify-character: 1.1.0+ micromark-util-resolve-all: 1.1.0+ micromark-util-symbol: 1.1.0+ micromark-util-types: 1.1.0+ uvu: 0.5.6+dependencies:devlop: 1.1.0@@ -19087,6 +19470,14 @@ snapshots:micromark-util-symbol: 2.0.1micromark-util-types: 2.0.2+ dependencies:+ micromark-factory-space: 1.1.0+ micromark-util-character: 1.2.0+ micromark-util-symbol: 1.1.0+ micromark-util-types: 1.1.0+ uvu: 0.5.6+dependencies:devlop: 1.1.0@@ -19095,10 +19486,22 @@ snapshots:micromark-util-symbol: 2.0.1micromark-util-types: 2.0.2+ dependencies:+ micromark-util-types: 1.1.0+dependencies:micromark-util-types: 2.0.2+ dependencies:+ micromark-factory-space: 1.1.0+ micromark-util-character: 1.2.0+ micromark-util-symbol: 1.1.0+ micromark-util-types: 1.1.0+ uvu: 0.5.6+dependencies:devlop: 1.1.0@@ -19107,6 +19510,17 @@ snapshots:micromark-util-symbol: 2.0.1micromark-util-types: 2.0.2+ dependencies:+ micromark-extension-gfm-autolink-literal: 1.0.5+ micromark-extension-gfm-footnote: 1.1.2+ micromark-extension-gfm-strikethrough: 1.0.7+ micromark-extension-gfm-table: 1.0.7+ micromark-extension-gfm-tagfilter: 1.0.2+ micromark-extension-gfm-task-list-item: 1.0.5+ micromark-util-combine-extensions: 1.1.0+ micromark-util-types: 1.1.0+dependencies:micromark-extension-gfm-autolink-literal: 2.1.0@@ -19129,6 +19543,17 @@ snapshots:micromark-util-types: 1.1.0uvu: 0.5.6+ dependencies:+ '@types/estree': 1.0.7+ devlop: 1.1.0+ micromark-factory-mdx-expression: 2.0.3+ micromark-factory-space: 2.0.1+ micromark-util-character: 2.1.1+ micromark-util-events-to-acorn: 2.0.3+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.2+dependencies:'@types/acorn': 4.0.6@@ -19142,10 +19567,27 @@ snapshots:uvu: 0.5.6vfile-message: 3.1.3+ dependencies:+ '@types/estree': 1.0.7+ devlop: 1.1.0+ estree-util-is-identifier-name: 3.0.0+ micromark-factory-mdx-expression: 2.0.3+ micromark-factory-space: 2.0.1+ micromark-util-character: 2.1.1+ micromark-util-events-to-acorn: 2.0.3+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.2+ vfile-message: 4.0.3+dependencies:micromark-util-types: 1.1.0+ dependencies:+ micromark-util-types: 2.0.2+dependencies:'@types/estree': 1.0.7@@ -19158,6 +19600,18 @@ snapshots:uvu: 0.5.6vfile-message: 3.1.3+ dependencies:+ '@types/estree': 1.0.7+ devlop: 1.1.0+ micromark-core-commonmark: 2.0.3+ micromark-util-character: 2.1.1+ micromark-util-events-to-acorn: 2.0.3+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.2+ unist-util-position-from-estree: 2.0.0+ vfile-message: 4.0.3+dependencies:acorn: 8.17.0@@ -19169,6 +19623,17 @@ snapshots:micromark-util-combine-extensions: 1.1.0micromark-util-types: 1.1.0+ dependencies:+ acorn: 8.17.0+ acorn-jsx: 5.3.2([email protected])+ micromark-extension-mdx-expression: 3.0.1+ micromark-extension-mdx-jsx: 3.0.2+ micromark-extension-mdx-md: 2.0.0+ micromark-extension-mdxjs-esm: 3.0.0+ micromark-util-combine-extensions: 2.0.1+ micromark-util-types: 2.0.2+dependencies:micromark-util-character: 1.2.0@@ -19206,6 +19671,18 @@ snapshots:uvu: 0.5.6vfile-message: 3.1.3+ dependencies:+ '@types/estree': 1.0.7+ devlop: 1.1.0+ micromark-factory-space: 2.0.1+ micromark-util-character: 2.1.1+ micromark-util-events-to-acorn: 2.0.3+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.2+ unist-util-position-from-estree: 2.0.0+ vfile-message: 4.0.3+dependencies:micromark-util-character: 1.2.0@@ -19321,6 +19798,16 @@ snapshots:uvu: 0.5.6vfile-message: 3.1.3+ dependencies:+ '@types/estree': 1.0.7+ '@types/unist': 3.0.3+ devlop: 1.1.0+ estree-util-visit: 2.0.0+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.2+ vfile-message: 4.0.3+@@ -19911,6 +20398,8 @@ snapshots:+ [email protected]: {}+dependencies:entities: 6.0.0@@ -20400,6 +20889,15 @@ snapshots:+ dependencies:+ '@types/hast': 2.3.4+ hast-util-embedded: 2.0.1+ hast-util-is-element: 2.1.3+ hast-util-whitespace: 2.0.1+ unified: 10.1.2+ unist-util-is: 5.2.0+dependencies:'@types/mdast': 3.0.15@@ -20407,6 +20905,15 @@ snapshots:micromark-extension-frontmatter: 1.1.1unified: 10.1.2+ dependencies:+ '@types/mdast': 3.0.15+ mdast-util-gfm: 2.0.2+ micromark-extension-gfm: 2.0.3+ unified: 10.1.2+ transitivePeerDependencies:+ - supports-color+dependencies:estree-util-is-identifier-name: 1.1.0@@ -21121,6 +21628,8 @@ snapshots:+ [email protected]: {}+@@ -21292,6 +21801,11 @@ snapshots:dependencies:imurmurhash: 0.1.4+ dependencies:+ '@types/unist': 2.0.6+ unist-util-is: 5.2.0+@@ -21304,6 +21818,10 @@ snapshots:dependencies:'@types/unist': 2.0.6+ dependencies:+ '@types/unist': 3.0.3+dependencies:'@types/unist': 2.0.6@@ -21478,6 +21996,11 @@ snapshots:+ dependencies:+ '@types/unist': 2.0.6+ vfile: 5.3.6+dependencies:'@types/unist': 2.0.6@@ -21661,6 +22184,8 @@ snapshots:optionalDependencies:'@zxing/text-encoding': 0.9.0+ [email protected]: {}+