Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

feat: Support async resource dependencies (#6030)

Oleg Isonen3d0a0657aae4
diff --git a/apps/builder/app/builder/features/pages/custom-metadata.tsx b/apps/builder/app/builder/features/pages/custom-metadata.tsx
index 752167bb4b..6a4525d249 100644
--- a/apps/builder/app/builder/features/pages/custom-metadata.tsx
+++ b/apps/builder/app/builder/features/pages/custom-metadata.tsx
@@ -16,6 +16,7 @@ import { isLiteralExpression } from "@webstudio-is/expression";
import { computeExpression } from "@webstudio-is/project-build/runtime";
import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
import { $pageRootScope } from "./page-utils";
+import { useAsyncValue } from "~/shared/use-async-value";
type Meta = {
property: string;
@@ -41,7 +42,11 @@ const MetadataItem = (props: {
const contentId = useId();
const { variableValues, scope, aliases } = useStore($pageRootScope);
- const content = computeExpression(props.content, variableValues);
+ const content = useAsyncValue(
+ () => computeExpression(props.content, variableValues),
+ [props.content, variableValues],
+ undefined
+ );
return (
<Grid
diff --git a/apps/builder/app/builder/features/pages/page-settings/page-settings.tsx b/apps/builder/app/builder/features/pages/page-settings/page-settings.tsx
index 708515cffc..b3e913b641 100644
--- a/apps/builder/app/builder/features/pages/page-settings/page-settings.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings/page-settings.tsx
@@ -1,7 +1,8 @@
-import { useState, useEffect, type JSX } from "react";
+import { useState, useEffect, useMemo, useRef, type JSX } from "react";
import { useStore } from "@nanostores/react";
import {
type Page,
+ type Pages,
findPageByIdOrPath,
getPageDraftabilityError,
isPageDraft,
@@ -295,6 +296,34 @@ export const FormFields = ({
);
};
+export const usePageSettingsErrors = ({
+ pages,
+ pageId,
+ values,
+ variableValues,
+}: {
+ pages: Pages | undefined;
+ pageId: Page["id"] | undefined;
+ values: PageSettingsValues;
+ variableValues: Map<string, unknown>;
+}) => {
+ const [errors, setErrors] = useState<PageSettingsErrors>({});
+ useEffect(() => {
+ let active = true;
+ validatePageSettings({ pages, pageId, values, variableValues }).then(
+ (nextErrors) => {
+ if (active) {
+ setErrors(nextErrors);
+ }
+ }
+ );
+ return () => {
+ active = false;
+ };
+ }, [pageId, pages, values, variableValues]);
+ return errors;
+};
+
export const NewPageSettings = ({
onSuccess,
}: {
@@ -310,7 +339,7 @@ export const NewPageSettings = ({
});
const [isSubmitAttempted, setIsSubmitAttempted] = useState(false);
const { variableValues } = useStore($pageRootScope);
- const errors = validatePageSettings({
+ const errors = usePageSettingsErrors({
pages,
pageId: undefined,
values,
@@ -439,7 +468,7 @@ export const PageSettings = ({
}) === undefined;
const [refreshDebounce, setRefreshDebounce] = useState(0);
- let errors: PageSettingsErrors = {};
+ const errorsRef = useRef<PageSettingsErrors>({});
const {
value: unsavedValues,
set: setUnsavedValues,
@@ -451,7 +480,7 @@ export const PageSettings = ({
},
{
resetOnSave: true,
- shouldSave: () => Object.keys(errors).length === 0,
+ shouldSave: () => Object.keys(errorsRef.current).length === 0,
}
);
@@ -472,15 +501,23 @@ export const PageSettings = ({
}
};
- const values: PageSettingsValues = {
- ...(page
- ? getPageSettingsValues({ page, pages, isHomePage })
- : pageSettingsDefaultValues),
- ...unsavedValues,
- };
+ const values = useMemo<PageSettingsValues>(
+ () => ({
+ ...(page
+ ? getPageSettingsValues({ page, pages, isHomePage })
+ : pageSettingsDefaultValues),
+ ...unsavedValues,
+ }),
+ [page, pages, isHomePage, unsavedValues]
+ );
const { variableValues } = useStore($pageRootScope);
- errors = validatePageSettings({ pages, pageId, values, variableValues });
+ const errors = usePageSettingsErrors({
+ pages,
+ pageId,
+ values,
+ variableValues,
+ });
if (unsavedValues.path !== undefined) {
addContentModePathError({
errors,
@@ -488,6 +525,7 @@ export const PageSettings = ({
path: unsavedValues.path,
});
}
+ errorsRef.current = errors;
useEffect(() => {
// we can't flush immediately as setState haven't propagated at that time
diff --git a/apps/builder/app/builder/features/pages/page-settings/section-general.tsx b/apps/builder/app/builder/features/pages/page-settings/section-general.tsx
index c5a0f38675..4f50f25e0f 100644
--- a/apps/builder/app/builder/features/pages/page-settings/section-general.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings/section-general.tsx
@@ -20,14 +20,13 @@ import { isLiteralExpression } from "@webstudio-is/expression";
import { documentTypes, type Pages } from "@webstudio-is/sdk";
import { HomeIcon, InfoCircleIcon } from "@webstudio-is/icons";
import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
-import { computeExpression } from "@webstudio-is/project-build/runtime";
import { $permissions } from "~/shared/nano-states";
import { $pageRootScope } from "../page-utils";
import type {
PageSettingsErrors,
PageSettingsValues,
} from "@webstudio-is/project-build/runtime";
-import { computePageSettingsText, type OnChange } from "./shared";
+import { usePageSettingsText, type OnChange } from "./shared";
const autoSelectHandler: FocusEventHandler<HTMLInputElement> = (event) =>
event.target.select();
@@ -151,7 +150,7 @@ const StatusField = ({
</Flex>
<BindableExpressionControl
expression={value ?? ""}
- value={String(computeExpression(value, variableValues) ?? "")}
+ value={usePageSettingsText(value, variableValues)}
bound={value !== undefined && isLiteralExpression(value) === false}
showBinding={showBindingControls}
scope={scope}
@@ -243,7 +242,7 @@ const RedirectField = ({
<BindableExpressionControl
expression={value ?? ""}
- value={computePageSettingsText(value, variableValues)}
+ value={usePageSettingsText(value, variableValues)}
bound={value !== undefined && isLiteralExpression(value) === false}
showBinding={showBindingControls}
scope={scope}
diff --git a/apps/builder/app/builder/features/pages/page-settings/section-marketplace.tsx b/apps/builder/app/builder/features/pages/page-settings/section-marketplace.tsx
index df9e09d447..b7329853b5 100644
--- a/apps/builder/app/builder/features/pages/page-settings/section-marketplace.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings/section-marketplace.tsx
@@ -16,7 +16,7 @@ import { $assets } from "~/shared/sync/data-stores";
import { Card } from "../../marketplace/card";
import { ImageInfo } from "../image-info";
import type { PageSettingsValues } from "@webstudio-is/project-build/runtime";
-import { computePageSettingsText, type OnChange } from "./shared";
+import { usePageSettingsText, type OnChange } from "./shared";
export const MarketplaceSection = ({
values,
@@ -31,7 +31,7 @@ export const MarketplaceSection = ({
({ property }) => property === "ws:category"
);
// @todo remove after all stores are migrated
- const categoryFallback = computePageSettingsText(
+ const categoryFallback = usePageSettingsText(
categoryMeta?.content ?? `""`,
new Map()
);
diff --git a/apps/builder/app/builder/features/pages/page-settings/section-search.test.tsx b/apps/builder/app/builder/features/pages/page-settings/section-search.test.tsx
new file mode 100644
index 0000000000..23048a0e0a
--- /dev/null
+++ b/apps/builder/app/builder/features/pages/page-settings/section-search.test.tsx
@@ -0,0 +1,54 @@
+import { act } from "react-dom/test-utils";
+import { createRoot } from "react-dom/client";
+import { expect, test, vi } from "vitest";
+import { pageSettingsDefaultValues } from "@webstudio-is/project-build/runtime";
+import { SearchSection } from "./section-search";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+test("search exclusion preserves false and can be toggled in both directions", async () => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ const onChange = vi.fn();
+ const render = async (expression: string) => {
+ await act(async () => {
+ root.render(
+ <SearchSection
+ values={{
+ ...pageSettingsDefaultValues,
+ excludePageFromSearch: expression,
+ }}
+ errors={{}}
+ onChange={onChange}
+ showBindingControls={false}
+ />
+ );
+ });
+ };
+ try {
+ await render("false");
+ const checkbox =
+ container.querySelector<HTMLButtonElement>('[role="checkbox"]')!;
+ expect(checkbox.getAttribute("aria-checked")).toBe("false");
+ await act(async () => checkbox.click());
+ expect(onChange).toHaveBeenLastCalledWith({
+ field: "excludePageFromSearch",
+ value: "true",
+ });
+ await render("true");
+ expect(checkbox.getAttribute("aria-checked")).toBe("true");
+ await act(async () => checkbox.click());
+ expect(onChange).toHaveBeenLastCalledWith({
+ field: "excludePageFromSearch",
+ value: "false",
+ });
+ await render("false");
+ expect(checkbox.getAttribute("aria-checked")).toBe("false");
+ } finally {
+ await act(async () => root.unmount());
+ container.remove();
+ }
+});
diff --git a/apps/builder/app/builder/features/pages/page-settings/section-search.tsx b/apps/builder/app/builder/features/pages/page-settings/section-search.tsx
index ca9e03a9c9..e8afdc103e 100644
--- a/apps/builder/app/builder/features/pages/page-settings/section-search.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings/section-search.tsx
@@ -11,8 +11,9 @@ import {
theme,
} from "@webstudio-is/design-system";
import { isLiteralExpression } from "@webstudio-is/expression";
-import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
import { computeExpression } from "@webstudio-is/project-build/runtime";
+import { useAsyncValue } from "~/shared/use-async-value";
+import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
import type {
PageSettingsErrors,
PageSettingsValues,
@@ -21,7 +22,7 @@ import { useStore } from "@nanostores/react";
import { $assets, $projectSettings } from "~/shared/sync/data-stores";
import { $pageRootScope } from "../page-utils";
import { SearchPreview } from "../search-preview";
-import { computePageSettingsText, usePageUrl, type OnChange } from "./shared";
+import { usePageSettingsText, usePageUrl, type OnChange } from "./shared";
// Search-engine previews represent an external light surface, not Builder UI.
const searchPreviewBackground = "#ffffff";
@@ -47,7 +48,7 @@ const LanguageField = ({
<Label htmlFor={id}>Language</Label>
<BindableExpressionControl
expression={value}
- value={computePageSettingsText(value, variableValues)}
+ value={usePageSettingsText(value, variableValues)}
bound={isLiteralExpression(value) === false}
showBinding={showBindingControls}
scope={scope}
@@ -100,13 +101,14 @@ export const SearchSection = ({
const pageUrl = usePageUrl(values);
const faviconAsset = assets.get(projectSettings?.meta.faviconAssetId ?? "");
const faviconUrl = faviconAsset?.type === "image" ? faviconAsset.name : "";
- const title = computePageSettingsText(values.title, variableValues);
- const description = computePageSettingsText(
- values.description,
- variableValues
- );
+ const title = usePageSettingsText(values.title, variableValues);
+ const description = usePageSettingsText(values.description, variableValues);
const excludePageFromSearch = Boolean(
- computeExpression(values.excludePageFromSearch, variableValues)
+ useAsyncValue(
+ () => computeExpression(values.excludePageFromSearch, variableValues),
+ [values.excludePageFromSearch, variableValues],
+ undefined
+ )
);
return (
<Grid gap={2}>
diff --git a/apps/builder/app/builder/features/pages/page-settings/section-social-image.tsx b/apps/builder/app/builder/features/pages/page-settings/section-social-image.tsx
index e325da446d..7bfd6c1363 100644
--- a/apps/builder/app/builder/features/pages/page-settings/section-social-image.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings/section-social-image.tsx
@@ -18,7 +18,7 @@ import { isLiteralExpression } from "@webstudio-is/expression";
import { $pageRootScope } from "../page-utils";
import { ImageInfo } from "../image-info";
import { SocialPreview } from "../social-preview";
-import { computePageSettingsText, usePageUrl, type OnChange } from "./shared";
+import { usePageSettingsText, usePageUrl, type OnChange } from "./shared";
export const SocialImageSection = ({
values,
@@ -37,16 +37,13 @@ export const SocialImageSection = ({
const assets = useStore($assets);
const socialImageAsset = assets.get(values.socialImageAssetId);
const { variableValues, scope, aliases } = useStore($pageRootScope);
- const socialImageUrl = computePageSettingsText(
+ const socialImageUrl = usePageSettingsText(
values.socialImageUrl,
variableValues
);
const pageUrl = usePageUrl(values);
- const title = computePageSettingsText(values.title, variableValues);
- const description = computePageSettingsText(
- values.description,
- variableValues
- );
+ const title = usePageSettingsText(values.title, variableValues);
+ const description = usePageSettingsText(values.description, variableValues);
return (
<Grid gap={2}>
<Text color="subtle">
diff --git a/apps/builder/app/builder/features/pages/page-settings/section-text-content.tsx b/apps/builder/app/builder/features/pages/page-settings/section-text-content.tsx
index 975a6c72d5..fe7f9ddb7d 100644
--- a/apps/builder/app/builder/features/pages/page-settings/section-text-content.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings/section-text-content.tsx
@@ -3,13 +3,13 @@ import { useStore } from "@nanostores/react";
import { Grid, Label, Text, TextArea } from "@webstudio-is/design-system";
import { isLiteralExpression } from "@webstudio-is/expression";
import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
-import { computeExpression } from "@webstudio-is/project-build/runtime";
import type {
PageSettingsErrors,
PageSettingsValues,
} from "@webstudio-is/project-build/runtime";
import { $pageRootScope } from "../page-utils";
import type { OnChange } from "./shared";
+import { usePageSettingsText } from "./shared";
export const TextContentSection = ({
values,
@@ -30,9 +30,7 @@ export const TextContentSection = ({
<Label htmlFor={contentId}>Text</Label>
<BindableExpressionControl
expression={values.content}
- value={String(
- computeExpression(values.content, variableValues) ?? ""
- )}
+ value={usePageSettingsText(values.content, variableValues)}
bound={isLiteralExpression(values.content) === false}
scope={scope}
aliases={aliases}
diff --git a/apps/builder/app/builder/features/pages/page-settings/shared.test.ts b/apps/builder/app/builder/features/pages/page-settings/shared.test.ts
index 3fb88ddc03..0c0a984ded 100644
--- a/apps/builder/app/builder/features/pages/page-settings/shared.test.ts
+++ b/apps/builder/app/builder/features/pages/page-settings/shared.test.ts
@@ -1,16 +1,18 @@
import { describe, expect, test } from "vitest";
-import { computePageSettingsText } from "./shared";
+import { computeExpression } from "@webstudio-is/project-build/runtime";
-describe("computePageSettingsText", () => {
- test("renders literal and computed values as text", () => {
- expect(computePageSettingsText(`"Page title"`, new Map())).toBe(
+describe("page settings expression values", () => {
+ test("renders literal and computed values as text", async () => {
+ await expect(computeExpression(`"Page title"`, new Map())).resolves.toBe(
"Page title"
);
- expect(computePageSettingsText("42", new Map())).toBe("42");
+ await expect(computeExpression("42", new Map())).resolves.toBe(42);
});
- test("does not expose missing expression values as text", () => {
- expect(computePageSettingsText("missingVariable", new Map())).toBe("");
- expect(computePageSettingsText("null", new Map())).toBe("");
+ test("does not expose missing expression values as text", async () => {
+ await expect(computeExpression("missingVariable", new Map())).resolves.toBe(
+ undefined
+ );
+ await expect(computeExpression("null", new Map())).resolves.toBe(null);
});
});
diff --git a/apps/builder/app/builder/features/pages/page-settings/shared.ts b/apps/builder/app/builder/features/pages/page-settings/shared.ts
index a6ad59b643..e10d9516db 100644
--- a/apps/builder/app/builder/features/pages/page-settings/shared.ts
+++ b/apps/builder/app/builder/features/pages/page-settings/shared.ts
@@ -2,6 +2,7 @@ import { useStore } from "@nanostores/react";
import { getPagePath } from "@webstudio-is/sdk";
import type { PageSettingsValues } from "@webstudio-is/project-build/runtime";
import { computeExpression } from "@webstudio-is/project-build/runtime";
+import { useAsyncValue } from "~/shared/use-async-value";
import {
compilePathnamePattern,
tokenizePathnamePattern,
@@ -19,11 +20,15 @@ export type OnChange = (
}[keyof PageSettingsValues]
) => void;
-export const computePageSettingsText = (
+export const usePageSettingsText = (
expression: string,
variables: Map<string, unknown>
) => {
- const value = computeExpression(expression, variables);
+ const value = useAsyncValue(
+ () => computeExpression(expression, variables),
+ [expression, variables],
+ undefined
+ );
return value === undefined || value === null ? "" : String(value);
};
diff --git a/apps/builder/app/builder/features/pages/page-utils.test.ts b/apps/builder/app/builder/features/pages/page-utils.test.ts
index 096fc18658..a818837819 100644
--- a/apps/builder/app/builder/features/pages/page-utils.test.ts
+++ b/apps/builder/app/builder/features/pages/page-utils.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from "vitest";
+import { describe, expect, test, vi } from "vitest";
import { setEnv } from "@webstudio-is/feature-flags";
import { createDefaultPages } from "@webstudio-is/project-build";
import type { Project } from "@webstudio-is/project";
@@ -37,7 +37,12 @@ import {
import { registerContainers } from "~/shared/sync/sync-stores";
import { $selectedPageId } from "~/shared/nano-states";
import { updateCurrentSystem } from "~/shared/system";
-import { $resourcesCache, getResourceKey } from "~/shared/resources";
+import {
+ $resourcesCache,
+ computeResourceRequest,
+ getResourceKey,
+} from "~/shared/resources";
+import { subscribeResourceRequestPlan } from "~/shared/nano-states/props";
setEnv("*");
registerContainers();
@@ -129,7 +134,7 @@ const createPages = () => {
const toMap = <T extends { id: string }>(list: T[]) =>
new Map(list.map((item) => [item.id, item]));
-test("page root scope should rely on selected page", () => {
+test("page root scope should rely on selected page", async () => {
const pages = createDefaultPages({
rootInstanceId: "homeRootId",
homePageId: "homePageId",
@@ -162,90 +167,99 @@ test("page root scope should rely on selected page", () => {
},
])
);
- expect($pageRootScope.get()).toEqual({
- aliases: new Map([
- ["$ws$system", "system"],
- ["$ws$dataSource$2", "page variable"],
- ]),
- scope: {
- $ws$system: initialSystem,
- $ws$dataSource$2: "",
- },
- variableValues: new Map<string, unknown>([
- [SYSTEM_VARIABLE_ID, initialSystem],
- ["2", ""],
- ]),
- });
+ await vi.waitFor(() =>
+ expect($pageRootScope.get()).toEqual({
+ aliases: new Map([
+ ["$ws$system", "system"],
+ ["$ws$dataSource$2", "page variable"],
+ ]),
+ scope: {
+ $ws$system: initialSystem,
+ $ws$dataSource$2: "",
+ },
+ variableValues: new Map<string, unknown>([
+ [SYSTEM_VARIABLE_ID, initialSystem],
+ ["2", ""],
+ ]),
+ })
+ );
});
-test("page root scope should use variable and resource values", () => {
- $pages.set(
- createDefaultPages({
+test("page root scope should use a resource value consumed by the page", async () => {
+ const unsubscribeResourceRequestPlan = subscribeResourceRequestPlan(() => {});
+ try {
+ const pages = createDefaultPages({
rootInstanceId: "homeRootId",
homePageId: "homePageId",
- })
- );
- $selectedPageId.set("homePageId");
- $dataSources.set(
- toMap([
- {
- id: "valueVariableId",
- scopeInstanceId: "homeRootId",
- name: "value variable",
- type: "variable",
- value: { type: "string", value: "" },
- },
- {
- id: "resourceVariableId",
- scopeInstanceId: "homeRootId",
- name: "resource variable",
- type: "resource",
- resourceId: "resourceId",
- },
- ])
- );
- $dataSourceVariables.set(
- new Map([["valueVariableId", "value variable value"]])
- );
- const resourceKey = getResourceKey({
- name: "my-resource",
- url: "",
- searchParams: [],
- method: "get",
- headers: [],
- });
- $resources.set(
- toMap<Resource>([
- {
- id: "resourceId",
- name: "my-resource",
- url: `""`,
- method: "get",
- headers: [],
- },
- ])
- );
- $resourcesCache.set(new Map([[resourceKey, "resource variable value"]]));
- expect($pageRootScope.get()).toEqual({
- aliases: new Map([
- ["$ws$system", "system"],
- ["$ws$dataSource$valueVariableId", "value variable"],
- ["$ws$dataSource$resourceVariableId", "resource variable"],
- ]),
- scope: {
- $ws$system: initialSystem,
- $ws$dataSource$resourceVariableId: "resource variable value",
- $ws$dataSource$valueVariableId: "value variable value",
- },
- variableValues: new Map<string, unknown>([
- [SYSTEM_VARIABLE_ID, initialSystem],
- ["valueVariableId", "value variable value"],
- ["resourceVariableId", "resource variable value"],
- ]),
- });
+ });
+ const homePage = pages.pages.get("homePageId");
+ if (homePage === undefined) {
+ throw new Error("Home page is missing");
+ }
+ pages.pages.set("homePageId", {
+ ...homePage,
+ title: "$ws$dataSource$resourceVariableId",
+ });
+ $pages.set(pages);
+ $selectedPageId.set("homePageId");
+ $dataSources.set(
+ toMap([
+ {
+ id: "valueVariableId",
+ scopeInstanceId: "homeRootId",
+ name: "value variable",
+ type: "variable",
+ value: { type: "string", value: "" },
+ },
+ {
+ id: "resourceVariableId",
+ scopeInstanceId: "homeRootId",
+ name: "resource variable",
+ type: "resource",
+ resourceId: "resourceId",
+ },
+ ])
+ );
+ $dataSourceVariables.set(
+ new Map([["valueVariableId", "value variable value"]])
+ );
+ const resource = {
+ id: "resourceId",
+ name: "my-resource",
+ url: `""`,
+ method: "get",
+ headers: [],
+ } satisfies Resource;
+ $resources.set(toMap([resource]));
+ const resourceKey = getResourceKey(
+ await computeResourceRequest(resource, new Map())
+ );
+ $resourcesCache.set(new Map([[resourceKey, "resource variable value"]]));
+ await vi.waitFor(() =>
+ expect($pageRootScope.get()).toEqual({
+ aliases: new Map([
+ ["$ws$system", "system"],
+ ["$ws$dataSource$valueVariableId", "value variable"],
+ ["$ws$dataSource$resourceVariableId", "resource variable"],
+ ]),
+ scope: {
+ $ws$system: initialSystem,
+ $ws$dataSource$resourceVariableId: "resource variable value",
+ $ws$dataSource$valueVariableId: "value variable value",
+ },
+ variableValues: new Map<string, unknown>([
+ [SYSTEM_VARIABLE_ID, initialSystem],
+ ["valueVariableId", "value variable value"],
+ ["resourceVariableId", "resource variable value"],
+ ]),
+ })
+ );
+ } finally {
+ unsubscribeResourceRequestPlan();
+ }
});
-test("page root scope should provide page system variable value", () => {
+test("page root scope should provide page system variable value", async () => {
$pages.set(
createDefaultPages({
rootInstanceId: "homeRootId",
@@ -264,16 +278,18 @@ test("page root scope should provide page system variable value", () => {
},
])
);
- expect($pageRootScope.get()).toEqual({
- aliases: new Map([["$ws$dataSource$systemId", "system"]]),
- scope: {
- $ws$dataSource$systemId: initialSystem,
- },
- variableValues: new Map([
- [SYSTEM_VARIABLE_ID, initialSystem],
- ["systemId", initialSystem],
- ]),
- });
+ await vi.waitFor(() =>
+ expect($pageRootScope.get()).toEqual({
+ aliases: new Map([["$ws$dataSource$systemId", "system"]]),
+ scope: {
+ $ws$dataSource$systemId: initialSystem,
+ },
+ variableValues: new Map([
+ [SYSTEM_VARIABLE_ID, initialSystem],
+ ["systemId", initialSystem],
+ ]),
+ })
+ );
const updatedSystem = {
...initialSystem,
params: { slug: "my-post" },
@@ -281,16 +297,18 @@ test("page root scope should provide page system variable value", () => {
updateCurrentSystem({
params: updatedSystem.params,
});
- expect($pageRootScope.get()).toEqual({
- aliases: new Map([["$ws$dataSource$systemId", "system"]]),
- scope: {
- $ws$dataSource$systemId: updatedSystem,
- },
- variableValues: new Map([
- [SYSTEM_VARIABLE_ID, updatedSystem],
- ["systemId", updatedSystem],
- ]),
- });
+ await vi.waitFor(() =>
+ expect($pageRootScope.get()).toEqual({
+ aliases: new Map([["$ws$dataSource$systemId", "system"]]),
+ scope: {
+ $ws$dataSource$systemId: updatedSystem,
+ },
+ variableValues: new Map([
+ [SYSTEM_VARIABLE_ID, updatedSystem],
+ ["systemId", updatedSystem],
+ ]),
+ })
+ );
});
describe("isFolder", () => {
diff --git a/apps/builder/app/builder/features/pages/template-settings.tsx b/apps/builder/app/builder/features/pages/template-settings.tsx
index 520737d35f..26d065da70 100644
--- a/apps/builder/app/builder/features/pages/template-settings.tsx
+++ b/apps/builder/app/builder/features/pages/template-settings.tsx
@@ -16,7 +16,6 @@ import {
nameToPath,
pageSettingsDefaultValues,
pageTemplateSettingsInput,
- validatePageSettings,
type PageSettingsErrors,
type PageSettingsValues,
} from "@webstudio-is/project-build/runtime";
@@ -32,6 +31,7 @@ import {
updatePage,
FormFields,
PageSettingsPanel,
+ usePageSettingsErrors,
} from "./page-settings/page-settings";
import type { OnChange } from "./page-settings/shared";
import { useDraftValue } from "~/builder/shared/use-draft-value";
@@ -405,7 +405,7 @@ export const CreatePageFromTemplateSettings = ({
);
const [values, setValues] = useState<PageSettingsValues>(initialValues);
- const errors = validatePageSettings({
+ const errors = usePageSettingsErrors({
pages,
pageId: undefined,
values,
diff --git a/apps/builder/app/builder/features/settings-panel/asset-query-form.test.tsx b/apps/builder/app/builder/features/settings-panel/asset-query-form.test.tsx
index fad48fb034..bc75bc025c 100644
--- a/apps/builder/app/builder/features/settings-panel/asset-query-form.test.tsx
+++ b/apps/builder/app/builder/features/settings-panel/asset-query-form.test.tsx
@@ -116,31 +116,33 @@ test("preserves and explains an invalid stored Assets query", () => {
).toBe("false");
});
-test("reports every issue from the shared query validator", () => {
+test("reports every issue from the shared query validator", async () => {
const configuration =
createDefaultStructuredAssetQueryResourceConfiguration();
expect(
- getAssetQueryConfigurationValidation({
- configuration: {
- ...configuration,
- where: {
- all: [
- {
- field: ["size"],
- operator: "gt",
- value: '"large"',
- },
- {
- field: ["extension"],
- operator: "contains",
- value: "{}",
- },
- ],
+ (
+ await getAssetQueryConfigurationValidation({
+ configuration: {
+ ...configuration,
+ where: {
+ all: [
+ {
+ field: ["size"],
+ operator: "gt",
+ value: '"large"',
+ },
+ {
+ field: ["extension"],
+ operator: "contains",
+ value: "{}",
+ },
+ ],
+ },
},
- },
- scope: {},
- }).issues
+ scope: {},
+ })
+ ).issues
).toMatchObject([
{
code: "INCOMPATIBLE_VALUE",
@@ -153,25 +155,27 @@ test("reports every issue from the shared query validator", () => {
]);
});
-test("reports every invalid query value expression", () => {
+test("reports every invalid query value expression", async () => {
const configuration =
createDefaultStructuredAssetQueryResourceConfiguration();
expect(
- getAssetQueryConfigurationValidation({
- configuration: {
- ...configuration,
- where: {
- all: [
- { field: ["size"], operator: "gt", value: "(" },
- { field: ["extension"], operator: "eq", value: "}" },
- ],
+ (
+ await getAssetQueryConfigurationValidation({
+ configuration: {
+ ...configuration,
+ where: {
+ all: [
+ { field: ["size"], operator: "gt", value: "(" },
+ { field: ["extension"], operator: "eq", value: "}" },
+ ],
+ },
+ limit: "missing(",
+ offset: "alsoMissing(",
},
- limit: "missing(",
- offset: "alsoMissing(",
- },
- scope: {},
- }).issues
+ scope: {},
+ })
+ ).issues
).toMatchObject([
{
code: "INVALID_QUERY_EXPRESSION",
@@ -192,7 +196,7 @@ test("reports every invalid query value expression", () => {
]);
});
-test("uses the loaded field catalog with the shared query validator", () => {
+test("uses the loaded field catalog with the shared query validator", async () => {
const configuration =
createDefaultStructuredAssetQueryResourceConfiguration();
const definition = {
@@ -209,23 +213,25 @@ test("uses the loaded field catalog with the shared query validator", () => {
} as const;
expect(
- getAssetQueryConfigurationValidation({
- configuration: {
- ...configuration,
- where: {
- field: ["properties", "score"],
- operator: "eq",
- value: '"high"',
+ (
+ await getAssetQueryConfigurationValidation({
+ configuration: {
+ ...configuration,
+ where: {
+ field: ["properties", "score"],
+ operator: "eq",
+ value: '"high"',
+ },
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["properties", "missing"]],
+ },
},
- output: {
- mode: "fields",
- includeMetadata: false,
- fields: [["properties", "missing"]],
- },
- },
- scope: {},
- definition,
- }).issues
+ scope: {},
+ definition,
+ })
+ ).issues
).toMatchObject([
{
severity: "warning",
diff --git a/apps/builder/app/builder/features/settings-panel/asset-query-form.tsx b/apps/builder/app/builder/features/settings-panel/asset-query-form.tsx
index f7353c7def..347a43cc5e 100644
--- a/apps/builder/app/builder/features/settings-panel/asset-query-form.tsx
+++ b/apps/builder/app/builder/features/settings-panel/asset-query-form.tsx
@@ -29,6 +29,7 @@ import {
import { computeExpressionWithinScope } from "@webstudio-is/project-build/runtime";
import { Text, theme } from "@webstudio-is/design-system";
import { $assets } from "~/shared/sync/data-stores";
+import { useAsyncValue } from "~/shared/use-async-value";
import { BindableQueryBuilder } from "~/builder/shared/query-builder";
import { fetch as builderFetch } from "~/shared/fetch.client";
import { CenteredPanelMessage, Row } from "./shared";
@@ -173,7 +174,7 @@ const getAssetQueryCatalog = (
};
};
-const getAssetQueryConfigurationValidation = ({
+const getAssetQueryConfigurationValidation = async ({
configuration,
scope,
definition,
@@ -181,7 +182,7 @@ const getAssetQueryConfigurationValidation = ({
configuration: StructuredAssetQueryResourceConfiguration;
scope: Record<string, unknown>;
definition?: AssetQueryDefinition;
-}): { body?: string; issues: readonly AssetQuerySetupIssue[] } => {
+}): Promise<{ body?: string; issues: readonly AssetQuerySetupIssue[] }> => {
const issues: AssetQuerySetupIssue[] = [];
const invalidExpressionPaths = new Set<string>();
const invalidExpressionPathValues: string[][] = [];
@@ -189,7 +190,7 @@ const getAssetQueryConfigurationValidation = ({
invalidExpressionPaths.add(JSON.stringify(path));
invalidExpressionPathValues.push(path);
};
- const evaluateExpression = (source: string, path: string[]) => {
+ const evaluateExpression = async (source: string, path: string[]) => {
if (isQueryExpression(source) === false) {
markInvalidExpression(path);
issues.push(
@@ -202,7 +203,7 @@ const getAssetQueryConfigurationValidation = ({
return;
}
try {
- return computeExpressionWithinScope(source, scope);
+ return await computeExpressionWithinScope(source, scope);
} catch (error) {
markInvalidExpression(path);
issues.push(
@@ -216,38 +217,48 @@ const getAssetQueryConfigurationValidation = ({
);
}
};
- const evaluateWhere = (
+ const evaluateWhere = async (
where: StructuredAssetQueryResourceConfiguration["where"],
path: string[]
- ): unknown => {
+ ): Promise<unknown> => {
if ("field" in where) {
return {
...where,
- value: evaluateExpression(where.value, [...path, "value"]),
+ value: await evaluateExpression(where.value, [...path, "value"]),
};
}
if ("all" in where) {
return {
- all: where.all.map((child, index) =>
- evaluateWhere(child, [...path, "all", String(index)])
+ all: await Promise.all(
+ where.all.map((child, index) =>
+ evaluateWhere(child, [...path, "all", String(index)])
+ )
),
};
}
return {
- any: where.any.map((child, index) =>
- evaluateWhere(child, [...path, "any", String(index)])
+ any: await Promise.all(
+ where.any.map((child, index) =>
+ evaluateWhere(child, [...path, "any", String(index)])
+ )
),
};
};
const query = {
result: configuration.result,
- where: evaluateWhere(configuration.where, ["query", "where"]),
+ where: await evaluateWhere(configuration.where, ["query", "where"]),
sort: configuration.sort,
...(configuration.result === "many"
? {
- limit: evaluateExpression(configuration.limit, ["query", "limit"]),
- offset: evaluateExpression(configuration.offset, ["query", "offset"]),
+ limit: await evaluateExpression(configuration.limit, [
+ "query",
+ "limit",
+ ]),
+ offset: await evaluateExpression(configuration.offset, [
+ "query",
+ "offset",
+ ]),
}
: {}),
output: configuration.output,
@@ -361,14 +372,15 @@ export const AssetQueryForm = ({
result: configuration.result,
});
}, [baseDefinition, configuration.result, configuredPaths]);
- const configurationValidation = useMemo(
+ const configurationValidation = useAsyncValue(
() =>
getAssetQueryConfigurationValidation({
configuration,
scope,
definition: baseDefinition,
}),
- [baseDefinition, configuration, scope]
+ [baseDefinition, configuration, scope],
+ { issues: [] }
);
const configurationIssues =
storedConfigurationError === undefined
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.ts
index aa2e978041..bfb4619450 100644
--- 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.ts
@@ -59,7 +59,7 @@ export const createContentBlockSourceController = ({
resolveExpressionAssetId: (
expression: string,
renderScope: string
- ) => string | undefined;
+ ) => string | undefined | PromiseLike<string | undefined>;
flushAsset: (assetId: string) => Promise<unknown>;
updateAssetSource: (
assetId: string,
@@ -251,7 +251,7 @@ export const createBuilderContentBlockSourceController = ({
openAsset: (assetId) => openExternalContentAsset({ projectId, assetId }),
reloadAsset: (assetId, expectedName) =>
reloadExternalContentAsset({ projectId, assetId, expectedName }),
- resolveExpressionAssetId: (expression, scope) => {
+ resolveExpressionAssetId: async (expression, scope) => {
const instanceSelector = parseContentBlockRenderScope(scope);
return instanceSelector === undefined
? undefined
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.tsx
index 60428c6b12..47912a96e7 100644
--- 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.tsx
@@ -51,15 +51,25 @@ export const ContentBlockSourceSection = ({
() => parseContentBlockRenderScope(renderScope),
[renderScope]
);
- const resolvedAssetId = useMemo(() => {
+ const [resolvedAssetId, setResolvedAssetId] = useState<string>();
+ useEffect(() => {
+ let active = true;
if (source === undefined || instanceSelector === undefined) {
+ setResolvedAssetId(undefined);
return;
}
- return resolveContentBlockOccurrenceAssetId({
+ void resolveContentBlockOccurrenceAssetId({
source,
instanceSelector,
variableValuesByRenderScope: variableValues,
+ }).then((assetId) => {
+ if (active) {
+ setResolvedAssetId(assetId);
+ }
});
+ return () => {
+ active = false;
+ };
}, [instanceSelector, source, variableValues]);
const resolvedAsset =
resolvedAssetId === undefined ? undefined : assets.get(resolvedAssetId);
diff --git a/apps/builder/app/builder/features/settings-panel/controls/resource-control.tsx b/apps/builder/app/builder/features/settings-panel/controls/resource-control.tsx
index d33ac54825..55cd9dea4b 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/resource-control.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/resource-control.tsx
@@ -22,6 +22,7 @@ import type { Resource } from "@webstudio-is/sdk";
import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
import { validatePrimitiveValue } from "@webstudio-is/project-build/runtime";
import { $variableValuesByInstanceSelector } from "~/shared/nano-states";
+import { useAsyncValue } from "~/shared/use-async-value";
import { $dataSources } from "~/shared/sync/data-stores";
import { $props, $resources } from "~/shared/sync/data-stores";
import {
@@ -276,9 +277,13 @@ export const ResourceControl = ({
const id = useId();
const bound = isLiteralExpression(urlExpression) === false;
- const localValue = useDraftValue(
- String(computeExpression(resource.url, variableValues) ?? ""),
- (value) => updateResource({ ...resource, url: JSON.stringify(value) })
+ const evaluatedUrl = useAsyncValue(
+ () => computeExpression(resource.url, variableValues),
+ [resource.url, variableValues],
+ undefined
+ );
+ const localValue = useDraftValue(String(evaluatedUrl ?? ""), (value) =>
+ updateResource({ ...resource, url: JSON.stringify(value) })
);
return (
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.tsx
index ddf80d43df..cdc67665c0 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
@@ -240,11 +240,13 @@ const getResetBindingButton = () => {
return button;
};
-test("renders the existing bound Text content control for the expression child", () => {
+test("renders the existing bound Text content control for the expression child", async () => {
renderTextContent();
+ await vi.waitFor(() =>
+ expect(container.querySelector('[role="textbox"]')?.textContent).toBe("2")
+ );
expect(container.textContent).toContain("Text Content");
- expect(container.querySelector('[role="textbox"]')?.textContent).toBe("2");
expect(container.querySelector('[data-variant="bound"]')).not.toBeNull();
});
@@ -293,7 +295,14 @@ test("resets a mixed expression without replacing its text sibling", async () =>
const resetButton = getResetBindingButton();
expect(resetButton.disabled).toBe(false);
- act(() => resetButton.click());
+ await act(async () => {
+ resetButton.click();
+ await vi.waitFor(() =>
+ expect($instances.get().get("reading-time")?.children).toEqual([
+ { type: "text", value: " · test" },
+ ])
+ );
+ });
expect($instances.get().get("reading-time")?.children).toEqual([
{ type: "text", value: " · test" },
@@ -312,7 +321,14 @@ test("resets and consolidates every expression on the instance", async () => {
const resetButton = getResetBindingButton();
expect(resetButton.disabled).toBe(false);
- act(() => resetButton.click());
+ await act(async () => {
+ resetButton.click();
+ await vi.waitFor(() =>
+ expect($instances.get().get("reading-time")?.children).toEqual([
+ { type: "text", value: "ABCD" },
+ ])
+ );
+ });
expect($instances.get().get("reading-time")?.children).toEqual([
{ type: "text", value: "ABCD" },
@@ -326,7 +342,14 @@ test("resets a sole expression to its evaluated text value", async () => {
const resetButton = getResetBindingButton();
expect(resetButton.disabled).toBe(false);
- act(() => resetButton.click());
+ await act(async () => {
+ resetButton.click();
+ await vi.waitFor(() =>
+ expect($instances.get().get("reading-time")?.children).toEqual([
+ { type: "text", value: "2" },
+ ])
+ );
+ });
expect($instances.get().get("reading-time")?.children).toEqual([
{ type: "text", value: "2" },
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.tsx
index 3df3b30494..e3c267697b 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
@@ -30,6 +30,7 @@ import { evaluateExpressionWithinScope } from "~/builder/shared/binding-popover"
import { getTextContentUpdateOperation } from "./text-content-utils";
import { useCodeTextLanguageSupport } from "./code";
import { parseError } from "~/shared/error/error-parse";
+import { useAsyncValue } from "~/shared/use-async-value";
const useInstance = (instanceId: Instance["id"]) => {
const $store = useMemo(() => {
@@ -69,26 +70,27 @@ export const TextContent = ({
executeRuntimeMutation(operation);
}
};
- const resetBindings = (evaluatedValue: unknown) => {
+ const resetBindings = async (evaluatedValue: unknown) => {
if (instance === undefined || target === undefined) {
return;
}
- const replacements = instance.children.flatMap((child, childIndex) => {
- if (child.type !== "expression") {
- return [];
- }
- const value =
- childIndex === target.childIndex
- ? evaluatedValue
- : evaluateExpressionWithinScope(child.value, binding.scope);
- return [
- {
- childIndex,
- expression: child.value,
- text: String(value),
- },
- ];
- });
+ const replacements = (
+ await Promise.all(
+ instance.children.map(async (child, childIndex) => {
+ if (child.type !== "expression") {
+ return;
+ }
+ const value =
+ childIndex === target.childIndex
+ ? evaluatedValue
+ : await evaluateExpressionWithinScope(child.value, binding.scope);
+ return { childIndex, expression: child.value, text: String(value) };
+ })
+ )
+ ).filter(
+ (replacement): replacement is NonNullable<typeof replacement> =>
+ replacement !== undefined
+ );
executeRuntimeMutation({
id: "instances.setTextContent",
input: {
@@ -106,13 +108,18 @@ export const TextContent = ({
boundExpression: child.type === "expression" ? child : undefined,
fallbackExpression: expression,
});
+ const evaluatedChildValue = useAsyncValue(
+ () =>
+ child.type === "expression"
+ ? evaluateExpressionWithinScope(child.value, binding.scope)
+ : Promise.resolve(undefined),
+ [binding.scope, child],
+ undefined
+ );
let displayedValue = computedValue;
if (hasMixedContent && child.type === "expression") {
try {
- displayedValue = evaluateExpressionWithinScope(
- child.value,
- binding.scope
- );
+ displayedValue = evaluatedChildValue;
} catch {
displayedValue = undefined;
}
diff --git a/apps/builder/app/builder/features/settings-panel/resource-panel.test.ts b/apps/builder/app/builder/features/settings-panel/resource-panel.test.ts
new file mode 100644
index 0000000000..46da7845a9
--- /dev/null
+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.test.ts
@@ -0,0 +1,30 @@
+import { expect, test } from "vitest";
+import { encodeDataVariableId, type DataSources } from "@webstudio-is/sdk";
+import { getResourceScopeForInstance } from "./resource-panel";
+
+test("includes resource documents when building another resource expression", () => {
+ const dataSources: DataSources = new Map([
+ [
+ "resourceDataSource",
+ {
+ type: "resource",
+ id: "resourceDataSource",
+ name: "Author",
+ resourceId: "authorResource",
+ },
+ ],
+ ]);
+ const document = { data: { id: 1 } };
+ const { scope, variableValues } = getResourceScopeForInstance({
+ page: undefined,
+ instanceKey: "body",
+ dataSources,
+ variableValuesByInstanceSelector: new Map([
+ ["body", new Map([["resourceDataSource", document]])],
+ ]),
+ includeResourceDataSources: true,
+ });
+
+ expect(scope[encodeDataVariableId("resourceDataSource")]).toBe(document);
+ expect(variableValues.get("resourceDataSource")).toBe(document);
+});
diff --git a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
index dcc17edfd2..169e8d514b 100644
--- a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
@@ -14,6 +14,7 @@ import {
import { useStore } from "@nanostores/react";
import {
encodeDataVariableId,
+ getResourceCycleDataSourceIds,
isAssetsResource as isAssetsResourceRecord,
SYSTEM_VARIABLE_ID,
systemParameter,
@@ -26,6 +27,7 @@ import {
import {
generateObjectExpression,
isLiteralExpression,
+ parseStringLiteralExpression,
parseExpressionObject,
} from "@webstudio-is/expression";
import {
@@ -71,6 +73,7 @@ import {
} from "~/shared/code-editor-base";
import { executeRuntimeMutation } from "~/shared/instance-utils/data";
import { invalidateAssets } from "~/shared/resources";
+import { useAsyncValue } from "~/shared/use-async-value";
import { onNextTransactionComplete } from "~/shared/sync/project-queue";
import {
createResourceFieldsFromFormData,
@@ -109,9 +112,16 @@ export const UrlField = ({
// revalidate and hide error message
// until validity is checks again
useEffect(() => {
- ref.current?.setCustomValidity(validateResourceUrlExpression(value, scope));
+ void validateResourceUrlExpression(value, scope).then((error) => {
+ ref.current?.setCustomValidity(error);
+ });
setError("");
}, [value, scope]);
+ const evaluatedValue = useAsyncValue(
+ () => evaluateExpressionWithinScope(value, scope),
+ [scope, value],
+ undefined
+ );
return (
<Grid gap={1}>
<Label
@@ -133,7 +143,7 @@ export const UrlField = ({
<input type="hidden" readOnly={true} name="url" value={value} />
<BindableExpressionControl
expression={value}
- value={String(evaluateExpressionWithinScope(value, scope))}
+ value={String(evaluatedValue ?? "")}
bound={isLiteralExpression(value) === false}
scope={scope}
aliases={aliases}
@@ -227,7 +237,11 @@ const ExpressionNameValuePair = ({
onChange: (name: string, value: string) => void;
onDelete: () => void;
}) => {
- const evaluatedValue = evaluateExpressionWithinScope(value, scope);
+ const evaluatedValue = useAsyncValue(
+ () => evaluateExpressionWithinScope(value, scope),
+ [scope, value],
+ undefined
+ );
const isValueString = typeof evaluatedValue === "string";
return (
<Grid
@@ -395,11 +409,13 @@ export const getResourceScopeForInstance = ({
instanceKey,
dataSources,
variableValuesByInstanceSelector,
+ includeResourceDataSources = false,
}: {
page: undefined | Page | PageTemplate;
instanceKey: undefined | string;
dataSources: DataSources;
variableValuesByInstanceSelector: Map<string, Map<string, unknown>>;
+ includeResourceDataSources?: boolean;
}) => {
const scope: Record<string, unknown> = {};
const aliases = new Map<string, string>();
@@ -412,8 +428,10 @@ export const getResourceScopeForInstance = ({
if (dataSource.type === "parameter") {
hiddenDataSourceIds.add(dataSource.id);
}
- // prevent resources using data of other resources
- if (dataSource.type === "resource") {
+ if (
+ dataSource.type === "resource" &&
+ includeResourceDataSources === false
+ ) {
hiddenDataSourceIds.add(dataSource.id);
}
}
@@ -471,12 +489,14 @@ export const useResourceScope = ({ variable }: { variable?: DataSource }) => {
$selectedInstancePathWithRoot,
$variableValuesByInstanceSelector,
$dataSources,
+ $resources,
],
(
page,
instancePath,
variableValuesByInstanceSelector,
- dataSources
+ dataSources,
+ resources
) => {
const { scope, aliases, variableValues } =
getResourceScopeForInstance({
@@ -487,17 +507,27 @@ export const useResourceScope = ({ variable }: { variable?: DataSource }) => {
}),
dataSources,
variableValuesByInstanceSelector,
+ includeResourceDataSources: true,
});
- // prevent showing currently edited variable in suggestions
- // to avoid cirular dependeny
+ // Prevent showing dependencies that would create a cycle.
const newScope = { ...scope };
const newAliases = new Map(aliases);
const newVariableValues = new Map(variableValues);
if (variable) {
- const key = encodeDataVariableId(variable.id);
- delete newScope[key];
- newAliases.delete(key);
- newVariableValues.delete(variable.id);
+ const hiddenDataSourceIds =
+ variable.type === "resource"
+ ? getResourceCycleDataSourceIds({
+ resourceDataSource: variable,
+ resources,
+ dataSources,
+ })
+ : [variable.id];
+ for (const dataSourceId of hiddenDataSourceIds) {
+ const key = encodeDataVariableId(dataSourceId);
+ delete newScope[key];
+ newAliases.delete(key);
+ newVariableValues.delete(dataSourceId);
+ }
}
return {
scope: newScope,
@@ -545,13 +575,20 @@ const BodyField = ({
const [bodyError, setBodyError] = useState("");
const bodyRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
- bodyRef.current?.setCustomValidity(
- validateResourceBodyExpression(value, bodyType, scope)
+ void validateResourceBodyExpression(value, bodyType, scope).then(
+ (error) => {
+ bodyRef.current?.setCustomValidity(error);
+ }
);
setBodyError("");
}, [value, bodyType, scope]);
- const updateBody = (newBody: string) => {
- const evaluatedValue = evaluateExpressionWithinScope(newBody, scope);
+ const evaluatedValue = useAsyncValue(
+ () => evaluateExpressionWithinScope(value, scope),
+ [scope, value],
+ undefined
+ );
+ const updateBody = async (newBody: string) => {
+ const evaluatedValue = await evaluateExpressionWithinScope(newBody, scope);
// automatically add Content-Type: application/json header
// when value is object
const isBodyObject =
@@ -562,12 +599,8 @@ const BodyField = ({
bodyType === "json"
? isBodyLiteral
? value
- : (JSON.stringify(
- evaluateExpressionWithinScope(value, scope),
- null,
- 2
- ) ?? "")
- : String(evaluateExpressionWithinScope(value, scope) ?? "");
+ : (JSON.stringify(evaluatedValue, null, 2) ?? "")
+ : String(evaluatedValue ?? "");
return (
<Grid gap={1}>
@@ -660,7 +693,7 @@ const parseHeaders = (headers: Resource["headers"]) => {
const newHeaders = headers.filter((header) => {
// cast raw expression result to string
const value = String(
- evaluateExpressionWithinScope(header.value, {})
+ parseStringLiteralExpression(header.value) ?? ""
).toLowerCase();
if (isCacheControl(header.name)) {
// move simple header like Cache-Control: max-age=10 to dedicated input
@@ -1033,9 +1066,7 @@ export const GraphqlResourceForm = forwardRef<
);
const queryId = useId();
const [query, setQuery] = useState(
- () =>
- evaluateExpressionWithinScope(bodyExpressions.get("query") ?? "", {}) ??
- ""
+ () => parseStringLiteralExpression(bodyExpressions.get("query") ?? "") ?? ""
);
const [variables, setVariables] = useState(
() => bodyExpressions.get("variables") ?? "{}"
@@ -1045,15 +1076,19 @@ export const GraphqlResourceForm = forwardRef<
);
const [variablesError, setVariablesError] = useState("");
const variablesRef = useRef<HTMLInputElement>(null);
+ const evaluatedVariables = useAsyncValue(
+ () => evaluateExpressionWithinScope(variables, scope),
+ [scope, variables],
+ undefined
+ );
useEffect(() => {
- const evaluatedValue = evaluateExpressionWithinScope(variables, scope);
variablesRef.current?.setCustomValidity(
- typeof evaluatedValue === "object" && evaluatedValue !== null
+ typeof evaluatedVariables === "object" && evaluatedVariables !== null
? ""
: "Expected valid JSON object in GraphQL variables"
);
setVariablesError("");
- }, [variables, scope]);
+ }, [evaluatedVariables]);
useImperativeHandle(ref, () => ({
save: (formData) => {
@@ -1177,11 +1212,7 @@ export const GraphqlResourceForm = forwardRef<
value={
isVariablesLiteral
? variables
- : (JSON.stringify(
- evaluateExpressionWithinScope(variables, scope),
- null,
- 2
- ) ?? "")
+ : (JSON.stringify(evaluatedVariables, null, 2) ?? "")
}
bound={isVariablesLiteral === false}
scope={scope}
diff --git a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
index 6d03d8f763..9c330741e0 100644
--- a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
@@ -690,11 +690,49 @@ const VariablePreview = ({
);
const resourcePerformanceCache = useStore($resourcePerformanceCache);
const resourceScope = useResourceScope({ variable });
+ const [resolvedResourceRequest, setResolvedResourceRequest] = useState<
+ ResourceRequest | undefined
+ >(() => resourceRequest.safeParse(variableValue).data);
+ useEffect(() => {
+ const parsedResourceRequest = resourceRequest.safeParse(variableValue).data;
+ if (parsedResourceRequest !== undefined) {
+ setResolvedResourceRequest(parsedResourceRequest);
+ return;
+ }
+ if (variable?.type !== "resource") {
+ setResolvedResourceRequest(undefined);
+ return;
+ }
+ const resource = resources.get(variable.resourceId);
+ if (resource === undefined) {
+ setResolvedResourceRequest(undefined);
+ return;
+ }
+ let active = true;
+ setResolvedResourceRequest(undefined);
+ void computeResourceRequest(resource, resourceScope.variableValues)
+ .then((request) => {
+ if (active) {
+ setResolvedResourceRequest(request);
+ }
+ })
+ .catch(() => {
+ if (active) {
+ setResolvedResourceRequest(undefined);
+ }
+ });
+ return () => {
+ active = false;
+ };
+ }, [resources, resourceScope.variableValues, variable, variableValue]);
+ const parsedResourceRequest = resourceRequest.safeParse(variableValue).data;
+ const computedResourceRequest =
+ parsedResourceRequest ??
+ (variable?.type === "resource" ? resolvedResourceRequest : undefined);
let computedValue: unknown;
let resourceDiagnostics: AssetQueryPreviewDiagnostics | undefined;
let resourcePerformance: ResourcePerformance | undefined;
let resourceDiagnosticsError: unknown;
- let computedResourceRequest: ResourceRequest | undefined;
let computedResourceKey: string | undefined;
if (variableType === "string" || variableType === "boolean") {
computedValue = variableValue;
@@ -708,20 +746,8 @@ const VariablePreview = ({
} else if (variableType === "parameter") {
computedValue = variable ? variableValues.get(variable.id) : undefined;
} else {
- // try to load current resource or saved one
- let parsedResourceRequest = resourceRequest.safeParse(variableValue).data;
- if (!parsedResourceRequest && variable?.type === "resource") {
- const resource = resources.get(variable.resourceId);
- if (resource) {
- parsedResourceRequest = computeResourceRequest(
- resource,
- resourceScope.variableValues
- );
- }
- }
- if (parsedResourceRequest) {
- computedResourceRequest = parsedResourceRequest;
- const resourceKey = getResourceKey(parsedResourceRequest);
+ if (computedResourceRequest) {
+ const resourceKey = getResourceKey(computedResourceRequest);
computedResourceKey = resourceKey;
computedValue = resourcesCache.get(resourceKey);
resourceDiagnostics = resourceDiagnosticsCache.get(resourceKey);
@@ -897,7 +923,7 @@ const VariablePopoverContent = ({
const resourceScope = useResourceScope({ variable });
- const reloadData = () => {
+ const reloadData = async () => {
const formData = getReloadableResourceFormData(formRef.current);
if (formData === undefined) {
return;
@@ -906,7 +932,7 @@ const VariablePopoverContent = ({
id: variable?.id ?? "new",
formData,
});
- const resourceRequest = computeResourceRequest(
+ const resourceRequest = await computeResourceRequest(
resource,
resourceScope.variableValues
);
@@ -914,13 +940,13 @@ const VariablePopoverContent = ({
setValue(resourceRequest);
};
- const copyAsCurl = () => {
+ const copyAsCurl = async () => {
const formData = new FormData(formRef.current ?? undefined);
const resource = createResourceValueFromFormData({
id: variable?.id ?? "new",
formData,
});
- const resourceRequest = computeResourceRequest(
+ const resourceRequest = await computeResourceRequest(
resource,
resourceScope.variableValues
);
diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-editor.test.tsx b/apps/builder/app/builder/features/text-file-editor/text-file-editor.test.tsx
index d7dae91364..93024b906c 100644
--- a/apps/builder/app/builder/features/text-file-editor/text-file-editor.test.tsx
+++ b/apps/builder/app/builder/features/text-file-editor/text-file-editor.test.tsx
@@ -25,7 +25,7 @@ afterEach(() => {
test.each(["direct", "dynamic"])(
"derives MDX completions from template names for a %s source",
- (sourceType) => {
+ async (sourceType) => {
const instances = new Map<string, Instance>([
[
"block",
@@ -106,7 +106,7 @@ test.each(["direct", "dynamic"])(
);
}
- const completions = getMdxCompletionComponents({
+ const completions = await getMdxCompletionComponents({
assetId: "article",
metas: new Map(Object.entries(coreMetas)),
});
@@ -119,8 +119,8 @@ test.each(["direct", "dynamic"])(
}
);
-test("does not suggest registered custom components without templates", () => {
- const completions = getMdxCompletionComponents({
+test("does not suggest registered custom components without templates", async () => {
+ const completions = await getMdxCompletionComponents({
assetId: "article",
metas: componentMetas,
});
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.tsx
index f2a783a3b8..23bddafe4d 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,6 +1,5 @@
import {
useEffect,
- useMemo,
useRef,
useState,
type ReactNode,
@@ -67,6 +66,7 @@ import {
type WsComponentMeta,
} from "@webstudio-is/sdk";
import { CodeEditor } from "~/shared/code-editor";
+import { useAsyncValue } from "~/shared/use-async-value";
import { EditorDialog, type EditorApi } from "~/shared/code-editor-base";
import {
$assetFolders,
@@ -132,13 +132,13 @@ const getStaticMdxCompletionProps = (
];
});
-const getMdxEditorSourceBlockInstanceIds = (assetId: string) =>
+const getMdxEditorSourceBlockInstanceIds = async (assetId: string) =>
Array.from(
new Set([
- ...getMdxAssetSourceBlockInstanceIds({
+ ...(await getMdxAssetSourceBlockInstanceIds({
assetId,
state: readBuilderStateStores(),
- }),
+ })),
...Array.from($externalContentRoots.get().values()).flatMap((root) =>
root.assetId === assetId
? [root.sourceBlockInstanceId ?? root.blockInstanceId]
@@ -147,13 +147,13 @@ const getMdxEditorSourceBlockInstanceIds = (assetId: string) =>
])
);
-const getMdxCompletionComponents = ({
+const getMdxCompletionComponents = async ({
assetId,
metas,
}: {
assetId: string;
metas: Map<string, WsComponentMeta>;
-}): MdxCompletionComponent[] => {
+}): Promise<MdxCompletionComponent[]> => {
const components = new Map<string, MdxCompletionComponent>();
const componentIds = Array.from(metas.keys());
for (const [component, meta] of metas) {
@@ -196,7 +196,9 @@ const getMdxCompletionComponents = ({
propsByInstanceId.set(prop.instanceId, props);
}
const templates = new Map<string, MdxCompletionComponent>();
- for (const blockInstanceId of getMdxEditorSourceBlockInstanceIds(assetId)) {
+ for (const blockInstanceId of await getMdxEditorSourceBlockInstanceIds(
+ assetId
+ )) {
for (const [template] of findBlockTemplates({
anchor: [blockInstanceId],
instances,
@@ -698,8 +700,8 @@ export const TextFileEditor = ({
asset.projectId !== undefined
? getAssetContentBridge().getContentSession?.(asset.projectId)
: undefined;
- const languageExtensions = useMemo(
- () => {
+ const languageExtensions = useAsyncValue(
+ async () => {
// The state reader below is intentionally refreshed when its external
// Content Block context or template definitions change.
void externalContentRoots;
@@ -720,12 +722,13 @@ export const TextFileEditor = ({
inspectMdxAssetSource({
source,
assetId,
- sourceBlockInstanceIds: getMdxEditorSourceBlockInstanceIds(assetId),
+ sourceBlockInstanceIds:
+ await getMdxEditorSourceBlockInstanceIds(assetId),
state: readBuilderStateStores(),
metas: registeredComponentMetas,
projectId,
}),
- getMdxCompletionComponents({
+ await getMdxCompletionComponents({
assetId,
metas: registeredComponentMetas,
})
@@ -770,7 +773,8 @@ export const TextFileEditor = ({
instances,
props,
registeredComponentMetas,
- ]
+ ],
+ []
);
useEffect(() => {
diff --git a/apps/builder/app/builder/shared/binding-popover.test.ts b/apps/builder/app/builder/shared/binding-popover.test.ts
index 6ea68750f0..77b8cc3d62 100644
--- a/apps/builder/app/builder/shared/binding-popover.test.ts
+++ b/apps/builder/app/builder/shared/binding-popover.test.ts
@@ -2,19 +2,21 @@ import { expect, test } from "vitest";
import { encodeDataSourceVariable } from "@webstudio-is/sdk";
import { evaluateExpressionWithinScope } from "./binding-popover";
-test("evaluateExpressionWithinScope works", () => {
+test("evaluateExpressionWithinScope works", async () => {
const variableName = "jsonVariable";
const encVariableName = encodeDataSourceVariable(variableName);
const variableValue = 1;
- expect(
+ await expect(
evaluateExpressionWithinScope(`${encVariableName} + ${encVariableName}`, {
[encVariableName]: variableValue,
})
- ).toEqual(2);
+ ).resolves.toEqual(2);
});
-test("evaluateExpressionWithinScope treats empty expression as undefined", () => {
- expect(evaluateExpressionWithinScope("", {})).toBeUndefined();
- expect(evaluateExpressionWithinScope(" ", {})).toBeUndefined();
+test("evaluateExpressionWithinScope treats empty expression as undefined", async () => {
+ await expect(evaluateExpressionWithinScope("", {})).resolves.toBeUndefined();
+ await expect(
+ evaluateExpressionWithinScope(" ", {})
+ ).resolves.toBeUndefined();
});
diff --git a/apps/builder/app/builder/shared/binding-popover.tsx b/apps/builder/app/builder/shared/binding-popover.tsx
index a994787862..401e4e80ee 100644
--- a/apps/builder/app/builder/shared/binding-popover.tsx
+++ b/apps/builder/app/builder/shared/binding-popover.tsx
@@ -48,8 +48,9 @@ import {
type EditorApi,
} from "./expression-editor";
import { normalizeEditorValue } from "~/shared/code-editor-base";
+import { useAsyncValue } from "~/shared/use-async-value";
-export const evaluateExpressionWithinScope = (
+export const evaluateExpressionWithinScope = async (
expression: string,
scope: Record<string, unknown>
) => computeExpressionWithinScope(expression, scope);
@@ -340,15 +341,16 @@ export const BindingPopover = ({
const hasUnsavedChange = useRef<boolean>(false);
const preventedClosing = useRef<boolean>(false);
const isDesignMode = useStore($isDesignMode);
-
+ const normalizedValue = normalizeEditorValue(value);
+ const evaluatedValue = useAsyncValue(
+ () => evaluateExpressionWithinScope(normalizedValue, scope),
+ [normalizedValue, scope],
+ undefined
+ );
+ const valueError = validate?.(evaluatedValue);
if (!isDesignMode) {
return;
}
-
- const normalizedValue = normalizeEditorValue(value);
- const valueError = validate?.(
- evaluateExpressionWithinScope(normalizedValue, scope)
- );
return (
<FloatingPanel
placement="left-start"
@@ -379,16 +381,17 @@ export const BindingPopover = ({
prefix={<TrashIcon />}
color="ghost"
disabled={variant === "default" || onRemove === undefined}
- onClick={(event) => {
+ onClick={async (event) => {
event.preventDefault();
if (onRemove === undefined) {
return;
}
// inline variables and close dialog
- const evaluatedValue = evaluateExpressionWithinScope(
- normalizedValue,
- scope
- );
+ const evaluatedValue =
+ await evaluateExpressionWithinScope(
+ normalizedValue,
+ scope
+ );
onRemove(evaluatedValue);
preventedClosing.current = false;
diff --git a/apps/builder/app/builder/shared/commands.test.ts b/apps/builder/app/builder/shared/commands.test.ts
index 5258b0a415..c2191ae582 100644
--- a/apps/builder/app/builder/shared/commands.test.ts
+++ b/apps/builder/app/builder/shared/commands.test.ts
@@ -367,7 +367,7 @@ describe("cut", () => {
]);
emitCommand("cut");
- await Promise.resolve();
+ await vi.waitFor(() => expect(writeText).toHaveBeenCalled());
expect(JSON.parse(writeText.mock.calls[0]?.[0] ?? "")).toMatchObject({
"@webstudio/instances/v0.1": {
diff --git a/apps/builder/app/builder/shared/query-builder.test.tsx b/apps/builder/app/builder/shared/query-builder.test.tsx
index 10887b045a..5a58eae188 100644
--- a/apps/builder/app/builder/shared/query-builder.test.tsx
+++ b/apps/builder/app/builder/shared/query-builder.test.tsx
@@ -104,6 +104,11 @@ test.each(["Backspace", "Delete"])(
} as const satisfies QueryDefinition<string, string>;
const container = renderQueryBuilder({ value, capabilities });
+ await vi.waitFor(() =>
+ expect(container.querySelector(".cm-content")?.textContent).toBe(
+ '"/blog/article"'
+ )
+ );
const editor = container.querySelector(".cm-content");
const source = Array.from(container.querySelectorAll(".cm-content")).at(-1);
@@ -139,7 +144,7 @@ test.each(["Backspace", "Delete"])(
}
);
-test("shows an evaluated value for a bound number input", () => {
+test("shows an evaluated value for a bound number input", async () => {
const capabilities = {
version: 1,
fields: [],
@@ -171,6 +176,8 @@ test("shows an evaluated value for a bound number input", () => {
'input[aria-label="Limit"]'
);
+ await vi.waitFor(() => expect(input?.value).toBe("20"));
+
expect(input?.value).toBe("20");
expect(input?.step).toBe("1");
expect(input?.disabled).toBe(true);
diff --git a/apps/builder/app/builder/shared/query-builder.tsx b/apps/builder/app/builder/shared/query-builder.tsx
index b994988a62..c3b5b6ebd4 100644
--- a/apps/builder/app/builder/shared/query-builder.tsx
+++ b/apps/builder/app/builder/shared/query-builder.tsx
@@ -9,6 +9,7 @@ import type { QueryDefinition } from "@webstudio-is/query-builder";
import { evaluateExpressionWithinScope } from "./binding-popover";
import { BindableExpressionControl } from "./bindable-expression";
import { ExpressionEditor, formatValue } from "./expression-editor";
+import { useAsyncValue } from "~/shared/use-async-value";
const BoundExpression = ({
"aria-label": label,
@@ -27,7 +28,11 @@ const BoundExpression = ({
aliases: Map<string, string>;
}) => {
const bound = isLiteralExpression(value) === false;
- const evaluatedValue = evaluateExpressionWithinScope(value, scope);
+ const evaluatedValue = useAsyncValue(
+ () => evaluateExpressionWithinScope(value, scope),
+ [scope, value],
+ undefined
+ );
if (input === "number") {
const number = Number(evaluatedValue);
diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsx
index fdef5f8e0e..a1fb31a854 100644
--- a/apps/builder/app/canvas/canvas.tsx
+++ b/apps/builder/app/canvas/canvas.tsx
@@ -36,6 +36,7 @@ import {
registerComponentLibrary,
$registeredComponents,
subscribeComponentHooks,
+ subscribeResourceRequestPlan,
$isPreviewMode,
$isDesignMode,
$isContentMode,
@@ -276,6 +277,10 @@ export const Canvas = () => {
useEffect(subscribeStyles, []);
+ // The canvas runs in a separate frame and needs its own resource documents
+ // from the cache synchronized by the Builder.
+ useEffect(() => subscribeResourceRequestPlan(() => {}), []);
+
useEffect(subscribeComponentHooks, []);
useEffect(subscribeCommands, []);
diff --git a/apps/builder/app/canvas/elements.test.tsx b/apps/builder/app/canvas/elements.test.tsx
index d666cf33dc..319c0f527f 100644
--- a/apps/builder/app/canvas/elements.test.tsx
+++ b/apps/builder/app/canvas/elements.test.tsx
@@ -1,14 +1,29 @@
import { forwardRef } from "react";
-import { renderToStaticMarkup } from "react-dom/server";
+import { act } from "react-dom/test-utils";
+import { createRoot } from "react-dom/client";
import { expect, test } from "vitest";
-import type { Instance } from "@webstudio-is/sdk";
+import { ROOT_INSTANCE_ID, type Instance } from "@webstudio-is/sdk";
import type { Components } from "@webstudio-is/react-sdk";
+import { $variableValuesByInstanceSelector } from "~/shared/nano-states";
+import { getInstanceKey } from "~/shared/nano-states/instances";
import {
createInstanceChildrenElements,
type WebstudioComponentProps,
} from "./elements";
-test("renders expression and instance siblings in order", () => {
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+test("renders expression and instance siblings in order", async () => {
+ $variableValuesByInstanceSelector.set(
+ new Map([
+ [
+ getInstanceKey(["parent", ROOT_INSTANCE_ID]),
+ new Map([["name", "world"]]),
+ ],
+ ])
+ );
const instances = new Map<string, Instance>([
[
"child",
@@ -35,10 +50,59 @@ test("renders expression and instance siblings in order", () => {
],
Component,
components: new Map() as Components,
- variableValues: new Map([["name", "world"]]),
});
- expect(renderToStaticMarkup(<>{children}</>)).toBe(
- "Hello world<span>child</span>"
- );
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ await act(async () => {
+ root.render(<>{children}</>);
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ });
+ expect(container.innerHTML).toBe("Hello world<span>child</span>");
+ root.unmount();
+ container.remove();
+ $variableValuesByInstanceSelector.set(new Map());
+});
+
+test("updates expressions when async scoped values resolve", async () => {
+ $variableValuesByInstanceSelector.set(new Map());
+ const children = createInstanceChildrenElements({
+ instances: new Map(),
+ instanceSelector: ["parent"],
+ children: [
+ {
+ type: "expression",
+ value: "$ws$dataSource$resource.data.title",
+ },
+ ],
+ Component: forwardRef<HTMLElement, WebstudioComponentProps>(() => <span />),
+ components: new Map() as Components,
+ });
+
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ await act(async () => {
+ root.render(<>{children}</>);
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ });
+ expect(container.innerHTML).toBe("");
+
+ await act(async () => {
+ $variableValuesByInstanceSelector.set(
+ new Map([
+ [
+ getInstanceKey(["parent", ROOT_INSTANCE_ID]),
+ new Map([["resource", { data: { title: "Loaded" } }]]),
+ ],
+ ])
+ );
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ });
+
+ expect(container.innerHTML).toBe("Loaded");
+ root.unmount();
+ container.remove();
+ $variableValuesByInstanceSelector.set(new Map());
});
diff --git a/apps/builder/app/canvas/elements.tsx b/apps/builder/app/canvas/elements.tsx
index c32723d903..44631549d4 100644
--- a/apps/builder/app/canvas/elements.tsx
+++ b/apps/builder/app/canvas/elements.tsx
@@ -1,10 +1,12 @@
import {
Fragment,
+ useMemo,
type ForwardRefExoticComponent,
type JSX,
type RefAttributes,
type RefObject,
} from "react";
+import { useStore } from "@nanostores/react";
import type { Instance, Instances } from "@webstudio-is/sdk";
import type { Components } from "@webstudio-is/react-sdk";
import { renderText as renderTextValue } from "@webstudio-is/react-sdk/runtime";
@@ -12,6 +14,12 @@ import {
computeExpression,
type InstanceSelector,
} from "@webstudio-is/project-build/runtime";
+import {
+ $unscopedVariableValues,
+ $variableValuesByInstanceSelector,
+} from "~/shared/nano-states";
+import { getInstanceVariableValues } from "~/shared/instance-utils/variable-values";
+import { useAsyncValue } from "~/shared/use-async-value";
export type WebstudioComponentProps = {
instance: Instance;
@@ -61,13 +69,40 @@ const renderText = (text: string): Array<JSX.Element> => {
));
};
+const AsyncTextExpression = ({
+ expression,
+ instanceSelector,
+}: {
+ expression: string;
+ instanceSelector: InstanceSelector;
+}) => {
+ const variableValuesByInstanceSelector = useStore(
+ $variableValuesByInstanceSelector
+ );
+ const unscopedVariableValues = useStore($unscopedVariableValues);
+ const variableValues = useMemo(
+ () =>
+ getInstanceVariableValues(
+ variableValuesByInstanceSelector,
+ instanceSelector,
+ unscopedVariableValues
+ ) ?? new Map(),
+ [variableValuesByInstanceSelector, instanceSelector, unscopedVariableValues]
+ );
+ const value = useAsyncValue(
+ () => computeExpression(expression, variableValues),
+ [expression, variableValues],
+ undefined
+ );
+ return renderText(String(renderTextValue(value)));
+};
+
export const createInstanceChildrenElements = ({
instances,
instanceSelector,
children,
Component,
components,
- variableValues = new Map(),
}: {
instances: Instances;
instanceSelector: InstanceSelector;
@@ -76,15 +111,19 @@ export const createInstanceChildrenElements = ({
WebstudioComponentProps & RefAttributes<HTMLElement>
>;
components: Components;
- variableValues?: ReadonlyMap<string, unknown>;
}) => {
const elements = children.map((child) => {
if (child.type === "text") {
return renderText(child.value);
}
if (child.type === "expression") {
- const value = computeExpression(child.value, variableValues);
- return renderText(String(renderTextValue(value)));
+ return (
+ <AsyncTextExpression
+ key={child.value}
+ expression={child.value}
+ instanceSelector={instanceSelector}
+ />
+ );
}
if (child.type === "id") {
return createInstanceElement({
diff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
index f4ac10fc49..c45fcb6a13 100644
--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
@@ -6,6 +6,7 @@ import {
useRef,
useLayoutEffect,
useMemo,
+ useState,
useContext,
Fragment,
type ReactNode,
@@ -56,12 +57,10 @@ import {
getIndexedInstanceId,
$registeredComponentMetas,
$variableValuesByInstanceSelector,
- $unscopedVariableValues,
$isDesignMode,
$selectedInstanceRenderState,
$selectedPageHash,
} from "~/shared/nano-states";
-import { getInstanceVariableValues } from "~/shared/instance-utils/variable-values";
import { $project, $props } from "~/shared/sync/data-stores";
import { $textEditingInstanceSelector } from "~/shared/nano-states";
import { $instances } from "~/shared/sync/data-stores";
@@ -553,15 +552,25 @@ const ExternalContentRootLoader = ({
}),
[allProps, instance.id]
);
- const sourceAssetId = useMemo(() => {
+ const [sourceAssetId, setSourceAssetId] = useState<string>();
+ useEffect(() => {
+ let active = true;
if (source === undefined) {
+ setSourceAssetId(undefined);
return;
}
- return resolveContentBlockOccurrenceAssetId({
+ void resolveContentBlockOccurrenceAssetId({
source,
instanceSelector,
variableValuesByRenderScope: variableValues,
+ }).then((assetId) => {
+ if (active) {
+ setSourceAssetId(assetId);
+ }
});
+ return () => {
+ active = false;
+ };
}, [instanceSelector, source, variableValues]);
const diagnosticsSnapshot = findExternalContentRoot(
@@ -698,10 +707,6 @@ const WebstudioComponentCanvasInner = forwardRef<
const { [showAttribute]: show = true, ...instanceProps } =
useInstanceProps(instanceSelector);
- const hasExpressionChildren = instance.children.some(
- (child) => child.type === "expression"
- );
-
const children =
getTextContent(instanceProps) ??
createInstanceChildrenElements({
@@ -710,13 +715,6 @@ const WebstudioComponentCanvasInner = forwardRef<
children: instance.children,
Component: WebstudioComponentCanvas,
components,
- variableValues: hasExpressionChildren
- ? getInstanceVariableValues(
- $variableValuesByInstanceSelector.get(),
- instanceSelector,
- $unscopedVariableValues.get()
- )
- : undefined,
});
/**
* Prevents edited element from having a size of 0 on the first render.
@@ -779,16 +777,6 @@ const WebstudioComponentCanvasInner = forwardRef<
children: instance.children,
Component: WebstudioComponentCanvas,
components,
- variableValues: hasExpressionChildren
- ? getInstanceVariableValues(
- $variableValuesByInstanceSelector.get(),
- [
- getIndexedInstanceId(instance.id, key),
- ...instanceSelector,
- ],
- $unscopedVariableValues.get()
- )
- : undefined,
})}
</Fragment>
));
@@ -1020,9 +1008,6 @@ const WebstudioComponentPreviewInner = forwardRef<
const { isSafeMode } = useContext(ReactSdkContext);
const { [showAttribute]: show = true, ...instanceProps } =
useInstanceProps(instanceSelector);
- const hasExpressionChildren = instance.children.some(
- (child) => child.type === "expression"
- );
const props: {
[componentAttribute]: string;
[idAttribute]: string;
@@ -1058,16 +1043,6 @@ const WebstudioComponentPreviewInner = forwardRef<
children: instance.children,
Component: WebstudioComponentPreview,
components,
- variableValues: hasExpressionChildren
- ? getInstanceVariableValues(
- $variableValuesByInstanceSelector.get(),
- [
- getIndexedInstanceId(instance.id, key),
- ...instanceSelector,
- ],
- $unscopedVariableValues.get()
- )
- : undefined,
})}
</Fragment>
));
@@ -1125,13 +1100,6 @@ const WebstudioComponentPreviewInner = forwardRef<
children: instance.children,
Component: WebstudioComponentPreview,
components,
- variableValues: hasExpressionChildren
- ? getInstanceVariableValues(
- $variableValuesByInstanceSelector.get(),
- instanceSelector,
- $unscopedVariableValues.get()
- )
- : undefined,
})}
</Component>
);
diff --git a/apps/builder/app/routes/rest.resources-loader.ts b/apps/builder/app/routes/rest.resources-loader.ts
index 9faa993469..dea10bceee 100644
--- a/apps/builder/app/routes/rest.resources-loader.ts
+++ b/apps/builder/app/routes/rest.resources-loader.ts
@@ -1,4 +1,3 @@
-import { z } from "zod";
import { type ActionFunctionArgs, data, json } from "@remix-run/server-runtime";
import { isLocalResource } from "@webstudio-is/sdk/runtime";
import { parseBuilderUrl } from "@webstudio-is/protocol";
@@ -10,7 +9,10 @@ import { loader as assetsOpenApiLoader } from "./rest.assets.openapi[.]json";
import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
import { checkCsrf } from "~/services/csrf-session.server";
import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";
-import { loadResourceRequestList } from "~/services/resource-list-loader.server";
+import {
+ loadResourceRequestList,
+ resourceRequestListSchema,
+} from "~/services/resource-list-loader.server";
export const action = async ({ request }: ActionFunctionArgs) => {
preventCrossOriginCookie(request);
@@ -54,7 +56,7 @@ export const action = async ({ request }: ActionFunctionArgs) => {
const requestJson = await request.json();
const { sourceOrigin } = parseBuilderUrl(request.url);
- const requestList = z.array(z.unknown()).safeParse(requestJson);
+ const requestList = resourceRequestListSchema.safeParse(requestJson);
if (requestList.success === false) {
throw data(requestList.error, {
diff --git a/apps/builder/app/services/resource-list-loader.server.ts b/apps/builder/app/services/resource-list-loader.server.ts
index 8a41395169..815f5382a4 100644
--- a/apps/builder/app/services/resource-list-loader.server.ts
+++ b/apps/builder/app/services/resource-list-loader.server.ts
@@ -1,8 +1,10 @@
+import { z } from "zod";
import { type ResourceRequest, resourceRequest } from "@webstudio-is/sdk";
import {
createResourceFetchBatchProvider,
isLocalResource,
loadResource,
+ resourceLoadConcurrency,
} from "@webstudio-is/sdk/runtime";
import { getZodValidationIssues } from "@webstudio-is/project-build/runtime";
import { executeAssetQueries } from "~/shared/$resources/assets-query.server";
@@ -14,6 +16,10 @@ const defaultDependencies = {
now: () => performance.now(),
};
+export const resourceRequestListSchema = z
+ .array(z.unknown())
+ .max(resourceLoadConcurrency);
+
const getResponseBytes = (value: unknown) => {
try {
return new TextEncoder().encode(JSON.stringify(value)).byteLength;
diff --git a/apps/builder/app/shared/content-block-source-utils.test.ts b/apps/builder/app/shared/content-block-source-utils.test.ts
index efc80c2654..443d1fe4b5 100644
--- a/apps/builder/app/shared/content-block-source-utils.test.ts
+++ b/apps/builder/app/shared/content-block-source-utils.test.ts
@@ -17,21 +17,21 @@ describe("Content Block occurrence source", () => {
expect(parseContentBlockRenderScope('["block",1]')).toBeUndefined();
});
- test("resolves a root-qualified variable scope", () => {
+ test("resolves a root-qualified variable scope", async () => {
const values = new Map([["asset", "article"]]);
const rootQualified = new Map([
[JSON.stringify([...selector, ROOT_INSTANCE_ID]), values],
]);
- expect(
+ await expect(
resolveContentBlockOccurrenceAssetId({
source: { type: "expression", value: "asset" },
instanceSelector: selector,
variableValuesByRenderScope: rootQualified,
})
- ).toBe("article");
+ ).resolves.toBe("article");
});
- test("resolves each bound Collection occurrence independently", () => {
+ test("resolves each bound Collection occurrence independently", async () => {
const first = ["block", "collection[first]", "collection", "body"];
const second = ["block", "collection[second]", "collection", "body"];
const values = new Map([
@@ -39,15 +39,17 @@ describe("Content Block occurrence source", () => {
[JSON.stringify(second), new Map([["asset", "b.mdx"]])],
]);
- expect(
- [first, second].map((instanceSelector) =>
- resolveContentBlockOccurrenceAssetId({
- source: { type: "expression", value: "asset" },
- instanceSelector,
- variableValuesByRenderScope: values,
- })
+ await expect(
+ Promise.all(
+ [first, second].map((instanceSelector) =>
+ resolveContentBlockOccurrenceAssetId({
+ source: { type: "expression", value: "asset" },
+ instanceSelector,
+ variableValuesByRenderScope: values,
+ })
+ )
)
- ).toEqual(["a.mdx", "b.mdx"]);
+ ).resolves.toEqual(["a.mdx", "b.mdx"]);
});
test("detects repeated selectors consistently", () => {
diff --git a/apps/builder/app/shared/content-block-source-utils.ts b/apps/builder/app/shared/content-block-source-utils.ts
index eee3fbb62f..7290277413 100644
--- a/apps/builder/app/shared/content-block-source-utils.ts
+++ b/apps/builder/app/shared/content-block-source-utils.ts
@@ -22,7 +22,7 @@ export const parseContentBlockRenderScope = (renderScope: string) => {
}
};
-export const resolveContentBlockOccurrenceAssetId = ({
+export const resolveContentBlockOccurrenceAssetId = async ({
source,
instanceSelector,
variableValuesByRenderScope,
diff --git a/apps/builder/app/shared/copy-paste/copy-paste.test.ts b/apps/builder/app/shared/copy-paste/copy-paste.test.ts
index 9d24846efc..03ba095295 100644
--- a/apps/builder/app/shared/copy-paste/copy-paste.test.ts
+++ b/apps/builder/app/shared/copy-paste/copy-paste.test.ts
@@ -123,7 +123,9 @@ const createClipboardEvent = (type: "copy" | "cut" | "paste") => {
getData: (mimeType: string) =>
connected ? (data.get(mimeType) ?? "") : "",
setData: (mimeType: string, value: string) => {
- data.set(mimeType, value);
+ if (connected) {
+ data.set(mimeType, value);
+ }
},
} as DataTransfer;
const event = new Event(type, {
@@ -131,7 +133,7 @@ const createClipboardEvent = (type: "copy" | "cut" | "paste") => {
cancelable: true,
}) as ClipboardEvent;
Object.defineProperty(event, "clipboardData", { value: clipboardData });
- if (type === "paste") {
+ if (type === "paste" || type === "cut") {
disconnectClipboardData.set(event, () => {
connected = false;
});
@@ -183,7 +185,7 @@ const setupToastSuccess = () => {
};
const waitForClipboardEvent = () =>
- new Promise((resolve) => setTimeout(resolve, 0));
+ new Promise((resolve) => setTimeout(resolve, 20));
const pastePlainText = async (
value: unknown,
@@ -265,7 +267,7 @@ test("does not copy instance to clipboard when no instance is selected", async (
expect(writeText).not.toHaveBeenCalled();
});
-test("copies selected instance through clipboard event", () => {
+test("copies selected instance through clipboard event", async () => {
resetStores();
const abortController = new AbortController();
initCopyPaste({ signal: abortController.signal });
@@ -295,6 +297,7 @@ test("copies selected instance through clipboard event", () => {
const { clipboardData, event } = createClipboardEvent("copy");
dispatchClipboardEvent(event);
+ await waitForClipboardEvent();
expect(event.defaultPrevented).toBe(true);
expect(clipboardData.getData("text/plain")).toContain(
@@ -303,7 +306,7 @@ test("copies selected instance through clipboard event", () => {
abortController.abort();
});
-test("copies multi-selected instances through clipboard event", () => {
+test("copies multi-selected instances through clipboard event", async () => {
resetStores();
const abortController = new AbortController();
initCopyPaste({ signal: abortController.signal });
@@ -348,6 +351,7 @@ test("copies multi-selected instances through clipboard event", () => {
const { clipboardData, event } = createClipboardEvent("copy");
dispatchClipboardEvent(event);
+ await waitForClipboardEvent();
expect(event.defaultPrevented).toBe(true);
expect(JSON.parse(clipboardData.getData("text/plain"))).toMatchObject({
@@ -358,7 +362,7 @@ test("copies multi-selected instances through clipboard event", () => {
abortController.abort();
});
-test("content mode copies selected instances through clipboard event", () => {
+test("content mode copies selected instances through clipboard event", async () => {
resetStores();
const abortController = new AbortController();
const toastInfo = setupToastInfo();
@@ -389,6 +393,7 @@ test("content mode copies selected instances through clipboard event", () => {
const { clipboardData, event } = createClipboardEvent("copy");
dispatchClipboardEvent(event);
+ await waitForClipboardEvent();
expect(event.defaultPrevented).toBe(true);
expect(clipboardData.getData("text/plain")).toContain(
@@ -398,7 +403,7 @@ test("content mode copies selected instances through clipboard event", () => {
abortController.abort();
});
-test("content mode reports unsupported copy selection", () => {
+test("content mode reports unsupported copy selection", async () => {
resetStores();
const abortController = new AbortController();
const toastInfo = setupToastInfo();
@@ -406,6 +411,7 @@ test("content mode reports unsupported copy selection", () => {
const { event } = createClipboardEvent("copy");
dispatchClipboardEvent(event);
+ await waitForClipboardEvent();
expect(event.defaultPrevented).toBe(false);
expect(toastInfo).toHaveBeenCalledWith(
@@ -447,6 +453,7 @@ test("content mode pastes instance clipboard data through clipboard event", asyn
const { clipboardData: copyData, event: copyEvent } =
createClipboardEvent("copy");
dispatchClipboardEvent(copyEvent);
+ await waitForClipboardEvent();
const clipboardText = copyData.getData("text/plain");
selectInstance(["body-id"]);
const { clipboardData, event } = createClipboardEvent("paste");
@@ -521,6 +528,7 @@ test("pastes multi-selected instance clipboard data through clipboard event", as
const { clipboardData: copyData, event: copyEvent } =
createClipboardEvent("copy");
dispatchClipboardEvent(copyEvent);
+ await waitForClipboardEvent();
const clipboardText = copyData.getData("text/plain");
expect(JSON.parse(clipboardText)).toMatchObject({
"@webstudio/instances/v0.1": {
@@ -1000,8 +1008,10 @@ test("does not intercept native paste while editing text", async () => {
abortController.abort();
});
-test("cuts multi-selected instances through clipboard event", () => {
+test("cuts multi-selected instances through clipboard event", async () => {
resetStores();
+ const writeText = vi.fn().mockResolvedValue(undefined);
+ vi.stubGlobal("navigator", { ...navigator, clipboard: { writeText } });
const abortController = new AbortController();
initCopyPaste({ signal: abortController.signal });
$instances.set(
@@ -1042,12 +1052,13 @@ test("cuts multi-selected instances through clipboard event", () => {
["box-id", "body-id"],
["heading-id", "body-id"],
]);
- const { clipboardData, event } = createClipboardEvent("cut");
+ const { event } = createClipboardEvent("cut");
dispatchClipboardEvent(event);
+ await waitForClipboardEvent();
expect(event.defaultPrevented).toBe(true);
- expect(JSON.parse(clipboardData.getData("text/plain"))).toMatchObject({
+ expect(JSON.parse(writeText.mock.calls[0]?.[0] ?? "")).toMatchObject({
"@webstudio/instances/v0.1": {
rootInstanceIds: ["box-id", "heading-id"],
},
@@ -1058,7 +1069,7 @@ test("cuts multi-selected instances through clipboard event", () => {
abortController.abort();
});
-test("content mode blocks cut through clipboard event", () => {
+test("content mode blocks cut through clipboard event", async () => {
resetStores();
const abortController = new AbortController();
const toastInfo = setupToastInfo();
@@ -1066,6 +1077,7 @@ test("content mode blocks cut through clipboard event", () => {
const { event } = createClipboardEvent("cut");
dispatchClipboardEvent(event);
+ await waitForClipboardEvent();
expect(event.defaultPrevented).toBe(false);
expect(toastInfo).toHaveBeenCalledWith(
@@ -1450,6 +1462,92 @@ test("does not cut instance to clipboard when no instance is selected", async ()
expect(writeText).not.toHaveBeenCalled();
});
+test.each(["keyboard", "programmatic"] as const)(
+ "%s cut preserves selected instances until the clipboard write succeeds",
+ async (mode) => {
+ for (const multiple of [false, true]) {
+ for (const outcome of ["success", "failure", "disabled"] as const) {
+ resetStores();
+ setupPage();
+ const toastError = setupToastError();
+ const roots = multiple ? ["box-id", "heading-id"] : ["box-id"];
+ const instances = new Map<string, Instance>([
+ [
+ "body-id",
+ {
+ type: "instance",
+ id: "body-id",
+ component: "Body",
+ children: roots.map((value) => ({ type: "id", value })),
+ },
+ ],
+ ...roots.map((id): [string, Instance] => [
+ id,
+ { type: "instance", id, component: "Box", children: [] },
+ ]),
+ ]);
+ $instances.set(instances);
+ selectInstances(roots.map((id) => [id, "body-id"]));
+ let finishWrite = () => {};
+ const writeText = vi.fn(
+ () =>
+ new Promise<void>((resolve, reject) => {
+ finishWrite = () =>
+ outcome === "failure"
+ ? reject(new Error("Clipboard write denied"))
+ : resolve();
+ })
+ );
+ vi.stubGlobal("navigator", { ...navigator, clipboard: { writeText } });
+ const controller = new AbortController();
+ initCopyPaste({ signal: controller.signal });
+ if (outcome === "disabled") {
+ $authTokenPermissions.set({
+ ...$authTokenPermissions.get(),
+ canCopy: false,
+ });
+ }
+ let operation: Promise<unknown> | undefined;
+ try {
+ if (mode === "keyboard") {
+ const { event } = createClipboardEvent("cut");
+ dispatchClipboardEvent(event);
+ } else {
+ operation = Promise.resolve(cutInstance()).catch(
+ (error: unknown) => error
+ );
+ }
+ await waitForClipboardEvent();
+ expect($instances.get()).toEqual(instances);
+ expect(writeText).toHaveBeenCalledTimes(
+ outcome === "disabled" ? 0 : 1
+ );
+ finishWrite();
+ await operation;
+ await waitForClipboardEvent();
+ if (outcome === "success") {
+ for (const id of roots) {
+ expect($instances.get().has(id)).toBe(false);
+ }
+ expect($instances.get().get("body-id")?.children).toEqual([]);
+ } else {
+ expect($instances.get()).toEqual(instances);
+ if (mode === "keyboard" && outcome === "failure") {
+ expect(toastError).toHaveBeenCalled();
+ }
+ }
+ } finally {
+ finishWrite();
+ await operation;
+ await waitForClipboardEvent();
+ controller.abort();
+ vi.restoreAllMocks();
+ }
+ }
+ }
+ }
+);
+
test("cuts selected instance to clipboard and removes it", 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.ts
index ed3885b25c..1cf8975e16 100644
--- a/apps/builder/app/shared/copy-paste/copy-paste.ts
+++ b/apps/builder/app/shared/copy-paste/copy-paste.ts
@@ -81,7 +81,10 @@ export type Plugin = {
name: string;
mimeType: string;
onCopy?: () => undefined | string | Promise<undefined | string>;
- onCut?: () => undefined | string;
+ // Delete the source only after writeClipboard confirms the data was saved.
+ onCut?: (
+ writeClipboard: (data: string) => Promise<boolean>
+ ) => undefined | Promise<undefined | string>;
onPaste?: (data: string) => PasteResult | Promise<PasteResult>;
};
@@ -166,7 +169,12 @@ const initPlugins = ({
if (data instanceof Promise) {
event.preventDefault();
void data
- .then((value) => writeClipboardText(value))
+ .then((value) => {
+ if (value !== undefined) {
+ event.clipboardData?.setData(mimeType, value);
+ }
+ return writeClipboardText(value);
+ })
.catch(() =>
builderApi.toast.error(
"Could not prepare the selected content for copying."
@@ -187,12 +195,13 @@ const initPlugins = ({
if (validateClipboardEvent(event) === false) {
return;
}
- for (const { mimeType, onCut } of plugins) {
- const data = onCut?.();
- if (data) {
- // must prevent default, otherwise setData() will not work
+ for (const { onCut } of plugins) {
+ const operation = onCut?.(writeClipboardText);
+ if (operation !== undefined) {
event.preventDefault();
- event.clipboardData?.setData(mimeType, data);
+ operation.catch(() => {
+ builderApi.toast.error("Could not cut the selected content.");
+ });
break;
}
}
@@ -281,6 +290,18 @@ export const initCopyPasteForContentEditMode = ({
return;
}
const data = instanceText.onCopy?.();
+ if (data instanceof Promise) {
+ event.preventDefault();
+ void data
+ .then((value) => {
+ if (value !== undefined) {
+ event.clipboardData?.setData(instanceText.mimeType, value);
+ }
+ return writeClipboardText(value);
+ })
+ .catch(() => undefined);
+ return;
+ }
if (data) {
event.preventDefault();
event.clipboardData?.setData(instanceText.mimeType, data);
@@ -363,7 +384,9 @@ const writeClipboardText = async (
data = await data;
if (data && validateCopyPermission()) {
await navigator.clipboard.writeText(data);
+ return true;
}
+ return false;
};
// Public API for programmatic copy/paste/cut operations
@@ -401,6 +424,6 @@ export const emitPaste = async () => {
await pasteClipboardText?.(text);
};
-export const cutInstance = () => {
- return writeClipboardText(instanceText.onCut?.());
+export const cutInstance = async () => {
+ await instanceText.onCut?.(writeClipboardText);
};
diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts b/apps/builder/app/shared/copy-paste/plugin-instance.test.ts
index 3a82c7ce9c..c55ec041b0 100644
--- a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-instance.test.ts
@@ -113,19 +113,167 @@ const getMapDifference = <Type extends Map<unknown, unknown>>(
};
describe("copy and cut guards", () => {
- test("does not copy without a selected instance", () => {
+ test.each([false, true])(
+ "does not delete an edit queued during clipboard completion (multiple: %s)",
+ async (multiple) => {
+ setPageRoot("body0");
+ const roots = multiple ? ["box1", "box2"] : ["box1"];
+ $instances.set(
+ toMap([
+ createInstance(
+ "body0",
+ "Body",
+ roots.map((value) => ({ type: "id", value }))
+ ),
+ ...roots.map((id) =>
+ createInstance(id, "Box", [{ type: "text", value: "Before" }])
+ ),
+ ])
+ );
+ selectInstances(roots.map((id) => [id, "body0"]));
+ const notify = vi
+ .spyOn(builderApiTesting.api.toast, "info")
+ .mockImplementation(() => {});
+ let edited = false;
+ await instanceText.onCut(async () => {
+ queueMicrotask(() =>
+ queueMicrotask(() => {
+ // Like an instance mutation, an edit cannot target a deleted instance.
+ if ($instances.get().has("box1") === false) {
+ return;
+ }
+ const instances = new Map($instances.get());
+ instances.set(
+ "box1",
+ createInstance("box1", "Box", [
+ { type: "text", value: "New edit" },
+ ])
+ );
+ $instances.set(instances);
+ edited = true;
+ })
+ );
+ return true;
+ });
+ // Either cut finished first, or the edit must cancel the whole deletion.
+ expect($instances.get().get("body0")?.children).toEqual(
+ edited ? roots.map((value) => ({ type: "id", value })) : []
+ );
+ expect(notify).toHaveBeenCalledTimes(edited ? 1 : 0);
+ if (edited) {
+ expect($instances.get().get("box1")?.children).toEqual([
+ { type: "text", value: "New edit" },
+ ]);
+ }
+ }
+ );
+
+ test.each(
+ [false, true].flatMap((multiple) =>
+ ["content", "property", "project"].map((change) => ({ multiple, change }))
+ )
+ )(
+ "preserves pending cut after $change change (multiple: $multiple)",
+ async ({ multiple, change }) => {
+ setPageRoot("body0");
+ const project = $project.get();
+ const roots = multiple ? ["box1", "box2"] : ["box1"];
+ $instances.set(
+ toMap([
+ createInstance(
+ "body0",
+ "Body",
+ roots.map((value) => ({ type: "id", value }))
+ ),
+ ...roots.map((id) =>
+ createInstance(id, "Box", [{ type: "text", value: "Before" }])
+ ),
+ ])
+ );
+ $props.set(new Map());
+ selectInstances(roots.map((id) => [id, "body0"]));
+ const notify = vi
+ .spyOn(builderApiTesting.api.toast, "info")
+ .mockImplementation(() => {});
+ let copied: string | undefined;
+ try {
+ await instanceText.onCut(async (data) => {
+ copied = data;
+ if (change === "content") {
+ const instances = new Map($instances.get());
+ instances.set(
+ "box1",
+ createInstance("box1", "Box", [
+ { type: "text", value: "New edit" },
+ ])
+ );
+ $instances.set(instances);
+ }
+ if (change === "property") {
+ $props.set(
+ new Map([
+ [
+ "prop",
+ {
+ id: "prop",
+ instanceId: "box1",
+ name: "title",
+ type: "string",
+ value: "New edit",
+ },
+ ],
+ ])
+ );
+ }
+ if (change === "project") {
+ $project.set({ id: "another-project" } as Project);
+ }
+ return true;
+ });
+ const transfer = JSON.parse(copied ?? "");
+ const fragment = multiple
+ ? transfer["@webstudio/instances/v0.1"].fragment
+ : transfer["@webstudio/instance/v0.1"];
+ expect(
+ fragment.instances.find(
+ (instance: Instance) => instance.id === "box1"
+ ).children
+ ).toEqual([{ type: "text", value: "Before" }]);
+ expect($instances.get().get("body0")?.children).toEqual(
+ roots.map((value) => ({ type: "id", value }))
+ );
+ for (const id of roots) {
+ expect($instances.get().has(id)).toBe(true);
+ }
+ if (change === "content") {
+ expect($instances.get().get("box1")?.children).toEqual([
+ { type: "text", value: "New edit" },
+ ]);
+ }
+ if (change === "property") {
+ expect($props.get().get("prop")?.value).toBe("New edit");
+ }
+ expect(notify).toHaveBeenCalledTimes(1);
+ } finally {
+ $project.set(project);
+ $props.set(new Map());
+ }
+ }
+ );
+
+ test("does not copy without a selected instance", async () => {
selectInstance(undefined);
expect(instanceText.onCopy?.()).toBeUndefined();
});
- test("does not cut without a selected instance", () => {
+ test("does not cut without a selected instance", async () => {
selectInstance(undefined);
- expect(instanceText.onCut?.()).toBeUndefined();
+ expect(instanceText.onCut?.(async () => true)).toBeUndefined();
});
- test("does not copy or cut the selected root instance", () => {
+ test("does not copy or cut the selected root instance", async () => {
const instances: Instances = toMap([
createInstance("body0", "Body", [{ type: "id", value: "box1" }]),
createInstance("box1", "Box", []),
@@ -133,12 +281,14 @@ describe("copy and cut guards", () => {
$instances.set(instances);
selectInstance(["body0"]);
- expect(instanceText.onCopy?.()).toBeUndefined();
- expect(instanceText.onCut?.()).toBeUndefined();
+ await expect(instanceText.onCopy?.()).resolves.toBeUndefined();
+ await expect(
+ instanceText.onCut?.(async () => true)
+ ).resolves.toBeUndefined();
expect($instances.get()).toEqual(instances);
});
- test("copies multiple selected roots into one combined fragment", () => {
+ test("copies multiple selected roots into one combined fragment", async () => {
$instances.set(
toMap([
createInstance("body0", "Body", [
@@ -154,7 +304,7 @@ describe("copy and cut guards", () => {
["box2", "body0"],
]);
- const clipboardData = instanceText.onCopy?.();
+ const clipboardData = await instanceText.onCopy?.();
expect(JSON.parse(clipboardData ?? "")).toMatchObject({
"@webstudio/instances/v0.1": {
@@ -268,7 +418,7 @@ describe("copy and cut guards", () => {
);
selectInstance(["item", "collection[0]", "collection", "body"]);
- const clipboardData = instanceText.onCopy?.();
+ const clipboardData = await instanceText.onCopy?.();
const fragment = JSON.parse(clipboardData ?? "")[
"@webstudio/instance/v0.1"
];
@@ -346,7 +496,7 @@ describe("copy and cut guards", () => {
["box1", "body0"],
["box2", "body0"],
]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
selectInstance(["body0"]);
const result = await instanceText.onPaste?.(clipboardData);
@@ -462,7 +612,7 @@ describe("copy and cut guards", () => {
] satisfies Instance[])
);
selectInstance(["legacy-button", "body0"]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
selectInstance(["body0"]);
const warn = vi
.spyOn(builderApiTesting.api.toast, "warn")
@@ -490,7 +640,7 @@ describe("copy and cut guards", () => {
["box1", "body0"],
["box2", "body0"],
]);
- const clipboardData = JSON.parse(instanceText.onCopy?.() ?? "");
+ const clipboardData = JSON.parse((await instanceText.onCopy?.()) ?? "");
clipboardData["@webstudio/instances/v0.1"].rootInstanceIds = [
"box1",
"child",
@@ -517,7 +667,7 @@ describe("copy and cut guards", () => {
expect($instances.get().get("body0")?.children).toEqual(bodyChildren);
});
- test("writes only copyable roots when multi-copy skips selected roots", () => {
+ test("writes only copyable roots when multi-copy skips selected roots", async () => {
$instances.set(
toMap([
createInstance("body0", "Body", [
@@ -533,7 +683,7 @@ describe("copy and cut guards", () => {
["box1", "body0"],
]);
- const clipboardData = instanceText.onCopy?.();
+ const clipboardData = await instanceText.onCopy?.();
expect(JSON.parse(clipboardData ?? "")).toMatchObject({
"@webstudio/instances/v0.1": {
@@ -542,7 +692,7 @@ describe("copy and cut guards", () => {
});
});
- test("does not copy when no multi-selected root is copyable", () => {
+ test("does not copy when no multi-selected root is copyable", async () => {
const instances: Instances = toMap([
createInstance("body0", "Body", [
{ type: "id", value: "template1" },
@@ -557,11 +707,11 @@ describe("copy and cut guards", () => {
["template2", "body0"],
]);
- expect(instanceText.onCopy?.()).toBeUndefined();
+ await expect(instanceText.onCopy?.()).resolves.toBeUndefined();
expect($instances.get()).toEqual(instances);
});
- test("cuts multiple selected roots into one combined fragment and removes them", () => {
+ test("cuts multiple selected roots into one combined fragment and removes them", async () => {
$instances.set(
toMap([
createInstance("body0", "Body", [
@@ -577,7 +727,7 @@ describe("copy and cut guards", () => {
["box2", "body0"],
]);
- const clipboardData = instanceText.onCut?.();
+ const clipboardData = await instanceText.onCut?.(async () => true);
expect(JSON.parse(clipboardData ?? "")).toMatchObject({
"@webstudio/instances/v0.1": {
@@ -590,7 +740,7 @@ describe("copy and cut guards", () => {
expect($allSelectedInstanceSelectors.get()).toEqual([]);
});
- test("cuts only copyable roots when multi-cut skips selected roots", () => {
+ test("cuts only copyable roots when multi-cut skips selected roots", async () => {
$instances.set(
toMap([
createInstance("body0", "Body", [
@@ -606,7 +756,7 @@ describe("copy and cut guards", () => {
["box1", "body0"],
]);
- const clipboardData = instanceText.onCut?.();
+ const clipboardData = await instanceText.onCut?.(async () => true);
expect(JSON.parse(clipboardData ?? "")).toMatchObject({
"@webstudio/instances/v0.1": {
@@ -621,7 +771,7 @@ describe("copy and cut guards", () => {
expect($allSelectedInstanceSelectors.get()).toEqual([]);
});
- test("does not cut when no multi-selected root is copyable", () => {
+ test("does not cut when no multi-selected root is copyable", async () => {
const instances: Instances = toMap([
createInstance("body0", "Body", [
{ type: "id", value: "template1" },
@@ -636,7 +786,9 @@ describe("copy and cut guards", () => {
["template2", "body0"],
]);
- expect(instanceText.onCut?.()).toBeUndefined();
+ await expect(
+ instanceText.onCut?.(async () => true)
+ ).resolves.toBeUndefined();
expect($instances.get()).toEqual(instances);
expect($allSelectedInstanceSelectors.get()).toEqual([
["template1", "body0"],
@@ -751,7 +903,7 @@ describe("paste target", () => {
test("is inside selected instance", async () => {
$instances.set(instances);
selectInstance(["box1", "body0"]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
selectInstance(["box2", "body0"]);
await instanceText.onPaste?.(clipboardData);
@@ -768,7 +920,7 @@ describe("paste target", () => {
test("is after selected instance when same as copied", async () => {
$instances.set(instances);
selectInstance(["box1", "body0"]);
- await instanceText.onPaste?.(instanceText.onCopy?.() ?? "");
+ await instanceText.onPaste?.((await instanceText.onCopy?.()) ?? "");
const instancesDifference = getMapDifference(instances, $instances.get());
const [newBox1] = instancesDifference.keys();
@@ -800,7 +952,7 @@ describe("paste target", () => {
] satisfies Instance[])
);
selectInstance(["source", "body0"]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
selectInstances([
["box1", "body0"],
["box2", "body0"],
@@ -842,7 +994,7 @@ describe("paste target", () => {
["source1", "body0"],
["source2", "body0"],
]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
selectInstances([
["box1", "body0"],
["box2", "body0"],
@@ -884,7 +1036,7 @@ describe("paste target", () => {
] satisfies Instance[])
);
selectInstance(["source", "body0"]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
selectInstances([
["box", "group", "section", "body0"],
["aside", "section", "body0"],
@@ -921,7 +1073,7 @@ describe("paste target", () => {
] satisfies Instance[])
);
selectInstance(["source", "body0"]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
selectInstance(["slot1", "body0"]);
await instanceText.onPaste?.(clipboardData);
@@ -954,7 +1106,7 @@ describe("paste target", () => {
] satisfies Instance[])
);
selectInstance(["source", "body0"]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
selectInstance(["slot1", "body0"]);
await instanceText.onPaste?.(clipboardData);
@@ -990,7 +1142,7 @@ describe("paste target", () => {
);
selectInstance(["box", "fragment", "slot1", "body0"]);
- await instanceText.onPaste?.(instanceText.onCopy?.() ?? "");
+ await instanceText.onPaste?.((await instanceText.onCopy?.()) ?? "");
expect($instances.get().get("slot1")?.children).toEqual([
{ type: "id", value: "fragment" },
@@ -1025,7 +1177,7 @@ describe("paste target", () => {
);
selectInstance(["box", "slot1", "body0"]);
- await instanceText.onPaste?.(instanceText.onCopy?.() ?? "");
+ await instanceText.onPaste?.((await instanceText.onCopy?.()) ?? "");
const fragmentId = expectSlotsShareFragment($instances.get(), [
"slot1",
@@ -1055,7 +1207,7 @@ describe("paste target", () => {
);
selectInstance(["box", "div", "fragment", "slot1", "body0"]);
- await instanceText.onPaste?.(instanceText.onCopy?.() ?? "");
+ await instanceText.onPaste?.((await instanceText.onCopy?.()) ?? "");
expect($instances.get().get("slot1")?.children).toEqual([
{ type: "id", value: "fragment" },
@@ -1088,7 +1240,7 @@ describe("paste target", () => {
] satisfies Instance[])
);
selectInstance(["source", "body0"]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
selectInstance(["div", "fragment", "slot1", "body0"]);
await instanceText.onPaste?.(clipboardData);
@@ -1123,7 +1275,7 @@ describe("paste target", () => {
] satisfies Instance[])
);
selectInstance(["box", "fragment", "slot1", "body0"]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
selectInstance(["target", "body0"]);
await instanceText.onPaste?.(clipboardData);
@@ -1166,7 +1318,7 @@ describe("paste target", () => {
] satisfies Instance[])
);
selectInstance(["box", "slot1", "body0"]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
selectInstance(["target", "body0"]);
await instanceText.onPaste?.(clipboardData);
@@ -1250,7 +1402,7 @@ describe("paste target", () => {
$props.set(props);
$resources.set(resources);
selectInstance(["box", "div", "fragment", "slot1", "body0"]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
selectInstance(["target", "body0"]);
await instanceText.onPaste?.(clipboardData);
@@ -1323,7 +1475,7 @@ describe("paste target", () => {
]);
});
- test("cuts shared slot child from all slot occurrences", () => {
+ test("cuts shared slot child from all slot occurrences", async () => {
$instances.set(
toMap([
createInstance("body0", "Body", [
@@ -1338,7 +1490,7 @@ describe("paste target", () => {
);
selectInstance(["box", "fragment", "slot1", "body0"]);
- const clipboardData = instanceText.onCut?.();
+ const clipboardData = await instanceText.onCut?.(async () => true);
expect(JSON.parse(clipboardData ?? "")).toMatchObject({
"@webstudio/instance/v0.1": {
instanceSelector: ["box", "fragment", "slot1", "body0"],
@@ -1357,7 +1509,7 @@ describe("paste target", () => {
expect($instances.get().has("box")).toBe(false);
});
- test("cuts legacy shared slot child from all slot occurrences", () => {
+ test("cuts legacy shared slot child from all slot occurrences", async () => {
$instances.set(
toMap([
createInstance("body0", "Body", [
@@ -1378,7 +1530,7 @@ describe("paste target", () => {
);
selectInstance(["box", "slot1", "body0"]);
- const clipboardData = instanceText.onCut?.();
+ const clipboardData = await instanceText.onCut?.(async () => true);
expect(JSON.parse(clipboardData ?? "")).toMatchObject({
"@webstudio/instance/v0.1": {
instanceSelector: ["box", "slot1", "body0"],
@@ -1402,7 +1554,7 @@ describe("paste target", () => {
expect($instances.get().has("box")).toBe(false);
});
- test("cuts nested shared slot child from all slot occurrences", () => {
+ test("cuts nested shared slot child from all slot occurrences", async () => {
$instances.set(
toMap([
createInstance("body0", "Body", [
@@ -1418,7 +1570,7 @@ describe("paste target", () => {
);
selectInstance(["box", "div", "fragment", "slot1", "body0"]);
- const clipboardData = instanceText.onCut?.();
+ const clipboardData = await instanceText.onCut?.(async () => true);
expect(JSON.parse(clipboardData ?? "")).toMatchObject({
"@webstudio/instance/v0.1": {
instanceSelector: ["box", "div", "fragment", "slot1", "body0"],
@@ -1439,7 +1591,7 @@ describe("paste target", () => {
expect($instances.get().has("box")).toBe(false);
});
- test("cuts shared slot child and preserves shared siblings", () => {
+ test("cuts shared slot child and preserves shared siblings", async () => {
$instances.set(
toMap([
createInstance("body0", "Body", [
@@ -1458,7 +1610,7 @@ describe("paste target", () => {
);
selectInstance(["box", "fragment", "slot1", "body0"]);
- const clipboardData = instanceText.onCut?.();
+ const clipboardData = await instanceText.onCut?.(async () => true);
expect(JSON.parse(clipboardData ?? "")).toMatchObject({
"@webstudio/instance/v0.1": {
instanceSelector: ["box", "fragment", "slot1", "body0"],
@@ -1539,7 +1691,7 @@ describe("data sources", () => {
$dataSources.set(dataSources);
$props.set(props);
selectInstance(["box1", "body0"]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
selectInstance(["body0"]);
await instanceText.onPaste?.(clipboardData);
@@ -1608,7 +1760,7 @@ describe("data sources", () => {
$props.set(props);
$dataSources.set(dataSources);
selectInstance(["box2", "box1", "body0"]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
selectInstance(["box1", "body0"]);
await instanceText.onPaste?.(clipboardData);
@@ -1690,7 +1842,7 @@ describe("data sources", () => {
$props.set(props);
$dataSources.set(dataSources);
selectInstance(["list", "body"]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
selectInstance(["body"]);
await instanceText.onPaste?.(clipboardData);
@@ -1748,7 +1900,7 @@ test("when paste into copied instance insert after it", async () => {
])
);
selectInstance(["box", "body"]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
await instanceText.onPaste?.(clipboardData);
expect($instances.get()).toEqual(
@@ -1774,7 +1926,7 @@ test("prevent pasting portal into own descendants", async () => {
]);
$instances.set(instances);
selectInstance(["portal", "body"]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
selectInstance(["fragment", "portal", "body"]);
await instanceText.onPaste?.(clipboardData);
expect($instances.get()).toEqual(instances);
@@ -1796,7 +1948,7 @@ test("prevent pasting portal into copy of it", async () => {
]);
$instances.set(instances);
selectInstance(["portal1", "body"]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
selectInstance(["portal2", "body"]);
await instanceText.onPaste?.(clipboardData);
expect($instances.get()).toEqual(instances);
@@ -1818,7 +1970,7 @@ test("insert portal into its sibling", async () => {
])
);
selectInstance(["portal", "body"]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
selectInstance(["sibling", "body"]);
await instanceText.onPaste?.(clipboardData);
@@ -1860,7 +2012,7 @@ test("inserts multi-root clipboard into descendant of copied non-portal root", a
["portal", "body"],
["box", "body"],
]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
selectInstance(["target", "box", "body"]);
await instanceText.onPaste?.(clipboardData);
@@ -1892,7 +2044,7 @@ test("insert into portal fragment when portal is a target", async () => {
])
);
selectInstance(["box", "body"]);
- const clipboardData = instanceText.onCopy?.() ?? "";
+ const clipboardData = (await instanceText.onCopy?.()) ?? "";
selectInstance(["portal", "body"]);
// fragment not exists
diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.ts
index ed0eede107..2acf15baae 100644
--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts
@@ -35,7 +35,12 @@ import {
type WebstudioFragment,
isComponentDetachable,
} from "@webstudio-is/sdk";
-import { $assetFolders, $instances, $project } from "~/shared/sync/data-stores";
+import {
+ $assetFolders,
+ $instances,
+ $project,
+ readBuilderStateStores,
+} from "~/shared/sync/data-stores";
import { deleteInstanceBySelector } from "../instance-utils/mutation";
import {
$allSelectedInstanceSelectors,
@@ -71,10 +76,10 @@ import {
const invalidPasteDataMessage =
"Could not paste Webstudio instance data. The clipboard data appears to be incomplete or invalid.";
-const getTreeData = (
+const getTreeData = async (
instanceSelector: InstanceSelector,
{ showToast = true }: { showToast?: boolean } = {}
-): InstanceTransferData | undefined => {
+): Promise<InstanceTransferData | undefined> => {
const instances = $instances.get();
const [targetInstanceId] = instanceSelector;
const instance = instances.get(targetInstanceId);
@@ -144,7 +149,7 @@ const getTreeData = (
});
const resolvedAssetId =
source?.type === "expression"
- ? resolveContentBlockOccurrenceAssetId({
+ ? await resolveContentBlockOccurrenceAssetId({
source,
instanceSelector,
variableValuesByRenderScope:
@@ -501,24 +506,26 @@ const handlePasteInstance = async (clipboardData: string) => {
});
};
-const handleCopyInstance = () => {
+const handleCopyInstanceAsync = async () => {
const selectedInstanceSelectors = $allSelectedInstanceSelectors.get();
if (selectedInstanceSelectors.length === 0) {
return;
}
if (selectedInstanceSelectors.length === 1) {
- const data = getTreeData(selectedInstanceSelectors[0]);
+ const data = await getTreeData(selectedInstanceSelectors[0]);
if (data === undefined) {
return;
}
return stringify(data);
}
- const selectedData = selectedInstanceSelectors
- .map((instanceSelector) =>
- getTreeData(instanceSelector, { showToast: false })
+ const selectedData = (
+ await Promise.all(
+ selectedInstanceSelectors.map((instanceSelector) =>
+ getTreeData(instanceSelector, { showToast: false })
+ )
)
- .filter((data): data is InstanceTransferData => data !== undefined);
+ ).filter((data): data is InstanceTransferData => data !== undefined);
if (selectedData.length === 0) {
return;
}
@@ -528,30 +535,52 @@ const handleCopyInstance = () => {
return stringifyMultiRootSelection(selectedData);
};
-const handleCutInstance = () => {
+const handleCutInstanceAsync = async (
+ writeClipboard: (data: string) => Promise<boolean>
+) => {
+ // Sync stores are immutable. Validate after the final await so no queued
+ // edit can run between this check and deletion.
+ const sourceData = readBuilderStateStores();
+ const projectId = $project.get()?.id;
+ const canDeleteCopiedContent = () => {
+ if (
+ projectId !== $project.get()?.id ||
+ shallowEqual(sourceData, readBuilderStateStores()) === false
+ ) {
+ builderApi.toast.info(
+ "The project changed while copying. Nothing was removed. Try cutting again."
+ );
+ return false;
+ }
+ return true;
+ };
const selectedInstanceSelectors = $allSelectedInstanceSelectors.get();
if (selectedInstanceSelectors.length > 1) {
const instances = $instances.get();
- const selectedPaths = selectedInstanceSelectors
- .map((instanceSelector) => {
- const data = getTreeData(instanceSelector, { showToast: false });
- const instancePath =
- data === undefined
- ? undefined
- : getInstancePath(data.instanceSelector, instances);
- if (data === undefined || instancePath === undefined) {
- return;
- }
- return { data, instancePath };
- })
- .filter(
- (
- item
- ): item is {
- data: InstanceTransferData;
- instancePath: NonNullable<ReturnType<typeof getInstancePath>>;
- } => item !== undefined
- );
+ const selectedPaths = (
+ await Promise.all(
+ selectedInstanceSelectors.map(async (instanceSelector) => {
+ const data = await getTreeData(instanceSelector, {
+ showToast: false,
+ });
+ const instancePath =
+ data === undefined
+ ? undefined
+ : getInstancePath(data.instanceSelector, instances);
+ if (data === undefined || instancePath === undefined) {
+ return;
+ }
+ return { data, instancePath };
+ })
+ )
+ ).filter(
+ (
+ item
+ ): item is {
+ data: InstanceTransferData;
+ instancePath: NonNullable<ReturnType<typeof getInstancePath>>;
+ } => item !== undefined
+ );
if (selectedPaths.length === 0) {
return;
}
@@ -560,6 +589,13 @@ const handleCutInstance = () => {
reportSkippedSelectedInstances("cut");
}
const clipboardData = stringifyMultiRootSelection(selectedPathData);
+ if (
+ clipboardData === undefined ||
+ (await writeClipboard(clipboardData)) === false ||
+ canDeleteCopiedContent() === false
+ ) {
+ return;
+ }
for (const { instancePath } of sortInstancePathsForChildMutation(
selectedPaths
)) {
@@ -577,15 +613,36 @@ const handleCutInstance = () => {
if (instancePath.length === 1) {
return;
}
- const data = getTreeData(instancePath[0].instanceSelector);
+ const data = await getTreeData(instancePath[0].instanceSelector);
if (data === undefined) {
return;
}
+ const clipboardData = stringify(data);
+ if (
+ (await writeClipboard(clipboardData)) === false ||
+ canDeleteCopiedContent() === false
+ ) {
+ return;
+ }
deleteInstanceBySelector(instancePath[0].instanceSelector);
- if (data === undefined) {
+ return clipboardData;
+};
+
+const handleCopyInstance = () =>
+ $allSelectedInstanceSelectors.get().length === 0
+ ? undefined
+ : handleCopyInstanceAsync();
+
+const handleCutInstance = (
+ writeClipboard: (data: string) => Promise<boolean>
+) => {
+ if (
+ $allSelectedInstanceSelectors.get().length === 0 &&
+ $selectedInstancePath.get() === undefined
+ ) {
return;
}
- return stringify(data);
+ return handleCutInstanceAsync(writeClipboard);
};
export const instanceText = {
diff --git a/apps/builder/app/shared/nano-states/props.test.tsx b/apps/builder/app/shared/nano-states/props.test.tsx
index 2437109169..d9e779a244 100644
--- a/apps/builder/app/shared/nano-states/props.test.tsx
+++ b/apps/builder/app/shared/nano-states/props.test.tsx
@@ -1,9 +1,9 @@
-import { beforeEach, expect, test } from "vitest";
-import { cleanStores } from "nanostores";
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { createDefaultPages } from "@webstudio-is/project-build";
import { setEnv } from "@webstudio-is/feature-flags";
import {
type DataSource,
+ encodeDataSourceVariable,
type Instance,
ROOT_INSTANCE_ID,
type Resource,
@@ -22,9 +22,9 @@ import {
$resources,
} from "../sync/data-stores";
import {
- __testing__,
$propValuesByInstanceSelector,
$variableValuesByInstanceSelector,
+ subscribeResourceRequestPlan,
} from "./props";
import { $dataSourceVariables } from "./variables";
import { $selectedPageId } from "./pages";
@@ -49,8 +49,6 @@ const Fragment = createTemplateComponentFixture("Fragment");
const Slot = createTemplateComponentFixture("Slot");
const Text = createTemplateComponentFixture("Text");
-const { $computedResourceRequests } = __testing__;
-
const initialSystem = {
origin: "https://undefined.wstd.work",
params: {},
@@ -58,6 +56,8 @@ const initialSystem = {
search: {},
};
+const waitForStores = () => new Promise((resolve) => setTimeout(resolve, 20));
+
registerContainers();
setEnv("*");
@@ -86,6 +86,9 @@ const selectPageRoot = (
$selectedPageId.set(defaultPages.homePageId);
};
+let unsubscribeResourceRequestPlan: (() => void) | undefined;
+let resourceRequests: readonly { name: string }[] = [];
+
beforeEach(() => {
$instances.set(new Map());
$props.set(new Map());
@@ -94,9 +97,19 @@ beforeEach(() => {
$dataSourceVariables.set(new Map());
$resourcesCache.set(new Map());
$externalContentRoots.set(new Map());
+ resourceRequests = [];
+ unsubscribeResourceRequestPlan = subscribeResourceRequestPlan((plan) => {
+ resourceRequests = plan.requests;
+ });
+});
+
+afterEach(() => {
+ unsubscribeResourceRequestPlan?.();
+ unsubscribeResourceRequestPlan = undefined;
+ resourceRequests = [];
});
-test("provides occurrence frontmatter to a repeated Content Block", () => {
+test("provides occurrence frontmatter to a repeated Content Block", async () => {
const sourceBlock: Instance = {
type: "instance",
id: "source-block",
@@ -144,7 +157,9 @@ test("provides occurrence frontmatter to a repeated Content Block", () => {
])
);
selectPageRoot(runtimeBlock.id);
+ await waitForStores();
+ await waitForStores();
expect(
$variableValuesByInstanceSelector
.get()
@@ -153,7 +168,7 @@ test("provides occurrence frontmatter to a repeated Content Block", () => {
).toEqual({ frontmatter: { title: "Occurrence title" } });
});
-test("does not reuse frontmatter from a previous Collection occurrence", () => {
+test("does not reuse frontmatter from a previous Collection occurrence", async () => {
const collectionData = new Variable("Posts", ["first", "second"]);
const collectionItem = new Parameter("Collection Item");
const document = new Parameter(contentBlockDocumentProp);
@@ -177,6 +192,7 @@ test("does not reuse frontmatter from a previous Collection occurrence", () => {
$dataSources.set(data.dataSources);
$props.set(data.props);
selectPageRoot("body");
+ await waitForStores();
const firstBlockSelector = ["block", "collection[0]", "collection", "body"];
$externalContentRoots.set(
new Map([
@@ -194,12 +210,14 @@ test("does not reuse frontmatter from a previous Collection occurrence", () => {
])
);
+ await waitForStores();
const values = $propValuesByInstanceSelector.get();
expect(
values
.get(getInstanceKey(["title", ...firstBlockSelector]))
?.get("ariaLabel")
).toBe("First title");
+ await waitForStores();
expect(
values
.get(
@@ -215,7 +233,7 @@ test("does not reuse frontmatter from a previous Collection occurrence", () => {
).toBe(false);
});
-test("does not preload resources in statically hidden subtrees", () => {
+test("does not preload resources in statically hidden subtrees", async () => {
$instances.set(
toMap([
{
@@ -232,29 +250,51 @@ test("does not preload resources in statically hidden subtrees", () => {
id: "hidden",
type: "instance",
component: "Box",
- children: [{ type: "id", value: "hidden-child" }],
+ children: [
+ { type: "id", value: "hidden-child" },
+ {
+ type: "expression",
+ value: encodeDataSourceVariable("hidden-data-source"),
+ },
+ ],
},
{
id: "hidden-child",
type: "instance",
component: "Box",
- children: [],
+ children: [
+ {
+ type: "expression",
+ value: encodeDataSourceVariable("hidden-child-data-source"),
+ },
+ ],
},
{
id: "visible",
type: "instance",
component: "Box",
- children: [],
+ children: [
+ {
+ type: "expression",
+ value: encodeDataSourceVariable("visible-data-source"),
+ },
+ ],
},
{
id: "dynamic",
type: "instance",
component: "Box",
- children: [],
+ children: [
+ {
+ type: "expression",
+ value: encodeDataSourceVariable("dynamic-data-source"),
+ },
+ ],
},
])
);
selectPageRoot("root");
+ await waitForStores();
$props.set(
toMap([
{
@@ -296,14 +336,67 @@ test("does not preload resources in statically hidden subtrees", () => {
)
);
- expect(
- $computedResourceRequests.get().map((request) => request.name)
- ).toEqual(["visible", "dynamic"]);
+ await vi.waitFor(() => {
+ expect(resourceRequests.map((request) => request.name)).toEqual([
+ "visible",
+ "dynamic",
+ ]);
+ });
+});
+
+test("preloads resources consumed by copied expressions", async () => {
+ const dataSourceId = "copied-resource-data-source";
+ $instances.set(
+ toMap([
+ {
+ id: "root",
+ type: "instance",
+ component: "Body",
+ children: [
+ {
+ type: "expression",
+ value: `${encodeDataSourceVariable(dataSourceId)}.data.year`,
+ },
+ ],
+ },
+ ])
+ );
+ selectPageRoot("root");
+ await waitForStores();
+ $dataSources.set(
+ toMap([
+ {
+ id: dataSourceId,
+ scopeInstanceId: "template-source",
+ type: "resource",
+ name: "Current date",
+ resourceId: "current-date-resource",
+ },
+ ])
+ );
+ $resources.set(
+ toMap([
+ {
+ id: "current-date-resource",
+ name: "Current date",
+ url: '"/$resources/current-date"',
+ method: "get",
+ headers: [],
+ },
+ ])
+ );
+
+ await vi.waitFor(() => {
+ expect(resourceRequests.map((request) => request.name)).toEqual([
+ "Current date",
+ ]);
+ });
});
-test("collect prop values", () => {
+test("collect prop values", async () => {
setBoxInstance("box");
selectPageRoot("box");
+ await waitForStores();
$dataSources.set(new Map());
$props.set(
toMap([
@@ -323,6 +416,7 @@ test("collect prop values", () => {
},
])
);
+ await waitForStores();
expect(
$propValuesByInstanceSelector.get().get(getInstanceKey(["box"]))
).toEqual(
@@ -331,13 +425,12 @@ test("collect prop values", () => {
["second", { name: "John" }],
])
);
-
- cleanStores($propValuesByInstanceSelector);
});
-test("compute expression prop values", () => {
+test("compute expression prop values", async () => {
setBoxInstance("box");
selectPageRoot("box");
+ await waitForStores();
$dataSources.set(
toMap([
{
@@ -382,6 +475,7 @@ test("compute expression prop values", () => {
},
])
);
+ await waitForStores();
expect(
$propValuesByInstanceSelector.get().get(getInstanceKey(["box"]))
).toEqual(
@@ -393,6 +487,7 @@ test("compute expression prop values", () => {
);
$dataSourceVariables.set(new Map([["var1", 4]]));
+ await waitForStores();
expect(
$propValuesByInstanceSelector.get().get(getInstanceKey(["box"]))
).toEqual(
@@ -402,13 +497,12 @@ test("compute expression prop values", () => {
["third", "something"],
])
);
-
- cleanStores($propValuesByInstanceSelector);
});
-test("generate action prop callbacks", () => {
+test("generate action prop callbacks", async () => {
setBoxInstance("box");
selectPageRoot("box");
+ await waitForStores();
$dataSources.set(
toMap([
{
@@ -444,23 +538,24 @@ test("generate action prop callbacks", () => {
},
])
);
+ await waitForStores();
const values1 = $propValuesByInstanceSelector
.get()
.get(getInstanceKey(["box"]));
expect(values1?.get("value")).toEqual(1);
(values1?.get("onChange") as () => void)();
+ await waitForStores();
const values2 = $propValuesByInstanceSelector
.get()
.get(getInstanceKey(["box"]));
expect(values2?.get("value")).toEqual(2);
-
- cleanStores($propValuesByInstanceSelector);
});
-test("resolve asset prop values", () => {
+test("resolve asset prop values", async () => {
setBoxInstance("box");
selectPageRoot("box");
+ await waitForStores();
$dataSources.set(new Map());
$assets.set(
toMap([
@@ -488,6 +583,7 @@ test("resolve asset prop values", () => {
},
])
);
+ await waitForStores();
expect(
$propValuesByInstanceSelector.get().get(getInstanceKey(["box"]))
).toEqual(
@@ -496,13 +592,12 @@ test("resolve asset prop values", () => {
["myAsset", "/cgi/asset/my-file.jpg"],
])
);
-
- cleanStores($propValuesByInstanceSelector);
});
-test("resolve page prop values", () => {
+test("resolve page prop values", async () => {
setBoxInstance("box");
selectPageRoot("box");
+ await waitForStores();
$dataSources.set(new Map());
$props.set(
toMap([
@@ -515,14 +610,13 @@ test("resolve page prop values", () => {
},
])
);
+ await waitForStores();
expect(
$propValuesByInstanceSelector.get().get(getInstanceKey(["box"]))
).toEqual(new Map<string, unknown>([["myPage", "/"]]));
-
- cleanStores($propValuesByInstanceSelector);
});
-test("compute expression from collection items", () => {
+test("compute expression from collection items", async () => {
$instances.set(
toMap([
{
@@ -540,6 +634,7 @@ test("compute expression from collection items", () => {
])
);
selectPageRoot("list");
+ await waitForStores();
$dataSources.set(
toMap([
{
@@ -575,6 +670,7 @@ test("compute expression from collection items", () => {
},
])
);
+ await waitForStores();
expect($propValuesByInstanceSelector.get()).toEqual(
new Map([
[
@@ -595,11 +691,9 @@ test("compute expression from collection items", () => {
],
])
);
-
- cleanStores($propValuesByInstanceSelector);
});
-test("compute expression from object collection items", () => {
+test("compute expression from object collection items", async () => {
const dataVariable = new Variable("dataVariable", {
first: "orange",
second: "apple",
@@ -621,8 +715,10 @@ test("compute expression from object collection items", () => {
$dataSources.set(data.dataSources);
$props.set(data.props);
selectPageRoot("bodyId");
+ await waitForStores();
$dataSourceVariables.set(new Map([]));
+ await waitForStores();
expect($propValuesByInstanceSelector.get()).toEqual(
new Map([
[getInstanceKey(["bodyId"]), new Map<string, unknown>([])],
@@ -661,11 +757,9 @@ test("compute expression from object collection items", () => {
],
])
);
-
- cleanStores($propValuesByInstanceSelector);
});
-test("compute prop values inside collection without item parameter", () => {
+test("compute prop values inside collection without item parameter", async () => {
$instances.set(
toMap([
{
@@ -683,6 +777,7 @@ test("compute prop values inside collection without item parameter", () => {
])
);
selectPageRoot("list");
+ await waitForStores();
$dataSources.set(new Map());
$props.set(
toMap([
@@ -702,6 +797,7 @@ test("compute prop values inside collection without item parameter", () => {
},
])
);
+ await waitForStores();
expect($propValuesByInstanceSelector.get()).toEqual(
new Map([
[
@@ -718,11 +814,9 @@ test("compute prop values inside collection without item parameter", () => {
],
])
);
-
- cleanStores($propValuesByInstanceSelector);
});
-test("access parameter value from variables values", () => {
+test("access parameter value from variables values", async () => {
$instances.set(
toMap([
{
@@ -734,6 +828,7 @@ test("access parameter value from variables values", () => {
])
);
selectPageRoot("body");
+ await waitForStores();
$dataSources.set(
toMap([
{
@@ -756,6 +851,7 @@ test("access parameter value from variables values", () => {
},
])
);
+ await waitForStores();
expect($propValuesByInstanceSelector.get()).toEqual(
new Map([
[
@@ -764,15 +860,14 @@ test("access parameter value from variables values", () => {
],
])
);
-
- cleanStores($propValuesByInstanceSelector);
});
-test("compute props bound to resource variables", () => {
+test("compute props bound to resource variables", async () => {
$instances.set(
toMap([{ id: "body", type: "instance", component: "Body", children: [] }])
);
selectPageRoot("body");
+ await waitForStores();
$dataSources.set(
toMap([
{
@@ -814,19 +909,19 @@ test("compute props bound to resource variables", () => {
},
])
);
- expect($propValuesByInstanceSelector.get()).toEqual(
- new Map([
- [
- getInstanceKey(["body"]),
- new Map<string, unknown>([["resource", "my-value"]]),
- ],
- ])
- );
-
- cleanStores($propValuesByInstanceSelector);
+ await vi.waitFor(() => {
+ expect($propValuesByInstanceSelector.get()).toEqual(
+ new Map([
+ [
+ getInstanceKey(["body"]),
+ new Map<string, unknown>([["resource", "my-value"]]),
+ ],
+ ])
+ );
+ });
});
-test("compute instance text content when plain text", () => {
+test("compute instance text content when plain text", async () => {
$instances.set(
toMap([
{
@@ -862,6 +957,8 @@ test("compute instance text content when plain text", () => {
])
);
selectPageRoot("body");
+ await waitForStores();
+ await waitForStores();
expect($propValuesByInstanceSelector.get()).toEqual(
new Map([
[getInstanceKey(["body"]), new Map<string, unknown>()],
@@ -876,11 +973,9 @@ test("compute instance text content when plain text", () => {
],
])
);
-
- cleanStores($propValuesByInstanceSelector);
});
-test("compute instance text content bound to expression", () => {
+test("compute instance text content bound to expression", async () => {
$instances.set(
toMap([
{
@@ -911,6 +1006,8 @@ test("compute instance text content bound to expression", () => {
])
);
selectPageRoot("body");
+ await waitForStores();
+ await waitForStores();
expect($propValuesByInstanceSelector.get()).toEqual(
new Map([
[getInstanceKey(["body"]), new Map<string, unknown>()],
@@ -920,11 +1017,9 @@ test("compute instance text content bound to expression", () => {
],
])
);
-
- cleanStores($propValuesByInstanceSelector);
});
-test("does not collapse mixed expression and element children into text", () => {
+test("does not collapse mixed expression and element children into text", async () => {
$instances.set(
toMap([
{
@@ -952,14 +1047,13 @@ test("does not collapse mixed expression and element children into text", () =>
);
selectPageRoot("body");
+ await waitForStores();
expect(
$propValuesByInstanceSelector.get().get(getInstanceKey(["mixed", "body"]))
).toEqual(new Map());
-
- cleanStores($propValuesByInstanceSelector);
});
-test("use page system values in props", () => {
+test("use page system values in props", async () => {
const systemParameter = new Parameter("system");
const data = renderData(
<Body
@@ -973,6 +1067,7 @@ test("use page system values in props", () => {
$dataSources.set(data.dataSources);
$props.set(data.props);
selectPageRoot("bodyId", systemParameterId);
+ await waitForStores();
expect($propValuesByInstanceSelector.get()).toEqual(
new Map([
[
@@ -985,7 +1080,7 @@ test("use page system values in props", () => {
);
});
-test("compute props with global variables", () => {
+test("compute props with global variables", async () => {
const rootVariable = new Variable("rootVariable", "root value");
const data = renderData(
<ws.root ws:id={ROOT_INSTANCE_ID} vars={expression`${rootVariable}`}>
@@ -999,6 +1094,7 @@ test("compute props with global variables", () => {
$dataSources.set(data.dataSources);
$props.set(data.props);
selectPageRoot("bodyId");
+ await waitForStores();
expect($propValuesByInstanceSelector.get()).toEqual(
new Map([
[getInstanceKey(["bodyId"]), new Map<string, unknown>()],
@@ -1010,7 +1106,7 @@ test("compute props with global variables", () => {
);
});
-test("use global system values in props", () => {
+test("use global system values in props", async () => {
const data = renderData(
<Body ws:id="bodyId" data-origin={expression`$ws$system.origin`}></Body>
);
@@ -1019,6 +1115,7 @@ test("use global system values in props", () => {
$dataSources.set(data.dataSources);
$props.set(data.props);
selectPageRoot("bodyId");
+ await waitForStores();
expect($propValuesByInstanceSelector.get()).toEqual(
new Map([
[
@@ -1031,7 +1128,7 @@ test("use global system values in props", () => {
);
});
-test("compute variable values for page root", () => {
+test("compute variable values for page root", async () => {
const bodyVariable = new Variable("bodyVariable", "initial");
const data = renderData(
<Body ws:id="bodyId" vars={expression`${bodyVariable}`}></Body>
@@ -1042,6 +1139,7 @@ test("compute variable values for page root", () => {
const [dataSourceId] = data.dataSources.keys();
selectPageRoot("bodyId");
$dataSourceVariables.set(new Map([[dataSourceId, "success"]]));
+ await waitForStores();
expect(
$variableValuesByInstanceSelector
.get()
@@ -1054,7 +1152,7 @@ test("compute variable values for page root", () => {
);
});
-test("nest variable values from global root to current instance", () => {
+test("nest variable values from global root to current instance", async () => {
const bodyVariable = new Variable("bodyVariable", "");
const boxVariable = new Variable("boxVariable", "");
const textVariable = new Variable("textVariable", "");
@@ -1077,6 +1175,7 @@ test("nest variable values from global root to current instance", () => {
[textVariableId, "textValue"],
])
);
+ await waitForStores();
expect($variableValuesByInstanceSelector.get()).toEqual(
new Map([
[
@@ -1110,7 +1209,7 @@ test("nest variable values from global root to current instance", () => {
);
});
-test("compute item values for collection", () => {
+test("compute item values for collection", async () => {
const dataVariable = new Variable("dataVariable", [
"apple",
"banana",
@@ -1134,6 +1233,7 @@ test("compute item values for collection", () => {
const [_dataVariableId, itemParameterId] = data.dataSources.keys();
selectPageRoot("bodyId");
$dataSourceVariables.set(new Map([]));
+ await waitForStores();
const values = $variableValuesByInstanceSelector.get();
expect(
values
@@ -1148,6 +1248,7 @@ test("compute item values for collection", () => {
)
?.get(itemParameterId)
).toEqual("apple");
+ await waitForStores();
expect(
values
.get(
@@ -1161,6 +1262,7 @@ test("compute item values for collection", () => {
)
?.get(itemParameterId)
).toEqual("banana");
+ await waitForStores();
expect(
values
.get(
@@ -1176,7 +1278,7 @@ test("compute item values for collection", () => {
).toEqual("orange");
});
-test("keeps explicitly referenced outer collection items in nested scope", () => {
+test("keeps explicitly referenced outer collection items in nested scope", async () => {
const outerItem = new Parameter("item");
const innerItem = new Parameter("item");
const data = renderData(
@@ -1193,7 +1295,7 @@ test("keeps explicitly referenced outer collection items in nested scope", () =>
$props.set(data.props);
const [outerItemId, innerItemId] = data.dataSources.keys();
selectPageRoot("bodyId");
-
+ await waitForStores();
const values = $variableValuesByInstanceSelector
.get()
.get(
@@ -1211,7 +1313,7 @@ test("keeps explicitly referenced outer collection items in nested scope", () =>
expect(values?.get(innerItemId)).toBe("inner");
});
-test("compute item values for collection with object data", () => {
+test("compute item values for collection with object data", async () => {
const dataVariable = new Variable("dataVariable", {
first: "apple",
second: "banana",
@@ -1235,6 +1337,7 @@ test("compute item values for collection with object data", () => {
const [_dataVariableId, itemParameterId] = data.dataSources.keys();
selectPageRoot("bodyId");
$dataSourceVariables.set(new Map([]));
+ await waitForStores();
const values = $variableValuesByInstanceSelector.get();
expect(
values
@@ -1249,6 +1352,7 @@ test("compute item values for collection with object data", () => {
)
?.get(itemParameterId)
).toEqual("apple");
+ await waitForStores();
expect(
values
.get(
@@ -1262,6 +1366,7 @@ test("compute item values for collection with object data", () => {
)
?.get(itemParameterId)
).toEqual("banana");
+ await waitForStores();
expect(
values
.get(
@@ -1277,7 +1382,7 @@ test("compute item values for collection with object data", () => {
).toEqual("orange");
});
-test("compute item values for collection with nested object data", () => {
+test("compute item values for collection with nested object data", async () => {
const dataVariable = new Variable("dataVariable", {
user1: { name: "Alice", age: 30 },
user2: { name: "Bob", age: 25 },
@@ -1300,6 +1405,7 @@ test("compute item values for collection with nested object data", () => {
const [_dataVariableId, itemParameterId] = data.dataSources.keys();
selectPageRoot("bodyId");
$dataSourceVariables.set(new Map([]));
+ await waitForStores();
const values = $variableValuesByInstanceSelector.get();
expect(
values
@@ -1314,6 +1420,7 @@ test("compute item values for collection with nested object data", () => {
)
?.get(itemParameterId)
).toEqual({ name: "Alice", age: 30 });
+ await waitForStores();
expect(
values
.get(
@@ -1329,7 +1436,7 @@ test("compute item values for collection with nested object data", () => {
).toEqual({ name: "Bob", age: 25 });
});
-test("compute inherited item values inside collection without item parameter", () => {
+test("compute inherited item values inside collection without item parameter", async () => {
const dataVariable = new Variable("dataVariable", [
{ items: ["apple", "banana"] },
]);
@@ -1358,6 +1465,7 @@ test("compute inherited item values inside collection without item parameter", (
)?.id;
selectPageRoot("bodyId");
$dataSourceVariables.set(new Map([]));
+ await waitForStores();
const values = $variableValuesByInstanceSelector.get();
expect(
values
@@ -1378,7 +1486,7 @@ test("compute inherited item values inside collection without item parameter", (
});
});
-test("compute resource variable values", () => {
+test("compute resource variable values", async () => {
const resourceVariable = new ResourceValue("resourceVariable", {
url: expression`""`,
method: "get",
@@ -1402,15 +1510,17 @@ test("compute resource variable values", () => {
searchParams: [],
});
$resourcesCache.set(new Map([[key, "my-value"]]));
- expect(
- $variableValuesByInstanceSelector
- .get()
- .get(getInstanceKey(["bodyId", ROOT_INSTANCE_ID]))
- ?.get(resourceVariableId)
- ).toEqual("my-value");
+ await vi.waitFor(() => {
+ expect(
+ $variableValuesByInstanceSelector
+ .get()
+ .get(getInstanceKey(["bodyId", ROOT_INSTANCE_ID]))
+ ?.get(resourceVariableId)
+ ).toEqual("my-value");
+ });
});
-test("stop variables lookup outside of slots", () => {
+test("stop variables lookup outside of slots", async () => {
const bodyVariable = new Variable("bodyVariable", "body");
const slotVariable = new Variable("slotVariable", "slot");
const boxVariable = new Variable("boxVariable", "box");
@@ -1427,6 +1537,7 @@ test("stop variables lookup outside of slots", () => {
$dataSources.set(data.dataSources);
$props.set(data.props);
selectPageRoot("bodyId");
+ await waitForStores();
const values = $variableValuesByInstanceSelector.get();
expect(
values.get(getInstanceKey(["slotId", "bodyId", ROOT_INSTANCE_ID]))?.size
@@ -1450,7 +1561,7 @@ test("stop variables lookup outside of slots", () => {
).toEqual(2);
});
-test("compute parameter and resource variables without values to make it available in scope", () => {
+test("compute parameter and resource variables without values to make it available in scope", async () => {
const resourceVariable = new ResourceValue("resourceVariable", {
url: expression`""`,
method: "get",
@@ -1469,6 +1580,7 @@ test("compute parameter and resource variables without values to make it availab
$props.set(data.props);
const [resourceVariableId, parameterVariableId] = data.dataSources.keys();
selectPageRoot("bodyId");
+ await waitForStores();
const values = $variableValuesByInstanceSelector
.get()
.get(getInstanceKey(["bodyId", ROOT_INSTANCE_ID]));
@@ -1476,7 +1588,7 @@ test("compute parameter and resource variables without values to make it availab
expect(values?.get(parameterVariableId)).toEqual(undefined);
});
-test("provide page system variable value", () => {
+test("provide page system variable value", async () => {
const system = new Parameter("system");
const data = renderData(
<Body ws:id="bodyId" vars={expression`${system}`}></Body>
@@ -1486,6 +1598,7 @@ test("provide page system variable value", () => {
$props.set(data.props);
const [systemId] = data.dataSources.keys();
selectPageRoot("bodyId", systemId);
+ await waitForStores();
expect(
$variableValuesByInstanceSelector
.get()
@@ -1495,6 +1608,7 @@ test("provide page system variable value", () => {
updateCurrentSystem({
params: { slug: "my-post" },
});
+ await waitForStores();
expect(
$variableValuesByInstanceSelector
.get()
@@ -1508,7 +1622,7 @@ test("provide page system variable value", () => {
});
});
-test("provide global system variable value", () => {
+test("provide global system variable value", async () => {
const data = renderData(
<Body ws:id="bodyId" vars={expression`$ws$system`}></Body>
);
@@ -1517,6 +1631,7 @@ test("provide global system variable value", () => {
$props.set(data.props);
selectPageRoot("bodyId");
$systemDataByPage.set(new Map());
+ await waitForStores();
expect($variableValuesByInstanceSelector.get()).toEqual(
new Map([
[
@@ -1532,6 +1647,7 @@ test("provide global system variable value", () => {
updateCurrentSystem({
params: { slug: "my-post" },
});
+ await waitForStores();
const updatedSystem = {
params: { slug: "my-post" },
pathname: "/",
@@ -1552,7 +1668,7 @@ test("provide global system variable value", () => {
);
});
-test("keeps shadowed variables addressable by id in nested scope", () => {
+test("keeps shadowed variables addressable by id in nested scope", async () => {
const bodyVariable = new Variable("myVariable", "body");
const boxVariable = new Variable("myVariable", "box");
const data = renderData(
@@ -1566,6 +1682,7 @@ test("keeps shadowed variables addressable by id in nested scope", () => {
const [bodyVariableId, boxVariableId] = data.dataSources.keys();
selectPageRoot("bodyId");
$systemDataByPage.set(new Map());
+ await waitForStores();
expect($variableValuesByInstanceSelector.get()).toEqual(
new Map([
[
@@ -1591,7 +1708,7 @@ test("keeps shadowed variables addressable by id in nested scope", () => {
);
});
-test("inherit variables from global root", () => {
+test("inherit variables from global root", async () => {
const rootVariable = new Variable("rootVariable", "root");
const boxVariable = new Variable("myVariable", "box");
const data = renderData(
@@ -1607,6 +1724,7 @@ test("inherit variables from global root", () => {
$props.set(data.props);
const [rootVariableId, boxVariableId] = data.dataSources.keys();
selectPageRoot("bodyId");
+ await waitForStores();
expect($variableValuesByInstanceSelector.get()).toEqual(
new Map([
[
@@ -1635,7 +1753,7 @@ test("inherit variables from global root", () => {
);
});
-test("inherit variables from global root inside slots", () => {
+test("inherit variables from global root inside slots", async () => {
const rootVariable = new Variable("rootVariable", "root");
const bodyVariable = new Variable("bodyVariable", "body");
const boxVariable = new Variable("myVariable", "box");
@@ -1657,6 +1775,7 @@ test("inherit variables from global root inside slots", () => {
const [rootVariableId, _bodyVariableId, boxVariableId] =
data.dataSources.keys();
selectPageRoot("bodyId");
+ await waitForStores();
expect(
$variableValuesByInstanceSelector
.get()
diff --git a/apps/builder/app/shared/nano-states/props.ts b/apps/builder/app/shared/nano-states/props.ts
index edf170006b..36c93f9949 100644
--- a/apps/builder/app/shared/nano-states/props.ts
+++ b/apps/builder/app/shared/nano-states/props.ts
@@ -1,10 +1,10 @@
-import { computed } from "nanostores";
+import { atom, computed } from "nanostores";
import type {
DataSource,
Instance,
Prop,
- ResourceRequest,
ImageAsset,
+ Resource,
} from "@webstudio-is/sdk";
import {
decodeDataSourceVariable,
@@ -12,6 +12,7 @@ import {
collectionComponent,
blockComponent,
contentBlockDocumentProp,
+ getPageResourceRootIds,
portalComponent,
ROOT_INSTANCE_ID,
SYSTEM_VARIABLE_ID,
@@ -37,8 +38,8 @@ import { computeExpression } from "@webstudio-is/project-build/runtime";
import { $currentSystem } from "../system";
import {
$resourcesCache,
- computeResourceRequest,
- getResourceKey,
+ type ResourceRequestPlan,
+ computeResourceRequestPlan,
preloadResources,
} from "../resources";
import {
@@ -204,6 +205,98 @@ const $resourceVariableValues = computed(
}
);
+type ResourceRequestPlanInput = {
+ rootResourceIds: Iterable<Resource["id"]>;
+ resources: ReturnType<typeof $resources.get>;
+ dataSources: ReturnType<typeof $dataSources.get>;
+ values: ReturnType<typeof $resourceVariableValues.get>;
+ resourceCache: ReturnType<typeof $resourcesCache.get>;
+};
+
+const getResourceRequestPlanInput = ({
+ page,
+ instances,
+ props,
+ dataSources,
+ resources,
+ values,
+ resourceCache,
+}: {
+ page: ReturnType<typeof $selectedPage.get>;
+ instances: ReturnType<typeof $instances.get>;
+ props: ReturnType<typeof $props.get>;
+ dataSources: ReturnType<typeof $dataSources.get>;
+ resources: ReturnType<typeof $resources.get>;
+ values: ReturnType<typeof $resourceVariableValues.get>;
+ resourceCache: ReturnType<typeof $resourcesCache.get>;
+}): ResourceRequestPlanInput => {
+ if (page === undefined) {
+ return {
+ rootResourceIds: [],
+ resources,
+ dataSources,
+ values,
+ resourceCache,
+ };
+ }
+ const instanceIds = findTreeInstanceIdsExcludingStaticHidden({
+ instances,
+ props,
+ rootInstanceId: page.rootInstanceId,
+ });
+ const visibleInstances = new Map<Instance["id"], Instance>();
+ for (const instanceId of instanceIds) {
+ const instance = instances.get(instanceId);
+ if (instance !== undefined) {
+ visibleInstances.set(instanceId, instance);
+ }
+ }
+ const rootResourceIds = getPageResourceRootIds({
+ page,
+ instances: visibleInstances,
+ props,
+ dataSources,
+ });
+ return {
+ rootResourceIds,
+ resources,
+ dataSources,
+ values,
+ resourceCache,
+ };
+};
+
+const $resourceRequestPlanInput = computed(
+ [
+ $selectedPage,
+ $instances,
+ $props,
+ $dataSources,
+ $resources,
+ $resourceVariableValues,
+ $resourcesCache,
+ ],
+ (page, instances, props, dataSources, resources, values, resourceCache) =>
+ getResourceRequestPlanInput({
+ page,
+ instances,
+ props,
+ dataSources,
+ resources,
+ values,
+ resourceCache,
+ })
+);
+
+const createEmptyResourceRequestPlan = (): ResourceRequestPlan => ({
+ requests: [],
+ documents: new Map(),
+});
+
+const $resourceRequestPlan = atom<ResourceRequestPlan>(
+ createEmptyResourceRequestPlan()
+);
+
/**
* values of all variables without computing scope specifics like collections
* simplified version of variable values by instance selector
@@ -212,21 +305,11 @@ export const $unscopedVariableValues = computed(
[
$dataSources,
$dataSourceVariables,
- $resources,
- $resourceVariableValues,
- $resourcesCache,
+ $resourceRequestPlan,
$selectedPage,
$currentSystem,
],
- (
- dataSources,
- dataSourceVariables,
- resources,
- resourceVariableValues,
- resourcesCache,
- page,
- system
- ) => {
+ (dataSources, dataSourceVariables, resourceRequestPlan, page, system) => {
const values = new Map<string, unknown>();
// support global system
values.set(SYSTEM_VARIABLE_ID, system);
@@ -246,17 +329,10 @@ export const $unscopedVariableValues = computed(
values.set(dataSourceId, value);
}
if (dataSource.type === "resource") {
- const resource = resources.get(dataSource.resourceId);
- if (resource) {
- const resourceRequest = computeResourceRequest(
- resource,
- resourceVariableValues
- );
- values.set(
- dataSourceId,
- resourcesCache.get(getResourceKey(resourceRequest))
- );
- }
+ values.set(
+ dataSourceId,
+ resourceRequestPlan.documents.get(dataSource.resourceId)
+ );
}
}
return values;
@@ -269,7 +345,7 @@ export const $unscopedVariableValues = computed(
* essential to support collections which provide different values in each item
* for same variables
*/
-export const $propValuesByInstanceSelector = computed(
+const $propValuesInput = computed(
[
$instances,
$props,
@@ -289,139 +365,177 @@ export const $propValuesByInstanceSelector = computed(
assets,
uploadingFilesDataStore,
externalContentRoots
- ) => {
- // already includes global variables
- const variableValues = new Map<string, unknown>(unscopedVariableValues);
-
- let propsList = Array.from(props.values());
-
- // ignore asset and page props when params is not provided
- if (pages) {
- const uploadingImageAssets = uploadingFilesDataStore
- .map(uploadingFileDataToAsset)
- .filter(<T>(value: T): value is NonNullable<T> => value !== undefined)
- .filter((asset): asset is ImageAsset => asset.type === "image");
-
- // use whole props list to let access hash props from other pages and instances
- propsList = normalizeProps({
- props: propsList,
- assetBaseUrl,
- assets,
- uploadingImageAssets,
- pages,
- source: "canvas",
- });
- }
- // collect props and group by instances
- const propsByInstanceId = mapGroupBy(propsList, (prop) => prop.instanceId);
-
- // traverse instances tree and compute props within each instance
- const propValuesByInstanceSelector = new Map<
- Instance["id"],
- Map<Prop["name"], unknown>
- >();
- if (page === undefined) {
- return propValuesByInstanceSelector;
+ ) => ({
+ instances,
+ props,
+ page,
+ unscopedVariableValues,
+ pages,
+ assets,
+ uploadingFilesDataStore,
+ externalContentRoots,
+ })
+);
+
+const computePropValues = async ({
+ instances,
+ props,
+ page,
+ unscopedVariableValues,
+ pages,
+ assets,
+ uploadingFilesDataStore,
+ externalContentRoots,
+}: ReturnType<typeof $propValuesInput.get>) => {
+ // already includes global variables
+ const variableValues = new Map<string, unknown>(unscopedVariableValues);
+
+ let propsList = Array.from(props.values());
+
+ // ignore asset and page props when params is not provided
+ if (pages) {
+ const uploadingImageAssets = uploadingFilesDataStore
+ .map(uploadingFileDataToAsset)
+ .filter(<T>(value: T): value is NonNullable<T> => value !== undefined)
+ .filter((asset): asset is ImageAsset => asset.type === "image");
+
+ // use whole props list to let access hash props from other pages and instances
+ propsList = normalizeProps({
+ props: propsList,
+ assetBaseUrl,
+ assets,
+ uploadingImageAssets,
+ pages,
+ source: "canvas",
+ });
+ }
+ // collect props and group by instances
+ const propsByInstanceId = mapGroupBy(propsList, (prop) => prop.instanceId);
+
+ // traverse instances tree and compute props within each instance
+ const propValuesByInstanceSelector = new Map<
+ Instance["id"],
+ Map<Prop["name"], unknown>
+ >();
+ if (page === undefined) {
+ return propValuesByInstanceSelector;
+ }
+ const traverseInstances = async (instanceSelector: InstanceSelector) => {
+ const [instanceId] = instanceSelector;
+ const instance = instances.get(instanceId);
+ if (instance === undefined) {
+ return;
}
- const traverseInstances = (instanceSelector: InstanceSelector) => {
- const [instanceId] = instanceSelector;
- const instance = instances.get(instanceId);
- if (instance === undefined) {
- return;
- }
- const propValues = new Map<Prop["name"], unknown>();
- const props = propsByInstanceId.get(instanceId);
- const parameters = new Map<Prop["name"], DataSource["id"]>();
+ const propValues = new Map<Prop["name"], unknown>();
+ const props = propsByInstanceId.get(instanceId);
+ const parameters = new Map<Prop["name"], DataSource["id"]>();
- if (props) {
- for (const prop of props) {
- // at this point asset and page either already converted to string
- // or can be ignored
- if (prop.type === "asset" || prop.type === "page") {
- continue;
- }
- if (prop.type === "expression") {
- const value = computeExpression(prop.value, variableValues);
- if (value !== undefined) {
- propValues.set(prop.name, value);
- }
- continue;
- }
- if (prop.type === "action") {
- const action = getAction(prop, variableValues);
- if (typeof action === "function") {
- propValues.set(prop.name, action);
- }
- continue;
+ if (props) {
+ for (const prop of props) {
+ // at this point asset and page either already converted to string
+ // or can be ignored
+ if (prop.type === "asset" || prop.type === "page") {
+ continue;
+ }
+ if (prop.type === "expression") {
+ const value = await computeExpression(prop.value, variableValues);
+ if (value !== undefined) {
+ propValues.set(prop.name, value);
}
- if (prop.type === "parameter") {
- parameters.set(prop.name, prop.value);
- continue;
+ continue;
+ }
+ if (prop.type === "action") {
+ const action = getAction(prop, variableValues);
+ if (typeof action === "function") {
+ propValues.set(prop.name, action);
}
- propValues.set(prop.name, prop.value);
+ continue;
}
+ if (prop.type === "parameter") {
+ parameters.set(prop.name, prop.value);
+ continue;
+ }
+ propValues.set(prop.name, prop.value);
}
+ }
- setContentBlockDocumentValue({
- instance,
- instanceSelector,
- parameters,
- propsByInstanceId,
- variableValues,
- externalContentRoots,
- });
+ setContentBlockDocumentValue({
+ instance,
+ instanceSelector,
+ parameters,
+ propsByInstanceId,
+ variableValues,
+ externalContentRoots,
+ });
- propValuesByInstanceSelector.set(
- getInstanceKey(instanceSelector),
- propValues
- );
-
- if (instance.component === collectionComponent) {
- const originalData = propValues.get("data");
- const itemVariableId = parameters.get("item");
- const itemKeyVariableId = parameters.get("itemKey");
- if (originalData) {
- for (const [key, value] of getCollectionEntries(originalData)) {
- if (itemVariableId !== undefined) {
- variableValues.set(itemVariableId, value);
- }
- if (itemKeyVariableId !== undefined) {
- variableValues.set(itemKeyVariableId, key);
- }
- for (const child of instance.children) {
- if (child.type === "id") {
- const indexId = getIndexedInstanceId(instanceId, key);
- traverseInstances([child.value, indexId, ...instanceSelector]);
- }
+ propValuesByInstanceSelector.set(
+ getInstanceKey(instanceSelector),
+ propValues
+ );
+
+ if (instance.component === collectionComponent) {
+ const originalData = propValues.get("data");
+ const itemVariableId = parameters.get("item");
+ const itemKeyVariableId = parameters.get("itemKey");
+ if (originalData) {
+ for (const [key, value] of getCollectionEntries(originalData)) {
+ if (itemVariableId !== undefined) {
+ variableValues.set(itemVariableId, value);
+ }
+ if (itemKeyVariableId !== undefined) {
+ variableValues.set(itemKeyVariableId, key);
+ }
+ for (const child of instance.children) {
+ if (child.type === "id") {
+ const indexId = getIndexedInstanceId(instanceId, key);
+ await traverseInstances([
+ child.value,
+ indexId,
+ ...instanceSelector,
+ ]);
}
}
}
- return;
}
- for (const child of instance.children) {
- // plain text can be edited from props panel
- if (child.type === "text" && instance.children.length === 1) {
- propValues.set(textContentAttribute, child.value);
- }
- if (child.type === "expression" && instance.children.length === 1) {
- const value = computeExpression(child.value, variableValues);
- if (value !== undefined) {
- propValues.set(textContentAttribute, value);
- }
- }
- if (child.type === "id") {
- traverseInstances([child.value, ...instanceSelector]);
+ return;
+ }
+ for (const child of instance.children) {
+ // plain text can be edited from props panel
+ if (child.type === "text" && instance.children.length === 1) {
+ propValues.set(textContentAttribute, child.value);
+ }
+ if (child.type === "expression" && instance.children.length === 1) {
+ const value = await computeExpression(child.value, variableValues);
+ if (value !== undefined) {
+ propValues.set(textContentAttribute, value);
}
}
- };
+ if (child.type === "id") {
+ await traverseInstances([child.value, ...instanceSelector]);
+ }
+ }
+ };
- traverseInstances([page.rootInstanceId]);
+ await traverseInstances([page.rootInstanceId]);
- return propValuesByInstanceSelector;
- }
+ return propValuesByInstanceSelector;
+};
+
+export const $propValuesByInstanceSelector = atom(
+ new Map<string, Map<Prop["name"], unknown>>()
);
+let propValuesRevision = 0;
+$propValuesInput.subscribe((input) => {
+ const revision = ++propValuesRevision;
+ void computePropValues(input).then((values) => {
+ if (revision === propValuesRevision) {
+ $propValuesByInstanceSelector.set(values);
+ }
+ });
+});
+
export const $propValuesByInstanceSelectorWithMemoryProps = computed(
[$propValuesByInstanceSelector, $memoryProps, $isPreviewMode],
(propValuesByInstanceSelector, memoryProps, isPreviewMode) => {
@@ -443,16 +557,14 @@ export const $propValuesByInstanceSelectorWithMemoryProps = computed(
}
);
-export const $variableValuesByInstanceSelector = computed(
+const $variableValuesInput = computed(
[
$instances,
$props,
$selectedPage,
$dataSources,
$dataSourceVariables,
- $resources,
- $resourceVariableValues,
- $resourcesCache,
+ $resourceRequestPlan,
$currentSystem,
$externalContentRoots,
],
@@ -462,230 +574,242 @@ export const $variableValuesByInstanceSelector = computed(
page,
dataSources,
dataSourceVariables,
- resources,
- resourceVariableValues,
- resourcesCache,
+ resourceRequestPlan,
system,
externalContentRoots
- ) => {
- const propsByInstanceId = mapGroupBy(
- props.values(),
- (prop) => prop.instanceId
- );
+ ) => ({
+ instances,
+ props,
+ page,
+ dataSources,
+ dataSourceVariables,
+ resourceRequestPlan,
+ system,
+ externalContentRoots,
+ })
+);
- const variablesByInstanceId = mapGroupBy(
- dataSources.values(),
- (dataSource) => dataSource.scopeInstanceId
- );
+const computeVariableValues = async ({
+ instances,
+ props,
+ page,
+ dataSources,
+ dataSourceVariables,
+ resourceRequestPlan,
+ system,
+ externalContentRoots,
+}: ReturnType<typeof $variableValuesInput.get>) => {
+ const propsByInstanceId = mapGroupBy(
+ props.values(),
+ (prop) => prop.instanceId
+ );
+
+ const variablesByInstanceId = mapGroupBy(
+ dataSources.values(),
+ (dataSource) => dataSource.scopeInstanceId
+ );
+
+ // traverse instances tree and compute props within each instance
+ const variableValuesByInstanceSelector = new Map<
+ Instance["id"],
+ Map<Prop["name"], unknown>
+ >();
+ if (page === undefined) {
+ return variableValuesByInstanceSelector;
+ }
- // traverse instances tree and compute props within each instance
- const variableValuesByInstanceSelector = new Map<
- Instance["id"],
- Map<Prop["name"], unknown>
- >();
- if (page === undefined) {
- return variableValuesByInstanceSelector;
+ const collectVariables = (
+ instanceSelector: InstanceSelector,
+ parentVariableValues = new Map<string, unknown>()
+ ) => {
+ const [instanceId] = instanceSelector;
+ const variableValues = new Map<string, unknown>(parentVariableValues);
+ variableValuesByInstanceSelector.set(
+ getInstanceKey(instanceSelector),
+ variableValues
+ );
+ const variables = variablesByInstanceId.get(instanceId);
+ // set global system value
+ if (instanceId === ROOT_INSTANCE_ID) {
+ variableValues.set(SYSTEM_VARIABLE_ID, system);
}
-
- const collectVariables = (
- instanceSelector: InstanceSelector,
- parentVariableValues = new Map<string, unknown>()
- ) => {
- const [instanceId] = instanceSelector;
- const variableValues = new Map<string, unknown>(parentVariableValues);
- variableValuesByInstanceSelector.set(
- getInstanceKey(instanceSelector),
- variableValues
- );
- const variables = variablesByInstanceId.get(instanceId);
- // set global system value
- if (instanceId === ROOT_INSTANCE_ID) {
- variableValues.set(SYSTEM_VARIABLE_ID, system);
- }
- if (variables) {
- for (const variable of variables) {
- if (variable.type === "variable") {
- const value = dataSourceVariables.get(variable.id);
- variableValues.set(variable.id, value ?? variable.value.value);
- }
- if (variable.type === "parameter") {
- const value = dataSourceVariables.get(variable.id);
- variableValues.set(variable.id, value);
- // set page system value
- if (variable.id === page.systemDataSourceId) {
- variableValues.set(variable.id, system);
- }
- }
- if (variable.type === "resource") {
- const resource = resources.get(variable.resourceId);
- if (resource) {
- const resourceRequest = computeResourceRequest(
- resource,
- resourceVariableValues
- );
- variableValues.set(
- variable.id,
- resourcesCache.get(getResourceKey(resourceRequest))
- );
- }
- }
+ if (variables) {
+ for (const variable of variables) {
+ if (variable.type === "variable") {
+ const value = dataSourceVariables.get(variable.id);
+ variableValues.set(variable.id, value ?? variable.value.value);
}
- }
- return variableValues;
- };
-
- const traverseInstances = (
- instanceSelector: InstanceSelector,
- parentVariableValues = new Map<string, unknown>()
- ) => {
- let variableValues = collectVariables(
- instanceSelector,
- parentVariableValues
- );
-
- const [instanceId] = instanceSelector;
- const propValues = new Map<Prop["name"], unknown>();
- const props = propsByInstanceId.get(instanceId);
- const parameters = new Map<Prop["name"], DataSource["id"]>();
- if (props) {
- for (const prop of props) {
- if (
- prop.type === "asset" ||
- prop.type === "page" ||
- prop.type === "action"
- ) {
- continue;
- }
- if (prop.type === "expression") {
- const value = computeExpression(prop.value, variableValues);
- if (value !== undefined) {
- propValues.set(prop.name, value);
- }
- continue;
- }
- if (prop.type === "parameter") {
- parameters.set(prop.name, prop.value);
- continue;
+ if (variable.type === "parameter") {
+ const value = dataSourceVariables.get(variable.id);
+ variableValues.set(variable.id, value);
+ // set page system value
+ if (variable.id === page.systemDataSourceId) {
+ variableValues.set(variable.id, system);
}
- propValues.set(prop.name, prop.value);
+ }
+ if (variable.type === "resource") {
+ variableValues.set(
+ variable.id,
+ resourceRequestPlan.documents.get(variable.resourceId)
+ );
}
}
+ }
+ return variableValues;
+ };
- const instance = instances.get(instanceId);
- if (instance === undefined) {
- return;
- }
-
- setContentBlockDocumentValue({
- instance,
- instanceSelector,
- parameters,
- propsByInstanceId,
- variableValues,
- externalContentRoots,
- });
+ const traverseInstances = async (
+ instanceSelector: InstanceSelector,
+ parentVariableValues = new Map<string, unknown>()
+ ) => {
+ let variableValues = collectVariables(
+ instanceSelector,
+ parentVariableValues
+ );
- if (instance.component === collectionComponent) {
- const originalData = propValues.get("data");
- const itemVariableId = parameters.get("item");
- const itemKeyVariableId = parameters.get("itemKey");
- // prevent accessing item from collection
- if (itemVariableId !== undefined) {
- variableValues.delete(itemVariableId);
- }
- if (itemKeyVariableId !== undefined) {
- variableValues.delete(itemKeyVariableId);
+ const [instanceId] = instanceSelector;
+ const propValues = new Map<Prop["name"], unknown>();
+ const props = propsByInstanceId.get(instanceId);
+ const parameters = new Map<Prop["name"], DataSource["id"]>();
+ if (props) {
+ for (const prop of props) {
+ if (
+ prop.type === "asset" ||
+ prop.type === "page" ||
+ prop.type === "action"
+ ) {
+ continue;
}
- if (originalData) {
- for (const [key, value] of getCollectionEntries(originalData)) {
- const itemVariableValues = new Map(variableValues);
- if (itemVariableId !== undefined) {
- itemVariableValues.set(itemVariableId, value);
- }
- if (itemKeyVariableId !== undefined) {
- itemVariableValues.set(itemKeyVariableId, key);
- }
- for (const child of instance.children) {
- if (child.type === "id") {
- const indexId = getIndexedInstanceId(instanceId, key);
- traverseInstances(
- [child.value, indexId, ...instanceSelector],
- itemVariableValues
- );
- }
- }
+ if (prop.type === "expression") {
+ const value = await computeExpression(prop.value, variableValues);
+ if (value !== undefined) {
+ propValues.set(prop.name, value);
}
+ continue;
}
- return;
- }
- // reset values for slot children to let slots behave as isolated components
- if (instance.component === portalComponent) {
- // allow accessing global variables in slots
- variableValues = globalVariableValues;
- }
- for (const child of instance.children) {
- if (child.type === "id") {
- traverseInstances([child.value, ...instanceSelector], variableValues);
+ if (prop.type === "parameter") {
+ parameters.set(prop.name, prop.value);
+ continue;
}
+ propValues.set(prop.name, prop.value);
}
- };
- const globalVariableValues = collectVariables([ROOT_INSTANCE_ID]);
- traverseInstances(
- [page.rootInstanceId, ROOT_INSTANCE_ID],
- globalVariableValues
- );
- return variableValuesByInstanceSelector;
- }
-);
+ }
-const $computedResourceRequests = computed(
- [
- $selectedPage,
- $instances,
- $props,
- $dataSources,
- $resources,
- $resourceVariableValues,
- ],
- (page, instances, props, dataSources, resources, values) => {
- const computedResourceRequests: ResourceRequest[] = [];
- if (page === undefined) {
- return computedResourceRequests;
+ const instance = instances.get(instanceId);
+ if (instance === undefined) {
+ return;
}
- const instanceIds = findTreeInstanceIdsExcludingStaticHidden({
- instances,
- props,
- rootInstanceId: page.rootInstanceId,
+
+ setContentBlockDocumentValue({
+ instance,
+ instanceSelector,
+ parameters,
+ propsByInstanceId,
+ variableValues,
+ externalContentRoots,
});
- instanceIds.add(ROOT_INSTANCE_ID);
- // load only resources bound to variables on current page
- // action resources should not be loaded automatically
- for (const dataSource of dataSources.values()) {
- if (
- instanceIds.has(dataSource.scopeInstanceId ?? "") &&
- dataSource.type === "resource"
- ) {
- const resource = resources.get(dataSource.resourceId);
- if (resource) {
- computedResourceRequests.push(
- computeResourceRequest(resource, values)
- );
+
+ if (instance.component === collectionComponent) {
+ const originalData = propValues.get("data");
+ const itemVariableId = parameters.get("item");
+ const itemKeyVariableId = parameters.get("itemKey");
+ // prevent accessing item from collection
+ if (itemVariableId !== undefined) {
+ variableValues.delete(itemVariableId);
+ }
+ if (itemKeyVariableId !== undefined) {
+ variableValues.delete(itemKeyVariableId);
+ }
+ if (originalData) {
+ for (const [key, value] of getCollectionEntries(originalData)) {
+ const itemVariableValues = new Map(variableValues);
+ if (itemVariableId !== undefined) {
+ itemVariableValues.set(itemVariableId, value);
+ }
+ if (itemKeyVariableId !== undefined) {
+ itemVariableValues.set(itemKeyVariableId, key);
+ }
+ for (const child of instance.children) {
+ if (child.type === "id") {
+ const indexId = getIndexedInstanceId(instanceId, key);
+ await traverseInstances(
+ [child.value, indexId, ...instanceSelector],
+ itemVariableValues
+ );
+ }
+ }
}
}
+ return;
}
- return computedResourceRequests;
- }
+ // reset values for slot children to let slots behave as isolated components
+ if (instance.component === portalComponent) {
+ // allow accessing global variables in slots
+ variableValues = globalVariableValues;
+ }
+ for (const child of instance.children) {
+ if (child.type === "id") {
+ await traverseInstances(
+ [child.value, ...instanceSelector],
+ variableValues
+ );
+ }
+ }
+ };
+ const globalVariableValues = collectVariables([ROOT_INSTANCE_ID]);
+ await traverseInstances(
+ [page.rootInstanceId, ROOT_INSTANCE_ID],
+ globalVariableValues
+ );
+ return variableValuesByInstanceSelector;
+};
+
+export const $variableValuesByInstanceSelector = atom(
+ new Map<string, Map<string, unknown>>()
);
-/**
- * subscribe to all resources changes
- * load them with currently available variable values
- * and store in cache
- */
-export const subscribeResources = () => {
- return $computedResourceRequests.subscribe((computedResourceRequests) => {
- preloadResources(computedResourceRequests);
+let variableValuesRevision = 0;
+$variableValuesInput.subscribe((input) => {
+ const revision = ++variableValuesRevision;
+ void computeVariableValues(input).then((values) => {
+ if (revision === variableValuesRevision) {
+ $variableValuesByInstanceSelector.set(values);
+ }
+ });
+});
+
+/** Recompute the async resource plan when its inputs change. */
+export const subscribeResourceRequestPlan = (
+ onPlan: (plan: ResourceRequestPlan) => void
+) => {
+ $resourceRequestPlan.set(createEmptyResourceRequestPlan());
+ let active = true;
+ let revision = 0;
+ const unsubscribe = $resourceRequestPlanInput.subscribe((input) => {
+ const currentRevision = ++revision;
+ void computeResourceRequestPlan(input)
+ .then((resourceRequestPlan) => {
+ if (active && currentRevision === revision) {
+ $resourceRequestPlan.set(resourceRequestPlan);
+ onPlan(resourceRequestPlan);
+ }
+ })
+ .catch((error: unknown) => {
+ if (active && currentRevision === revision) {
+ console.error("Failed to compute resource requests", error);
+ }
+ });
});
+ return () => {
+ active = false;
+ revision += 1;
+ unsubscribe();
+ $resourceRequestPlan.set(createEmptyResourceRequestPlan());
+ };
};
-export const __testing__ = { $computedResourceRequests };
+/** Recompute the plan and preload the requests it produces. */
+export const subscribeResources = () =>
+ subscribeResourceRequestPlan(({ requests }) => {
+ preloadResources(requests);
+ });
diff --git a/apps/builder/app/shared/resources.test.ts b/apps/builder/app/shared/resources.test.ts
index 1472853a17..4a87df84c3 100644
--- a/apps/builder/app/shared/resources.test.ts
+++ b/apps/builder/app/shared/resources.test.ts
@@ -1,5 +1,11 @@
import { afterEach, expect, test, vi } from "vitest";
-import type { ResourceRequest } from "@webstudio-is/sdk";
+import {
+ encodeDataSourceVariable,
+ type DataSources,
+ type Resource,
+ type ResourceRequest,
+ type Resources,
+} from "@webstudio-is/sdk";
import {
__testing__,
$hasPendingResources,
@@ -9,6 +15,8 @@ import {
$resourcePerformanceCache,
$resourcesState,
$resourcesCache,
+ computeResourceRequest,
+ computeResourceRequestPlan,
getResourceKey,
invalidateAssets,
loadResourceDiagnostics,
@@ -57,6 +65,292 @@ test("removes obsolete queued requests but keeps cached results", () => {
unlisten();
});
+test("unlocks reachable resource requests as dependency documents are cached", async () => {
+ const authorVariable = encodeDataSourceVariable("authorDataSource");
+ const resources: Resources = new Map([
+ [
+ "authorResource",
+ {
+ id: "authorResource",
+ name: "Author",
+ method: "get",
+ url: '"https://example.com/authors/1"',
+ headers: [],
+ },
+ ],
+ [
+ "postsResource",
+ {
+ id: "postsResource",
+ name: "Posts",
+ method: "get",
+ url: `"https://example.com/authors/" + ${authorVariable}.data.id + "/posts"`,
+ headers: [],
+ },
+ ],
+ [
+ "unusedResource",
+ {
+ id: "unusedResource",
+ name: "Unused",
+ method: "get",
+ url: '"https://example.com/unused"',
+ headers: [],
+ },
+ ],
+ ]);
+ const dataSources: DataSources = new Map([
+ [
+ "authorDataSource",
+ {
+ type: "resource",
+ id: "authorDataSource",
+ name: "Author",
+ resourceId: "authorResource",
+ },
+ ],
+ [
+ "postsDataSource",
+ {
+ type: "resource",
+ id: "postsDataSource",
+ name: "Posts",
+ resourceId: "postsResource",
+ },
+ ],
+ [
+ "unusedDataSource",
+ {
+ type: "resource",
+ id: "unusedDataSource",
+ name: "Unused",
+ resourceId: "unusedResource",
+ },
+ ],
+ ]);
+ const resourceCache = new Map<string, unknown>();
+
+ const waiting = await computeResourceRequestPlan({
+ rootResourceIds: ["postsResource"],
+ resources,
+ dataSources,
+ values: new Map(),
+ resourceCache,
+ });
+ expect(waiting.requests.map(({ name }) => name)).toEqual(["Author"]);
+ expect(waiting.documents.has("postsResource")).toBe(false);
+
+ const authorRequest = waiting.requests[0];
+ resourceCache.set(getResourceKey(authorRequest), { data: { id: 1 } });
+ const ready = await computeResourceRequestPlan({
+ rootResourceIds: ["postsResource"],
+ resources,
+ dataSources,
+ values: new Map(),
+ resourceCache,
+ });
+
+ expect(ready.requests.map(({ name }) => name)).toEqual(["Author", "Posts"]);
+ expect(ready.requests[1].url).toBe("https://example.com/authors/1/posts");
+ expect(ready.requests.some(({ name }) => name === "Unused")).toBe(false);
+});
+
+test("computes resource request fields from promise-valued variables", async () => {
+ let resolveValue: (value: string) => void = () => {};
+ const value = new Promise<string>((resolve) => {
+ resolveValue = resolve;
+ });
+ const resource: Resource = {
+ id: "resource",
+ name: "Resource",
+ method: "get",
+ url: encodeDataSourceVariable("url"),
+ searchParams: [{ name: "page", value: encodeDataSourceVariable("page") }],
+ headers: [{ name: "x-token", value: encodeDataSourceVariable("token") }],
+ body: encodeDataSourceVariable("body"),
+ };
+ const requestPromise = computeResourceRequest(
+ resource,
+ new Map<string, unknown>([
+ ["url", value],
+ ["page", "2"],
+ ["token", "secret"],
+ ["body", { ok: true }],
+ ])
+ );
+ resolveValue("https://example.com/items");
+
+ await expect(requestPromise).resolves.toEqual({
+ name: "Resource",
+ method: "get",
+ url: "https://example.com/items",
+ searchParams: [{ name: "page", value: "2" }],
+ headers: [{ name: "x-token", value: "secret" }],
+ body: { ok: true },
+ });
+});
+
+test("resolves missing request dependencies once and reuses provided values", async () => {
+ const remoteVariable = encodeDataSourceVariable("remote");
+ const resource: Resource = {
+ id: "resource",
+ name: "Resource",
+ method: "get",
+ url: `${remoteVariable}.url`,
+ searchParams: [{ name: "id", value: `${remoteVariable}.id` }],
+ headers: [{ name: "x-title", value: `${remoteVariable}.title` }],
+ };
+ const resolveDataSource = vi.fn(async () => ({
+ url: "https://example.com/items",
+ id: 42,
+ title: "Remote item",
+ }));
+
+ await expect(
+ computeResourceRequest(resource, new Map(), resolveDataSource)
+ ).resolves.toEqual({
+ name: "Resource",
+ method: "get",
+ url: "https://example.com/items",
+ searchParams: [{ name: "id", value: 42 }],
+ headers: [{ name: "x-title", value: "Remote item" }],
+ });
+ expect(resolveDataSource).toHaveBeenCalledOnce();
+
+ const providedValue = { url: "https://example.com/provided" };
+ const providedResolver = vi.fn();
+ await expect(
+ computeResourceRequest(
+ { ...resource, url: `${remoteVariable}.url` },
+ new Map([["remote", providedValue]]),
+ providedResolver
+ )
+ ).resolves.toMatchObject({ url: "https://example.com/provided" });
+ expect(providedResolver).not.toHaveBeenCalled();
+
+ await expect(
+ computeResourceRequest(
+ { ...resource, url: remoteVariable },
+ new Map(),
+ () => null
+ )
+ ).resolves.toMatchObject({ url: null });
+});
+
+test("computes async resource plans with dependency documents", async () => {
+ const authorVariable = encodeDataSourceVariable("authorDataSource");
+ const resources: Resources = new Map([
+ [
+ "authorResource",
+ {
+ id: "authorResource",
+ name: "Author",
+ method: "get",
+ url: '"https://example.com/authors/1"',
+ headers: [],
+ },
+ ],
+ [
+ "postsResource",
+ {
+ id: "postsResource",
+ name: "Posts",
+ method: "get",
+ url: `"https://example.com/authors/" + ${authorVariable}.data.id + "/posts"`,
+ headers: [],
+ },
+ ],
+ ]);
+ const dataSources: DataSources = new Map([
+ [
+ "authorDataSource",
+ {
+ type: "resource",
+ id: "authorDataSource",
+ name: "Author",
+ resourceId: "authorResource",
+ },
+ ],
+ [
+ "postsDataSource",
+ {
+ type: "resource",
+ id: "postsDataSource",
+ name: "Posts",
+ resourceId: "postsResource",
+ },
+ ],
+ ]);
+ const authorRequest = await computeResourceRequest(
+ resources.get("authorResource") as Resource,
+ new Map()
+ );
+ const resourceCache = new Map([
+ [getResourceKey(authorRequest), Promise.resolve({ data: { id: 1 } })],
+ ]);
+
+ const result = await computeResourceRequestPlan({
+ rootResourceIds: ["postsResource"],
+ resources,
+ dataSources,
+ values: new Map(),
+ resourceCache,
+ });
+
+ expect(result.requests.map(({ name }) => name)).toEqual(["Author", "Posts"]);
+ expect(result.requests[1]?.url).toBe("https://example.com/authors/1/posts");
+ expect(result.documents.get("postsResource")).toBeUndefined();
+});
+
+test.each([
+ ["a", "b", "healthy"],
+ ["healthy", "b", "a"],
+ ["parent", "healthy"],
+])(
+ "skips cycles without blocking independent resources (%j)",
+ async (...rootResourceIds) => {
+ const resources: Resources = new Map(
+ [
+ ["a", encodeDataSourceVariable("b")],
+ ["b", encodeDataSourceVariable("a")],
+ [
+ "parent",
+ `${encodeDataSourceVariable("a")} + ${encodeDataSourceVariable("b")}`,
+ ],
+ ["healthy", '"https://example.com/healthy"'],
+ ].map(([id, url]) => [
+ id,
+ { id, name: id, method: "get", url, headers: [] },
+ ])
+ );
+ const dataSources: DataSources = new Map(
+ [...resources.keys()].map((id) => [
+ id,
+ { id, name: id, type: "resource", resourceId: id },
+ ])
+ );
+ const healthy = await computeResourceRequest(
+ resources.get("healthy")!,
+ new Map()
+ );
+ const document = { data: "healthy" };
+
+ const result = await computeResourceRequestPlan({
+ rootResourceIds,
+ resources,
+ dataSources,
+ values: new Map(),
+ resourceCache: new Map([[getResourceKey(healthy), document]]),
+ });
+
+ expect(result).toEqual({
+ requests: [healthy],
+ documents: new Map([["healthy", document]]),
+ });
+ },
+ 1000
+);
+
test("dispatches resources synchronously", async () => {
const request: ResourceRequest = {
name: "Immediate",
@@ -403,7 +697,7 @@ test("keeps a replacement pending when an obsolete same-key batch settles", asyn
expect($resourcesCache.get().get(key)).toEqual({ data: "fresh" });
});
-test("fills capacity freed by obsolete resources in a mixed batch", async () => {
+test("loads fresh resources within remaining mixed-batch capacity", async () => {
const shared = Array.from({ length: 2 }, (_, index) => ({
name: `Shared ${index}`,
method: "get" as const,
@@ -453,15 +747,68 @@ test("fills capacity freed by obsolete resources in a mixed batch", async () =>
await firstLoad;
});
-test("drains bounded batches without an additional delay", async () => {
- vi.useFakeTimers();
- const requests: ResourceRequest[] = Array.from({ length: 6 }, (_, index) => ({
- name: `Resource ${index}`,
+test("counts obsolete requests until their mixed batch settles", async () => {
+ const shared: ResourceRequest = {
+ name: "Shared",
method: "get",
- url: `https://example.com/resource-${index}`,
+ url: "https://example.com/shared",
+ searchParams: [],
+ headers: [],
+ };
+ const obsolete = Array.from({ length: 19 }, (_, index) => ({
+ name: `Obsolete ${index}`,
+ method: "get" as const,
+ url: `https://example.com/obsolete-${index}`,
+ searchParams: [],
+ headers: [],
+ }));
+ const fresh = Array.from({ length: 19 }, (_, index) => ({
+ name: `Fresh ${index}`,
+ method: "get" as const,
+ url: `https://example.com/fresh-${index}`,
searchParams: [],
headers: [],
}));
+ let resolveFirst = (_response: Response) => {};
+ const requestFetch = vi
+ .fn<typeof globalThis.fetch>()
+ .mockImplementationOnce(
+ () =>
+ new Promise<Response>((resolve) => {
+ resolveFirst = resolve;
+ })
+ )
+ .mockResolvedValueOnce(Response.json([]));
+
+ queueResources([shared, ...obsolete]);
+ const firstLoad = loadResources(requestFetch as typeof globalThis.fetch);
+ queueResources([shared, ...fresh]);
+ startLoading(requestFetch as typeof globalThis.fetch);
+
+ expect(requestFetch).toHaveBeenCalledOnce();
+
+ resolveFirst(Response.json([]));
+ await firstLoad;
+ await vi.waitFor(() => {
+ expect(requestFetch).toHaveBeenCalledTimes(2);
+ });
+ expect(JSON.parse(String(requestFetch.mock.calls[1][1]?.body))).toEqual(
+ fresh
+ );
+});
+
+test("drains bounded batches without an additional delay", async () => {
+ vi.useFakeTimers();
+ const requests: ResourceRequest[] = Array.from(
+ { length: 21 },
+ (_, index) => ({
+ name: `Resource ${index}`,
+ method: "get",
+ url: `https://example.com/resource-${index}`,
+ searchParams: [],
+ headers: [],
+ })
+ );
const fetch = vi.fn<typeof globalThis.fetch>(async () => Response.json([]));
queueResources(requests);
@@ -471,7 +818,7 @@ test("drains bounded batches without an additional delay", async () => {
});
expect(fetch).toHaveBeenCalledTimes(2);
- expect(JSON.parse(String(fetch.mock.calls[0][1]?.body))).toHaveLength(5);
+ expect(JSON.parse(String(fetch.mock.calls[0][1]?.body))).toHaveLength(20);
expect(JSON.parse(String(fetch.mock.calls[1][1]?.body))).toHaveLength(1);
});
diff --git a/apps/builder/app/shared/resources.ts b/apps/builder/app/shared/resources.ts
index c47e115884..8372aaa8b0 100644
--- a/apps/builder/app/shared/resources.ts
+++ b/apps/builder/app/shared/resources.ts
@@ -1,8 +1,21 @@
import { atom, computed } from "nanostores";
-import type { DataSource, Resource, ResourceRequest } from "@webstudio-is/sdk";
-import { isAssetsResourceRequest } from "@webstudio-is/sdk/runtime";
+import {
+ getResourceDependencyIds,
+ type DataSource,
+ type DataSources,
+ type Resource,
+ type ResourceRequest,
+ type Resources,
+} from "@webstudio-is/sdk";
+import {
+ isAssetsResourceRequest,
+ resourceLoadConcurrency,
+} from "@webstudio-is/sdk/runtime";
import { restResourcesLoader } from "./router-utils";
-import { computeExpression } from "@webstudio-is/project-build/runtime";
+import {
+ computeExpression,
+ type ResolveExpressionDataSource,
+} from "@webstudio-is/project-build/runtime";
import { fetch } from "./fetch.client";
import { getResourceKey } from "./resource-utils";
import { type AssetQueryPreviewDiagnostics } from "@webstudio-is/content-engine";
@@ -12,8 +25,6 @@ import {
type ResourcePerformance,
} from "./resource-diagnostics";
-const MAX_PENDING_RESOURCES = 5;
-
type InFlightResourceBatch = {
controller: AbortController;
versions: Map<string, number>;
@@ -95,8 +106,16 @@ export const $hasPendingResources = computed(
(pendingResourceKeys) => pendingResourceKeys.size > 0
);
+const getInFlightResourceCount = () => {
+ let count = 0;
+ for (const batch of inFlightBatches) {
+ count += batch.versions.size;
+ }
+ return count;
+};
+
const loadResources = async (requestFetch: typeof fetch = fetch) => {
- const availableSlots = MAX_PENDING_RESOURCES - pending.size;
+ const availableSlots = resourceLoadConcurrency - getInFlightResourceCount();
if (availableSlots <= 0) {
return;
}
@@ -169,7 +188,10 @@ const loadResources = async (requestFetch: typeof fetch = fetch) => {
};
const startLoading = (requestFetch: typeof fetch = fetch) => {
- if (pending.size >= MAX_PENDING_RESOURCES || queue.size === 0) {
+ if (
+ getInFlightResourceCount() >= resourceLoadConcurrency ||
+ queue.size === 0
+ ) {
return;
}
void loadResources(requestFetch);
@@ -420,29 +442,151 @@ export const invalidateAssets = (requestFetch: typeof fetch = fetch) => {
startLoading(requestFetch);
};
-export const computeResourceRequest = (
+export const computeResourceRequest = async (
resource: Resource,
- values: Map<DataSource["id"], unknown>
-): ResourceRequest => {
+ values: ReadonlyMap<DataSource["id"], unknown>,
+ resolveDataSource?: ResolveExpressionDataSource
+): Promise<ResourceRequest> => {
+ const resolvedDataSources = new Map<DataSource["id"], unknown>();
+ const resolve = (dataSourceId: DataSource["id"], value: unknown) => {
+ if (values.has(dataSourceId)) {
+ return values.get(dataSourceId);
+ }
+ if (resolvedDataSources.has(dataSourceId)) {
+ return resolvedDataSources.get(dataSourceId);
+ }
+ const resolved =
+ resolveDataSource === undefined
+ ? value
+ : resolveDataSource(dataSourceId, value);
+ resolvedDataSources.set(dataSourceId, resolved);
+ return resolved;
+ };
+ const [url, searchParams, headers, body] = await Promise.all([
+ computeExpression(resource.url, values, resolve),
+ Promise.all(
+ (resource.searchParams ?? []).map(async ({ name, value }) => ({
+ name,
+ value: await computeExpression(value, values, resolve),
+ }))
+ ),
+ Promise.all(
+ resource.headers.map(async ({ name, value }) => ({
+ name,
+ value: await computeExpression(value, values, resolve),
+ }))
+ ),
+ resource.body === undefined
+ ? undefined
+ : computeExpression(resource.body, values, resolve),
+ ]);
const request: ResourceRequest = {
name: resource.name,
method: resource.method,
- url: computeExpression(resource.url, values),
- searchParams: (resource.searchParams ?? []).map(({ name, value }) => ({
- name,
- value: computeExpression(value, values),
- })),
- headers: resource.headers.map(({ name, value }) => ({
- name,
- value: computeExpression(value, values),
- })),
+ url,
+ searchParams,
+ headers,
};
if (resource.body !== undefined) {
- request.body = computeExpression(resource.body, values);
+ request.body = body;
}
return request;
};
+const getDataSourcesByResourceId = (dataSources: DataSources) => {
+ const dataSourcesByResourceId = new Map<Resource["id"], DataSource[]>();
+ for (const dataSource of dataSources.values()) {
+ if (dataSource.type !== "resource") {
+ continue;
+ }
+ const entries = dataSourcesByResourceId.get(dataSource.resourceId) ?? [];
+ entries.push(dataSource);
+ dataSourcesByResourceId.set(dataSource.resourceId, entries);
+ }
+ return dataSourcesByResourceId;
+};
+
+export type ResourceRequestPlan = Readonly<{
+ requests: readonly ResourceRequest[];
+ documents: ReadonlyMap<Resource["id"], unknown>;
+}>;
+
+export const computeResourceRequestPlan = async ({
+ rootResourceIds,
+ resources,
+ dataSources,
+ values,
+ resourceCache,
+}: {
+ rootResourceIds: Iterable<Resource["id"]>;
+ resources: Resources;
+ dataSources: DataSources;
+ values: ReadonlyMap<DataSource["id"], unknown>;
+ resourceCache: ReadonlyMap<string, unknown>;
+}): Promise<ResourceRequestPlan> => {
+ const resolvedValues = new Map(values);
+ const documents = new Map<Resource["id"], unknown>();
+ const requests = new Map<Resource["id"], ResourceRequest>();
+ const pending = new Map<Resource["id"], Promise<boolean>>();
+ const dataSourcesByResourceId = getDataSourcesByResourceId(dataSources);
+
+ const visit = (
+ resourceId: Resource["id"],
+ ancestors: ReadonlySet<Resource["id"]> = new Set()
+ ): Promise<boolean> => {
+ if (ancestors.has(resourceId)) {
+ return Promise.resolve(false);
+ }
+ const previous = pending.get(resourceId);
+ if (previous !== undefined) {
+ return previous;
+ }
+ const nextAncestors = new Set(ancestors).add(resourceId);
+ // Walk dependencies before publishing the pending promise so back edges
+ // encounter their ancestor instead of awaiting a promise in the same cycle.
+ const resolution = (async () => {
+ const resource = resources.get(resourceId);
+ if (resource === undefined) {
+ return false;
+ }
+ const dependencyIds = getResourceDependencyIds({
+ resource,
+ dataSources,
+ });
+ const dependenciesResolved = await Promise.all(
+ [...dependencyIds].map((dependencyId) =>
+ visit(dependencyId, nextAncestors)
+ )
+ );
+ if (dependenciesResolved.some((resolved) => resolved === false)) {
+ return false;
+ }
+ const request = await computeResourceRequest(resource, resolvedValues);
+ requests.set(resourceId, request);
+ const key = getResourceKey(request);
+ if (resourceCache.has(key) === false) {
+ return false;
+ }
+ const document = resourceCache.get(key);
+ documents.set(resourceId, document);
+ for (const dataSource of dataSourcesByResourceId.get(resourceId) ?? []) {
+ resolvedValues.set(dataSource.id, document);
+ }
+ return true;
+ })();
+ pending.set(resourceId, resolution);
+ return resolution;
+ };
+
+ await Promise.all(
+ [...new Set(rootResourceIds)].map((resourceId) => visit(resourceId))
+ );
+ return {
+ requests: Array.from(requests.values()),
+ documents,
+ };
+};
+
const reset = () => {
for (const batch of inFlightBatches) {
batch.controller.abort();
diff --git a/apps/builder/app/shared/rest-resources-loader.node.test.ts b/apps/builder/app/shared/rest-resources-loader.node.test.ts
index ec104da971..bbe66f8632 100644
--- a/apps/builder/app/shared/rest-resources-loader.node.test.ts
+++ b/apps/builder/app/shared/rest-resources-loader.node.test.ts
@@ -1,9 +1,28 @@
import { expect, test, vi } from "vitest";
import type { ResourceRequest } from "@webstudio-is/sdk";
-import { loadResource } from "@webstudio-is/sdk/runtime";
-import { loadResourceRequestList } from "../services/resource-list-loader.server";
+import {
+ loadResource,
+ resourceLoadConcurrency,
+} from "@webstudio-is/sdk/runtime";
+import {
+ loadResourceRequestList,
+ resourceRequestListSchema,
+} from "../services/resource-list-loader.server";
import { getResourceKey } from "./resource-utils";
+test("limits each server resource batch to the shared concurrency", () => {
+ expect(
+ resourceRequestListSchema.safeParse(
+ Array.from({ length: resourceLoadConcurrency })
+ ).success
+ ).toBe(true);
+ expect(
+ resourceRequestListSchema.safeParse(
+ Array.from({ length: resourceLoadConcurrency + 1 })
+ ).success
+ ).toBe(false);
+});
+
test("batches Assets while starting and preserving independent remote resources", async () => {
const events: string[] = [];
const assets: ResourceRequest[] = ["Tools", "Updates"].map((category) => ({
diff --git a/apps/builder/app/shared/use-async-value.ts b/apps/builder/app/shared/use-async-value.ts
new file mode 100644
index 0000000000..5c22ae5754
--- /dev/null
+++ b/apps/builder/app/shared/use-async-value.ts
@@ -0,0 +1,23 @@
+import { useEffect, useState, type DependencyList } from "react";
+
+export const useAsyncValue = <Value>(
+ getValue: () => PromiseLike<Value>,
+ dependencies: DependencyList,
+ initialValue: Value
+) => {
+ const [value, setValue] = useState(initialValue);
+ useEffect(() => {
+ let active = true;
+ void getValue().then((nextValue) => {
+ if (active) {
+ setValue(nextValue);
+ }
+ });
+ return () => {
+ active = false;
+ };
+ // The caller owns the dependency list for the async computation.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, dependencies);
+ return value;
+};
diff --git a/docs/university/foundations/copy-paste/README.md b/docs/university/foundations/copy-paste/README.md
index 73735426c9..776b451474 100644
--- a/docs/university/foundations/copy-paste/README.md
+++ b/docs/university/foundations/copy-paste/README.md
@@ -4,6 +4,10 @@ description: Webstudio supports copy-pasting within the platform and from extern
# ↔️ Copy-Paste
+Cut removes selected content only after it is copied to the clipboard. If project
+data changes while the cut is pending, Webstudio keeps the copy but removes
+nothing. A message asks you to try cutting again.
+
{% content-ref url="css.md" %}
[css.md](css.md)
{% endcontent-ref %}
diff --git a/docs/university/foundations/variables.md b/docs/university/foundations/variables.md
index 5e244e0f8f..48af24e66c 100644
--- a/docs/university/foundations/variables.md
+++ b/docs/university/foundations/variables.md
@@ -105,6 +105,16 @@ There are several fields available to configure the fetch request.
Once the Resource fetches data, you'll use the [Expression editor](expression-editor.md) to bind data from the response to your website. See [Binding](expression-editor.md#binding) for more information.
+#### Dependent resources
+
+Bind a Resource request field to another Resource variable when one request needs data from an earlier response. For example, bind an author ID from one Resource into the URL or search parameters of a second Resource that loads the author's posts.
+
+Webstudio fetches the dependency first and evaluates the dependent request after the dependency data is available. A Resource cannot depend on itself or on another Resource that already depends on it. Collection item and component parameter variables are not available in Resource request fields.
+
+When a Form uses a Resource action, Webstudio fetches that action's dependencies when the form is submitted, not when the page loads.
+
+Form actions bypass Webstudio's resource cache so each submission sends a new request. Their dependencies still use the configured cache lifetime.
+
#### Caching
You may be wondering whether every visit to your blog results in an API call to your CMS or if the content is cached in Webstudio.
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.tsx
index 40d1b230d9..fd10aed37e 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,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 55164bf9dd..5b804100f8 100644
--- a/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsx
+++ b/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsx
@@ -4,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 864b48df2e..9c7d45562e 100644
--- a/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx
+++ b/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/fixtures/react-router-cloudflare/app/routes/_index.tsx b/fixtures/react-router-cloudflare/app/routes/_index.tsx
index 051857b2cd..34b4765781 100644
--- a/fixtures/react-router-cloudflare/app/routes/_index.tsx
+++ b/fixtures/react-router-cloudflare/app/routes/_index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
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.tsx
index 40d1b230d9..fd10aed37e 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,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 55164bf9dd..5b804100f8 100644
--- a/fixtures/react-router-docker/app/__generated__/_index.server.tsx
+++ b/fixtures/react-router-docker/app/__generated__/_index.server.tsx
@@ -4,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 864b48df2e..9c7d45562e 100644
--- a/fixtures/react-router-docker/app/routes/[another-page]._index.tsx
+++ b/fixtures/react-router-docker/app/routes/[another-page]._index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/fixtures/react-router-docker/app/routes/_index.tsx b/fixtures/react-router-docker/app/routes/_index.tsx
index 051857b2cd..34b4765781 100644
--- a/fixtures/react-router-docker/app/routes/_index.tsx
+++ b/fixtures/react-router-docker/app/routes/_index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
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.tsx
index 40d1b230d9..fd10aed37e 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,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 55164bf9dd..5b804100f8 100644
--- a/fixtures/react-router-netlify/app/__generated__/_index.server.tsx
+++ b/fixtures/react-router-netlify/app/__generated__/_index.server.tsx
@@ -4,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 864b48df2e..9c7d45562e 100644
--- a/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx
+++ b/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/fixtures/react-router-netlify/app/routes/_index.tsx b/fixtures/react-router-netlify/app/routes/_index.tsx
index 051857b2cd..34b4765781 100644
--- a/fixtures/react-router-netlify/app/routes/_index.tsx
+++ b/fixtures/react-router-netlify/app/routes/_index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
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.tsx
index 40d1b230d9..fd10aed37e 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,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 55164bf9dd..5b804100f8 100644
--- a/fixtures/react-router-vercel/app/__generated__/_index.server.tsx
+++ b/fixtures/react-router-vercel/app/__generated__/_index.server.tsx
@@ -4,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 864b48df2e..9c7d45562e 100644
--- a/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx
+++ b/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/fixtures/react-router-vercel/app/routes/_index.tsx b/fixtures/react-router-vercel/app/routes/_index.tsx
index 051857b2cd..34b4765781 100644
--- a/fixtures/react-router-vercel/app/routes/_index.tsx
+++ b/fixtures/react-router-vercel/app/routes/_index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
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.tsx
index 40d1b230d9..fd10aed37e 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,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 55164bf9dd..5b804100f8 100644
--- a/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsx
+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsx
@@ -4,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
return { data: _data, action: _action, contentData: _contentData }
}
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.tsx
index 0e16cc445e..67acd100fe 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,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 821087eabb..656e3caf0a 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,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
return { data: _data, action: _action, contentData: _contentData }
}
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.tsx
index 40d1b230d9..fd10aed37e 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,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 55164bf9dd..5b804100f8 100644
--- a/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsx
+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsx
@@ -4,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index c7dde77853..8faf169ca5 100644
--- a/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx
+++ b/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx
@@ -276,9 +276,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -307,25 +308,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx b/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx
index ada034ef65..722f7cb30d 100644
--- a/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx
+++ b/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx
@@ -276,9 +276,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -307,25 +308,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js
index 5e487e7016..68c8fbeb6e 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 gd=Object.defineProperty;var bd=(t,e)=>{for(var n in e)gd(t,n,{get:e[n],enumerable:!0})};var Ys;function b(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 yy=Symbol("zod_brand"),Oe=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Dt=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Ys=globalThis).__zod_globalConfig??(Ys.__zod_globalConfig={});var Rt=globalThis.__zod_globalConfig;function _e(t){return t&&Object.assign(Rt,t),Rt}var F={};bd(F,{BIGINT_FORMAT_RANGES:()=>ni,Class:()=>mo,NUMBER_FORMAT_RANGES:()=>_o,aborted:()=>He,allowsEval:()=>go,assert:()=>Sd,assertEqual:()=>wd,assertIs:()=>xd,assertNever:()=>Ed,assertNotEqual:()=>_d,assignProp:()=>Ye,base64ToUint8Array:()=>oi,base64urlToUint8Array:()=>jd,cached:()=>It,captureStackTrace:()=>qn,cleanEnum:()=>Bd,cleanRegex:()=>fn,clone:()=>xe,cloneDef:()=>Dd,createTransparentProxy:()=>Td,defineLazy:()=>M,esc:()=>Gn,escapeRegex:()=>Ue,explicitlyAborted:()=>xo,extend:()=>zd,finalizeIssue:()=>me,floatSafeRemainder:()=>ho,getElementAtPath:()=>Rd,getEnumValues:()=>un,getLengthableOrigin:()=>dn,getParsedType:()=>Cd,getSizableOrigin:()=>ri,hexToUint8Array:()=>Qd,isObject:()=>bt,isPlainObject:()=>Xe,issue:()=>Ot,joinValues:()=>Ad,jsonStringifyReplacer:()=>kt,merge:()=>Ld,mergeDefs:()=>je,normalizeParams:()=>I,nullish:()=>ln,numKeys:()=>Od,objectClone:()=>vd,omit:()=>$d,optionalKeys:()=>wo,parsedType:()=>Zd,partial:()=>Md,pick:()=>Nd,prefixIssues:()=>Qe,primitiveTypes:()=>ei,promiseAllObject:()=>kd,propertyKeyTypes:()=>bo,randomString:()=>Id,required:()=>Fd,safeExtend:()=>Pd,shallowClone:()=>Hs,slugify:()=>yo,stringifyPrimitive:()=>ti,uint8ArrayToBase64:()=>si,uint8ArrayToBase64url:()=>Ud,uint8ArrayToHex:()=>Vd,unwrapMessage:()=>cn});function wd(t){return t}function _d(t){return t}function xd(t){}function Ed(t){throw new Error("Unexpected value in exhaustive check")}function Sd(t){}function un(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 Ad(t,e="|"){return t.map(n=>ti(n)).join(e)}function kt(t,e){return typeof e=="bigint"?e.toString():e}function It(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function ln(t){return t==null}function fn(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 Xs=Symbol("evaluating");function M(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==Xs)return r===void 0&&(r=Xs,r=n()),r},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function vd(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 je(...t){let e={};for(let n of t){let r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function Dd(t){return je(t._zod.def)}function Rd(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function kd(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 Id(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 qn="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function bt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var go=It(()=>{if(Rt.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Xe(t){if(bt(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let n=e.prototype;return!(bt(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Hs(t){return Xe(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function Od(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}var Cd=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"]),ei=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ue(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xe(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 Td(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 ti(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]},ni={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Nd(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=je(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 xe(t,s)}function $d(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=je(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 xe(t,s)}function zd(t,e){if(!Xe(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=je(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return Ye(this,"shape",s),s}});return xe(t,o)}function Pd(t,e){if(!Xe(e))throw new Error("Invalid input to safeExtend: expected a plain object");let n=je(t._zod.def,{get shape(){let r={...t._zod.def.shape,...e};return Ye(this,"shape",r),r}});return xe(t,n)}function Ld(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=je(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 xe(t,n)}function Md(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=je(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 xe(e,i)}function Fd(t,e,n){let r=je(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 xe(e,r)}function He(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 Qe(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function cn(t){return typeof t=="string"?t:t?.message}function me(t,e,n){let r=t.message?t.message:cn(t.inst?._zod.def?.error?.(t))??cn(e?.error?.(t))??cn(n.customError?.(t))??cn(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 ri(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function dn(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Zd(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 Ot(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function Bd(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function oi(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 si(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}function jd(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-e.length%4)%4);return oi(e+n)}function Ud(t){return si(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Qd(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 Vd(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var mo=class{constructor(...e){}};var ii=(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,kt,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Jn=b("$ZodError",ii),Eo=b("$ZodError",ii,{Parent:Error});function ai(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 ci(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 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 Oe;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>me(c,s,_e())));throw qn(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,_e())));throw qn(a,o?.callee),a}return i.value};var pn=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 Oe;return s.issues.length?{success:!1,error:new(t??Jn)(s.issues.map(i=>me(i,o,_e())))}:{success:!0,data:s.value}},ui=pn(Eo),mn=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,_e())))}:{success:!0,data:s.value}},li=mn(Eo),fi=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Kn(t)(e,n,o)};var di=t=>(e,n,r)=>Kn(t)(e,n,r);var pi=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Wn(t)(e,n,o)};var mi=t=>async(e,n,r)=>Wn(t)(e,n,r);var hi=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return pn(t)(e,n,o)};var yi=t=>(e,n,r)=>pn(t)(e,n,r);var gi=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return mn(t)(e,n,o)};var bi=t=>async(e,n,r)=>mn(t)(e,n,r);var wi=/^[cC][0-9a-z]{6,}$/,_i=/^[0-9a-z]+$/,xi=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ei=/^[0-9a-vA-V]{20}$/,Si=/^[A-Za-z0-9]{27}$/,Ai=/^[a-zA-Z0-9_-]{21}$/,vi=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Di=/^([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})$/,So=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 Ri=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var qd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ki(){return new RegExp(qd,"u")}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])$/,Oi=/^(([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 Ci=/^((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])$/,Ti=/^(([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])$/,Ni=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ao=/^[A-Za-z0-9_-]*$/;var $i=/^https?$/,zi=/^\+[1-9]\d{6,14}$/,Pi="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Li=new RegExp(`^${Pi}$`);function Mi(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 Fi(t){return new RegExp(`^${Mi(t)}$`)}function Zi(t){let e=Mi({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(`^${Pi}T(?:${r})$`)}var Bi=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var ji=/^-?\d+$/,vo=/^-?\d+(?:\.\d+)?$/,Ui=/^(?:true|false)$/i,Qi=/^null$/i;var Vi=/^[^A-Z]*$/,Gi=/^[^a-z]*$/;var te=b("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),qi={number:"number",bigint:"bigint",object:"date"},Do=b("$ZodCheckLessThan",(t,e)=>{te.init(t,e);let n=qi[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=b("$ZodCheckGreaterThan",(t,e)=>{te.init(t,e);let n=qi[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=b("$ZodCheckMultipleOf",(t,e)=>{te.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})}}),Ki=b("$ZodCheckNumberFormat",(t,e)=>{te.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=ji)}),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 Wi=b("$ZodCheckMaxLength",(t,e)=>{var n;te.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!ln(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=dn(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Yi=b("$ZodCheckMinLength",(t,e)=>{var n;te.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!ln(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=dn(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Xi=b("$ZodCheckLengthEquals",(t,e)=>{var n;te.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!ln(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=dn(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})}}),hn=b("$ZodCheckStringFormat",(t,e)=>{var n,r;te.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=()=>{})}),Hi=b("$ZodCheckRegex",(t,e)=>{hn.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})}}),ea=b("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Vi),hn.init(t,e)}),ta=b("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Gi),hn.init(t,e)}),na=b("$ZodCheckIncludes",(t,e)=>{te.init(t,e);let n=Ue(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})}}),ra=b("$ZodCheckStartsWith",(t,e)=>{te.init(t,e);let n=new RegExp(`^${Ue(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})}}),oa=b("$ZodCheckEndsWith",(t,e)=>{te.init(t,e);let n=new RegExp(`.*${Ue(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 sa=b("$ZodCheckOverwrite",(t,e)=>{te.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});var Xn=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 Ad=Object.defineProperty;var vd=(t,e)=>{for(var n in e)Ad(t,n,{get:e[n],enumerable:!0})};var ni;function b(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 Sy=Symbol("zod_brand"),Te=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Rt=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(ni=globalThis).__zod_globalConfig??(ni.__zod_globalConfig={});var kt=globalThis.__zod_globalConfig;function xe(t){return t&&Object.assign(kt,t),kt}var F={};vd(F,{BIGINT_FORMAT_RANGES:()=>ai,Class:()=>bo,NUMBER_FORMAT_RANGES:()=>Ao,aborted:()=>et,allowsEval:()=>Eo,assert:()=>Od,assertEqual:()=>Dd,assertIs:()=>kd,assertNever:()=>Id,assertNotEqual:()=>Rd,assignProp:()=>Xe,base64ToUint8Array:()=>ui,base64urlToUint8Array:()=>Kd,cached:()=>Ot,captureStackTrace:()=>Wn,cleanEnum:()=>Jd,cleanRegex:()=>pn,clone:()=>Se,cloneDef:()=>Nd,createTransparentProxy:()=>Fd,defineLazy:()=>M,esc:()=>Kn,escapeRegex:()=>Ve,explicitlyAborted:()=>vo,extend:()=>jd,finalizeIssue:()=>he,floatSafeRemainder:()=>wo,getElementAtPath:()=>$d,getEnumValues:()=>fn,getLengthableOrigin:()=>mn,getParsedType:()=>Md,getSizableOrigin:()=>ci,hexToUint8Array:()=>Yd,isObject:()=>wt,isPlainObject:()=>He,issue:()=>Ct,joinValues:()=>Cd,jsonStringifyReplacer:()=>It,merge:()=>Qd,mergeDefs:()=>Qe,normalizeParams:()=>I,nullish:()=>dn,numKeys:()=>Ld,objectClone:()=>Td,omit:()=>Bd,optionalKeys:()=>So,parsedType:()=>qd,partial:()=>Vd,pick:()=>Zd,prefixIssues:()=>Ge,primitiveTypes:()=>si,promiseAllObject:()=>zd,propertyKeyTypes:()=>xo,randomString:()=>Pd,required:()=>Gd,safeExtend:()=>Ud,shallowClone:()=>oi,slugify:()=>_o,stringifyPrimitive:()=>ii,uint8ArrayToBase64:()=>li,uint8ArrayToBase64url:()=>Wd,uint8ArrayToHex:()=>Xd,unwrapMessage:()=>ln});function Dd(t){return t}function Rd(t){return t}function kd(t){}function Id(t){throw new Error("Unexpected value in exhaustive check")}function Od(t){}function fn(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 Cd(t,e="|"){return t.map(n=>ii(n)).join(e)}function It(t,e){return typeof e=="bigint"?e.toString():e}function Ot(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function dn(t){return t==null}function pn(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function wo(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 ri=Symbol("evaluating");function M(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==ri)return r===void 0&&(r=ri,r=n()),r},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Td(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Xe(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Qe(...t){let e={};for(let n of t){let r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function Nd(t){return Qe(t._zod.def)}function $d(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function zd(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 Pd(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<t;r++)n+=e[Math.floor(Math.random()*e.length)];return n}function Kn(t){return JSON.stringify(t)}function _o(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Wn="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function wt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Eo=Ot(()=>{if(kt.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(wt(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let n=e.prototype;return!(wt(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function oi(t){return He(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function Ld(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}var Md=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}`)}},xo=new Set(["string","number","symbol"]),si=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ve(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Se(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 Fd(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 ii(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function So(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Ao={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]},ai={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Zd(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=Qe(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 Xe(this,"shape",i),i},checks:[]});return Se(t,s)}function Bd(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=Qe(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 Xe(this,"shape",i),i},checks:[]});return Se(t,s)}function jd(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=Qe(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return Xe(this,"shape",s),s}});return Se(t,o)}function Ud(t,e){if(!He(e))throw new Error("Invalid input to safeExtend: expected a plain object");let n=Qe(t._zod.def,{get shape(){let r={...t._zod.def.shape,...e};return Xe(this,"shape",r),r}});return Se(t,n)}function Qd(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=Qe(t._zod.def,{get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Xe(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return Se(t,n)}function Vd(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=Qe(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 Xe(this,"shape",c),c},checks:[]});return Se(e,i)}function Gd(t,e,n){let r=Qe(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 Xe(this,"shape",s),s}});return Se(e,r)}function et(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 vo(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 Ge(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function ln(t){return typeof t=="string"?t:t?.message}function he(t,e,n){let r=t.message?t.message:ln(t.inst?._zod.def?.error?.(t))??ln(e?.error?.(t))??ln(n.customError?.(t))??ln(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 ci(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function mn(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function qd(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 Ct(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function Jd(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function ui(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 li(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}function Kd(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-e.length%4)%4);return ui(e+n)}function Wd(t){return li(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Yd(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 Xd(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var bo=class{constructor(...e){}};var fi=(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,It,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Yn=b("$ZodError",fi),Do=b("$ZodError",fi,{Parent:Error});function di(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 pi(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 Xn=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 Te;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>he(c,s,xe())));throw Wn(a,o?.callee),a}return i.value};var Hn=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=>he(c,s,xe())));throw Wn(a,o?.callee),a}return i.value};var hn=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 Te;return s.issues.length?{success:!1,error:new(t??Yn)(s.issues.map(i=>he(i,o,xe())))}:{success:!0,data:s.value}},mi=hn(Do),yn=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=>he(i,o,xe())))}:{success:!0,data:s.value}},hi=yn(Do),yi=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Xn(t)(e,n,o)};var gi=t=>(e,n,r)=>Xn(t)(e,n,r);var bi=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Hn(t)(e,n,o)};var wi=t=>async(e,n,r)=>Hn(t)(e,n,r);var _i=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return hn(t)(e,n,o)};var Ei=t=>(e,n,r)=>hn(t)(e,n,r);var xi=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return yn(t)(e,n,o)};var Si=t=>async(e,n,r)=>yn(t)(e,n,r);var Ai=/^[cC][0-9a-z]{6,}$/,vi=/^[0-9a-z]+$/,Di=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ri=/^[0-9a-vA-V]{20}$/,ki=/^[A-Za-z0-9]{27}$/,Ii=/^[a-zA-Z0-9_-]{21}$/,Oi=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Ci=/^([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})$/,Ro=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 Ti=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var ep="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Ni(){return new RegExp(ep,"u")}var $i=/^(?:(?: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])$/,zi=/^(([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 Pi=/^((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])$/,Li=/^(([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])$/,Mi=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ko=/^[A-Za-z0-9_-]*$/;var Fi=/^https?$/,Zi=/^\+[1-9]\d{6,14}$/,Bi="(?:(?:\\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])))",ji=new RegExp(`^${Bi}$`);function Ui(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 Qi(t){return new RegExp(`^${Ui(t)}$`)}function Vi(t){let e=Ui({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(`^${Bi}T(?:${r})$`)}var Gi=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var qi=/^-?\d+$/,Io=/^-?\d+(?:\.\d+)?$/,Ji=/^(?:true|false)$/i,Ki=/^null$/i;var Wi=/^[^A-Z]*$/,Yi=/^[^a-z]*$/;var te=b("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Xi={number:"number",bigint:"bigint",object:"date"},Oo=b("$ZodCheckLessThan",(t,e)=>{te.init(t,e);let n=Xi[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})}}),Co=b("$ZodCheckGreaterThan",(t,e)=>{te.init(t,e);let n=Xi[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})}}),Hi=b("$ZodCheckMultipleOf",(t,e)=>{te.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):wo(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})}}),ea=b("$ZodCheckNumberFormat",(t,e)=>{te.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,s]=Ao[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=qi)}),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 ta=b("$ZodCheckMaxLength",(t,e)=>{var n;te.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!dn(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=mn(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),na=b("$ZodCheckMinLength",(t,e)=>{var n;te.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!dn(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=mn(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),ra=b("$ZodCheckLengthEquals",(t,e)=>{var n;te.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!dn(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=mn(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})}}),gn=b("$ZodCheckStringFormat",(t,e)=>{var n,r;te.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=()=>{})}),oa=b("$ZodCheckRegex",(t,e)=>{gn.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})}}),sa=b("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Wi),gn.init(t,e)}),ia=b("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Yi),gn.init(t,e)}),aa=b("$ZodCheckIncludes",(t,e)=>{te.init(t,e);let n=Ve(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})}}),ca=b("$ZodCheckStartsWith",(t,e)=>{te.init(t,e);let n=new RegExp(`^${Ve(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})}}),ua=b("$ZodCheckEndsWith",(t,e)=>{te.init(t,e);let n=new RegExp(`.*${Ve(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 la=b("$ZodCheckOverwrite",(t,e)=>{te.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});var tr=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 aa={major:4,minor:4,patch:3};var U=b("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=aa;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=He(i),d;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,p=l._zod.check(i);if(p instanceof Promise&&c?.async===!1)throw new Oe;if(d||p instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await p,i.issues.length!==f&&(u||(u=He(i,f)))});else{if(i.issues.length===f)continue;u||(u=He(i,f))}}return d?d.then(()=>i):i},s=(i,a,c)=>{if(He(i))return i.aborted=!0,i;let u=o(a,r,c);if(u instanceof Promise){if(c.async===!1)throw new Oe;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 Oe;return c.then(u=>o(u,r,a))}return o(c,r,a)}}M(t,"~standard",()=>({validate:o=>{try{let s=ui(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return li(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),tr=b("$ZodString",(t,e)=>{U.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Bi(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}}),Q=b("$ZodStringFormat",(t,e)=>{hn.init(t,e),tr.init(t,e)}),ya=b("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Di),Q.init(t,e)}),ga=b("$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=So(r))}else e.pattern??(e.pattern=So());Q.init(t,e)}),ba=b("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Ri),Q.init(t,e)}),wa=b("$ZodURL",(t,e)=>{Q.init(t,e),t._zod.check=n=>{try{let r=n.value.trim();if(!e.normalize&&e.protocol?.source===$i.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})}}}),_a=b("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=ki()),Q.init(t,e)}),xa=b("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Ai),Q.init(t,e)}),Ea=b("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=wi),Q.init(t,e)}),Sa=b("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=_i),Q.init(t,e)}),Aa=b("$ZodULID",(t,e)=>{e.pattern??(e.pattern=xi),Q.init(t,e)}),va=b("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Ei),Q.init(t,e)}),Da=b("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Si),Q.init(t,e)}),Ra=b("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Zi(e)),Q.init(t,e)}),ka=b("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Li),Q.init(t,e)}),Ia=b("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Fi(e)),Q.init(t,e)}),Oa=b("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=vi),Q.init(t,e)}),Ca=b("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Ii),Q.init(t,e),t._zod.bag.format="ipv4"}),Ta=b("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Oi),Q.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 Na=b("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Ci),Q.init(t,e)}),$a=b("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Ti),Q.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 za(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Pa=b("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Ni),Q.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{za(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function Jd(t){if(!Ao.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return za(n)}var La=b("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Ao),Q.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{Jd(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Ma=b("$ZodE164",(t,e)=>{e.pattern??(e.pattern=zi),Q.init(t,e)});function Kd(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 Fa=b("$ZodJWT",(t,e)=>{Q.init(t,e),t._zod.check=n=>{Kd(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}});var Io=b("$ZodNumber",(t,e)=>{U.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}}),Za=b("$ZodNumberFormat",(t,e)=>{Ki.init(t,e),Io.init(t,e)}),Ba=b("$ZodBoolean",(t,e)=>{U.init(t,e),t._zod.pattern=Ui,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 ja=b("$ZodNull",(t,e)=>{U.init(t,e),t._zod.pattern=Qi,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 Ua=b("$ZodUnknown",(t,e)=>{U.init(t,e),t._zod.parse=n=>n}),Qa=b("$ZodNever",(t,e)=>{U.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function ca(t,e,n){t.issues.length&&e.issues.push(...Qe(n,t.issues)),e.value[n]=t.value}var Va=b("$ZodArray",(t,e)=>{U.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=>ca(u,n,i))):ca(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(...Qe(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 Ga(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 qa(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=>er(y,n,f,e,d,l))):er(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 Wd=b("$ZodObject",(t,e)=>{if(U.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=It(()=>Ga(e));M(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=bt,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(g=>er(g,a,f,u,y,m))):er(h,a,f,u,y,m)}return s?qa(d,u,a,c,r.value,t):d.length?Promise.all(d).then(()=>a):a}}),Ja=b("$ZodObjectJIT",(t,e)=>{Wd.init(t,e);let n=t._zod.parse,r=It(()=>Ga(e)),o=f=>{let p=new Xn(["shape","payload","ctx"]),y=r.value,m=S=>{let _=Gn(S);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),g=0;for(let S of y.keys)h[S]=`key_${g++}`;p.write("const newResult = {};");for(let S of y.keys){let _=h[S],w=Gn(S),A=f[S],D=A?._zod?.optin==="optional",E=A?._zod?.optout==="optional";p.write(`const ${_} = ${m(S)};`),D&&E?p.write(`
+`))}};var da={major:4,minor:4,patch:3};var U=b("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=da;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=et(i),d;for(let l of a){if(l._zod.def.when){if(vo(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 Te;if(d||p instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await p,i.issues.length!==f&&(u||(u=et(i,f)))});else{if(i.issues.length===f)continue;u||(u=et(i,f))}}return d?d.then(()=>i):i},s=(i,a,c)=>{if(et(i))return i.aborted=!0,i;let u=o(a,r,c);if(u instanceof Promise){if(c.async===!1)throw new Te;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 Te;return c.then(u=>o(u,r,a))}return o(c,r,a)}}M(t,"~standard",()=>({validate:o=>{try{let s=mi(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return hi(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),or=b("$ZodString",(t,e)=>{U.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Gi(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}}),Q=b("$ZodStringFormat",(t,e)=>{gn.init(t,e),or.init(t,e)}),Ea=b("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Ci),Q.init(t,e)}),xa=b("$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=Ro(r))}else e.pattern??(e.pattern=Ro());Q.init(t,e)}),Sa=b("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Ti),Q.init(t,e)}),Aa=b("$ZodURL",(t,e)=>{Q.init(t,e),t._zod.check=n=>{try{let r=n.value.trim();if(!e.normalize&&e.protocol?.source===Fi.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})}}}),va=b("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Ni()),Q.init(t,e)}),Da=b("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Ii),Q.init(t,e)}),Ra=b("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Ai),Q.init(t,e)}),ka=b("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=vi),Q.init(t,e)}),Ia=b("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Di),Q.init(t,e)}),Oa=b("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Ri),Q.init(t,e)}),Ca=b("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=ki),Q.init(t,e)}),Ta=b("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Vi(e)),Q.init(t,e)}),Na=b("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=ji),Q.init(t,e)}),$a=b("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Qi(e)),Q.init(t,e)}),za=b("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Oi),Q.init(t,e)}),Pa=b("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=$i),Q.init(t,e),t._zod.bag.format="ipv4"}),La=b("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=zi),Q.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 Ma=b("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Pi),Q.init(t,e)}),Fa=b("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Li),Q.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 Za(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Ba=b("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Mi),Q.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{Za(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function tp(t){if(!ko.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Za(n)}var ja=b("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=ko),Q.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{tp(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Ua=b("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Zi),Q.init(t,e)});function np(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 Qa=b("$ZodJWT",(t,e)=>{Q.init(t,e),t._zod.check=n=>{np(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}});var No=b("$ZodNumber",(t,e)=>{U.init(t,e),t._zod.pattern=t._zod.bag.pattern??Io,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}}),Va=b("$ZodNumberFormat",(t,e)=>{ea.init(t,e),No.init(t,e)}),Ga=b("$ZodBoolean",(t,e)=>{U.init(t,e),t._zod.pattern=Ji,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 qa=b("$ZodNull",(t,e)=>{U.init(t,e),t._zod.pattern=Ki,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 Ja=b("$ZodUnknown",(t,e)=>{U.init(t,e),t._zod.parse=n=>n}),Ka=b("$ZodNever",(t,e)=>{U.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function pa(t,e,n){t.issues.length&&e.issues.push(...Ge(n,t.issues)),e.value[n]=t.value}var Wa=b("$ZodArray",(t,e)=>{U.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=>pa(u,n,i))):pa(c,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function rr(t,e,n,r,o,s){let i=n in r;if(t.issues.length){if(o&&s&&!i)return;e.issues.push(...Ge(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 Ya(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=So(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Xa(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(g=>rr(g,n,f,e,d,l))):rr(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 rp=b("$ZodObject",(t,e)=>{if(U.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=Ot(()=>Ya(e));M(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=wt,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],g=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(y=>rr(y,a,f,u,g,m))):rr(h,a,f,u,g,m)}return s?Xa(d,u,a,c,r.value,t):d.length?Promise.all(d).then(()=>a):a}}),Ha=b("$ZodObjectJIT",(t,e)=>{rp.init(t,e);let n=t._zod.parse,r=Ot(()=>Ya(e)),o=f=>{let p=new tr(["shape","payload","ctx"]),g=r.value,m=S=>{let _=Kn(S);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),y=0;for(let S of g.keys)h[S]=`key_${y++}`;p.write("const newResult = {};");for(let S of g.keys){let _=h[S],w=Kn(S),A=f[S],D=A?._zod?.optin==="optional",x=A?._zod?.optout==="optional";p.write(`const ${_} = ${m(S)};`),D&&x?p.write(`
if (${_}.issues.length) {
if (${w} in input) {
payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
@@ -59,136 +59,136 @@ var gd=Object.defineProperty;var bd=(t,e)=>{for(var n in e)gd(t,n,{get:e[n],enum
}
}
- `)}p.write("payload.value = newResult;"),p.write("return payload;");let x=p.compile();return(S,_)=>x(f,S,_)},s,i=bt,a=!Rt.jitless,u=a&&go.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?qa([],y,f,p,l,t):f):n(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:y,inst:t}),f)}});function ua(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=>!He(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,_e())))}),e)}var Oo=b("$ZodUnion",(t,e)=>{U.init(t,e),M(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),M(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),M(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),M(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=>fn(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=>ua(a,r,t,o)):ua(i,r,t,o)}});var Ka=b("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,Oo.init(t,e);let n=t._zod.parse;M(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=It(()=>{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(!bt(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)}}),Wa=b("$ZodIntersection",(t,e)=>{U.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])=>la(n,c,u)):la(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(Xe(t)&&Xe(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 la(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}),He(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 Ya=b("$ZodRecord",(t,e)=>{U.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Xe(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,_e())),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(...Qe(u,p.issues)),n.value[l]=p.value})):(f.issues.length&&n.issues.push(...Qe(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,_e())),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(...Qe(a,l.issues)),n.value[c.value]=l.value})):(d.issues.length&&n.issues.push(...Qe(a,d.issues)),n.value[c.value]=d.value)}}return s.length?Promise.all(s).then(()=>n):n}});var Xa=b("$ZodEnum",(t,e)=>{U.init(t,e);let n=un(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"?Ue(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}}),Ha=b("$ZodLiteral",(t,e)=>{if(U.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"?Ue(r):r?Ue(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 ec=b("$ZodTransform",(t,e)=>{U.init(t,e),t._zod.optin="optional",t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Dt(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 Oe;return n.value=o,n.fallback=!0,n}});function fa(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var Co=b("$ZodOptional",(t,e)=>{U.init(t,e),t._zod.optin="optional",t._zod.optout="optional",M(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),M(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${fn(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=>fa(i,o)):fa(s,o)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),tc=b("$ZodExactOptional",(t,e)=>{Co.init(t,e),M(t._zod,"values",()=>e.innerType._zod.values),M(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(n,r)=>e.innerType._zod.run(n,r)}),nc=b("$ZodNullable",(t,e)=>{U.init(t,e),M(t._zod,"optin",()=>e.innerType._zod.optin),M(t._zod,"optout",()=>e.innerType._zod.optout),M(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${fn(n.source)}|null)$`):void 0}),M(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)}),rc=b("$ZodDefault",(t,e)=>{U.init(t,e),t._zod.optin="optional",M(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=>da(s,e)):da(o,e)}});function da(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var oc=b("$ZodPrefault",(t,e)=>{U.init(t,e),t._zod.optin="optional",M(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))}),sc=b("$ZodNonOptional",(t,e)=>{U.init(t,e),M(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=>pa(s,t)):pa(o,t)}});function pa(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 ic=b("$ZodCatch",(t,e)=>{U.init(t,e),t._zod.optin="optional",M(t._zod,"optout",()=>e.innerType._zod.optout),M(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,_e()))},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,_e()))},input:n.value}),n.issues=[],n.fallback=!0),n)}});var ac=b("$ZodPipe",(t,e)=>{U.init(t,e),M(t._zod,"values",()=>e.in._zod.values),M(t._zod,"optin",()=>e.in._zod.optin),M(t._zod,"optout",()=>e.out._zod.optout),M(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 cc=b("$ZodReadonly",(t,e)=>{U.init(t,e),M(t._zod,"propValues",()=>e.innerType._zod.propValues),M(t._zod,"values",()=>e.innerType._zod.values),M(t._zod,"optin",()=>e.innerType?._zod?.optin),M(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(ma):ma(o)}});function ma(t){return t.value=Object.freeze(t.value),t}var uc=b("$ZodLazy",(t,e)=>{U.init(t,e),M(t._zod,"innerType",()=>{let n=e;return n._cachedInner||(n._cachedInner=e.getter()),n._cachedInner}),M(t._zod,"pattern",()=>t._zod.innerType?._zod?.pattern),M(t._zod,"propValues",()=>t._zod.innerType?._zod?.propValues),M(t._zod,"optin",()=>t._zod.innerType?._zod?.optin??void 0),M(t._zod,"optout",()=>t._zod.innerType?._zod?.optout??void 0),t._zod.parse=(n,r)=>t._zod.innerType._zod.run(n,r)}),lc=b("$ZodCustom",(t,e)=>{te.init(t,e),U.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=>ha(s,n,r,t));ha(o,n,r,t)}});function ha(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(Ot(o))}}var fc,Ny=Symbol("ZodOutput"),$y=Symbol("ZodInput"),To=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 Yd(){return new To}(fc=globalThis).__zod_globalRegistry??(fc.__zod_globalRegistry=Yd());var wt=globalThis.__zod_globalRegistry;function dc(t,e){return new t({type:"string",...I(e)})}function pc(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...I(e)})}function No(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...I(e)})}function mc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...I(e)})}function hc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(e)})}function yc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(e)})}function gc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(e)})}function bc(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...I(e)})}function wc(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...I(e)})}function _c(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(e)})}function xc(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...I(e)})}function Ec(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(e)})}function Sc(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...I(e)})}function Ac(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...I(e)})}function vc(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(e)})}function Dc(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(e)})}function Rc(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(e)})}function kc(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(e)})}function Ic(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(e)})}function Oc(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...I(e)})}function Cc(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...I(e)})}function Tc(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...I(e)})}function Nc(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...I(e)})}function $c(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(e)})}function zc(t,e){return new t({type:"string",format:"date",check:"string_format",...I(e)})}function Pc(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...I(e)})}function Lc(t,e){return new t({type:"string",format:"duration",check:"string_format",...I(e)})}function Mc(t,e){return new t({type:"number",checks:[],...I(e)})}function Fc(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...I(e)})}function Zc(t,e){return new t({type:"boolean",...I(e)})}function Bc(t,e){return new t({type:"null",...I(e)})}function jc(t){return new t({type:"unknown"})}function Uc(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 yn(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 gn(t,e){return new Ro({check:"greater_than",...I(e),value:t,inclusive:!0})}function or(t,e){return new Ji({check:"multiple_of",...I(e),value:t})}function sr(t,e){return new Wi({check:"max_length",...I(e),maximum:t})}function Ct(t,e){return new Yi({check:"min_length",...I(e),minimum:t})}function ir(t,e){return new Xi({check:"length_equals",...I(e),length:t})}function $o(t,e){return new Hi({check:"string_format",format:"regex",...I(e),pattern:t})}function zo(t){return new ea({check:"string_format",format:"lowercase",...I(t)})}function Po(t){return new ta({check:"string_format",format:"uppercase",...I(t)})}function Lo(t,e){return new na({check:"string_format",format:"includes",...I(e),includes:t})}function Mo(t,e){return new ra({check:"string_format",format:"starts_with",...I(e),prefix:t})}function Fo(t,e){return new oa({check:"string_format",format:"ends_with",...I(e),suffix:t})}function et(t){return new sa({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 Qc(t,e,n){return new t({type:"array",element:e,...I(n)})}function Vc(t,e,n){return new t({type:"custom",check:"custom",fn:e,...I(n)})}function Gc(t,e){let n=Xd(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(Ot(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(Ot(s))}},t(r.value,r)),e);return n}function Xd(t,e){let n=new te({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??wt,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 J(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),J(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"&&oe(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 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>
+ `)}p.write("payload.value = newResult;"),p.write("return payload;");let E=p.compile();return(S,_)=>E(f,S,_)},s,i=wt,a=!kt.jitless,u=a&&Eo.value,d=e.catchall,l;t._zod.parse=(f,p)=>{l??(l=r.value);let g=f.value;return i(g)?a&&u&&p?.async===!1&&p.jitless!==!0?(s||(s=o(e.shape)),f=s(f,p),d?Xa([],g,f,p,l,t):f):n(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:g,inst:t}),f)}});function ma(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=>!et(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=>he(i,r,xe())))}),e)}var $o=b("$ZodUnion",(t,e)=>{U.init(t,e),M(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),M(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),M(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),M(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=>pn(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=>ma(a,r,t,o)):ma(i,r,t,o)}});var ec=b("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,$o.init(t,e);let n=t._zod.parse;M(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=Ot(()=>{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(!wt(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)}}),tc=b("$ZodIntersection",(t,e)=>{U.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])=>ha(n,c,u)):ha(n,s,i)}});function To(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=To(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=To(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 ha(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}),et(t))return t;let i=To(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 nc=b("$ZodRecord",(t,e)=>{U.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=>he(p,r,xe())),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(...Ge(u,p.issues)),n.value[l]=p.value})):(f.issues.length&&n.issues.push(...Ge(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"&&Io.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=>he(l,r,xe())),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(...Ge(a,l.issues)),n.value[c.value]=l.value})):(d.issues.length&&n.issues.push(...Ge(a,d.issues)),n.value[c.value]=d.value)}}return s.length?Promise.all(s).then(()=>n):n}});var rc=b("$ZodEnum",(t,e)=>{U.init(t,e);let n=fn(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(o=>xo.has(typeof o)).map(o=>typeof o=="string"?Ve(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}}),oc=b("$ZodLiteral",(t,e)=>{if(U.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"?Ve(r):r?Ve(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 sc=b("$ZodTransform",(t,e)=>{U.init(t,e),t._zod.optin="optional",t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Rt(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 Te;return n.value=o,n.fallback=!0,n}});function ya(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var zo=b("$ZodOptional",(t,e)=>{U.init(t,e),t._zod.optin="optional",t._zod.optout="optional",M(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),M(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${pn(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=>ya(i,o)):ya(s,o)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),ic=b("$ZodExactOptional",(t,e)=>{zo.init(t,e),M(t._zod,"values",()=>e.innerType._zod.values),M(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(n,r)=>e.innerType._zod.run(n,r)}),ac=b("$ZodNullable",(t,e)=>{U.init(t,e),M(t._zod,"optin",()=>e.innerType._zod.optin),M(t._zod,"optout",()=>e.innerType._zod.optout),M(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${pn(n.source)}|null)$`):void 0}),M(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)}),cc=b("$ZodDefault",(t,e)=>{U.init(t,e),t._zod.optin="optional",M(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=>ga(s,e)):ga(o,e)}});function ga(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var uc=b("$ZodPrefault",(t,e)=>{U.init(t,e),t._zod.optin="optional",M(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))}),lc=b("$ZodNonOptional",(t,e)=>{U.init(t,e),M(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=>ba(s,t)):ba(o,t)}});function ba(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 fc=b("$ZodCatch",(t,e)=>{U.init(t,e),t._zod.optin="optional",M(t._zod,"optout",()=>e.innerType._zod.optout),M(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=>he(i,r,xe()))},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=>he(s,r,xe()))},input:n.value}),n.issues=[],n.fallback=!0),n)}});var dc=b("$ZodPipe",(t,e)=>{U.init(t,e),M(t._zod,"values",()=>e.in._zod.values),M(t._zod,"optin",()=>e.in._zod.optin),M(t._zod,"optout",()=>e.out._zod.optout),M(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=>nr(i,e.in,r)):nr(s,e.in,r)}let o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>nr(s,e.out,r)):nr(o,e.out,r)}});function nr(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 pc=b("$ZodReadonly",(t,e)=>{U.init(t,e),M(t._zod,"propValues",()=>e.innerType._zod.propValues),M(t._zod,"values",()=>e.innerType._zod.values),M(t._zod,"optin",()=>e.innerType?._zod?.optin),M(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(wa):wa(o)}});function wa(t){return t.value=Object.freeze(t.value),t}var mc=b("$ZodLazy",(t,e)=>{U.init(t,e),M(t._zod,"innerType",()=>{let n=e;return n._cachedInner||(n._cachedInner=e.getter()),n._cachedInner}),M(t._zod,"pattern",()=>t._zod.innerType?._zod?.pattern),M(t._zod,"propValues",()=>t._zod.innerType?._zod?.propValues),M(t._zod,"optin",()=>t._zod.innerType?._zod?.optin??void 0),M(t._zod,"optout",()=>t._zod.innerType?._zod?.optout??void 0),t._zod.parse=(n,r)=>t._zod.innerType._zod.run(n,r)}),hc=b("$ZodCustom",(t,e)=>{te.init(t,e),U.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=>_a(s,n,r,t));_a(o,n,r,t)}});function _a(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(Ct(o))}}var yc,Zy=Symbol("ZodOutput"),By=Symbol("ZodInput"),Po=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 op(){return new Po}(yc=globalThis).__zod_globalRegistry??(yc.__zod_globalRegistry=op());var _t=globalThis.__zod_globalRegistry;function gc(t,e){return new t({type:"string",...I(e)})}function bc(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...I(e)})}function Lo(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...I(e)})}function wc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...I(e)})}function _c(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(e)})}function Ec(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(e)})}function xc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(e)})}function Sc(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...I(e)})}function Ac(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...I(e)})}function vc(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(e)})}function Dc(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...I(e)})}function Rc(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(e)})}function kc(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...I(e)})}function Ic(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...I(e)})}function Oc(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(e)})}function Cc(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(e)})}function Tc(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(e)})}function Nc(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(e)})}function $c(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(e)})}function zc(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...I(e)})}function Pc(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...I(e)})}function Lc(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...I(e)})}function Mc(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...I(e)})}function Fc(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(e)})}function Zc(t,e){return new t({type:"string",format:"date",check:"string_format",...I(e)})}function Bc(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...I(e)})}function jc(t,e){return new t({type:"string",format:"duration",check:"string_format",...I(e)})}function Uc(t,e){return new t({type:"number",checks:[],...I(e)})}function Qc(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...I(e)})}function Vc(t,e){return new t({type:"boolean",...I(e)})}function Gc(t,e){return new t({type:"null",...I(e)})}function qc(t){return new t({type:"unknown"})}function Jc(t,e){return new t({type:"never",...I(e)})}function sr(t,e){return new Oo({check:"less_than",...I(e),value:t,inclusive:!1})}function bn(t,e){return new Oo({check:"less_than",...I(e),value:t,inclusive:!0})}function ir(t,e){return new Co({check:"greater_than",...I(e),value:t,inclusive:!1})}function wn(t,e){return new Co({check:"greater_than",...I(e),value:t,inclusive:!0})}function ar(t,e){return new Hi({check:"multiple_of",...I(e),value:t})}function cr(t,e){return new ta({check:"max_length",...I(e),maximum:t})}function Tt(t,e){return new na({check:"min_length",...I(e),minimum:t})}function ur(t,e){return new ra({check:"length_equals",...I(e),length:t})}function Mo(t,e){return new oa({check:"string_format",format:"regex",...I(e),pattern:t})}function Fo(t){return new sa({check:"string_format",format:"lowercase",...I(t)})}function Zo(t){return new ia({check:"string_format",format:"uppercase",...I(t)})}function Bo(t,e){return new aa({check:"string_format",format:"includes",...I(e),includes:t})}function jo(t,e){return new ca({check:"string_format",format:"starts_with",...I(e),prefix:t})}function Uo(t,e){return new ua({check:"string_format",format:"ends_with",...I(e),suffix:t})}function tt(t){return new la({check:"overwrite",tx:t})}function Qo(t){return tt(e=>e.normalize(t))}function Vo(){return tt(t=>t.trim())}function Go(){return tt(t=>t.toLowerCase())}function qo(){return tt(t=>t.toUpperCase())}function Jo(){return tt(t=>_o(t))}function Kc(t,e,n){return new t({type:"array",element:e,...I(n)})}function Wc(t,e,n){return new t({type:"custom",check:"custom",fn:e,...I(n)})}function Yc(t,e){let n=sp(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(Ct(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(Ct(s))}},t(r.value,r)),e);return n}function sp(t,e){let n=new te({check:"custom",...I(e)});return n._zod.check=t,n}function Ko(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??_t,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 J(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),J(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"&&oe(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 Wo(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??(g=>g);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>
-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:bn(e,"input",t.processors),output:bn(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function oe(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 oe(r.element,n);if(r.type==="set")return oe(r.valueType,n);if(r.type==="lazy")return oe(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 oe(r.innerType,n);if(r.type==="intersection")return oe(r.left,n)||oe(r.right,n);if(r.type==="record"||r.type==="map")return oe(r.keyType,n)||oe(r.valueType,n);if(r.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:oe(r.in,n)||oe(r.out,n);if(r.type==="object"){for(let o in r.shape)if(oe(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(oe(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(oe(o,n))return!0;return!!(r.rest&&oe(r.rest,n))}return!1}var qc=(t,e={})=>n=>{let r=Vo({...n,processors:e});return J(t,r),Go(r,t),qo(r,t)},bn=(t,e,n={})=>r=>{let{libraryOptions:o,target:s}=r??{},i=Vo({...o??{},target:s,io:e,processors:n});return J(t,i),Go(i,t),qo(i,t)};var Hd={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=Hd[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}))])}},Kc=(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)},Wc=(t,e,n,r)=>{n.type="boolean"};var Yc=(t,e,n,r)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"};var Xc=(t,e,n,r)=>{n.not={}};var Hc=(t,e,n,r)=>{};var eu=(t,e,n,r)=>{let o=t._zod.def,s=un(o.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},tu=(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 nu=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var ru=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var ou=(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=J(s.element,e,{...r,path:[...r.path,"items"]})},su=(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]=J(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=J(s.catchall,e,{...r,path:[...r.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},iu=(t,e,n,r)=>{let o=t._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>J(a,e,{...r,path:[...r.path,s?"oneOf":"anyOf",c]}));s?n.oneOf=i:n.anyOf=i},au=(t,e,n,r)=>{let o=t._zod.def,s=J(o.left,e,{...r,path:[...r.path,"allOf",0]}),i=J(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 cu=(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=J(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=J(s.keyType,e,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=J(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)}},uu=(t,e,n,r)=>{let o=t._zod.def,s=J(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"}]},lu=(t,e,n,r)=>{let o=t._zod.def;J(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType},fu=(t,e,n,r)=>{let o=t._zod.def;J(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},du=(t,e,n,r)=>{let o=t._zod.def;J(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)))},pu=(t,e,n,r)=>{let o=t._zod.def;J(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},mu=(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;J(i,e,r);let a=e.seen.get(t);a.ref=i},hu=(t,e,n,r)=>{let o=t._zod.def;J(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType,n.readOnly=!0};var Jo=(t,e,n,r)=>{let o=t._zod.def;J(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType},yu=(t,e,n,r)=>{let o=t._zod.innerType;J(o,e,r);let s=e.seen.get(t);s.ref=o};var ip=b("ZodISODateTime",(t,e)=>{Ra.init(t,e),q.init(t,e)});function gu(t){return $c(ip,t)}var ap=b("ZodISODate",(t,e)=>{ka.init(t,e),q.init(t,e)});function bu(t){return zc(ap,t)}var cp=b("ZodISOTime",(t,e)=>{Ia.init(t,e),q.init(t,e)});function wu(t){return Pc(cp,t)}var up=b("ZodISODuration",(t,e)=>{Oa.init(t,e),q.init(t,e)});function _u(t){return Lc(up,t)}var xu=(t,e)=>{Jn.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>ci(t,n)},flatten:{value:n=>ai(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,kt,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,kt,2)}},isEmpty:{get(){return t.issues.length===0}}})},Eu=b("ZodError",xu),ue=b("ZodError",xu,{Parent:Error});var Su=Kn(ue),Au=Wn(ue),vu=pn(ue),Du=mn(ue),Ru=fi(ue),ku=di(ue),Iu=pi(ue),Ou=mi(ue),Cu=hi(ue),Tu=yi(ue),Nu=gi(ue),$u=bi(ue);var zu=new WeakMap;function wn(t,e,n){let r=Object.getPrototypeOf(t),o=zu.get(r);if(o||(o=new Set,zu.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 V=b("ZodType",(t,e)=>(U.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:bn(t,"input"),output:bn(t,"output")}}),t.toJSONSchema=qc(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,r)=>Su(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>vu(t,n,r),t.parseAsync=async(n,r)=>Au(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Du(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>Ru(t,n,r),t.decode=(n,r)=>ku(t,n,r),t.encodeAsync=async(n,r)=>Iu(t,n,r),t.decodeAsync=async(n,r)=>Ou(t,n,r),t.safeEncode=(n,r)=>Cu(t,n,r),t.safeDecode=(n,r)=>Tu(t,n,r),t.safeEncodeAsync=async(n,r)=>Nu(t,n,r),t.safeDecodeAsync=async(n,r)=>$u(t,n,r),wn(t,"ZodType",{check(...n){let r=this.def;return this.clone(F.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 xe(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(sm(n,r))},superRefine(n,r){return this.check(im(n,r))},overwrite(n){return this.check(et(n))},optional(){return Zu(this)},exactOptional(){return Vp(this)},nullable(){return Bu(this)},nullish(){return Zu(Bu(this))},nonoptional(n){return Yp(this,n)},array(){return j(this)},or(n){return Tt([this,n])},and(n){return Zp(this,n)},transform(n){return ju(this,Up(n))},default(n){return Jp(this,n)},prefault(n){return Wp(this,n)},catch(n){return Hp(this,n)},pipe(n){return ju(this,n)},readonly(){return nm(this)},describe(n){let r=this.clone();return wt.add(r,{description:n}),r},meta(...n){if(n.length===0)return wt.get(this);let r=this.clone();return wt.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 wt.get(t)?.description},configurable:!0}),t)),Uu=b("_ZodString",(t,e)=>{tr.init(t,e),V.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,wn(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(Ct(...r))},max(...r){return this.check(sr(...r))},length(...r){return this.check(ir(...r))},nonempty(...r){return this.check(Ct(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())}})}),pp=b("ZodString",(t,e)=>{tr.init(t,e),Uu.init(t,e),t.email=n=>t.check(pc(mp,n)),t.url=n=>t.check(bc(hp,n)),t.jwt=n=>t.check(Nc(Op,n)),t.emoji=n=>t.check(wc(yp,n)),t.guid=n=>t.check(No(Pu,n)),t.uuid=n=>t.check(mc(cr,n)),t.uuidv4=n=>t.check(hc(cr,n)),t.uuidv6=n=>t.check(yc(cr,n)),t.uuidv7=n=>t.check(gc(cr,n)),t.nanoid=n=>t.check(_c(gp,n)),t.guid=n=>t.check(No(Pu,n)),t.cuid=n=>t.check(xc(bp,n)),t.cuid2=n=>t.check(Ec(wp,n)),t.ulid=n=>t.check(Sc(_p,n)),t.base64=n=>t.check(Oc(Rp,n)),t.base64url=n=>t.check(Cc(kp,n)),t.xid=n=>t.check(Ac(xp,n)),t.ksuid=n=>t.check(vc(Ep,n)),t.ipv4=n=>t.check(Dc(Sp,n)),t.ipv6=n=>t.check(Rc(Ap,n)),t.cidrv4=n=>t.check(kc(vp,n)),t.cidrv6=n=>t.check(Ic(Dp,n)),t.e164=n=>t.check(Tc(Ip,n)),t.datetime=n=>t.check(gu(n)),t.date=n=>t.check(bu(n)),t.time=n=>t.check(wu(n)),t.duration=n=>t.check(_u(n))});function v(t){return dc(pp,t)}var q=b("ZodStringFormat",(t,e)=>{Q.init(t,e),Uu.init(t,e)}),mp=b("ZodEmail",(t,e)=>{ba.init(t,e),q.init(t,e)});var Pu=b("ZodGUID",(t,e)=>{ya.init(t,e),q.init(t,e)});var cr=b("ZodUUID",(t,e)=>{ga.init(t,e),q.init(t,e)});var hp=b("ZodURL",(t,e)=>{wa.init(t,e),q.init(t,e)});var yp=b("ZodEmoji",(t,e)=>{_a.init(t,e),q.init(t,e)});var gp=b("ZodNanoID",(t,e)=>{xa.init(t,e),q.init(t,e)});var bp=b("ZodCUID",(t,e)=>{Ea.init(t,e),q.init(t,e)});var wp=b("ZodCUID2",(t,e)=>{Sa.init(t,e),q.init(t,e)});var _p=b("ZodULID",(t,e)=>{Aa.init(t,e),q.init(t,e)});var xp=b("ZodXID",(t,e)=>{va.init(t,e),q.init(t,e)});var Ep=b("ZodKSUID",(t,e)=>{Da.init(t,e),q.init(t,e)});var Sp=b("ZodIPv4",(t,e)=>{Ca.init(t,e),q.init(t,e)});var Ap=b("ZodIPv6",(t,e)=>{Ta.init(t,e),q.init(t,e)});var vp=b("ZodCIDRv4",(t,e)=>{Na.init(t,e),q.init(t,e)});var Dp=b("ZodCIDRv6",(t,e)=>{$a.init(t,e),q.init(t,e)});var Rp=b("ZodBase64",(t,e)=>{Pa.init(t,e),q.init(t,e)});var kp=b("ZodBase64URL",(t,e)=>{La.init(t,e),q.init(t,e)});var Ip=b("ZodE164",(t,e)=>{Ma.init(t,e),q.init(t,e)});var Op=b("ZodJWT",(t,e)=>{Fa.init(t,e),q.init(t,e)});var Qu=b("ZodNumber",(t,e)=>{Io.init(t,e),V.init(t,e),t._zod.processJSONSchema=(r,o,s)=>Kc(t,r,o,s),wn(t,"ZodNumber",{gt(r,o){return this.check(rr(r,o))},gte(r,o){return this.check(gn(r,o))},min(r,o){return this.check(gn(r,o))},lt(r,o){return this.check(nr(r,o))},lte(r,o){return this.check(yn(r,o))},max(r,o){return this.check(yn(r,o))},int(r){return this.check(Lu(r))},safe(r){return this.check(Lu(r))},positive(r){return this.check(rr(0,r))},nonnegative(r){return this.check(gn(0,r))},negative(r){return this.check(nr(0,r))},nonpositive(r){return this.check(yn(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 N(t){return Mc(Qu,t)}var Cp=b("ZodNumberFormat",(t,e)=>{Za.init(t,e),Qu.init(t,e)});function Lu(t){return Fc(Cp,t)}var Tp=b("ZodBoolean",(t,e)=>{Ba.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Wc(t,n,r,o)});function Ve(t){return Zc(Tp,t)}var Np=b("ZodNull",(t,e)=>{ja.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Yc(t,n,r,o)});function $p(t){return Bc(Np,t)}var zp=b("ZodUnknown",(t,e)=>{Ua.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Hc(t,n,r,o)});function Mu(){return jc(zp)}var Pp=b("ZodNever",(t,e)=>{Qa.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Xc(t,n,r,o)});function Vu(t){return Uc(Pp,t)}var Lp=b("ZodArray",(t,e)=>{Va.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ou(t,n,r,o),t.element=e.element,wn(t,"ZodArray",{min(n,r){return this.check(Ct(n,r))},nonempty(n){return this.check(Ct(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 j(t,e){return Qc(Lp,t,e)}var Gu=b("ZodObject",(t,e)=>{Ja.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>su(t,n,r,o),F.defineLazy(t,"shape",()=>e.shape),wn(t,"ZodObject",{keyof(){return ee(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Mu()})},loose(){return this.clone({...this._zod.def,catchall:Mu()})},strict(){return this.clone({...this._zod.def,catchall:Vu()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return F.extend(this,n)},safeExtend(n){return F.safeExtend(this,n)},merge(n){return F.merge(this,n)},pick(n){return F.pick(this,n)},omit(n){return F.omit(this,n)},partial(...n){return F.partial(Ju,this,n[0])},required(...n){return F.required(Ku,this,n[0])}})});function tt(t,e){let n={type:"object",shape:t??{},...F.normalizeParams(e)};return new Gu(n)}function O(t,e){return new Gu({type:"object",shape:t,catchall:Vu(),...F.normalizeParams(e)})}var qu=b("ZodUnion",(t,e)=>{Oo.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>iu(t,n,r,o),t.options=e.options});function Tt(t,e){return new qu({type:"union",options:t,...F.normalizeParams(e)})}var Mp=b("ZodDiscriminatedUnion",(t,e)=>{qu.init(t,e),Ka.init(t,e)});function Nt(t,e,n){return new Mp({type:"union",options:e,discriminator:t,...F.normalizeParams(n)})}var Fp=b("ZodIntersection",(t,e)=>{Wa.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>au(t,n,r,o)});function Zp(t,e){return new Fp({type:"intersection",left:t,right:e})}var Fu=b("ZodRecord",(t,e)=>{Ya.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>cu(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType});function Ee(t,e,n){return!e||!e._zod?new Fu({type:"record",keyType:v(),valueType:t,...F.normalizeParams(e)}):new Fu({type:"record",keyType:t,valueType:e,...F.normalizeParams(n)})}var Ko=b("ZodEnum",(t,e)=>{Xa.init(t,e),V.init(t,e),t._zod.processJSONSchema=(r,o,s)=>eu(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:[],...F.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:[],...F.normalizeParams(o),entries:s})}});function ee(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new Ko({type:"enum",entries:n,...F.normalizeParams(e)})}var Bp=b("ZodLiteral",(t,e)=>{Ha.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>tu(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 Z(t,e){return new Bp({type:"literal",values:Array.isArray(t)?t:[t],...F.normalizeParams(e)})}var jp=b("ZodTransform",(t,e)=>{ec.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ru(t,n,r,o),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Dt(t.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(F.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(F.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 Up(t){return new jp({type:"transform",transform:t})}var Ju=b("ZodOptional",(t,e)=>{Co.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Jo(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Zu(t){return new Ju({type:"optional",innerType:t})}var Qp=b("ZodExactOptional",(t,e)=>{tc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Jo(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Vp(t){return new Qp({type:"optional",innerType:t})}var Gp=b("ZodNullable",(t,e)=>{nc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>uu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Bu(t){return new Gp({type:"nullable",innerType:t})}var qp=b("ZodDefault",(t,e)=>{rc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>fu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Jp(t,e){return new qp({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():F.shallowClone(e)}})}var Kp=b("ZodPrefault",(t,e)=>{oc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>du(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Wp(t,e){return new Kp({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():F.shallowClone(e)}})}var Ku=b("ZodNonOptional",(t,e)=>{sc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>lu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Yp(t,e){return new Ku({type:"nonoptional",innerType:t,...F.normalizeParams(e)})}var Xp=b("ZodCatch",(t,e)=>{ic.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>pu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Hp(t,e){return new Xp({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var em=b("ZodPipe",(t,e)=>{ac.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>mu(t,n,r,o),t.in=e.in,t.out=e.out});function ju(t,e){return new em({type:"pipe",in:t,out:e})}var tm=b("ZodReadonly",(t,e)=>{cc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>hu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function nm(t){return new tm({type:"readonly",innerType:t})}var rm=b("ZodLazy",(t,e)=>{uc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>yu(t,n,r,o),t.unwrap=()=>t._zod.def.getter()});function Wo(t){return new rm({type:"lazy",getter:t})}var om=b("ZodCustom",(t,e)=>{lc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>nu(t,n,r,o)});function sm(t,e={}){return Vc(om,t,e)}function im(t,e){return Gc(t,e)}function nt(t){let e=Wo(()=>Tt([v(t),N(),Ve(),$p(),j(e),Ee(v(),e)]));return e}var Wu=t=>"field"in t?[t]:("all"in t?t.all:t.any).flatMap(Wu),ur=t=>Wu(t);var $t=(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=$t(o,e);if(s===!1)return!1;r||=s===void 0}return r?void 0:!0}for(let o of n){let s=$t(o,e);if(s===!0)return!0;r||=s===void 0}return r?void 0:!1},Yu=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}},Xu=(t,e={})=>{let n=o=>{let s=j(o),i=e.maximumChildren===void 0?s:s.max(e.maximumChildren);return Tt([t,O({all:i}),O({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 _t(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=_t(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=>_t(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(`${_t(o)}:${_t(t[o],e)}`);n=`{${r.join(",")}}`}return e.delete(t),n}var am=new TextEncoder,rt=t=>am.encode(t),Ce=t=>rt(t).byteLength,se=class extends Error{constructor(){super("Byte stream exceeds the configured limit"),this.name="ByteLimitExceededError"}},cm=(t,e)=>{let n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.byteLength;return n},zt=t=>typeof t=="string"?{async*[Symbol.asyncIterator](){yield rt(t)}}:t instanceof Uint8Array?{async*[Symbol.asyncIterator](){yield t}}:t,Hu=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()}}}),Xo=async(t,e)=>{let n=[],r=0;for await(let o of zt(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 cm(n,r)},Te=async(t,e)=>{let n=await Xo(t,e+1);if(n.byteLength>e)throw new se;return n},le=t=>new TextDecoder("utf-8",{fatal:!0}).decode(t),Pt=t=>t.charCodeAt(0)===65279?t.slice(1):t;var el=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")}},Ho=(t,e)=>{if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return el(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(Ho(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))el(o),s!==void 0&&Object.defineProperty(r,o,{value:Ho(s,e),enumerable:!0,configurable:!0,writable:!0})}finally{e.delete(t)}return r}throw new Error("Value cannot be represented as JSON")},ot=t=>Ho(t,new Set),fe=t=>{let e=_t(ot(t));if(e===void 0)throw new Error("Value cannot be represented as canonical JSON");return e},_n=(t,e)=>t===void 0||e===void 0?t===e:fe(t)===fe(e),Ne=(t,e)=>t<e?-1:t>e?1:0,es=async t=>{let e=typeof t=="string"?rt(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("")},tl=async t=>`sha256:${await es(t)}`;var nl=Nt("type",[O({type:Z("document")}),O({type:Z("json"),path:j(v()).min(1)}),O({type:Z("markdown-body")}),O({type:Z("markdown-frontmatter")})]),ts=O({documentId:v().min(1),revision:v().min(1),representation:nl}),um=t=>{let e=nl.parse(t);return e.type==="json"?Object.freeze({...e,path:Object.freeze([...e.path])}):Object.freeze(e)},rl=t=>{let e=ts.parse(t);return Object.freeze({...e,representation:um(e.representation)})};var xn=["json","markdown","mdx"],ol=t=>typeof t=="string"&&xn.includes(t),sl=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 lr=O({id:v().min(1),revision:v().min(1),contentRef:v().min(1),format:ee(xn).optional()}),fr=O({sourceId:v().min(1),referenceId:v().min(1),reference:ts});var Lt=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 $e=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])}},lm=(t,e)=>Ne(t.sourceId,e.sourceId)||Ne(t.referenceId,e.referenceId),En=({nodes:t,edges:e})=>{let n=t.map(a=>Object.freeze(lr.parse(a))).sort((a,c)=>Ne(a.id,c.id)),r=new Map,o=new Map;for(let a of n){if(r.has(a.id))throw new $e({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 $e({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=fr.parse(a);return Object.freeze({...c,reference:rl(c.reference)})}).sort(lm),i=new Set;for(let a of s){if(r.get(a.sourceId)===void 0)throw new $e({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 $e({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 $e({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 $e({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)})},fm=t=>new Map(t.nodes.map(e=>[e.id,e]));var dr=({graph:t,rootIds:e})=>{let n=fm(t),r=Lt(t.edges),o=new Map,s=[],i=[],a=c=>{let u=n.get(c);if(u===void 0)throw new $e({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 $e({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(Ne))a(c);return Object.freeze(i)};var dm=v().regex(/^sha256:[a-f0-9]{64}$/),il=O({format:Z("webstudio-document-graph"),version:Z(1),nodes:j(lr),edges:j(fr),integrity:O({algorithm:Z("sha256"),checksum:dm})});var pm=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"}),ll=O({_id:v().min(1),_type:Z("asset.file"),name:v().min(1),description:v().optional(),path:pm,key:v(),folderId:v().min(1).optional(),extension:v().regex(/^[a-z0-9]*$/),mimeType:v().min(1),size:N().int().nonnegative(),createdAt:v().datetime().optional(),revision:v().min(1),contentRef:v().min(1),properties:Ee(v(),nt()),excerpt:v().optional(),metadataError:O({code:v().min(1),message:v().min(1),reason:v().min(1).optional(),line:N().int().positive().optional(),column:N().int().positive().optional()}).optional()}),rs=ll.partial().required({_id:!0}),mm=ee(["null","boolean","number","string","object","array"]),hm=tt({format:Z("webstudio-builder-asset-field-catalog"),version:Z(1),canonicalRevision:v().regex(/^sha256:[a-f0-9]{64}$/),documentCount:N().int().nonnegative(),fields:Ee(v().min(1),tt({queryPath:j(v().min(1)).min(1).max(k.fieldPathDepth).optional(),types:j(mm).min(1),occurrences:N().int().positive(),optional:Z(!0).optional(),mixed:Z(!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"})}}),pr=v().regex(/^sha256:[a-f0-9]{64}$/),fl=O({fields:j(j(v().min(1)).min(1).max(k.fieldPathDepth)).min(1).max(k.outputFieldCount+1),rows:j(j(nt())).max(k.resultCount),totalCount:N().int().nonnegative().max(k.candidateDocuments),hasMore:Ve()}).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"})}),al=O({format:Z("webstudio-content-database"),version:Z(1),assetRevision:pr,documents:j(rs),documentGraph:il.optional(),contents:Ee(v().min(1),v()).optional(),assetReferences:Ee(v().min(1),j(O({start:N().int().nonnegative(),end:N().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:Ee(v().min(1),j(O({path:j(v().min(1).or(N().int().nonnegative())).min(1),assetId:v().min(1),suffix:v().min(1).optional(),structured:Z(!0).optional()}))).optional(),fieldCatalog:hm,queries:Ee(pr,fl).optional(),database:O({maxBytes:N().int().positive(),unboundedBytes:N().int().nonnegative(),sourceDocumentCount:N().int().nonnegative(),includedDocumentCount:N().int().nonnegative().optional()}).optional(),integrity:O({algorithm:Z("sha256"),checksum:pr})}).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"})}),ym=Nt("mode",[O({mode:Z("none")}),O({mode:Z("full"),maxBytes:N().int().positive().max(k.hydratedFileBytes).optional()}),O({mode:Z("range"),offset:N().int().nonnegative(),length:N().int().positive().max(k.hydratedRangeBytes)}),O({mode:Z("markdown-body-ref"),maxBytes:N().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"]},dl=Object.keys(os),pl=["url","width","height"],mr=t=>pl.includes(t),ml=dl.filter(t=>mr(t)===!1&&t!=="excerpt"),hl=ml.filter(t=>t!=="id"),yl=t=>ml.includes(t),gm=ee(dl),Sn=j(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||gm.safeParse(t[0]).success===!1)&&e.addIssue({code:"custom",message:"Asset query field path is unsupported"})}),ns=Ve().default(!0),bm=Nt("mode",[O({mode:Z("all"),includeMetadata:ns}),O({mode:Z("base"),includeMetadata:ns}),O({mode:Z("fields"),includeMetadata:ns,fields:j(Sn).max(k.outputFieldCount).refine(t=>new Set(t.map(Yu)).size===t.length,{error:"Selected output fields must be unique"})})]),wm={mode:"fields",includeMetadata:!1,fields:pl.map(t=>[t])},gl=["eq","ne","contains","startsWith","endsWith","gt","gte","lt","lte"],Vb=[...gl,"in","exists","isEmpty"],_m=O({field:Sn,operator:ee(gl),value:nt()}),xm=O({field:Sn,operator:Z("in"),value:j(nt()).max(k.resultCount)}),Em=O({field:Sn,operator:ee(["exists","isEmpty"]),value:Ve()}),Sm=Nt("operator",[_m,xm,Em]),Am=Xu(Sm,{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 vm=Am,bl=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]},Dm=O({field:Sn,direction:ee(["asc","desc"])}),Rm=ee(["many","one","first","last"]),km=({output:t,content:e})=>t.includeMetadata||t.mode==="all"||t.mode==="fields"&&t.fields.length>0||e.mode!=="none",st=O({result:Rm.default("many"),where:vm.default({all:[]}),sort:j(Dm).max(k.sortCount).default([]),limit:N().int().nonnegative().max(k.resultCount).default(k.defaultResultCount),offset:N().int().nonnegative().max(k.candidateDocuments).default(0),output:bm.default(wm),content:ym.default({mode:"none"})}).superRefine((t,e)=>{km(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."})}),wl=O({query:st,indexRevision:v().min(1).max(255).optional()}),Im=tt({_id:v().min(1),revision:v().min(1),contentRef:v().min(1),encoding:Z("utf-8"),text:v(),range:tt({offset:N().int().nonnegative(),length:N().int().nonnegative(),total:N().int().nonnegative()}).optional()}),Om=Im.omit({_id:!0,revision:!0,contentRef:!0}),_l=ll.omit({_id:!0,_type:!0,contentRef:!0}).partial().extend({id:v().min(1),url:v().min(1).optional(),width:N().positive().optional(),height:N().positive().optional(),content:Om.optional()}).refine(t=>t.width===void 0==(t.height===void 0),{error:"Asset dimensions must include both width and height"}),Cm=O({format:Z("webstudio-content-database"),version:Z(1),revision:pr,usedBytes:N().int().nonnegative(),maxBytes:N().int().positive(),unboundedBytes:N().int().nonnegative(),includedDocumentCount:N().int().nonnegative(),omittedDocumentCount:N().int().nonnegative(),omissionReason:ee(["size","unavailable"]).optional(),truncated:Ve()}),cl=Cm.pick({usedBytes:!0,maxBytes:!0,unboundedBytes:!0,includedDocumentCount:!0,omittedDocumentCount:!0,omissionReason:!0,truncated:!0}),ss=O({items:j(_l),totalCount:N().int().nonnegative(),hasMore:Ve()}),Tm=O({item:_l.nullable(),totalCount:N().int().nonnegative()}),xl=Tt([ss,Tm]),ul=O({line:N().int().positive(),column:N().int().positive(),offset:N().int().nonnegative().optional()}),Nm=O({severity:ee(["error","warning"]),scope:ee(["query","database"]),phase:ee(["metadata","reference","source"]),code:v().min(1),message:v().min(1),assetId:v().min(1),path:v().min(1),line:N().int().positive().optional(),column:N().int().positive().optional(),reference:v().min(1).optional(),nodeType:v().min(1).optional(),reason:v().min(1).optional(),sourceRange:O({start:ul,end:ul}).optional()}),$m=O({severity:ee(["error","warning"]),code:v().min(1),path:j(v()),message:v().min(1)}),zm=O({scope:Z("query-preview"),queryIssues:j($m).optional(),queryWarnings:j(v().min(1)).optional(),query:cl,database:cl,artifacts:O({query:al,database:al}).optional(),unresolved:xl.optional(),issues:j(Nm).optional(),issueCount:N().int().nonnegative().optional(),issuesTruncated:Ve().optional()}),Gb=O({data:xl,__diagnostics__:zm}),Pm=ee(["INVALID_REQUEST","REQUEST_CANCELLED","UNAUTHORIZED","FORBIDDEN","STALE_INDEX","CONTENT_IDENTITY_REQUIRED","CONTENT_NOT_TEXT","CONTENT_DECODING_FAILED","CONTENT_LIMIT_EXCEEDED","MULTIPLE_RESULTS","INTERNAL_ERROR"]),Lm=tt({ok:Z(!1),error:tt({code:Pm,message:v().min(1),retryable:Ve(),details:Ee(v(),nt()).optional()}),meta:tt({queryHash:v().min(1).optional(),indexRevision:v().min(1).optional(),assetRevision:v().min(1).optional()}).optional()}),El=({code:t,message:e,retryable:n=!1,details:r})=>Lm.parse({ok:!1,error:{code:t,message:e,retryable:n,details:r}});var Sl=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 Fm(o)}};var is=(t,e)=>e+"/"+Mm(t),Mm=t=>t.toString().replace(/~/g,"~0").replace(/\//g,"~1"),Fm=t=>t.toString().replace(/~1/g,"/").replace(/~0/g,"~");var hr=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 Mt=t=>typeof t=="object"&&t!==null&&Array.isArray(t)===!1,yr=t=>{if(Mt(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}},Zm=(t,e)=>{let n=yr(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}},Bm=t=>`#${t}`;var Al=async({source:t,maximumBytes:e=k.hydratedFileBytes})=>{let n;try{n=await Te(t,e)}catch(o){throw o instanceof se?new de({code:"CONTENT_LIMIT_EXCEEDED",message:"JSON document exceeds the byte limit",cause:o}):o}let r;try{r=Pt(le(n))}catch(o){throw new de({code:"CONTENT_DECODING_FAILED",message:"JSON document is not valid UTF-8",cause:o})}try{return ot(JSON.parse(r))}catch(o){throw new de({code:"INVALID_DOCUMENT",message:"JSON document is invalid",cause:o})}};var jm=(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(Mt(n)&&Object.hasOwn(n,r)){n=n[r];continue}return}return n},vl=({document:t,representation:e})=>{let n=ot(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=jm(n,e.path);if(r===void 0)throw new de({code:"JSON_PATH_NOT_FOUND",message:"JSON document path does not exist"});return r},Um=(t,e,n)=>{Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0})},gr=({document:t,references:e,allowUnresolvedReferences:n=!1})=>{let r=ot(t),o=new Set,s=(a,c)=>{let u=Bm(c);if(Zm(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 ot(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(Mt(a)){let l={};for(let[f,p]of Object.entries(a))Um(l,f,s(p,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 br=Symbol.for("yaml.alias"),wr=Symbol.for("yaml.document"),Se=Symbol.for("yaml.map"),as=Symbol.for("yaml.pair"),pe=Symbol.for("yaml.scalar"),Ge=Symbol.for("yaml.seq"),ie=Symbol.for("yaml.node.type"),he=t=>!!t&&typeof t=="object"&&t[ie]===br,ze=t=>!!t&&typeof t=="object"&&t[ie]===wr,ye=t=>!!t&&typeof t=="object"&&t[ie]===Se,$=t=>!!t&&typeof t=="object"&&t[ie]===as,T=t=>!!t&&typeof t=="object"&&t[ie]===pe,ge=t=>!!t&&typeof t=="object"&&t[ie]===Ge;function B(t){if(t&&typeof t=="object")switch(t[ie]){case Se:case Ge:return!0}return!1}function z(t){if(t&&typeof t=="object")switch(t[ie]){case br:case Se:case pe:case Ge:return!0}return!1}var _r=t=>(T(t)||B(t))&&!!t.anchor;var ce=Symbol("break visit"),Dl=Symbol("skip children"),Pe=Symbol("remove node");function Le(t,e){let n=Rl(e);ze(t)?Ft(null,t.contents,n,Object.freeze([t]))===Pe&&(t.contents=null):Ft(null,t,n,Object.freeze([]))}Le.BREAK=ce;Le.SKIP=Dl;Le.REMOVE=Pe;function Ft(t,e,n,r){let o=kl(t,e,n,r);if(z(o)||$(o))return Il(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=Ft(s,e.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===ce)return ce;i===Pe&&(e.items.splice(s,1),s-=1)}}}else if($(e)){r=Object.freeze(r.concat(e));let s=Ft("key",e.key,n,r);if(s===ce)return ce;s===Pe&&(e.key=null);let i=Ft("value",e.value,n,r);if(i===ce)return ce;i===Pe&&(e.value=null)}}return o}async function xr(t,e){let n=Rl(e);ze(t)?await Zt(null,t.contents,n,Object.freeze([t]))===Pe&&(t.contents=null):await Zt(null,t,n,Object.freeze([]))}xr.BREAK=ce;xr.SKIP=Dl;xr.REMOVE=Pe;async function Zt(t,e,n,r){let o=await kl(t,e,n,r);if(z(o)||$(o))return Il(t,r,o),Zt(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 Zt(s,e.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===ce)return ce;i===Pe&&(e.items.splice(s,1),s-=1)}}}else if($(e)){r=Object.freeze(r.concat(e));let s=await Zt("key",e.key,n,r);if(s===ce)return ce;s===Pe&&(e.key=null);let i=await Zt("value",e.value,n,r);if(i===ce)return ce;i===Pe&&(e.value=null)}}return o}function Rl(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 kl(t,e,n,r){if(typeof n=="function")return n(t,e,r);if(ye(e))return n.Map?.(t,e,r);if(ge(e))return n.Seq?.(t,e,r);if($(e))return n.Pair?.(t,e,r);if(T(e))return n.Scalar?.(t,e,r);if(he(e))return n.Alias?.(t,e,r)}function Il(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(ze(r))r.contents=n;else{let o=he(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}var Qm={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Vm=t=>t.replace(/[!,[\]{}]/g,e=>Qm[e]),Me=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+Vm(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&&z(e.contents)){let s={};Le(e.contents,(i,a)=>{z(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(`
-`)}};Me.defaultYaml={explicit:!1,version:"1.2"};Me.defaultTags={"!!":"tag:yaml.org,2002:"};function Er(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 Le(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 Ol(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&&(T(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 it(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=it(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=it(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=it(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=it(t,r,o,s);i===void 0?delete r[o]:i!==s&&(r[o]=i)}return t.call(e,n,r)}function H(t,e,n){if(Array.isArray(t))return t.map((r,o)=>H(r,String(o),n));if(t&&typeof t.toJSON=="function"){if(!n||!_r(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 at=class{constructor(e){Object.defineProperty(this,ie,{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(!ze(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=H(this,"",i);if(typeof o=="function")for(let{count:c,res:u}of i.anchors.values())o(u,c);return typeof s=="function"?it(s,{"":a},"",a):a}};var qe=class extends at{constructor(e){super(br),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=[],Le(e,{Node:(s,i)=>{(he(i)||_r(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||(H(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(Er(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(he(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($(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 at{constructor(e){super(pe),this.value=e}toJSON(e,n){return n?.keep?this.value:H(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 Gm="tag:yaml.org,2002:";function qm(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 Je(t,e,n){if(ze(t)&&(t=t.contents),z(t))return t;if($(t)){let l=n.schema[Se].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 qe(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=Gm+e.slice(2));let u=qm(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[Se]:Symbol.iterator in Object(t)?i[Ge]:i[Se]}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 R(t);return e?d.tag=e:u.default||(d.tag=u.tag),c&&(c.node=d),d}function An(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 Je(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 jt=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Bt=class extends at{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=>z(r)||$(r)?r.clone(e):r),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(jt(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,An(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&&T(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&&T(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,An(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}};var Cl=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function be(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Fe=(t,e,n)=>t.endsWith(`
-`)?be(n,e):n.includes(`
+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 Yo(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),g=p.schema;if(g.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(g)):Object.assign(u,g),Object.assign(u,d),a._zod.parent===l)for(let h in u)h==="$ref"||h==="allOf"||h in d||delete u[h];if(g.$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 g in u)g==="$ref"||g==="allOf"||g in p.def&&JSON.stringify(u[g])===JSON.stringify(p.def[g])&&delete u[g]}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:_n(e,"input",t.processors),output:_n(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function oe(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 oe(r.element,n);if(r.type==="set")return oe(r.valueType,n);if(r.type==="lazy")return oe(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 oe(r.innerType,n);if(r.type==="intersection")return oe(r.left,n)||oe(r.right,n);if(r.type==="record"||r.type==="map")return oe(r.keyType,n)||oe(r.valueType,n);if(r.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:oe(r.in,n)||oe(r.out,n);if(r.type==="object"){for(let o in r.shape)if(oe(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(oe(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(oe(o,n))return!0;return!!(r.rest&&oe(r.rest,n))}return!1}var Xc=(t,e={})=>n=>{let r=Ko({...n,processors:e});return J(t,r),Wo(r,t),Yo(r,t)},_n=(t,e,n={})=>r=>{let{libraryOptions:o,target:s}=r??{},i=Ko({...o??{},target:s,io:e,processors:n});return J(t,i),Wo(i,t),Yo(i,t)};var ip={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Hc=(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=ip[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}))])}},eu=(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)},tu=(t,e,n,r)=>{n.type="boolean"};var nu=(t,e,n,r)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"};var ru=(t,e,n,r)=>{n.not={}};var ou=(t,e,n,r)=>{};var su=(t,e,n,r)=>{let o=t._zod.def,s=fn(o.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},iu=(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 au=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var cu=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var uu=(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=J(s.element,e,{...r,path:[...r.path,"items"]})},lu=(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]=J(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=J(s.catchall,e,{...r,path:[...r.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},fu=(t,e,n,r)=>{let o=t._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>J(a,e,{...r,path:[...r.path,s?"oneOf":"anyOf",c]}));s?n.oneOf=i:n.anyOf=i},du=(t,e,n,r)=>{let o=t._zod.def,s=J(o.left,e,{...r,path:[...r.path,"allOf",0]}),i=J(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 pu=(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=J(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=J(s.keyType,e,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=J(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)}},mu=(t,e,n,r)=>{let o=t._zod.def,s=J(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"}]},hu=(t,e,n,r)=>{let o=t._zod.def;J(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType},yu=(t,e,n,r)=>{let o=t._zod.def;J(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},gu=(t,e,n,r)=>{let o=t._zod.def;J(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)))},bu=(t,e,n,r)=>{let o=t._zod.def;J(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},wu=(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;J(i,e,r);let a=e.seen.get(t);a.ref=i},_u=(t,e,n,r)=>{let o=t._zod.def;J(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType,n.readOnly=!0};var Xo=(t,e,n,r)=>{let o=t._zod.def;J(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType},Eu=(t,e,n,r)=>{let o=t._zod.innerType;J(o,e,r);let s=e.seen.get(t);s.ref=o};var pp=b("ZodISODateTime",(t,e)=>{Ta.init(t,e),q.init(t,e)});function xu(t){return Fc(pp,t)}var mp=b("ZodISODate",(t,e)=>{Na.init(t,e),q.init(t,e)});function Su(t){return Zc(mp,t)}var hp=b("ZodISOTime",(t,e)=>{$a.init(t,e),q.init(t,e)});function Au(t){return Bc(hp,t)}var yp=b("ZodISODuration",(t,e)=>{za.init(t,e),q.init(t,e)});function vu(t){return jc(yp,t)}var Du=(t,e)=>{Yn.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>pi(t,n)},flatten:{value:n=>di(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,It,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,It,2)}},isEmpty:{get(){return t.issues.length===0}}})},Ru=b("ZodError",Du),ue=b("ZodError",Du,{Parent:Error});var ku=Xn(ue),Iu=Hn(ue),Ou=hn(ue),Cu=yn(ue),Tu=yi(ue),Nu=gi(ue),$u=bi(ue),zu=wi(ue),Pu=_i(ue),Lu=Ei(ue),Mu=xi(ue),Fu=Si(ue);var Zu=new WeakMap;function En(t,e,n){let r=Object.getPrototypeOf(t),o=Zu.get(r);if(o||(o=new Set,Zu.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 V=b("ZodType",(t,e)=>(U.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:_n(t,"input"),output:_n(t,"output")}}),t.toJSONSchema=Xc(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,r)=>ku(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Ou(t,n,r),t.parseAsync=async(n,r)=>Iu(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Cu(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>Tu(t,n,r),t.decode=(n,r)=>Nu(t,n,r),t.encodeAsync=async(n,r)=>$u(t,n,r),t.decodeAsync=async(n,r)=>zu(t,n,r),t.safeEncode=(n,r)=>Pu(t,n,r),t.safeDecode=(n,r)=>Lu(t,n,r),t.safeEncodeAsync=async(n,r)=>Mu(t,n,r),t.safeDecodeAsync=async(n,r)=>Fu(t,n,r),En(t,"ZodType",{check(...n){let r=this.def;return this.clone(F.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 Se(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(dm(n,r))},superRefine(n,r){return this.check(pm(n,r))},overwrite(n){return this.check(tt(n))},optional(){return Vu(this)},exactOptional(){return Xp(this)},nullable(){return Gu(this)},nullish(){return Vu(Gu(this))},nonoptional(n){return om(this,n)},array(){return j(this)},or(n){return Nt([this,n])},and(n){return qp(this,n)},transform(n){return qu(this,Wp(n))},default(n){return tm(this,n)},prefault(n){return rm(this,n)},catch(n){return im(this,n)},pipe(n){return qu(this,n)},readonly(){return um(this)},describe(n){let r=this.clone();return _t.add(r,{description:n}),r},meta(...n){if(n.length===0)return _t.get(this);let r=this.clone();return _t.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 _t.get(t)?.description},configurable:!0}),t)),Ju=b("_ZodString",(t,e)=>{or.init(t,e),V.init(t,e),t._zod.processJSONSchema=(r,o,s)=>Hc(t,r,o,s);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,En(t,"_ZodString",{regex(...r){return this.check(Mo(...r))},includes(...r){return this.check(Bo(...r))},startsWith(...r){return this.check(jo(...r))},endsWith(...r){return this.check(Uo(...r))},min(...r){return this.check(Tt(...r))},max(...r){return this.check(cr(...r))},length(...r){return this.check(ur(...r))},nonempty(...r){return this.check(Tt(1,...r))},lowercase(r){return this.check(Fo(r))},uppercase(r){return this.check(Zo(r))},trim(){return this.check(Vo())},normalize(...r){return this.check(Qo(...r))},toLowerCase(){return this.check(Go())},toUpperCase(){return this.check(qo())},slugify(){return this.check(Jo())}})}),_p=b("ZodString",(t,e)=>{or.init(t,e),Ju.init(t,e),t.email=n=>t.check(bc(Ep,n)),t.url=n=>t.check(Sc(xp,n)),t.jwt=n=>t.check(Mc(Lp,n)),t.emoji=n=>t.check(Ac(Sp,n)),t.guid=n=>t.check(Lo(Bu,n)),t.uuid=n=>t.check(wc(fr,n)),t.uuidv4=n=>t.check(_c(fr,n)),t.uuidv6=n=>t.check(Ec(fr,n)),t.uuidv7=n=>t.check(xc(fr,n)),t.nanoid=n=>t.check(vc(Ap,n)),t.guid=n=>t.check(Lo(Bu,n)),t.cuid=n=>t.check(Dc(vp,n)),t.cuid2=n=>t.check(Rc(Dp,n)),t.ulid=n=>t.check(kc(Rp,n)),t.base64=n=>t.check(zc($p,n)),t.base64url=n=>t.check(Pc(zp,n)),t.xid=n=>t.check(Ic(kp,n)),t.ksuid=n=>t.check(Oc(Ip,n)),t.ipv4=n=>t.check(Cc(Op,n)),t.ipv6=n=>t.check(Tc(Cp,n)),t.cidrv4=n=>t.check(Nc(Tp,n)),t.cidrv6=n=>t.check($c(Np,n)),t.e164=n=>t.check(Lc(Pp,n)),t.datetime=n=>t.check(xu(n)),t.date=n=>t.check(Su(n)),t.time=n=>t.check(Au(n)),t.duration=n=>t.check(vu(n))});function v(t){return gc(_p,t)}var q=b("ZodStringFormat",(t,e)=>{Q.init(t,e),Ju.init(t,e)}),Ep=b("ZodEmail",(t,e)=>{Sa.init(t,e),q.init(t,e)});var Bu=b("ZodGUID",(t,e)=>{Ea.init(t,e),q.init(t,e)});var fr=b("ZodUUID",(t,e)=>{xa.init(t,e),q.init(t,e)});var xp=b("ZodURL",(t,e)=>{Aa.init(t,e),q.init(t,e)});var Sp=b("ZodEmoji",(t,e)=>{va.init(t,e),q.init(t,e)});var Ap=b("ZodNanoID",(t,e)=>{Da.init(t,e),q.init(t,e)});var vp=b("ZodCUID",(t,e)=>{Ra.init(t,e),q.init(t,e)});var Dp=b("ZodCUID2",(t,e)=>{ka.init(t,e),q.init(t,e)});var Rp=b("ZodULID",(t,e)=>{Ia.init(t,e),q.init(t,e)});var kp=b("ZodXID",(t,e)=>{Oa.init(t,e),q.init(t,e)});var Ip=b("ZodKSUID",(t,e)=>{Ca.init(t,e),q.init(t,e)});var Op=b("ZodIPv4",(t,e)=>{Pa.init(t,e),q.init(t,e)});var Cp=b("ZodIPv6",(t,e)=>{La.init(t,e),q.init(t,e)});var Tp=b("ZodCIDRv4",(t,e)=>{Ma.init(t,e),q.init(t,e)});var Np=b("ZodCIDRv6",(t,e)=>{Fa.init(t,e),q.init(t,e)});var $p=b("ZodBase64",(t,e)=>{Ba.init(t,e),q.init(t,e)});var zp=b("ZodBase64URL",(t,e)=>{ja.init(t,e),q.init(t,e)});var Pp=b("ZodE164",(t,e)=>{Ua.init(t,e),q.init(t,e)});var Lp=b("ZodJWT",(t,e)=>{Qa.init(t,e),q.init(t,e)});var Ku=b("ZodNumber",(t,e)=>{No.init(t,e),V.init(t,e),t._zod.processJSONSchema=(r,o,s)=>eu(t,r,o,s),En(t,"ZodNumber",{gt(r,o){return this.check(ir(r,o))},gte(r,o){return this.check(wn(r,o))},min(r,o){return this.check(wn(r,o))},lt(r,o){return this.check(sr(r,o))},lte(r,o){return this.check(bn(r,o))},max(r,o){return this.check(bn(r,o))},int(r){return this.check(ju(r))},safe(r){return this.check(ju(r))},positive(r){return this.check(ir(0,r))},nonnegative(r){return this.check(wn(0,r))},negative(r){return this.check(sr(0,r))},nonpositive(r){return this.check(bn(0,r))},multipleOf(r,o){return this.check(ar(r,o))},step(r,o){return this.check(ar(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 N(t){return Uc(Ku,t)}var Mp=b("ZodNumberFormat",(t,e)=>{Va.init(t,e),Ku.init(t,e)});function ju(t){return Qc(Mp,t)}var Fp=b("ZodBoolean",(t,e)=>{Ga.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>tu(t,n,r,o)});function qe(t){return Vc(Fp,t)}var Zp=b("ZodNull",(t,e)=>{qa.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>nu(t,n,r,o)});function Bp(t){return Gc(Zp,t)}var jp=b("ZodUnknown",(t,e)=>{Ja.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ou(t,n,r,o)});function Uu(){return qc(jp)}var Up=b("ZodNever",(t,e)=>{Ka.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ru(t,n,r,o)});function Wu(t){return Jc(Up,t)}var Qp=b("ZodArray",(t,e)=>{Wa.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>uu(t,n,r,o),t.element=e.element,En(t,"ZodArray",{min(n,r){return this.check(Tt(n,r))},nonempty(n){return this.check(Tt(1,n))},max(n,r){return this.check(cr(n,r))},length(n,r){return this.check(ur(n,r))},unwrap(){return this.element}})});function j(t,e){return Kc(Qp,t,e)}var Yu=b("ZodObject",(t,e)=>{Ha.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>lu(t,n,r,o),F.defineLazy(t,"shape",()=>e.shape),En(t,"ZodObject",{keyof(){return ee(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Uu()})},loose(){return this.clone({...this._zod.def,catchall:Uu()})},strict(){return this.clone({...this._zod.def,catchall:Wu()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return F.extend(this,n)},safeExtend(n){return F.safeExtend(this,n)},merge(n){return F.merge(this,n)},pick(n){return F.pick(this,n)},omit(n){return F.omit(this,n)},partial(...n){return F.partial(Hu,this,n[0])},required(...n){return F.required(el,this,n[0])}})});function nt(t,e){let n={type:"object",shape:t??{},...F.normalizeParams(e)};return new Yu(n)}function O(t,e){return new Yu({type:"object",shape:t,catchall:Wu(),...F.normalizeParams(e)})}var Xu=b("ZodUnion",(t,e)=>{$o.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>fu(t,n,r,o),t.options=e.options});function Nt(t,e){return new Xu({type:"union",options:t,...F.normalizeParams(e)})}var Vp=b("ZodDiscriminatedUnion",(t,e)=>{Xu.init(t,e),ec.init(t,e)});function $t(t,e,n){return new Vp({type:"union",options:e,discriminator:t,...F.normalizeParams(n)})}var Gp=b("ZodIntersection",(t,e)=>{tc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>du(t,n,r,o)});function qp(t,e){return new Gp({type:"intersection",left:t,right:e})}var Qu=b("ZodRecord",(t,e)=>{nc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>pu(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType});function Ae(t,e,n){return!e||!e._zod?new Qu({type:"record",keyType:v(),valueType:t,...F.normalizeParams(e)}):new Qu({type:"record",keyType:t,valueType:e,...F.normalizeParams(n)})}var Ho=b("ZodEnum",(t,e)=>{rc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(r,o,s)=>su(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 Ho({...e,checks:[],...F.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 Ho({...e,checks:[],...F.normalizeParams(o),entries:s})}});function ee(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new Ho({type:"enum",entries:n,...F.normalizeParams(e)})}var Jp=b("ZodLiteral",(t,e)=>{oc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>iu(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 Z(t,e){return new Jp({type:"literal",values:Array.isArray(t)?t:[t],...F.normalizeParams(e)})}var Kp=b("ZodTransform",(t,e)=>{sc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>cu(t,n,r,o),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Rt(t.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(F.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(F.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 Wp(t){return new Kp({type:"transform",transform:t})}var Hu=b("ZodOptional",(t,e)=>{zo.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Xo(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Vu(t){return new Hu({type:"optional",innerType:t})}var Yp=b("ZodExactOptional",(t,e)=>{ic.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Xo(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Xp(t){return new Yp({type:"optional",innerType:t})}var Hp=b("ZodNullable",(t,e)=>{ac.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>mu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Gu(t){return new Hp({type:"nullable",innerType:t})}var em=b("ZodDefault",(t,e)=>{cc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>yu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function tm(t,e){return new em({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():F.shallowClone(e)}})}var nm=b("ZodPrefault",(t,e)=>{uc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>gu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function rm(t,e){return new nm({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():F.shallowClone(e)}})}var el=b("ZodNonOptional",(t,e)=>{lc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>hu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function om(t,e){return new el({type:"nonoptional",innerType:t,...F.normalizeParams(e)})}var sm=b("ZodCatch",(t,e)=>{fc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>bu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function im(t,e){return new sm({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var am=b("ZodPipe",(t,e)=>{dc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>wu(t,n,r,o),t.in=e.in,t.out=e.out});function qu(t,e){return new am({type:"pipe",in:t,out:e})}var cm=b("ZodReadonly",(t,e)=>{pc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>_u(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function um(t){return new cm({type:"readonly",innerType:t})}var lm=b("ZodLazy",(t,e)=>{mc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Eu(t,n,r,o),t.unwrap=()=>t._zod.def.getter()});function es(t){return new lm({type:"lazy",getter:t})}var fm=b("ZodCustom",(t,e)=>{hc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>au(t,n,r,o)});function dm(t,e={}){return Wc(fm,t,e)}function pm(t,e){return Yc(t,e)}function rt(t){let e=es(()=>Nt([v(t),N(),qe(),Bp(),j(e),Ae(v(),e)]));return e}var tl=t=>"field"in t?[t]:("all"in t?t.all:t.any).flatMap(tl),dr=t=>tl(t);var zt=(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=zt(o,e);if(s===!1)return!1;r||=s===void 0}return r?void 0:!0}for(let o of n){let s=zt(o,e);if(s===!0)return!0;r||=s===void 0}return r?void 0:!1},nl=t=>JSON.stringify(t),ts=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=ts(o);n+=s.conditions,r=Math.max(r,s.depth+1)}return{conditions:n,depth:r}},rl=(t,e={})=>{let n=o=>{let s=j(o),i=e.maximumChildren===void 0?s:s.max(e.maximumChildren);return Nt([t,O({all:i}),O({any:i})])},r=es(()=>n(r));return e.maximumConditions===void 0&&e.maximumDepth===void 0?r:r.superRefine((o,s)=>{let{conditions:i,depth:a}=ts(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 Et(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=Et(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=>Et(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(`${Et(o)}:${Et(t[o],e)}`);n=`{${r.join(",")}}`}return e.delete(t),n}var mm=new TextEncoder,ot=t=>mm.encode(t),Ne=t=>ot(t).byteLength,se=class extends Error{constructor(){super("Byte stream exceeds the configured limit"),this.name="ByteLimitExceededError"}},hm=(t,e)=>{let n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.byteLength;return n},Pt=t=>typeof t=="string"?{async*[Symbol.asyncIterator](){yield ot(t)}}:t instanceof Uint8Array?{async*[Symbol.asyncIterator](){yield t}}:t,ol=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()}}}),ns=async(t,e)=>{let n=[],r=0;for await(let o of Pt(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 hm(n,r)},$e=async(t,e)=>{let n=await ns(t,e+1);if(n.byteLength>e)throw new se;return n},le=t=>new TextDecoder("utf-8",{fatal:!0}).decode(t),Lt=t=>t.charCodeAt(0)===65279?t.slice(1):t;var sl=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")}},rs=(t,e)=>{if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return sl(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(rs(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))sl(o),s!==void 0&&Object.defineProperty(r,o,{value:rs(s,e),enumerable:!0,configurable:!0,writable:!0})}finally{e.delete(t)}return r}throw new Error("Value cannot be represented as JSON")},st=t=>rs(t,new Set),fe=t=>{let e=Et(st(t));if(e===void 0)throw new Error("Value cannot be represented as canonical JSON");return e},xn=(t,e)=>t===void 0||e===void 0?t===e:fe(t)===fe(e),ze=(t,e)=>t<e?-1:t>e?1:0,os=async t=>{let e=typeof t=="string"?ot(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("")},il=async t=>`sha256:${await os(t)}`;var al=$t("type",[O({type:Z("document")}),O({type:Z("json"),path:j(v()).min(1)}),O({type:Z("markdown-body")}),O({type:Z("markdown-frontmatter")})]),ss=O({documentId:v().min(1),revision:v().min(1),representation:al}),ym=t=>{let e=al.parse(t);return e.type==="json"?Object.freeze({...e,path:Object.freeze([...e.path])}):Object.freeze(e)},cl=t=>{let e=ss.parse(t);return Object.freeze({...e,representation:ym(e.representation)})};var Sn=["json","markdown","mdx"],ul=t=>typeof t=="string"&&Sn.includes(t),ll=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 pr=O({id:v().min(1),revision:v().min(1),contentRef:v().min(1),format:ee(Sn).optional()}),mr=O({sourceId:v().min(1),referenceId:v().min(1),reference:ss});var Mt=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 Pe=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])}},gm=(t,e)=>ze(t.sourceId,e.sourceId)||ze(t.referenceId,e.referenceId),An=({nodes:t,edges:e})=>{let n=t.map(a=>Object.freeze(pr.parse(a))).sort((a,c)=>ze(a.id,c.id)),r=new Map,o=new Map;for(let a of n){if(r.has(a.id))throw new Pe({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 Pe({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=mr.parse(a);return Object.freeze({...c,reference:cl(c.reference)})}).sort(gm),i=new Set;for(let a of s){if(r.get(a.sourceId)===void 0)throw new Pe({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 Pe({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 Pe({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 Pe({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)})},bm=t=>new Map(t.nodes.map(e=>[e.id,e]));var hr=({graph:t,rootIds:e})=>{let n=bm(t),r=Mt(t.edges),o=new Map,s=[],i=[],a=c=>{let u=n.get(c);if(u===void 0)throw new Pe({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 Pe({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(ze))a(c);return Object.freeze(i)};var wm=v().regex(/^sha256:[a-f0-9]{64}$/),fl=O({format:Z("webstudio-document-graph"),version:Z(1),nodes:j(pr),edges:j(mr),integrity:O({algorithm:Z("sha256"),checksum:wm})});var _m=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"}),hl=O({_id:v().min(1),_type:Z("asset.file"),name:v().min(1),description:v().optional(),path:_m,key:v(),folderId:v().min(1).optional(),extension:v().regex(/^[a-z0-9]*$/),mimeType:v().min(1),size:N().int().nonnegative(),createdAt:v().datetime().optional(),revision:v().min(1),contentRef:v().min(1),properties:Ae(v(),rt()),excerpt:v().optional(),metadataError:O({code:v().min(1),message:v().min(1),reason:v().min(1).optional(),line:N().int().positive().optional(),column:N().int().positive().optional()}).optional()}),as=hl.partial().required({_id:!0}),Em=ee(["null","boolean","number","string","object","array"]),xm=nt({format:Z("webstudio-builder-asset-field-catalog"),version:Z(1),canonicalRevision:v().regex(/^sha256:[a-f0-9]{64}$/),documentCount:N().int().nonnegative(),fields:Ae(v().min(1),nt({queryPath:j(v().min(1)).min(1).max(k.fieldPathDepth).optional(),types:j(Em).min(1),occurrences:N().int().positive(),optional:Z(!0).optional(),mixed:Z(!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"})}}),yr=v().regex(/^sha256:[a-f0-9]{64}$/),yl=O({fields:j(j(v().min(1)).min(1).max(k.fieldPathDepth)).min(1).max(k.outputFieldCount+1),rows:j(j(rt())).max(k.resultCount),totalCount:N().int().nonnegative().max(k.candidateDocuments),hasMore:qe()}).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"})}),dl=O({format:Z("webstudio-content-database"),version:Z(1),assetRevision:yr,documents:j(as),documentGraph:fl.optional(),contents:Ae(v().min(1),v()).optional(),assetReferences:Ae(v().min(1),j(O({start:N().int().nonnegative(),end:N().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:Ae(v().min(1),j(O({path:j(v().min(1).or(N().int().nonnegative())).min(1),assetId:v().min(1),suffix:v().min(1).optional(),structured:Z(!0).optional()}))).optional(),fieldCatalog:xm,queries:Ae(yr,yl).optional(),database:O({maxBytes:N().int().positive(),unboundedBytes:N().int().nonnegative(),sourceDocumentCount:N().int().nonnegative(),includedDocumentCount:N().int().nonnegative().optional()}).optional(),integrity:O({algorithm:Z("sha256"),checksum:yr})}).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"})}),Sm=$t("mode",[O({mode:Z("none")}),O({mode:Z("full"),maxBytes:N().int().positive().max(k.hydratedFileBytes).optional()}),O({mode:Z("range"),offset:N().int().nonnegative(),length:N().int().positive().max(k.hydratedRangeBytes)}),O({mode:Z("markdown-body-ref"),maxBytes:N().int().positive().max(k.hydratedFileBytes).optional()})]),cs={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"]},gl=Object.keys(cs),bl=["url","width","height"],gr=t=>bl.includes(t),wl=gl.filter(t=>gr(t)===!1&&t!=="excerpt"),_l=wl.filter(t=>t!=="id"),El=t=>wl.includes(t),Am=ee(gl),vn=j(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"})}),is=qe().default(!0),vm=$t("mode",[O({mode:Z("all"),includeMetadata:is}),O({mode:Z("base"),includeMetadata:is}),O({mode:Z("fields"),includeMetadata:is,fields:j(vn).max(k.outputFieldCount).refine(t=>new Set(t.map(nl)).size===t.length,{error:"Selected output fields must be unique"})})]),Dm={mode:"fields",includeMetadata:!1,fields:bl.map(t=>[t])},xl=["eq","ne","contains","startsWith","endsWith","gt","gte","lt","lte"],Xb=[...xl,"in","exists","isEmpty"],Rm=O({field:vn,operator:ee(xl),value:rt()}),km=O({field:vn,operator:Z("in"),value:j(rt()).max(k.resultCount)}),Im=O({field:vn,operator:ee(["exists","isEmpty"]),value:qe()}),Om=$t("operator",[Rm,km,Im]),Cm=rl(Om,{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 Tm=Cm,Sl=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]},Nm=O({field:vn,direction:ee(["asc","desc"])}),$m=ee(["many","one","first","last"]),zm=({output:t,content:e})=>t.includeMetadata||t.mode==="all"||t.mode==="fields"&&t.fields.length>0||e.mode!=="none",it=O({result:$m.default("many"),where:Tm.default({all:[]}),sort:j(Nm).max(k.sortCount).default([]),limit:N().int().nonnegative().max(k.resultCount).default(k.defaultResultCount),offset:N().int().nonnegative().max(k.candidateDocuments).default(0),output:vm.default(Dm),content:Sm.default({mode:"none"})}).superRefine((t,e)=>{zm(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=O({query:it,indexRevision:v().min(1).max(255).optional()}),Pm=nt({_id:v().min(1),revision:v().min(1),contentRef:v().min(1),encoding:Z("utf-8"),text:v(),range:nt({offset:N().int().nonnegative(),length:N().int().nonnegative(),total:N().int().nonnegative()}).optional()}),Lm=Pm.omit({_id:!0,revision:!0,contentRef:!0}),vl=hl.omit({_id:!0,_type:!0,contentRef:!0}).partial().extend({id:v().min(1),url:v().min(1).optional(),width:N().positive().optional(),height:N().positive().optional(),content:Lm.optional()}).refine(t=>t.width===void 0==(t.height===void 0),{error:"Asset dimensions must include both width and height"}),Mm=O({format:Z("webstudio-content-database"),version:Z(1),revision:yr,usedBytes:N().int().nonnegative(),maxBytes:N().int().positive(),unboundedBytes:N().int().nonnegative(),includedDocumentCount:N().int().nonnegative(),omittedDocumentCount:N().int().nonnegative(),omissionReason:ee(["size","unavailable"]).optional(),truncated:qe()}),pl=Mm.pick({usedBytes:!0,maxBytes:!0,unboundedBytes:!0,includedDocumentCount:!0,omittedDocumentCount:!0,omissionReason:!0,truncated:!0}),us=O({items:j(vl),totalCount:N().int().nonnegative(),hasMore:qe()}),Fm=O({item:vl.nullable(),totalCount:N().int().nonnegative()}),Dl=Nt([us,Fm]),ml=O({line:N().int().positive(),column:N().int().positive(),offset:N().int().nonnegative().optional()}),Zm=O({severity:ee(["error","warning"]),scope:ee(["query","database"]),phase:ee(["metadata","reference","source"]),code:v().min(1),message:v().min(1),assetId:v().min(1),path:v().min(1),line:N().int().positive().optional(),column:N().int().positive().optional(),reference:v().min(1).optional(),nodeType:v().min(1).optional(),reason:v().min(1).optional(),sourceRange:O({start:ml,end:ml}).optional()}),Bm=O({severity:ee(["error","warning"]),code:v().min(1),path:j(v()),message:v().min(1)}),jm=O({scope:Z("query-preview"),queryIssues:j(Bm).optional(),queryWarnings:j(v().min(1)).optional(),query:pl,database:pl,artifacts:O({query:dl,database:dl}).optional(),unresolved:Dl.optional(),issues:j(Zm).optional(),issueCount:N().int().nonnegative().optional(),issuesTruncated:qe().optional()}),Hb=O({data:Dl,__diagnostics__:jm}),Um=ee(["INVALID_REQUEST","REQUEST_CANCELLED","UNAUTHORIZED","FORBIDDEN","STALE_INDEX","CONTENT_IDENTITY_REQUIRED","CONTENT_NOT_TEXT","CONTENT_DECODING_FAILED","CONTENT_LIMIT_EXCEEDED","MULTIPLE_RESULTS","INTERNAL_ERROR"]),Qm=nt({ok:Z(!1),error:nt({code:Um,message:v().min(1),retryable:qe(),details:Ae(v(),rt()).optional()}),meta:nt({queryHash:v().min(1).optional(),indexRevision:v().min(1).optional(),assetRevision:v().min(1).optional()}).optional()}),Rl=({code:t,message:e,retryable:n=!1,details:r})=>Qm.parse({ok:!1,error:{code:t,message:e,retryable:n,details:r}});var kl=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 Gm(o)}};var ls=(t,e)=>e+"/"+Vm(t),Vm=t=>t.toString().replace(/~/g,"~0").replace(/\//g,"~1"),Gm=t=>t.toString().replace(/~1/g,"/").replace(/~0/g,"~");var br=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},fs=t=>t.reason??new DOMException("The operation was aborted","AbortError"),Il=t=>{if(t?.aborted)throw fs(t)},Ft=async(t,e)=>e===void 0?await t:await new Promise((n,r)=>{let o=()=>e.removeEventListener("abort",s),s=()=>{o(),r(fs(e))};e.addEventListener("abort",s,{once:!0}),Promise.resolve(t).then(i=>{o(),n(i)},i=>{o(),r(i)}),e.aborted&&s()}),wr=({concurrency:t,signal:e})=>{if(Number.isSafeInteger(t)===!1||t<=0)throw new TypeError("Concurrency must be a positive safe integer");let n=0,r=[],o=async()=>{if(Il(e),n<t){n+=1;return}await new Promise((i,a)=>{let c,u=()=>{let d=r.indexOf(c);d!==-1&&r.splice(d,1),e!==void 0&&a(fs(e))};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 Il(e),await i()}finally{s()}}};var Zt=t=>typeof t=="object"&&t!==null&&Array.isArray(t)===!1,_r=t=>{if(Zt(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}},qm=(t,e)=>{let n=_r(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}},Jm=t=>`#${t}`;var Ol=async({source:t,maximumBytes:e=k.hydratedFileBytes})=>{let n;try{n=await $e(t,e)}catch(o){throw o instanceof se?new de({code:"CONTENT_LIMIT_EXCEEDED",message:"JSON document exceeds the byte limit",cause:o}):o}let r;try{r=Lt(le(n))}catch(o){throw new de({code:"CONTENT_DECODING_FAILED",message:"JSON document is not valid UTF-8",cause:o})}try{return st(JSON.parse(r))}catch(o){throw new de({code:"INVALID_DOCUMENT",message:"JSON document is invalid",cause:o})}};var Km=(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(Zt(n)&&Object.hasOwn(n,r)){n=n[r];continue}return}return n},Cl=({document:t,representation:e})=>{let n=st(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=Km(n,e.path);if(r===void 0)throw new de({code:"JSON_PATH_NOT_FOUND",message:"JSON document path does not exist"});return r},Wm=(t,e,n)=>{Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0})},Er=({document:t,references:e,allowUnresolvedReferences:n=!1})=>{let r=st(t),o=new Set,s=(a,c)=>{let u=Jm(c);if(qm(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 st(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,ls(String(f),c)));if(Zt(a)){let l={};for(let[f,p]of Object.entries(a))Wm(l,f,s(p,ls(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 xr=Symbol.for("yaml.alias"),Sr=Symbol.for("yaml.document"),ve=Symbol.for("yaml.map"),ds=Symbol.for("yaml.pair"),pe=Symbol.for("yaml.scalar"),Je=Symbol.for("yaml.seq"),ie=Symbol.for("yaml.node.type"),ye=t=>!!t&&typeof t=="object"&&t[ie]===xr,Le=t=>!!t&&typeof t=="object"&&t[ie]===Sr,ge=t=>!!t&&typeof t=="object"&&t[ie]===ve,$=t=>!!t&&typeof t=="object"&&t[ie]===ds,T=t=>!!t&&typeof t=="object"&&t[ie]===pe,be=t=>!!t&&typeof t=="object"&&t[ie]===Je;function B(t){if(t&&typeof t=="object")switch(t[ie]){case ve:case Je:return!0}return!1}function z(t){if(t&&typeof t=="object")switch(t[ie]){case xr:case ve:case pe:case Je:return!0}return!1}var Ar=t=>(T(t)||B(t))&&!!t.anchor;var ce=Symbol("break visit"),Tl=Symbol("skip children"),Me=Symbol("remove node");function Fe(t,e){let n=Nl(e);Le(t)?Bt(null,t.contents,n,Object.freeze([t]))===Me&&(t.contents=null):Bt(null,t,n,Object.freeze([]))}Fe.BREAK=ce;Fe.SKIP=Tl;Fe.REMOVE=Me;function Bt(t,e,n,r){let o=$l(t,e,n,r);if(z(o)||$(o))return zl(t,r,o),Bt(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=Bt(s,e.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===ce)return ce;i===Me&&(e.items.splice(s,1),s-=1)}}}else if($(e)){r=Object.freeze(r.concat(e));let s=Bt("key",e.key,n,r);if(s===ce)return ce;s===Me&&(e.key=null);let i=Bt("value",e.value,n,r);if(i===ce)return ce;i===Me&&(e.value=null)}}return o}async function vr(t,e){let n=Nl(e);Le(t)?await jt(null,t.contents,n,Object.freeze([t]))===Me&&(t.contents=null):await jt(null,t,n,Object.freeze([]))}vr.BREAK=ce;vr.SKIP=Tl;vr.REMOVE=Me;async function jt(t,e,n,r){let o=await $l(t,e,n,r);if(z(o)||$(o))return zl(t,r,o),jt(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 jt(s,e.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===ce)return ce;i===Me&&(e.items.splice(s,1),s-=1)}}}else if($(e)){r=Object.freeze(r.concat(e));let s=await jt("key",e.key,n,r);if(s===ce)return ce;s===Me&&(e.key=null);let i=await jt("value",e.value,n,r);if(i===ce)return ce;i===Me&&(e.value=null)}}return o}function Nl(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 $l(t,e,n,r){if(typeof n=="function")return n(t,e,r);if(ge(e))return n.Map?.(t,e,r);if(be(e))return n.Seq?.(t,e,r);if($(e))return n.Pair?.(t,e,r);if(T(e))return n.Scalar?.(t,e,r);if(ye(e))return n.Alias?.(t,e,r)}function zl(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(Le(r))r.contents=n;else{let o=ye(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}var Ym={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Xm=t=>t.replace(/[!,[\]{}]/g,e=>Ym[e]),Ze=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+Xm(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&&z(e.contents)){let s={};Fe(e.contents,(i,a)=>{z(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(`
+`)}};Ze.defaultYaml={explicit:!1,version:"1.2"};Ze.defaultTags={"!!":"tag:yaml.org,2002:"};function Dr(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 ps(t){let e=new Set;return Fe(t,{Value(n,r){r.anchor&&e.add(r.anchor)}}),e}function ms(t,e){for(let n=1;;++n){let r=`${t}${n}`;if(!e.has(r))return r}}function Pl(t,e){let n=[],r=new Map,o=null;return{onAnchor:s=>{n.push(s),o??(o=ps(t));let i=ms(e,o);return o.add(i),i},setAnchors:()=>{for(let s of n){let i=r.get(s);if(typeof i=="object"&&i.anchor&&(T(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 at(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=at(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=at(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=at(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=at(t,r,o,s);i===void 0?delete r[o]:i!==s&&(r[o]=i)}return t.call(e,n,r)}function H(t,e,n){if(Array.isArray(t))return t.map((r,o)=>H(r,String(o),n));if(t&&typeof t.toJSON=="function"){if(!n||!Ar(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 ct=class{constructor(e){Object.defineProperty(this,ie,{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(!Le(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=H(this,"",i);if(typeof o=="function")for(let{count:c,res:u}of i.anchors.values())o(u,c);return typeof s=="function"?at(s,{"":a},"",a):a}};var Ke=class extends ct{constructor(e){super(xr),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=[],Fe(e,{Node:(s,i)=>{(ye(i)||Ar(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||(H(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=Rr(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(Dr(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 Rr(t,e,n){if(ye(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=Rr(t,o,n);s>r&&(r=s)}return r}else if($(e)){let r=Rr(t,e.key,n),o=Rr(t,e.value,n);return Math.max(r,o)}return 1}var kr=t=>!t||typeof t!="function"&&typeof t!="object",R=class extends ct{constructor(e){super(pe),this.value=e}toJSON(e,n){return n?.keep?this.value:H(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 Hm="tag:yaml.org,2002:";function eh(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 We(t,e,n){if(Le(t)&&(t=t.contents),z(t))return t;if($(t)){let l=n.schema[ve].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 Ke(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=Hm+e.slice(2));let u=eh(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[ve]:Symbol.iterator in Object(t)?i[Je]:i[ve]}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 R(t);return e?d.tag=e:u.default||(d.tag=u.tag),c&&(c.node=d),d}function Dn(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 We(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 Qt=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Ut=class extends ct{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=>z(r)||$(r)?r.clone(e):r),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(Qt(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,Dn(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&&T(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&&T(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,Dn(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}};var Ll=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function we(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Be=(t,e,n)=>t.endsWith(`
+`)?we(n,e):n.includes(`
`)?`
-`+be(n,e):(t.endsWith(" ")?"":" ")+n;var ls="flow",vr="block",vn="quoted";function Dn(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,g=-1;n===vr&&(m=Tl(t,m,e.length),m!==-1&&(l=m+c));for(let S;S=t[m+=1];){if(n===vn&&S==="\\"){switch(h=m,t[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}g=m}if(S===`
-`)n===vr&&(m=Tl(t,m,e.length)),l=m+e.length+c,f=void 0;else{if(S===" "&&p&&p!==" "&&p!==`
+`+we(n,e):(t.endsWith(" ")?"":" ")+n;var hs="flow",Ir="block",Rn="quoted";function kn(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,g=!1,m=-1,h=-1,y=-1;n===Ir&&(m=Ml(t,m,e.length),m!==-1&&(l=m+c));for(let S;S=t[m+=1];){if(n===Rn&&S==="\\"){switch(h=m,t[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}y=m}if(S===`
+`)n===Ir&&(m=Ml(t,m,e.length)),l=m+e.length+c,f=void 0;else{if(S===" "&&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===vn){for(;p===" "||p===" ";)p=S,S=t[m+=1],y=!0;let _=m>g+1?m-2:h-1;if(d[_])return t;u.push(_),d[_]=!0,l=_+c,f=void 0}else y=!0}p=S}if(y&&a&&a(),u.length===0)return t;i&&i();let x=t.slice(0,u[0]);for(let S=0;S<u.length;++S){let _=u[S],w=u[S+1]||t.length;_===0?x=`
-${e}${t.slice(0,w)}`:(n===vn&&d[_]&&(x+=`${t[_]}\\`),x+=`
-${e}${t.slice(_+1,w)}`)}return x}function Tl(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 Rr=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),kr=t=>/^(%|---|\.\.\.)/m.test(t);function Jm(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 Rn(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)+`
+`&&_!==" "&&(f=m)}if(m>=l)if(f)u.push(f),l=f+c,f=void 0;else if(n===Rn){for(;p===" "||p===" ";)p=S,S=t[m+=1],g=!0;let _=m>y+1?m-2:h-1;if(d[_])return t;u.push(_),d[_]=!0,l=_+c,f=void 0}else g=!0}p=S}if(g&&a&&a(),u.length===0)return t;i&&i();let E=t.slice(0,u[0]);for(let S=0;S<u.length;++S){let _=u[S],w=u[S+1]||t.length;_===0?E=`
+${e}${t.slice(0,w)}`:(n===Rn&&d[_]&&(E+=`${t[_]}\\`),E+=`
+${e}${t.slice(_+1,w)}`)}return E}function Ml(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 Cr=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),Tr=t=>/^(%|---|\.\.\.)/m.test(t);function th(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 In(t,e){let n=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=e,o=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(Tr(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)+`
`;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:Dn(i,s,vn,Rr(e,!1))}function fs(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
-`)||/[ \t]\n|\n[ \t]/.test(t))return Rn(t,e);let n=e.indent||(kr(t)?" ":""),r="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
-${n}`)+"'";return e.implicitKey?r:Dn(r,n,ls,Rr(e,!1))}function Ut(t,e){let{singleQuote:n}=e.options,r;if(n===!1)r=Rn;else{let o=t.includes('"'),s=t.includes("'");o&&!s?r=fs:s&&!o?r=Rn:r=n?fs:Rn}return r(t,e)}var ds;try{ds=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:kn(i,s,Rn,Cr(e,!1))}function ys(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
+`)||/[ \t]\n|\n[ \t]/.test(t))return In(t,e);let n=e.indent||(Tr(t)?" ":""),r="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
+${n}`)+"'";return e.implicitKey?r:kn(r,n,hs,Cr(e,!1))}function Vt(t,e){let{singleQuote:n}=e.options,r;if(n===!1)r=In;else{let o=t.includes('"'),s=t.includes("'");o&&!s?r=ys:s&&!o?r=In:r=n?ys:In}return r(t,e)}var gs;try{gs=new RegExp(`(^|(?<!
))
+(?!
-|$)`,"g")}catch{ds=/\n+(?!\n|$)/g}function Dr({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 Ut(n,r);let u=r.indent||(r.forceBlockIndent||kr(n)?" ":""),d=i==="literal"?!0:i==="folded"||e===R.BLOCK_FOLDED?!1:e===R.BLOCK_LITERAL?!0:!Jm(n,c,u.length);if(!n)return d?`|
+|$)`,"g")}catch{gs=/\n+(?!\n|$)/g}function Or({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 Vt(n,r);let u=r.indent||(r.forceBlockIndent||Tr(n)?" ":""),d=i==="literal"?!0:i==="folded"||e===R.BLOCK_FOLDED?!1:e===R.BLOCK_LITERAL?!0:!th(n,c,u.length);if(!n)return d?`|
`:`>
`;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(ds,`$&${u}`));let m=!1,h,g=-1;for(h=0;h<n.length;++h){let w=n[h];if(w===" ")m=!0;else if(w===`
-`)g=h;else break}let x=n.substring(0,g<h?g+1:h);x&&(n=n.substring(x.length),x=x.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}`),A=!1,D=Rr(r,!0);i!=="folded"&&e!==R.BLOCK_FOLDED&&(D.onOverflow=()=>{A=!0});let E=Dn(`${x}${w}${p}`,u,vr,D);if(!A)return`>${_}
-${u}${E}`}return n=n.replace(/\n+/g,`$&${u}`),`|${_}
-${u}${x}${n}${p}`}function Km(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 Ut(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||d||!s.includes(`
-`)?Ut(s,e):Dr(t,e,n,r);if(!a&&!d&&o!==R.PLAIN&&s.includes(`
-`))return Dr(t,e,n,r);if(kr(s)){if(c==="")return e.forceBlockIndent=!0,Dr(t,e,n,r);if(a&&c===u)return Ut(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 Ut(s,e)}return a?l:Dn(l,c,ls,Rr(e,!1))}function xt(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=d=>{switch(d){case R.BLOCK_FOLDED:case R.BLOCK_LITERAL:return o||s?Ut(i.value,e):Dr(i,e,n,r);case R.QUOTE_DOUBLE:return Rn(i.value,e);case R.QUOTE_SINGLE:return fs(i.value,e);case R.PLAIN:return Km(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 Ir(t,e){let n=Object.assign({blockQuote:!0,commentString:Cl,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 Wm(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(T(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 Ym(t,e,{anchors:n,doc:r}){if(!r.directives)return"";let o=[],s=(T(t)||B(t))&&t.anchor;s&&Er(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(he(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=z(t)?t:e.doc.createNode(t,{onTagObj:c=>o=c});o??(o=Wm(e.doc.schema.tags,s));let i=Ym(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):T(s)?xt(s,e,n,r):s.toString(e,n,r);return i?T(s)||a[0]==="{"||a[0]==="["?`${i} ${a}`:`${i}
-${e.indent}${a}`:a}function Nl({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=z(t)&&t.comment||null;if(l){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(B(t)||!z(t)&&typeof t=="object"){let D="With simple keys, collection cannot be used as a key value";throw new Error(D)}}let p=!l&&(!t||f&&e==null&&!n.inFlow||B(t)||(T(t)?t.type===R.BLOCK_FOLDED||t.type===R.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+=Fe(h,n.indent,u(f)):m&&o&&o(),h;y&&(f=null),p?(f&&(h+=Fe(h,n.indent,u(f))),h=`? ${h}
-${a}:`):(h=`${h}:`,f&&(h+=Fe(h,n.indent,u(f))));let g,x,S;z(e)?(g=!!e.spaceBefore,x=e.commentBefore,S=e.comment):(g=!1,x=null,S=null,e&&typeof e=="object"&&(e=i.createNode(e))),n.implicitKey=!1,!p&&!f&&T(e)&&(n.indentAtStart=h.length+1),m=!1,!d&&c.length>=2&&!n.inFlow&&!p&&ge(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let _=!1,w=Ke(e,n,()=>_=!0,()=>m=!0),A=" ";if(f||g||x){if(A=g?`
-`:"",x){let D=u(x);A+=`
-${be(D,n.indent)}`}w===""&&!n.inFlow?A===`
+`&&w!==" "&&w!==" ")break}let p=n.substring(f),g=p.indexOf(`
+`);g===-1?l="-":n===p||g!==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(gs,`$&${u}`));let m=!1,h,y=-1;for(h=0;h<n.length;++h){let w=n[h];if(w===" ")m=!0;else if(w===`
+`)y=h;else break}let E=n.substring(0,y<h?y+1:h);E&&(n=n.substring(E.length),E=E.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}`),A=!1,D=Cr(r,!0);i!=="folded"&&e!==R.BLOCK_FOLDED&&(D.onOverflow=()=>{A=!0});let x=kn(`${E}${w}${p}`,u,Ir,D);if(!A)return`>${_}
+${u}${x}`}return n=n.replace(/\n+/g,`$&${u}`),`|${_}
+${u}${E}${n}${p}`}function nh(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 Vt(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||d||!s.includes(`
+`)?Vt(s,e):Or(t,e,n,r);if(!a&&!d&&o!==R.PLAIN&&s.includes(`
+`))return Or(t,e,n,r);if(Tr(s)){if(c==="")return e.forceBlockIndent=!0,Or(t,e,n,r);if(a&&c===u)return Vt(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:g}=e.doc.schema;if(g.some(f)||p?.some(f))return Vt(s,e)}return a?l:kn(l,c,hs,Cr(e,!1))}function xt(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=d=>{switch(d){case R.BLOCK_FOLDED:case R.BLOCK_LITERAL:return o||s?Vt(i.value,e):Or(i,e,n,r);case R.QUOTE_DOUBLE:return In(i.value,e);case R.QUOTE_SINGLE:return ys(i.value,e);case R.PLAIN:return nh(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 Nr(t,e){let n=Object.assign({blockQuote:!0,commentString:Ll,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 rh(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(T(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 oh(t,e,{anchors:n,doc:r}){if(!r.directives)return"";let o=[],s=(T(t)||B(t))&&t.anchor;s&&Dr(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 Ye(t,e,n,r){if($(t))return t.toString(e,n,r);if(ye(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=z(t)?t:e.doc.createNode(t,{onTagObj:c=>o=c});o??(o=rh(e.doc.schema.tags,s));let i=oh(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):T(s)?xt(s,e,n,r):s.toString(e,n,r);return i?T(s)||a[0]==="{"||a[0]==="["?`${i} ${a}`:`${i}
+${e.indent}${a}`:a}function Fl({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=z(t)&&t.comment||null;if(l){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(B(t)||!z(t)&&typeof t=="object"){let D="With simple keys, collection cannot be used as a key value";throw new Error(D)}}let p=!l&&(!t||f&&e==null&&!n.inFlow||B(t)||(T(t)?t.type===R.BLOCK_FOLDED||t.type===R.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(l||!s),indent:a+c});let g=!1,m=!1,h=Ye(t,n,()=>g=!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 g&&r&&r(),h===""?"?":p?`? ${h}`:h}else if(s&&!l||e==null&&p)return h=`? ${h}`,f&&!g?h+=Be(h,n.indent,u(f)):m&&o&&o(),h;g&&(f=null),p?(f&&(h+=Be(h,n.indent,u(f))),h=`? ${h}
+${a}:`):(h=`${h}:`,f&&(h+=Be(h,n.indent,u(f))));let y,E,S;z(e)?(y=!!e.spaceBefore,E=e.commentBefore,S=e.comment):(y=!1,E=null,S=null,e&&typeof e=="object"&&(e=i.createNode(e))),n.implicitKey=!1,!p&&!f&&T(e)&&(n.indentAtStart=h.length+1),m=!1,!d&&c.length>=2&&!n.inFlow&&!p&&be(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let _=!1,w=Ye(e,n,()=>_=!0,()=>m=!0),A=" ";if(f||y||E){if(A=y?`
+`:"",E){let D=u(E);A+=`
+${we(D,n.indent)}`}w===""&&!n.inFlow?A===`
`&&S&&(A=`
`):A+=`
-${n.indent}`}else if(!p&&B(e)){let D=w[0],E=w.indexOf(`
-`),C=E!==-1,P=n.inFlow??e.flow??e.items.length===0;if(C||!P){let G=!1;if(C&&(D==="&"||D==="!")){let L=w.indexOf(" ");D==="&"&&L!==-1&&L<E&&w[L+1]==="!"&&(L=w.indexOf(" ",L+1)),(L===-1||E<L)&&(G=!0)}G||(A=`
+${n.indent}`}else if(!p&&B(e)){let D=w[0],x=w.indexOf(`
+`),C=x!==-1,P=n.inFlow??e.flow??e.items.length===0;if(C||!P){let G=!1;if(C&&(D==="&"||D==="!")){let L=w.indexOf(" ");D==="&"&&L!==-1&&L<x&&w[L+1]==="!"&&(L=w.indexOf(" ",L+1)),(L===-1||x<L)&&(G=!0)}G||(A=`
${n.indent}`)}}else(w===""||w[0]===`
-`)&&(A="");return h+=A+w,n.inFlow?_&&r&&r():S&&!_?h+=Fe(h,n.indent,u(S)):m&&o&&o(),h}function ps(t,e){(t==="debug"||t==="warn")&&console.warn(e)}var Or="<<",Ae={identify:t=>t===Or||typeof t=="symbol"&&t.description===Or,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new R(Symbol(Or)),{addToJSMap:hs}),stringify:()=>Or},$l=(t,e)=>(Ae.identify(e)||T(e)&&(!e.type||e.type===R.PLAIN)&&Ae.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===Ae.tag&&n.default);function hs(t,e,n){let r=zl(t,n);if(ge(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=zl(t,n);if(!ye(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 zl(t,e){return t&&he(e)?e.resolve(t.doc,t):e}function Cr(t,e,{key:n,value:r}){if(z(n)&&n.addToJSMap)n.addToJSMap(t,e,r);else if($l(t,n))hs(t,e,r);else{let o=H(n,"",t);if(e instanceof Map)e.set(o,H(r,o,t));else if(e instanceof Set)e.add(o);else{let s=Xm(n,o,t),i=H(r,s,t);s in e?Object.defineProperty(e,s,{value:i,writable:!0,enumerable:!0,configurable:!0}):e[s]=i}}return e}function Xm(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(z(t)&&n?.doc){let r=Ir(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 Qt(t,e,n){let r=Je(t,void 0,n),o=Je(e,void 0,n);return new K(r,o)}var K=class t{constructor(e,n=null){Object.defineProperty(this,ie,{value:as}),this.key=e,this.value=n}clone(e){let{key:n,value:r}=this;return z(n)&&(n=n.clone(e)),z(r)&&(r=r.clone(e)),new t(n,r)}toJSON(e,n){let r=n?.mapAsMap?new Map:{};return Cr(n,r,this)}toString(e,n,r){return e?.doc?Nl(this,e,n,r):JSON.stringify(this)}};function Nr(t,e,n){return(e.inFlow??t.flow?eh:Hm)(t,e,n)}function Hm({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(z(m))!l&&m.spaceBefore&&f.push(""),Tr(n,f,m.commentBefore,l),m.comment&&(h=m.comment);else if($(m)){let x=z(m.key)?m.key:null;x&&(!l&&x.spaceBefore&&f.push(""),Tr(n,f,x.commentBefore,l))}l=!1;let g=Ke(m,d,()=>h=null,()=>l=!0);h&&(g+=Fe(g,s,u(h))),l&&h&&(l=!1),f.push(r+g)}let p;if(f.length===0)p=o.start+o.end;else{p=f[0];for(let y=1;y<f.length;++y){let m=f[y];p+=m?`
+`)&&(A="");return h+=A+w,n.inFlow?_&&r&&r():S&&!_?h+=Be(h,n.indent,u(S)):m&&o&&o(),h}function bs(t,e){(t==="debug"||t==="warn")&&console.warn(e)}var $r="<<",De={identify:t=>t===$r||typeof t=="symbol"&&t.description===$r,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new R(Symbol($r)),{addToJSMap:_s}),stringify:()=>$r},Zl=(t,e)=>(De.identify(e)||T(e)&&(!e.type||e.type===R.PLAIN)&&De.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===De.tag&&n.default);function _s(t,e,n){let r=Bl(t,n);if(be(r))for(let o of r.items)ws(t,e,o);else if(Array.isArray(r))for(let o of r)ws(t,e,o);else ws(t,e,r)}function ws(t,e,n){let r=Bl(t,n);if(!ge(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 Bl(t,e){return t&&ye(e)?e.resolve(t.doc,t):e}function zr(t,e,{key:n,value:r}){if(z(n)&&n.addToJSMap)n.addToJSMap(t,e,r);else if(Zl(t,n))_s(t,e,r);else{let o=H(n,"",t);if(e instanceof Map)e.set(o,H(r,o,t));else if(e instanceof Set)e.add(o);else{let s=sh(n,o,t),i=H(r,s,t);s in e?Object.defineProperty(e,s,{value:i,writable:!0,enumerable:!0,configurable:!0}):e[s]=i}}return e}function sh(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(z(t)&&n?.doc){let r=Nr(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)+'..."'),bs(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 Gt(t,e,n){let r=We(t,void 0,n),o=We(e,void 0,n);return new K(r,o)}var K=class t{constructor(e,n=null){Object.defineProperty(this,ie,{value:ds}),this.key=e,this.value=n}clone(e){let{key:n,value:r}=this;return z(n)&&(n=n.clone(e)),z(r)&&(r=r.clone(e)),new t(n,r)}toJSON(e,n){let r=n?.mapAsMap?new Map:{};return zr(n,r,this)}toString(e,n,r){return e?.doc?Fl(this,e,n,r):JSON.stringify(this)}};function Lr(t,e,n){return(e.inFlow??t.flow?ah:ih)(t,e,n)}function ih({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 g=0;g<e.length;++g){let m=e[g],h=null;if(z(m))!l&&m.spaceBefore&&f.push(""),Pr(n,f,m.commentBefore,l),m.comment&&(h=m.comment);else if($(m)){let E=z(m.key)?m.key:null;E&&(!l&&E.spaceBefore&&f.push(""),Pr(n,f,E.commentBefore,l))}l=!1;let y=Ye(m,d,()=>h=null,()=>l=!0);h&&(y+=Be(y,s,u(h))),l&&h&&(l=!1),f.push(r+y)}let p;if(f.length===0)p=o.start+o.end;else{p=f[0];for(let g=1;g<f.length;++g){let m=f[g];p+=m?`
${c}${m}`:`
`}}return t?(p+=`
-`+be(u(t),c),a&&a()):l&&i&&i(),p}function eh({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(z(m))m.spaceBefore&&l.push(""),Tr(e,l,m.commentBefore,!1),m.comment&&(h=m.comment);else if($(m)){let x=z(m.key)?m.key:null;x&&(x.spaceBefore&&l.push(""),Tr(e,l,x.commentBefore,!1),x.comment&&(u=!0));let S=z(m.value)?m.value:null;S?(S.comment&&(h=S.comment),S.commentBefore&&(u=!0)):m.value==null&&x?.comment&&(h=x.comment)}h&&(u=!0);let g=Ke(m,c,()=>h=null);u||(u=l.length>d||g.includes(`
-`)),y<t.length-1?g+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(u||(u=l.reduce((x,S)=>x+S.length+2,2)+(g.length+2)>e.options.lineWidth)),u&&(g+=",")),h&&(g+=Fe(g,r,a(h))),l.push(g),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?`
+`+we(u(t),c),a&&a()):l&&i&&i(),p}function ah({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 g=0;g<t.length;++g){let m=t[g],h=null;if(z(m))m.spaceBefore&&l.push(""),Pr(e,l,m.commentBefore,!1),m.comment&&(h=m.comment);else if($(m)){let E=z(m.key)?m.key:null;E&&(E.spaceBefore&&l.push(""),Pr(e,l,E.commentBefore,!1),E.comment&&(u=!0));let S=z(m.value)?m.value:null;S?(S.comment&&(h=S.comment),S.commentBefore&&(u=!0)):m.value==null&&E?.comment&&(h=E.comment)}h&&(u=!0);let y=Ye(m,c,()=>h=null);u||(u=l.length>d||y.includes(`
+`)),g<t.length-1?y+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(u||(u=l.reduce((E,S)=>E+S.length+2,2)+(y.length+2)>e.options.lineWidth)),u&&(y+=",")),h&&(y+=Be(y,r,a(h))),l.push(y),d=l.length}let{start:f,end:p}=n;if(l.length===0)return f+p;if(!u){let g=l.reduce((m,h)=>m+h.length+2,2);u=e.options.lineWidth>0&&g>e.options.lineWidth}if(u){let g=f;for(let m of l)g+=m?`
${s}${o}${m}`:`
-`;return`${y}
-${o}${p}`}else return`${f}${i}${l.join(" ")}${i}${p}`}function Tr({indent:t,options:{commentString:e}},n,r,o){if(r&&o&&(r=r.replace(/^\n+/,"")),r){let s=be(e(r),t);n.push(s.trimStart())}}function ct(t,e){let n=T(e)?e.value:e;for(let r of t)if($(r)&&(r.key===e||r.key===n||T(r.key)&&r.key.value===n))return r}var W=class extends Bt{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Se,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(Qt(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=ct(this.items,r.key),s=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${r.key} already set`);T(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=ct(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let o=ct(this.items,e)?.value;return(!n&&T(o)?o.value:o)??void 0}has(e){return!!ct(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)Cr(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})),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 ye(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>W.from(t,e,n)};var ne=class extends Bt{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=$r(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let r=$r(e);if(typeof r!="number")return;let o=this.items[r];return!n&&T(o)?o.value:o}has(e){let n=$r(e);return typeof n=="number"&&n<this.items.length}set(e,n){let r=$r(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);let o=this.items[r];T(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(H(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(Je(a,void 0,r))}}return s}};function $r(t){let e=T(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:ne,tag:"tag:yaml.org,2002:seq",resolve(t,e){return ge(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>ne.from(t,e,n)};var ut={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),xt(t,e,n,r)}};var Et={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"&&Et.test.test(t)?t:e.options.nullStr};var kn={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&&kn.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 re({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 zr={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:re},Pr={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():re(t)}},Lr={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:re};var Mr=t=>typeof t=="bigint"||Number.isInteger(t),ys=(t,e,n,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),n);function Pl(t,e,n){let{value:r}=t;return Mr(r)&&r>=0?n+r.toString(e):re(t)}var Fr={identify:t=>Mr(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=>Pl(t,8,"0o")},Zr={identify:Mr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>ys(t,0,10,n),stringify:re},Br={identify:t=>Mr(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=>Pl(t,16,"0x")};var Ll=[ve,De,ut,Et,kn,Fr,Zr,Br,zr,Pr,Lr];function Ml(t){return typeof t=="bigint"||Number.isInteger(t)}var jr=({value:t})=>JSON.stringify(t),th=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:jr},{identify:t=>t==null,createNode:()=>new R(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:jr},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:jr},{identify:Ml,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})=>Ml(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:jr}],nh={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Fl=[ve,De].concat(th,nh);var In={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),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===R.BLOCK_LITERAL?`
-`:" ")}return xt({comment:t,type:e,value:a},r,o,s)}};function gs(t,e){if(ge(t))for(let n=0;n<t.items.length;++n){let r=t.items[n];if(!$(r)){if(ye(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}
+`;return`${g}
+${o}${p}`}else return`${f}${i}${l.join(" ")}${i}${p}`}function Pr({indent:t,options:{commentString:e}},n,r,o){if(r&&o&&(r=r.replace(/^\n+/,"")),r){let s=we(e(r),t);n.push(s.trimStart())}}function ut(t,e){let n=T(e)?e.value:e;for(let r of t)if($(r)&&(r.key===e||r.key===n||T(r.key)&&r.key.value===n))return r}var W=class extends Ut{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(ve,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(Gt(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=ut(this.items,r.key),s=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${r.key} already set`);T(o.value)&&kr(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=ut(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let o=ut(this.items,e)?.value;return(!n&&T(o)?o.value:o)??void 0}has(e){return!!ut(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)zr(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})),Lr(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:n})}};var Re={collection:"map",default:!0,nodeClass:W,tag:"tag:yaml.org,2002:map",resolve(t,e){return ge(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>W.from(t,e,n)};var ne=class extends Ut{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Je,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=Mr(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let r=Mr(e);if(typeof r!="number")return;let o=this.items[r];return!n&&T(o)?o.value:o}has(e){let n=Mr(e);return typeof n=="number"&&n<this.items.length}set(e,n){let r=Mr(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);let o=this.items[r];T(o)&&kr(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(H(s,String(o++),n));return r}toString(e,n,r){return e?Lr(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(We(a,void 0,r))}}return s}};function Mr(t){let e=T(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:ne,tag:"tag:yaml.org,2002:seq",resolve(t,e){return be(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>ne.from(t,e,n)};var lt={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),xt(t,e,n,r)}};var St={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"&&St.test.test(t)?t:e.options.nullStr};var On={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&&On.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 re({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 Fr={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:re},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():re(t)}},Br={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:re};var jr=t=>typeof t=="bigint"||Number.isInteger(t),Es=(t,e,n,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),n);function jl(t,e,n){let{value:r}=t;return jr(r)&&r>=0?n+r.toString(e):re(t)}var Ur={identify:t=>jr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>Es(t,2,8,n),stringify:t=>jl(t,8,"0o")},Qr={identify:jr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>Es(t,0,10,n),stringify:re},Vr={identify:t=>jr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>Es(t,2,16,n),stringify:t=>jl(t,16,"0x")};var Ul=[Re,ke,lt,St,On,Ur,Qr,Vr,Fr,Zr,Br];function Ql(t){return typeof t=="bigint"||Number.isInteger(t)}var Gr=({value:t})=>JSON.stringify(t),ch=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:Gr},{identify:t=>t==null,createNode:()=>new R(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Gr},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:Gr},{identify:Ql,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})=>Ql(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:Gr}],uh={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Vl=[Re,ke].concat(ch,uh);var Cn={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),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===R.BLOCK_LITERAL?`
+`:" ")}return xt({comment:t,type:e,value:a},r,o,s)}};function xs(t,e){if(be(t))for(let n=0;n<t.items.length;++n){let r=t.items[n];if(!$(r)){if(ge(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 bs(t,e,n){let{replacer:r}=n,o=new ne(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(Qt(a,c,n))}return o}var On={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:gs,createNode:bs};var Vt=class t extends ne{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=H(o.key,"",n),i=H(o.value,s,n)):s=H(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}};Vt.tag="tag:yaml.org,2002:omap";var Cn={collection:"seq",identify:t=>t instanceof Map,nodeClass:Vt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=gs(t,e),r=[];for(let{key:o}of n.items)T(o)&&(r.includes(o.value)?e(`Ordered maps must not include duplicate keys: ${o.value}`):r.push(o.value));return Object.assign(new Vt,n)},createNode:(t,e,n)=>Vt.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 Bl={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:re},jl={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():re(t)}},Ul={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:re};var Tn=t=>typeof t=="bigint"||Number.isInteger(t);function Ur(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(Tn(r)){let o=r.toString(e);return r<0?"-"+n+o.substr(1):n+o}return re(t)}var Ql={identify:Tn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>Ur(t,2,2,n),stringify:t=>xs(t,2,"0b")},Vl={identify:Tn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>Ur(t,1,8,n),stringify:t=>xs(t,8,"0")},Gl={identify:Tn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>Ur(t,0,10,n),stringify:re},ql={identify:Tn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>Ur(t,2,16,n),stringify:t=>xs(t,16,"0x")};var Gt=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),ct(this.items,n.key)||this.items.push(n)}get(e,n){let r=ct(this.items,e);return!n&&$(r)?T(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=ct(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(Qt(i,null,r));return s}};Gt.tag="tag:yaml.org,2002:set";var Nn={collection:"map",identify:t=>t instanceof Set,nodeClass:Gt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>Gt.from(t,e,n),resolve(t,e){if(ye(t)){if(t.hasAllNullValues(!0))return Object.assign(new Gt,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};function Es(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 Jl(t){let{value:e}=t,n=i=>i;if(typeof e=="bigint")n=i=>BigInt(i);else if(isNaN(e)||!isFinite(e))return re(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 Qr={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})=>Es(t,n),stringify:Jl},Vr={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=>Es(t,!1),stringify:Jl},qt={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(qt.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=Es(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 Ss=[ve,De,ut,Et,ws,_s,Ql,Vl,Gl,ql,Bl,jl,Ul,In,Ae,Cn,On,Nn,Qr,Vr,qt];var Kl=new Map([["core",Ll],["failsafe",[ve,De,ut]],["json",Fl],["yaml11",Ss],["yaml-1.1",Ss]]),Wl={binary:In,bool:kn,float:Lr,floatExp:Pr,floatNaN:zr,floatTime:Vr,int:Zr,intHex:Br,intOct:Fr,intTime:Qr,map:ve,merge:Ae,null:Et,omap:Cn,pairs:On,seq:De,set:Nn,timestamp:qt},Yl={"tag:yaml.org,2002:binary":In,"tag:yaml.org,2002:merge":Ae,"tag:yaml.org,2002:omap":Cn,"tag:yaml.org,2002:pairs":On,"tag:yaml.org,2002:set":Nn,"tag:yaml.org,2002:timestamp":qt};function Gr(t,e,n){let r=Kl.get(e);if(r&&!t)return n&&!r.includes(Ae)?r.concat(Ae):r.slice();let o=r;if(!o)if(Array.isArray(t))o=[];else{let s=Array.from(Kl.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(Ae)),o.reduce((s,i)=>{let a=typeof i=="string"?Wl[i]:i;if(!a){let c=JSON.stringify(i),u=Object.keys(Wl).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 rh=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,$n=class t{constructor({compat:e,customTags:n,merge:r,resolveKnownTags:o,schema:s,sortMapEntries:i,toStringDefaults:a}){this.compat=Array.isArray(e)?Gr(e,"compat"):e?Gr(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=o?Yl:{},this.tags=Gr(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,Se,{value:ve}),Object.defineProperty(this,pe,{value:ut}),Object.defineProperty(this,Ge,{value:De}),this.sortMapEntries=typeof i=="function"?i:i===!0?rh:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function Xl(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=Ir(t,e),{commentString:s}=o.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(be(c,""))}let i=!1,a=null;if(t.contents){if(z(t.contents)){if(t.contents.spaceBefore&&r&&n.push(""),t.contents.commentBefore){let d=s(t.contents.commentBefore);n.push(be(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+=Fe(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(be(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(be(s(c),"")))}return n.join(`
+${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 Ss(t,e,n){let{replacer:r}=n,o=new ne(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(Gt(a,c,n))}return o}var Tn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:xs,createNode:Ss};var qt=class t extends ne{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=H(o.key,"",n),i=H(o.value,s,n)):s=H(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=Ss(e,n,r),s=new this;return s.items=o.items,s}};qt.tag="tag:yaml.org,2002:omap";var Nn={collection:"seq",identify:t=>t instanceof Map,nodeClass:qt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=xs(t,e),r=[];for(let{key:o}of n.items)T(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 Gl({value:t,source:e},n){return e&&(t?As:vs).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var As={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:Gl},vs={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:Gl};var ql={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:re},Jl={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():re(t)}},Kl={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:re};var $n=t=>typeof t=="bigint"||Number.isInteger(t);function qr(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 Ds(t,e,n){let{value:r}=t;if($n(r)){let o=r.toString(e);return r<0?"-"+n+o.substr(1):n+o}return re(t)}var Wl={identify:$n,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>qr(t,2,2,n),stringify:t=>Ds(t,2,"0b")},Yl={identify:$n,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>qr(t,1,8,n),stringify:t=>Ds(t,8,"0")},Xl={identify:$n,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>qr(t,0,10,n),stringify:re},Hl={identify:$n,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>qr(t,2,16,n),stringify:t=>Ds(t,16,"0x")};var Jt=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),ut(this.items,n.key)||this.items.push(n)}get(e,n){let r=ut(this.items,e);return!n&&$(r)?T(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=ut(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(Gt(i,null,r));return s}};Jt.tag="tag:yaml.org,2002:set";var zn={collection:"map",identify:t=>t instanceof Set,nodeClass:Jt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>Jt.from(t,e,n),resolve(t,e){if(ge(t)){if(t.hasAllNullValues(!0))return Object.assign(new Jt,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};function Rs(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 ef(t){let{value:e}=t,n=i=>i;if(typeof e=="bigint")n=i=>BigInt(i);else if(isNaN(e)||!isFinite(e))return re(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})=>Rs(t,n),stringify:ef},Kr={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=>Rs(t,!1),stringify:ef},Kt={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(Kt.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=Rs(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 ks=[Re,ke,lt,St,As,vs,Wl,Yl,Xl,Hl,ql,Jl,Kl,Cn,De,Nn,Tn,zn,Jr,Kr,Kt];var tf=new Map([["core",Ul],["failsafe",[Re,ke,lt]],["json",Vl],["yaml11",ks],["yaml-1.1",ks]]),nf={binary:Cn,bool:On,float:Br,floatExp:Zr,floatNaN:Fr,floatTime:Kr,int:Qr,intHex:Vr,intOct:Ur,intTime:Jr,map:Re,merge:De,null:St,omap:Nn,pairs:Tn,seq:ke,set:zn,timestamp:Kt},rf={"tag:yaml.org,2002:binary":Cn,"tag:yaml.org,2002:merge":De,"tag:yaml.org,2002:omap":Nn,"tag:yaml.org,2002:pairs":Tn,"tag:yaml.org,2002:set":zn,"tag:yaml.org,2002:timestamp":Kt};function Wr(t,e,n){let r=tf.get(e);if(r&&!t)return n&&!r.includes(De)?r.concat(De):r.slice();let o=r;if(!o)if(Array.isArray(t))o=[];else{let s=Array.from(tf.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(De)),o.reduce((s,i)=>{let a=typeof i=="string"?nf[i]:i;if(!a){let c=JSON.stringify(i),u=Object.keys(nf).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 lh=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,Pn=class t{constructor({compat:e,customTags:n,merge:r,resolveKnownTags:o,schema:s,sortMapEntries:i,toStringDefaults:a}){this.compat=Array.isArray(e)?Wr(e,"compat"):e?Wr(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=o?rf:{},this.tags=Wr(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,ve,{value:Re}),Object.defineProperty(this,pe,{value:lt}),Object.defineProperty(this,Je,{value:ke}),this.sortMapEntries=typeof i=="function"?i:i===!0?lh:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function of(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=Nr(t,e),{commentString:s}=o.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(we(c,""))}let i=!1,a=null;if(t.contents){if(z(t.contents)){if(t.contents.spaceBefore&&r&&n.push(""),t.contents.commentBefore){let d=s(t.contents.commentBefore);n.push(we(d,""))}o.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>i=!0,u=Ye(t.contents,o,()=>a=null,c);a&&(u+=Be(u,"",s(a))),(u[0]==="|"||u[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${u}`:n.push(u)}else n.push(Ye(t.contents,o));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(`
+`)?(n.push("..."),n.push(we(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(we(s(c),"")))}return n.join(`
`)+`
-`}var lt=class t{constructor(e,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ie,{value:wr});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 Me({version:i}),this.setSchema(i,r),this.contents=e===void 0?null:this.createNode(e,o,r)}clone(){let e=Object.create(t.prototype,{[ie]:{value:wr}});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=z(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 qe(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=x=>typeof x=="number"||x instanceof String||x instanceof Number,g=n.filter(h).map(String);g.length>0&&(n=n.concat(g)),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}=Ol(this,i||"a"),y={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:l,onTagObj:u,replacer:o,schema:this.schema,sourceObjects:p},m=Je(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 Jt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return jt(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 jt(e)?!n&&T(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 jt(e)?this.contents!==void 0:B(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=An(this.schema,[e],n):Jt(this.contents)&&this.contents.set(e,n)}setIn(e,n){jt(e)?this.contents=n:this.contents==null?this.contents=An(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 Me({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 Me({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 $n(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=H(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"?it(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 Xl(this,e)}};function Jt(t){if(B(t))return!0;throw new Error("Expected a YAML collection as document contents")}var zn=class extends Error{constructor(e,n,r,o){super(),this.name=e,this.code=r,this.message=o,this.pos=n}},Re=class extends zn{constructor(e,n,r){super("YAMLParseError",e,n,r)}},Pn=class extends zn{constructor(e,n,r){super("YAMLWarning",e,n,r)}},As=(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 ft=class t{constructor(e,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ie,{value:Sr});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 Ze({version:i}),this.setSchema(i,r),this.contents=e===void 0?null:this.createNode(e,o,r)}clone(){let e=Object.create(t.prototype,{[ie]:{value:Sr}});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=z(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Wt(this.contents)&&this.contents.add(e)}addIn(e,n){Wt(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let r=ps(this);e.anchor=!n||r.has(n)?ms(n||"a",r):n}return new Ke(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=E=>typeof E=="number"||E instanceof String||E instanceof Number,y=n.filter(h).map(String);y.length>0&&(n=n.concat(y)),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}=Pl(this,i||"a"),g={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:l,onTagObj:u,replacer:o,schema:this.schema,sourceObjects:p},m=We(e,d,g);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 Wt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Qt(e)?this.contents==null?!1:(this.contents=null,!0):Wt(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 Qt(e)?!n&&T(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 Qt(e)?this.contents!==void 0:B(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=Dn(this.schema,[e],n):Wt(this.contents)&&this.contents.set(e,n)}setIn(e,n){Qt(e)?this.contents=n:this.contents==null?this.contents=Dn(this.schema,Array.from(e),n):Wt(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 Ze({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 Ze({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 Pn(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=H(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"?at(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 of(this,e)}};function Wt(t){if(B(t))return!0;throw new Error("Expected a YAML collection as document contents")}var Ln=class extends Error{constructor(e,n,r,o){super(),this.name=e,this.code=r,this.message=o,this.pos=n}},Ie=class extends Ln{constructor(e,n,r){super("YAMLParseError",e,n,r)}},Mn=class extends Ln{constructor(e,n,r){super("YAMLWarning",e,n,r)}},Is=(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 Ze(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,g=null,x=null,S=null,_=null,w=null;for(let E of t)switch(y&&(E.type!=="space"&&E.type!=="newline"&&E.type!=="comma"&&s(E.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),m&&(u&&E.type!=="comment"&&E.type!=="newline"&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),E.type){case"space":!e&&(n!=="doc-start"||r?.type!=="flow-collection")&&E.source.includes(" ")&&(m=E),d=!0;break;case"comment":{d||s(E,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let C=E.source.substring(1)||" ";l?l+=f+C:l=C,f="",u=!1;break}case"newline":u?l?l+=E.source:(!_||n!=="seq-item-ind")&&(c=!0):f+=E.source,u=!0,p=!0,(h||g)&&(x=E),d=!0;break;case"anchor":h&&s(E,"MULTIPLE_ANCHORS","A node can have at most one anchor"),E.source.endsWith(":")&&s(E.offset+E.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),h=E,w??(w=E.offset),u=!1,d=!1,y=!0;break;case"tag":{g&&s(E,"MULTIPLE_TAGS","A node can have at most one tag"),g=E,w??(w=E.offset),u=!1,d=!1,y=!0;break}case n:(h||g)&&s(E,"BAD_PROP_ORDER",`Anchors and tags must be after the ${E.source} indicator`),_&&s(E,"UNEXPECTED_TOKEN",`Unexpected ${E.source} in ${e??"collection"}`),_=E,u=n==="seq-item-ind"||n==="explicit-key-ind",d=!1;break;case"comma":if(e){S&&s(E,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),S=E,u=!1,d=!1;break}default:s(E,"UNEXPECTED_TOKEN",`Unexpected ${E.type} token`),u=!1,d=!1}let A=t[t.length-1],D=A?A.offset+A.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:S,found:_,spaceBefore:c,comment:l,hasNewline:p,anchor:h,tag:g,newlineAfterProp:x,end:D,start:w??D}}function ft(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(ft(e.key)||ft(e.value))return!0}return!1;default:return!0}}function Ln(t,e,n){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&ft(e)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function qr(t,e,n){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let o=typeof r=="function"?r:(s,i)=>s===i||T(s)&&T(i)&&s.value===i.value;return e.some(s=>o(s.key,n))}var Hl="All mapping items must start at the same column";function ef({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=Ze(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",Hl)),!m.anchor&&!m.tag&&!p){u=m.end,m.comment&&(a.comment?a.comment+=`
-`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||ft(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",Hl);n.atKey=!0;let g=m.end,x=f?t(n,f,m,o):e(n,g,l,null,m,o);n.schema.compat&&Ln(r.indent,f,o),n.atKey=!1,qr(n,a.items,x)&&o(g,"DUPLICATE_KEY","Map keys must be unique");let S=Ze(p??[],{indicator:"map-value-ind",next:y,offset:x.range[2],onError:o,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=S.end,S.found){h&&(y?.type==="block-map"&&!S.hasNewline&&o(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&m.start<S.found.offset-1024&&o(x.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,S,o):e(n,c,p,null,S,o);n.schema.compat&&Ln(r.indent,y,o),c=_.range[2];let w=new K(x,_);n.options.keepSourceTokens&&(w.srcToken=d),a.items.push(w)}else{h&&o(x.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),S.comment&&(x.comment?x.comment+=`
-`+S.comment:x.comment=S.comment);let _=new K(x);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 tf({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=s?.nodeClass??ne,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=Ze(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&&Ln(r.indent,l,o),c=p.range[2],a.items.push(p)}return a.range=[r.offset,c,u??c],a}function Be(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 vs="Block collections are not allowed within flow collections",Ds=t=>t&&(t.type==="block-map"||t.type==="block-seq");function nf({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=r.start.source==="{",a=i?"flow map":"flow sequence",c=s?.nodeClass??(i?W:ne),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 g=r.items[h],{start:x,key:S,sep:_,value:w}=g,A=Ze(x,{flow:a,indicator:"explicit-key-ind",next:S??_?.[0],offset:l,onError:o,parentIndent:r.indent,startOnNewline:!1});if(!A.found){if(!A.anchor&&!A.tag&&!_&&!w){h===0&&A.comma?o(A.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):h<r.items.length-1&&o(A.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),A.comment&&(u.comment?u.comment+=`
-`+A.comment:u.comment=A.comment),l=A.end;continue}!i&&n.options.strict&&ft(S)&&o(S,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(h===0)A.comma&&o(A.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(A.comma||o(A.start,"MISSING_CHAR",`Missing , between ${a} items`),A.comment){let D="";e:for(let E of x)switch(E.type){case"comma":case"space":break;case"comment":D=E.source.substring(1);break e;default:break e}if(D){let E=u.items[u.items.length-1];$(E)&&(E=E.value??E.key),E.comment?E.comment+=`
-`+D:E.comment=D,A.comment=A.comment.substring(D.length+1)}}if(!i&&!_&&!A.found){let D=w?t(n,w,A,o):e(n,A.end,_,null,A,o);u.items.push(D),l=D.range[2],Ds(w)&&o(D.range,"BLOCK_IN_FLOW",vs)}else{n.atKey=!0;let D=A.end,E=S?t(n,S,A,o):e(n,D,x,null,A,o);Ds(S)&&o(E.range,"BLOCK_IN_FLOW",vs),n.atKey=!1;let C=Ze(_??[],{flow:a,indicator:"map-value-ind",next:w,offset:E.range[2],onError:o,parentIndent:r.indent,startOnNewline:!1});if(C.found){if(!i&&!A.found&&n.options.strict){if(_)for(let L of _){if(L===C.found)break;if(L.type==="newline"){o(L,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}A.start<C.found.offset-1024&&o(C.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(C.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let P=w?t(n,w,C,o):C.found?e(n,C.end,_,null,C,o):null;P?Ds(w)&&o(P.range,"BLOCK_IN_FLOW",vs):C.comment&&(E.comment?E.comment+=`
-`+C.comment:E.comment=C.comment);let G=new K(E,P);if(n.options.keepSourceTokens&&(G.srcToken=g),i){let L=u;qr(n,L.items,E)&&o(D,"DUPLICATE_KEY","Map keys must be unique"),L.items.push(G)}else{let L=new W(n.schema);L.flow=!0,L.items.push(G);let gt=(P??E).range;L.range=[E.range[0],gt[1],gt[2]],u.items.push(L)}l=P?P.range[2]:C.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),g=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",g),p&&p.source.length!==1&&y.unshift(p)}if(y.length>0){let h=Be(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"?ef(t,e,n,r,s):n.type==="block-seq"?tf(t,e,n,r,s):nf(t,e,n,r,s),a=i.constructor;return o==="!"||o===a.tagName?(i.tag=a.tagName,i):(o&&(i.tag=o),i)}function rf(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===ne.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),d=c.resolve?.(u,f=>o(s,"TAG_RESOLVE_FAILED",f),e.options)??u,l=z(d)?d:new R(d);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=oh(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?sh(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,g]=i[m];if(g===""||g==="\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+g.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,g]=i[m];u+=h.length+g.length+1;let x=g[g.length-1]==="\r";if(x&&(g=g.slice(0,-1)),g&&h.length<c){let _=`Block scalar lines must not be less indented than their ${o.indent?"explicit indentation indicator":"first line"}`;n(u-g.length-(x?2:1),"BAD_INDENT",_),h=""}s===R.BLOCK_LITERAL?(l+=f+h.slice(c)+g,f=`
-`):h.length>c||g[0]===" "?(f===" "?f=`
+`}};function je(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,g=!1,m=null,h=null,y=null,E=null,S=null,_=null,w=null;for(let x of t)switch(g&&(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"),g=!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 C=x.source.substring(1)||" ";l?l+=f+C:l=C,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||y)&&(E=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,g=!0;break;case"tag":{y&&s(x,"MULTIPLE_TAGS","A node can have at most one tag"),y=x,w??(w=x.offset),u=!1,d=!1,g=!0;break}case n:(h||y)&&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){S&&s(x,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),S=x,u=!1,d=!1;break}default:s(x,"UNEXPECTED_TOKEN",`Unexpected ${x.type} token`),u=!1,d=!1}let A=t[t.length-1],D=A?A.offset+A.source.length:o;return g&&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:S,found:_,spaceBefore:c,comment:l,hasNewline:p,anchor:h,tag:y,newlineAfterProp:E,end:D,start:w??D}}function dt(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(dt(e.key)||dt(e.value))return!0}return!1;default:return!0}}function Fn(t,e,n){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&dt(e)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function Yr(t,e,n){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let o=typeof r=="function"?r:(s,i)=>s===i||T(s)&&T(i)&&s.value===i.value;return e.some(s=>o(s.key,n))}var sf="All mapping items must start at the same column";function af({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:g}=d,m=je(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",sf)),!m.anchor&&!m.tag&&!p){u=m.end,m.comment&&(a.comment?a.comment+=`
+`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||dt(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",sf);n.atKey=!0;let y=m.end,E=f?t(n,f,m,o):e(n,y,l,null,m,o);n.schema.compat&&Fn(r.indent,f,o),n.atKey=!1,Yr(n,a.items,E)&&o(y,"DUPLICATE_KEY","Map keys must be unique");let S=je(p??[],{indicator:"map-value-ind",next:g,offset:E.range[2],onError:o,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=S.end,S.found){h&&(g?.type==="block-map"&&!S.hasNewline&&o(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&m.start<S.found.offset-1024&&o(E.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let _=g?t(n,g,S,o):e(n,c,p,null,S,o);n.schema.compat&&Fn(r.indent,g,o),c=_.range[2];let w=new K(E,_);n.options.keepSourceTokens&&(w.srcToken=d),a.items.push(w)}else{h&&o(E.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),S.comment&&(E.comment?E.comment+=`
+`+S.comment:E.comment=S.comment);let _=new K(E);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 cf({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=s?.nodeClass??ne,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=je(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&&Fn(r.indent,l,o),c=p.range[2],a.items.push(p)}return a.range=[r.offset,c,u??c],a}function Ue(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 Os="Block collections are not allowed within flow collections",Cs=t=>t&&(t.type==="block-map"||t.type==="block-seq");function uf({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=r.start.source==="{",a=i?"flow map":"flow sequence",c=s?.nodeClass??(i?W:ne),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 y=r.items[h],{start:E,key:S,sep:_,value:w}=y,A=je(E,{flow:a,indicator:"explicit-key-ind",next:S??_?.[0],offset:l,onError:o,parentIndent:r.indent,startOnNewline:!1});if(!A.found){if(!A.anchor&&!A.tag&&!_&&!w){h===0&&A.comma?o(A.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):h<r.items.length-1&&o(A.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),A.comment&&(u.comment?u.comment+=`
+`+A.comment:u.comment=A.comment),l=A.end;continue}!i&&n.options.strict&&dt(S)&&o(S,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(h===0)A.comma&&o(A.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(A.comma||o(A.start,"MISSING_CHAR",`Missing , between ${a} items`),A.comment){let D="";e:for(let x of E)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];$(x)&&(x=x.value??x.key),x.comment?x.comment+=`
+`+D:x.comment=D,A.comment=A.comment.substring(D.length+1)}}if(!i&&!_&&!A.found){let D=w?t(n,w,A,o):e(n,A.end,_,null,A,o);u.items.push(D),l=D.range[2],Cs(w)&&o(D.range,"BLOCK_IN_FLOW",Os)}else{n.atKey=!0;let D=A.end,x=S?t(n,S,A,o):e(n,D,E,null,A,o);Cs(S)&&o(x.range,"BLOCK_IN_FLOW",Os),n.atKey=!1;let C=je(_??[],{flow:a,indicator:"map-value-ind",next:w,offset:x.range[2],onError:o,parentIndent:r.indent,startOnNewline:!1});if(C.found){if(!i&&!A.found&&n.options.strict){if(_)for(let L of _){if(L===C.found)break;if(L.type==="newline"){o(L,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}A.start<C.found.offset-1024&&o(C.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(C.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let P=w?t(n,w,C,o):C.found?e(n,C.end,_,null,C,o):null;P?Cs(w)&&o(P.range,"BLOCK_IN_FLOW",Os):C.comment&&(x.comment?x.comment+=`
+`+C.comment:x.comment=C.comment);let G=new K(x,P);if(n.options.keepSourceTokens&&(G.srcToken=y),i){let L=u;Yr(n,L.items,x)&&o(D,"DUPLICATE_KEY","Map keys must be unique"),L.items.push(G)}else{let L=new W(n.schema);L.flow=!0,L.items.push(G);let bt=(P??x).range;L.range=[x.range[0],bt[1],bt[2]],u.items.push(L)}l=P?P.range[2]:C.end}}let f=i?"}":"]",[p,...g]=r.end,m=l;if(p?.source===f)m=p.offset+p.source.length;else{let h=a[0].toUpperCase()+a.substring(1),y=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",y),p&&p.source.length!==1&&g.unshift(p)}if(g.length>0){let h=Ue(g,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 Ts(t,e,n,r,o,s){let i=n.type==="block-map"?af(t,e,n,r,s):n.type==="block-seq"?cf(t,e,n,r,s):uf(t,e,n,r,s),a=i.constructor;return o==="!"||o===a.tagName?(i.tag=a.tagName,i):(o&&(i.tag=o),i)}function lf(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,g=f&&s?f.offset>s.offset?f:s:f??s;g&&(!p||p.offset<g.offset)&&o(g,"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===ne.tagName&&a==="seq")return Ts(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),Ts(t,e,n,o,i)}let u=Ts(t,e,n,o,i,c),d=c.resolve?.(u,f=>o(s,"TAG_RESOLVE_FAILED",f),e.options)??u,l=z(d)?d:new R(d);return l.range=u.range,l.tag=i,c?.format&&(l.format=c.format),l}function Ns(t,e,n){let r=e.offset,o=fh(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?dh(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,y]=i[m];if(y===""||y==="\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+y.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,y]=i[m];u+=h.length+y.length+1;let E=y[y.length-1]==="\r";if(E&&(y=y.slice(0,-1)),y&&h.length<c){let _=`Block scalar lines must not be less indented than their ${o.indent?"explicit indentation indicator":"first line"}`;n(u-y.length-(E?2:1),"BAD_INDENT",_),h=""}s===R.BLOCK_LITERAL?(l+=f+h.slice(c)+y,f=`
+`):h.length>c||y[0]===" "?(f===" "?f=`
`:!p&&f===`
`&&(f=`
-`),l+=f+h.slice(c)+g,f=`
-`,p=!0):g===""?f===`
+`),l+=f+h.slice(c)+y,f=`
+`,p=!0):y===""?f===`
`?l+=`
`:f=`
-`:(l+=f+g,f=" ",p=!1)}switch(o.chomp){case"-":break;case"+":for(let m=a;m<i.length;++m)l+=`
+`:(l+=f+y,f=" ",p=!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 oh({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 sh(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,p,y)=>n(r+f,p,y);switch(o){case"scalar":a=R.PLAIN,c=ih(s,u);break;case"single-quoted-scalar":a=R.QUOTE_SINGLE,c=ah(s,u);break;case"double-quoted-scalar":a=R.QUOTE_DOUBLE,c=ch(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=Be(i,d,e,n);return{value:c,type:a,comment:l.comment,range:[r,d,l.offset]}}function ih(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}`),of(t)}function ah(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),of(t.slice(1,-1)).replace(/''/g,"'")}function of(t){let e,n;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
+`}let g=r+o.length+e.source.length;return{value:l,type:s,comment:o.comment,range:[r,g,g]}}function fh({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 g=Number(p);!i&&g?i=g: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 g=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",g);let m=p.source;m&&typeof m=="string"&&(l+=m.length)}}}return{mode:s,indent:i,chomp:a,comment:d,length:l}}function dh(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 $s(t,e,n){let{offset:r,type:o,source:s,end:i}=t,a,c,u=(f,p,g)=>n(r+f,p,g);switch(o){case"scalar":a=R.PLAIN,c=ph(s,u);break;case"single-quoted-scalar":a=R.QUOTE_SINGLE,c=mh(s,u);break;case"double-quoted-scalar":a=R.QUOTE_DOUBLE,c=hh(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=Ue(i,d,e,n);return{value:c,type:a,comment:l.comment,range:[r,d,l.offset]}}function ph(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}`),ff(t)}function mh(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),ff(t.slice(1,-1)).replace(/''/g,"'")}function ff(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 ch(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 hh(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}=uh(t,r);n+=s,r=i}else if(o==="\\"){let s=t[++r],i=lh[s];if(i)n+=i;else if(s===`
+`){let{fold:s,offset:i}=yh(t,r);n+=s,r=i}else if(o==="\\"){let s=t[++r],i=gh[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+=fh(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+=bh(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 uh(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 yh(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 lh={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
-`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function fh(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=dh(t.schema,o,c,n,r):e.type==="scalar"?u=ph(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=T(l)?l:new R(l)}catch(l){let f=l instanceof Error?l.message:String(l);r(n??e,"TAG_RESOLVE_FAILED",f),d=new R(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 dh(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 ph({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 sf(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 mh={composeNode:Cs,composeEmptyNode:Jr};function Cs(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=hh(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=rf(mh,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=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&&(!T(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 Jr(t,e,n,r,{spaceBefore:o,comment:s,anchor:i,tag:a,end:c},u){let d={type:"scalar",offset:sf(e,n,r),indent:-1,source:""},l=Os(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 hh({options:t},{offset:e,source:n,end:r},o){let s=new qe(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=Be(r,i,t.strict,o);return s.range=[e,i,a.offset],a.comment&&(s.comment=a.comment),s}function af(t,e,{offset:n,start:r,value:o,end:s},i){let a=Object.assign({_directives:e},t),c=new lt(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=Ze(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?Cs(u,o,d,i):Jr(u,d.end,r,null,d,i);let l=c.contents.range[2],f=Be(s,l,!1,i);return f.comment&&(c.comment=f.comment),c.range=[n,l,f.offset],c}function Mn(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 cf(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 gh={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
+`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function bh(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 zs(t,e,n,r){let{value:o,type:s,comment:i,range:a}=e.type==="block-scalar"?Ns(t,e,r):$s(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=wh(t.schema,o,c,n,r):e.type==="scalar"?u=_h(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=T(l)?l:new R(l)}catch(l){let f=l instanceof Error?l.message:String(l);r(n??e,"TAG_RESOLVE_FAILED",f),d=new R(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 wh(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 _h({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 df(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 Eh={composeNode:Ps,composeEmptyNode:Xr};function Ps(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=xh(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=zs(t,e,c,r),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{u=lf(Eh,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=Xr(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&&(!T(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 Xr(t,e,n,r,{spaceBefore:o,comment:s,anchor:i,tag:a,end:c},u){let d={type:"scalar",offset:df(e,n,r),indent:-1,source:""},l=zs(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 xh({options:t},{offset:e,source:n,end:r},o){let s=new Ke(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=Ue(r,i,t.strict,o);return s.range=[e,i,a.offset],a.comment&&(s.comment=a.comment),s}function pf(t,e,{offset:n,start:r,value:o,end:s},i){let a=Object.assign({_directives:e},t),c=new ft(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=je(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?Ps(u,o,d,i):Xr(u,d.end,r,null,d,i);let l=c.contents.range[2],f=Ue(s,l,!1,i);return f.comment&&(c.comment=f.comment),c.range=[n,l,f.offset],c}function Zn(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 mf(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 Fn=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,o,s)=>{let i=Mn(n);s?this.warnings.push(new Pn(i,r,o)):this.errors.push(new Re(i,r,o))},this.directives=new Me({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:r,afterEmptyLine:o}=cf(this.prelude);if(r){let s=e.contents;if(n)e.comment=e.comment?`${e.comment}
+`)+(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 Bn=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,o,s)=>{let i=Zn(n);s?this.warnings.push(new Mn(i,r,o)):this.errors.push(new Ie(i,r,o))},this.directives=new Ze({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:r,afterEmptyLine:o}=mf(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}
${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:cf(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=Mn(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",r,o)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=af(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(Mn(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(Mn(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=Be(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(Mn(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 lt(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 Ts=Symbol("break visit"),yh=Symbol("skip children"),uf=Symbol("remove item");function St(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),lf(Object.freeze([]),t,e)}St.BREAK=Ts;St.SKIP=yh;St.REMOVE=uf;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 lf(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=lf(Object.freeze(t.concat([[o,i]])),s.items[i],n);if(typeof a=="number")i=a-1;else{if(a===Ts)return Ts;a===uf&&(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 Ns="\uFEFF",$s="",zs="",Kr="";function ff(t){switch(t){case Ns:return"byte-order-mark";case $s:return"doc-mode";case zs:return"flow-error-end";case Kr: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:mf(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=Zn(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",r,o)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=pf(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 Ie(Zn(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 Ie(Zn(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=Ue(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 Ie(Zn(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 ft(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 Ls=Symbol("break visit"),Sh=Symbol("skip children"),hf=Symbol("remove item");function At(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),yf(Object.freeze([]),t,e)}At.BREAK=Ls;At.SKIP=Sh;At.REMOVE=hf;At.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};At.parentCollection=(t,e)=>{let n=At.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 yf(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=yf(Object.freeze(t.concat([[o,i]])),s.items[i],n);if(typeof a=="number")i=a-1;else{if(a===Ls)return Ls;a===hf&&(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 Ms="\uFEFF",Fs="",Zs="",Hr="";function gf(t){switch(t){case Ms:return"byte-order-mark";case Fs:return"doc-mode";case Zs:return"flow-error-end";case Hr: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 ke(t){switch(t){case void 0:case" ":case`
-`:case"\r":case" ":return!0;default:return!1}}var df=new Set("0123456789ABCDEFabcdef"),bh=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Wr=new Set(",[]{}"),wh=new Set(` ,[]{}
-\r `),Ps=t=>!t||wh.has(t),Zn=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 Oe(t){switch(t){case void 0:case" ":case`
+`:case"\r":case" ":return!0;default:return!1}}var bf=new Set("0123456789ABCDEFabcdef"),vh=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),eo=new Set(",[]{}"),Dh=new Set(` ,[]{}
+\r `),Bs=t=>!t||Dh.has(t),jn=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==="...")&&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]===Ns&&(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(`
+`||r>=this.indentNext||!n&&!this.atEnd?e+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(e,3);if((r==="---"||r==="...")&&Oe(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]===Ms&&(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 Fs,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==="...")&&Oe(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&&!Oe(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===":")&&Oe(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(Bs),"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("..."))&&Oe(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(Bs),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let i=this.charAt(1);if(this.flowKey||Oe(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=>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`
+`,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=>Oe(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 Kr,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&&Wr.has(s))break;n=r}else if(ke(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 Hr,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(Oe(s)||e&&eo.has(s))break;n=r}else if(Oe(o)){let s=this.buffer[r+1];if(o==="\r"&&(s===`
`?(r+=1,o=`
-`,s=this.buffer[r+1]):n=r),s==="#"||e&&Wr.has(s))break;if(o===`
-`){let i=this.continueScalar(r+1);if(i===-1)break;r=Math.max(r,i-2)}}else{if(e&&Wr.has(o))break;n=r}return!o&&!this.atEnd?this.setNext("plain-scalar"):(yield Kr,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&&Wr.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(bh.has(n))n=this.buffer[++e];else if(n==="%"&&df.has(this.buffer[e+1])&&df.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&&eo.has(s))break;if(o===`
+`){let i=this.continueScalar(r+1);if(i===-1)break;r=Math.max(r,i-2)}}else{if(e&&eo.has(o))break;n=r}return!o&&!this.atEnd?this.setNext("plain-scalar"):(yield Hr,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(Bs),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(Oe(r)||n&&eo.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(;!Oe(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(vh.has(n))n=this.buffer[++e];else if(n==="%"&&bf.has(this.buffer[e+1])&&bf.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 At=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 dt(t,e){for(let n=0;n<t.length;++n)if(t[n].type===e)return!0;return!1}function pf(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 hf(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 Yr(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 Kt(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 Xr(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 mf(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!dt(e.start,"explicit-key-ind")&&!dt(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,hf(e.value)?e.value.end?Xr(e.value.end,e.sep):e.value.end=e.sep:Xr(e.start,e.sep),delete e.sep)}var Bn=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 Zn,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=ff(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"&&mf(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&&pf(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":{pf(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=Yr(this.peek(2)),r=Kt(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 vt=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 pt(t,e){for(let n=0;n<t.length;++n)if(t[n].type===e)return!0;return!1}function wf(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 Ef(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 to(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 Yt(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 no(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 _f(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!pt(e.start,"explicit-key-ind")&&!pt(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Ef(e.value)?e.value.end?no(e.value.end,e.sep):e.value.end=e.sep:no(e.start,e.sep),delete e.sep)}var Un=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 jn,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=gf(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"&&_f(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&&wf(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":{wf(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=to(this.peek(2)),r=Yt(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)){Xr(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(dt(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(hf(n.key)&&!dt(n.sep,"newline")){let i=Kt(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(dt(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let i=Kt(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]}):dt(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&&!dt(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)){Xr(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||dt(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=Yr(r),s=Kt(o);mf(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)){no(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(pt(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(Ef(n.key)&&!pt(n.sep,"newline")){let i=Yt(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(pt(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let i=Yt(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]}):pt(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&&!pt(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)){no(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||pt(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=to(r),s=Yt(o);_f(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=Yr(e),r=Kt(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=Yr(e),r=Kt(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 _h(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new At||null,prettyErrors:e}}function Ls(t,e={}){let{lineCounter:n,prettyErrors:r}=_h(e),o=new Bn(n?.addNewLine),s=new Fn(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(As(t,n)),i.warnings.forEach(As(t,n))),i}var Ie=class extends Error{code;constructor(e){super(`Structured data failed validation: ${e}`),this.name="StructuredDataError",this.code=e}},gf=t=>Ce(JSON.stringify(t)),yf=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},bf=(t,e)=>{if(yf(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(Ce(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(yf(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(gf(o)>e.serializedBytes)throw new Ie("SERIALIZED_BYTES_EXCEEDED");return o};var Y=class extends Error{code;line;column;constructor(e,n,r,o){super(n,{cause:o}),this.name="MarkdownMetadataError",this.code=e,this.line=r?.line,this.column=r?.column}};var Wt=new Uint8Array([239,187,191]),wf=Wt.byteLength+10,Sh=(t,e,n=0)=>t.byteLength-n<e.byteLength?!1:e.every((r,o)=>t[n+o]===r),jn=(t,e)=>{let n=0;if(Sh(t,Wt))n=Wt.byteLength;else if(t.byteLength<Wt.byteLength&&Wt.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 Ah={bytes:k.frontmatterBytes,depth:k.frontmatterDepth,fields:k.frontmatterFields,stringBytes:k.frontmatterStringBytes,serializedBytes:k.indexedPropertiesBytes},_f=t=>{try{return le(t)}catch{throw new Y("FRONTMATTER_DECODING_FAILED","Markdown frontmatter is not valid UTF-8")}},vh=t=>t.code==="DEPTH_EXCEEDED"?new Y("FRONTMATTER_DEPTH_EXCEEDED","Markdown frontmatter exceeds the nesting limit"):t.code==="FIELDS_EXCEEDED"?new Y("FRONTMATTER_FIELDS_EXCEEDED","Markdown frontmatter exceeds the field limit"):t.code==="STRING_BYTES_EXCEEDED"?new Y("FRONTMATTER_STRING_BYTES_EXCEEDED","Markdown frontmatter contains a string that exceeds the byte limit"):t.code==="SERIALIZED_BYTES_EXCEEDED"?new Y("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter properties exceed the indexed byte limit"):new Y("FRONTMATTER_INVALID","Markdown frontmatter must contain a JSON-compatible object"),xf=(t,e)=>{let n=new At,r=Ls(t,{schema:"core",uniqueKeys:!0,lineCounter:n});if(r.errors.length>0){let s=r.errors[0],i=n.linePos(s.pos[0]);throw new Y("FRONTMATTER_INVALID",`Markdown frontmatter contains invalid YAML: ${s.message}`,{line:i.line+1,column:i.col},s)}let o;try{o=r.toJS({maxAliasCount:0})}catch{throw new Y("FRONTMATTER_INVALID","Markdown frontmatter contains unsupported YAML aliases")}if(o===null)return{};try{return bf(o,e)}catch(s){throw s instanceof Ie?vh(s):s}};var Ef=async(t,e={})=>{let n={...Ah,...e},r=n.bytes+wf,o=new Uint8Array(r),s=0;for await(let c of zt(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=jn(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 Y("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter exceeds the byte limit");let h=_f(p.subarray(y.yamlStart,y.yamlEnd));return{properties:xf(h,n),frontmatterBytes:m,consumedBytes:y.blockEnd}}}if(s>=r)break}let i=o.subarray(0,s),a=jn(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=_f(i.subarray(a.yamlStart,a.yamlEnd));return{properties:xf(u,n),frontmatterBytes:c,consumedBytes:a.blockEnd}}}throw new Y("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 Y("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 se?new Y("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown content exceeds the byte limit"):a}let r;try{r=le(n)}catch{throw new Y("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}let s=jn(n,!0)?.blockEnd??0,i;try{i=s===0?Pt(r):le(n.subarray(s))}catch{throw new Y("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}return{body:i,bodyBytes:Ce(i),sourceBytes:n.byteLength}};var pt=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}},Dh=O({source:v(),body:v(),frontmatter:Ee(v(),nt())}),to=t=>{let e;try{e=Dh.parse(t)}catch(n){throw new pt({code:"INVALID_DOCUMENT",message:"Markdown document is invalid",cause:n})}return Object.freeze({source:e.source,body:e.body,frontmatter:ot(e.frontmatter)})},eo="#frontmatter",Rh=t=>`${eo}${t.slice(1)}`,kh=t=>{if(t!==eo&&t.startsWith(`${eo}/`)===!1)throw new pt({code:"UNUSED_REFERENCE",message:`Resolved Markdown reference ${t} is outside frontmatter`,referenceId:t});return`#${t.slice(eo.length)}`},Ih=t=>{let e=t.referenceId===void 0?void 0:Rh(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 pt({code:n,message:t.message,referenceId:e,cause:t})},Sf=async({source:t,maximumBytes:e=k.hydratedFileBytes})=>{let n;try{n=await Te(t,e)}catch(i){throw i instanceof se?new pt({code:"CONTENT_LIMIT_EXCEEDED",message:"Markdown document exceeds the byte limit",cause:i}):i}let r;try{r=Pt(le(n))}catch(i){throw new pt({code:"CONTENT_DECODING_FAILED",message:"Markdown document is not valid UTF-8",cause:i})}let[o,s]=await Promise.all([Hr(n,e),Ef(n).catch(i=>{if(i instanceof Y)return{properties:{},frontmatterBytes:0,consumedBytes:0};throw i})]);return to({source:r,body:o.body,frontmatter:s.properties})};var Af=({document:t,references:e,allowUnresolvedReferences:n=!1})=>{let r=to(t),o=new Map;for(let[i,a]of e)o.set(kh(i),a);let s;try{s=gr({document:r.frontmatter,references:o,allowUnresolvedReferences:n})}catch(i){throw i instanceof de&&Ih(i),i}return to({...r,frontmatter:s})},vf=({document:t,representation:e})=>{let n=to(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 pt({code:"UNSUPPORTED_REPRESENTATION",message:`Markdown documents do not support ${e.type}`})};var Df=t=>{let e=encodeURIComponent(t);return e==="."?"%2E":e===".."?"%2E%2E":e};var Rf=t=>t.split("/").map(e=>{try{return Df(decodeURIComponent(e))}catch{return Df(e)}}).join("/");var kf=t=>Object.fromEntries(Object.entries(t??{}).map(([e,n])=>[e,n.url]));var no=(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})}},Oh=({reference:t,runtimeAsset:e})=>{let{url:n,contentRef:r,...o}=e;return{...o,id:t.assetId,src:no(n,t.suffix)}},mt=({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?Oh({reference:s,runtimeAsset:a}):no(a.url,s.suffix)}))}return o};var oo=t=>{let e=t.format==="json"?t.value:t.value.frontmatter;return Mt(e)?e:void 0},Fs=({document:t,references:e,runtimeAssets:n})=>{let r=oo(t);if(r===void 0||e===void 0)return t;let o=mt({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})})},ro=t=>Object.freeze(t),If=async({format:t,source:e,maximumBytes:n=k.hydratedFileBytes})=>ro(t==="json"?{format:t,value:await Al({source:e,maximumBytes:n})}:{format:t,value:await Sf({source:e,maximumBytes:n})});var Of=({document:t,references:e,allowUnresolvedReferences:n})=>t.format==="json"?ro({format:t.format,value:gr({document:t.value,references:e,allowUnresolvedReferences:n})}):ro({format:t.format,value:Af({document:t.value,references:e,allowUnresolvedReferences:n})}),Cf=({document:t,representation:e})=>t.format==="json"?vl({document:t.value,representation:e}):vf({document:t.value,representation:e});var so=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}},Yt=({node:t,source:e})=>{if(e.revision!==t.revision)throw new so({code:"REVISION_MISMATCH",documentId:t.id,expectedRevision:t.revision,actualRevision:e.revision});if(t.format!==void 0&&e.format!==t.format)throw new so({code:"FORMAT_MISMATCH",documentId:t.id,expectedFormat:t.format,actualFormat:e.format});return e};var Xt=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"},ae=(t,e)=>{try{t?.(e)}catch{}},Tf=({load:t,onEvent:e})=>async(n,r)=>{let o={documentId:n.id,revision:n.revision};ae(e,{type:"document-fetch-started",...o});try{let s=await t(n,r);return ae(e,{type:"document-fetch-completed",...o}),s}catch(s){throw ae(e,{type:"document-fetch-failed",...o,errorCode:Xt(s)}),s}};var Ch=O({format:ee(xn),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}},Nf=({fetch:t,getRequest:e,getMetadata:n,onEvent:r})=>Tf({load:async(s,{signal:i})=>{let a;try{a=await t(e(s),{signal:i})}catch(d){throw new Ht({code:"REQUEST_FAILED",message:`Document ${s.id} request failed`,documentId:s.id,cause:d})}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=Ch.parse(n({node:s,response:a}))}catch(d){throw new Ht({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 Ht({code:"BODY_MISSING",message:`Document ${s.id} response body is unavailable`,documentId:s.id});return Object.freeze({...c,source:Hu(u)})},onEvent:r});var en=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,zf=new Set,Zs=typeof process=="object"&&process?process:{},Pf=(t,e,n,r)=>{typeof Zs.emitWarning=="function"?Zs.emitWarning(t,e,n,r):console.error(`[${n}] ${e}: ${t}`)},io=globalThis.AbortController,$f=globalThis.AbortSignal;if(typeof io>"u"){$f=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},io=class{constructor(){e()}signal=new $f;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,Pf("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 Th=t=>!zf.has(t),Iv=Symbol("type"),ht=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Lf=t=>ht(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?tn:null:null,tn=class extends Array{constructor(e){super(e),this.fill(0)}},Bs=class t{heap;length;static#c=!1;static create(e){let n=Lf(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]}},nn=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.#E(n),rindexes:n=>e.#S(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:g,noDeleteOnFetchRejection:x,noDeleteOnStaleGet:S,allowStaleOnFetchRejection:_,allowStaleOnFetchAbort:w,ignoreFetchAbort:A}=e;if(n!==0&&!ht(n))throw new TypeError("max option must be a nonnegative integer");let D=n?Lf(n):Array;if(!D)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(g!==void 0&&typeof g!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#C=g,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 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=!!x,this.allowStaleOnFetchRejection=!!_,this.allowStaleOnFetchAbort=!!w,this.ignoreFetchAbort=!!A,this.maxEntrySize!==0){if(this.#f!==0&&!ht(this.#f))throw new TypeError("maxSize must be a positive integer if specified");if(!ht(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#B()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!S,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!a,this.ttlResolution=ht(o)||o===0?o:1,this.ttlAutopurge=!!s,this.ttl=r||0,this.ttl){if(!ht(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 E="LRU_CACHE_UNBOUNDED";Th(E)&&(zf.add(E),Pf("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",E,t))}}getRemainingTTL(e){return this.#r.has(e)?1/0:0}#z(){let e=new tn(this.#c),n=new tn(this.#c);this.#p=e,this.#_=n,this.#P=(s,i,a=en.now())=>{if(n[s]=i!==0?a:0,e[s]=i,i!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#m(s)&&this.#A(this.#n[s],"expire")},i+1);c.unref&&c.unref()}},this.#R=s=>{n[s]=e[s]!==0?en.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=en.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 tn(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(!ht(o))if(s){if(typeof s!="function")throw new TypeError("sizeCalculation must be a function");if(o=s(r,n),!ht(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.#T=(n,r,o)=>{if(e[n]=r,this.#f){let s=this.#f-e[n];for(;this.#g>s;)this.#N(!0)}this.#g+=e[n],o&&(o.entrySize=r,o.totalCalculatedSize=this.#g)}}#k=e=>{};#T=(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};*#E({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]}*#S({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.#E())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.#S())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.#E()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*rkeys(){for(let e of this.#S()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*values(){for(let e of this.#E())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#S())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.#E()){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.#E()){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.#S()){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.#S({allowStale:!0}))this.#m(n)&&(this.#A(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-(en.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.#E({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=en.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=en.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.#A(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.#N(!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.#T(l,d,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: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.#k(l),this.#T(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.#N(!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)}}}#N(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 io,{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:g}=i.signal,x=r.ignoreFetchAbort&&m!==void 0;if(r.status&&(g&&!h?(r.status.fetchAborted=!0,r.status.fetchError=i.signal.reason,x&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),g&&!x&&!h)return l(i.signal.reason);let S=p;return this.#e[n]===p&&(m===void 0?S.__staleWhileFetching?this.#e[n]=S.__staleWhileFetching:this.#A(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,g=h&&r.allowStaleOnFetchAbort,x=g||r.allowStaleOnFetchRejection,S=x||r.noDeleteOnFetchRejection,_=p;if(this.#e[n]===p&&(!S||_.__staleWhileFetching===void 0?this.#A(e,"fetch"):g||(this.#e[n]=_.__staleWhileFetching)),x)return r.status&&_.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),_.__staleWhileFetching;if(_.__returned===_)throw m},f=(m,h)=>{let g=this.#O?.(e,s,c);g&&g instanceof Promise&&g.then(x=>m(x===void 0?void 0:x),h),i.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(m(void 0),r.allowStaleOnFetchAbort&&(m=x=>u(x,!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.#D)return!1;let n=e;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof io}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:g,signal:x}=n;if(!this.#D)return g&&(g.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,status:g});let S={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:g,signal:x},_=this.#r.get(e);if(_===void 0){g&&(g.fetch="miss");let w=this.#$(e,_,S,m);return w.__returned=w}else{let w=this.#e[_];if(this.#t(w)){let P=r&&w.__staleWhileFetching!==void 0;return g&&(g.fetch="inflight",P&&(g.returnedStale=!0)),P?w.__staleWhileFetching:w.__returned=w}let A=this.#m(_);if(!h&&!A)return g&&(g.fetch="hit"),this.#I(_),o&&this.#R(_),g&&this.#v(g,_),w;let D=this.#$(e,_,S,m),C=D.__staleWhileFetching!==void 0&&r;return g&&(g.fetch=A?"stale":"refresh",C&&A&&(g.returnedStale=!0)),C?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.#A(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.#A(e,"delete")}#A(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.#S({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 nn({maxSize:t,sizeCalculation:e=>Math.max(1,e.bytes.byteLength)})},Un=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}},ao=({contentRef:t,revision:e,format:n})=>fe([t,e,n??null]),Nh=t=>{if(typeof t!="object"||t===null)return!1;let e=t;return ol(e.format)&&typeof e.revision=="string"&&e.revision.length>0&&e.bytes instanceof Uint8Array},Mf=t=>Object.freeze({format:t.format,revision:t.revision,source:t.bytes}),Ff=({load:t,cache:e,maximumBytes:n=k.hydratedFileBytes,onEvent:r})=>{let o=new Map;return async(s,i)=>{let a=ao(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){ae(r,{type:"document-cache-read-failed",documentId:s.id,revision:s.revision,errorCode:Xt(m)})}if(Nh(l)&&l.revision===s.revision&&l.bytes.byteLength<=n&&(s.format===void 0||l.format===s.format))return ae(r,{type:"document-cache-hit",documentId:s.id,revision:s.revision}),Mf(l);ae(r,{type:"document-cache-miss",documentId:s.id,revision:s.revision});let f=Yt({node:s,source:await t(s,i)}),p;try{p=await Te(f.source,n)}catch(m){throw m instanceof se?new Un({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),ae(r,{type:"document-cache-stored",documentId:s.id,revision:s.revision})}catch(m){ae(r,{type:"document-cache-write-failed",documentId:s.id,revision:s.revision,errorCode:Xt(m)})}return Mf(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}},co=t=>{if(t?.aborted)throw new We({code:"REQUEST_CANCELLED",message:"Document graph resolution was cancelled",cause:t.reason})},Zf=async({graph:t,rootIds:e,concurrency:n,signal:r,load:o,select:s,assemble:i})=>{co(r);let a=dr({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 hr([...d.values()],n,async p=>{co(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&&co(r),new We({code:"DOCUMENT_LOAD_FAILED",message:`Document ${y.id} could not be loaded`,documentId:y.id,cause:m})}});let l=Lt(t.edges),f=new Map;for(let p of a){co(r);let y=new Map;for(let h of l.get(p.id)??[]){let g=c.get(h.reference.documentId);if(g===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 x=f.get(h.reference.documentId),S;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});S=x}else try{S=await s({reference:h.reference,value:x,sourceNode:p,targetNode:g})}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,S)}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 vt=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}},$h=(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()}}},zh=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:d})=>{let l=dr({graph:t,rootIds:e}).length,f={rootCount:e.length,documentCount:l};ae(a,{type:"resolution-started",...f});try{if(l>s)throw new vt({code:"DOCUMENT_COUNT_EXCEEDED",message:"Document graph resolution exceeds the document limit",documentCount:l,documentLimit:s});let p=0,y=Promise.resolve(),m=await Zf({graph:t,rootIds:e,concurrency:n,signal:i,load:async(h,g)=>{let x=y,S=()=>{};y=new Promise(w=>{S=w});let _;try{_={status:"fulfilled",value:await d(h,g)}}catch(w){_={status:"rejected",reason:w}}await x;try{if(_.status==="rejected")throw _.reason;if(_.value.byteLength>r)throw new vt({code:"CONTENT_LIMIT_EXCEEDED",message:`Document ${h.id} exceeds the byte limit`,documentId:h.id,contentByteLimit:r,cause:new se});let w=p+_.value.byteLength;if(w>o)throw new vt({code:"TOTAL_BYTES_EXCEEDED",message:"Document graph resolution exceeds the total byte limit",documentId:h.id,totalBytes:w,totalByteLimit:o});return p=w,await _.value.parse()}finally{S()}},select:({reference:h,value:g})=>Cf({document:g,representation:h.representation}),assemble:({node:h,source:g,references:x})=>{let S=Of({document:g,references:x,allowUnresolvedReferences:c});return u?.({node:h,document:S})??S}});return ae(a,{type:"resolution-completed",...f}),m}catch(p){throw ae(a,{type:"resolution-failed",...f,errorCode:Xt(p)}),p}},Bf=({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 nn({maxSize:o,sizeCalculation:({byteLength:f})=>Math.max(1,f)}),i=new Map,a=$h(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(g){y(g)}};n.addEventListener("abort",h,{once:!0}),f.then(g=>{m(),p(g)},g=>{m(),y(g)}),n.aborted&&h()})),d=async(f,p)=>{c(p.signal);let y=ao(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 g=a(async()=>{c(p.signal);let x=Yt({node:f,source:await t(f,{signal:n})});c(p.signal);let S=await Xo(x.source,r+1);c(p.signal);let _,w=Object.freeze({format:x.format,revision:x.revision,bytes:S,byteLength:S.byteLength,parse:()=>(_??=If({format:x.format,source:S,maximumBytes:r}),_)});return w.byteLength<=o&&s.set(y,w),w});i.set(y,g);try{return await u(g)}finally{i.delete(y)}};return Object.freeze({getCached:f=>{c();let p=s.get(ao(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 zh({...f,concurrency:e,maximumBytes:r,signal:n,load:d})})};var jf=t=>{if(t.output.mode==="all")return"all";let e=[];for(let{field:n}of ur(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},Uf=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",...Sl(e)]}catch{return}},Qf=(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},Vf=({queryPaths:t,referenceId:e})=>{let n=Uf(e);return n!==void 0&&(t==="all"||t.some(r=>Qf(r,n)))},Gf=({graph:t,sourceId:e,field:n})=>n[0]!=="properties"?!1:t.edges.some(r=>{if(r.sourceId!==e)return!1;let o=Uf(r.referenceId);return o!==void 0&&Qf(n,o)}),qf=({graph:t,query:e})=>{let n=jf(e),r=new Set;for(let o of t.edges)Vf({queryPaths:n,referenceId:o.referenceId})&&r.add(o.sourceId);return[...r]},Jf=({graph:t,query:e,rootIds:n})=>{let r=jf(e),o=new Set(n),s=new Map(t.nodes.map(l=>[l.id,l])),i=Lt(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)&&Vf({queryPaths:r,referenceId:l.referenceId})&&(c.add(l),d(l.reference.documentId));return En({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 Kf=({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:En({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 Wf=({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=no(i,s.suffix);o=`${o.slice(0,s.start)}${a}${o.slice(s.end)}`}return o};var X=class extends Error{code;details;constructor({code:e,message:n,details:r}){super(n),this.name="AssetResourceHydrationError",this.code=e,this.details=r}},Ph=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 X({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 X({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())},Lh=t=>typeof t.mimeType=="string"&&(t.mimeType.startsWith("text/")||["application/json","application/javascript","application/xml","image/svg+xml"].includes(t.mimeType)),Mh=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 se?new X({code:"CONTENT_LIMIT_EXCEEDED",message:"Asset storage returned more content than requested"}):s}},Fh=t=>{try{return le(t)}catch{throw new X({code:"CONTENT_DECODING_FAILED",message:"Selected asset content is not valid UTF-8"})}},Zh=(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 X({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},Yf=t=>{let e=t.flatMap(({reason:s,document:i})=>{if(typeof i.path!="string")return[];let a=s instanceof X?s.code:"CONTENT_READ_FAILED",c=s instanceof Error&&s.message!==""?s.message:"Selected asset content could not be read";return[{severity:"error",scope:"query",phase:"source",code:a,message:c,assetId:i._id,path:i.path}]});if(e.length!==t.length)throw t[0].reason;if(t.length===1){let s=t[0].reason,i=e[0];throw i===void 0?s:new X({code:s instanceof X?s.code:"INVALID_REQUEST",message:i.message,details:{...s instanceof X?s.details:{},diagnostics:e}})}let n=new Set(e.map(({code:s})=>s)),r=e[0]?.code,o=n.size===1&&(r==="CONTENT_IDENTITY_REQUIRED"||r==="CONTENT_NOT_TEXT"||r==="CONTENT_DECODING_FAILED"||r==="CONTENT_LIMIT_EXCEEDED")?r:"INVALID_REQUEST";throw new X({code:o,message:`${e.length} selected asset content errors found`,details:{diagnostics:e}})},Xf=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=Ph(t);if(i.length>k.hydratedFileCount)throw new X({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(m=>[m._id,m])),c=i.map(m=>{let h=a.get(m._id);try{if(h===void 0||h.revision!==m.revision||h.contentRef!==m.contentRef||typeof h.size!="number"||typeof h.mimeType!="string")throw new X({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset content identity is stale or unavailable",details:{assetId:m._id}});let g={...h,size:h.size,mimeType:h.mimeType};if(Lh(g)===!1)throw new X({code:"CONTENT_NOT_TEXT",message:"Selected binary asset cannot be embedded as text",details:{assetId:m._id,mimeType:g.mimeType}});return{status:"fulfilled",value:{identity:m,document:g,readLength:Zh(g,n)}}}catch(g){return{status:"rejected",reason:g,document:h??{_id:m._id}}}}),u=c.flatMap(m=>m.status==="rejected"?[m]:[]);u.length>0&&Yf(u);let d=c.flatMap(m=>m.status==="fulfilled"?[m.value]:[]),l=d.reduce((m,h)=>m+h.readLength,0);if(l>k.hydratedTotalBytes)throw new X({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected assets exceed the total hydrated-content limit",details:{totalReadBytes:l,totalByteLimit:k.hydratedTotalBytes}});let f=await hr(d,k.concurrentContentReads,async m=>{try{let h=n.mode==="range"?{offset:n.offset,length:m.readLength}:m.readLength===0?void 0:{offset:0,length:m.readLength},g=await Mh({read:r,contentRef:m.identity.contentRef,range:h,maximumBytes:m.readLength});if(g.byteLength!==m.readLength)throw new X({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset bytes do not match canonical metadata",details:{assetId:m.identity._id}});let x;if(n.mode==="markdown-body-ref")try{x=(await Hr(g,m.readLength||1)).body;let _=o?.[m.identity.contentRef];_!==void 0&&s!==void 0&&(x=Wf({markdown:x,references:_,assetUrls:s}))}catch{throw new X({code:"CONTENT_DECODING_FAILED",message:"Selected Markdown body could not be decoded",details:{assetId:m.identity._id}})}else x=Fh(g);let S=Ce(x);return{status:"fulfilled",value:{id:m.identity._id,returnedBytes:S,content:{...m.identity,encoding:"utf-8",text:x,...n.mode==="range"?{range:{offset:n.offset,length:g.byteLength,total:m.document.size}}:{}}}}}catch(h){return{status:"rejected",reason:h,document:m.document}}}),p=f.flatMap(m=>m.status==="rejected"?[m]:[]);p.length>0&&Yf(p);let y=f.flatMap(m=>m.status==="fulfilled"?[m.value]:[]);return{content:Object.fromEntries(y.map(({id:m,content:h})=>[m,h])),hydratedFileCount:d.length,hydratedBytes:y.reduce((m,{returnedBytes:h})=>m+h,0)}};var hD=v().datetime({offset:!0}).transform(t=>new Date(t).toISOString());var Bh=/^[A-Za-z_][A-Za-z0-9_]*$/,Hf=(t,e)=>Bh.test(e)?`${t}.${e}`:`${t}[${JSON.stringify(e)}]`;var ed=({document:t,includes:e})=>{let n={};for(let r of hl){let o=t[r];o!==void 0&&e(r)&&(n[r]=o)}return n},yt=Symbol("missing property selection"),Us=(t,e)=>{if(e.some(r=>r.length===0)||typeof yr(t)=="string")return t;if(Array.isArray(t)){let r=e.filter(([s])=>s==="*").map(s=>s.slice(1));if(r.length===0)return yt;let o=t.map(s=>Us(s,r));return o.some(s=>s!==yt)?o.map(s=>s===yt?null:s):yt}if(typeof t!="object"||t===null)return yt;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!==yt&&(n[r]=i)}return Object.keys(n).length===0?yt:n},td=({properties:t,fields:e})=>{let n=e.filter(([o])=>o==="properties").map(o=>o.slice(1)),r=Us(t,n);return r===yt?{}:r};var we=class extends Error{code;issues;details;constructor(e,n){super(e,n),this.name="AssetQueryExecutionError",this.code=n?.code??"INVALID_REQUEST",this.issues=n?.issues,this.details=n?.details}},Qn=class extends we{code="MULTIPLE_RESULTS";matchedCount;constructor(e){super(`Expected at most one asset, but the query matched ${e}.`),this.matchedCount=e,this.name="AssetQueryMultipleResultsError"}},on=class extends Error{constructor(){super("The requested asset index revision is stale"),this.name="AssetIndexRevisionError"}},Qs=t=>{if(t[0]!=="properties")return t[0];let e="properties";for(let n of t.slice(1))e=Hf(e,n);return e},nd=({filter:t,fieldTypes:e})=>bl(e).includes(t.operator),rd=(t,e)=>t!==void 0&&Object.hasOwn(t.fields,e)?t.fields[e]:void 0,jh=t=>{if(t===null)return"null";if(Array.isArray(t))return"array";if(typeof t=="object")return"object";if(typeof t=="boolean")return"boolean";if(typeof t=="number")return"number";if(typeof t=="string")return"string"},Uh=({operator:t,fieldTypes:e})=>{if(!(t==="contains"&&e.includes("array"))){if(t==="startsWith"||t==="endsWith"||t==="contains")return["string"];if(t==="gt"||t==="gte"||t==="lt"||t==="lte")return e.filter(n=>n==="string"||n==="number");if(t==="eq"||t==="ne"||t==="in")return e}},od=({filter:t,fieldTypes:e,path:n})=>{let r=Uh({operator:t.operator,fieldTypes:e});return r===void 0?[]:(t.operator==="in"?t.value:[t.value]).flatMap((s,i)=>r.some(a=>a===jh(s))?[]:[t.operator==="in"?[...n,"value",String(i)]:[...n,"value"]])},Gs=(t,e=["query","where"])=>"field"in t?[{filter:t,path:e}]:"all"in t?t.all.flatMap((n,r)=>Gs(n,[...e,"all",String(r)])):t.any.flatMap((n,r)=>Gs(n,[...e,"any",String(r)])),Qh=({query:t,catalog:e})=>{let n=st.safeParse(t);if(n.success===!1)return{success:!1,issues:n.error.issues.map(u=>({severity:"error",code:u.code,path:["query",...u.path.map(String)],message:u.message}))};let r=n.data,o=new Map,s=[],i=[],a=(u,d,l)=>{s.push(l),i.push({severity:"warning",code:u,path:d,message:l})};for(let{filter:u,path:d}of Gs(r.where)){let l=Qs(u.field);if(o.set(l,u.field),u.field[0]==="properties"){let f=rd(e,l);if(e!==void 0&&f===void 0)a("UNOBSERVED_FIELD",[...d,"field"],`Asset field ${l} is not currently observed`);else if(f!==void 0&&nd({filter:u,fieldTypes:f.types})===!1)a("INCOMPATIBLE_OBSERVED_TYPES",[...d,"operator"],`Operator ${u.operator} is not compatible with the currently observed types of ${l}`);else if(f!==void 0)for(let p of od({filter:u,fieldTypes:f.types,path:d}))a("INCOMPATIBLE_OBSERVED_VALUE",p,`Filter value is not compatible with the currently observed types of ${l}`)}else{let f=os[u.field[0]];if(nd({filter:u,fieldTypes:f})===!1)i.push({severity:"error",code:"INCOMPATIBLE_OPERATOR",path:[...d,"operator"],message:`Operator ${u.operator} is incompatible with ${l}`});else for(let p of od({filter:u,fieldTypes:f,path:d}))i.push({severity:"error",code:"INCOMPATIBLE_VALUE",path:p,message:`Filter value is incompatible with ${l}`})}}for(let[u,d]of r.sort.entries()){let l=Qs(d.field);if(o.set(l,d.field),d.field[0]==="properties"){let f=rd(e,l);e!==void 0&&f===void 0?a("UNOBSERVED_FIELD",["query","sort",String(u),"field"],`Asset field ${l} is not currently observed`):f!==void 0&&f.types.some(p=>p==="object"||p==="array")&&a("STRUCTURED_SORT_ORDER",["query","sort",String(u),"field"],`Asset field ${l} currently includes structured values that use deterministic JSON sort order`)}}if(r.output.mode==="fields")for(let u of r.output.fields){let d=Qs(u);o.set(d,u)}let c=[...new Map(i.map(u=>[JSON.stringify([u.code,u.path,u.message]),u])).values()];return{success:c.some(({severity:u})=>u==="error")===!1,query:r,referencedFieldPaths:[...o.values()],warnings:[...new Set(s)],issues:c}},Vh=({query:t,catalog:e})=>{let n=Qh({query:t,catalog:e});if(n.success===!1){let r=n.issues.filter(({severity:o})=>o==="error");throw new we(r.length===1?r[0].message:`${r.length} invalid query operations found`,{issues:n.issues})}return{query:n.query,referencedFieldPaths:n.referencedFieldPaths,warnings:n.warnings,warningIssues:n.issues}},qs=(t,e,n)=>{let r=e[0]==="id"?t._id:mr(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},Gh=t=>typeof t=="string"||Array.isArray(t)?t.length===0:typeof t=="object"&&t!==null&&Object.keys(t).length===0,qh=(t,e)=>{if(typeof t=="number"&&typeof e=="number")return t-e;if(typeof t=="string"&&typeof e=="string")return Ne(t,e)},sd=(t,e)=>{if(t.field.length!==1||t.field[0]!=="path"||typeof e!="string")return[e];let n=Rf(e);return n===e?[e]:[e,n]},Js=(t,e,n)=>{let r=qs(t,e.field,n);if(e.operator==="exists")return r!=null===e.value;if(e.operator==="isEmpty")return Gh(r)===e.value;let o=sd(e,e.value);if(e.operator==="eq")return o.some(i=>_n(r,i));if(e.operator==="ne")return o.every(i=>_n(r,i)===!1);if(e.operator==="in")return e.value.some(i=>sd(e,i).some(a=>_n(r,a)));if(e.operator==="contains")return typeof r=="string"?o.some(i=>typeof i=="string"&&r.includes(i)):Array.isArray(r)&&r.some(i=>_n(i,e.value));if(e.operator==="startsWith")return typeof r=="string"&&o.some(i=>typeof i=="string"&&r.startsWith(i));if(e.operator==="endsWith")return typeof r=="string"&&o.some(i=>typeof i=="string"&&r.endsWith(i));let s=qh(r,o[o.length-1]);return s===void 0?!1:e.operator==="gt"?s>0:e.operator==="gte"?s>=0:e.operator==="lt"?s<0:s<=0},Jh=({document:t,where:e,runtimeAsset:n,filterKeys:r,filterResults:o})=>$t(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,Kh=({document:t,content:e})=>{if(e.mode!=="markdown-body-ref")return!0;let n=t.mimeType===void 0?void 0:sl(t.mimeType);return n==="markdown"||n==="mdx"?!0:t.extension==="md"||t.extension==="mdx"},Wh=(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")?Ne(String(t),String(e)):Ne(fe(t),fe(e))},Yh=({left:t,right:e,sort:n,runtimeAssets:r})=>{for(let o of n){let s=Wh(qs(t,o.field,r?.[t._id]),qs(e,o.field,r?.[e._id]));if(s!==0)return o.direction==="asc"?s:-s}return Ne(t._id,e._id)};var Xh=(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=td({properties:t.properties,fields:e.fields});return Object.keys(n).length===0?void 0:n},rn=(t,e)=>t.includeMetadata&&yl(e)||t.mode==="fields"&&t.fields.some(n=>n.length===1&&n[0]===e),Hh=t=>t.mode==="all"||t.mode==="fields"&&t.fields.some(e=>e.length===1&&e[0]==="excerpt"),ey=(t,e,n)=>{if(rn(e,"url")&&n===void 0)throw new we(`Asset URL is unavailable for ${t._id}`,{details:{assetId:t._id}});let r=Xh(t,e),o=n?.width!==void 0&&n.height!==void 0;return{...n!==void 0&&rn(e,"url")?{url:n.url}:{},...o&&rn(e,"width")?{width:n.width}:{},...o&&rn(e,"height")?{height:n.height}:{},...ed({document:t,includes:s=>rn(e,s)}),...r===void 0?{}:{properties:r},...t.excerpt===void 0||Hh(e)===!1?{}:{excerpt:t.excerpt},...t.metadataError===void 0||e.includeMetadata===!1?{}:{metadataError:t.metadataError}}},Ks=t=>{let e=Ce(fe(t));if(e>k.resultBytes)throw new we("Asset query result exceeds the byte limit",{code:"CONTENT_LIMIT_EXCEEDED",details:{resultBytes:e,resultByteLimit:k.resultBytes}})},uo=(t,e,n)=>{t[e]={status:"rejected",reason:n}},ty=({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=Vh({query:a,catalog:e}).query}catch(l){uo(n,i,l);continue}for(let l of ur(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}},id=({preparedQueries:t,results:e,createReason:n})=>{for(let{index:r}of t)uo(e,r,n())},Vs=t=>t.map(e=>{if(e===void 0)throw new Error("Asset query result was not settled");return e}),ny=({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(Kh({document:i,content:d.content})===!1||Jh({document:i,where:d.where,runtimeAsset:a,filterKeys:n,filterResults:c})===!1)continue;let l=ey(i,d.output,a);if(d.content.mode==="none"&&Object.keys(l).length===0&&d.output.mode!=="all"&&rn(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){uo(o,u.index,l)}}}for(let i of r.values())i.sorted=[...i.documents].sort((a,c)=>Yh({left:a,right:c,sort:i.sort,runtimeAssets:s}))},ry=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 Qn(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 we("Asset content reader is unavailable");let y=await Xf({result:d,documents:d,options:p,read:n,assetReferences:r,assetUrls:r===void 0?void 0:o});l=d.map((m,h)=>{let g=y.content[m._id];if(g===void 0)throw new we("Selected asset content could not be read");return{...l[h],content:{encoding:g.encoding,text:g.text,...g.range===void 0?{}:{range:g.range}}}})}let f=c==="many"?{items:l,totalCount:a.length,hasMore:i.offset+u.length<a.length}:{item:l[0]??null,totalCount:a.length};Ks(f),e[s.index]={status:"fulfilled",value:f}}catch(a){uo(e,s.index,a)}}))},ad=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}=ty({inputs:t,catalog:e,results:a});if(n.length>k.candidateDocuments)return id({preparedQueries:u,results:a,createReason:()=>new we("Asset query document limit was exceeded",{code:"CONTENT_LIMIT_EXCEEDED",details:{documentCount:n.length,documentLimit:k.candidateDocuments}})}),Vs(a);let l;try{l=n.map(p=>mt({value:p,references:i?.[p._id],runtimeAssets:o??{}}))}catch(p){return id({preparedQueries:u,results:a,createReason:()=>p}),Vs(a)}ny({preparedQueries:u,documents:l,filterKeys:c,sortGroups:d,results:a,runtimeAssets:o});let f=kf(o);return await ry({preparedQueries:u,results:a,read:r,assetReferences:s,assetUrls:f}),Vs(a)};var oy=async t=>await tl(fe(st.parse(t)));var sy=({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}},iy=t=>ss.parse({items:t.rows.map(e=>{let n={};for(let[r,o]of t.fields.entries())sy({item:n,field:o,value:e[r]});return n}),totalCount:t.totalCount,hasMore:t.hasMore}),cd=async({queries:t,query:e,assetValueReferences:n,runtimeAssets:r={}})=>{if(t===void 0)return;let o=t[await oy(st.parse(e))];if(o===void 0)return;let s=iy(o),i={...s,items:s.items.map(a=>mt({value:a,references:n?.[a.id],runtimeAssets:r}))};return Ks(i),i};var ay=(t,e)=>e===void 0?zt(t):{async*[Symbol.asyncIterator](){let n=0,r=0;for await(let o of zt(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}}},cy=({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=Yt({node:c,source:n(c)??await e(c,{signal:o})});return{data:ay(u.source,a),...a===void 0?{}:{contentLength:a.length}}}},uy=({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 on},c=w=>async(A,D)=>{let E=t.contents?.[A];if(E===void 0){let G=w??s;if(G===void 0)throw new Error("Content is not embedded in this database");return await G(A,D)}let C=rt(E),P=D===void 0?C:C.slice(D.offset,D.offset+D.length);return{data:async function*(){yield P}(),contentLength:P.byteLength}},u=w=>{if(w.status==="rejected")throw w.reason;return w.value},d=async({requests:w,queryContentReader:A,runtimeAssets:D,documents:E=t.documents})=>await ad({queries:w.map(({query:C})=>C),catalog:n,documents:E,read:c(A),runtimeAssets:D,assetReferences:t.assetReferences,assetValueReferences:t.assetValueReferences}),l=async({request:w,...A})=>u((await d({...A,requests:[w]}))[0]),f=async({requests:w,queryContentReader:A,runtimeAssets:D})=>{let E=Array.from({length:w.length}),C=[];for(let[P,G]of w.entries()){try{a(G);let L=await cd({queries:t.queries,query:G.query,assetValueReferences:t.assetValueReferences,runtimeAssets:D});if(L!==void 0){E[P]={status:"fulfilled",value:L};continue}}catch(L){E[P]={status:"rejected",reason:L};continue}C.push(P)}if(C.length>0){let P=await d({requests:C.map(G=>w[G]),queryContentReader:A,runtimeAssets:D});for(let[G,L]of C.entries())E[L]=P[G]}return E.map(P=>{if(P===void 0)throw new Error("Content database query was not settled");return P})},p=async(w,A,D)=>u((await f({requests:[w],queryContentReader:A,runtimeAssets:D}))[0]),y=async(...w)=>await p(...w),m=w=>async(A,D)=>{let E=o?.get(A.id);return E!==void 0?{format:"json",revision:A.revision,source:JSON.stringify(E.properties)}:await w(A,D)},h=({graph:w,query:A,runtimeAssets:D})=>qf({graph:w,query:A}).filter(E=>{let C=i.get(E),P=C===void 0?void 0:mt({value:C,references:t.assetValueReferences?.[E],runtimeAssets:D??{}});return P===void 0?!1:$t(A.where,G=>{if(!Gf({graph:w,sourceId:E,field:G.field}))return Js(P,G,D?.[E])})!==!1}),g=({rootIds:w,roots:A})=>{let D=new Map(w.flatMap((E,C)=>{let P=oo(A[C]);return P===void 0?[]:[[E,P]]}));return t.documents.map(E=>{let C=D.get(E._id);return C===void 0?E:rs.parse({...E,properties:C})})},x=async({request:w,graph:A,resolutionSession:D,contentReader:E,runtimeAssets:C,onEvent:P})=>{a(w);let G=st.parse(w.query),L=h({graph:A,query:G,runtimeAssets:C});if(L.length===0)return await p(w,E,C);let gt=Jf({graph:A,query:G,rootIds:L});ae(P,{type:"roots-selected",rootCount:L.length});let lo=await D.resolve({graph:gt,rootIds:L,onEvent:P,allowUnresolvedReferences:!0,transformDocument:({node:hd,document:yd})=>Fs({document:yd,references:t.assetValueReferences?.[hd.id],runtimeAssets:C})}),fo=g({rootIds:L,roots:lo.roots});return await l({request:w,queryContentReader:E,runtimeAssets:C,documents:fo})},S=async({requests:w,load:A,resolutionSession:D,readContent:E,runtimeAssets:C,signal:P,onEvent:G})=>{if(r===void 0)return await f({requests:w,queryContentReader:E,runtimeAssets:C});let L=m(A),gt=D??Bf({load:L,concurrency:k.concurrentContentReads,signal:P}),lo=cy({graph:r,load:L,getCached:gt.getCached,readFallback:E??s,signal:P});return await Promise.allSettled(w.map(fo=>x({request:fo,graph:r,resolutionSession:gt,contentReader:lo,runtimeAssets:C,onEvent:G})))};return{query:y,queryManyWithDocumentGraph:S,queryWithDocumentGraph:async({request:w,...A})=>u((await S({...A,requests:[w]}))[0])}};var Ws=({artifact:t,readContent:e})=>{let n=Kf({artifact:t});return uy({artifact:t,revision:t.revision,documentGraph:n?.graph,inlineDocuments:n?.inlineDocuments,readContent:e})};var sn=class extends Error{constructor(e,n){super(e,n),this.name="AssetQueryRequestError"}},Vn=class extends Error{},ly=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 Vn("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 Vn("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},ud=async t=>{let e;try{e=await ly(t,k.requestBytes)}catch(n){throw n instanceof Vn?new sn("Asset query request exceeds the byte limit",{cause:n}):n}try{return wl.parse(JSON.parse(le(e)))}catch(n){throw new sn("Asset query request is invalid",{cause:n})}};var ld=t=>{if(!(t instanceof sn))return;let e=t.message,n=new Set,r=t.cause;for(;r instanceof Error&&n.has(r)===!1;){if(r instanceof Eu)return{code:"INVALID_REQUEST",message:t.message,retryable:!1,status:400,details:{issues:r.issues.map(o=>({code:o.code,path:o.path.map(String),message:o.message}))}};e=r.message,n.add(r),r=r.cause}return{code:"INVALID_REQUEST",message:e,retryable:!1,status:400}},fd=t=>{if(t instanceof on)return{code:"STALE_INDEX",message:t.message,retryable:!1,status:409};if(t instanceof Qn)return{code:t.code,message:t.message,retryable:!1,details:{matchedCount:t.matchedCount},status:409};if(t instanceof we){let r={...t.details,...t.issues===void 0?{}:{issues:t.issues.map(o=>({...o,path:[...o.path]}))}};return{code:t.code,message:t.message,retryable:!1,...Object.keys(r).length===0?{}:{details:r},status:400}}if(t instanceof X)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 vt){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 Un)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 fy="/$resources/assets",dd=(t,e=200)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json; charset=utf-8"}}),an=({code:t,message:e,status:n,retryable:r=!1,details:o})=>dd(El({code:t,message:e,retryable:r,details:o}),n),dy=(t,e,n)=>typeof t=="string"||t instanceof URL?new Request(new URL(t,e),n):new Request(t,n),py=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"})},dR=({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,fetchDocument:s=globalThis.fetch,onDocumentGraphEvent:i})=>{pd({artifact:e,runtimeAssets:n});let a=js();return md({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,database:Ws({artifact:e}),fetchDocument:s,documentCache:a,onDocumentGraphEvent:i})},my=({baseUrl:t,runtimeAssets:e,embeddedContents:n,fetchDocument:r,cache:o,onEvent:s})=>{let i=Nf({fetch:r,getRequest:a=>{let c=e[a.id];if(c===void 0)throw new Error(`Published document URL is unavailable for ${a.id}`);return new URL(c.url,t)},getMetadata:({node:a})=>({format:a.format,revision:a.revision}),onEvent:s});return Ff({cache:o,onEvent:s,load:async(a,c)=>{let u=a.format,d=u===void 0?void 0:n?.[a.contentRef];return d!==void 0&&u!==void 0?{format:u,revision:a.revision,source:rt(d)}:await i(a,c)}})},pd=({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}`)},md=({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=my({baseUrl:o,runtimeAssets:n,embeddedContents:e.contents,fetchDocument:i,cache:a,onEvent:c});return async(l,f)=>{let p=dy(l,o,f),y=new URL(p.url);if(y.origin!==u||y.pathname!==fy||p.method.toUpperCase()!=="POST")return;let m;try{m=await ud(p.clone())}catch(g){let x=ld(g);return an(x!==void 0?x:{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 py({deploymentId:t,artifact:e,request:p});if(h!==void 0&&r!==void 0){let g=await r.match(h).catch(()=>{});if(g!==void 0)return new Response(g.body,g)}try{if(p.signal.aborted)return an({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let g=dd(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&&(g.headers.set("cache-control",p.headers.get("cache-control")),await r.put(h,g.clone()).catch(()=>{})),g}catch(g){if(p.signal.aborted)return an({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let x=fd(g);return an(x!==void 0?x:{code:"INTERNAL_ERROR",message:"Published asset query failed",status:500,retryable:!0})}}},pR=({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)};pd({artifact:e,runtimeAssets:n});let c=Ws({artifact:e}),u=js();return async({request:d,fallback:l})=>{let f=new URL(d.url).origin,p=md({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{pR as createGeneratedAssetResourceRuntime,dR 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=to(e),r=Yt(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=to(e),r=Yt(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 Rh(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new vt||null,prettyErrors:e}}function js(t,e={}){let{lineCounter:n,prettyErrors:r}=Rh(e),o=new Un(n?.addNewLine),s=new Bn(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 Ie(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(i.errors.forEach(Is(t,n)),i.warnings.forEach(Is(t,n))),i}var Ce=class extends Error{code;constructor(e){super(`Structured data failed validation: ${e}`),this.name="StructuredDataError",this.code=e}},Sf=t=>Ne(JSON.stringify(t)),xf=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},Af=(t,e)=>{if(xf(t)===!1)throw new Ce("INVALID");let n=0,r=(s,i)=>{if(i>e.depth)throw new Ce("DEPTH_EXCEEDED");if(typeof s=="string"){if(Ne(s)>e.stringBytes)throw new Ce("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 Ce("FIELDS_EXCEEDED");return r(a,i+1)});if(xf(s)){let a=Object.create(null);for(let[c,u]of Object.entries(s)){if(n+=1,n>e.fields)throw new Ce("FIELDS_EXCEEDED");a[c]=r(u,i+1)}return a}throw new Ce("INVALID")},o=r(t,1);if(Sf(o)>e.serializedBytes)throw new Ce("SERIALIZED_BYTES_EXCEEDED");return o};var Y=class extends Error{code;line;column;constructor(e,n,r,o){super(n,{cause:o}),this.name="MarkdownMetadataError",this.code=e,this.line=r?.line,this.column=r?.column}};var Xt=new Uint8Array([239,187,191]),vf=Xt.byteLength+10,Oh=(t,e,n=0)=>t.byteLength-n<e.byteLength?!1:e.every((r,o)=>t[n+o]===r),Qn=(t,e)=>{let n=0;if(Oh(t,Xt))n=Xt.byteLength;else if(t.byteLength<Xt.byteLength&&Xt.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 Ch={bytes:k.frontmatterBytes,depth:k.frontmatterDepth,fields:k.frontmatterFields,stringBytes:k.frontmatterStringBytes,serializedBytes:k.indexedPropertiesBytes},Df=t=>{try{return le(t)}catch{throw new Y("FRONTMATTER_DECODING_FAILED","Markdown frontmatter is not valid UTF-8")}},Th=t=>t.code==="DEPTH_EXCEEDED"?new Y("FRONTMATTER_DEPTH_EXCEEDED","Markdown frontmatter exceeds the nesting limit"):t.code==="FIELDS_EXCEEDED"?new Y("FRONTMATTER_FIELDS_EXCEEDED","Markdown frontmatter exceeds the field limit"):t.code==="STRING_BYTES_EXCEEDED"?new Y("FRONTMATTER_STRING_BYTES_EXCEEDED","Markdown frontmatter contains a string that exceeds the byte limit"):t.code==="SERIALIZED_BYTES_EXCEEDED"?new Y("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter properties exceed the indexed byte limit"):new Y("FRONTMATTER_INVALID","Markdown frontmatter must contain a JSON-compatible object"),Rf=(t,e)=>{let n=new vt,r=js(t,{schema:"core",uniqueKeys:!0,lineCounter:n});if(r.errors.length>0){let s=r.errors[0],i=n.linePos(s.pos[0]);throw new Y("FRONTMATTER_INVALID",`Markdown frontmatter contains invalid YAML: ${s.message}`,{line:i.line+1,column:i.col},s)}let o;try{o=r.toJS({maxAliasCount:0})}catch{throw new Y("FRONTMATTER_INVALID","Markdown frontmatter contains unsupported YAML aliases")}if(o===null)return{};try{return Af(o,e)}catch(s){throw s instanceof Ce?Th(s):s}};var kf=async(t,e={})=>{let n={...Ch,...e},r=n.bytes+vf,o=new Uint8Array(r),s=0;for await(let c of Pt(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),g=Qn(p,!1);if(g===null)return{properties:{},frontmatterBytes:0,consumedBytes:p.length};if(g!==void 0){let m=g.yamlEnd-g.yamlStart;if(m>n.bytes)throw new Y("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter exceeds the byte limit");let h=Df(p.subarray(g.yamlStart,g.yamlEnd));return{properties:Rf(h,n),frontmatterBytes:m,consumedBytes:g.blockEnd}}}if(s>=r)break}let i=o.subarray(0,s),a=Qn(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=Df(i.subarray(a.yamlStart,a.yamlEnd));return{properties:Rf(u,n),frontmatterBytes:c,consumedBytes:a.blockEnd}}}throw new Y("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter is not closed within the byte limit")};var ro=async(t,e=k.hydratedFileBytes)=>{if(Number.isInteger(e)===!1||e<=0||e>k.hydratedFileBytes)throw new Y("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 se?new Y("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown content exceeds the byte limit"):a}let r;try{r=le(n)}catch{throw new Y("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}let s=Qn(n,!0)?.blockEnd??0,i;try{i=s===0?Lt(r):le(n.subarray(s))}catch{throw new Y("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}return{body:i,bodyBytes:Ne(i),sourceBytes:n.byteLength}};var mt=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}},Nh=O({source:v(),body:v(),frontmatter:Ae(v(),rt())}),so=t=>{let e;try{e=Nh.parse(t)}catch(n){throw new mt({code:"INVALID_DOCUMENT",message:"Markdown document is invalid",cause:n})}return Object.freeze({source:e.source,body:e.body,frontmatter:st(e.frontmatter)})},oo="#frontmatter",$h=t=>`${oo}${t.slice(1)}`,zh=t=>{if(t!==oo&&t.startsWith(`${oo}/`)===!1)throw new mt({code:"UNUSED_REFERENCE",message:`Resolved Markdown reference ${t} is outside frontmatter`,referenceId:t});return`#${t.slice(oo.length)}`},Ph=t=>{let e=t.referenceId===void 0?void 0:$h(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 mt({code:n,message:t.message,referenceId:e,cause:t})},If=async({source:t,maximumBytes:e=k.hydratedFileBytes})=>{let n;try{n=await $e(t,e)}catch(i){throw i instanceof se?new mt({code:"CONTENT_LIMIT_EXCEEDED",message:"Markdown document exceeds the byte limit",cause:i}):i}let r;try{r=Lt(le(n))}catch(i){throw new mt({code:"CONTENT_DECODING_FAILED",message:"Markdown document is not valid UTF-8",cause:i})}let[o,s]=await Promise.all([ro(n,e),kf(n).catch(i=>{if(i instanceof Y)return{properties:{},frontmatterBytes:0,consumedBytes:0};throw i})]);return so({source:r,body:o.body,frontmatter:s.properties})};var Of=({document:t,references:e,allowUnresolvedReferences:n=!1})=>{let r=so(t),o=new Map;for(let[i,a]of e)o.set(zh(i),a);let s;try{s=Er({document:r.frontmatter,references:o,allowUnresolvedReferences:n})}catch(i){throw i instanceof de&&Ph(i),i}return so({...r,frontmatter:s})},Cf=({document:t,representation:e})=>{let n=so(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 mt({code:"UNSUPPORTED_REPRESENTATION",message:`Markdown documents do not support ${e.type}`})};var Tf=t=>{let e=encodeURIComponent(t);return e==="."?"%2E":e===".."?"%2E%2E":e};var Nf=t=>t.split("/").map(e=>{try{return Tf(decodeURIComponent(e))}catch{return Tf(e)}}).join("/");var $f=t=>Object.fromEntries(Object.entries(t??{}).map(([e,n])=>[e,n.url]));var io=(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}`},Us=({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]=Us({value:t[r],path:o,replacement:n}),s}return typeof r!="string"?t:{...t,[r]:Us({value:t[r],path:o,replacement:n})}},Lh=({reference:t,runtimeAsset:e})=>{let{url:n,contentRef:r,...o}=e;return{...o,id:t.assetId,src:io(n,t.suffix)}},ht=({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=Us({value:o,path:s.path,replacement:s.structured===!0?Lh({reference:s,runtimeAsset:a}):io(a.url,s.suffix)}))}return o};var co=t=>{let e=t.format==="json"?t.value:t.value.frontmatter;return Zt(e)?e:void 0},Qs=({document:t,references:e,runtimeAssets:n})=>{let r=co(t);if(r===void 0||e===void 0)return t;let o=ht({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})})},ao=t=>Object.freeze(t),zf=async({format:t,source:e,maximumBytes:n=k.hydratedFileBytes})=>ao(t==="json"?{format:t,value:await Ol({source:e,maximumBytes:n})}:{format:t,value:await If({source:e,maximumBytes:n})});var Pf=({document:t,references:e,allowUnresolvedReferences:n})=>t.format==="json"?ao({format:t.format,value:Er({document:t.value,references:e,allowUnresolvedReferences:n})}):ao({format:t.format,value:Of({document:t.value,references:e,allowUnresolvedReferences:n})}),Lf=({document:t,representation:e})=>t.format==="json"?Cl({document:t.value,representation:e}):Cf({document:t.value,representation:e});var uo=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}},Ht=({node:t,source:e})=>{if(e.revision!==t.revision)throw new uo({code:"REVISION_MISMATCH",documentId:t.id,expectedRevision:t.revision,actualRevision:e.revision});if(t.format!==void 0&&e.format!==t.format)throw new uo({code:"FORMAT_MISMATCH",documentId:t.id,expectedFormat:t.format,actualFormat:e.format});return e};var en=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"},ae=(t,e)=>{try{t?.(e)}catch{}},Mf=({load:t,onEvent:e})=>async(n,r)=>{let o={documentId:n.id,revision:n.revision};ae(e,{type:"document-fetch-started",...o});try{let s=await t(n,r);return ae(e,{type:"document-fetch-completed",...o}),s}catch(s){throw ae(e,{type:"document-fetch-failed",...o,errorCode:en(s)}),s}};var Mh=O({format:ee(Sn),revision:v().min(1)}),tn=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}},Ff=({fetch:t,getRequest:e,getMetadata:n,onEvent:r})=>Mf({load:async(s,{signal:i})=>{let a;try{a=await t(e(s),{signal:i})}catch(d){throw new tn({code:"REQUEST_FAILED",message:`Document ${s.id} request failed`,documentId:s.id,cause:d})}if(a.ok===!1)throw new tn({code:"HTTP_STATUS",message:`Document ${s.id} request returned status ${a.status}`,documentId:s.id,status:a.status});let c;try{c=Mh.parse(n({node:s,response:a}))}catch(d){throw new tn({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 tn({code:"BODY_MISSING",message:`Document ${s.id} response body is unavailable`,documentId:s.id});return Object.freeze({...c,source:ol(u)})},onEvent:r});var nn=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Bf=new Set,Vs=typeof process=="object"&&process?process:{},jf=(t,e,n,r)=>{typeof Vs.emitWarning=="function"?Vs.emitWarning(t,e,n,r):console.error(`[${n}] ${e}: ${t}`)},lo=globalThis.AbortController,Zf=globalThis.AbortSignal;if(typeof lo>"u"){Zf=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},lo=class{constructor(){e()}signal=new Zf;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=Vs.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,jf("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 Fh=t=>!Bf.has(t),Pv=Symbol("type"),yt=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Uf=t=>yt(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?rn:null:null,rn=class extends Array{constructor(e){super(e),this.fill(0)}},Gs=class t{heap;length;static#c=!1;static create(e){let n=Uf(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]}},on=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;#E;#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.#x(n),rindexes:n=>e.#S(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:g=0,sizeCalculation:m,fetchMethod:h,memoMethod:y,noDeleteOnFetchRejection:E,noDeleteOnStaleGet:S,allowStaleOnFetchRejection:_,allowStaleOnFetchAbort:w,ignoreFetchAbort:A}=e;if(n!==0&&!yt(n))throw new TypeError("max option must be a nonnegative integer");let D=n?Uf(n):Array;if(!D)throw new Error("invalid max value: "+n);if(this.#c=n,this.#f=p,this.maxEntrySize=g||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(y!==void 0&&typeof y!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#C=y,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=Gs.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.#E=!!this.#h,this.#l=!!this.#y,this.noDisposeOnSet=!!l,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!E,this.allowStaleOnFetchRejection=!!_,this.allowStaleOnFetchAbort=!!w,this.ignoreFetchAbort=!!A,this.maxEntrySize!==0){if(this.#f!==0&&!yt(this.#f))throw new TypeError("maxSize must be a positive integer if specified");if(!yt(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#B()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!S,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!a,this.ttlResolution=yt(o)||o===0?o:1,this.ttlAutopurge=!!s,this.ttl=r||0,this.ttl){if(!yt(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";Fh(x)&&(Bf.add(x),jf("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 rn(this.#c),n=new rn(this.#c);this.#p=e,this.#_=n,this.#P=(s,i,a=nn.now())=>{if(n[s]=i!==0?a:0,e[s]=i,i!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#m(s)&&this.#A(this.#n[s],"expire")},i+1);c.unref&&c.unref()}},this.#R=s=>{n[s]=e[s]!==0?nn.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=nn.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 rn(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(!yt(o))if(s){if(typeof s!="function")throw new TypeError("sizeCalculation must be a function");if(o=s(r,n),!yt(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.#T=(n,r,o)=>{if(e[n]=r,this.#f){let s=this.#f-e[n];for(;this.#g>s;)this.#N(!0)}this.#g+=e[n],o&&(o.entrySize=r,o.totalCalculatedSize=this.#g)}}#k=e=>{};#T=(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};*#x({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]}*#S({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.#x())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.#S())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.#x()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*rkeys(){for(let e of this.#S()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*values(){for(let e of this.#x())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#S())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.#x()){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.#x()){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.#S()){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.#S({allowStale:!0}))this.#m(n)&&(this.#A(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-(nn.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.#x({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=nn.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=nn.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.#A(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.#N(!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.#T(l,d,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:p}=f;p!==void 0&&!i&&(this.#E&&this.#h?.(p,e,"set"),this.#l&&this.#i?.push([p,e,"set"]))}else i||(this.#E&&this.#h?.(f,e,"set"),this.#l&&this.#i?.push([f,e,"set"]));if(this.#k(l),this.#T(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.#N(!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)}}}#N(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.#E||this.#l)&&(this.#E&&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 lo,{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:y}=i.signal,E=r.ignoreFetchAbort&&m!==void 0;if(r.status&&(y&&!h?(r.status.fetchAborted=!0,r.status.fetchError=i.signal.reason,E&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),y&&!E&&!h)return l(i.signal.reason);let S=p;return this.#e[n]===p&&(m===void 0?S.__staleWhileFetching?this.#e[n]=S.__staleWhileFetching:this.#A(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,y=h&&r.allowStaleOnFetchAbort,E=y||r.allowStaleOnFetchRejection,S=E||r.noDeleteOnFetchRejection,_=p;if(this.#e[n]===p&&(!S||_.__staleWhileFetching===void 0?this.#A(e,"fetch"):y||(this.#e[n]=_.__staleWhileFetching)),E)return r.status&&_.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),_.__staleWhileFetching;if(_.__returned===_)throw m},f=(m,h)=>{let y=this.#O?.(e,s,c);y&&y instanceof Promise&&y.then(E=>m(E===void 0?void 0:E),h),i.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(m(void 0),r.allowStaleOnFetchAbort&&(m=E=>u(E,!0)))})};r.status&&(r.status.fetchDispatched=!0);let p=new Promise(f).then(u,d),g=Object.assign(p,{__abortController:i,__staleWhileFetching:s,__returned:void 0});return n===void 0?(this.set(e,g,{...c.options,status:void 0}),n=this.#r.get(e)):this.#e[n]=g,g}#t(e){if(!this.#D)return!1;let n=e;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof lo}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:g=this.allowStaleOnFetchAbort,context:m,forceRefresh:h=!1,status:y,signal:E}=n;if(!this.#D)return y&&(y.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,status:y});let S={allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,ttl:i,noDisposeOnSet:a,size:c,sizeCalculation:u,noUpdateTTL:d,noDeleteOnFetchRejection:l,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:g,ignoreFetchAbort:p,status:y,signal:E},_=this.#r.get(e);if(_===void 0){y&&(y.fetch="miss");let w=this.#$(e,_,S,m);return w.__returned=w}else{let w=this.#e[_];if(this.#t(w)){let P=r&&w.__staleWhileFetching!==void 0;return y&&(y.fetch="inflight",P&&(y.returnedStale=!0)),P?w.__staleWhileFetching:w.__returned=w}let A=this.#m(_);if(!h&&!A)return y&&(y.fetch="hit"),this.#I(_),o&&this.#R(_),y&&this.#v(y,_),w;let D=this.#$(e,_,S,m),C=D.__staleWhileFetching!==void 0&&r;return y&&(y.fetch=A?"stale":"refresh",C&&A&&(y.returnedStale=!0)),C?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.#A(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.#A(e,"delete")}#A(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.#E||this.#l)&&(this.#E&&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.#S({allowStale:!0})){let r=this.#e[n];if(this.#t(r))r.__abortController.abort(new Error("deleted"));else{let o=this.#n[n];this.#E&&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 qs=({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 on({maxSize:t,sizeCalculation:e=>Math.max(1,e.bytes.byteLength)})},Vn=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}},fo=({contentRef:t,revision:e,format:n})=>fe([t,e,n??null]),Zh=t=>{if(typeof t!="object"||t===null)return!1;let e=t;return ul(e.format)&&typeof e.revision=="string"&&e.revision.length>0&&e.bytes instanceof Uint8Array},Qf=t=>Object.freeze({format:t.format,revision:t.revision,source:t.bytes}),Vf=({load:t,cache:e,maximumBytes:n=k.hydratedFileBytes,onEvent:r})=>{let o=new Map;return async(s,i)=>{let a=fo(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){ae(r,{type:"document-cache-read-failed",documentId:s.id,revision:s.revision,errorCode:en(m)})}if(Zh(l)&&l.revision===s.revision&&l.bytes.byteLength<=n&&(s.format===void 0||l.format===s.format))return ae(r,{type:"document-cache-hit",documentId:s.id,revision:s.revision}),Qf(l);ae(r,{type:"document-cache-miss",documentId:s.id,revision:s.revision});let f=Ht({node:s,source:await t(s,i)}),p;try{p=await $e(f.source,n)}catch(m){throw m instanceof se?new Vn({message:`Document ${s.id} exceeds the cache byte limit`,documentId:s.id,contentByteLimit:n,cause:m}):m}let g=Object.freeze({format:f.format,revision:f.revision,bytes:p});try{await e.set(a,g),ae(r,{type:"document-cache-stored",documentId:s.id,revision:s.revision})}catch(m){ae(r,{type:"document-cache-write-failed",documentId:s.id,revision:s.revision,errorCode:en(m)})}return Qf(g)})();c.set(i.signal,d);try{return await d}finally{c.delete(i.signal),c.size===0&&o.delete(a)}}};var me=class extends Error{code;resourceIds;constructor({code:e,message:n,resourceIds:r=[],cause:o}){super(n,{cause:o}),this.name="ResourceResolutionError",this.code=e,this.resourceIds=Object.freeze([...r])}},Gn=t=>{if(t?.aborted)throw new me({code:"REQUEST_CANCELLED",message:"Resource resolution was cancelled",cause:t.reason})},Bh=({resourcesById:t,rootIds:e})=>{let n=new Map,r=[],o=[],s=(i,a)=>{let c=t.get(i);if(c===void 0)throw new me({code:a===void 0?"ROOT_NOT_FOUND":"DEPENDENCY_NOT_FOUND",message:a===void 0?`Resource graph root ${i} does not exist`:`Resource ${a} dependency ${i} does not exist`,resourceIds:a===void 0?[i]:[a,i]});let u=n.get(i);if(u!=="visited"){if(u==="visiting"){let d=r.indexOf(i),l=[...r.slice(d),i];throw new me({code:"CYCLE",message:`Resource graph contains a cycle: ${l.join(" -> ")}`,resourceIds:l})}n.set(i,"visiting"),r.push(i);for(let d of c.dependencies)s(d,c.id);r.pop(),n.set(i,"visited"),o.push(c)}};for(let i of new Set(e))s(i);return o},Gf=async({resources:t,rootIds:e,concurrency:n,signal:r})=>{if(Number.isSafeInteger(n)===!1||n<=0)throw new TypeError("Resource resolution concurrency must be positive");Gn(r);let o=new Map;for(let l of t){if(o.has(l.id))throw new me({code:"DUPLICATE_RESOURCE",message:`Resource graph contains duplicate resource ${l.id}`,resourceIds:[l.id]});o.set(l.id,l)}let s=Bh({resourcesById:o,rootIds:e}),i=wr({concurrency:n,signal:r}),a=new Map,c=new Map,u=l=>{let f=c.get(l);if(f!==void 0)return f;let p=o.get(l),g=(async()=>{let m=new Map,h;try{h=await Promise.all(p.dependencies.map(u))}catch(y){throw y instanceof me&&y.code==="RESOLUTION_FAILED"?new me({code:y.code,message:`Resource dependency path ${[p.id,...y.resourceIds].join(" -> ")} could not be resolved`,resourceIds:[p.id,...y.resourceIds],cause:y.cause}):y}for(let[y,E]of p.dependencies.entries())m.set(E,h[y]);Gn(r);try{return await i(async()=>{Gn(r);let y=await Ft(p.resolve({documents:m,signal:r}),r);return Gn(r),y})}catch(y){throw r?.aborted&&Gn(r),y instanceof me?y:new me({code:"RESOLUTION_FAILED",message:`Resource ${p.id} could not be resolved`,resourceIds:[p.id],cause:y})}})();return c.set(l,g),g},d=await Promise.all(e.map(u));for(let l of s){let f=await c.get(l.id);a.set(l.id,f)}return Object.freeze({roots:Object.freeze(d),documents:a})};var _e=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}},po=t=>{if(t?.aborted)throw new _e({code:"REQUEST_CANCELLED",message:"Document graph resolution was cancelled",cause:t.reason})},qf=async({graph:t,rootIds:e,concurrency:n,signal:r,load:o,select:s,assemble:i})=>{po(r);let a=hr({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 g=d.get(p.contentRef);g===void 0?d.set(p.contentRef,{representative:p,nodes:[p]}):g.nodes.push(p)}await br([...d.values()],n,async p=>{po(r);let g=p.representative;try{let m=await Ft(o(g,{signal:r}),r);for(let h of p.nodes)u.set(h.id,m)}catch(m){throw r?.aborted&&po(r),new _e({code:"DOCUMENT_LOAD_FAILED",message:`Document ${g.id} could not be loaded`,documentId:g.id,cause:m})}});let l=Mt(t.edges),f=a.map(p=>({id:p.id,dependencies:(l.get(p.id)??[]).map(g=>g.reference.documentId),resolve:async({documents:g})=>{po(r);let m=new Map;for(let y of l.get(p.id)??[]){let E=c.get(y.reference.documentId);if(E===void 0||g.has(y.reference.documentId)===!1)throw new _e({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${p.id} dependency ${y.reference.documentId} is unavailable`,documentId:p.id,referenceId:y.referenceId});let S=g.get(y.reference.documentId),_;if(s===void 0){if(y.reference.representation.type!=="document")throw new _e({code:"REPRESENTATION_SELECTOR_REQUIRED",message:`Document ${p.id} reference ${y.referenceId} requires a representation selector`,documentId:p.id,referenceId:y.referenceId});_=S}else try{_=await s({reference:y.reference,value:S,sourceNode:p,targetNode:E})}catch(w){throw new _e({code:"DOCUMENT_SELECTION_FAILED",message:`Document ${p.id} reference ${y.referenceId} could not be selected`,documentId:p.id,referenceId:y.referenceId,cause:w})}m.set(y.referenceId,_)}if(u.has(p.id)===!1)throw new _e({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${p.id} source is unavailable`,documentId:p.id});let h=u.get(p.id);try{return await i({node:p,source:h,references:m})}catch(y){throw y instanceof _e?y:new _e({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${p.id} could not be assembled`,documentId:p.id,cause:y})}}}));try{let p=await Gf({resources:f,rootIds:e,concurrency:1,signal:r});return Object.freeze({roots:p.roots,values:p.documents})}catch(p){throw p instanceof me&&p.cause instanceof _e?p.cause:p instanceof me&&p.code==="REQUEST_CANCELLED"?new _e({code:"REQUEST_CANCELLED",message:"Document graph resolution was cancelled",cause:p.cause}):p}};var Dt=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}},jh=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:d})=>{let l=hr({graph:t,rootIds:e}).length,f={rootCount:e.length,documentCount:l};ae(a,{type:"resolution-started",...f});try{if(l>s)throw new Dt({code:"DOCUMENT_COUNT_EXCEEDED",message:"Document graph resolution exceeds the document limit",documentCount:l,documentLimit:s});let p=0,g=Promise.resolve(),m=await qf({graph:t,rootIds:e,concurrency:n,signal:i,load:async(h,y)=>{let E=g,S=()=>{};g=new Promise(w=>{S=w});let _;try{_={status:"fulfilled",value:await d(h,y)}}catch(w){_={status:"rejected",reason:w}}await E;try{if(_.status==="rejected")throw _.reason;if(_.value.byteLength>r)throw new Dt({code:"CONTENT_LIMIT_EXCEEDED",message:`Document ${h.id} exceeds the byte limit`,documentId:h.id,contentByteLimit:r,cause:new se});let w=p+_.value.byteLength;if(w>o)throw new Dt({code:"TOTAL_BYTES_EXCEEDED",message:"Document graph resolution exceeds the total byte limit",documentId:h.id,totalBytes:w,totalByteLimit:o});return p=w,await _.value.parse()}finally{S()}},select:({reference:h,value:y})=>Lf({document:y,representation:h.representation}),assemble:({node:h,source:y,references:E})=>{let S=Pf({document:y,references:E,allowUnresolvedReferences:c});return u?.({node:h,document:S})??S}});return ae(a,{type:"resolution-completed",...f}),m}catch(p){throw ae(a,{type:"resolution-failed",...f,errorCode:en(p)}),p}},Jf=({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 on({maxSize:o,sizeCalculation:({byteLength:f})=>Math.max(1,f)}),i=new Map,a=wr({concurrency:e,signal: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(),await Ft(f,n)),d=async(f,p)=>{c(p.signal);let g=fo(f),m=s.get(g);if(m!==void 0)return m;let h=i.get(g);if(h!==void 0)return await u(h);let y=a(async()=>{c(p.signal);let E=Ht({node:f,source:await t(f,{signal:n})});c(p.signal);let S=await ns(E.source,r+1);c(p.signal);let _,w=Object.freeze({format:E.format,revision:E.revision,bytes:S,byteLength:S.byteLength,parse:()=>(_??=zf({format:E.format,source:S,maximumBytes:r}),_)});return w.byteLength<=o&&s.set(g,w),w});i.set(g,y);try{return await u(y)}finally{i.delete(g)}};return Object.freeze({getCached:f=>{c();let p=s.get(fo(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 jh({...f,concurrency:e,maximumBytes:r,signal:n,load:d})})};var Kf=t=>{if(t.output.mode==="all")return"all";let e=[];for(let{field:n}of dr(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},Wf=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",...kl(e)]}catch{return}},Yf=(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},Xf=({queryPaths:t,referenceId:e})=>{let n=Wf(e);return n!==void 0&&(t==="all"||t.some(r=>Yf(r,n)))},Hf=({graph:t,sourceId:e,field:n})=>n[0]!=="properties"?!1:t.edges.some(r=>{if(r.sourceId!==e)return!1;let o=Wf(r.referenceId);return o!==void 0&&Yf(n,o)}),ed=({graph:t,query:e})=>{let n=Kf(e),r=new Set;for(let o of t.edges)Xf({queryPaths:n,referenceId:o.referenceId})&&r.add(o.sourceId);return[...r]},td=({graph:t,query:e,rootIds:n})=>{let r=Kf(e),o=new Set(n),s=new Map(t.nodes.map(l=>[l.id,l])),i=Mt(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)&&Xf({queryPaths:r,referenceId:l.referenceId})&&(c.add(l),d(l.reference.documentId));return An({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 nd=({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:An({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 rd=({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=io(i,s.suffix);o=`${o.slice(0,s.start)}${a}${o.slice(s.end)}`}return o};var X=class extends Error{code;details;constructor({code:e,message:n,details:r}){super(n),this.name="AssetResourceHydrationError",this.code=e,this.details=r}},Uh=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 X({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 X({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())},Qh=t=>typeof t.mimeType=="string"&&(t.mimeType.startsWith("text/")||["application/json","application/javascript","application/xml","image/svg+xml"].includes(t.mimeType)),Vh=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 se?new X({code:"CONTENT_LIMIT_EXCEEDED",message:"Asset storage returned more content than requested"}):s}},Gh=t=>{try{return le(t)}catch{throw new X({code:"CONTENT_DECODING_FAILED",message:"Selected asset content is not valid UTF-8"})}},qh=(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 X({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},od=t=>{let e=t.flatMap(({reason:s,document:i})=>{if(typeof i.path!="string")return[];let a=s instanceof X?s.code:"CONTENT_READ_FAILED",c=s instanceof Error&&s.message!==""?s.message:"Selected asset content could not be read";return[{severity:"error",scope:"query",phase:"source",code:a,message:c,assetId:i._id,path:i.path}]});if(e.length!==t.length)throw t[0].reason;if(t.length===1){let s=t[0].reason,i=e[0];throw i===void 0?s:new X({code:s instanceof X?s.code:"INVALID_REQUEST",message:i.message,details:{...s instanceof X?s.details:{},diagnostics:e}})}let n=new Set(e.map(({code:s})=>s)),r=e[0]?.code,o=n.size===1&&(r==="CONTENT_IDENTITY_REQUIRED"||r==="CONTENT_NOT_TEXT"||r==="CONTENT_DECODING_FAILED"||r==="CONTENT_LIMIT_EXCEEDED")?r:"INVALID_REQUEST";throw new X({code:o,message:`${e.length} selected asset content errors found`,details:{diagnostics:e}})},sd=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=Uh(t);if(i.length>k.hydratedFileCount)throw new X({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(m=>[m._id,m])),c=i.map(m=>{let h=a.get(m._id);try{if(h===void 0||h.revision!==m.revision||h.contentRef!==m.contentRef||typeof h.size!="number"||typeof h.mimeType!="string")throw new X({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset content identity is stale or unavailable",details:{assetId:m._id}});let y={...h,size:h.size,mimeType:h.mimeType};if(Qh(y)===!1)throw new X({code:"CONTENT_NOT_TEXT",message:"Selected binary asset cannot be embedded as text",details:{assetId:m._id,mimeType:y.mimeType}});return{status:"fulfilled",value:{identity:m,document:y,readLength:qh(y,n)}}}catch(y){return{status:"rejected",reason:y,document:h??{_id:m._id}}}}),u=c.flatMap(m=>m.status==="rejected"?[m]:[]);u.length>0&&od(u);let d=c.flatMap(m=>m.status==="fulfilled"?[m.value]:[]),l=d.reduce((m,h)=>m+h.readLength,0);if(l>k.hydratedTotalBytes)throw new X({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected assets exceed the total hydrated-content limit",details:{totalReadBytes:l,totalByteLimit:k.hydratedTotalBytes}});let f=await br(d,k.concurrentContentReads,async m=>{try{let h=n.mode==="range"?{offset:n.offset,length:m.readLength}:m.readLength===0?void 0:{offset:0,length:m.readLength},y=await Vh({read:r,contentRef:m.identity.contentRef,range:h,maximumBytes:m.readLength});if(y.byteLength!==m.readLength)throw new X({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset bytes do not match canonical metadata",details:{assetId:m.identity._id}});let E;if(n.mode==="markdown-body-ref")try{E=(await ro(y,m.readLength||1)).body;let _=o?.[m.identity.contentRef];_!==void 0&&s!==void 0&&(E=rd({markdown:E,references:_,assetUrls:s}))}catch{throw new X({code:"CONTENT_DECODING_FAILED",message:"Selected Markdown body could not be decoded",details:{assetId:m.identity._id}})}else E=Gh(y);let S=Ne(E);return{status:"fulfilled",value:{id:m.identity._id,returnedBytes:S,content:{...m.identity,encoding:"utf-8",text:E,...n.mode==="range"?{range:{offset:n.offset,length:y.byteLength,total:m.document.size}}:{}}}}}catch(h){return{status:"rejected",reason:h,document:m.document}}}),p=f.flatMap(m=>m.status==="rejected"?[m]:[]);p.length>0&&od(p);let g=f.flatMap(m=>m.status==="fulfilled"?[m.value]:[]);return{content:Object.fromEntries(g.map(({id:m,content:h})=>[m,h])),hydratedFileCount:d.length,hydratedBytes:g.reduce((m,{returnedBytes:h})=>m+h,0)}};var DD=v().datetime({offset:!0}).transform(t=>new Date(t).toISOString());var Jh=/^[A-Za-z_][A-Za-z0-9_]*$/,id=(t,e)=>Jh.test(e)?`${t}.${e}`:`${t}[${JSON.stringify(e)}]`;var ad=({document:t,includes:e})=>{let n={};for(let r of _l){let o=t[r];o!==void 0&&e(r)&&(n[r]=o)}return n},gt=Symbol("missing property selection"),Js=(t,e)=>{if(e.some(r=>r.length===0)||typeof _r(t)=="string")return t;if(Array.isArray(t)){let r=e.filter(([s])=>s==="*").map(s=>s.slice(1));if(r.length===0)return gt;let o=t.map(s=>Js(s,r));return o.some(s=>s!==gt)?o.map(s=>s===gt?null:s):gt}if(typeof t!="object"||t===null)return gt;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=Js(o,s);i!==gt&&(n[r]=i)}return Object.keys(n).length===0?gt:n},cd=({properties:t,fields:e})=>{let n=e.filter(([o])=>o==="properties").map(o=>o.slice(1)),r=Js(t,n);return r===gt?{}:r};var Ee=class extends Error{code;issues;details;constructor(e,n){super(e,n),this.name="AssetQueryExecutionError",this.code=n?.code??"INVALID_REQUEST",this.issues=n?.issues,this.details=n?.details}},qn=class extends Ee{code="MULTIPLE_RESULTS";matchedCount;constructor(e){super(`Expected at most one asset, but the query matched ${e}.`),this.matchedCount=e,this.name="AssetQueryMultipleResultsError"}},an=class extends Error{constructor(){super("The requested asset index revision is stale"),this.name="AssetIndexRevisionError"}},Ks=t=>{if(t[0]!=="properties")return t[0];let e="properties";for(let n of t.slice(1))e=id(e,n);return e},ud=({filter:t,fieldTypes:e})=>Sl(e).includes(t.operator),ld=(t,e)=>t!==void 0&&Object.hasOwn(t.fields,e)?t.fields[e]:void 0,Kh=t=>{if(t===null)return"null";if(Array.isArray(t))return"array";if(typeof t=="object")return"object";if(typeof t=="boolean")return"boolean";if(typeof t=="number")return"number";if(typeof t=="string")return"string"},Wh=({operator:t,fieldTypes:e})=>{if(!(t==="contains"&&e.includes("array"))){if(t==="startsWith"||t==="endsWith"||t==="contains")return["string"];if(t==="gt"||t==="gte"||t==="lt"||t==="lte")return e.filter(n=>n==="string"||n==="number");if(t==="eq"||t==="ne"||t==="in")return e}},fd=({filter:t,fieldTypes:e,path:n})=>{let r=Wh({operator:t.operator,fieldTypes:e});return r===void 0?[]:(t.operator==="in"?t.value:[t.value]).flatMap((s,i)=>r.some(a=>a===Kh(s))?[]:[t.operator==="in"?[...n,"value",String(i)]:[...n,"value"]])},Ys=(t,e=["query","where"])=>"field"in t?[{filter:t,path:e}]:"all"in t?t.all.flatMap((n,r)=>Ys(n,[...e,"all",String(r)])):t.any.flatMap((n,r)=>Ys(n,[...e,"any",String(r)])),Yh=({query:t,catalog:e})=>{let n=it.safeParse(t);if(n.success===!1)return{success:!1,issues:n.error.issues.map(u=>({severity:"error",code:u.code,path:["query",...u.path.map(String)],message:u.message}))};let r=n.data,o=new Map,s=[],i=[],a=(u,d,l)=>{s.push(l),i.push({severity:"warning",code:u,path:d,message:l})};for(let{filter:u,path:d}of Ys(r.where)){let l=Ks(u.field);if(o.set(l,u.field),u.field[0]==="properties"){let f=ld(e,l);if(e!==void 0&&f===void 0)a("UNOBSERVED_FIELD",[...d,"field"],`Asset field ${l} is not currently observed`);else if(f!==void 0&&ud({filter:u,fieldTypes:f.types})===!1)a("INCOMPATIBLE_OBSERVED_TYPES",[...d,"operator"],`Operator ${u.operator} is not compatible with the currently observed types of ${l}`);else if(f!==void 0)for(let p of fd({filter:u,fieldTypes:f.types,path:d}))a("INCOMPATIBLE_OBSERVED_VALUE",p,`Filter value is not compatible with the currently observed types of ${l}`)}else{let f=cs[u.field[0]];if(ud({filter:u,fieldTypes:f})===!1)i.push({severity:"error",code:"INCOMPATIBLE_OPERATOR",path:[...d,"operator"],message:`Operator ${u.operator} is incompatible with ${l}`});else for(let p of fd({filter:u,fieldTypes:f,path:d}))i.push({severity:"error",code:"INCOMPATIBLE_VALUE",path:p,message:`Filter value is incompatible with ${l}`})}}for(let[u,d]of r.sort.entries()){let l=Ks(d.field);if(o.set(l,d.field),d.field[0]==="properties"){let f=ld(e,l);e!==void 0&&f===void 0?a("UNOBSERVED_FIELD",["query","sort",String(u),"field"],`Asset field ${l} is not currently observed`):f!==void 0&&f.types.some(p=>p==="object"||p==="array")&&a("STRUCTURED_SORT_ORDER",["query","sort",String(u),"field"],`Asset field ${l} currently includes structured values that use deterministic JSON sort order`)}}if(r.output.mode==="fields")for(let u of r.output.fields){let d=Ks(u);o.set(d,u)}let c=[...new Map(i.map(u=>[JSON.stringify([u.code,u.path,u.message]),u])).values()];return{success:c.some(({severity:u})=>u==="error")===!1,query:r,referencedFieldPaths:[...o.values()],warnings:[...new Set(s)],issues:c}},Xh=({query:t,catalog:e})=>{let n=Yh({query:t,catalog:e});if(n.success===!1){let r=n.issues.filter(({severity:o})=>o==="error");throw new Ee(r.length===1?r[0].message:`${r.length} invalid query operations found`,{issues:n.issues})}return{query:n.query,referencedFieldPaths:n.referencedFieldPaths,warnings:n.warnings,warningIssues:n.issues}},Xs=(t,e,n)=>{let r=e[0]==="id"?t._id:gr(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},Hh=t=>typeof t=="string"||Array.isArray(t)?t.length===0:typeof t=="object"&&t!==null&&Object.keys(t).length===0,ey=(t,e)=>{if(typeof t=="number"&&typeof e=="number")return t-e;if(typeof t=="string"&&typeof e=="string")return ze(t,e)},dd=(t,e)=>{if(t.field.length!==1||t.field[0]!=="path"||typeof e!="string")return[e];let n=Nf(e);return n===e?[e]:[e,n]},Hs=(t,e,n)=>{let r=Xs(t,e.field,n);if(e.operator==="exists")return r!=null===e.value;if(e.operator==="isEmpty")return Hh(r)===e.value;let o=dd(e,e.value);if(e.operator==="eq")return o.some(i=>xn(r,i));if(e.operator==="ne")return o.every(i=>xn(r,i)===!1);if(e.operator==="in")return e.value.some(i=>dd(e,i).some(a=>xn(r,a)));if(e.operator==="contains")return typeof r=="string"?o.some(i=>typeof i=="string"&&r.includes(i)):Array.isArray(r)&&r.some(i=>xn(i,e.value));if(e.operator==="startsWith")return typeof r=="string"&&o.some(i=>typeof i=="string"&&r.startsWith(i));if(e.operator==="endsWith")return typeof r=="string"&&o.some(i=>typeof i=="string"&&r.endsWith(i));let s=ey(r,o[o.length-1]);return s===void 0?!1:e.operator==="gt"?s>0:e.operator==="gte"?s>=0:e.operator==="lt"?s<0:s<=0},ty=({document:t,where:e,runtimeAsset:n,filterKeys:r,filterResults:o})=>zt(e,s=>{let i=r.get(s)??fe(s),a=o.get(i);if(a!==void 0)return a;let c=Hs(t,s,n);return o.set(i,c),c})===!0,ny=({document:t,content:e})=>{if(e.mode!=="markdown-body-ref")return!0;let n=t.mimeType===void 0?void 0:ll(t.mimeType);return n==="markdown"||n==="mdx"?!0:t.extension==="md"||t.extension==="mdx"},ry=(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")?ze(String(t),String(e)):ze(fe(t),fe(e))},oy=({left:t,right:e,sort:n,runtimeAssets:r})=>{for(let o of n){let s=ry(Xs(t,o.field,r?.[t._id]),Xs(e,o.field,r?.[e._id]));if(s!==0)return o.direction==="asc"?s:-s}return ze(t._id,e._id)};var sy=(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=cd({properties:t.properties,fields:e.fields});return Object.keys(n).length===0?void 0:n},sn=(t,e)=>t.includeMetadata&&El(e)||t.mode==="fields"&&t.fields.some(n=>n.length===1&&n[0]===e),iy=t=>t.mode==="all"||t.mode==="fields"&&t.fields.some(e=>e.length===1&&e[0]==="excerpt"),ay=(t,e,n)=>{if(sn(e,"url")&&n===void 0)throw new Ee(`Asset URL is unavailable for ${t._id}`,{details:{assetId:t._id}});let r=sy(t,e),o=n?.width!==void 0&&n.height!==void 0;return{...n!==void 0&&sn(e,"url")?{url:n.url}:{},...o&&sn(e,"width")?{width:n.width}:{},...o&&sn(e,"height")?{height:n.height}:{},...ad({document:t,includes:s=>sn(e,s)}),...r===void 0?{}:{properties:r},...t.excerpt===void 0||iy(e)===!1?{}:{excerpt:t.excerpt},...t.metadataError===void 0||e.includeMetadata===!1?{}:{metadataError:t.metadataError}}},ei=t=>{let e=Ne(fe(t));if(e>k.resultBytes)throw new Ee("Asset query result exceeds the byte limit",{code:"CONTENT_LIMIT_EXCEEDED",details:{resultBytes:e,resultByteLimit:k.resultBytes}})},mo=(t,e,n)=>{t[e]={status:"rejected",reason:n}},cy=({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=Xh({query:a,catalog:e}).query}catch(l){mo(n,i,l);continue}for(let l of dr(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}},pd=({preparedQueries:t,results:e,createReason:n})=>{for(let{index:r}of t)mo(e,r,n())},Ws=t=>t.map(e=>{if(e===void 0)throw new Error("Asset query result was not settled");return e}),uy=({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(ny({document:i,content:d.content})===!1||ty({document:i,where:d.where,runtimeAsset:a,filterKeys:n,filterResults:c})===!1)continue;let l=ay(i,d.output,a);if(d.content.mode==="none"&&Object.keys(l).length===0&&d.output.mode!=="all"&&sn(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){mo(o,u.index,l)}}}for(let i of r.values())i.sorted=[...i.documents].sort((a,c)=>oy({left:a,right:c,sort:i.sort,runtimeAssets:s}))},ly=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 g=s.matches.get(p);return g===void 0?[]:[g]}),c=i.result??"many";if(c==="one"&&a.length>1)throw new qn(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 Ee("Asset content reader is unavailable");let g=await sd({result:d,documents:d,options:p,read:n,assetReferences:r,assetUrls:r===void 0?void 0:o});l=d.map((m,h)=>{let y=g.content[m._id];if(y===void 0)throw new Ee("Selected asset content could not be read");return{...l[h],content:{encoding:y.encoding,text:y.text,...y.range===void 0?{}:{range:y.range}}}})}let f=c==="many"?{items:l,totalCount:a.length,hasMore:i.offset+u.length<a.length}:{item:l[0]??null,totalCount:a.length};ei(f),e[s.index]={status:"fulfilled",value:f}}catch(a){mo(e,s.index,a)}}))},md=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}=cy({inputs:t,catalog:e,results:a});if(n.length>k.candidateDocuments)return pd({preparedQueries:u,results:a,createReason:()=>new Ee("Asset query document limit was exceeded",{code:"CONTENT_LIMIT_EXCEEDED",details:{documentCount:n.length,documentLimit:k.candidateDocuments}})}),Ws(a);let l;try{l=n.map(p=>ht({value:p,references:i?.[p._id],runtimeAssets:o??{}}))}catch(p){return pd({preparedQueries:u,results:a,createReason:()=>p}),Ws(a)}uy({preparedQueries:u,documents:l,filterKeys:c,sortGroups:d,results:a,runtimeAssets:o});let f=$f(o);return await ly({preparedQueries:u,results:a,read:r,assetReferences:s,assetUrls:f}),Ws(a)};var fy=async t=>await il(fe(it.parse(t)));var dy=({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}},py=t=>us.parse({items:t.rows.map(e=>{let n={};for(let[r,o]of t.fields.entries())dy({item:n,field:o,value:e[r]});return n}),totalCount:t.totalCount,hasMore:t.hasMore}),hd=async({queries:t,query:e,assetValueReferences:n,runtimeAssets:r={}})=>{if(t===void 0)return;let o=t[await fy(it.parse(e))];if(o===void 0)return;let s=py(o),i={...s,items:s.items.map(a=>ht({value:a,references:n?.[a.id],runtimeAssets:r}))};return ei(i),i};var my=(t,e)=>e===void 0?Pt(t):{async*[Symbol.asyncIterator](){let n=0,r=0;for await(let o of Pt(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}}},hy=({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=Ht({node:c,source:n(c)??await e(c,{signal:o})});return{data:my(u.source,a),...a===void 0?{}:{contentLength:a.length}}}},yy=({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 an},c=w=>async(A,D)=>{let x=t.contents?.[A];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(A,D)}let C=ot(x),P=D===void 0?C:C.slice(D.offset,D.offset+D.length);return{data:async function*(){yield P}(),contentLength:P.byteLength}},u=w=>{if(w.status==="rejected")throw w.reason;return w.value},d=async({requests:w,queryContentReader:A,runtimeAssets:D,documents:x=t.documents})=>await md({queries:w.map(({query:C})=>C),catalog:n,documents:x,read:c(A),runtimeAssets:D,assetReferences:t.assetReferences,assetValueReferences:t.assetValueReferences}),l=async({request:w,...A})=>u((await d({...A,requests:[w]}))[0]),f=async({requests:w,queryContentReader:A,runtimeAssets:D})=>{let x=Array.from({length:w.length}),C=[];for(let[P,G]of w.entries()){try{a(G);let L=await hd({queries:t.queries,query:G.query,assetValueReferences:t.assetValueReferences,runtimeAssets:D});if(L!==void 0){x[P]={status:"fulfilled",value:L};continue}}catch(L){x[P]={status:"rejected",reason:L};continue}C.push(P)}if(C.length>0){let P=await d({requests:C.map(G=>w[G]),queryContentReader:A,runtimeAssets:D});for(let[G,L]of C.entries())x[L]=P[G]}return x.map(P=>{if(P===void 0)throw new Error("Content database query was not settled");return P})},p=async(w,A,D)=>u((await f({requests:[w],queryContentReader:A,runtimeAssets:D}))[0]),g=async(...w)=>await p(...w),m=w=>async(A,D)=>{let x=o?.get(A.id);return x!==void 0?{format:"json",revision:A.revision,source:JSON.stringify(x.properties)}:await w(A,D)},h=({graph:w,query:A,runtimeAssets:D})=>ed({graph:w,query:A}).filter(x=>{let C=i.get(x),P=C===void 0?void 0:ht({value:C,references:t.assetValueReferences?.[x],runtimeAssets:D??{}});return P===void 0?!1:zt(A.where,G=>{if(!Hf({graph:w,sourceId:x,field:G.field}))return Hs(P,G,D?.[x])})!==!1}),y=({rootIds:w,roots:A})=>{let D=new Map(w.flatMap((x,C)=>{let P=co(A[C]);return P===void 0?[]:[[x,P]]}));return t.documents.map(x=>{let C=D.get(x._id);return C===void 0?x:as.parse({...x,properties:C})})},E=async({request:w,graph:A,resolutionSession:D,contentReader:x,runtimeAssets:C,onEvent:P})=>{a(w);let G=it.parse(w.query),L=h({graph:A,query:G,runtimeAssets:C});if(L.length===0)return await p(w,x,C);let bt=td({graph:A,query:G,rootIds:L});ae(P,{type:"roots-selected",rootCount:L.length});let ho=await D.resolve({graph:bt,rootIds:L,onEvent:P,allowUnresolvedReferences:!0,transformDocument:({node:xd,document:Sd})=>Qs({document:Sd,references:t.assetValueReferences?.[xd.id],runtimeAssets:C})}),yo=y({rootIds:L,roots:ho.roots});return await l({request:w,queryContentReader:x,runtimeAssets:C,documents:yo})},S=async({requests:w,load:A,resolutionSession:D,readContent:x,runtimeAssets:C,signal:P,onEvent:G})=>{if(r===void 0)return await f({requests:w,queryContentReader:x,runtimeAssets:C});let L=m(A),bt=D??Jf({load:L,concurrency:k.concurrentContentReads,signal:P}),ho=hy({graph:r,load:L,getCached:bt.getCached,readFallback:x??s,signal:P});return await Promise.allSettled(w.map(yo=>E({request:yo,graph:r,resolutionSession:bt,contentReader:ho,runtimeAssets:C,onEvent:G})))};return{query:g,queryManyWithDocumentGraph:S,queryWithDocumentGraph:async({request:w,...A})=>u((await S({...A,requests:[w]}))[0])}};var ti=({artifact:t,readContent:e})=>{let n=nd({artifact:t});return yy({artifact:t,revision:t.revision,documentGraph:n?.graph,inlineDocuments:n?.inlineDocuments,readContent:e})};var cn=class extends Error{constructor(e,n){super(e,n),this.name="AssetQueryRequestError"}},Jn=class extends Error{},gy=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 Jn("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 Jn("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},yd=async t=>{let e;try{e=await gy(t,k.requestBytes)}catch(n){throw n instanceof Jn?new cn("Asset query request exceeds the byte limit",{cause:n}):n}try{return Al.parse(JSON.parse(le(e)))}catch(n){throw new cn("Asset query request is invalid",{cause:n})}};var gd=t=>{if(!(t instanceof cn))return;let e=t.message,n=new Set,r=t.cause;for(;r instanceof Error&&n.has(r)===!1;){if(r instanceof Ru)return{code:"INVALID_REQUEST",message:t.message,retryable:!1,status:400,details:{issues:r.issues.map(o=>({code:o.code,path:o.path.map(String),message:o.message}))}};e=r.message,n.add(r),r=r.cause}return{code:"INVALID_REQUEST",message:e,retryable:!1,status:400}},bd=t=>{if(t instanceof an)return{code:"STALE_INDEX",message:t.message,retryable:!1,status:409};if(t instanceof qn)return{code:t.code,message:t.message,retryable:!1,details:{matchedCount:t.matchedCount},status:409};if(t instanceof Ee){let r={...t.details,...t.issues===void 0?{}:{issues:t.issues.map(o=>({...o,path:[...o.path]}))}};return{code:t.code,message:t.message,retryable:!1,...Object.keys(r).length===0?{}:{details:r},status:400}}if(t instanceof X)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 Dt){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 Vn)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 by="/$resources/assets",wd=(t,e=200)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json; charset=utf-8"}}),un=({code:t,message:e,status:n,retryable:r=!1,details:o})=>wd(Rl({code:t,message:e,retryable:r,details:o}),n),wy=(t,e,n)=>typeof t=="string"||t instanceof URL?new Request(new URL(t,e),n):new Request(t,n),_y=async({deploymentId:t,artifact:e,request:n})=>{let r=await n.clone().text(),o=n.headers.get("cache-control"),s=await os(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"})},SR=({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,fetchDocument:s=globalThis.fetch,onDocumentGraphEvent:i})=>{_d({artifact:e,runtimeAssets:n});let a=qs();return Ed({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,database:ti({artifact:e}),fetchDocument:s,documentCache:a,onDocumentGraphEvent:i})},Ey=({baseUrl:t,runtimeAssets:e,embeddedContents:n,fetchDocument:r,cache:o,onEvent:s})=>{let i=Ff({fetch:r,getRequest:a=>{let c=e[a.id];if(c===void 0)throw new Error(`Published document URL is unavailable for ${a.id}`);return new URL(c.url,t)},getMetadata:({node:a})=>({format:a.format,revision:a.revision}),onEvent:s});return Vf({cache:o,onEvent:s,load:async(a,c)=>{let u=a.format,d=u===void 0?void 0:n?.[a.contentRef];return d!==void 0&&u!==void 0?{format:u,revision:a.revision,source:ot(d)}:await i(a,c)}})},_d=({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}`)},Ed=({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=Ey({baseUrl:o,runtimeAssets:n,embeddedContents:e.contents,fetchDocument:i,cache:a,onEvent:c});return async(l,f)=>{let p=wy(l,o,f),g=new URL(p.url);if(g.origin!==u||g.pathname!==by||p.method.toUpperCase()!=="POST")return;let m;try{m=await yd(p.clone())}catch(y){let E=gd(y);return un(E!==void 0?E:{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 _y({deploymentId:t,artifact:e,request:p});if(h!==void 0&&r!==void 0){let y=await r.match(h).catch(()=>{});if(y!==void 0)return new Response(y.body,y)}try{if(p.signal.aborted)return un({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let y=wd(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&&(y.headers.set("cache-control",p.headers.get("cache-control")),await r.put(h,y.clone()).catch(()=>{})),y}catch(y){if(p.signal.aborted)return un({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let E=bd(y);return un(E!==void 0?E:{code:"INTERNAL_ERROR",message:"Published asset query failed",status:500,retryable:!0})}}},AR=({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)};_d({artifact:e,runtimeAssets:n});let c=ti({artifact:e}),u=qs();return async({request:d,fallback:l})=>{let f=new URL(d.url).origin,p=Ed({deploymentId:t,artifact:e,runtimeAssets:n,cache:a,baseUrl:f,database:c,fetchDocument:l,documentCache:u,onDocumentGraphEvent:r});return async(g,m)=>await p(g,m)??l(g,m)}};export{AR as createGeneratedAssetResourceRuntime,SR 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.tsx
index 59e808545c..6e96e87093 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,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 324b645289..0bc579460f 100644
--- a/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsx
@@ -4,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 3cec61be47..0399a65ed0 100644
--- a/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx
@@ -4,18 +4,20 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const assets_1: ResourceRequest = {
- name: "assets",
- control: "system",
- url: "/$resources/assets",
- searchParams: [
- ],
- method: "post",
- headers: [
- { name: "Content-Type", value: "application/json" },
- ],
- body: {
+ const assets_1 = (documents: ReadonlyMap<string, unknown>): ResourceRequest => {
+ return {
+ name: "assets",
+ control: "system",
+ url: "/$resources/assets",
+ searchParams: [
+ ],
+ method: "post",
+ headers: [
+ { name: "Content-Type", value: "application/json" },
+ ],
+ body: {
query: ({
output: {
mode: "fields",
@@ -34,12 +36,18 @@ export const getResources = (_props: { system: System; resources?: Record<string
offset: 0,
}),
},
+ }
+ }
+ const _data: ResourceRequestGraph = {
+ resources: [
+ { id: "oIYuHoIwG7GM5J9cCSsai", outputName: "assets_1", dependencies: [], createRequest: assets_1 },
+ ],
+ rootIds: [
+ "oIYuHoIwG7GM5J9cCSsai",
+ ],
}
- const _data = new Map<string, ResourceRequest>([
- ["assets_1", assets_1],
- ])
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 324b645289..0bc579460f 100644
--- a/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsx
@@ -4,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 324b645289..0bc579460f 100644
--- a/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsx
@@ -4,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 8ccd45a432..11b6af2243 100644
--- a/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsx
@@ -4,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index d2f7281338..0a87fd66d5 100644
--- a/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx
@@ -4,21 +4,29 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const jsonResourceVariable_1: ResourceRequest = {
- name: "jsonResourceVariable",
- url: "https://httpbin.org/get?hello=world",
- searchParams: [
+ const jsonResourceVariable_1 = (documents: ReadonlyMap<string, unknown>): ResourceRequest => {
+ return {
+ name: "jsonResourceVariable",
+ url: "https://httpbin.org/get?hello=world",
+ searchParams: [
+ ],
+ method: "get",
+ headers: [
+ ],
+ }
+ }
+ const _data: ResourceRequestGraph = {
+ resources: [
+ { id: "fjMzCru8O2U31xY2P1Ovr", outputName: "jsonResourceVariable_1", dependencies: [], createRequest: jsonResourceVariable_1 },
],
- method: "get",
- headers: [
+ rootIds: [
+ "fjMzCru8O2U31xY2P1Ovr",
],
}
- const _data = new Map<string, ResourceRequest>([
- ["jsonResourceVariable_1", jsonResourceVariable_1],
- ])
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 8ab770bac1..d1eefa9929 100644
--- a/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx
@@ -4,22 +4,30 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const action: ResourceRequest = {
- name: "action",
- url: "/custom",
- searchParams: [
+ const action = (documents: ReadonlyMap<string, unknown>): ResourceRequest => {
+ return {
+ name: "action",
+ url: "/custom",
+ searchParams: [
+ ],
+ method: "get",
+ headers: [
+ { name: "Content-Type", value: "application/json" },
+ ],
+ }
+ }
+ const _data: ResourceRequestGraph = {
+ resources: [
+ { id: "isNSM3wXcnHFikwNPlEOL", outputName: "action", dependencies: [], createRequest: action },
],
- method: "get",
- headers: [
- { name: "Content-Type", value: "application/json" },
+ rootIds: [
],
}
- const _data = new Map<string, ResourceRequest>([
- ])
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
- ["action", action],
+ const _action = new Map<string, { id: string; outputName: string }>([
+ ["action", { id: "isNSM3wXcnHFikwNPlEOL", outputName: "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.tsx
index 324b645289..0bc579460f 100644
--- a/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsx
@@ -4,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 8bfd9038ef..8de563335d 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,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index a9d43cecfa..21d3998516 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,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index e2d727acc8..d88577e3cd 100644
--- a/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsx
@@ -4,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 05d6e3c411..b3ddec534e 100644
--- a/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx
@@ -4,21 +4,29 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
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",
- searchParams: [
+ const list_1 = (documents: ReadonlyMap<string, unknown>): ResourceRequest => {
+ return {
+ name: "list",
+ url: "https://gist.githubusercontent.com/TrySound/56507c301ec85669db5f1541406a9259/raw/a49548730ab592c86b9e7781f5b29beec4765494/collection.json",
+ searchParams: [
+ ],
+ method: "get",
+ headers: [
+ ],
+ }
+ }
+ const _data: ResourceRequestGraph = {
+ resources: [
+ { id: "1vX6SQdaCjJN6MvJlG_cQ", outputName: "list_1", dependencies: [], createRequest: list_1 },
],
- method: "get",
- headers: [
+ rootIds: [
+ "1vX6SQdaCjJN6MvJlG_cQ",
],
}
- const _data = new Map<string, ResourceRequest>([
- ["list_1", list_1],
- ])
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 324b645289..0bc579460f 100644
--- a/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsx
@@ -4,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 8ccd45a432..11b6af2243 100644
--- a/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsx
@@ -4,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index 09e9e94c2e..4ce2f586aa 100644
--- a/fixtures/webstudio-features/app/__generated__/_index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/_index.server.tsx
@@ -4,11 +4,16 @@
import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
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.tsx
index b5e950efc7..1fb6546d37 100644
--- a/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/fixtures/webstudio-features/app/routes/[animations]._index.tsx b/fixtures/webstudio-features/app/routes/[animations]._index.tsx
index 9641e3a34e..ecc1bccd1f 100644
--- a/fixtures/webstudio-features/app/routes/[animations]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[animations]._index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/fixtures/webstudio-features/app/routes/[assets1]._index.tsx b/fixtures/webstudio-features/app/routes/[assets1]._index.tsx
index 93f42d008a..8e99c349bc 100644
--- a/fixtures/webstudio-features/app/routes/[assets1]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[assets1]._index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/fixtures/webstudio-features/app/routes/[class-names]._index.tsx b/fixtures/webstudio-features/app/routes/[class-names]._index.tsx
index 95bb5689a2..7f2aa62cd4 100644
--- a/fixtures/webstudio-features/app/routes/[class-names]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[class-names]._index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/fixtures/webstudio-features/app/routes/[content-block]._index.tsx b/fixtures/webstudio-features/app/routes/[content-block]._index.tsx
index 381e5d90e9..1ff50feb37 100644
--- a/fixtures/webstudio-features/app/routes/[content-block]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[content-block]._index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/fixtures/webstudio-features/app/routes/[duration]._index.tsx b/fixtures/webstudio-features/app/routes/[duration]._index.tsx
index c2ad4c7062..909a6572e8 100644
--- a/fixtures/webstudio-features/app/routes/[duration]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[duration]._index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/fixtures/webstudio-features/app/routes/[expressions]._index.tsx b/fixtures/webstudio-features/app/routes/[expressions]._index.tsx
index f7d84ace21..226e775b15 100644
--- a/fixtures/webstudio-features/app/routes/[expressions]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[expressions]._index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/fixtures/webstudio-features/app/routes/[form]._index.tsx b/fixtures/webstudio-features/app/routes/[form]._index.tsx
index e31ac374bc..5c49542397 100644
--- a/fixtures/webstudio-features/app/routes/[form]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[form]._index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx b/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx
index 470c672ce1..ccc195cfb3 100644
--- a/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx b/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx
index d0cc06a97c..e1855271c6 100644
--- a/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx b/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx
index 2b8ef1f132..602132621b 100644
--- a/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/fixtures/webstudio-features/app/routes/[radix]._index.tsx b/fixtures/webstudio-features/app/routes/[radix]._index.tsx
index afeacaf5c0..1f41b92a9a 100644
--- a/fixtures/webstudio-features/app/routes/[radix]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[radix]._index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/fixtures/webstudio-features/app/routes/[resources]._index.tsx b/fixtures/webstudio-features/app/routes/[resources]._index.tsx
index f2bbcf969c..6ce7f5c574 100644
--- a/fixtures/webstudio-features/app/routes/[resources]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[resources]._index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx b/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx
index 07745f4f33..53d35450d4 100644
--- a/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/fixtures/webstudio-features/app/routes/_index.tsx b/fixtures/webstudio-features/app/routes/_index.tsx
index 051857b2cd..34b4765781 100644
--- a/fixtures/webstudio-features/app/routes/_index.tsx
+++ b/fixtures/webstudio-features/app/routes/_index.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/packages/cli/src/prebuild.test.ts b/packages/cli/src/prebuild.test.ts
index d5c71f99d7..b3c30bd0fe 100644
--- a/packages/cli/src/prebuild.test.ts
+++ b/packages/cli/src/prebuild.test.ts
@@ -38,10 +38,12 @@ import { createPublishedAssetResourceFetch } from "@webstudio-is/content-engine/
import {
createStructuredAssetQueryResourceBody,
encodeDataSourceVariable,
+ encodeDataVariableId,
SYSTEM_VARIABLE_ID,
type Resource,
} from "@webstudio-is/sdk";
import { showAttribute } from "@webstudio-is/react-sdk";
+import { formBotFieldName, formIdFieldName } from "@webstudio-is/sdk/runtime";
import {
generateRedirectsModule,
getAssetResourcePrerenderPaths,
@@ -415,6 +417,7 @@ afterEach(async () => {
consoleInfo.mockRestore();
process.chdir(originalCwd);
globalThis.fetch = originalFetch;
+ vi.unstubAllGlobals();
await rm(tempDir, { recursive: true, force: true });
vi.restoreAllMocks();
});
@@ -2625,6 +2628,125 @@ sitemap.map((page) => page.path);`
);
});
+ test.each(["defaults", "react-router"])(
+ "submits identical forms twice while caching dependencies (%s)",
+ async (template) => {
+ const siteData = createSiteData({
+ instances: [["root", { id: "root", component: "Form", children: [] }]],
+ props: [
+ [
+ "action",
+ {
+ id: "action",
+ instanceId: "root",
+ name: "action",
+ type: "resource",
+ value: "submit",
+ },
+ ],
+ ],
+ });
+ siteData.build.dataSources = [
+ [
+ "author",
+ {
+ id: "author",
+ name: "Author",
+ type: "resource",
+ resourceId: "author",
+ scopeInstanceId: "root",
+ },
+ ],
+ ] as never;
+ siteData.build.resources = [
+ [
+ "author",
+ {
+ id: "author",
+ name: "Author",
+ method: "post",
+ url: '"https://example.com/author"',
+ body: '{ query: "author" }',
+ headers: [{ name: "Cache-Control", value: '"public, max-age=60"' }],
+ },
+ ],
+ [
+ "submit",
+ {
+ id: "submit",
+ name: "Submit",
+ method: "post",
+ url: `"https://example.com/submit/" + ${encodeDataSourceVariable("author")}.data.id`,
+ headers: [{ name: "Cache-Control", value: '"public, max-age=60"' }],
+ },
+ ],
+ ] as never;
+ await writeSiteData(siteData);
+ await prebuild({ assets: false, template: [template] });
+ await symlink(join(originalCwd, "node_modules"), "node_modules", "dir");
+ await build({
+ stdin: {
+ contents: 'export { action } from "./app/routes/_index"',
+ resolveDir: tempDir,
+ },
+ outfile: join(tempDir, "action.mjs"),
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ packages: "external",
+ loader: { ".css": "text" },
+ });
+ const { action } = await import(
+ pathToFileURL(join(tempDir, "action.mjs")).href
+ );
+ const cached = new Map<string, Response>();
+ vi.stubGlobal("caches", {
+ open: async () => ({
+ match: async (key: URL) => cached.get(key.href)?.clone(),
+ put: async (key: URL, response: Response) => {
+ cached.set(key.href, response.clone());
+ },
+ }),
+ });
+ const received: Array<{ url: string; body: unknown }> = [];
+ vi.stubGlobal(
+ "fetch",
+ async (input: RequestInfo | URL, init?: RequestInit) => {
+ const request = new Request(input, init);
+ received.push({ url: request.url, body: await request.json() });
+ return Response.json({ id: "author-123" });
+ }
+ );
+ for (let index = 0; index < 2; index += 1) {
+ const form = new FormData();
+ form.set(formIdFieldName, "action");
+ form.set(formBotFieldName, "brave");
+ form.set("message", "Hello");
+ await expect(
+ action({
+ request: new Request("https://example.com/", {
+ method: "POST",
+ headers: { host: "example.com" },
+ body: form,
+ }),
+ context: {},
+ })
+ ).resolves.toEqual({ success: true });
+ }
+ expect(received).toEqual([
+ { url: "https://example.com/author", body: { query: "author" } },
+ {
+ url: "https://example.com/submit/author-123",
+ body: { message: "Hello" },
+ },
+ {
+ url: "https://example.com/submit/author-123",
+ body: { message: "Hello" },
+ },
+ ]);
+ }
+ );
+
test("prerenders the configured Webhook Form method", async () => {
const siteData = createSiteData({
instances: [
@@ -3288,6 +3410,18 @@ sitemap.map((page) => page.path);`
const siteData = {
...createSiteData({
assets: [createAssetForIndexedDocument(document)],
+ props: [
+ [
+ "root-title",
+ {
+ id: "root-title",
+ instanceId: "root",
+ name: "title",
+ type: "expression",
+ value: `${encodeDataVariableId("posts-data")}.data["post-1"].properties.title`,
+ },
+ ],
+ ],
}),
assetIndex: index,
};
@@ -3347,8 +3481,8 @@ sitemap.map((page) => page.path);`
routeParams: {},
});
- expect(pageData.resources).toMatchObject({
- Posts: {
+ expect(Object.values(pageData.resources)).toMatchObject([
+ {
ok: true,
status: 200,
data: {
@@ -3359,7 +3493,7 @@ sitemap.map((page) => page.path);`
},
meta: { totalCount: 1, hasMore: false },
},
- });
+ ]);
await runGeneratedCommand("vite", ["build"]);
await runGeneratedCommand("vike", ["prerender"]);
await expect(readFile("dist/client/index.html", "utf8")).resolves.toContain(
diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.ts
index a0bbece6e7..a3d368359e 100644
--- a/packages/cli/src/prebuild.ts
+++ b/packages/cli/src/prebuild.ts
@@ -450,7 +450,9 @@ export const getAssetResourcePrerenderPaths = ({
enumerableConfigurations.length === 0
) {
throw new Error(
- `Dynamic SSG route parameter ${JSON.stringify(firstUnenumerableParameter)} cannot be completely enumerated from every Assets query branch`
+ `Dynamic SSG route parameter ${JSON.stringify(
+ firstUnenumerableParameter
+ )} cannot be completely enumerated from every Assets query branch`
);
}
}
@@ -505,7 +507,9 @@ export const getAssetResourcePrerenderPaths = ({
for (const match of [...pathParameters].reverse()) {
const name = match.groups?.name as string;
const value = values.get(name) as string;
- path = `${path.slice(0, match.index)}${encodeURIComponent(value)}${path.slice((match.index ?? 0) + match[0].length)}`;
+ path = `${path.slice(0, match.index)}${encodeURIComponent(
+ value
+ )}${path.slice((match.index ?? 0) + match[0].length)}`;
}
paths.add(path);
if (paths.size > assetResourceLimits.candidateDocuments) {
@@ -1613,9 +1617,13 @@ export const prebuild = async (options: {
for (const contribution of componentBuildContributions.values()) {
for (const buildImport of contribution.imports) {
if (buildImport.imported === undefined) {
- importsString += `import ${buildImport.local} from ${JSON.stringify(buildImport.source)};\n`;
+ importsString += `import ${buildImport.local} from ${JSON.stringify(
+ buildImport.source
+ )};\n`;
} else {
- importsString += `import { ${buildImport.imported} as ${buildImport.local} } from ${JSON.stringify(buildImport.source)};\n`;
+ importsString += `import { ${buildImport.imported} as ${
+ buildImport.local
+ } } from ${JSON.stringify(buildImport.source)};\n`;
}
}
componentBuildDeclarations.push(...contribution.declarations);
@@ -1688,7 +1696,11 @@ export const prebuild = async (options: {
export const projectId = "${siteData.build.projectId}";
- ${pagePath === "/" ? `export const projectVersion = ${siteData.build.version};` : ""}
+ ${
+ pagePath === "/"
+ ? `export const projectVersion = ${siteData.build.version};`
+ : ""
+ }
export const projectDomain = ${JSON.stringify(siteData.projectDomain)};
@@ -1758,6 +1770,7 @@ export const prebuild = async (options: {
dataSources,
props,
resources,
+ instances,
contentBlockResourceSelections: Array.from(
pageData.publishedContentBlocks?.values() ?? []
).flatMap((block) =>
@@ -1866,7 +1879,11 @@ export const prebuild = async (options: {
await writeGeneratedFile(
join(generatedDir, "$resources.sitemap.xml.ts"),
`
- export const sitemap: Array<{ path: string; lastModified: string }> = ${JSON.stringify(sitemap, null, 2)};
+ export const sitemap: Array<{ path: string; lastModified: string }> = ${JSON.stringify(
+ sitemap,
+ null,
+ 2
+ )};
`
);
diff --git a/packages/cli/templates/defaults/app/route-templates/html.tsx b/packages/cli/templates/defaults/app/route-templates/html.tsx
index 11f707f05b..7c454ae032 100644
--- a/packages/cli/templates/defaults/app/route-templates/html.tsx
+++ b/packages/cli/templates/defaults/app/route-templates/html.tsx
@@ -276,9 +276,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -307,25 +308,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/packages/cli/templates/react-router/app/route-templates/html.tsx b/packages/cli/templates/react-router/app/route-templates/html.tsx
index e01f19c70f..9315a0b938 100644
--- a/packages/cli/templates/react-router/app/route-templates/html.tsx
+++ b/packages/cli/templates/react-router/app/route-templates/html.tsx
@@ -275,9 +275,10 @@ export const action = async ({
};
const resourceName = formData.get(formIdFieldName);
- let resource =
+ const generatedResources = getResources({ system });
+ const actionResource =
typeof resourceName === "string"
- ? getResources({ system }).action.get(resourceName)
+ ? generatedResources.action.get(resourceName)
: undefined;
const formBotValue = formData.get(formBotFieldName);
@@ -306,25 +307,49 @@ export const action = async ({
formData.delete(formIdFieldName);
formData.delete(formBotFieldName);
- if (resource) {
- resource.body = Object.fromEntries(formData);
- } else {
+ let result: Awaited<ReturnType<typeof loadResource>>;
+ if (actionResource === undefined) {
if (contactEmail === undefined) {
throw new Error("Contact email not found");
}
-
- resource = context.getDefaultActionResource?.({
+ const resource = context.getDefaultActionResource?.({
url,
projectId,
contactEmail,
formData,
});
+ if (resource === undefined) {
+ throw Error("Resource not found");
+ }
+ result = await loadResource(fetch, resource);
+ } else {
+ const actionFetch = await createGeneratedAssetResourceFetch({
+ request,
+ context,
+ fallback: customFetch,
+ });
+ const results = await loadResources(
+ actionFetch,
+ {
+ ...generatedResources.data,
+ rootIds: [actionResource.id],
+ },
+ url,
+ {
+ requestOverrides: new Map([
+ // Mutations must reach the backend on every submission, even when
+ // the resource has caching enabled. Dependencies can stay cached.
+ [actionResource.id, { body: Object.fromEntries(formData), fetch }],
+ ]),
+ }
+ );
+ const actionResult = results[actionResource.outputName];
+ if (actionResult === undefined) {
+ throw Error("Resource not found");
+ }
+ result = actionResult as Awaited<ReturnType<typeof loadResource>>;
}
-
- if (resource === undefined) {
- throw Error("Resource not found");
- }
- const { ok, statusText } = await loadResource(fetch, resource);
+ const { ok, statusText } = result;
if (ok) {
return { success: true };
}
diff --git a/packages/content-engine/src/async-utils.test.ts b/packages/content-engine/src/async-utils.test.ts
index 45d58944e6..455671b124 100644
--- a/packages/content-engine/src/async-utils.test.ts
+++ b/packages/content-engine/src/async-utils.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test } from "vitest";
-import { mapBounded } from "./async-utils";
+import { createConcurrencyLimiter, mapBounded } from "./async-utils";
describe("bounded async work", () => {
test("limits concurrency and preserves result order", async () => {
@@ -24,6 +24,41 @@ describe("bounded async work", () => {
expect(maximumActive).toBe(2);
});
+ test("does not start queued work after cancellation", async () => {
+ const controller = new AbortController();
+ const limit = createConcurrencyLimiter({
+ concurrency: 1,
+ signal: controller.signal,
+ });
+ let releaseFirst = () => {};
+ let firstStarted = false;
+ const first = limit(
+ () =>
+ new Promise<void>((resolve) => {
+ firstStarted = true;
+ releaseFirst = resolve;
+ })
+ );
+ let secondStarted = false;
+ const second = limit(async () => {
+ secondStarted = true;
+ });
+ const secondOutcome = second.then(
+ () => "resolved",
+ (error) => error
+ );
+
+ await expect.poll(() => firstStarted).toBe(true);
+ releaseFirst();
+ await Promise.resolve();
+ const reason = new Error("cancelled");
+ controller.abort(reason);
+
+ await first;
+ await expect(secondOutcome).resolves.toBe(reason);
+ expect(secondStarted).toBe(false);
+ });
+
test("rejects invalid concurrency instead of silently skipping work", async () => {
await expect(mapBounded([1], 0, async () => {})).rejects.toThrow(
"Concurrency must be a positive safe integer"
diff --git a/packages/content-engine/src/async-utils.ts b/packages/content-engine/src/async-utils.ts
index fed7b685ff..4fe2217325 100644
--- a/packages/content-engine/src/async-utils.ts
+++ b/packages/content-engine/src/async-utils.ts
@@ -29,3 +29,103 @@ export const mapBounded = async <Value, Result>(
}
return results;
};
+
+const getAbortReason = (signal: AbortSignal) =>
+ signal.reason ?? new DOMException("The operation was aborted", "AbortError");
+
+const throwIfSignalAborted = (signal: AbortSignal | undefined) => {
+ if (signal?.aborted) {
+ throw getAbortReason(signal);
+ }
+};
+
+export const awaitWithSignal = async <Result>(
+ task: Result | PromiseLike<Result>,
+ signal?: AbortSignal
+) => {
+ if (signal === undefined) {
+ return await task;
+ }
+ return await new Promise<Result>((resolve, reject) => {
+ const cleanup = () => signal.removeEventListener("abort", onAbort);
+ const onAbort = () => {
+ cleanup();
+ reject(getAbortReason(signal));
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ Promise.resolve(task).then(
+ (value) => {
+ cleanup();
+ resolve(value);
+ },
+ (error) => {
+ cleanup();
+ reject(error);
+ }
+ );
+ if (signal.aborted) {
+ onAbort();
+ }
+ });
+};
+
+export const createConcurrencyLimiter = ({
+ concurrency,
+ signal,
+}: {
+ concurrency: number;
+ signal?: AbortSignal;
+}) => {
+ if (Number.isSafeInteger(concurrency) === false || concurrency <= 0) {
+ throw new TypeError("Concurrency must be a positive safe integer");
+ }
+ let active = 0;
+ const waiters: Array<{ start: () => void }> = [];
+
+ const acquire = async () => {
+ throwIfSignalAborted(signal);
+ if (active < concurrency) {
+ active += 1;
+ return;
+ }
+ await new Promise<void>((resolve, reject) => {
+ let waiter: { start: () => void };
+ const onAbort = () => {
+ const index = waiters.indexOf(waiter);
+ if (index !== -1) {
+ waiters.splice(index, 1);
+ }
+ if (signal !== undefined) {
+ reject(getAbortReason(signal));
+ }
+ };
+ waiter = {
+ start: () => {
+ signal?.removeEventListener("abort", onAbort);
+ resolve();
+ },
+ };
+ waiters.push(waiter);
+ signal?.addEventListener("abort", onAbort, { once: true });
+ });
+ };
+
+ const release = () => {
+ const next = waiters.shift();
+ if (next === undefined) {
+ active -= 1;
+ return;
+ }
+ next.start();
+ };
+
+ return async <Result>(run: () => Promise<Result>) => {
+ await acquire();
+ try {
+ throwIfSignalAborted(signal);
+ return await run();
+ } finally {
+ release();
+ }
+ };
+};
diff --git a/packages/content-engine/src/document-graph/document-resolution.ts b/packages/content-engine/src/document-graph/document-resolution.ts
index cfae27a397..a7a2e0a71c 100644
--- a/packages/content-engine/src/document-graph/document-resolution.ts
+++ b/packages/content-engine/src/document-graph/document-resolution.ts
@@ -1,4 +1,5 @@
import { LRUCache } from "lru-cache";
+import { awaitWithSignal, createConcurrencyLimiter } from "../async-utils";
import { ByteLimitExceededError, readBytePrefix } from "../byte-stream";
import { contentEngineLimits } from "../limits";
import {
@@ -107,62 +108,6 @@ export type DocumentResolutionSession = Readonly<{
) => Promise<ResolvedDocumentGraph<AdaptedDocument>>;
}>;
-const createConcurrencyLimiter = (
- concurrency: number,
- signal: AbortSignal | undefined
-) => {
- let active = 0;
- const waiters: Array<{ start: () => void }> = [];
-
- const acquire = async () => {
- signal?.throwIfAborted();
- if (active < concurrency) {
- active += 1;
- return;
- }
- await new Promise<void>((resolve, reject) => {
- let waiter: { start: () => void };
- const onAbort = () => {
- const index = waiters.indexOf(waiter);
- if (index !== -1) {
- waiters.splice(index, 1);
- }
- try {
- signal?.throwIfAborted();
- } catch (error) {
- reject(error);
- }
- };
- waiter = {
- start: () => {
- signal?.removeEventListener("abort", onAbort);
- resolve();
- },
- };
- waiters.push(waiter);
- signal?.addEventListener("abort", onAbort, { once: true });
- });
- };
-
- const release = () => {
- const next = waiters.shift();
- if (next === undefined) {
- active -= 1;
- return;
- }
- next.start();
- };
-
- return async <Result>(run: () => Promise<Result>) => {
- await acquire();
- try {
- return await run();
- } finally {
- release();
- }
- };
-};
-
const resolveWithSessionDocumentLoader = async ({
graph,
rootIds,
@@ -316,7 +261,7 @@ export const createDocumentResolutionSession = ({
sizeCalculation: ({ byteLength }) => Math.max(1, byteLength),
});
const pending = new Map<string, Promise<SessionDocumentSource>>();
- const limit = createConcurrencyLimiter(concurrency, signal);
+ const limit = createConcurrencyLimiter({ concurrency, signal });
const assertSessionSignal = (requestedSignal?: AbortSignal) => {
if (requestedSignal !== undefined && requestedSignal !== signal) {
@@ -327,34 +272,7 @@ export const createDocumentResolutionSession = ({
const waitForSessionTask = async <Result>(task: Promise<Result>) => {
assertSessionSignal();
- if (signal === undefined) {
- return await task;
- }
- return await new Promise<Result>((resolve, reject) => {
- const cleanup = () => signal.removeEventListener("abort", onAbort);
- const onAbort = () => {
- cleanup();
- try {
- signal.throwIfAborted();
- } catch (error) {
- reject(error);
- }
- };
- signal.addEventListener("abort", onAbort, { once: true });
- task.then(
- (value) => {
- cleanup();
- resolve(value);
- },
- (error) => {
- cleanup();
- reject(error);
- }
- );
- if (signal.aborted) {
- onAbort();
- }
- });
+ return await awaitWithSignal(task, signal);
};
const loadSessionDocument = async (
diff --git a/packages/content-engine/src/document-graph/index.ts b/packages/content-engine/src/document-graph/index.ts
index f251770b73..2ae56af5be 100644
--- a/packages/content-engine/src/document-graph/index.ts
+++ b/packages/content-engine/src/document-graph/index.ts
@@ -15,3 +15,4 @@ export * from "./resolver";
export * from "./document-resolution";
export * from "./query-references";
export * from "./observability";
+export * from "./resource-resolver";
diff --git a/packages/content-engine/src/document-graph/resolver.test.ts b/packages/content-engine/src/document-graph/resolver.test.ts
index 933c10efa4..20975d4c05 100644
--- a/packages/content-engine/src/document-graph/resolver.test.ts
+++ b/packages/content-engine/src/document-graph/resolver.test.ts
@@ -138,4 +138,48 @@ describe("document graph resolver", () => {
expect(loadCount).toBe(1);
expect(result.roots).toEqual(["first:shared", "second:shared"]);
});
+
+ test("cancels without waiting for a document loader to settle", async () => {
+ const controller = new AbortController();
+ let finish = () => {};
+ let markStarted = () => {};
+ const started = new Promise<void>((resolve) => {
+ markStarted = resolve;
+ });
+ const resolution = resolveDocumentGraph({
+ graph: createDocumentGraph({
+ nodes: [{ id: "root", revision: "r1", contentRef: "root" }],
+ edges: [],
+ }),
+ rootIds: ["root"],
+ concurrency: 1,
+ signal: controller.signal,
+ load: () =>
+ new Promise<string>((resolve) => {
+ finish = () => resolve("source");
+ markStarted();
+ }),
+ assemble: ({ source }) => source,
+ });
+ const outcome = resolution.then(
+ () => "resolved",
+ (error) => error
+ );
+
+ await started;
+ controller.abort(new Error("cancelled"));
+
+ await expect(
+ Promise.race([
+ outcome,
+ new Promise((resolve) =>
+ setTimeout(() => resolve("still pending"), 20)
+ ),
+ ])
+ ).resolves.toMatchObject({
+ code: "REQUEST_CANCELLED",
+ } satisfies Partial<DocumentGraphResolutionError>);
+ finish();
+ await outcome;
+ });
});
diff --git a/packages/content-engine/src/document-graph/resolver.ts b/packages/content-engine/src/document-graph/resolver.ts
index 28979636b7..019e310c3e 100644
--- a/packages/content-engine/src/document-graph/resolver.ts
+++ b/packages/content-engine/src/document-graph/resolver.ts
@@ -1,4 +1,4 @@
-import { mapBounded } from "../async-utils";
+import { awaitWithSignal, mapBounded } from "../async-utils";
import {
getDocumentGraphClosure,
type DocumentGraph,
@@ -6,6 +6,11 @@ import {
} from "./graph";
import { getDocumentGraphEdgesBySourceId } from "./graph-utils";
import type { DocumentReference } from "./reference";
+import {
+ ResourceResolutionError,
+ resolveResources,
+ type Resource,
+} from "./resource-resolver";
export type DocumentGraphResolutionErrorCode =
| "REQUEST_CANCELLED"
@@ -108,7 +113,7 @@ export const resolveDocumentGraph = async <Source, Value>({
assertActive(signal);
const node = group.representative;
try {
- const source = await load(node, { signal });
+ const source = await awaitWithSignal(load(node, { signal }), signal);
for (const groupedNode of group.nodes) {
sources.set(groupedNode.id, source);
}
@@ -126,77 +131,113 @@ export const resolveDocumentGraph = async <Source, Value>({
});
const edgesBySourceId = getDocumentGraphEdgesBySourceId(graph.edges);
- const values = new Map<string, Value>();
- for (const node of closure) {
- assertActive(signal);
- const references = new Map<string, unknown>();
- for (const edge of edgesBySourceId.get(node.id) ?? []) {
- const targetNode = nodesById.get(edge.reference.documentId);
- if (
- targetNode === undefined ||
- values.has(edge.reference.documentId) === false
- ) {
- throw new DocumentGraphResolutionError({
- code: "DOCUMENT_ASSEMBLY_FAILED",
- message: `Document ${node.id} dependency ${edge.reference.documentId} is unavailable`,
- documentId: node.id,
- referenceId: edge.referenceId,
- });
- }
- const targetValue = values.get(edge.reference.documentId) as Value;
- let selected: unknown;
- if (select === undefined) {
- if (edge.reference.representation.type !== "document") {
+ const resources: Resource<Value>[] = closure.map((node) => ({
+ id: node.id,
+ dependencies: (edgesBySourceId.get(node.id) ?? []).map(
+ (edge) => edge.reference.documentId
+ ),
+ resolve: async ({ documents }) => {
+ assertActive(signal);
+ const references = new Map<string, unknown>();
+ for (const edge of edgesBySourceId.get(node.id) ?? []) {
+ const targetNode = nodesById.get(edge.reference.documentId);
+ if (
+ targetNode === undefined ||
+ documents.has(edge.reference.documentId) === false
+ ) {
throw new DocumentGraphResolutionError({
- code: "REPRESENTATION_SELECTOR_REQUIRED",
- message: `Document ${node.id} reference ${edge.referenceId} requires a representation selector`,
+ code: "DOCUMENT_ASSEMBLY_FAILED",
+ message: `Document ${node.id} dependency ${edge.reference.documentId} is unavailable`,
documentId: node.id,
referenceId: edge.referenceId,
});
}
- selected = targetValue;
- } else {
- try {
- selected = await select({
- reference: edge.reference,
- value: targetValue,
- sourceNode: node,
- targetNode,
- });
- } catch (error) {
- throw new DocumentGraphResolutionError({
- code: "DOCUMENT_SELECTION_FAILED",
- message: `Document ${node.id} reference ${edge.referenceId} could not be selected`,
- documentId: node.id,
- referenceId: edge.referenceId,
- cause: error,
- });
+ const targetValue = documents.get(edge.reference.documentId) as Value;
+ let selected: unknown;
+ if (select === undefined) {
+ if (edge.reference.representation.type !== "document") {
+ throw new DocumentGraphResolutionError({
+ code: "REPRESENTATION_SELECTOR_REQUIRED",
+ message: `Document ${node.id} reference ${edge.referenceId} requires a representation selector`,
+ documentId: node.id,
+ referenceId: edge.referenceId,
+ });
+ }
+ selected = targetValue;
+ } else {
+ try {
+ selected = await select({
+ reference: edge.reference,
+ value: targetValue,
+ sourceNode: node,
+ targetNode,
+ });
+ } catch (error) {
+ throw new DocumentGraphResolutionError({
+ code: "DOCUMENT_SELECTION_FAILED",
+ message: `Document ${node.id} reference ${edge.referenceId} could not be selected`,
+ documentId: node.id,
+ referenceId: edge.referenceId,
+ cause: error,
+ });
+ }
}
+ references.set(edge.referenceId, selected);
}
- references.set(edge.referenceId, selected);
- }
- if (sources.has(node.id) === false) {
- throw new DocumentGraphResolutionError({
- code: "DOCUMENT_ASSEMBLY_FAILED",
- message: `Document ${node.id} source is unavailable`,
- documentId: node.id,
- });
+ if (sources.has(node.id) === false) {
+ throw new DocumentGraphResolutionError({
+ code: "DOCUMENT_ASSEMBLY_FAILED",
+ message: `Document ${node.id} source is unavailable`,
+ documentId: node.id,
+ });
+ }
+ const source = sources.get(node.id) as Source;
+ try {
+ return await assemble({ node, source, references });
+ } catch (error) {
+ if (error instanceof DocumentGraphResolutionError) {
+ throw error;
+ }
+ throw new DocumentGraphResolutionError({
+ code: "DOCUMENT_ASSEMBLY_FAILED",
+ message: `Document ${node.id} could not be assembled`,
+ documentId: node.id,
+ cause: error,
+ });
+ }
+ },
+ }));
+
+ try {
+ const resolved = await resolveResources({
+ resources,
+ rootIds,
+ // Preserve deterministic dependency-first document assembly. Source
+ // loading above remains bounded and concurrent.
+ concurrency: 1,
+ signal,
+ });
+ return Object.freeze({
+ roots: resolved.roots,
+ values: resolved.documents,
+ });
+ } catch (error) {
+ if (
+ error instanceof ResourceResolutionError &&
+ error.cause instanceof DocumentGraphResolutionError
+ ) {
+ throw error.cause;
}
- const source = sources.get(node.id) as Source;
- try {
- values.set(node.id, await assemble({ node, source, references }));
- } catch (error) {
+ if (
+ error instanceof ResourceResolutionError &&
+ error.code === "REQUEST_CANCELLED"
+ ) {
throw new DocumentGraphResolutionError({
- code: "DOCUMENT_ASSEMBLY_FAILED",
- message: `Document ${node.id} could not be assembled`,
- documentId: node.id,
- cause: error,
+ code: "REQUEST_CANCELLED",
+ message: "Document graph resolution was cancelled",
+ cause: error.cause,
});
}
+ throw error;
}
-
- return Object.freeze({
- roots: Object.freeze(rootIds.map((rootId) => values.get(rootId) as Value)),
- values,
- });
};
diff --git a/packages/content-engine/src/document-graph/resource-resolver.test.ts b/packages/content-engine/src/document-graph/resource-resolver.test.ts
new file mode 100644
index 0000000000..77b49010dc
--- /dev/null
+++ b/packages/content-engine/src/document-graph/resource-resolver.test.ts
@@ -0,0 +1,234 @@
+import { describe, expect, test, vi } from "vitest";
+import {
+ ResourceResolutionError,
+ resolveResources,
+ type Resource,
+} from "./resource-resolver";
+
+const resource = (
+ id: string,
+ dependencies: readonly string[],
+ resolve: Resource<unknown>["resolve"]
+): Resource<unknown> => ({ id, dependencies, resolve });
+
+describe("resource resolver", () => {
+ test("resolves only the requested closure and shares dependency documents", async () => {
+ const calls: string[] = [];
+ let active = 0;
+ let maximumActive = 0;
+ const resources = [
+ resource("source", [], async () => {
+ calls.push("source");
+ return "source document";
+ }),
+ resource("first", ["source"], async ({ documents }) => {
+ calls.push("first");
+ active += 1;
+ maximumActive = Math.max(maximumActive, active);
+ await Promise.resolve();
+ active -= 1;
+ return `${documents.get("source")}:first`;
+ }),
+ resource("second", ["source"], async ({ documents }) => {
+ calls.push("second");
+ active += 1;
+ maximumActive = Math.max(maximumActive, active);
+ await Promise.resolve();
+ active -= 1;
+ return `${documents.get("source")}:second`;
+ }),
+ resource("unused", [], async () => {
+ calls.push("unused");
+ return "unused document";
+ }),
+ ];
+
+ const result = await resolveResources({
+ resources,
+ rootIds: ["first", "second"],
+ concurrency: 2,
+ });
+
+ expect(result.roots).toEqual([
+ "source document:first",
+ "source document:second",
+ ]);
+ expect(result.documents).toEqual(
+ new Map([
+ ["source", "source document"],
+ ["first", "source document:first"],
+ ["second", "source document:second"],
+ ])
+ );
+ expect(calls.filter((id) => id === "source")).toHaveLength(1);
+ expect(calls).not.toContain("unused");
+ expect(maximumActive).toBe(2);
+ });
+
+ test("rejects a reachable missing dependency", async () => {
+ await expect(
+ resolveResources({
+ resources: [resource("root", ["missing"], async () => "root")],
+ rootIds: ["root"],
+ concurrency: 1,
+ })
+ ).rejects.toMatchObject({
+ code: "DEPENDENCY_NOT_FOUND",
+ resourceIds: ["root", "missing"],
+ } satisfies Partial<ResourceResolutionError>);
+ });
+
+ test("rejects dependency cycles before resolving resources", async () => {
+ const resolve = vi.fn(async () => "document");
+
+ await expect(
+ resolveResources({
+ resources: [
+ resource("first", ["second"], resolve),
+ resource("second", ["first"], resolve),
+ ],
+ rootIds: ["first"],
+ concurrency: 1,
+ })
+ ).rejects.toMatchObject({
+ code: "CYCLE",
+ resourceIds: ["first", "second", "first"],
+ } satisfies Partial<ResourceResolutionError>);
+ expect(resolve).not.toHaveBeenCalled();
+ });
+
+ test("wraps resolution failures with resource context", async () => {
+ await expect(
+ resolveResources({
+ resources: [
+ resource("root", [], async () => {
+ throw new Error("offline");
+ }),
+ ],
+ rootIds: ["root"],
+ concurrency: 1,
+ })
+ ).rejects.toMatchObject({
+ code: "RESOLUTION_FAILED",
+ resourceIds: ["root"],
+ } satisfies Partial<ResourceResolutionError>);
+ });
+
+ test("reports the dependency path and original cause", async () => {
+ const failure = new Error("offline");
+ const resolution = resolveResources({
+ resources: [
+ resource("root", ["middle"], async () => "root"),
+ resource("middle", ["leaf"], async () => "middle"),
+ resource("leaf", [], async () => {
+ throw failure;
+ }),
+ ],
+ rootIds: ["root"],
+ concurrency: 1,
+ });
+
+ await expect(resolution).rejects.toMatchObject({
+ code: "RESOLUTION_FAILED",
+ resourceIds: ["root", "middle", "leaf"],
+ cause: failure,
+ } satisfies Partial<ResourceResolutionError>);
+ });
+
+ test("passes cancellation to resource resolution", async () => {
+ const controller = new AbortController();
+ controller.abort(new Error("cancelled"));
+ const resolve = vi.fn(async () => "document");
+
+ await expect(
+ resolveResources({
+ resources: [resource("root", [], resolve)],
+ rootIds: ["root"],
+ concurrency: 1,
+ signal: controller.signal,
+ })
+ ).rejects.toMatchObject({
+ code: "REQUEST_CANCELLED",
+ resourceIds: [],
+ } satisfies Partial<ResourceResolutionError>);
+ expect(resolve).not.toHaveBeenCalled();
+ });
+
+ test("rejects when cancelled while a resource is resolving", async () => {
+ const controller = new AbortController();
+ let finish = () => {};
+ let markStarted = () => {};
+ const started = new Promise<void>((resolve) => {
+ markStarted = resolve;
+ });
+ const resolution = resolveResources({
+ resources: [
+ resource(
+ "root",
+ [],
+ () =>
+ new Promise<string>((resolve) => {
+ finish = () => resolve("document");
+ markStarted();
+ })
+ ),
+ ],
+ rootIds: ["root"],
+ concurrency: 1,
+ signal: controller.signal,
+ });
+
+ await started;
+ controller.abort(new Error("cancelled"));
+ finish();
+
+ await expect(resolution).rejects.toMatchObject({
+ code: "REQUEST_CANCELLED",
+ } satisfies Partial<ResourceResolutionError>);
+ });
+
+ test("cancels without waiting for a resource implementation to settle", async () => {
+ const controller = new AbortController();
+ let finish = () => {};
+ let markStarted = () => {};
+ const started = new Promise<void>((resolve) => {
+ markStarted = resolve;
+ });
+ const resolution = resolveResources({
+ resources: [
+ resource(
+ "root",
+ [],
+ () =>
+ new Promise<string>((resolve) => {
+ finish = () => resolve("document");
+ markStarted();
+ })
+ ),
+ ],
+ rootIds: ["root"],
+ concurrency: 1,
+ signal: controller.signal,
+ });
+ const outcome = resolution.then(
+ () => "resolved",
+ (error) => error
+ );
+
+ await started;
+ controller.abort(new Error("cancelled"));
+
+ await expect(
+ Promise.race([
+ outcome,
+ new Promise((resolve) =>
+ setTimeout(() => resolve("still pending"), 20)
+ ),
+ ])
+ ).resolves.toMatchObject({
+ code: "REQUEST_CANCELLED",
+ } satisfies Partial<ResourceResolutionError>);
+ finish();
+ await outcome;
+ });
+});
diff --git a/packages/content-engine/src/document-graph/resource-resolver.ts b/packages/content-engine/src/document-graph/resource-resolver.ts
new file mode 100644
index 0000000000..f6e428d6cf
--- /dev/null
+++ b/packages/content-engine/src/document-graph/resource-resolver.ts
@@ -0,0 +1,224 @@
+import { awaitWithSignal, createConcurrencyLimiter } from "../async-utils";
+
+export type Resource<Document> = Readonly<{
+ id: string;
+ dependencies: readonly string[];
+ resolve: (input: {
+ documents: ReadonlyMap<string, Document>;
+ signal?: AbortSignal;
+ }) => Document | Promise<Document>;
+}>;
+
+export type ResourceResolutionErrorCode =
+ | "DUPLICATE_RESOURCE"
+ | "ROOT_NOT_FOUND"
+ | "DEPENDENCY_NOT_FOUND"
+ | "CYCLE"
+ | "REQUEST_CANCELLED"
+ | "RESOLUTION_FAILED";
+
+export class ResourceResolutionError extends Error {
+ readonly code: ResourceResolutionErrorCode;
+ readonly resourceIds: readonly string[];
+
+ constructor({
+ code,
+ message,
+ resourceIds = [],
+ cause,
+ }: {
+ code: ResourceResolutionErrorCode;
+ message: string;
+ resourceIds?: readonly string[];
+ cause?: unknown;
+ }) {
+ super(message, { cause });
+ this.name = "ResourceResolutionError";
+ this.code = code;
+ this.resourceIds = Object.freeze([...resourceIds]);
+ }
+}
+
+export type ResolvedResources<Document> = Readonly<{
+ roots: readonly Document[];
+ documents: ReadonlyMap<string, Document>;
+}>;
+
+const assertActive = (signal: AbortSignal | undefined) => {
+ if (signal?.aborted) {
+ throw new ResourceResolutionError({
+ code: "REQUEST_CANCELLED",
+ message: "Resource resolution was cancelled",
+ cause: signal.reason,
+ });
+ }
+};
+
+const getReachableResources = <Document>({
+ resourcesById,
+ rootIds,
+}: {
+ resourcesById: ReadonlyMap<string, Resource<Document>>;
+ rootIds: readonly string[];
+}) => {
+ const state = new Map<string, "visiting" | "visited">();
+ const stack: string[] = [];
+ const ordered: Resource<Document>[] = [];
+
+ const visit = (resourceId: string, sourceId?: string) => {
+ const resource = resourcesById.get(resourceId);
+ if (resource === undefined) {
+ throw new ResourceResolutionError({
+ code:
+ sourceId === undefined ? "ROOT_NOT_FOUND" : "DEPENDENCY_NOT_FOUND",
+ message:
+ sourceId === undefined
+ ? `Resource graph root ${resourceId} does not exist`
+ : `Resource ${sourceId} dependency ${resourceId} does not exist`,
+ resourceIds:
+ sourceId === undefined ? [resourceId] : [sourceId, resourceId],
+ });
+ }
+ const resourceState = state.get(resourceId);
+ if (resourceState === "visited") {
+ return;
+ }
+ if (resourceState === "visiting") {
+ const cycleStart = stack.indexOf(resourceId);
+ const cycle = [...stack.slice(cycleStart), resourceId];
+ throw new ResourceResolutionError({
+ code: "CYCLE",
+ message: `Resource graph contains a cycle: ${cycle.join(" -> ")}`,
+ resourceIds: cycle,
+ });
+ }
+ state.set(resourceId, "visiting");
+ stack.push(resourceId);
+ for (const dependencyId of resource.dependencies) {
+ visit(dependencyId, resource.id);
+ }
+ stack.pop();
+ state.set(resourceId, "visited");
+ ordered.push(resource);
+ };
+
+ for (const rootId of new Set(rootIds)) {
+ visit(rootId);
+ }
+ return ordered;
+};
+
+/** Resolves only requested resources and their transitive dependencies. */
+export const resolveResources = async <Document>({
+ resources,
+ rootIds,
+ concurrency,
+ signal,
+}: {
+ resources: Iterable<Resource<Document>>;
+ rootIds: readonly string[];
+ concurrency: number;
+ signal?: AbortSignal;
+}): Promise<ResolvedResources<Document>> => {
+ if (Number.isSafeInteger(concurrency) === false || concurrency <= 0) {
+ throw new TypeError("Resource resolution concurrency must be positive");
+ }
+ assertActive(signal);
+ const resourcesById = new Map<string, Resource<Document>>();
+ for (const resource of resources) {
+ if (resourcesById.has(resource.id)) {
+ throw new ResourceResolutionError({
+ code: "DUPLICATE_RESOURCE",
+ message: `Resource graph contains duplicate resource ${resource.id}`,
+ resourceIds: [resource.id],
+ });
+ }
+ resourcesById.set(resource.id, resource);
+ }
+ const reachableResources = getReachableResources({
+ resourcesById,
+ rootIds,
+ });
+ const limit = createConcurrencyLimiter({ concurrency, signal });
+ const documents = new Map<string, Document>();
+ const pending = new Map<string, Promise<Document>>();
+
+ const resolveResource = (resourceId: string): Promise<Document> => {
+ const previous = pending.get(resourceId);
+ if (previous !== undefined) {
+ return previous;
+ }
+ const resource = resourcesById.get(resourceId) as Resource<Document>;
+ const resolution = (async () => {
+ const dependencyDocuments = new Map<string, Document>();
+ let dependencyValues: Document[];
+ try {
+ dependencyValues = await Promise.all(
+ resource.dependencies.map(resolveResource)
+ );
+ } catch (cause) {
+ if (
+ cause instanceof ResourceResolutionError &&
+ cause.code === "RESOLUTION_FAILED"
+ ) {
+ throw new ResourceResolutionError({
+ code: cause.code,
+ message: `Resource dependency path ${[
+ resource.id,
+ ...cause.resourceIds,
+ ].join(" -> ")} could not be resolved`,
+ resourceIds: [resource.id, ...cause.resourceIds],
+ cause: cause.cause,
+ });
+ }
+ throw cause;
+ }
+ for (const [index, dependencyId] of resource.dependencies.entries()) {
+ dependencyDocuments.set(
+ dependencyId,
+ dependencyValues[index] as Document
+ );
+ }
+ assertActive(signal);
+ try {
+ return await limit(async () => {
+ assertActive(signal);
+ const document = await awaitWithSignal(
+ resource.resolve({
+ documents: dependencyDocuments,
+ signal,
+ }),
+ signal
+ );
+ assertActive(signal);
+ return document;
+ });
+ } catch (cause) {
+ if (signal?.aborted) {
+ assertActive(signal);
+ }
+ if (cause instanceof ResourceResolutionError) {
+ throw cause;
+ }
+ throw new ResourceResolutionError({
+ code: "RESOLUTION_FAILED",
+ message: `Resource ${resource.id} could not be resolved`,
+ resourceIds: [resource.id],
+ cause,
+ });
+ }
+ })();
+ pending.set(resourceId, resolution);
+ return resolution;
+ };
+
+ const roots = await Promise.all(rootIds.map(resolveResource));
+ for (const resource of reachableResources) {
+ const document = await pending.get(resource.id);
+ documents.set(resource.id, document as Document);
+ }
+ return Object.freeze({
+ roots: Object.freeze(roots),
+ documents,
+ });
+};
diff --git a/packages/content-engine/src/index.ts b/packages/content-engine/src/index.ts
index c367eeaa26..59905bf9f2 100644
--- a/packages/content-engine/src/index.ts
+++ b/packages/content-engine/src/index.ts
@@ -18,4 +18,5 @@ export * from "./content-collection";
export { extractMarkdownFrontmatter } from "./frontmatter";
export { MarkdownMetadataError } from "./markdown-errors";
export { createUniqueAssetIdsByPath } from "./asset-path-resolution";
+export { awaitWithSignal } from "./async-utils";
export { appendAssetFieldPath } from "./canonical";
diff --git a/packages/project-build/src/runtime/block.test.ts b/packages/project-build/src/runtime/block.test.ts
index aa2e5264a9..b108015559 100644
--- a/packages/project-build/src/runtime/block.test.ts
+++ b/packages/project-build/src/runtime/block.test.ts
@@ -32,23 +32,23 @@ const createInstance = (
});
describe("block tree helpers", () => {
- test("resolves direct sources without expression values", () => {
- expect(
+ test("resolves direct sources without expression values", async () => {
+ await expect(
resolveContentBlockSourceAssetId({
source: { type: "asset", assetId: "post" },
})
- ).toBe("post");
- expect(
+ ).resolves.toBe("post");
+ await expect(
resolveContentBlockSourceAssetId({
source: { type: "expression", value: "post" },
})
- ).toBeUndefined();
- expect(
+ ).resolves.toBeUndefined();
+ await expect(
resolveContentBlockSourceAssetId({
source: { type: "expression", value: "post" },
values: new Map([["post", "post-asset"]]),
})
- ).toBe("post-asset");
+ ).resolves.toBe("post-asset");
});
test("finds block and block child selectors from nested anchors", () => {
diff --git a/packages/project-build/src/runtime/block.ts b/packages/project-build/src/runtime/block.ts
index b5338e7405..aebf9e4efa 100644
--- a/packages/project-build/src/runtime/block.ts
+++ b/packages/project-build/src/runtime/block.ts
@@ -14,7 +14,7 @@ import {
import { computeStringExpression } from "./data";
import type { InstanceSelector } from "./tree";
-export const resolveContentBlockSourceAssetId = ({
+export const resolveContentBlockSourceAssetId = async ({
source,
values,
}: {
@@ -25,7 +25,7 @@ export const resolveContentBlockSourceAssetId = ({
? source.assetId
: values === undefined
? undefined
- : computeStringExpression(source.value, values);
+ : await computeStringExpression(source.value, values);
export const findBlockTemplateNameCollision = ({
instance,
diff --git a/packages/project-build/src/runtime/content-block-application.test.ts b/packages/project-build/src/runtime/content-block-application.test.ts
index e8b1f2d97f..44e86c6b61 100644
--- a/packages/project-build/src/runtime/content-block-application.test.ts
+++ b/packages/project-build/src/runtime/content-block-application.test.ts
@@ -127,9 +127,9 @@ describe("createContentBlockApplication", () => {
type: "expression",
value: "collection.data._id",
});
- expect(
+ await expect(
getMdxAssetSourceBlockInstanceIds({ assetId: "asset", state })
- ).toEqual([]);
+ ).resolves.toEqual([]);
const diagnostics = await inspectMdxAssetSource({
source: "<Accordion />",
assetId: "asset",
@@ -169,12 +169,12 @@ describe("createContentBlockApplication", () => {
{ id: "connect", payload: [...connected.projectPayload] },
]).state;
- expect(
+ await expect(
getMdxAssetSourceBlockInstanceIds({
assetId: "asset",
state: connectedState,
})
- ).toEqual(["block"]);
+ ).resolves.toEqual(["block"]);
await expect(
inspectMdxAssetSource({
diff --git a/packages/project-build/src/runtime/content-block-application.ts b/packages/project-build/src/runtime/content-block-application.ts
index 6699124c15..315f4262c5 100644
--- a/packages/project-build/src/runtime/content-block-application.ts
+++ b/packages/project-build/src/runtime/content-block-application.ts
@@ -55,7 +55,7 @@ const bindContentBlockSource = (
: source;
/** Finds every Content Block whose current source resolves to an MDX Asset. */
-export const getMdxAssetSourceBlockInstanceIds = ({
+export const getMdxAssetSourceBlockInstanceIds = async ({
assetId,
state,
}: {
@@ -69,16 +69,24 @@ export const getMdxAssetSourceBlockInstanceIds = ({
values.set(dataSource.id, dataSource.value.value);
}
}
- return Array.from(
- getContentBlockSources({
- instances: state.instances?.values() ?? [],
- props: state.props?.values() ?? [],
- })
- ).flatMap(([blockInstanceId, contentSource]) =>
- resolveContentBlockSourceAssetId({ source: contentSource, values }) ===
- assetId
- ? [blockInstanceId]
- : []
+ const blockInstanceIds = await Promise.all(
+ Array.from(
+ getContentBlockSources({
+ instances: state.instances?.values() ?? [],
+ props: state.props?.values() ?? [],
+ })
+ ).map(async ([blockInstanceId, contentSource]) =>
+ (await resolveContentBlockSourceAssetId({
+ source: contentSource,
+ values,
+ })) === assetId
+ ? blockInstanceId
+ : undefined
+ )
+ );
+ return blockInstanceIds.filter(
+ (blockInstanceId): blockInstanceId is string =>
+ blockInstanceId !== undefined
);
};
@@ -145,7 +153,7 @@ export const inspectMdxAssetSource = async ({
}
const data = getData(state);
const blockInstanceIds = new Set([
- ...getMdxAssetSourceBlockInstanceIds({ assetId, state }),
+ ...(await getMdxAssetSourceBlockInstanceIds({ assetId, state })),
...sourceBlockInstanceIds,
]);
for (const blockInstanceId of blockInstanceIds) {
@@ -204,9 +212,9 @@ export const createContentBlockApplication = ({
source: ContentBlockSource;
state: BuilderState;
variables?: Readonly<Record<string, unknown>>;
- }) => string | undefined;
+ }) => string | undefined | PromiseLike<string | undefined>;
}) => {
- const resolveSource = ({
+ const resolveSource = async ({
source,
state,
blockInstanceId,
@@ -217,7 +225,7 @@ export const createContentBlockApplication = ({
blockInstanceId: string;
variables?: Readonly<Record<string, unknown>>;
}) => {
- const resolved = resolveSourceAssetId?.({ source, state, variables });
+ const resolved = await resolveSourceAssetId?.({ source, state, variables });
if (resolveSourceAssetId !== undefined) {
if (resolved === undefined || resolved === "") {
throw new Error("Content source does not resolve to an MDX Asset");
@@ -244,13 +252,13 @@ export const createContentBlockApplication = ({
values.set(dataSource.id, dataSource.value.value);
}
}
- const assetId = resolveContentBlockSourceAssetId({ source, values });
+ const assetId = await resolveContentBlockSourceAssetId({ source, values });
if (assetId !== undefined) {
return assetId;
}
const evaluated =
source.type === "expression"
- ? computeExpression(source.value, values)
+ ? await computeExpression(source.value, values)
: undefined;
const suppliedVariableShapes =
Object.entries(variables ?? {})
@@ -298,7 +306,7 @@ export const createContentBlockApplication = ({
renderScope: string;
variables?: Readonly<Record<string, unknown>>;
}) => {
- const assetId = resolveSource({
+ const assetId = await resolveSource({
source,
state,
blockInstanceId,
diff --git a/packages/project-build/src/runtime/data.test.tsx b/packages/project-build/src/runtime/data.test.tsx
index b0012d1c87..8f40415c44 100644
--- a/packages/project-build/src/runtime/data.test.tsx
+++ b/packages/project-build/src/runtime/data.test.tsx
@@ -24,6 +24,7 @@ import { createDefaultPages } from "@webstudio-is/project-build";
import {
computeExpression,
computeExpressionWithinScope,
+ computeStringExpression,
bindExpressionToInstanceScope,
createDataVariable,
dataVariableCreateInput,
@@ -1007,75 +1008,169 @@ test("replace data source ids in expression", () => {
).toEqual("https://example.com/cards.json");
});
-test("compute expression with decoded ids", () => {
- expect(
+test("compute expression with decoded ids", async () => {
+ await expect(
computeExpression("$ws$dataSource$myId", new Map([["myId", "value"]]))
- ).toEqual("value");
+ ).resolves.toEqual("value");
});
-test("compute expression with decoded names", () => {
- expect(
+test("compute expression asynchronously resolves only referenced data sources", async () => {
+ const resolveDataSource = vi.fn(async (id: string, value: unknown) => {
+ if (id === "remoteId") {
+ return { data: { title: "Remote title" } };
+ }
+ return value;
+ });
+
+ await expect(
+ computeExpression(
+ `${encodeDataVariableId("remoteId")}.data.title`,
+ new Map([
+ ["remoteId", undefined],
+ ["unusedId", undefined],
+ ]),
+ resolveDataSource
+ )
+ ).resolves.toBe("Remote title");
+ expect(resolveDataSource).toHaveBeenCalledOnce();
+ expect(resolveDataSource).toHaveBeenCalledWith("remoteId", undefined);
+});
+
+test("compute expression asynchronously resolves independent data sources in parallel", async () => {
+ let finishFirst: (value: number) => void = () => {};
+ let finishSecond: (value: number) => void = () => {};
+ let active = 0;
+ let maximumActive = 0;
+ const resolveDataSource = vi.fn((id: string) => {
+ active += 1;
+ maximumActive = Math.max(maximumActive, active);
+ return new Promise<number>((resolve) => {
+ const finish = (value: number) => {
+ active -= 1;
+ resolve(value);
+ };
+ if (id === "firstId") {
+ finishFirst = finish;
+ } else {
+ finishSecond = finish;
+ }
+ });
+ });
+
+ const result = computeExpression(
+ `${encodeDataVariableId("firstId")} + ${encodeDataVariableId("secondId")}`,
+ new Map(),
+ resolveDataSource
+ );
+ expect(resolveDataSource).toHaveBeenCalledTimes(2);
+ expect(maximumActive).toBe(2);
+ finishFirst(1);
+ finishSecond(2);
+
+ await expect(result).resolves.toBe(3);
+});
+
+test("compute expression asynchronously propagates resolver failures", async () => {
+ const failure = new Error("offline");
+
+ await expect(
+ computeExpression(encodeDataVariableId("remoteId"), new Map(), async () => {
+ throw failure;
+ })
+ ).rejects.toBe(failure);
+});
+
+test("compute string and scoped expressions asynchronously", async () => {
+ const resolveDataSource = async (id: string) =>
+ id === "remoteId" ? "Remote title" : undefined;
+
+ await expect(
+ computeStringExpression(
+ encodeDataVariableId("remoteId"),
+ new Map(),
+ resolveDataSource
+ )
+ ).resolves.toBe("Remote title");
+ await expect(
+ computeExpressionWithinScope(
+ encodeDataVariableId("remoteId"),
+ { [encodeDataVariableId("remoteId")]: undefined },
+ resolveDataSource
+ )
+ ).resolves.toBe("Remote title");
+});
+
+test("compute expression with decoded names", async () => {
+ await expect(
computeExpression("My$32$Name", new Map([["My Name", "value"]]))
- ).toEqual("value");
+ ).resolves.toEqual("value");
});
-test("compute expression when invalid syntax", () => {
+test("compute expression when invalid syntax", async () => {
const spy = vi.spyOn(console, "error");
- expect(computeExpression("https://github.com", new Map())).toEqual(undefined);
+ await expect(
+ computeExpression("https://github.com", new Map())
+ ).resolves.toEqual(undefined);
expect(spy).not.toHaveBeenCalled();
spy.mockRestore();
});
-test("compute expression with nested field of undefined without error", () => {
+test("compute expression with nested field of undefined without error", async () => {
const spy = vi.spyOn(console, "error");
const variables = new Map([["myVariable", undefined]]);
- expect(computeExpression("myVariable.field", variables)).toEqual(undefined);
+ await expect(
+ computeExpression("myVariable.field", variables)
+ ).resolves.toEqual(undefined);
expect(spy).not.toHaveBeenCalled();
spy.mockRestore();
});
-test("compute literal expression when variable is json object", () => {
+test("compute literal expression when variable is json object", async () => {
const jsonObject = { hello: "world", subObject: { world: "hello" } };
const variables = new Map([["jsonVariable", jsonObject]]);
- expect(computeExpression("`${jsonVariable}`", variables)).toEqual(
- `{"hello":"world","subObject":{"world":"hello"}}`
- );
- expect(computeExpression("`${jsonVariable.subObject}`", variables)).toEqual(
- `{"world":"hello"}`
- );
+ await expect(
+ computeExpression("`${jsonVariable}`", variables)
+ ).resolves.toEqual(`{"hello":"world","subObject":{"world":"hello"}}`);
+ await expect(
+ computeExpression("`${jsonVariable.subObject}`", variables)
+ ).resolves.toEqual(`{"world":"hello"}`);
});
-test("compute literal expression when object is frozen", () => {
+test("compute literal expression when object is frozen", async () => {
const jsonObject = Object.freeze({
hello: "world",
subObject: { world: "hello" },
});
const variables = new Map([["jsonVariable", jsonObject]]);
- expect(computeExpression("`${jsonVariable.subObject}`", variables)).toEqual(
- `{"world":"hello"}`
- );
+ await expect(
+ computeExpression("`${jsonVariable.subObject}`", variables)
+ ).resolves.toEqual(`{"world":"hello"}`);
});
-test("compute expression does not clone unused variables", () => {
+test("compute expression does not clone unused variables", async () => {
const variables = new Map<string, unknown>([
["usedVariable", 1],
["unusedVariable", Object.freeze({ callback: () => undefined })],
]);
- expect(computeExpression("usedVariable + 1", variables)).toEqual(2);
+ await expect(
+ computeExpression("usedVariable + 1", variables)
+ ).resolves.toEqual(2);
});
-test("compute expression cache reads current variables", () => {
- expect(
+test("compute expression cache reads current variables", async () => {
+ await expect(
computeExpression("cachedVariable", new Map([["cachedVariable", "first"]]))
- ).toEqual("first");
- expect(
+ ).resolves.toEqual("first");
+ await expect(
computeExpression("cachedVariable", new Map([["cachedVariable", "second"]]))
- ).toEqual("second");
+ ).resolves.toEqual("second");
});
-test("compute unset variables as undefined", () => {
- expect(computeExpression(`a`, new Map())).toEqual(undefined);
- expect(computeExpression("`${a}`", new Map())).toEqual("undefined");
+test("compute unset variables as undefined", async () => {
+ await expect(computeExpression(`a`, new Map())).resolves.toEqual(undefined);
+ await expect(computeExpression("`${a}`", new Map())).resolves.toEqual(
+ "undefined"
+ );
});
test("find unset variable names", () => {
@@ -3758,36 +3853,46 @@ describe("resource expression form validation", () => {
[encodeDataVariableId("bodyJson")]: { ok: true },
};
- test("computes expressions against encoded variable scope names", () => {
- expect(computeExpressionWithinScope("apiUrl", scope)).toBe(
+ test("computes expressions against encoded variable scope names", async () => {
+ await expect(computeExpressionWithinScope("apiUrl", scope)).resolves.toBe(
"https://example.com/users"
);
- expect(computeExpressionWithinScope(" ", scope)).toBeUndefined();
+ await expect(
+ computeExpressionWithinScope(" ", scope)
+ ).resolves.toBeUndefined();
});
- test("validates evaluated resource urls", () => {
- expect(validateResourceUrlExpression("apiUrl", scope)).toBe("");
- expect(validateResourceUrlExpression("bodyJson", scope)).toBe(
- "URL expects a string"
- );
- expect(validateResourceUrlExpression("emptyUrl", scope)).toBe(
- "URL is required"
- );
- expect(validateResourceUrlExpression('"not a url"', scope)).toBe(
- "URL is invalid"
- );
- });
-
- test("validates evaluated resource body by body type", () => {
- expect(validateResourceBodyExpression("", "json", scope)).toBe("");
- expect(validateResourceBodyExpression("bodyJson", "json", scope)).toBe("");
- expect(validateResourceBodyExpression("bodyText", "json", scope)).toBe(
- "Expected valid JSON object in body"
- );
- expect(validateResourceBodyExpression("bodyText", "text", scope)).toBe("");
- expect(validateResourceBodyExpression("bodyJson", "text", scope)).toBe(
- "Expected string in body"
+ test("validates evaluated resource urls", async () => {
+ await expect(validateResourceUrlExpression("apiUrl", scope)).resolves.toBe(
+ ""
);
+ await expect(
+ validateResourceUrlExpression("bodyJson", scope)
+ ).resolves.toBe("URL expects a string");
+ await expect(
+ validateResourceUrlExpression("emptyUrl", scope)
+ ).resolves.toBe("URL is required");
+ await expect(
+ validateResourceUrlExpression('"not a url"', scope)
+ ).resolves.toBe("URL is invalid");
+ });
+
+ test("validates evaluated resource body by body type", async () => {
+ await expect(
+ validateResourceBodyExpression("", "json", scope)
+ ).resolves.toBe("");
+ await expect(
+ validateResourceBodyExpression("bodyJson", "json", scope)
+ ).resolves.toBe("");
+ await expect(
+ validateResourceBodyExpression("bodyText", "json", scope)
+ ).resolves.toBe("Expected valid JSON object in body");
+ await expect(
+ validateResourceBodyExpression("bodyText", "text", scope)
+ ).resolves.toBe("");
+ await expect(
+ validateResourceBodyExpression("bodyJson", "text", scope)
+ ).resolves.toBe("Expected string in body");
});
});
diff --git a/packages/project-build/src/runtime/data.ts b/packages/project-build/src/runtime/data.ts
index 96c07c77e6..32ffd93867 100644
--- a/packages/project-build/src/runtime/data.ts
+++ b/packages/project-build/src/runtime/data.ts
@@ -487,7 +487,7 @@ export const replaceDataSourcesInExpression = (
}
};
-export const computeExpression = (
+const evaluateExpression = (
expression: string,
variables: ReadonlyMap<DataSource["name"], unknown>
) => {
@@ -514,29 +514,83 @@ export const computeExpression = (
}
};
-export const computeStringExpression = (
+export type ResolveExpressionDataSource = (
+ dataSourceId: DataSource["id"],
+ value: unknown
+) => unknown | PromiseLike<unknown>;
+
+const resolveExpressionVariables = async ({
+ expression,
+ variables,
+ resolveDataSource,
+}: {
+ expression: string;
+ variables: ReadonlyMap<DataSource["id"], unknown>;
+ resolveDataSource: ResolveExpressionDataSource;
+}) => {
+ const dataSourceIds = new Set<DataSource["id"]>();
+ for (const identifier of getExpressionIdentifiers(expression)) {
+ const dataSourceId = decodeDataVariableId(identifier);
+ if (dataSourceId !== undefined) {
+ dataSourceIds.add(dataSourceId);
+ }
+ }
+ const resolved = new Map(variables);
+ await Promise.all(
+ [...dataSourceIds].map(async (dataSourceId) => {
+ resolved.set(
+ dataSourceId,
+ await resolveDataSource(dataSourceId, variables.get(dataSourceId))
+ );
+ })
+ );
+ return resolved;
+};
+
+export const computeExpression = async (
expression: string,
- variables: ReadonlyMap<DataSource["name"], unknown>
+ variables: ReadonlyMap<DataSource["id"], unknown>,
+ resolveDataSource: ResolveExpressionDataSource = (_dataSourceId, value) =>
+ value
+) =>
+ evaluateExpression(
+ expression,
+ await resolveExpressionVariables({
+ expression,
+ variables,
+ resolveDataSource,
+ })
+ );
+
+export const computeStringExpression = async (
+ expression: string,
+ variables: ReadonlyMap<DataSource["id"], unknown>,
+ resolveDataSource?: ResolveExpressionDataSource
) => {
- const value = computeExpression(expression, variables);
+ const value = await computeExpression(
+ expression,
+ variables,
+ resolveDataSource
+ );
return typeof value === "string" && value !== "" ? value : undefined;
};
-export const computeExpressionWithinScope = (
+export const computeExpressionWithinScope = async (
expression: string,
- scope: Record<string, unknown>
+ scope: Record<string, unknown>,
+ resolveDataSource?: ResolveExpressionDataSource
) => {
if (expression.trim() === "") {
return;
}
- const variables = new Map<DataSource["name"], unknown>();
+ const variables = new Map<DataSource["id"], unknown>();
for (const [name, value] of Object.entries(scope)) {
- const decodedName = decodeDataSourceVariable(name);
- if (decodedName !== undefined) {
- variables.set(decodedName, value);
+ const dataSourceId = decodeDataVariableId(name);
+ if (dataSourceId !== undefined) {
+ variables.set(dataSourceId, value);
}
}
- return computeExpression(expression, variables);
+ return computeExpression(expression, variables, resolveDataSource);
};
const getParentInstanceById = (instances: Instances) => {
@@ -1933,11 +1987,11 @@ export const createResourceFieldsFromResource = (
body: resource.body,
});
-export const validateResourceUrlExpression = (
+export const validateResourceUrlExpression = async (
expression: string,
scope: Record<string, unknown>
) => {
- const value = computeExpressionWithinScope(expression, scope);
+ const value = await computeExpressionWithinScope(expression, scope);
if (typeof value !== "string") {
return "URL expects a string";
}
@@ -1954,7 +2008,7 @@ export const validateResourceUrlExpression = (
export type ResourceBodyInputType = undefined | "text" | "json";
-export const validateResourceBodyExpression = (
+export const validateResourceBodyExpression = async (
expression: string,
bodyType: ResourceBodyInputType,
scope: Record<string, unknown>
@@ -1962,7 +2016,7 @@ export const validateResourceBodyExpression = (
if (expression === "") {
return "";
}
- const value = computeExpressionWithinScope(expression, scope);
+ const value = await computeExpressionWithinScope(expression, scope);
if (bodyType === "json") {
return typeof value === "object" && value !== null
? ""
diff --git a/packages/project-build/src/runtime/pages.test.ts b/packages/project-build/src/runtime/pages.test.ts
index aa90a24cce..4e95aead0a 100644
--- a/packages/project-build/src/runtime/pages.test.ts
+++ b/packages/project-build/src/runtime/pages.test.ts
@@ -2518,9 +2518,9 @@ describe("page settings validation", () => {
).toBe("/folder/post");
});
- test("accumulates duplicate path errors from the general section", () => {
+ test("accumulates duplicate path errors from the general section", async () => {
const pages = createPages();
- const errors = validatePageSettings({
+ const errors = await validatePageSettings({
pages,
pageId: undefined,
values: createPageSettingsValues({ path: "/page" }),
@@ -2530,8 +2530,8 @@ describe("page settings validation", () => {
expect(errors.path).toEqual(["All paths must be unique"]);
});
- test("accumulates auth errors with other field errors", () => {
- const errors = validatePageSettings({
+ test("accumulates auth errors with other field errors", async () => {
+ const errors = await validatePageSettings({
pages: createPages(),
pageId: undefined,
values: createPageSettingsValues({
@@ -2555,24 +2555,26 @@ describe("page settings validation", () => {
});
});
- test("does not require auth when both credentials are empty", () => {
+ test("does not require auth when both credentials are empty", async () => {
expect(
- validatePageSettings({
- pages: createPages(),
- pageId: undefined,
- values: createPageSettingsValues(),
- variableValues: new Map(),
- }).auth
+ (
+ await validatePageSettings({
+ pages: createPages(),
+ pageId: undefined,
+ values: createPageSettingsValues(),
+ variableValues: new Map(),
+ })
+ ).auth
).toBeUndefined();
});
- test("validates only visible document type sections", () => {
+ test("validates only visible document type sections", async () => {
const invalidHtmlMetadata = {
title: `""`,
language: `"not a locale"`,
};
- const textErrors = validatePageSettings({
+ const textErrors = await validatePageSettings({
pages: createPages(),
pageId: undefined,
values: createPageSettingsValues({
@@ -2587,7 +2589,7 @@ describe("page settings validation", () => {
expect(textErrors.language).toBeUndefined();
expect(textErrors.content).toBeDefined();
- const xmlErrors = validatePageSettings({
+ const xmlErrors = await validatePageSettings({
pages: createPages(),
pageId: undefined,
values: createPageSettingsValues({
@@ -2603,8 +2605,8 @@ describe("page settings validation", () => {
expect(xmlErrors.content).toBeUndefined();
});
- test("allows redirect on the home page", () => {
- const errors = validatePageSettings({
+ test("allows redirect on the home page", async () => {
+ const errors = await validatePageSettings({
pages: createPages(),
pageId: "home",
values: createPageSettingsValues({
diff --git a/packages/project-build/src/runtime/pages.ts b/packages/project-build/src/runtime/pages.ts
index d9ab12a5f4..effbb35276 100644
--- a/packages/project-build/src/runtime/pages.ts
+++ b/packages/project-build/src/runtime/pages.ts
@@ -1499,7 +1499,7 @@ export const computePageSettingsPath = (
.replace(/\/+/g, "/");
};
-export const validatePageSettingsGeneralSection = ({
+export const validatePageSettingsGeneralSection = async ({
pages,
pageId,
values,
@@ -1509,12 +1509,16 @@ export const validatePageSettingsGeneralSection = ({
pageId: undefined | Page["id"];
values: PageSettingsValues;
variableValues: Map<string, unknown>;
-}): PageSettingsErrors => {
+}): Promise<PageSettingsErrors> => {
+ const [status, redirect] = await Promise.all([
+ computeExpression(values.status ?? `undefined`, variableValues),
+ computeExpression(values.redirect, variableValues),
+ ]);
const computedValues = {
name: values.name,
path: values.path,
- status: computeExpression(values.status ?? `undefined`, variableValues),
- redirect: computeExpression(values.redirect, variableValues),
+ status,
+ redirect,
documentType: values.documentType,
};
@@ -1585,63 +1589,71 @@ export const validatePageSettingsAuthSection = (
return { auth: authErrors };
};
-export const validatePageSettingsSearchSection = (
+export const validatePageSettingsSearchSection = async (
values: PageSettingsValues,
variableValues: Map<string, unknown>
-): PageSettingsErrors => {
+): Promise<PageSettingsErrors> => {
+ const [title, description, excludePageFromSearch, language] =
+ await Promise.all([
+ computeExpression(values.title, variableValues),
+ computeExpression(values.description, variableValues),
+ computeExpression(values.excludePageFromSearch, variableValues),
+ computeExpression(values.language, variableValues),
+ ]);
const parsedResult = pageSearchSettingsInput.safeParse({
- title:
- computeExpression(values.title, variableValues) ??
- "exclude from validation",
- description: computeExpression(values.description, variableValues),
- excludePageFromSearch: computeExpression(
- values.excludePageFromSearch,
- variableValues
- ),
- language: computeExpression(values.language, variableValues),
+ title: title ?? "exclude from validation",
+ description,
+ excludePageFromSearch,
+ language,
});
return parsedResult.success ? {} : parsedResult.error.flatten().fieldErrors;
};
-export const validatePageSettingsSocialImageSection = (
+export const validatePageSettingsSocialImageSection = async (
values: PageSettingsValues,
variableValues: Map<string, unknown>
-): PageSettingsErrors => {
+): Promise<PageSettingsErrors> => {
+ const socialImageUrl = await computeExpression(
+ values.socialImageUrl,
+ variableValues
+ );
const parsedResult = pageSocialImageSettingsInput.safeParse({
- socialImageUrl: computeExpression(values.socialImageUrl, variableValues),
+ socialImageUrl,
});
return parsedResult.success ? {} : parsedResult.error.flatten().fieldErrors;
};
-export const validatePageSettingsCustomMetadataSection = (
+export const validatePageSettingsCustomMetadataSection = async (
values: PageSettingsValues,
variableValues: Map<string, unknown>
-): PageSettingsErrors => {
- const parsedResult = pageCustomMetadataSettingsInput.safeParse({
- customMetas: values.customMetas.map((item) => ({
+): Promise<PageSettingsErrors> => {
+ const customMetas = await Promise.all(
+ values.customMetas.map(async (item) => ({
property: item.property,
- content: computeExpression(item.content, variableValues),
- })),
+ content: await computeExpression(item.content, variableValues),
+ }))
+ );
+ const parsedResult = pageCustomMetadataSettingsInput.safeParse({
+ customMetas,
});
return parsedResult.success ? {} : parsedResult.error.flatten().fieldErrors;
};
-export const validatePageSettingsTextContentSection = (
+export const validatePageSettingsTextContentSection = async (
values: PageSettingsValues,
variableValues: Map<string, unknown>
-): PageSettingsErrors => {
+): Promise<PageSettingsErrors> => {
if (values.documentType !== "text") {
return {};
}
- const parsedResult = pageTextContentSettingsInput.safeParse({
- content: computeExpression(values.content, variableValues),
- });
+ const content = await computeExpression(values.content, variableValues);
+ const parsedResult = pageTextContentSettingsInput.safeParse({ content });
return parsedResult.success ? {} : parsedResult.error.flatten().fieldErrors;
};
-export const validatePageSettings = ({
+export const validatePageSettings = async ({
pages,
pageId,
values,
@@ -1651,7 +1663,7 @@ export const validatePageSettings = ({
pageId: undefined | Page["id"];
values: PageSettingsValues;
variableValues: Map<string, unknown>;
-}): PageSettingsErrors => {
+}): Promise<PageSettingsErrors> => {
const errors: PageSettingsErrors = {};
const sectionErrors = [
validatePageSettingsGeneralSection({
@@ -1660,7 +1672,7 @@ export const validatePageSettings = ({
values,
variableValues,
}),
- validatePageSettingsAuthSection(values),
+ Promise.resolve(validatePageSettingsAuthSection(values)),
];
if (values.documentType === "html") {
sectionErrors.push(
@@ -1674,7 +1686,8 @@ export const validatePageSettings = ({
validatePageSettingsTextContentSection(values, variableValues)
);
}
- for (const sectionError of sectionErrors) {
+ const resolvedSectionErrors = await Promise.all(sectionErrors);
+ for (const sectionError of resolvedSectionErrors) {
if (sectionError.auth) {
errors.auth = { ...errors.auth, ...sectionError.auth };
}
diff --git a/packages/project-build/src/runtime/search.ts b/packages/project-build/src/runtime/search.ts
index b91d6d73f5..ae561c567a 100644
--- a/packages/project-build/src/runtime/search.ts
+++ b/packages/project-build/src/runtime/search.ts
@@ -1,5 +1,8 @@
import { z } from "zod";
-import { isLiteralExpression } from "@webstudio-is/expression";
+import {
+ isLiteralExpression,
+ parseStringLiteralExpression,
+} from "@webstudio-is/expression";
import { isAssetsResource, type StyleDecl } from "@webstudio-is/sdk";
import { hasTopLevelJsonLdContext } from "@webstudio-is/sdk/runtime";
import { validateJsonLdWithSchemaOrg } from "@webstudio-is/sdk/schema-org";
@@ -8,7 +11,6 @@ import { validateSelector } from "@webstudio-is/css-data";
import * as bcp47 from "bcp-47";
import type { BuilderState } from "../state/builder-state";
import { throwBuilderRuntimeError } from "./errors";
-import { computeExpression } from "./data";
import { listAssets } from "./assets";
import { listCssVariables, listDesignTokens } from "./styles";
import { getInstanceDepths } from "./instances";
@@ -335,8 +337,7 @@ const getStaticString = (expression: string) => {
if (isLiteralExpression(expression) === false) {
return;
}
- const value = computeExpression(expression, new Map());
- return typeof value === "string" ? value : undefined;
+ return parseStringLiteralExpression(expression);
};
export const analyzeProject = (
diff --git a/packages/react-sdk/placeholder.d.ts b/packages/react-sdk/placeholder.d.ts
index 8b08ae3438..18c69009ac 100644
--- a/packages/react-sdk/placeholder.d.ts
+++ b/packages/react-sdk/placeholder.d.ts
@@ -36,13 +36,14 @@ declare module "__CLIENT__" {
declare module "__SERVER__" {
import type { PageMeta, System, ResourceRequest } from "@webstudio-is/sdk";
+ import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources: (props: {
system: System;
resources?: Record<string, any>;
}) => {
- data: Map<string, ResourceRequest>;
- action: Map<string, ResourceRequest>;
+ data: ResourceRequestGraph;
+ action: Map<string, { id: string; outputName: string }>;
contentData?: Map<string, ResourceRequest>;
};
diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts
index 0342cf14ac..9d035a7c35 100644
--- a/packages/sdk/src/index.ts
+++ b/packages/sdk/src/index.ts
@@ -34,6 +34,7 @@ export type {
} from "./component-build";
export * from "./expression";
export * from "./resources-generator";
+export * from "./resource-dependencies";
export * from "./page-meta-generator";
export * from "./url-pattern";
export * from "./link-utils";
diff --git a/packages/sdk/src/resource-dependencies.test.ts b/packages/sdk/src/resource-dependencies.test.ts
new file mode 100644
index 0000000000..1d014ab65b
--- /dev/null
+++ b/packages/sdk/src/resource-dependencies.test.ts
@@ -0,0 +1,243 @@
+import { expect, test } from "vitest";
+import type { Resource } from "./schema/resources";
+import {
+ getPageResourceRootIds,
+ getResourceCycleDataSourceIds,
+ getResourceDataSourceIds,
+ getResourceDependencyIds,
+ getTransitiveResourceIds,
+} from "./resource-dependencies";
+
+test("extracts unique data source dependencies from every resource expression", () => {
+ const resource: Resource = {
+ id: "resource",
+ name: "Resource",
+ method: "post",
+ url: "`https://example.com/${$ws$dataSource$urlId}`",
+ searchParams: [{ name: "query", value: "$ws$dataSource$queryId.value" }],
+ headers: [
+ { name: "authorization", value: "$ws$dataSource$tokenId" },
+ { name: "duplicate", value: "$ws$dataSource$queryId.value" },
+ ],
+ body: `{
+ value: $ws$dataSource$body__DASH__id,
+ literal: "$ws$dataSource$notAnIdentifier"
+ }`,
+ };
+
+ expect(getResourceDataSourceIds(resource)).toEqual(
+ new Set(["urlId", "queryId", "tokenId", "body-id"])
+ );
+});
+
+test("ignores malformed legacy resource expressions", () => {
+ expect(
+ getResourceDataSourceIds({
+ id: "resource",
+ name: "Resource",
+ method: "get",
+ url: "https://example.com/plain-url",
+ headers: [],
+ })
+ ).toEqual(new Set());
+});
+
+test("finds direct resource dependencies", () => {
+ const resource: Resource = {
+ id: "resource",
+ name: "Resource",
+ method: "get",
+ url: "$ws$dataSource$firstDataSource.data.id",
+ headers: [],
+ };
+ const dataSources = new Map([
+ [
+ "firstDataSource",
+ {
+ type: "resource" as const,
+ id: "firstDataSource",
+ name: "First",
+ resourceId: "firstResource",
+ },
+ ],
+ [
+ "variableDataSource",
+ {
+ type: "variable" as const,
+ id: "variableDataSource",
+ name: "Variable",
+ value: { type: "string" as const, value: "value" },
+ },
+ ],
+ ]);
+
+ expect(getResourceDependencyIds({ resource, dataSources })).toEqual(
+ new Set(["firstResource"])
+ );
+});
+
+test("does not load a resource used only by ignored custom metadata", () => {
+ expect(
+ getPageResourceRootIds({
+ page: {
+ rootInstanceId: "body",
+ title: '"Page"',
+ meta: {
+ custom: [
+ {
+ property: " ",
+ content: "$ws$dataSource$resourceDataSource.data.title",
+ },
+ ],
+ },
+ },
+ instances: new Map(),
+ props: new Map(),
+ dataSources: new Map([
+ [
+ "resourceDataSource",
+ {
+ type: "resource",
+ id: "resourceDataSource",
+ name: "Resource",
+ resourceId: "resource",
+ },
+ ],
+ ]),
+ })
+ ).toEqual(new Set());
+});
+
+test("finds transitive resource dependencies for editor cycle prevention", () => {
+ const resources = new Map<string, Resource>([
+ [
+ "firstResource",
+ {
+ id: "firstResource",
+ name: "First",
+ method: "get",
+ url: '"/first"',
+ headers: [],
+ },
+ ],
+ [
+ "secondResource",
+ {
+ id: "secondResource",
+ name: "Second",
+ method: "get",
+ url: "$ws$dataSource$firstDataSource.data.url + $ws$dataSource$tokenDataSource",
+ headers: [],
+ },
+ ],
+ [
+ "thirdResource",
+ {
+ id: "thirdResource",
+ name: "Third",
+ method: "get",
+ url: "$ws$dataSource$secondDataSource.data.url",
+ headers: [],
+ },
+ ],
+ ]);
+ const dataSources = new Map([
+ [
+ "firstDataSource",
+ {
+ type: "resource" as const,
+ id: "firstDataSource",
+ name: "First",
+ resourceId: "firstResource",
+ },
+ ],
+ [
+ "secondDataSource",
+ {
+ type: "resource" as const,
+ id: "secondDataSource",
+ name: "Second",
+ resourceId: "secondResource",
+ },
+ ],
+ [
+ "tokenDataSource",
+ {
+ type: "variable" as const,
+ id: "tokenDataSource",
+ name: "Token",
+ value: { type: "string" as const, value: "secret" },
+ },
+ ],
+ ]);
+
+ expect(
+ getTransitiveResourceIds({
+ resourceId: "thirdResource",
+ resources,
+ dataSources,
+ })
+ ).toEqual(new Set(["secondResource", "firstResource"]));
+});
+
+test("prevents resource cycles through aliases of the edited resource", () => {
+ const resources = new Map<string, Resource>([
+ [
+ "editedResource",
+ {
+ id: "editedResource",
+ name: "Edited",
+ method: "get",
+ url: '"/edited"',
+ headers: [],
+ },
+ ],
+ [
+ "dependentResource",
+ {
+ id: "dependentResource",
+ name: "Dependent",
+ method: "get",
+ url: "$ws$dataSource$editedAlias.data.url",
+ headers: [],
+ },
+ ],
+ ]);
+ const resourceDataSource = {
+ type: "resource" as const,
+ id: "editedDataSource",
+ name: "Edited",
+ resourceId: "editedResource",
+ };
+ const dataSources = new Map([
+ [resourceDataSource.id, resourceDataSource],
+ [
+ "editedAlias",
+ {
+ type: "resource" as const,
+ id: "editedAlias",
+ name: "Edited alias",
+ resourceId: "editedResource",
+ },
+ ],
+ [
+ "dependentDataSource",
+ {
+ type: "resource" as const,
+ id: "dependentDataSource",
+ name: "Dependent",
+ resourceId: "dependentResource",
+ },
+ ],
+ ]);
+
+ expect(
+ getResourceCycleDataSourceIds({
+ resourceDataSource,
+ resources,
+ dataSources,
+ })
+ ).toEqual(
+ new Set(["editedDataSource", "editedAlias", "dependentDataSource"])
+ );
+});
diff --git a/packages/sdk/src/resource-dependencies.ts b/packages/sdk/src/resource-dependencies.ts
new file mode 100644
index 0000000000..f5467538f6
--- /dev/null
+++ b/packages/sdk/src/resource-dependencies.ts
@@ -0,0 +1,170 @@
+import { getExpressionIdentifiers } from "@webstudio-is/expression";
+import { decodeDataVariableId } from "./expression";
+import { findTreeInstanceIds } from "./instances-utils";
+import type { DataSource, DataSources } from "./schema/data-sources";
+import type { Instances } from "./schema/instances";
+import type { Page } from "./schema/pages";
+import type { Props } from "./schema/props";
+import type { Resource } from "./schema/resources";
+
+export const getExpressionDataSourceIds = (
+ expressions: Iterable<string | undefined>
+) => {
+ const dataSourceIds = new Set<DataSource["id"]>();
+ for (const expression of expressions) {
+ if (expression === undefined) {
+ continue;
+ }
+ for (const identifier of getExpressionIdentifiers(expression)) {
+ const dataSourceId = decodeDataVariableId(identifier);
+ if (dataSourceId !== undefined) {
+ dataSourceIds.add(dataSourceId);
+ }
+ }
+ }
+ return dataSourceIds;
+};
+
+/** Returns data sources referenced by any expression in a resource request. */
+export const getResourceDataSourceIds = (resource: Resource) => {
+ return getExpressionDataSourceIds([
+ resource.url,
+ ...(resource.searchParams ?? []).map(({ value }) => value),
+ ...resource.headers.map(({ value }) => value),
+ resource.body,
+ ]);
+};
+
+export const getResourceDependencyIds = ({
+ resource,
+ dataSources,
+}: {
+ resource: Resource;
+ dataSources: DataSources;
+}) => {
+ const dependencyIds = new Set<Resource["id"]>();
+ for (const dataSourceId of getResourceDataSourceIds(resource)) {
+ const dataSource = dataSources.get(dataSourceId);
+ if (dataSource?.type === "resource") {
+ dependencyIds.add(dataSource.resourceId);
+ }
+ }
+ return dependencyIds;
+};
+
+export const getPageResourceRootIds = ({
+ page,
+ instances,
+ props,
+ dataSources,
+}: {
+ page: Pick<Page, "rootInstanceId" | "title" | "meta">;
+ instances: Instances;
+ props: Props;
+ dataSources: DataSources;
+}) => {
+ const instanceIds = findTreeInstanceIds(instances, page.rootInstanceId);
+ const expressions: Array<string | undefined> = [
+ page.title,
+ page.meta?.description,
+ page.meta?.excludePageFromSearch,
+ page.meta?.language,
+ page.meta?.socialImageUrl,
+ page.meta?.status,
+ page.meta?.redirect,
+ page.meta?.content,
+ ...(page.meta?.custom ?? [])
+ .filter(({ property }) => property.trim().length > 0)
+ .map(({ content }) => content),
+ ];
+ for (const prop of props.values()) {
+ if (instances.size > 0 && instanceIds.has(prop.instanceId) === false) {
+ continue;
+ }
+ if (prop.type === "expression") {
+ expressions.push(prop.value);
+ }
+ if (prop.type === "action") {
+ for (const action of prop.value) {
+ expressions.push(action.code);
+ }
+ }
+ }
+ for (const instanceId of instanceIds) {
+ const instance = instances.get(instanceId);
+ if (instance === undefined) {
+ continue;
+ }
+ for (const child of instance.children) {
+ if (child.type === "expression") {
+ expressions.push(child.value);
+ }
+ }
+ }
+ const resourceIds = new Set<Resource["id"]>();
+ for (const dataSourceId of getExpressionDataSourceIds(expressions)) {
+ const dataSource = dataSources.get(dataSourceId);
+ if (dataSource?.type === "resource") {
+ resourceIds.add(dataSource.resourceId);
+ }
+ }
+ return resourceIds;
+};
+
+export const getTransitiveResourceIds = ({
+ resourceId,
+ resources,
+ dataSources,
+}: {
+ resourceId: Resource["id"];
+ resources: ReadonlyMap<Resource["id"], Resource>;
+ dataSources: DataSources;
+}) => {
+ const dependencies = new Set<Resource["id"]>();
+ const visitedResourceIds = new Set<Resource["id"]>();
+ const visit = (currentResourceId: Resource["id"]) => {
+ if (visitedResourceIds.has(currentResourceId)) {
+ return;
+ }
+ visitedResourceIds.add(currentResourceId);
+ const resource = resources.get(currentResourceId);
+ if (resource === undefined) {
+ return;
+ }
+ for (const dependencyId of getResourceDependencyIds({
+ resource,
+ dataSources,
+ })) {
+ dependencies.add(dependencyId);
+ visit(dependencyId);
+ }
+ };
+ visit(resourceId);
+ return dependencies;
+};
+
+export const getResourceCycleDataSourceIds = ({
+ resourceDataSource,
+ resources,
+ dataSources,
+}: {
+ resourceDataSource: Extract<DataSource, { type: "resource" }>;
+ resources: ReadonlyMap<Resource["id"], Resource>;
+ dataSources: DataSources;
+}) => {
+ const dataSourceIds = new Set<DataSource["id"]>([resourceDataSource.id]);
+ for (const candidate of dataSources.values()) {
+ if (
+ candidate.type === "resource" &&
+ (candidate.resourceId === resourceDataSource.resourceId ||
+ getTransitiveResourceIds({
+ resourceId: candidate.resourceId,
+ resources,
+ dataSources,
+ }).has(resourceDataSource.resourceId))
+ ) {
+ dataSourceIds.add(candidate.id);
+ }
+ }
+ return dataSourceIds;
+};
diff --git a/packages/sdk/src/resource-loader.test.ts b/packages/sdk/src/resource-loader.test.ts
index accf4bf887..2f1ea368d9 100644
--- a/packages/sdk/src/resource-loader.test.ts
+++ b/packages/sdk/src/resource-loader.test.ts
@@ -18,9 +18,330 @@ import {
getResourceCacheKey,
isLocalResource,
loadResource,
+ loadResources,
+ type ResourceRequestGraph,
} from "./resource-loader";
import type { ResourceRequest } from "./schema/resources";
+test("resolves request resources after their dependency documents", async () => {
+ const requestedUrls: string[] = [];
+ const fetch = vi.fn<typeof globalThis.fetch>(async (input) => {
+ const url = String(input);
+ requestedUrls.push(url);
+ if (url.endsWith("/posts")) {
+ return Response.json({ id: "author-id" });
+ }
+ return Response.json({ name: "Ada" });
+ });
+ const graph: ResourceRequestGraph = {
+ resources: [
+ {
+ id: "posts",
+ outputName: "Posts",
+ dependencies: [],
+ createRequest: () => ({
+ name: "Posts",
+ method: "get",
+ url: "https://example.com/posts",
+ searchParams: [],
+ headers: [],
+ }),
+ },
+ {
+ id: "author",
+ outputName: "Author",
+ dependencies: ["posts"],
+ createRequest: (documents) => ({
+ name: "Author",
+ method: "get",
+ url: `https://example.com/authors/${
+ (documents.get("posts") as { data: { id: string } }).data.id
+ }`,
+ searchParams: [],
+ headers: [],
+ }),
+ },
+ {
+ id: "unused",
+ outputName: "Unused",
+ dependencies: [],
+ createRequest: () => ({
+ name: "Unused",
+ method: "get",
+ url: "https://example.com/unused",
+ searchParams: [],
+ headers: [],
+ }),
+ },
+ ],
+ rootIds: ["author"],
+ };
+
+ await expect(loadResources(fetch, graph)).resolves.toEqual({
+ Author: {
+ data: { name: "Ada" },
+ ok: true,
+ status: 200,
+ statusText: "",
+ },
+ });
+ expect(requestedUrls).toEqual([
+ "https://example.com/posts",
+ "https://example.com/authors/author-id",
+ ]);
+});
+
+test("applies action request overrides after resolving remote dependencies", async () => {
+ const requests: Array<{ url: string; body: string | null }> = [];
+ const fetch = vi.fn<typeof globalThis.fetch>(async (input, init) => {
+ const url = String(input);
+ requests.push({ url, body: (init?.body as string | undefined) ?? null });
+ return url.endsWith("/author")
+ ? Response.json({ id: "author-123" })
+ : Response.json({ ok: true });
+ });
+ const graph: ResourceRequestGraph = {
+ resources: [
+ {
+ id: "author",
+ outputName: "Author",
+ dependencies: [],
+ createRequest: () => ({
+ name: "Author",
+ method: "get",
+ url: "https://example.com/author",
+ searchParams: [],
+ headers: [],
+ }),
+ },
+ {
+ id: "submit",
+ outputName: "Submit",
+ dependencies: ["author"],
+ createRequest: (documents) => ({
+ name: "Submit",
+ method: "post",
+ url: `https://example.com/submit/${(documents.get("author") as { data: { id: string } }).data.id}`,
+ searchParams: [],
+ headers: [],
+ body: { stale: true },
+ }),
+ },
+ ],
+ rootIds: ["submit"],
+ };
+
+ await expect(
+ loadResources(fetch, graph, undefined, {
+ requestOverrides: new Map([
+ ["submit", { body: { email: "[email protected]" } }],
+ ]),
+ })
+ ).resolves.toEqual({
+ Submit: {
+ data: { ok: true },
+ ok: true,
+ status: 200,
+ statusText: "",
+ },
+ });
+ expect(requests).toEqual([
+ { url: "https://example.com/author", body: null },
+ {
+ url: "https://example.com/submit/author-123",
+ body: JSON.stringify({ email: "[email protected]" }),
+ },
+ ]);
+});
+
+test("runs independent resources concurrently while keeping dependency chains serial", async () => {
+ const independentIds = Array.from(
+ { length: 19 },
+ (_, index) => `independent-${index}`
+ );
+ const initialRequestIds = new Set(["chain-first", ...independentIds]);
+ const requestedUrls: string[] = [];
+ let active = 0;
+ let maximumActive = 0;
+ let initialRequestCount = 0;
+ let releaseInitialRequests = () => {};
+ const initialRequestsReleased = new Promise<void>((resolve) => {
+ releaseInitialRequests = resolve;
+ });
+ let resolveInitialRequestsStarted = () => {};
+ const initialRequestsStarted = new Promise<void>((resolve) => {
+ resolveInitialRequestsStarted = resolve;
+ });
+ const fetch = vi.fn<typeof globalThis.fetch>(async (input) => {
+ const url = String(input);
+ requestedUrls.push(url);
+ active += 1;
+ maximumActive = Math.max(maximumActive, active);
+ const requestId = url.split("/").at(-1);
+ if (requestId !== undefined && initialRequestIds.has(requestId)) {
+ initialRequestCount += 1;
+ if (initialRequestCount === initialRequestIds.size) {
+ resolveInitialRequestsStarted();
+ }
+ await initialRequestsReleased;
+ }
+ const response =
+ requestId === "chain-first"
+ ? Response.json({ id: "chain-document" })
+ : Response.json({ requestId });
+ active -= 1;
+ return response;
+ });
+ const graph: ResourceRequestGraph = {
+ resources: [
+ {
+ id: "chain-first",
+ outputName: "Chain first",
+ dependencies: [],
+ createRequest: () => ({
+ name: "Chain first",
+ method: "get",
+ url: "https://example.com/chain-first",
+ searchParams: [],
+ headers: [],
+ }),
+ },
+ {
+ id: "chain-second",
+ outputName: "Chain second",
+ dependencies: ["chain-first"],
+ createRequest: (documents) => ({
+ name: "Chain second",
+ method: "get",
+ url: `https://example.com/chain-second/${
+ (documents.get("chain-first") as { data: { id: string } }).data.id
+ }`,
+ searchParams: [],
+ headers: [],
+ }),
+ },
+ {
+ id: "chain-third",
+ outputName: "Chain third",
+ dependencies: ["chain-second"],
+ createRequest: () => ({
+ name: "Chain third",
+ method: "get",
+ url: "https://example.com/chain-third",
+ searchParams: [],
+ headers: [],
+ }),
+ },
+ ...independentIds.map((id) => ({
+ id,
+ outputName: id,
+ dependencies: [],
+ createRequest: () => ({
+ name: id,
+ method: "get" as const,
+ url: `https://example.com/${id}`,
+ searchParams: [],
+ headers: [],
+ }),
+ })),
+ ],
+ rootIds: ["chain-third", ...independentIds],
+ };
+
+ const resultPromise = loadResources(fetch, graph);
+ await initialRequestsStarted;
+
+ expect(initialRequestCount).toBe(20);
+ expect(maximumActive).toBe(20);
+ expect(requestedUrls).not.toContain(
+ "https://example.com/chain-second/chain-document"
+ );
+
+ releaseInitialRequests();
+ const result = await resultPromise;
+
+ expect(fetch).toHaveBeenCalledTimes(22);
+ const chainSecondIndex = requestedUrls.indexOf(
+ "https://example.com/chain-second/chain-document"
+ );
+ const chainThirdIndex = requestedUrls.indexOf(
+ "https://example.com/chain-third"
+ );
+ expect(chainSecondIndex).toBeGreaterThanOrEqual(20);
+ expect(chainThirdIndex).toBeGreaterThan(chainSecondIndex);
+ expect(result["Chain third"]).toMatchObject({
+ data: { requestId: "chain-third" },
+ });
+});
+
+test.each(["legacy map", "request graph"] as const)(
+ "bounds concurrent resource requests from a %s",
+ async (inputType) => {
+ let active = 0;
+ let maximumActive = 0;
+ const fetch = vi.fn<typeof globalThis.fetch>(async () => {
+ active += 1;
+ maximumActive = Math.max(maximumActive, active);
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ active -= 1;
+ return Response.json({});
+ });
+ const requests = new Map<string, ResourceRequest>();
+ for (let index = 0; index < 21; index += 1) {
+ requests.set(`resource-${index}`, {
+ name: `Resource ${index}`,
+ method: "get",
+ url: `https://example.com/${index}`,
+ searchParams: [],
+ headers: [],
+ });
+ }
+ const graph: ResourceRequestGraph = {
+ resources: Array.from(requests, ([id, request]) => ({
+ id,
+ outputName: id,
+ dependencies: [],
+ createRequest: () => request,
+ })),
+ rootIds: Array.from(requests.keys()),
+ };
+
+ await loadResources(fetch, inputType === "legacy map" ? requests : graph);
+
+ expect(maximumActive).toBe(20);
+ }
+);
+
+test("preserves structured cancellation results for legacy request maps", async () => {
+ const controller = new AbortController();
+ controller.abort(new Error("cancelled"));
+ const fetch = vi.fn<typeof globalThis.fetch>(async (_input, init) => {
+ init?.signal?.throwIfAborted();
+ return Response.json({});
+ });
+ const request: ResourceRequest = {
+ name: "Resource",
+ method: "get",
+ url: "https://example.com/resource",
+ searchParams: [],
+ headers: [],
+ };
+
+ await expect(
+ loadResources(fetch, new Map([["Resource", request]]), undefined, {
+ signal: controller.signal,
+ })
+ ).resolves.toMatchObject({
+ Resource: {
+ ok: false,
+ data: {
+ error: { code: "REQUEST_CANCELLED" },
+ },
+ status: 499,
+ },
+ });
+});
+
test("builds canonical Assets command URLs", () => {
expect(assetsUploadsApiUrl).toBe("/rest/assets/uploads");
expect(getAssetUploadApiUrl("folder/name.png")).toBe(
@@ -557,6 +878,39 @@ describe("loadResource", () => {
});
});
+ test("preserves the first abort reason when cancellation precedes timeout", async () => {
+ vi.useFakeTimers();
+ const controller = new AbortController();
+ let rejectFetch = () => {};
+ mockFetch.mockImplementation(
+ () =>
+ new Promise((_resolve, reject) => {
+ rejectFetch = () => reject(new DOMException("Aborted", "AbortError"));
+ })
+ );
+ const pending = loadResource(
+ mockFetch,
+ {
+ name: "resource",
+ url: "https://example.com/resource",
+ searchParams: [],
+ method: "get",
+ headers: [],
+ },
+ undefined,
+ { signal: controller.signal, timeoutMs: 100 }
+ );
+
+ controller.abort();
+ await vi.advanceTimersByTimeAsync(100);
+ rejectFetch();
+
+ await expect(pending).resolves.toMatchObject({
+ data: { error: { code: "REQUEST_CANCELLED" } },
+ status: 499,
+ });
+ });
+
test("aborts at the deadline and returns a structured timeout", async () => {
vi.useFakeTimers();
mockFetch.mockImplementation(
@@ -595,6 +949,34 @@ describe("loadResource", () => {
});
});
+ test("times out when fetch ignores its abort signal", async () => {
+ vi.useFakeTimers();
+ mockFetch.mockImplementation(() => new Promise(() => {}));
+ const pending = loadResource(
+ mockFetch,
+ {
+ name: "resource",
+ url: "https://example.com/resource",
+ searchParams: [],
+ method: "get",
+ headers: [],
+ },
+ undefined,
+ { timeoutMs: 100 }
+ );
+ let result: Awaited<typeof pending> | undefined;
+ void pending.then((value) => {
+ result = value;
+ });
+
+ await vi.advanceTimersByTimeAsync(100);
+
+ expect(result).toMatchObject({
+ data: { error: { code: "REQUEST_TIMEOUT" } },
+ status: 504,
+ });
+ });
+
test("returns a safe structured network failure", async () => {
const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});
mockFetch.mockRejectedValue(new Error("secret upstream detail"));
diff --git a/packages/sdk/src/resource-loader.ts b/packages/sdk/src/resource-loader.ts
index e4363fc79b..fdc21a64ed 100644
--- a/packages/sdk/src/resource-loader.ts
+++ b/packages/sdk/src/resource-loader.ts
@@ -1,9 +1,15 @@
import hash from "@emotion/hash";
+import {
+ awaitWithSignal,
+ resolveResources as resolveResourceGraph,
+ type Resource,
+} from "@webstudio-is/content-engine";
import type { ResourceRequest } from "./schema/resources";
import { serializeValue } from "./to-string";
const LOCAL_RESOURCE_PREFIX = "$resources";
const RESOURCE_ERROR_DETAIL_LIMIT = 2000;
+export const resourceLoadConcurrency = 20;
const formatResourceErrorDetail = (data: unknown) => {
let detail = "";
@@ -80,6 +86,25 @@ export type ResourceLoadOptions = {
timeoutMs?: number;
};
+export type ResourceGraphLoadOptions = ResourceLoadOptions & {
+ requestOverrides?: ReadonlyMap<
+ string,
+ Partial<ResourceRequest> & { fetch?: typeof fetch }
+ >;
+};
+
+export type ResourceRequestResource = Readonly<{
+ id: string;
+ outputName: string;
+ dependencies: readonly string[];
+ createRequest: (documents: ReadonlyMap<string, unknown>) => ResourceRequest;
+}>;
+
+export type ResourceRequestGraph = Readonly<{
+ resources: readonly ResourceRequestResource[];
+ rootIds: readonly string[];
+}>;
+
export const createResourceFetchBatchProvider = ({
baseUrl,
shouldBatch,
@@ -265,6 +290,9 @@ export const loadResource = async (
options.timeoutMs === undefined
? undefined
: setTimeout(() => {
+ if (controller.signal.aborted) {
+ return;
+ }
didTimeout = true;
controller.abort();
}, options.timeoutMs);
@@ -302,15 +330,20 @@ export const loadResource = async (
method,
headers: requestHeaders,
};
+ let signal: AbortSignal | undefined;
if (options.signal !== undefined || options.timeoutMs !== undefined) {
- requestInit.signal = controller.signal;
+ signal = controller.signal;
+ requestInit.signal = signal;
}
if (method !== "get" && body !== undefined) {
requestInit.body = serializeValue(body);
}
- const response = await customFetch(href, requestInit);
+ const response = await awaitWithSignal(
+ customFetch(href, requestInit),
+ signal
+ );
- let data = await response.text();
+ let data = await awaitWithSignal(response.text(), signal);
try {
// If it looks like JSON and quacks like JSON, then it probably is JSON.
@@ -373,22 +406,59 @@ export const loadResource = async (
export const loadResources = async (
customFetch: typeof fetch,
- requests: Map<string, ResourceRequest>,
+ requests: Map<string, ResourceRequest> | ResourceRequestGraph,
baseUrl?: string | URL,
- options?: ResourceLoadOptions
+ options?: ResourceGraphLoadOptions
) => {
- return Object.fromEntries(
- await Promise.all(
- Array.from(
- requests,
- async ([name, request]) =>
- [
- name,
- await loadResource(customFetch, request, baseUrl, options),
- ] as const
- )
- )
+ const isLegacyMap = requests instanceof Map;
+ const graph: ResourceRequestGraph = isLegacyMap
+ ? {
+ resources: Array.from(requests, ([name, request]) => ({
+ id: name,
+ outputName: name,
+ dependencies: [],
+ createRequest: () => request,
+ })),
+ rootIds: Array.from(requests.keys()),
+ }
+ : requests;
+ const resources: Resource<unknown>[] = graph.resources.map((resource) => ({
+ id: resource.id,
+ dependencies: resource.dependencies,
+ resolve: ({ documents, signal }) => {
+ const { requestOverrides, ...loadOptions } = options ?? {};
+ const { fetch: requestFetch = customFetch, ...overrides } =
+ requestOverrides?.get(resource.id) ?? {};
+ const request = resource.createRequest(documents);
+ const resolvedRequest = {
+ ...request,
+ ...overrides,
+ };
+ return loadResource(requestFetch, resolvedRequest, baseUrl, {
+ ...loadOptions,
+ signal: signal ?? options?.signal,
+ });
+ },
+ }));
+ const resolved = await resolveResourceGraph({
+ resources,
+ rootIds: graph.rootIds,
+ concurrency: resourceLoadConcurrency,
+ // Legacy maps expose cancellation as a structured transport document.
+ // Graph callers use resolver-level cancellation instead.
+ signal: isLegacyMap ? undefined : options?.signal,
+ });
+ const resourcesById = new Map(
+ graph.resources.map((resource) => [resource.id, resource])
);
+ const output = new Map<string, unknown>();
+ for (const resourceId of graph.rootIds) {
+ const resource = resourcesById.get(resourceId);
+ if (resource !== undefined && resolved.documents.has(resourceId)) {
+ output.set(resource.outputName, resolved.documents.get(resourceId));
+ }
+ }
+ return Object.fromEntries(output);
};
/**
diff --git a/packages/sdk/src/resources-generator.test.tsx b/packages/sdk/src/resources-generator.test.tsx
index 50059e1151..9e0ec83242 100644
--- a/packages/sdk/src/resources-generator.test.tsx
+++ b/packages/sdk/src/resources-generator.test.tsx
@@ -48,23 +48,30 @@ test("generate resources loader", () => {
})
).toMatchInlineSnapshot(`
"import type { System, ResourceRequest } from "@webstudio-is/sdk";
+ import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const resourceName: ResourceRequest = {
- name: "resourceName",
- url: "https://my-json.com",
- searchParams: [
+ const resourceName = (documents: ReadonlyMap<string, unknown>): ResourceRequest => {
+ return {
+ name: "resourceName",
+ url: "https://my-json.com",
+ searchParams: [
+ ],
+ method: "post",
+ headers: [
+ { name: "Content-Type", value: "application/json" },
+ ],
+ body: { body: true },
+ }
+ }
+ const _data: ResourceRequestGraph = {
+ resources: [
+ { id: "resourceId", outputName: "resourceName", dependencies: [], createRequest: resourceName },
],
- method: "post",
- headers: [
- { name: "Content-Type", value: "application/json" },
+ rootIds: [
],
- body: { body: true },
}
- const _data = new Map<string, ResourceRequest>([
- ["resourceName", resourceName],
- ])
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
return { data: _data, action: _action, contentData: _contentData }
}
@@ -72,7 +79,7 @@ test("generate resources loader", () => {
`);
});
-test("selects only Resources used by the resolved dynamic MDX candidate", () => {
+test("selects only resources used by the resolved dynamic MDX candidate", () => {
const generated = generateResources({
scope: createScope(),
page: { rootInstanceId: "body" } as Page,
@@ -131,41 +138,57 @@ test("selects only Resources used by the resolved dynamic MDX candidate", () =>
expect(generated).toContain('_contentData.set("ArticleAPI", ArticleAPI)');
expect(generated).toContain('if (SelectedAsset === "other")');
expect(generated).toContain('_contentData.set("OtherAPI", OtherAPI)');
+ expect(generated).not.toContain('id: "articleResource", outputName:');
+ expect(generated).not.toContain('id: "otherResource", outputName:');
});
-test("does not add dynamic selection inputs to ordinary Resources", () => {
+test("loads a remote dynamic selection input as a graph root", () => {
const generated = generateResources({
scope: createScope(),
page: { rootInstanceId: "body" } as Page,
dataSources: toMap([
{
- id: "sourceVariable",
+ id: "selectedAsset",
scopeInstanceId: "body",
type: "resource",
- name: "Source",
- resourceId: "sourceResource",
+ name: "Selected Asset",
+ resourceId: "selectionResource",
+ },
+ {
+ id: "articleVariable",
+ scopeInstanceId: "article",
+ type: "resource",
+ name: "Article API",
+ resourceId: "articleResource",
},
]),
resources: toMap([
{
- id: "sourceResource",
- name: "Source",
- url: '"https://example.com/source"',
+ id: "selectionResource",
+ name: "Selected Asset",
+ url: '"https://example.com/selection"',
method: "get",
headers: [],
},
{
- id: "dependentResource",
- name: "Dependent",
- url: `${encodeDataSourceVariable("sourceVariable")}.url`,
+ id: "articleResource",
+ name: "Article API",
+ url: '"https://example.com/article"',
method: "get",
headers: [],
},
]),
props: new Map(),
+ contentBlockResourceSelections: [
+ {
+ sourceExpression: `${encodeDataSourceVariable("selectedAsset")}.id`,
+ candidates: [{ assetId: "article", resourceIds: ["articleResource"] }],
+ },
+ ],
});
- expect(generated).not.toContain(" = _props.resources");
+ expect(generated).toContain('rootIds: [\n "selectionResource"');
+ expect(generated).toContain('_props.resources?.["SelectedAsset"]');
});
test("generates a configured Assets request on the standard endpoint", () => {
@@ -241,24 +264,31 @@ test("generate variable and use in resources loader", () => {
})
).toMatchInlineSnapshot(`
"import type { System, ResourceRequest } from "@webstudio-is/sdk";
+ import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
let AccessToken = "my-token"
- const resourceName: ResourceRequest = {
- name: "resourceName",
- url: "https://my-json.com/",
- searchParams: [
+ const resourceName = (documents: ReadonlyMap<string, unknown>): ResourceRequest => {
+ return {
+ name: "resourceName",
+ url: "https://my-json.com/",
+ searchParams: [
+ ],
+ method: "post",
+ headers: [
+ { name: "Authorization", value: "Token " + AccessToken },
+ ],
+ body: { body: true },
+ }
+ }
+ const _data: ResourceRequestGraph = {
+ resources: [
+ { id: "resourceId", outputName: "resourceName", dependencies: [], createRequest: resourceName },
],
- method: "post",
- headers: [
- { name: "Authorization", value: "Token " + AccessToken },
+ rootIds: [
],
- body: { body: true },
}
- const _data = new Map<string, ResourceRequest>([
- ["resourceName", resourceName],
- ])
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
return { data: _data, action: _action, contentData: _contentData }
}
@@ -266,6 +296,182 @@ test("generate variable and use in resources loader", () => {
`);
});
+test("generate dependency-gated resource request factories", () => {
+ const generated = generateResources({
+ scope: createScope(),
+ page: { rootInstanceId: "body" } as Page,
+ dataSources: toMap([
+ {
+ id: "firstDataSource",
+ scopeInstanceId: "body",
+ type: "resource",
+ name: "First",
+ resourceId: "firstResource",
+ },
+ {
+ id: "secondDataSource",
+ scopeInstanceId: "body",
+ type: "resource",
+ name: "Second",
+ resourceId: "secondResource",
+ },
+ ]),
+ resources: toMap([
+ {
+ id: "firstResource",
+ name: "First",
+ method: "get",
+ url: '"https://example.com/first"',
+ headers: [],
+ },
+ {
+ id: "secondResource",
+ name: "Second",
+ method: "get",
+ url: '"https://example.com/second/" + $ws$dataSource$firstDataSource.data.id',
+ headers: [],
+ },
+ ]),
+ props: toMap([
+ {
+ id: "prop",
+ instanceId: "body",
+ name: "data-value",
+ type: "expression",
+ value: "$ws$dataSource$secondDataSource",
+ },
+ ]),
+ });
+
+ expect(generated).toContain('const First_1 = documents.get("firstResource")');
+ expect(generated).toContain("const _data: ResourceRequestGraph");
+ expect(generated).toContain(
+ 'dependencies: ["firstResource"], createRequest: Second'
+ );
+});
+
+test("generates action resources as on-demand graph roots with dependencies", () => {
+ const generated = generateResources({
+ scope: createScope(),
+ page: { rootInstanceId: "body" } as Page,
+ dataSources: toMap([
+ {
+ id: "authorDataSource",
+ scopeInstanceId: "body",
+ type: "resource",
+ name: "Author",
+ resourceId: "authorResource",
+ },
+ ]),
+ resources: toMap([
+ {
+ id: "authorResource",
+ name: "Author",
+ method: "get",
+ url: '"https://example.com/author"',
+ headers: [],
+ },
+ {
+ id: "submitResource",
+ name: "Submit",
+ method: "post",
+ url: '"https://example.com/submit/" + $ws$dataSource$authorDataSource.data.id',
+ headers: [],
+ },
+ ]),
+ props: toMap([
+ {
+ id: "submitAction",
+ instanceId: "body",
+ name: "Submit",
+ type: "resource",
+ value: "submitResource",
+ },
+ ]),
+ });
+
+ expect(generated).toContain(
+ 'const Author_1 = documents.get("authorResource")'
+ );
+ expect(generated).toContain(
+ 'dependencies: ["authorResource"], createRequest: Submit'
+ );
+ expect(generated).toContain(
+ '["Submit", { id: "submitResource", outputName: "Submit" }]'
+ );
+ expect(generated).toContain("rootIds: [\n ]");
+});
+
+test("generates lazy roots only for resource expressions in the page tree", () => {
+ const generated = generateResources({
+ scope: createScope(),
+ page: { rootInstanceId: "body" } as Page,
+ instances: toMap([
+ { id: "body", type: "instance", component: "Body", children: [] },
+ { id: "other", type: "instance", component: "Body", children: [] },
+ ]),
+ dataSources: toMap([
+ {
+ id: "usedDataSource",
+ scopeInstanceId: "body",
+ type: "resource",
+ name: "Used",
+ resourceId: "usedResource",
+ },
+ {
+ id: "unusedDataSource",
+ scopeInstanceId: "other",
+ type: "resource",
+ name: "Unused",
+ resourceId: "unusedResource",
+ },
+ ]),
+ resources: toMap([
+ {
+ id: "usedResource",
+ name: "Used",
+ method: "get",
+ url: '"https://example.com/used"',
+ headers: [],
+ },
+ {
+ id: "unusedResource",
+ name: "Unused",
+ method: "get",
+ url: '"https://example.com/unused"',
+ headers: [],
+ },
+ ]),
+ props: toMap([
+ {
+ id: "usedProp",
+ instanceId: "body",
+ name: "data-used",
+ type: "expression",
+ value: "$ws$dataSource$usedDataSource",
+ },
+ {
+ id: "unusedProp",
+ instanceId: "other",
+ name: "data-unused",
+ type: "expression",
+ value: "$ws$dataSource$unusedDataSource",
+ },
+ {
+ id: "otherPageAction",
+ instanceId: "other",
+ name: "action",
+ type: "resource",
+ value: "usedResource",
+ },
+ ]),
+ });
+
+ expect(generated).toContain("const _data: ResourceRequestGraph");
+ expect(generated).toContain('rootIds: [\n "usedResource",\n ]');
+ expect(generated).not.toContain('["Used", Used]');
+});
+
test("generate page system variable and use in resources loader", () => {
expect(
generateResources({
@@ -304,24 +510,31 @@ test("generate page system variable and use in resources loader", () => {
})
).toMatchInlineSnapshot(`
"import type { System, ResourceRequest } from "@webstudio-is/sdk";
+ import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
const system = _props.system
- const resourceName: ResourceRequest = {
- name: "resourceName",
- url: "https://my-json.com/" + system?.params?.slug,
- searchParams: [
+ const resourceName = (documents: ReadonlyMap<string, unknown>): ResourceRequest => {
+ return {
+ name: "resourceName",
+ url: "https://my-json.com/" + system?.params?.slug,
+ searchParams: [
+ ],
+ method: "post",
+ headers: [
+ { name: "Content-Type", value: "application/json" },
+ ],
+ body: { body: true },
+ }
+ }
+ const _data: ResourceRequestGraph = {
+ resources: [
+ { id: "resourceId", outputName: "resourceName", dependencies: [], createRequest: resourceName },
],
- method: "post",
- headers: [
- { name: "Content-Type", value: "application/json" },
+ rootIds: [
],
- body: { body: true },
}
- const _data = new Map<string, ResourceRequest>([
- ["resourceName", resourceName],
- ])
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
return { data: _data, action: _action, contentData: _contentData }
}
@@ -349,25 +562,33 @@ test("generate global system variable and use in resources loader", () => {
})
).toMatchInlineSnapshot(`
"import type { System, ResourceRequest } from "@webstudio-is/sdk";
+ import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
const system = _props.system
- const MyResource: ResourceRequest = {
- name: "My Resource",
- control: "system",
- url: "https://my-json.com/" + system?.params?.slug,
- searchParams: [
+ const MyResource = (documents: ReadonlyMap<string, unknown>): ResourceRequest => {
+ return {
+ name: "My Resource",
+ control: "system",
+ url: "https://my-json.com/" + system?.params?.slug,
+ searchParams: [
+ ],
+ method: "post",
+ headers: [
+ { name: "Content-Type", value: "application/json" },
+ ],
+ body: { body: true },
+ }
+ }
+ const _data: ResourceRequestGraph = {
+ resources: [
+ { id: "resource:0", outputName: "MyResource", dependencies: [], createRequest: MyResource },
],
- method: "post",
- headers: [
- { name: "Content-Type", value: "application/json" },
+ rootIds: [
+ "resource:0",
],
- body: { body: true },
}
- const _data = new Map<string, ResourceRequest>([
- ["MyResource", MyResource],
- ])
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
return { data: _data, action: _action, contentData: _contentData }
}
@@ -386,11 +607,16 @@ test("generate empty resources loader", () => {
})
).toMatchInlineSnapshot(`
"import type { System, ResourceRequest } from "@webstudio-is/sdk";
+ import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
return { data: _data, action: _action, contentData: _contentData }
}
@@ -438,23 +664,30 @@ test("generate resource loader with search params", () => {
})
).toMatchInlineSnapshot(`
"import type { System, ResourceRequest } from "@webstudio-is/sdk";
+ import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
let term = "my-term"
- const resourceName: ResourceRequest = {
- name: "resourceName",
- url: "https://my-json.com",
- searchParams: [
- { name: "search", value: term },
+ const resourceName = (documents: ReadonlyMap<string, unknown>): ResourceRequest => {
+ return {
+ name: "resourceName",
+ url: "https://my-json.com",
+ searchParams: [
+ { name: "search", value: term },
+ ],
+ method: "get",
+ headers: [
+ ],
+ }
+ }
+ const _data: ResourceRequestGraph = {
+ resources: [
+ { id: "resourceId", outputName: "resourceName", dependencies: [], createRequest: resourceName },
],
- method: "get",
- headers: [
+ rootIds: [
],
}
- const _data = new Map<string, ResourceRequest>([
- ["resourceName", resourceName],
- ])
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
return { data: _data, action: _action, contentData: _contentData }
}
@@ -481,11 +714,16 @@ test("prevent generating unused variables", () => {
})
).toMatchInlineSnapshot(`
"import type { System, ResourceRequest } from "@webstudio-is/sdk";
+ import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
return { data: _data, action: _action, contentData: _contentData }
}
@@ -514,11 +752,16 @@ test("prevent generating unused system variable", () => {
})
).toMatchInlineSnapshot(`
"import type { System, ResourceRequest } from "@webstudio-is/sdk";
+ import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
return { data: _data, action: _action, contentData: _contentData }
}
@@ -526,7 +769,7 @@ test("prevent generating unused system variable", () => {
`);
});
-test("generate action resource without loading a stale data source", () => {
+test("generates action resources as lazy roots without loading stale data", () => {
expect(
generateResources({
scope: createScope(),
@@ -564,21 +807,29 @@ test("generate action resource without loading a stale data source", () => {
})
).toMatchInlineSnapshot(`
"import type { System, ResourceRequest } from "@webstudio-is/sdk";
+ import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const resourceName: ResourceRequest = {
- name: "resourceName",
- url: "https://my-url.com",
- searchParams: [
+ const resourceName = (documents: ReadonlyMap<string, unknown>): ResourceRequest => {
+ return {
+ name: "resourceName",
+ url: "https://my-url.com",
+ searchParams: [
+ ],
+ method: "post",
+ headers: [
+ ],
+ }
+ }
+ const _data: ResourceRequestGraph = {
+ resources: [
+ { id: "resourceId", outputName: "resourceName", dependencies: [], createRequest: resourceName },
],
- method: "post",
- headers: [
+ rootIds: [
],
}
- const _data = new Map<string, ResourceRequest>([
- ])
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
- ["resourceName", resourceName],
+ const _action = new Map<string, { id: string; outputName: string }>([
+ ["resourceName", { id: "resourceId", outputName: "resourceName" }],
])
return { data: _data, action: _action, contentData: _contentData }
}
@@ -605,11 +856,16 @@ test("skip missing resource referenced by data source", () => {
})
).toMatchInlineSnapshot(`
"import type { System, ResourceRequest } from "@webstudio-is/sdk";
+ import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
return { data: _data, action: _action, contentData: _contentData }
}
@@ -636,11 +892,16 @@ test("skip missing resource referenced by action prop", () => {
})
).toMatchInlineSnapshot(`
"import type { System, ResourceRequest } from "@webstudio-is/sdk";
+ import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
- const _data = new Map<string, ResourceRequest>([
- ])
+ const _data: ResourceRequestGraph = {
+ resources: [
+ ],
+ rootIds: [
+ ],
+ }
const _contentData = new Map<string, ResourceRequest>()
- const _action = new Map<string, ResourceRequest>([
+ const _action = new Map<string, { id: string; outputName: string }>([
])
return { data: _data, action: _action, contentData: _contentData }
}
diff --git a/packages/sdk/src/resources-generator.ts b/packages/sdk/src/resources-generator.ts
index 64a724b0ea..2e7112329e 100644
--- a/packages/sdk/src/resources-generator.ts
+++ b/packages/sdk/src/resources-generator.ts
@@ -1,10 +1,77 @@
-import type { DataSources } from "./schema/data-sources";
+import type { DataSource, DataSources } from "./schema/data-sources";
import type { Page } from "./schema/pages";
-import type { Resources } from "./schema/resources";
-import type { Props } from "./schema/props";
+import type { Resource, Resources } from "./schema/resources";
+import type { Prop, Props } from "./schema/props";
import type { Instance, Instances } from "./schema/instances";
import type { Scope } from "./scope";
import { generateExpression, SYSTEM_VARIABLE_ID } from "./expression";
+import { findTreeInstanceIds } from "./instances-utils";
+import {
+ getExpressionDataSourceIds,
+ getPageResourceRootIds,
+ getResourceDependencyIds,
+ getResourceDataSourceIds,
+} from "./resource-dependencies";
+
+const generateResourceRequestFields = ({
+ resource,
+ indent,
+ dataSources,
+ usedDataSources,
+ scope,
+}: {
+ resource: Resource;
+ indent: string;
+ dataSources: DataSources;
+ usedDataSources: DataSources;
+ scope: Scope;
+}) => {
+ let generated = "";
+ generated += `${indent}name: ${JSON.stringify(resource.name)},\n`;
+ if (resource.control !== undefined) {
+ generated += `${indent}control: "${resource.control}",\n`;
+ }
+ const url = generateExpression({
+ expression: resource.url,
+ dataSources,
+ usedDataSources,
+ scope,
+ });
+ generated += `${indent}url: ${url},\n`;
+ generated += `${indent}searchParams: [\n`;
+ for (const searchParam of resource.searchParams ?? []) {
+ const value = generateExpression({
+ expression: searchParam.value,
+ dataSources,
+ usedDataSources,
+ scope,
+ });
+ generated += `${indent} { name: "${searchParam.name}", value: ${value} },\n`;
+ }
+ generated += `${indent}],\n`;
+ generated += `${indent}method: "${resource.method}",\n`;
+ generated += `${indent}headers: [\n`;
+ for (const header of resource.headers) {
+ const value = generateExpression({
+ expression: header.value,
+ dataSources,
+ usedDataSources,
+ scope,
+ });
+ generated += `${indent} { name: "${header.name}", value: ${value} },\n`;
+ }
+ generated += `${indent}],\n`;
+ if (resource.body !== undefined && resource.body.length > 0) {
+ const body = generateExpression({
+ expression: resource.body,
+ dataSources,
+ usedDataSources,
+ scope,
+ });
+ generated += `${indent}body: ${body},\n`;
+ }
+ return generated;
+};
export const generateResources = ({
scope,
@@ -12,6 +79,7 @@ export const generateResources = ({
dataSources,
props,
resources,
+ instances = new Map(),
contentBlockResourceSelections = [],
}: {
scope: Scope;
@@ -19,6 +87,7 @@ export const generateResources = ({
dataSources: DataSources;
props: Props;
resources: Resources;
+ instances?: Instances;
contentBlockResourceSelections?: readonly {
sourceExpression: string;
candidates: readonly {
@@ -28,66 +97,140 @@ export const generateResources = ({
}[];
}) => {
const usedDataSources: DataSources = new Map();
- const contentSelectionDataSourceIds = new Set<string>();
- const generatedResourceIds = new Set(resources.keys());
+ const contentInputDataSourceIds = new Set<string>();
const selectedResourceIds = new Set(
contentBlockResourceSelections.flatMap(({ candidates }) =>
candidates.flatMap(({ resourceIds }) => resourceIds)
)
);
+ const pageInstanceIds = findTreeInstanceIds(instances, page.rootInstanceId);
+ const actionResourceProps = Array.from(props.values()).filter(
+ (prop): prop is Extract<Prop, { type: "resource" }> =>
+ (instances.size === 0 || pageInstanceIds.has(prop.instanceId)) &&
+ prop.type === "resource" &&
+ resources.has(prop.value)
+ );
+ const actionResourceIds = new Set(
+ actionResourceProps.map((prop) => prop.value)
+ );
+ const resourceDataSourceByResourceId = new Map(
+ Array.from(dataSources.values())
+ .filter(
+ (dataSource): dataSource is Extract<DataSource, { type: "resource" }> =>
+ dataSource.type === "resource" && resources.has(dataSource.resourceId)
+ )
+ .map((dataSource) => [dataSource.resourceId, dataSource] as const)
+ );
+ const rootResourceIds = getPageResourceRootIds({
+ page,
+ instances,
+ props,
+ dataSources,
+ });
+ for (const { sourceExpression } of contentBlockResourceSelections) {
+ for (const dataSourceId of getExpressionDataSourceIds([sourceExpression])) {
+ const dataSource = dataSources.get(dataSourceId);
+ if (dataSource?.type === "resource") {
+ rootResourceIds.add(dataSource.resourceId);
+ contentInputDataSourceIds.add(dataSource.id);
+ }
+ }
+ }
+ for (const resourceId of selectedResourceIds) {
+ const resource = resources.get(resourceId);
+ if (resource === undefined) {
+ continue;
+ }
+ for (const dataSourceId of getResourceDataSourceIds(resource)) {
+ const dataSource = dataSources.get(dataSourceId);
+ if (dataSource?.type !== "resource") {
+ continue;
+ }
+ if (selectedResourceIds.has(dataSource.resourceId)) {
+ throw new Error(
+ "Dynamic Content Block Resources cannot depend on another selected Resource"
+ );
+ }
+ rootResourceIds.add(dataSource.resourceId);
+ contentInputDataSourceIds.add(dataSource.id);
+ }
+ }
+ const graphResourceIds = new Set<Resource["id"]>();
+ const resourceDependencies = new Map<Resource["id"], Resource["id"][]>();
+ const addResourceAndDependencies = (resourceId: Resource["id"]) => {
+ if (graphResourceIds.has(resourceId)) {
+ return;
+ }
+ const resource = resources.get(resourceId);
+ if (resource === undefined) {
+ return;
+ }
+ graphResourceIds.add(resourceId);
+ const dependencies = Array.from(
+ getResourceDependencyIds({
+ resource,
+ dataSources,
+ })
+ );
+ resourceDependencies.set(resourceId, dependencies);
+ for (const dependencyId of dependencies) {
+ addResourceAndDependencies(dependencyId);
+ }
+ };
+ for (const dataSource of resourceDataSourceByResourceId.values()) {
+ if (
+ selectedResourceIds.has(dataSource.resourceId) === false &&
+ actionResourceIds.has(dataSource.resourceId) === false
+ ) {
+ addResourceAndDependencies(dataSource.resourceId);
+ }
+ }
+ for (const resourceId of rootResourceIds) {
+ addResourceAndDependencies(resourceId);
+ }
+ for (const resourceId of actionResourceIds) {
+ addResourceAndDependencies(resourceId);
+ }
let generatedRequests = "";
for (const resource of resources.values()) {
- let generatedRequest = "";
- // call resource by bound variable name
const resourceName = scope.getName(resource.id, resource.name);
- generatedRequest += ` const ${resourceName}: ResourceRequest = {\n`;
- generatedRequest += ` name: ${JSON.stringify(resource.name)},\n`;
- if (resource.control !== undefined) {
- generatedRequest += ` control: "${resource.control}",\n`;
+ if (graphResourceIds.has(resource.id)) {
+ const requestDataSources: DataSources = new Map();
+ const fields = generateResourceRequestFields({
+ resource,
+ indent: " ",
+ dataSources,
+ usedDataSources: requestDataSources,
+ scope,
+ });
+ let generatedRequest = ` const ${resourceName} = (documents: ReadonlyMap<string, unknown>): ResourceRequest => {\n`;
+ for (const dataSource of requestDataSources.values()) {
+ usedDataSources.set(dataSource.id, dataSource);
+ if (dataSource.type !== "resource") {
+ continue;
+ }
+ const name = scope.getName(dataSource.id, dataSource.name);
+ generatedRequest += ` const ${name} = documents.get(${JSON.stringify(
+ dataSource.resourceId
+ )})\n`;
+ }
+ generatedRequest += ` return {\n`;
+ generatedRequest += fields;
+ generatedRequest += ` }\n`;
+ generatedRequest += ` }\n`;
+ generatedRequests += generatedRequest;
+ continue;
}
- const url = generateExpression({
- expression: resource.url,
+ generatedRequests += ` const ${resourceName}: ResourceRequest = {\n`;
+ generatedRequests += generateResourceRequestFields({
+ resource,
+ indent: " ",
dataSources,
usedDataSources,
scope,
});
- generatedRequest += ` url: ${url},\n`;
- generatedRequest += ` searchParams: [\n`;
- for (const searchParam of resource.searchParams ?? []) {
- const value = generateExpression({
- expression: searchParam.value,
- dataSources,
- usedDataSources,
- scope,
- });
- generatedRequest += ` { name: "${searchParam.name}", value: ${value} },\n`;
- }
- generatedRequest += ` ],\n`;
- generatedRequest += ` method: "${resource.method}",\n`;
- generatedRequest += ` headers: [\n`;
- for (const header of resource.headers) {
- const value = generateExpression({
- expression: header.value,
- dataSources,
- usedDataSources,
- scope,
- });
- generatedRequest += ` { name: "${header.name}", value: ${value} },\n`;
- }
- generatedRequest += ` ],\n`;
- // prevent computing empty expression
- if (resource.body !== undefined && resource.body.length > 0) {
- const body = generateExpression({
- expression: resource.body,
- dataSources,
- usedDataSources,
- scope,
- });
- generatedRequest += ` body: ${body},\n`;
- }
- generatedRequest += ` }\n`;
- generatedRequests += generatedRequest;
+ generatedRequests += ` }\n`;
}
const generatedContentSelections = contentBlockResourceSelections.map(
@@ -115,7 +258,7 @@ export const generateResources = ({
}
}
for (const dataSource of selectionDataSources.values()) {
- contentSelectionDataSourceIds.add(dataSource.id);
+ contentInputDataSourceIds.add(dataSource.id);
usedDataSources.set(dataSource.id, dataSource);
}
return { source, candidates };
@@ -142,72 +285,104 @@ export const generateResources = ({
}
if (
dataSource.type === "resource" &&
- contentSelectionDataSourceIds.has(dataSource.id)
+ contentInputDataSourceIds.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`;
+ generatedVariables += ` const ${name} = _props.resources?.[${JSON.stringify(
+ resourceName
+ )}]\n`;
}
}
let generated = "";
generated += `import type { System, ResourceRequest } from "@webstudio-is/sdk";\n`;
+ generated += `import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";\n`;
generated += `export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {\n`;
generated += generatedVariables;
generated += generatedRequests;
- const actionResourceIds = new Set<string>();
- for (const prop of props.values()) {
- if (prop.type === "resource" && generatedResourceIds.has(prop.value)) {
- actionResourceIds.add(prop.value);
+ generated += ` const _data: ResourceRequestGraph = {\n`;
+ generated += ` resources: [\n`;
+ for (const resourceId of graphResourceIds) {
+ const resource = resources.get(resourceId);
+ if (resource === undefined) {
+ continue;
}
+ const name = scope.getName(resourceId, resource.name);
+ const dependencies = resourceDependencies.get(resourceId) ?? [];
+ generated += ` { id: ${JSON.stringify(
+ resourceId
+ )}, outputName: ${JSON.stringify(name)}, dependencies: ${JSON.stringify(
+ dependencies
+ )}, createRequest: ${name} },\n`;
}
-
- generated += ` const _data = new Map<string, ResourceRequest>([\n`;
- for (const dataSource of dataSources.values()) {
+ generated += ` ],\n`;
+ generated += ` rootIds: [\n`;
+ for (const resourceId of rootResourceIds) {
if (
- dataSource.type === "resource" &&
- generatedResourceIds.has(dataSource.resourceId) &&
- selectedResourceIds.has(dataSource.resourceId) === false &&
- actionResourceIds.has(dataSource.resourceId) === false
+ graphResourceIds.has(resourceId) &&
+ selectedResourceIds.has(resourceId) === false &&
+ actionResourceIds.has(resourceId) === false
) {
- const name = scope.getName(dataSource.resourceId, dataSource.name);
- generated += ` ["${name}", ${name}],\n`;
+ generated += ` ${JSON.stringify(resourceId)},\n`;
}
}
- generated += ` ])\n`;
+ generated += ` ],\n`;
+ generated += ` }\n`;
+
+ if (
+ [...selectedResourceIds].some((resourceId) =>
+ graphResourceIds.has(resourceId)
+ )
+ ) {
+ generated += ` const _contentDocuments = new Map<string, unknown>([\n`;
+ for (const dataSource of usedDataSources.values()) {
+ if (
+ dataSource.type !== "resource" ||
+ contentInputDataSourceIds.has(dataSource.id) === false
+ ) {
+ continue;
+ }
+ const name = scope.getName(dataSource.id, dataSource.name);
+ generated += ` [${JSON.stringify(dataSource.resourceId)}, ${name}],\n`;
+ }
+ 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`;
+ for (const { source, candidates } of generatedContentSelections) {
+ for (const { assetId, resourceIds } of candidates) {
+ generated += ` if (${source} === ${JSON.stringify(assetId)}) {\n`;
+ for (const resourceId of resourceIds) {
+ const dataSource = resourceDataSourceByResourceId.get(resourceId);
+ if (dataSource === undefined || actionResourceIds.has(resourceId)) {
+ continue;
}
- generated += ` }\n`;
+ const name = scope.getName(resourceId, dataSource.name);
+ const request = graphResourceIds.has(resourceId)
+ ? `${scope.getName(resourceId, resources.get(resourceId)?.name ?? dataSource.name)}(_contentDocuments)`
+ : name;
+ generated += ` _contentData.set(${JSON.stringify(name)}, ${request})\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)) {
- const name = scope.getName(prop.value, prop.name);
- generated += ` ["${name}", ${name}],\n`;
+ generated += ` const _action = new Map<string, { id: string; outputName: string }>([\n`;
+ for (const prop of actionResourceProps) {
+ const resource = resources.get(prop.value);
+ if (resource === undefined || graphResourceIds.has(prop.value) === false) {
+ continue;
}
+ const name = scope.getName(prop.value, prop.name);
+ const outputName = scope.getName(prop.value, resource.name);
+ generated += ` ["${name}", { id: ${JSON.stringify(
+ prop.value
+ )}, outputName: ${JSON.stringify(outputName)} }],\n`;
}
generated += ` ])\n`;