Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
fix: Show all Markdown and Assets query diagnostics (#6308)
Oleg Isonen55920c57c4d3
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.tsxindex 120035ee6b..89e7062d9e 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@@ -1,13 +1,21 @@import { createRoot, type Root } from "react-dom/client";import { act } from "react-dom/test-utils";import { afterEach, expect, test, vi } from "vitest";+import {+ createDefaultStructuredAssetQueryResourceConfiguration,+ type Resource,+} from "@webstudio-is/sdk";import {createAssetQueryJsonSchema,createAssetResourceOpenApi,} from "@webstudio-is/protocol/asset-resource-api";import { AssetQueryForm, __testing__ } from "./asset-query-form";-const { configureAssetQueryDefinition, loadAssetQueryDefinition } = __testing__;+const {+ configureAssetQueryDefinition,+ getAssetQueryConfigurationValidation,+ loadAssetQueryDefinition,+} = __testing__;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }@@ -39,6 +47,199 @@ test("renders a centered message while the OpenAPI description is loading", () =expect(container.textContent).toContain("Loading query editor…");});+test("reports while the query editor is loading", async () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ const onPendingChange = vi.fn();+ let resolveFetch: (response: Response) => void = () => {};++ act(() => {+ root?.render(+ <AssetQueryForm+ scope={{}}+ aliases={new Map()}+ fetchDescription={() =>+ new Promise((resolve) => {+ resolveFetch = resolve;+ })+ }+ onPendingChange={onPendingChange}+ />+ );+ });++ expect(onPendingChange).toHaveBeenLastCalledWith(true);++ await act(async () => {+ resolveFetch(new Response(undefined, { status: 500 }));+ });++ expect(onPendingChange).toHaveBeenLastCalledWith(false);+});++test("preserves and explains an invalid stored Assets query", () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ const body = "({ query: { where: 1 } })";+ const resource: Resource = {+ id: "posts",+ name: "Posts",+ control: "system",+ method: "post",+ url: '"/$resources/assets"',+ headers: [],+ body,+ };++ act(() => {+ root?.render(+ <AssetQueryForm+ resource={resource}+ scope={{}}+ aliases={new Map()}+ fetchDescription={() => new Promise(() => {})}+ />+ );+ });++ expect(container.textContent).toContain(+ "Stored Assets query is invalid: Enter valid filters."+ );+ expect(+ container.querySelector<HTMLInputElement>('input[name="body"]')?.value+ ).toBe(body);+ expect(+ container.querySelector<HTMLInputElement>('input[name="asset-query-valid"]')+ ?.value+ ).toBe("false");+});++test("reports every issue from the shared query validator", () => {+ const configuration =+ createDefaultStructuredAssetQueryResourceConfiguration();++ expect(+ getAssetQueryConfigurationValidation({+ configuration: {+ ...configuration,+ where: {+ all: [+ {+ field: ["size"],+ operator: "gt",+ value: '"large"',+ },+ {+ field: ["extension"],+ operator: "contains",+ value: "{}",+ },+ ],+ },+ },+ scope: {},+ }).issues+ ).toMatchObject([+ {+ code: "INCOMPATIBLE_VALUE",+ path: ["query", "where", "all", "0", "value"],+ },+ {+ code: "INCOMPATIBLE_VALUE",+ path: ["query", "where", "all", "1", "value"],+ },+ ]);+});++test("reports every invalid query value expression", () => {+ const configuration =+ createDefaultStructuredAssetQueryResourceConfiguration();++ expect(+ getAssetQueryConfigurationValidation({+ configuration: {+ ...configuration,+ where: {+ all: [+ { field: ["size"], operator: "gt", value: "(" },+ { field: ["extension"], operator: "eq", value: "}" },+ ],+ },+ limit: "missing(",+ offset: "alsoMissing(",+ },+ scope: {},+ }).issues+ ).toMatchObject([+ {+ code: "INVALID_QUERY_EXPRESSION",+ path: ["query", "where", "all", "0", "value"],+ },+ {+ code: "INVALID_QUERY_EXPRESSION",+ path: ["query", "where", "all", "1", "value"],+ },+ {+ code: "INVALID_QUERY_EXPRESSION",+ path: ["query", "limit"],+ },+ {+ code: "INVALID_QUERY_EXPRESSION",+ path: ["query", "offset"],+ },+ ]);+});++test("uses the loaded field catalog with the shared query validator", () => {+ const configuration =+ createDefaultStructuredAssetQueryResourceConfiguration();+ const definition = {+ version: 1,+ fields: [+ {+ path: ["properties", "score"] as string[],+ label: "score",+ types: ["number"] as string[],+ },+ ],+ operators: [],+ source: { fieldPathSchema: true, controls: [] },+ } as const;++ expect(+ getAssetQueryConfigurationValidation({+ configuration: {+ ...configuration,+ where: {+ field: ["properties", "score"],+ operator: "eq",+ value: '"high"',+ },+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["properties", "missing"]],+ },+ },+ scope: {},+ definition,+ }).issues+ ).toMatchObject([+ {+ severity: "warning",+ code: "INCOMPATIBLE_OBSERVED_VALUE",+ path: ["query", "where", "value"],+ },+ {+ severity: "warning",+ code: "UNOBSERVED_FIELD",+ path: ["query", "output", "fields", "0"],+ },+ ]);+});+test("loads the external query schema declared by OpenAPI", async () => {const openApi = createAssetResourceOpenApi({builderSessionCookieName: "session",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.tsxindex c9b86315a3..f7353c7def 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@@ -3,7 +3,7 @@ import { useStore } from "@nanostores/react";import {createDefaultStructuredAssetQueryResourceConfiguration,createStructuredAssetQueryResourceBody,- parseStructuredAssetQueryResourceBody,+ parseStructuredAssetQueryResourceBodyResult,type Resource,type StructuredAssetQueryFilterBinding,type StructuredAssetQueryResourceConfiguration,@@ -11,7 +11,7 @@ import {import { assetsOpenApiUrl } from "@webstudio-is/sdk/runtime";import {addConfiguredQueryFields,- createQuerySourceCodec,+ isQueryExpression,loadOpenApiQueryDefinition,type QueryDefinition,} from "@webstudio-is/query-builder";@@ -19,6 +19,14 @@ import {getQueryConditions,getQueryFieldKey,} from "@webstudio-is/query-builder/runtime";+import {+ appendAssetFieldPath,+ validateAssetQuery,+ type AssetObservedFieldType,+ type AssetQuerySetupIssue,+ type BuilderAssetFieldCatalog,+} from "@webstudio-is/content-engine";+import { computeExpressionWithinScope } from "@webstudio-is/project-build/runtime";import { Text, theme } from "@webstudio-is/design-system";import { $assets } from "~/shared/sync/data-stores";import { BindableQueryBuilder } from "~/builder/shared/query-builder";@@ -106,30 +114,226 @@ const configureAssetQueryDefinition = ({};};+const createConfigurationIssue = (+ code: string,+ message: string,+ path: string[] = ["query"]+): AssetQuerySetupIssue => ({+ severity: "error",+ code,+ path,+ message,+});++const observedFieldTypes = new Set<AssetObservedFieldType>([+ "null",+ "boolean",+ "number",+ "string",+ "object",+ "array",+]);++const getAssetQueryCatalog = (+ definition: AssetQueryDefinition | undefined+): BuilderAssetFieldCatalog | undefined => {+ if (definition === undefined) {+ return;+ }+ const fields: BuilderAssetFieldCatalog["fields"] = {};+ for (const field of definition.fields) {+ if (field.path[0] !== "properties") {+ continue;+ }+ const types = [...new Set(field.types)]+ .filter((type): type is AssetObservedFieldType =>+ observedFieldTypes.has(type as AssetObservedFieldType)+ )+ .sort();+ if (types.length === 0) {+ continue;+ }+ let catalogPath = "properties";+ for (const segment of field.path.slice(1)) {+ catalogPath = appendAssetFieldPath(catalogPath, segment);+ }+ fields[catalogPath] = {+ queryPath: field.path,+ types,+ occurrences: 1,+ ...(types.length > 1 ? { mixed: true } : {}),+ };+ }+ return {+ format: "webstudio-builder-asset-field-catalog",+ version: 1,+ canonicalRevision: `sha256:${"0".repeat(64)}`,+ documentCount: 1,+ fields,+ };+};++const getAssetQueryConfigurationValidation = ({+ configuration,+ scope,+ definition,+}: {+ configuration: StructuredAssetQueryResourceConfiguration;+ scope: Record<string, unknown>;+ definition?: AssetQueryDefinition;+}): { body?: string; issues: readonly AssetQuerySetupIssue[] } => {+ const issues: AssetQuerySetupIssue[] = [];+ const invalidExpressionPaths = new Set<string>();+ const invalidExpressionPathValues: string[][] = [];+ const markInvalidExpression = (path: string[]) => {+ invalidExpressionPaths.add(JSON.stringify(path));+ invalidExpressionPathValues.push(path);+ };+ const evaluateExpression = (source: string, path: string[]) => {+ if (isQueryExpression(source) === false) {+ markInvalidExpression(path);+ issues.push(+ createConfigurationIssue(+ "INVALID_QUERY_EXPRESSION",+ "Enter a valid query expression.",+ path+ )+ );+ return;+ }+ try {+ return computeExpressionWithinScope(source, scope);+ } catch (error) {+ markInvalidExpression(path);+ issues.push(+ createConfigurationIssue(+ "INVALID_QUERY_EXPRESSION",+ error instanceof Error+ ? error.message+ : "The Assets query expression cannot be evaluated.",+ path+ )+ );+ }+ };+ const evaluateWhere = (+ where: StructuredAssetQueryResourceConfiguration["where"],+ path: string[]+ ): unknown => {+ if ("field" in where) {+ return {+ ...where,+ value: evaluateExpression(where.value, [...path, "value"]),+ };+ }+ if ("all" in where) {+ return {+ 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)])+ ),+ };+ };++ const query = {+ result: configuration.result,+ where: evaluateWhere(configuration.where, ["query", "where"]),+ sort: configuration.sort,+ ...(configuration.result === "many"+ ? {+ limit: evaluateExpression(configuration.limit, ["query", "limit"]),+ offset: evaluateExpression(configuration.offset, ["query", "offset"]),+ }+ : {}),+ output: configuration.output,+ content: configuration.content,+ };+ const validation = validateAssetQuery({+ query,+ catalog: getAssetQueryCatalog(definition),+ });+ issues.push(+ ...validation.issues.filter(+ (issue) =>+ invalidExpressionPaths.has(JSON.stringify(issue.path)) === false &&+ invalidExpressionPathValues.some(+ (invalidPath) =>+ issue.path.length < invalidPath.length &&+ issue.path.every((segment, index) => segment === invalidPath[index])+ ) === false+ )+ );++ if (issues.some(({ severity }) => severity === "error")) {+ return { issues };+ }++ let body: string;+ try {+ body = createStructuredAssetQueryResourceBody(configuration);+ } catch (error) {+ issues.push(+ createConfigurationIssue(+ "INVALID_QUERY_SOURCE",+ error instanceof Error+ ? error.message+ : "The Assets query configuration cannot be saved."+ )+ );+ return { issues };+ }++ return {+ body,+ issues: [+ ...new Map(+ issues.map((issue) => [+ JSON.stringify([issue.code, issue.path, issue.message]),+ issue,+ ])+ ).values(),+ ],+ };+};+export const AssetQueryForm = ({resource,scope,aliases,sourceContainer,fetchDescription = builderFetch,+ onPendingChange,}: {resource?: Resource;scope: Record<string, unknown>;aliases: Map<string, string>;sourceContainer?: Element | null;fetchDescription?: typeof globalThis.fetch;+ onPendingChange?: (pending: boolean) => void;}) => {const assets = useStore($assets);- const initial = useMemo(+ const initialResult = useMemo(() =>- parseStructuredAssetQueryResourceBody(resource?.body) ??- defaultConfiguration,- [resource?.body]+ resource === undefined+ ? ({ success: true, value: defaultConfiguration } as const)+ : parseStructuredAssetQueryResourceBodyResult(resource.body),+ [resource]);+ const initial = initialResult.success+ ? initialResult.value+ : defaultConfiguration;const [configuration, setConfiguration] =useState<StructuredAssetQueryResourceConfiguration>(() =>normalizeConfiguration(initial));+ const [storedConfigurationError, setStoredConfigurationError] = useState<+ string | undefined+ >(() => (initialResult.success ? undefined : initialResult.message));const [baseDefinition, setBaseDefinition] = useState<AssetQueryDefinition>();const [descriptionError, setDescriptionError] = useState<string>();const configuredPaths = useMemo(@@ -157,34 +361,39 @@ export const AssetQueryForm = ({result: configuration.result,});}, [baseDefinition, configuration.result, configuredPaths]);- const configurationError = useMemo(() => {- if (definition === undefined) {- return;- }- if (- (configuration.result === "first" || configuration.result === "last") &&- configuration.sort.length === 0- ) {- return "Add sorting to define which item is first.";- }- try {- createQuerySourceCodec<- string,- StructuredAssetQueryFilterBinding["operator"],- StructuredAssetQueryResourceConfiguration- >(definition).format(configuration);- } catch {- return "Complete every Assets query field.";- }- }, [configuration, definition]);+ const configurationValidation = useMemo(+ () =>+ getAssetQueryConfigurationValidation({+ configuration,+ scope,+ definition: baseDefinition,+ }),+ [baseDefinition, configuration, scope]+ );+ const configurationIssues =+ storedConfigurationError === undefined+ ? configurationValidation.issues+ : [+ createConfigurationIssue(+ "INVALID_STORED_QUERY",+ storedConfigurationError+ ),+ ];+ const configurationHasErrors = configurationIssues.some(+ ({ severity }) => severity === "error"+ );useEffect(() => {setConfiguration(normalizeConfiguration(initial));- }, [initial, resource?.id]);+ setStoredConfigurationError(+ initialResult.success ? undefined : initialResult.message+ );+ }, [initial, initialResult, resource?.id]);const body =- configurationError === undefined- ? createStructuredAssetQueryResourceBody(configuration)+ configurationHasErrors === false &&+ configurationValidation.body !== undefined+ ? configurationValidation.body: (resource?.body ?? "");useEffect(() => {@@ -207,12 +416,19 @@ export const AssetQueryForm = ({};}, [assets, fetchDescription]);+ useEffect(() => {+ onPendingChange?.(+ definition === undefined && descriptionError === undefined+ );+ return () => onPendingChange?.(false);+ }, [definition, descriptionError, onPendingChange]);+return (<><inputtype="hidden"name="asset-query-valid"- value={configurationError === undefined ? "true" : "false"}+ value={configurationHasErrors ? "false" : "true"}/><input type="hidden" name="header-name" value="Content-Type" /><input type="hidden" name="header-value" value='"application/json"' />@@ -235,6 +451,7 @@ export const AssetQueryForm = ({sourceContainer={sourceContainer}sectionPaddingInline={theme.panel.paddingInline}onChange={(value) => {+ setStoredConfigurationError(undefined);setConfiguration(configuration.result === "many" && value.result !== "many"? {@@ -249,16 +466,23 @@ export const AssetQueryForm = ({) : (<CenteredPanelMessage>Loading query editor…</CenteredPanelMessage>)}- {descriptionError === undefined && configurationError !== undefined && (- <Row>- <Text color="destructive">{configurationError}</Text>- </Row>- )}+ {descriptionError === undefined &&+ configurationIssues.map((issue, index) => (+ <Row key={`${issue.code}:${issue.path.join(".")}:${index}`}>+ <Text+ color={issue.severity === "error" ? "destructive" : undefined}+ >+ {issue.path.length === 0 ? "" : `${issue.path.join(".")}: `}+ {issue.message}+ </Text>+ </Row>+ ))}</>);};export const __testing__ = {configureAssetQueryDefinition,+ getAssetQueryConfigurationValidation,loadAssetQueryDefinition,};diff --git a/apps/builder/app/builder/features/settings-panel/content-database-diagnostics-view.test.tsx b/apps/builder/app/builder/features/settings-panel/content-database-diagnostics-view.test.tsxindex ccb928a082..91fb887de2 100644--- a/apps/builder/app/builder/features/settings-panel/content-database-diagnostics-view.test.tsx+++ b/apps/builder/app/builder/features/settings-panel/content-database-diagnostics-view.test.tsx@@ -90,6 +90,38 @@ test("orders collapsible sections and opens only database sizes by default", ()}}value={{scope: "query-preview",+ queryIssues: [+ {+ severity: "warning",+ code: "UNOBSERVED_FIELD",+ path: ["query", "where", "all", "0", "field"],+ message:+ "Asset field properties.subtitle is not currently observed",+ },+ ],+ queryWarnings: [+ "Asset field properties.subtitle is not currently observed",+ ],+ issues: [+ {+ severity: "warning",+ scope: "query",+ phase: "metadata",+ code: "FRONTMATTER_INVALID",+ message: "Invalid YAML at line 3, column 1",+ assetId: "post",+ path: "posts/broken.md",+ line: 3,+ column: 1,+ reference: "#frontmatter/author",+ sourceRange: {+ start: { line: 3, column: 1, offset: 12 },+ end: { line: 3, column: 12, offset: 23 },+ },+ },+ ],+ issueCount: 1,+ issuesTruncated: false,unresolved: {items: [{@@ -127,6 +159,7 @@ test("orders collapsible sections and opens only database sizes by default", ()});const sectionLabels = [+ "Errors and warnings","Database and sizes","Timing","Assets batch work",@@ -137,11 +170,15 @@ test("orders collapsible sections and opens only database sizes by default", ()const triggers = Array.from(container.querySelectorAll<HTMLButtonElement>("button[aria-controls]"));- expect(triggers).toHaveLength(sectionLabels.length);- expect(triggers.map((trigger) => trigger.parentElement?.textContent)).toEqual(- sectionLabels+ const sectionTriggers = triggers.filter((trigger) =>+ sectionLabels.includes(trigger.parentElement?.textContent ?? ""));- expect(triggers.map((trigger) => trigger.dataset.state)).toEqual([+ expect(sectionTriggers).toHaveLength(sectionLabels.length);+ expect(+ sectionTriggers.map((trigger) => trigger.parentElement?.textContent)+ ).toEqual(sectionLabels);+ expect(sectionTriggers.map((trigger) => trigger.dataset.state)).toEqual([+ "open","open","closed","closed",@@ -149,6 +186,26 @@ test("orders collapsible sections and opens only database sizes by default", ()"closed","closed",]);+ const diagnosticTriggers = triggers.filter((trigger) =>+ trigger.getAttribute("aria-label")?.startsWith("Warning: ")+ );+ expect(diagnosticTriggers).toHaveLength(2);+ expect(diagnosticTriggers.map((trigger) => trigger.dataset.state)).toEqual([+ "closed",+ "closed",+ ]);+ expect(container.textContent).toContain("Invalid YAML at line 3, column 1");+ expect(container.textContent).toContain(+ "Asset field properties.subtitle is not currently observed"+ );+ expect(+ diagnosticTriggers[0]?.parentElement?.querySelector(+ 'svg[aria-hidden="true"]'+ )+ ).not.toBeNull();+ expect(container.textContent).not.toContain("posts/broken.md:3:1");+ expect(container.textContent).not.toContain("query.where.all.0.field");+ expect(container.textContent).toContain("0 errors and 2 warnings.");const copyButtons = Array.from(container.querySelectorAll<HTMLButtonElement>('button[aria-label^="Copy "]'));@@ -165,7 +222,7 @@ test("orders collapsible sections and opens only database sizes by default", ()).at(-1);act(() => timingCopyButton?.click());- expect(triggers[1]?.dataset.state).toBe("closed");+ expect(sectionTriggers[2]?.dataset.state).toBe("closed");expect(writeText).toHaveBeenCalledOnce();expect(JSON.parse(writeText.mock.calls[0]?.[0] ?? "")).toEqual({builderRoundTripMs: 150.25,@@ -183,12 +240,30 @@ test("orders collapsible sections and opens only database sizes by default", ()},});+ const firstDiagnosticTitle =+ diagnosticTriggers[0]?.parentElement?.querySelector<HTMLButtonElement>(+ 'button[tabindex="-1"]'+ );+ expect(firstDiagnosticTitle).not.toBeNull();act(() => {- triggers[1]?.click();- triggers[2]?.click();- triggers[5]?.click();+ firstDiagnosticTitle?.click();+ diagnosticTriggers[1]?.click();+ sectionTriggers[2]?.click();+ sectionTriggers[3]?.click();+ sectionTriggers[6]?.click();});+ expect(diagnosticTriggers[0]?.dataset.state).toBe("open");+ expect(container.textContent).toContain("posts/broken.md:3:1");+ expect(container.textContent).toContain("posts/broken.md:3:1–3:12");+ expect(container.textContent).toContain("query.where.all.0.field");+ expect(container.textContent).toContain("UNOBSERVED_FIELD");+ const queryDiagnosticContent = document.getElementById(+ diagnosticTriggers[0]?.getAttribute("aria-controls") ?? ""+ );+ expect(queryDiagnosticContent?.textContent).toBe(+ "LocationQuery · query.where.all.0.fieldReasonAsset field properties.subtitle is not currently observedCodeUNOBSERVED_FIELD"+ );const editor = container.querySelector(".cm-content");expect(editor).not.toBeNull();expect(editor?.getAttribute("aria-readonly")).toBe("true");@@ -210,3 +285,67 @@ test("orders collapsible sections and opens only database sizes by default", ()expect(container.textContent).toContain("Database and sizes");expect(container.querySelectorAll('svg[tabindex="0"]')).toHaveLength(26);});++test("counts and labels query setup errors by their severity", () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ act(() => {+ root?.render(+ <TooltipProvider>+ <ContentDatabaseDiagnostics+ value={{+ scope: "query-preview",+ queryIssues: [+ {+ severity: "error",+ code: "INVALID_LIMIT",+ path: ["query", "limit"],+ message: "Limit must be a positive integer",+ },+ {+ severity: "warning",+ code: "UNOBSERVED_FIELD",+ path: ["query", "sort", "0", "field"],+ message: "The sort field is not currently observed",+ },+ ],+ query: {+ usedBytes: 0,+ maxBytes: 500_000,+ unboundedBytes: 0,+ includedDocumentCount: 0,+ omittedDocumentCount: 0,+ truncated: false,+ },+ database: {+ usedBytes: 0,+ maxBytes: 500_000,+ unboundedBytes: 0,+ includedDocumentCount: 0,+ omittedDocumentCount: 0,+ truncated: false,+ },+ }}+ />+ </TooltipProvider>+ );+ });++ expect(container.textContent).toContain("1 error and 1 warning.");+ expect(container.textContent).toContain(+ "Error · Limit must be a positive integer"+ );+ expect(container.textContent).toContain(+ "The sort field is not currently observed"+ );+ expect(container.textContent).not.toContain("query.limit");+ const diagnosticTriggers = Array.from(+ container.querySelectorAll<HTMLButtonElement>('button[data-state="closed"]')+ ).filter((trigger) =>+ trigger.getAttribute("aria-label")?.match(/^(Error|Warning): /)+ );+ act(() => diagnosticTriggers.forEach((trigger) => trigger.click()));+ expect(container.textContent).toContain("Query · query.limit");+ expect(container.textContent).toContain("Query · query.sort.0.field");+});diff --git a/apps/builder/app/builder/features/settings-panel/content-database-diagnostics.tsx b/apps/builder/app/builder/features/settings-panel/content-database-diagnostics.tsxindex c635dd2e58..e7df9c35f8 100644--- a/apps/builder/app/builder/features/settings-panel/content-database-diagnostics.tsx+++ b/apps/builder/app/builder/features/settings-panel/content-database-diagnostics.tsx@@ -19,8 +19,13 @@ import {import {RequestDiagnosticsRow,RequestDiagnosticsContent,+ RequestDiagnosticDisclosure,RequestDiagnosticsTable,} from "./request-inspector";+import {+ getRequestSourceDiagnosticDetails,+ getRequestSourceDiagnosticLocation,+} from "./request-error-diagnostics";const runtimeContentNote ="Referenced documents fetched from storage at runtime are not included.";@@ -379,6 +384,20 @@ export const ContentDatabaseDiagnostics = ({value.database.omittedDocumentCount === 1 ? "file" : "files"}`;const rows = getContentDatabaseDiagnosticRows(value);+ const queryIssueErrorCount =+ value.queryIssues?.filter(({ severity }) => severity === "error").length ??+ 0;+ const queryIssueWarningCount =+ value.queryIssues === undefined+ ? (value.queryWarnings?.length ?? 0)+ : value.queryIssues.filter(({ severity }) => severity === "warning")+ .length;+ const errorCount =+ (value.issues?.filter(({ severity }) => severity === "error").length ?? 0) ++ queryIssueErrorCount;+ const warningCount =+ (value.issues?.filter(({ severity }) => severity === "warning").length ??+ 0) + queryIssueWarningCount;const databaseAndSizes = {...getPerformanceSizes(performance),scope: value.scope,@@ -387,6 +406,66 @@ export const ContentDatabaseDiagnostics = ({};return (<RequestDiagnosticsContent padded={false}>+ {(value.issues !== undefined && value.issues.length > 0) ||+ (value.queryIssues !== undefined && value.queryIssues.length > 0) ||+ (value.queryWarnings !== undefined && value.queryWarnings.length > 0) ? (+ <DiagnosticsSection+ label="Errors and warnings"+ data={{+ queryIssues: value.queryIssues,+ queryWarnings: value.queryWarnings,+ issues: value.issues,+ }}+ isOpen+ >+ <PanelBanner variant={errorCount > 0 ? "error" : "warning"}>+ <Text>+ {errorCount} {errorCount === 1 ? "error" : "errors"} and{" "}+ {warningCount} {warningCount === 1 ? "warning" : "warnings"}+ {value.issuesTruncated+ ? `; showing the first ${value.issues?.length ?? 0}.`+ : "."}+ </Text>+ </PanelBanner>+ <RequestDiagnosticsTable>+ {value.queryIssues !== undefined+ ? value.queryIssues.map((issue, index) => (+ <RequestDiagnosticDisclosure+ key={`${issue.path.join(".")}:${issue.code}:${index}`}+ severity={issue.severity}+ title={issue.message}+ location={`Query${+ issue.path.length === 0+ ? ""+ : ` · ${issue.path.join(".")}`+ }`}+ reason={issue.message}+ details={[{ label: "Code", value: issue.code }]}+ />+ ))+ : value.queryWarnings?.map((warning, index) => (+ <RequestDiagnosticDisclosure+ key={`query-warning:${index}`}+ severity="warning"+ title={warning}+ location="Query setup"+ reason={warning}+ details={[{ label: "Context", value: "Current query" }]}+ />+ ))}+ {value.issues?.map((issue, index) => (+ <RequestDiagnosticDisclosure+ key={`${issue.scope}:${issue.assetId}:${issue.code}:${index}`}+ severity={issue.severity}+ title={issue.message}+ location={getRequestSourceDiagnosticLocation(issue)}+ reason={issue.reason ?? issue.message}+ details={getRequestSourceDiagnosticDetails(issue)}+ />+ ))}+ </RequestDiagnosticsTable>+ </DiagnosticsSection>+ ) : undefined}<DiagnosticsSectionlabel="Database and sizes"data={databaseAndSizes}diff --git a/apps/builder/app/builder/features/settings-panel/request-error-diagnostics.test.ts b/apps/builder/app/builder/features/settings-panel/request-error-diagnostics.test.tsindex e101d7216e..d1026d3549 100644--- a/apps/builder/app/builder/features/settings-panel/request-error-diagnostics.test.ts+++ b/apps/builder/app/builder/features/settings-panel/request-error-diagnostics.test.ts@@ -1,7 +1,204 @@import { describe, expect, test } from "vitest";-import { getRequestErrorDiagnostics } from "./request-error-diagnostics";+import {+ getRequestErrorDiagnostics,+ getRequestQueryDiagnostics,+ getRequestSourceDiagnosticDetails,+ getRequestSourceDiagnosticLocation,+ getRequestSourceDiagnostics,+} from "./request-error-diagnostics";describe("request error diagnostics", () => {+ test("keeps every structured source diagnostic", () => {+ const diagnostics = getRequestSourceDiagnostics({+ diagnostics: [+ {+ severity: "error",+ scope: "query",+ phase: "source",+ code: "invalid-mdx",+ message: "First error",+ assetId: "one",+ path: "one.mdx",+ line: 2,+ column: 1,+ reference: "#frontmatter/author",+ sourceRange: {+ start: { line: 2, column: 1, offset: 12 },+ end: { line: 2, column: 8, offset: 19 },+ },+ },+ {+ severity: "warning",+ scope: "database",+ phase: "source",+ code: "unsafe-mdx",+ message: "Second warning",+ path: "two.mdx",+ },+ ],+ });+ expect(diagnostics).toEqual([+ {+ severity: "error",+ scope: "query",+ phase: "source",+ code: "invalid-mdx",+ message: "First error",+ assetId: "one",+ path: "one.mdx",+ line: 2,+ column: 1,+ reference: "#frontmatter/author",+ sourceRange: {+ start: { line: 2, column: 1, offset: 12 },+ end: { line: 2, column: 8, offset: 19 },+ },+ },+ {+ severity: "warning",+ scope: "database",+ phase: "source",+ code: "unsafe-mdx",+ message: "Second warning",+ path: "two.mdx",+ },+ ]);+ expect(diagnostics.map(getRequestSourceDiagnosticDetails)).toEqual([+ [+ { label: "Context", value: "Current query" },+ { label: "Phase", value: "Source" },+ { label: "Code", value: "invalid-mdx" },+ { label: "Asset ID", value: "one" },+ { label: "Reference", value: "#frontmatter/author" },+ { label: "Source offsets", value: "12–19" },+ ],+ [+ { label: "Context", value: "Published database" },+ { label: "Phase", value: "Source" },+ { label: "Code", value: "unsafe-mdx" },+ ],+ ]);+ expect(diagnostics.map(getRequestSourceDiagnosticLocation)).toEqual([+ "one.mdx:2:1–2:8",+ "two.mdx",+ ]);+ });++ test("treats API file issues as source diagnostics, not query setup issues", () => {+ const details = {+ issues: [+ {+ severity: "error",+ scope: "query",+ phase: "reference",+ code: "TARGET_NOT_FOUND",+ path: ["content/post.mdx"],+ message: "Referenced author does not exist",+ constraint: "TARGET_NOT_FOUND",+ assetId: "post",+ file: "content/post.mdx",+ reference: "#frontmatter/author",+ nodeType: "mdxJsxFlowElement",+ reason: "missing-reference",+ sourceRange: {+ start: { line: 4, column: 3, offset: 31 },+ end: { line: 4, column: 22, offset: 50 },+ },+ },+ ],+ };++ const diagnostics = getRequestSourceDiagnostics(details);+ expect(diagnostics).toEqual([+ {+ severity: "error",+ scope: "query",+ phase: "reference",+ code: "TARGET_NOT_FOUND",+ message: "Referenced author does not exist",+ assetId: "post",+ path: "content/post.mdx",+ reference: "#frontmatter/author",+ nodeType: "mdxJsxFlowElement",+ reason: "missing-reference",+ sourceRange: {+ start: { line: 4, column: 3, offset: 31 },+ end: { line: 4, column: 22, offset: 50 },+ },+ },+ ]);+ expect(getRequestQueryDiagnostics(details)).toEqual([]);+ expect(getRequestSourceDiagnosticLocation(diagnostics[0])).toBe(+ "content/post.mdx:4:3–4:22"+ );+ expect(getRequestSourceDiagnosticDetails(diagnostics[0])).toEqual([+ { label: "Context", value: "Current query" },+ { label: "Phase", value: "Reference" },+ { label: "Code", value: "TARGET_NOT_FOUND" },+ { label: "Asset ID", value: "post" },+ { label: "Reference", value: "#frontmatter/author" },+ { label: "Node type", value: "mdxJsxFlowElement" },+ { label: "Source offsets", value: "31–50" },+ ]);+ });++ test("keeps every structured query setup error", () => {+ expect(+ getRequestQueryDiagnostics({+ issues: [+ {+ code: "too_small",+ path: ["query", "limit"],+ message: "Too small",+ },+ {+ severity: "warning",+ code: "custom",+ path: ["query", "sort"],+ message: "Sorting is required",+ },+ ],+ })+ ).toEqual([+ {+ severity: "error",+ code: "too_small",+ path: ["query", "limit"],+ message: "Too small",+ },+ {+ severity: "warning",+ code: "custom",+ path: ["query", "sort"],+ message: "Sorting is required",+ },+ ]);+ });++ test("distinguishes diagnostics response schema issues from query issues", () => {+ expect(+ getRequestQueryDiagnostics({+ issues: [+ {+ severity: "error",+ scope: "diagnostics",+ code: "invalid_type",+ path: ["__diagnostics__", "query", "usedBytes"],+ message: "Expected a number",+ },+ ],+ })+ ).toEqual([+ {+ severity: "error",+ context: "diagnostics",+ code: "invalid_type",+ path: ["__diagnostics__", "query", "usedBytes"],+ message: "Expected a number",+ },+ ]);+ });+test("extracts HTTP and structured API error information", () => {expect(getRequestErrorDiagnostics({diff --git a/apps/builder/app/builder/features/settings-panel/request-error-diagnostics.tsx b/apps/builder/app/builder/features/settings-panel/request-error-diagnostics.tsxindex 66280b7667..c5e42994ad 100644--- a/apps/builder/app/builder/features/settings-panel/request-error-diagnostics.tsx+++ b/apps/builder/app/builder/features/settings-panel/request-error-diagnostics.tsx@@ -1,11 +1,12 @@import { PanelBanner, Text } from "@webstudio-is/design-system";import {RequestDiagnosticsContent,+ RequestDiagnosticDisclosure,RequestDiagnosticsRow,RequestDiagnosticsTable,} from "./request-inspector";-type RequestErrorDiagnosticsValue = {+export type RequestErrorDiagnosticsValue = {status?: number;statusText?: string;code?: string;@@ -14,11 +15,143 @@ type RequestErrorDiagnosticsValue = {details?: Record<string, unknown>;};+type SourcePoint = {+ line: number;+ column: number;+ offset?: number;+};++type SourceRange = {+ start: SourcePoint;+ end: SourcePoint;+};++type SourceDiagnostic = {+ severity: "error" | "warning";+ scope?: "query" | "database";+ phase?: "metadata" | "reference" | "source";+ code: string;+ message: string;+ assetId?: string;+ path: string;+ line?: number;+ column?: number;+ reference?: string;+ nodeType?: string;+ reason?: string;+ sourceRange?: SourceRange;+};++type QueryDiagnostic = {+ severity: "error" | "warning";+ context?: "diagnostics";+ code: string;+ path: string[];+ message: string;+};+const asRecord = (value: unknown): Record<string, unknown> | undefined =>typeof value === "object" && value !== null && Array.isArray(value) === false? (value as Record<string, unknown>): undefined;+const getSourcePoint = (value: unknown): SourcePoint | undefined => {+ const point = asRecord(value);+ if (+ typeof point?.line !== "number" ||+ Number.isInteger(point.line) === false ||+ point.line < 1 ||+ typeof point.column !== "number" ||+ Number.isInteger(point.column) === false ||+ point.column < 1 ||+ (point.offset !== undefined &&+ (typeof point.offset !== "number" ||+ Number.isInteger(point.offset) === false ||+ point.offset < 0))+ ) {+ return;+ }+ return {+ line: point.line,+ column: point.column,+ ...(point.offset === undefined ? {} : { offset: point.offset }),+ };+};++const getSourceRange = (value: unknown): SourceRange | undefined => {+ const range = asRecord(value);+ const start = getSourcePoint(range?.start);+ const end = getSourcePoint(range?.end);+ if (start === undefined || end === undefined) {+ return;+ }+ return { start, end };+};++const getSourceDiagnostic = ({+ value,+ path,+ defaultSeverity,+}: {+ value: unknown;+ path: string | undefined;+ defaultSeverity?: SourceDiagnostic["severity"];+}): SourceDiagnostic | undefined => {+ const diagnostic = asRecord(value);+ const severity =+ diagnostic?.severity === "error" || diagnostic?.severity === "warning"+ ? diagnostic.severity+ : defaultSeverity;+ if (+ severity === undefined ||+ typeof diagnostic?.code !== "string" ||+ typeof diagnostic.message !== "string" ||+ path === undefined+ ) {+ return;+ }+ const sourceRange = getSourceRange(diagnostic.sourceRange);+ return {+ severity,+ ...(diagnostic.scope === "query" || diagnostic.scope === "database"+ ? { scope: diagnostic.scope }+ : {}),+ ...(diagnostic.phase === "metadata" ||+ diagnostic.phase === "reference" ||+ diagnostic.phase === "source"+ ? { phase: diagnostic.phase }+ : {}),+ code: diagnostic.code,+ message: diagnostic.message,+ ...(typeof diagnostic.assetId === "string"+ ? { assetId: diagnostic.assetId }+ : {}),+ path,+ ...(typeof diagnostic.line === "number" ? { line: diagnostic.line } : {}),+ ...(typeof diagnostic.column === "number"+ ? { column: diagnostic.column }+ : {}),+ ...(typeof diagnostic.reference === "string"+ ? { reference: diagnostic.reference }+ : {}),+ ...(typeof diagnostic.nodeType === "string"+ ? { nodeType: diagnostic.nodeType }+ : {}),+ ...(typeof diagnostic.reason === "string"+ ? { reason: diagnostic.reason }+ : {}),+ ...(sourceRange === undefined ? {} : { sourceRange }),+ };+};++const isSourceIssue = (issue: Record<string, unknown> | undefined) =>+ typeof issue?.file === "string" ||+ typeof issue?.assetId === "string" ||+ issue?.phase === "metadata" ||+ issue?.phase === "reference" ||+ issue?.phase === "source" ||+ getSourceRange(issue?.sourceRange) !== undefined;+export const getRequestErrorDiagnostics = (value: unknown): RequestErrorDiagnosticsValue | undefined => {@@ -66,39 +199,214 @@ export const getRequestErrorDiagnostics = (const formatDetail = (value: unknown) =>typeof value === "string" ? value : JSON.stringify(value);+export const getRequestSourceDiagnostics = (+ details: Record<string, unknown> | undefined+): SourceDiagnostic[] => {+ const diagnostics = Array.isArray(details?.diagnostics)+ ? details.diagnostics.flatMap((value) => {+ const diagnostic = asRecord(value);+ const parsed = getSourceDiagnostic({+ value,+ path:+ typeof diagnostic?.path === "string" ? diagnostic.path : undefined,+ });+ return parsed === undefined ? [] : [parsed];+ })+ : [];+ const fileIssues = Array.isArray(details?.issues)+ ? details.issues.flatMap((value) => {+ const issue = asRecord(value);+ if (isSourceIssue(issue) === false) {+ return [];+ }+ const issuePath =+ Array.isArray(issue?.path) &&+ issue.path.every((part) => typeof part === "string") &&+ issue.path.length > 0+ ? issue.path.join(".")+ : undefined;+ const parsed = getSourceDiagnostic({+ value,+ path:+ typeof issue?.file === "string"+ ? issue.file+ : (issuePath ??+ (typeof issue?.assetId === "string"+ ? issue.assetId+ : undefined)),+ defaultSeverity: "error",+ });+ return parsed === undefined ? [] : [parsed];+ })+ : [];+ return [...diagnostics, ...fileIssues];+};++export const getRequestQueryDiagnostics = (+ details: Record<string, unknown> | undefined+): QueryDiagnostic[] =>+ Array.isArray(details?.issues)+ ? details.issues.flatMap((value) => {+ const issue = asRecord(value);+ if (isSourceIssue(issue)) {+ return [];+ }+ if (+ typeof issue?.code !== "string" ||+ typeof issue.message !== "string" ||+ (issue.severity !== undefined &&+ issue.severity !== "error" &&+ issue.severity !== "warning") ||+ Array.isArray(issue.path) === false ||+ issue.path.some((part) => typeof part !== "string")+ ) {+ return [];+ }+ return [+ {+ severity: issue.severity === "warning" ? "warning" : "error",+ ...(issue.scope === "diagnostics"+ ? { context: "diagnostics" as const }+ : {}),+ code: issue.code,+ path: issue.path as string[],+ message: issue.message,+ },+ ];+ })+ : [];++export const getRequestSourceDiagnosticDetails = (+ diagnostic: SourceDiagnostic+) => {+ const details: { label: string; value: string }[] = [];+ if (diagnostic.scope !== undefined) {+ details.push({+ label: "Context",+ value:+ diagnostic.scope === "query" ? "Current query" : "Published database",+ });+ }+ if (diagnostic.phase !== undefined) {+ details.push({+ label: "Phase",+ value:+ diagnostic.phase === "metadata"+ ? "Metadata"+ : diagnostic.phase === "reference"+ ? "Reference"+ : "Source",+ });+ }+ details.push({ label: "Code", value: diagnostic.code });+ if (diagnostic.assetId !== undefined) {+ details.push({ label: "Asset ID", value: diagnostic.assetId });+ }+ if (diagnostic.reference !== undefined) {+ details.push({ label: "Reference", value: diagnostic.reference });+ }+ if (diagnostic.nodeType !== undefined) {+ details.push({ label: "Node type", value: diagnostic.nodeType });+ }+ const startOffset = diagnostic.sourceRange?.start.offset;+ const endOffset = diagnostic.sourceRange?.end.offset;+ if (startOffset !== undefined && endOffset !== undefined) {+ details.push({+ label: "Source offsets",+ value: `${startOffset}–${endOffset}`,+ });+ } else if (startOffset !== undefined) {+ details.push({ label: "Source start offset", value: `${startOffset}` });+ } else if (endOffset !== undefined) {+ details.push({ label: "Source end offset", value: `${endOffset}` });+ }+ return details;+};++export const getRequestSourceDiagnosticLocation = (+ diagnostic: SourceDiagnostic+) => {+ if (diagnostic.sourceRange !== undefined) {+ const { start, end } = diagnostic.sourceRange;+ return `${diagnostic.path}:${start.line}:${start.column}–${end.line}:${end.column}`;+ }+ if (diagnostic.line === undefined) {+ return diagnostic.path;+ }+ return `${diagnostic.path}:${diagnostic.line}${+ diagnostic.column === undefined ? "" : `:${diagnostic.column}`+ }`;+};+export const RequestErrorDiagnostics = ({value,}: {value: RequestErrorDiagnosticsValue;-}) => (- <RequestDiagnosticsContent>- <PanelBanner variant="error">- <Text>{value.message}</Text>- </PanelBanner>- <RequestDiagnosticsTable>- {value.status !== undefined && (- <RequestDiagnosticsRow- label="HTTP status"- value={`${value.status}${value.statusText === undefined ? "" : ` ${value.statusText}`}`}- />- )}- {value.code !== undefined && (- <RequestDiagnosticsRow label="Error code" value={value.code} />- )}- <RequestDiagnosticsRow label="Message" value={value.message} />- {value.retryable !== undefined && (- <RequestDiagnosticsRow- label="Retryable"- value={value.retryable ? "Yes" : "No"}- />- )}- {Object.entries(value.details ?? {}).map(([key, detail]) => (- <RequestDiagnosticsRow- key={key}- label={`Details · ${key}`}- value={formatDetail(detail)}- />- ))}- </RequestDiagnosticsTable>- </RequestDiagnosticsContent>-);+}) => {+ const sourceDiagnostics = getRequestSourceDiagnostics(value.details);+ const queryDiagnostics = getRequestQueryDiagnostics(value.details);+ return (+ <RequestDiagnosticsContent>+ <PanelBanner variant="error">+ <Text>{value.message}</Text>+ </PanelBanner>+ <RequestDiagnosticsTable>+ {value.status !== undefined && (+ <RequestDiagnosticsRow+ label="HTTP status"+ value={`${value.status}${+ value.statusText === undefined ? "" : ` ${value.statusText}`+ }`}+ />+ )}+ {value.code !== undefined && (+ <RequestDiagnosticsRow label="Error code" value={value.code} />+ )}+ <RequestDiagnosticsRow label="Message" value={value.message} />+ {sourceDiagnostics.map((diagnostic, index) => (+ <RequestDiagnosticDisclosure+ key={`${diagnostic.path}:${diagnostic.code}:${index}`}+ severity={diagnostic.severity}+ title={diagnostic.message}+ location={getRequestSourceDiagnosticLocation(diagnostic)}+ reason={diagnostic.reason ?? diagnostic.message}+ details={getRequestSourceDiagnosticDetails(diagnostic)}+ />+ ))}+ {queryDiagnostics.map((diagnostic, index) => (+ <RequestDiagnosticDisclosure+ key={`${diagnostic.path.join(".")}:${diagnostic.code}:${index}`}+ severity={diagnostic.severity}+ title={diagnostic.message}+ location={`${+ diagnostic.context === "diagnostics"+ ? "Diagnostics response"+ : "Query"+ }${+ diagnostic.path.length === 0+ ? ""+ : ` · ${diagnostic.path.join(".")}`+ }`}+ reason={diagnostic.message}+ details={[{ label: "Code", value: diagnostic.code }]}+ />+ ))}+ {value.retryable !== undefined && (+ <RequestDiagnosticsRow+ label="Retryable"+ value={value.retryable ? "Yes" : "No"}+ />+ )}+ {Object.entries(value.details ?? {})+ .filter(([key]) => key !== "diagnostics" && key !== "issues")+ .map(([key, detail]) => (+ <RequestDiagnosticsRow+ key={key}+ label={`Details · ${key}`}+ value={formatDetail(detail)}+ />+ ))}+ </RequestDiagnosticsTable>+ </RequestDiagnosticsContent>+ );+};diff --git a/apps/builder/app/builder/features/settings-panel/request-inspector.stories.tsx b/apps/builder/app/builder/features/settings-panel/request-inspector.stories.tsxnew file mode 100644index 0000000000..f59e611fdc--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/request-inspector.stories.tsx@@ -0,0 +1,65 @@+import { Flex, StorySection } from "@webstudio-is/design-system";+import {+ RequestDiagnosticDisclosure,+ RequestDiagnosticsTable,+} from "./request-inspector";++export default {+ title: "Settings panel/Request diagnostics",+ component: RequestDiagnosticDisclosure,+};++const DiagnosticExamples = ({+ defaultOpen,+ width = 816,+}: {+ defaultOpen: boolean;+ width?: number;+}) => (+ <StorySection title={defaultOpen ? "Expanded" : "Collapsed"}>+ <Flex direction="column" gap={5} css={{ width, maxWidth: "100%" }}>+ <RequestDiagnosticsTable>+ <RequestDiagnosticDisclosure+ defaultOpen={defaultOpen}+ severity="warning"+ title='Missing closing "quote at line 3, column 1: published: true ^'+ location="content/articles/broken.md:4:1"+ reason={+ 'Missing closing "quote at line 3, column 1:\n\npublished: true\n\n^'+ }+ details={[+ { label: "Context", value: "Current query" },+ { label: "Phase", value: "Metadata" },+ { label: "Code", value: "FRONTMATTER_INVALID" },+ { label: "Asset ID", value: "RI08dJPedj6XKX0nCJopT" },+ ]}+ />+ <RequestDiagnosticDisclosure+ defaultOpen={defaultOpen}+ severity="error"+ title="Unexpected closing tag in MDX content"+ location="content/articles/broken-component.mdx:18:3"+ reason="Unexpected closing tag in MDX content"+ details={[+ { label: "Context", value: "Current query" },+ { label: "Phase", value: "Source" },+ { label: "Code", value: "INVALID_MDX" },+ { label: "Asset ID", value: "broken-mdx" },+ ]}+ />+ </RequestDiagnosticsTable>+ </Flex>+ </StorySection>+);++export const Collapsed = () => <DiagnosticExamples defaultOpen={false} />;++export const Expanded = () => <DiagnosticExamples defaultOpen />;++export const ExpandedNarrow = () => (+ <DiagnosticExamples defaultOpen width={320} />+);++export const ExpandedDark = () => <DiagnosticExamples defaultOpen />;++ExpandedDark.globals = { colorScheme: "dark" };diff --git a/apps/builder/app/builder/features/settings-panel/request-inspector.test.tsx b/apps/builder/app/builder/features/settings-panel/request-inspector.test.tsxindex 1f6eafd341..2c4ffd356f 100644--- a/apps/builder/app/builder/features/settings-panel/request-inspector.test.tsx+++ b/apps/builder/app/builder/features/settings-panel/request-inspector.test.tsx@@ -91,6 +91,7 @@ test("shows when diagnostics are loading", () => {root?.render(<RequestInspectorpreview={<div>Preview content</div>}+ diagnostics={<div>Partial diagnostics</div>}diagnosticsPending/>);@@ -106,8 +107,55 @@ test("shows when diagnostics are loading", () => {diagnostics?.click();});- expect(container.textContent).toContain("Loading diagnostics...");+ expect(+ container.querySelector('[role="status"]')?.getAttribute("aria-label")+ ).toBe("Loading diagnostics…");+ expect(container.textContent).toContain("Partial diagnostics");expect(container.textContent).not.toContain("No diagnostics available");+ expect(+ container.querySelector('[data-state="active"][aria-busy="true"]')+ ).not.toBeNull();+});++test("shows when query content is loading", () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ act(() => {+ root?.render(+ <RequestInspector+ queryContainerRef={() => {}}+ queryPending+ preview={<div>Preview content</div>}+ />+ );+ });++ expect(+ container.querySelector('[role="status"]')?.getAttribute("aria-label")+ ).toBe("Loading query…");+ expect(+ container.querySelector('[data-state="active"][aria-busy="true"]')+ ).not.toBeNull();+});++test("shows when preview content is loading", () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ act(() => {+ root?.render(+ <RequestInspector preview={<div>Previous preview</div>} previewPending />+ );+ });++ expect(+ container.querySelector('[role="status"]')?.getAttribute("aria-label")+ ).toBe("Loading preview…");+ expect(container.textContent).toContain("Previous preview");+ expect(+ container.querySelector('[data-state="active"][aria-busy="true"]')+ ).not.toBeNull();});test("keeps preview first when no query editor is available", () => {diff --git a/apps/builder/app/builder/features/settings-panel/request-inspector.tsx b/apps/builder/app/builder/features/settings-panel/request-inspector.tsxindex cbc4df9b11..8102b2a0c9 100644--- a/apps/builder/app/builder/features/settings-panel/request-inspector.tsx+++ b/apps/builder/app/builder/features/settings-panel/request-inspector.tsx@@ -1,4 +1,10 @@-import type { ComponentProps, ReactNode, Ref } from "react";+import {+ Fragment,+ useState,+ type ComponentProps,+ type ReactNode,+ type Ref,+} from "react";import {cssVar,Flex,@@ -7,13 +13,17 @@ import {PanelTabsContent,PanelTabsList,PanelTabsTrigger,+ rawTheme,ScrollAreaNative,+ SectionTitle,+ SectionTitleLabel,styled,Text,Tooltip,theme,} from "@webstudio-is/design-system";-import { InfoCircleIcon } from "@webstudio-is/icons";+import { AlertIcon, InfoCircleIcon, SpinnerIcon } from "@webstudio-is/icons";+import { CollapsibleSectionRoot } from "~/builder/shared/collapsible-section";export const clearSettledDiagnosticsKey = (pendingKey: string | undefined,@@ -101,16 +111,118 @@ export const RequestDiagnosticsRow = ({</Grid>);+export const RequestDiagnosticDisclosure = ({+ severity,+ title,+ location,+ reason,+ details,+ defaultOpen = false,+}: {+ severity: "error" | "warning";+ title: string;+ location: string;+ reason: ReactNode;+ details: readonly { label: string; value: ReactNode }[];+ defaultOpen?: boolean;+}) => {+ const [isOpen, setIsOpen] = useState(defaultOpen);+ return (+ <Grid+ css={{+ borderBottom: `1px solid ${cssVar("--border-default")}`,+ "&:last-child": { borderBottom: 0 },+ }}+ >+ <CollapsibleSectionRoot+ isOpen={isOpen}+ onOpenChange={setIsOpen}+ fullWidth+ showSeparator={false}+ trigger={+ <SectionTitle+ aria-label={`${severity === "error" ? "Error" : "Warning"}: ${title}`}+ >+ {severity === "warning" && (+ <AlertIcon+ aria-hidden+ color={cssVar("--foreground-warning")}+ style={{ flexShrink: 0 }}+ />+ )}+ <SectionTitleLabel onClick={() => setIsOpen((value) => !value)}>+ {severity === "error" ? `Error · ${title}` : title}+ </SectionTitleLabel>+ </SectionTitle>+ }+ >+ <Grid+ css={{+ gridTemplateColumns: "max-content minmax(0, 1fr)",+ columnGap: theme.spacing[7],+ rowGap: theme.spacing[3],+ paddingInline: theme.panel.paddingInline,+ paddingTop: theme.spacing[2],+ "& > :nth-child(odd)": { minWidth: theme.spacing[17] },+ "& > :nth-child(even)": {+ minWidth: 0,+ overflowWrap: "anywhere",+ },+ }}+ >+ <Text color="moreSubtle">Location</Text>+ <Text userSelect="text">{location}</Text>+ <Text color="moreSubtle">Reason</Text>+ <Text userSelect="text" css={{ whiteSpace: "pre-wrap" }}>+ {reason}+ </Text>+ {details.map(({ label, value }) => (+ <Fragment key={label}>+ <Text color="moreSubtle">{label}</Text>+ <Text userSelect="text">{value}</Text>+ </Fragment>+ ))}+ </Grid>+ </CollapsibleSectionRoot>+ </Grid>+ );+};++const RequestInspectorLoading = ({ label }: { label: string }) => (+ <Flex+ role="status"+ aria-label={label}+ aria-live="polite"+ direction="column"+ align="center"+ justify="center"+ gap={2}+ css={{+ position: "absolute",+ inset: 0,+ zIndex: 1,+ backgroundColor: cssVar("--background-primary"),+ }}+ >+ <SpinnerIcon size={rawTheme.spacing[15]} />+ <Text color="moreSubtle">{label}</Text>+ </Flex>+);+export const RequestInspector = ({queryContainerRef,preview,diagnostics,+ queryPending = false,+ previewPending = false,diagnosticsPending = false,onDiagnosticsOpen,}: {queryContainerRef?: Ref<HTMLDivElement>;preview: ReactNode;diagnostics?: ReactNode;+ queryPending?: boolean;+ previewPending?: boolean;diagnosticsPending?: boolean;onDiagnosticsOpen?: () => void;}) => (@@ -137,6 +249,7 @@ export const RequestInspector = ({{queryContainerRef !== undefined && (<PanelTabsContentvalue="query"+ aria-busy={queryPending}css={{ flex: 1, position: "relative", overflow: "hidden" }}><div@@ -149,27 +262,30 @@ export const RequestInspector = ({position: "relative",}}/>+ {queryPending && <RequestInspectorLoading label="Loading query…" />}</PanelTabsContent>)}<PanelTabsContentvalue="preview"+ aria-busy={previewPending}css={{ flex: 1, position: "relative", overflow: "hidden" }}>{preview}+ {previewPending && <RequestInspectorLoading label="Loading preview…" />}</PanelTabsContent><PanelTabsContentvalue="diagnostics"+ aria-busy={diagnosticsPending}css={{ flex: 1, position: "relative", overflow: "hidden" }}>{diagnostics ?? (<Flex align="center" justify="center" css={{ height: "100%" }}>- <Text color="moreSubtle">- {diagnosticsPending- ? "Loading diagnostics..."- : "No diagnostics available"}- </Text>+ <Text color="moreSubtle">No diagnostics available</Text></Flex>)}+ {diagnosticsPending && (+ <RequestInspectorLoading label="Loading diagnostics…" />+ )}</PanelTabsContent></PanelTabs>);diff --git a/apps/builder/app/builder/features/settings-panel/resource-diagnostics-view.test.tsx b/apps/builder/app/builder/features/settings-panel/resource-diagnostics-view.test.tsxnew file mode 100644index 0000000000..8111b7c4b2--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/resource-diagnostics-view.test.tsx@@ -0,0 +1,176 @@+import { act } from "react-dom/test-utils";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, expect, test } from "vitest";+import { TooltipProvider } from "@webstudio-is/design-system";+import { ResourceDiagnosticsView } from "./resource-diagnostics-view";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let root: Root | undefined;++afterEach(() => {+ act(() => root?.unmount());+ root = undefined;+ document.body.innerHTML = "";+});++test("shows an explicit empty state when no diagnostics are available", () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ act(() => {+ root?.render(+ <TooltipProvider>+ <ResourceDiagnosticsView />+ </TooltipProvider>+ );+ });++ expect(container.textContent).toContain("No diagnostics available");+});++test("shows every diagnostics response schema issue at its exact path", () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ act(() => {+ root?.render(+ <TooltipProvider>+ <ResourceDiagnosticsView+ diagnosticsRequestError={{+ status: 500,+ code: "INVALID_DIAGNOSTICS_RESPONSE",+ message: "Resource diagnostics response is invalid",+ retryable: true,+ details: {+ issues: [+ {+ severity: "error",+ scope: "diagnostics",+ code: "invalid_value",+ path: ["__diagnostics__", "scope"],+ message: 'Expected "query-preview"',+ },+ {+ severity: "error",+ scope: "diagnostics",+ code: "invalid_type",+ path: ["__diagnostics__", "query", "usedBytes"],+ message: "Expected a number",+ },+ ],+ },+ }}+ />+ </TooltipProvider>+ );+ });++ expect(container.textContent).toContain('Expected "query-preview"');+ expect(container.textContent).toContain("Expected a number");+ expect(container.textContent).not.toContain("__diagnostics__.scope");+ const diagnosticTriggers = Array.from(+ container.querySelectorAll<HTMLButtonElement>('button[data-state="closed"]')+ );+ expect(diagnosticTriggers).toHaveLength(2);+ for (const trigger of diagnosticTriggers) {+ expect(+ trigger.parentElement?.parentElement?.querySelector(+ "[data-diagnostics-info]"+ )+ ).toBeNull();+ }+ act(() => diagnosticTriggers.forEach((trigger) => trigger.click()));+ expect(container.textContent).toContain(+ "Diagnostics response · __diagnostics__.scope"+ );+ expect(container.textContent).toContain(+ "Diagnostics response · __diagnostics__.query.usedBytes"+ );+});++test("shows every detailed diagnostic instead of the ordinary preview error", () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ act(() => {+ root?.render(+ <TooltipProvider>+ <ResourceDiagnosticsView+ requestError={{+ status: 500,+ code: "INTERNAL_ERROR",+ message: "Asset query preview failed",+ retryable: true,+ }}+ diagnostics={{+ scope: "query-preview",+ issues: [+ {+ severity: "warning",+ scope: "query",+ phase: "source",+ code: "FRONTMATTER_INVALID",+ message: "Markdown frontmatter contains invalid YAML",+ assetId: "broken",+ path: "content/broken.md",+ line: 4,+ column: 1,+ },+ {+ severity: "error",+ scope: "query",+ phase: "source",+ code: "invalid-mdx",+ message: "Unexpected closing tag",+ assetId: "broken-mdx",+ path: "content/broken.mdx",+ line: 8,+ column: 3,+ },+ ],+ query: {+ usedBytes: 100,+ maxBytes: 1000,+ unboundedBytes: 100,+ includedDocumentCount: 1,+ omittedDocumentCount: 0,+ truncated: false,+ },+ database: {+ usedBytes: 100,+ maxBytes: 1000,+ unboundedBytes: 100,+ includedDocumentCount: 1,+ omittedDocumentCount: 0,+ truncated: false,+ },+ }}+ />+ </TooltipProvider>+ );+ });++ expect(container.textContent).toContain(+ "Markdown frontmatter contains invalid YAML"+ );+ expect(container.textContent).toContain("Error · Unexpected closing tag");+ expect(container.textContent).not.toContain("content/broken.md:4:1");+ const diagnosticTriggers = Array.from(+ container.querySelectorAll<HTMLButtonElement>('button[data-state="closed"]')+ );+ expect(diagnosticTriggers).toHaveLength(2);+ for (const trigger of diagnosticTriggers) {+ expect(+ trigger.parentElement?.parentElement?.querySelector(+ "[data-diagnostics-info]"+ )+ ).toBeNull();+ }+ act(() => diagnosticTriggers.forEach((trigger) => trigger.click()));+ expect(container.textContent).toContain("content/broken.md:4:1");+ expect(container.textContent).toContain("content/broken.mdx:8:3");+ expect(container.textContent).not.toContain("Asset query preview failed");+});diff --git a/apps/builder/app/builder/features/settings-panel/resource-diagnostics-view.tsx b/apps/builder/app/builder/features/settings-panel/resource-diagnostics-view.tsxnew file mode 100644index 0000000000..d59ce9e926--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/resource-diagnostics-view.tsx@@ -0,0 +1,46 @@+import type { AssetQueryPreviewDiagnostics } from "@webstudio-is/content-engine";+import { Flex, Text } from "@webstudio-is/design-system";+import type { ResourcePerformance } from "~/shared/resource-diagnostics";+import {+ ContentDatabaseDiagnostics,+ ResourcePerformanceDiagnostics,+} from "./content-database-diagnostics";+import {+ RequestErrorDiagnostics,+ type RequestErrorDiagnosticsValue,+} from "./request-error-diagnostics";++export const ResourceDiagnosticsView = ({+ requestError,+ diagnosticsRequestError,+ diagnostics,+ performance,+}: {+ requestError?: RequestErrorDiagnosticsValue;+ diagnosticsRequestError?: RequestErrorDiagnosticsValue;+ diagnostics?: AssetQueryPreviewDiagnostics;+ performance?: ResourcePerformance;+}) => {+ if (diagnosticsRequestError !== undefined) {+ return <RequestErrorDiagnostics value={diagnosticsRequestError} />;+ }+ if (diagnostics !== undefined) {+ return (+ <ContentDatabaseDiagnostics+ value={diagnostics}+ performance={performance}+ />+ );+ }+ if (requestError !== undefined) {+ return <RequestErrorDiagnostics value={requestError} />;+ }+ if (performance !== undefined) {+ return <ResourcePerformanceDiagnostics value={performance} />;+ }+ return (+ <Flex align="center" justify="center" css={{ height: "100%" }}>+ <Text color="moreSubtle">No diagnostics available</Text>+ </Flex>+ );+};diff --git a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx b/apps/builder/app/builder/features/settings-panel/resource-panel.tsxindex bfe1c7265c..3665f5e49b 100644--- a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx@@ -834,14 +834,35 @@ export const ResourceForm = forwardRef<});ResourceForm.displayName = "ResourceForm";+type SystemResourceFormProps = {+ variable?: DataSource;+ querySourceContainer?: Element | null;+ onQueryActiveChange?: (active: boolean) => void;+ onQueryPendingChange?: (pending: boolean) => void;+};++const AssetQueryLoadingFallback = ({+ onPendingChange,+}: {+ onPendingChange?: (pending: boolean) => void;+}) => {+ useEffect(() => {+ onPendingChange?.(true);+ return () => onPendingChange?.(false);+ }, [onPendingChange]);+ return <CenteredPanelMessage>Loading query editor…</CenteredPanelMessage>;+};+export const SystemResourceForm = forwardRef<undefined | PanelApi,- {- variable?: DataSource;- querySourceContainer?: Element | null;- onQueryActiveChange?: (active: boolean) => void;- }->(({ variable, querySourceContainer, onQueryActiveChange }, ref) => {+ SystemResourceFormProps+>((props, ref) => {+ const {+ variable,+ querySourceContainer,+ onQueryActiveChange,+ onQueryPendingChange,+ } = props;const { scope, aliases } = useResourceScope({ variable });const resources = useStore($resources);const { allowDynamicData } = useStore($permissions);@@ -888,8 +909,11 @@ export const SystemResourceForm = forwardRef<localResource.value === JSON.stringify(assetsResourceUrl);useEffect(() => {onQueryActiveChange?.(isAssetsResource);- return () => onQueryActiveChange?.(false);- }, [isAssetsResource, onQueryActiveChange]);+ return () => {+ onQueryActiveChange?.(false);+ onQueryPendingChange?.(false);+ };+ }, [isAssetsResource, onQueryActiveChange, onQueryPendingChange]);useImperativeHandle(ref, () => ({save: (formData) => {if (formData.get("asset-query-valid") === "false") {@@ -961,7 +985,7 @@ export const SystemResourceForm = forwardRef<{isAssetsResource && (<Suspensefallback={- <CenteredPanelMessage>Loading query editor…</CenteredPanelMessage>+ <AssetQueryLoadingFallback onPendingChange={onQueryPendingChange} />}><AssetQueryForm@@ -969,6 +993,7 @@ export const SystemResourceForm = forwardRef<scope={scope}aliases={aliases}sourceContainer={querySourceContainer}+ onPendingChange={onQueryPendingChange}/></Suspense>)}diff --git a/apps/builder/app/builder/features/settings-panel/variable-popover.test.ts b/apps/builder/app/builder/features/settings-panel/variable-popover.test.tsnew file mode 100644index 0000000000..89bf881009--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/variable-popover.test.ts@@ -0,0 +1,17 @@+import { expect, test } from "vitest";+import { __testing__ } from "./variable-popover";++const { getReloadableResourceFormData } = __testing__;++test("blocks resource loads while the visible Assets query is invalid", () => {+ const form = document.createElement("form");+ const queryValidity = document.createElement("input");+ queryValidity.name = "asset-query-valid";+ queryValidity.value = "false";+ form.appendChild(queryValidity);++ expect(getReloadableResourceFormData(form)).toBeUndefined();++ queryValidity.value = "true";+ expect(getReloadableResourceFormData(form)).toBeInstanceOf(FormData);+});diff --git a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx b/apps/builder/app/builder/features/settings-panel/variable-popover.tsxindex 005af9a25e..6d03d8f763 100644--- a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx+++ b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx@@ -15,7 +15,7 @@ import {useCallback,useMemo,} from "react";-import { CopyIcon, RefreshIcon, UpgradeIcon } from "@webstudio-is/icons";+import { CopyIcon, RefreshIcon } from "@webstudio-is/icons";import {Box,Button,@@ -30,14 +30,11 @@ import {InputErrorsTooltip,InputField,Label,- Link,- PanelBanner,ProChip,ScrollArea,Select,SplitView,Switch,- Text,TextArea,Tooltip,theme,@@ -89,7 +86,9 @@ import {import { generateCurl } from "./curl";import {$hasPendingResources,+ $pendingResourceKeys,$resourceDiagnosticsCache,+ $resourceDiagnosticsErrorCache,$resourcePerformanceCache,$resourcesCache,computeResourceRequest,@@ -103,15 +102,12 @@ import {clearSettledDiagnosticsKey,RequestInspector,} from "./request-inspector";-import {- ContentDatabaseDiagnostics,- ResourcePerformanceDiagnostics,-} from "./content-database-diagnostics";import {getRequestErrorDiagnostics,RequestErrorDiagnostics,} from "./request-error-diagnostics";import type { ResourcePerformance } from "~/shared/resource-diagnostics";+import { ResourceDiagnosticsView } from "./resource-diagnostics-view";const NameField = ({variable,@@ -552,6 +548,7 @@ const VariablePanelForm = forwardRef<onValueChange: (value: unknown) => void;querySourceContainer: Element | null;onQueryActiveChange: (active: boolean) => void;+ onQueryPendingChange: (pending: boolean) => void;}>((@@ -563,33 +560,12 @@ const VariablePanelForm = forwardRef<onValueChange,querySourceContainer,onQueryActiveChange,+ onQueryPendingChange,},ref) => {- const { allowDynamicData } = useStore($permissions);-- const isResource =- variableType === "resource" ||- variableType === "graphql-resource" ||- variableType === "system-resource";- const requiresUpgrade = allowDynamicData === false && isResource;return (<>- {requiresUpgrade && (- <PanelBanner>- <Text>Resource fetching is part of the CMS functionality.</Text>- <Flex align="center" gap={1}>- <UpgradeIcon />- <Link- color="inherit"- target="_blank"- href="https://webstudio.is/pricing"- >- Upgrade to Pro- </Link>- </Flex>- </PanelBanner>- )}<Flexdirection="column"css={{@@ -664,6 +640,7 @@ const VariablePanelForm = forwardRef<variable={variable}querySourceContainer={querySourceContainer}onQueryActiveChange={onQueryActiveChange}+ onQueryPendingChange={onQueryPendingChange}/>)}</Flex>@@ -686,6 +663,7 @@ const VariablePreview = ({variableValue,onLoadData,queryActive,+ queryPending,queryContainerRef,}: {variable?: DataSource;@@ -693,6 +671,7 @@ const VariablePreview = ({variableValue: unknown;onLoadData: () => void;queryActive: boolean;+ queryPending: boolean;queryContainerRef: (element: HTMLDivElement | null) => void;}) => {const [pendingDiagnosticsKey, setPendingDiagnosticsKey] = useState<string>();@@ -701,15 +680,20 @@ const VariablePreview = ({variableType === "graphql-resource" ||variableType === "system-resource";const hasPendingResources = useStore($hasPendingResources);+ const pendingResourceKeys = useStore($pendingResourceKeys);const resources = useStore($resources);const variableValues = useStore($instanceVariableValues);const resourcesCache = useStore($resourcesCache);const resourceDiagnosticsCache = useStore($resourceDiagnosticsCache);+ const resourceDiagnosticsErrorCache = useStore(+ $resourceDiagnosticsErrorCache+ );const resourcePerformanceCache = useStore($resourcePerformanceCache);const resourceScope = useResourceScope({ variable });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") {@@ -741,6 +725,7 @@ const VariablePreview = ({computedResourceKey = resourceKey;computedValue = resourcesCache.get(resourceKey);resourceDiagnostics = resourceDiagnosticsCache.get(resourceKey);+ resourceDiagnosticsError = resourceDiagnosticsErrorCache.get(resourceKey);resourcePerformance = resourcePerformanceCache.get(resourceKey);}}@@ -756,7 +741,7 @@ const VariablePreview = ({onChange: () => {},onChangeComplete: () => {},};- const preview = (+ const previewContent = (<Gridalign="stretch"css={{@@ -786,13 +771,27 @@ const VariablePreview = ({</Grid>);if (isResource === false) {- return preview;+ return previewContent;}const requestErrorDiagnostics = getRequestErrorDiagnostics(computedValue);+ const diagnosticsRequestError = getRequestErrorDiagnostics(+ resourceDiagnosticsError+ );+ const preview =+ requestErrorDiagnostics === undefined ? (+ previewContent+ ) : (+ <RequestErrorDiagnostics value={requestErrorDiagnostics} />+ );return (<RequestInspectorqueryContainerRef={queryActive ? queryContainerRef : undefined}preview={preview}+ queryPending={queryPending}+ previewPending={+ computedResourceKey !== undefined &&+ pendingResourceKeys.has(computedResourceKey)+ }onDiagnosticsOpen={computedResourceRequest !== undefined &&isAssetsResourceRequest(computedResourceRequest) &&@@ -809,21 +808,14 @@ const VariablePreview = ({}: undefined}- diagnosticsPending={- pendingDiagnosticsKey === computedResourceKey &&- resourceDiagnostics === undefined- }+ diagnosticsPending={pendingDiagnosticsKey === computedResourceKey}diagnostics={- requestErrorDiagnostics !== undefined ? (- <RequestErrorDiagnostics value={requestErrorDiagnostics} />- ) : resourceDiagnostics !== undefined ? (- <ContentDatabaseDiagnostics- value={resourceDiagnostics}- performance={resourcePerformance}- />- ) : resourcePerformance !== undefined ? (- <ResourcePerformanceDiagnostics value={resourcePerformance} />- ) : undefined+ <ResourceDiagnosticsView+ requestError={requestErrorDiagnostics}+ diagnosticsRequestError={diagnosticsRequestError}+ diagnostics={resourceDiagnostics}+ performance={resourcePerformance}+ />}/>);@@ -841,6 +833,7 @@ const VariablePopoverContent = ({const hasPendingResources = useStore($hasPendingResources);const panelRef = useRef<undefined | PanelApi>(undefined);const [queryActive, setQueryActive] = useState(false);+ const [queryPending, setQueryPending] = useState(false);const [querySourceContainer, setQuerySourceContainer] =useState<HTMLDivElement | null>(null);const queryContainerRef = useCallback(@@ -905,7 +898,10 @@ const VariablePopoverContent = ({const resourceScope = useResourceScope({ variable });const reloadData = () => {- const formData = new FormData(formRef.current ?? undefined);+ const formData = getReloadableResourceFormData(formRef.current);+ if (formData === undefined) {+ return;+ }const resource = createResourceValueFromFormData({id: variable?.id ?? "new",formData,@@ -987,6 +983,7 @@ const VariablePopoverContent = ({onValueChange={setValue}querySourceContainer={querySourceContainer}onQueryActiveChange={setQueryActive}+ onQueryPendingChange={setQueryPending}/></fieldset></form>@@ -999,6 +996,7 @@ const VariablePopoverContent = ({variableValue={value}onLoadData={reloadData}queryActive={queryActive}+ queryPending={queryPending}queryContainerRef={queryContainerRef}/>}@@ -1116,4 +1114,12 @@ export const VariablePopoverTrigger = ({VariablePopoverTrigger.displayName = "VariablePopoverTrigger";-undefined;+const getReloadableResourceFormData = (form: HTMLFormElement | null) => {+ const formData = new FormData(form ?? undefined);+ if (formData.get("asset-query-valid") === "false") {+ return;+ }+ return formData;+};++export const __testing__ = { getReloadableResourceFormData };diff --git a/apps/builder/app/builder/features/text-file-editor/mdx-editor-lint.test.ts b/apps/builder/app/builder/features/text-file-editor/mdx-editor-lint.test.tsindex 077b81cae8..98fea9c260 100644--- a/apps/builder/app/builder/features/text-file-editor/mdx-editor-lint.test.ts+++ b/apps/builder/app/builder/features/text-file-editor/mdx-editor-lint.test.ts@@ -27,6 +27,7 @@ test("decorates the exact unsupported MDX source range", async () => {from: 8,to: 18,severity: "warning",+ source: "unsafe-mdx",message: "Executable MDX expressions are not supported",},]);diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx b/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsxindex 6ed5cf378c..bb38f73b6d 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@@ -42,8 +42,10 @@ import {} from "@webstudio-is/icons";import {formatAssetName,+ inspectMdxAssetSource,MdxAuthoredContentConflictError,} from "@webstudio-is/project-build/runtime";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";import {getAssetUrl,getPagePath,@@ -57,6 +59,7 @@ import {$assets,$pages,$props,+ readBuilderStateStores,} from "~/shared/sync/data-stores";import { $authPermit } from "~/shared/nano-states";import { AssetManager } from "~/builder/shared/asset-manager";@@ -470,22 +473,31 @@ export const TextFileEditor = ({asset.projectId !== undefined? getAssetContentBridge().getContentSession?.(asset.projectId): undefined;- const semanticDiagnostics = useMemo(- () =>- Array.from(externalContentRoots.values()).flatMap((root) =>- root.identity?.assetId === assetId &&- (root.projectId === undefined || root.projectId === asset?.projectId)- ? (root.diagnostics ?? [])- : []- ),- [asset?.projectId, assetId, externalContentRoots]- );const languageExtensions = useMemo(- () =>- asset === undefined- ? []- : getTextFileEditorExtensions(asset, semanticDiagnostics),- [asset, semanticDiagnostics]+ () => {+ // The state reader below is intentionally refreshed when its external+ // Content Block context changes.+ void externalContentRoots;+ if (asset === undefined) {+ return [];+ }+ if (isMdxFileAsset(asset) === false || asset.projectId === undefined) {+ return getTextFileEditorExtensions(asset);+ }+ const projectId = asset.projectId;+ return getTextFileEditorExtensions(asset, [], async ({ source }) =>+ inspectMdxAssetSource({+ source,+ assetId,+ state: readBuilderStateStores(),+ metas: componentMetas,+ projectId,+ })+ );+ },+ // Recreate the linter after a Content Block is materialized or refreshed so+ // contextual template and content-model diagnostics are recalculated.+ [asset, assetId, externalContentRoots]);useEffect(() => {diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts b/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.tsindex f0764bf367..091af28cc4 100644--- a/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts+++ b/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts@@ -6,7 +6,7 @@ import {} from "@webstudio-is/sdk";import {getTextFileEditorExtensions,- getMdxEditorDiagnostics,+ getTextFileEditorDiagnostics,getMdxPersistenceFeedback,isMarkdownAsset,normalizeTextFileContent,@@ -23,7 +23,7 @@ describe("text file assets", () => {expect(isTextFileAsset({ format: "pdf" })).toBe(false);});- test.each(["md", "js", "css", "json", "html", "xml", "svg"])(+ test.each(["js", "css", "json", "html", "xml", "svg"])("uses the available CodeMirror language for %s",(format) => {expect(getTextFileEditorExtensions({ format })).toHaveLength(1);@@ -42,7 +42,7 @@ describe("text file assets", () => {expect(getTextFileEditorExtensions({ format })).toHaveLength(language === undefined || language === "plain"? 0- : format === "mdx"+ : format === "md" || format === "mdx"? 4: 1);@@ -86,20 +86,39 @@ describe("text file assets", () => {test("reports MDX diagnostics at parser source ranges", async () => {await expect(- getMdxEditorDiagnostics("# Kept\n\n{danger()}\n")+ getTextFileEditorDiagnostics({+ source: "# Kept\n\n{danger()}\n",+ format: "mdx",+ })).resolves.toEqual([{from: 8,to: 18,severity: "warning",+ source: "unsafe-mdx",message: "Executable MDX expressions are not supported",},]);});+ test("reports every Markdown frontmatter error inline", async () => {+ await expect(+ getTextFileEditorDiagnostics({+ source: "---\na: 1\na: 2\nb: 1\nb: 2\n---\n",+ format: "md",+ })+ ).resolves.toMatchObject([+ { from: 9, to: 10, severity: "warning" },+ { from: 19, to: 20, severity: "warning" },+ ]);+ });+test("reports unrecoverable MDX without blocking the source", async () => {const source = "# Kept\n\n<ws.element";- const diagnostics = await getMdxEditorDiagnostics(source);+ const diagnostics = await getTextFileEditorDiagnostics({+ source,+ format: "mdx",+ });expect(diagnostics).toHaveLength(1);expect(diagnostics[0]).toMatchObject({severity: "error",@@ -111,26 +130,31 @@ describe("text file assets", () => {test("reports connected Content Block warnings at property ranges", async () => {const source = '<ws.element ws:name="Card" class="legacy" />';await expect(- getMdxEditorDiagnostics(source, [- {- code: "ignored-template-prop",- severity: "warning",- blockInstanceId: "block",- assetId: "asset",- templateName: "Card",- propName: "class",- reason: "incompatible",- sourceRange: {- start: { line: 1, column: 28, offset: 27 },- end: { line: 1, column: 42, offset: 41 },+ getTextFileEditorDiagnostics({+ source,+ format: "mdx",+ semanticDiagnostics: [+ {+ code: "ignored-template-prop",+ severity: "warning",+ blockInstanceId: "block",+ assetId: "asset",+ templateName: "Card",+ propName: "class",+ reason: "incompatible",+ sourceRange: {+ start: { line: 1, column: 28, offset: 27 },+ end: { line: 1, column: 42, offset: 41 },+ },},- },- ])+ ],+ })).resolves.toEqual([{from: 27,to: 41,severity: "warning",+ source: "ignored-template-prop",message:'Property "class" on template "Card" was ignored because it is incompatible. Line 1, column 28.',},@@ -140,29 +164,90 @@ describe("text file assets", () => {test("reports connected Content Block content-model errors", async () => {const source = '<ws.element ws:tag="li">nested item</ws.element>';await expect(- getMdxEditorDiagnostics(source, [- {- code: "invalid-mdx",- severity: "error",- blockInstanceId: "block",- assetId: "asset",- message: "Placing <li> element inside a <li> violates HTML spec.",- sourceRange: {- start: { line: 1, column: 1, offset: 0 },- end: { line: 1, column: source.length + 1, offset: source.length },+ getTextFileEditorDiagnostics({+ source,+ format: "mdx",+ semanticDiagnostics: [+ {+ code: "invalid-mdx",+ severity: "error",+ blockInstanceId: "block",+ assetId: "asset",+ message: "Placing <li> element inside a <li> violates HTML spec.",+ sourceRange: {+ start: { line: 1, column: 1, offset: 0 },+ end: {+ line: 1,+ column: source.length + 1,+ offset: source.length,+ },+ },},- },- ])+ ],+ })).resolves.toEqual([{from: 0,to: source.length,severity: "error",+ source: "invalid-mdx",message: "Placing <li> element inside a <li> violates HTML spec.",},]);});+ test("uses the shared contextual validator and keeps every diagnostic", async () => {+ const validateSource = async () => [+ {+ code: "unresolved-template" as const,+ severity: "warning" as const,+ blockInstanceId: "block",+ assetId: "asset",+ templateName: "Card",+ sourceRange: {+ start: { line: 1, column: 1, offset: 0 },+ end: { line: 1, column: 7, offset: 6 },+ },+ },+ {+ code: "unsafe-mdx" as const,+ severity: "warning" as const,+ blockInstanceId: "block",+ assetId: "asset",+ nodeType: "mdxFlowExpression",+ reason: "Card",+ sourceRange: {+ start: { line: 1, column: 1, offset: 0 },+ end: { line: 1, column: 7, offset: 6 },+ },+ },+ ];++ await expect(+ getTextFileEditorDiagnostics({+ source: "<Card>",+ format: "mdx",+ validateSource,+ })+ ).resolves.toEqual([+ {+ from: 0,+ to: 6,+ severity: "warning",+ source: "unresolved-template",+ message:+ 'Template "Card" is not available and was skipped. Line 1, column 1.',+ },+ {+ from: 0,+ to: 6,+ severity: "warning",+ source: "unsafe-mdx",+ message: "Card",+ },+ ]);+ });+test("keeps failed and conflicting MDX saves visible", () => {expect(getMdxPersistenceFeedback({diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts b/apps/builder/app/builder/features/text-file-editor/text-file-utils.tsindex daecfa7e93..ee163ab928 100644--- a/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts+++ b/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts@@ -12,9 +12,9 @@ import { javascript } from "@codemirror/lang-javascript";import { markdown } from "@codemirror/lang-markdown";import { parseJsonExpression } from "@webstudio-is/expression";import {- createMdxSourceDiagnostics,- parseMdxDocumentRecovering,type MdxSourcePoint,+ type TextAssetSourceDiagnostic,+ validateTextAssetSource,} from "@webstudio-is/content-engine/mdx";import {getAssetTextEditorLanguage,@@ -30,6 +30,18 @@ export type MdxPersistenceFeedback = Readonly<{message: string;}>;+type TextFileSourceDiagnostic =+ | TextAssetSourceDiagnostic+ | ContentBlockDiagnostic;++export type ValidateTextFileSource = (input: {+ source: string;+ format: "md" | "mdx";+}) => Promise<readonly TextFileSourceDiagnostic[]>;++const validateTextFileSource: ValidateTextFileSource = async (input) =>+ (await validateTextAssetSource(input)).diagnostics;+export const getMdxPersistenceFeedback = (state: Pick<AssetContentSessionState, "status" | "error">): MdxPersistenceFeedback | undefined => {@@ -61,41 +73,47 @@ const getPointOffset = (source: string, point: MdxSourcePoint) => {return Math.min(offset + point.column - 1, source.length);};-export const getMdxEditorDiagnostics = async (- source: string,- semanticDiagnostics: readonly ContentBlockDiagnostic[] = []-): Promise<Diagnostic[]> => {- const result = await parseMdxDocumentRecovering({ source });+export const getTextFileEditorDiagnostics = async ({+ source,+ format,+ semanticDiagnostics = [],+ validateSource = validateTextFileSource,+}: {+ source: string;+ format: "md" | "mdx";+ semanticDiagnostics?: readonly ContentBlockDiagnostic[];+ validateSource?: ValidateTextFileSource;+}): Promise<Diagnostic[]> => {const diagnostics = [- ...createMdxSourceDiagnostics(result.diagnostics).map((diagnostic) => ({- sourceRange: diagnostic.sourceRange,- severity: diagnostic.severity,- message: diagnostic.message,- })),- ...semanticDiagnostics.map((diagnostic) => ({- sourceRange: diagnostic.sourceRange,- severity: diagnostic.severity,- message:- diagnostic.code === "invalid-mdx"- ? diagnostic.message- : diagnostic.code === "unsafe-mdx"- ? diagnostic.reason- : formatContentBlockDiagnostic(diagnostic),- })),+ ...(await validateSource({ source, format })),+ ...semanticDiagnostics,].map((diagnostic) => {const from =- diagnostic.sourceRange === undefined- ? 0- : getPointOffset(source, diagnostic.sourceRange.start);+ "sourceRange" in diagnostic && diagnostic.sourceRange !== undefined+ ? getPointOffset(source, diagnostic.sourceRange.start)+ : "line" in diagnostic &&+ diagnostic.line !== undefined &&+ diagnostic.column !== undefined+ ? getPointOffset(source, {+ line: diagnostic.line,+ column: diagnostic.column,+ })+ : 0;const to =- diagnostic.sourceRange === undefined- ? Math.min(1, source.length)- : Math.max(from, getPointOffset(source, diagnostic.sourceRange.end));+ "sourceRange" in diagnostic && diagnostic.sourceRange !== undefined+ ? Math.max(from, getPointOffset(source, diagnostic.sourceRange.end))+ : Math.min(source.length, from + 1);return {from,to,severity: diagnostic.severity,- message: diagnostic.message,+ source: diagnostic.code,+ message:+ "message" in diagnostic+ ? diagnostic.message+ : diagnostic.code === "unsafe-mdx"+ ? diagnostic.reason+ : formatContentBlockDiagnostic(diagnostic),};});return Array.from(@@ -105,12 +123,19 @@ export const getMdxEditorDiagnostics = async ();};-const getMdxExtensions = (- semanticDiagnostics: readonly ContentBlockDiagnostic[]+const getMarkdownExtensions = (+ format: "md" | "mdx",+ semanticDiagnostics: readonly ContentBlockDiagnostic[],+ validateSource: ValidateTextFileSource): Extension[] => [linter((view) =>- getMdxEditorDiagnostics(view.state.doc.toString(), semanticDiagnostics),+ getTextFileEditorDiagnostics({+ source: view.state.doc.toString(),+ format,+ semanticDiagnostics,+ validateSource,+ }),{ delay: 300 }),lintGutter(),@@ -129,15 +154,20 @@ const languageExtensions = {export const getTextFileEditorExtensions = (asset: Pick<Asset, "format">,- semanticDiagnostics: readonly ContentBlockDiagnostic[] = []+ semanticDiagnostics: readonly ContentBlockDiagnostic[] = [],+ validateSource: ValidateTextFileSource = validateTextFileSource): Extension[] => {const language = getAssetTextEditorLanguage(asset);if (language === undefined) {return [];}const extensions = languageExtensions[language];- return asset.format.toLowerCase() === "mdx"- ? [...extensions, ...getMdxExtensions(semanticDiagnostics)]+ const format = asset.format.toLowerCase();+ return format === "md" || format === "mdx"+ ? [+ ...extensions,+ ...getMarkdownExtensions(format, semanticDiagnostics, validateSource),+ ]: extensions;};diff --git a/apps/builder/app/routes/rest.resources-loader.ts b/apps/builder/app/routes/rest.resources-loader.tsindex 883ccb4a5d..9faa993469 100644--- a/apps/builder/app/routes/rest.resources-loader.ts+++ b/apps/builder/app/routes/rest.resources-loader.ts@@ -57,7 +57,6 @@ export const action = async ({ request }: ActionFunctionArgs) => {const requestList = z.array(z.unknown()).safeParse(requestJson);if (requestList.success === false) {- console.error("data:", requestJson);throw data(requestList.error, {status: 400,headers: privateNoStoreResponseHeaders,diff --git a/apps/builder/app/services/api-router.server.test.ts b/apps/builder/app/services/api-router.server.test.tsindex 035dc64c5f..5229e0d4a6 100644--- a/apps/builder/app/services/api-router.server.test.ts+++ b/apps/builder/app/services/api-router.server.test.ts@@ -19,6 +19,7 @@ import {import { db as authDb } from "@webstudio-is/authorization-token/index.server";import { blockComponent } from "@webstudio-is/sdk";import { AssetIndexRevisionError } from "@webstudio-is/content-engine";+import { DocumentSourceDiagnosticsError } from "@webstudio-is/content-engine/compiler";import * as assetUploader from "@webstudio-is/asset-uploader/server";import { apiRouter, __testing__ } from "./api-router.server";import * as assetQueryPreview from "./asset-query-preview.server";@@ -211,6 +212,14 @@ describe("api router build operation adapters", () => {).resolves.toMatchObject({valid: true,warnings: ["Asset field properties.missing is not currently observed"],+ issues: [+ {+ severity: "warning",+ code: "UNOBSERVED_FIELD",+ path: ["query", "where", "all", "0", "field"],+ message: "Asset field properties.missing is not currently observed",+ },+ ],});await expect(caller.assetQueries.preview({@@ -248,6 +257,118 @@ describe("api router build operation adapters", () => {code: "CONFLICT",cause: { webstudioCode: "STALE_INDEX" },});+ vi.mocked(assetQueryPreview.previewProjectAssetQuery).mockRejectedValueOnce(+ new DocumentSourceDiagnosticsError([+ {+ severity: "warning",+ code: "FRONTMATTER_INVALID",+ message: "Markdown frontmatter contains invalid YAML",+ assetId: "markdown",+ path: "content/broken.md",+ line: 4,+ column: 1,+ },+ {+ severity: "error",+ code: "invalid-mdx",+ message: "Unexpected closing tag",+ assetId: "mdx",+ path: "content/broken.mdx",+ line: 8,+ column: 3,+ reference: "Card",+ nodeType: "mdxJsxFlowElement",+ reason: "unexpected-close-tag",+ sourceRange: {+ start: { line: 8, column: 3, offset: 80 },+ end: { line: 8, column: 10, offset: 87 },+ },+ },+ ])+ );+ await expect(+ caller.assetQueries.preview({+ projectId: "project-1",+ query: { limit: 10 },+ })+ ).rejects.toMatchObject({+ code: "BAD_REQUEST",+ cause: {+ webstudioCode: "INVALID_REQUEST",+ issues: [+ {+ code: "FRONTMATTER_INVALID",+ path: ["content/broken.md"],+ message: "Markdown frontmatter contains invalid YAML",+ constraint: "FRONTMATTER_INVALID",+ detail:+ "Line 4, column 1. Scope: query. Severity: warning. Asset: markdown",+ },+ {+ code: "invalid-mdx",+ path: ["content/broken.mdx"],+ message: "Unexpected closing tag",+ constraint: "invalid-mdx",+ detail:+ "Line 8, column 3. Scope: query. Severity: error. Asset: mdx",+ severity: "error",+ scope: "query",+ phase: "source",+ assetId: "mdx",+ file: "content/broken.mdx",+ line: 8,+ column: 3,+ reference: "Card",+ nodeType: "mdxJsxFlowElement",+ reason: "unexpected-close-tag",+ sourceRange: {+ start: { line: 8, column: 3, offset: 80 },+ end: { line: 8, column: 10, offset: 87 },+ },+ },+ ],+ },+ });+ await expect(+ caller.assetQueries.validate({+ projectId: "project-1",+ query: {+ where: {+ all: [+ { field: ["width"], operator: "contains", value: 1 },+ { field: ["height"], operator: "startsWith", value: "1" },+ {+ field: ["properties", "missing"],+ operator: "eq",+ value: true,+ },+ ],+ },+ },+ })+ ).rejects.toMatchObject({+ code: "BAD_REQUEST",+ cause: {+ webstudioCode: "INVALID_REQUEST",+ issues: [+ expect.objectContaining({+ code: "INCOMPATIBLE_OPERATOR",+ path: ["query", "where", "all", "0", "operator"],+ message: "Operator contains is incompatible with width",+ }),+ expect.objectContaining({+ code: "INCOMPATIBLE_OPERATOR",+ path: ["query", "where", "all", "1", "operator"],+ message: "Operator startsWith is incompatible with height",+ }),+ expect.objectContaining({+ code: "UNOBSERVED_FIELD",+ path: ["query", "where", "all", "2", "field"],+ message: "Asset field properties.missing is not currently observed",+ }),+ ],+ },+ });await expect(caller.assetQueries.fieldCatalog({ projectId: "project-1" })).resolves.toMatchObject({diff --git a/apps/builder/app/services/api-router.server.ts b/apps/builder/app/services/api-router.server.tsindex aa655425d3..f03627c8ad 100644--- a/apps/builder/app/services/api-router.server.ts+++ b/apps/builder/app/services/api-router.server.ts@@ -31,10 +31,13 @@ import {paginatedOutputInputSchema,} from "@webstudio-is/project-build/runtime";import {- getAssetResourceQueryError,+ getDetailedAssetResourceQueryError,+ assetQueryDiagnosticIssue,assetQueryRequest,+ assetQuerySetupIssue,getAssetQueryWhereMetrics,validateAssetQueryAgainstCatalog,+ type AssetResourceQueryError,} from "@webstudio-is/content-engine";import {loadBuilderAssetFieldCatalog,@@ -125,14 +128,130 @@ const assetQueryInput = projectIdInput.extend(assetQueryRequest.shape);const assetQueryValidationInput = projectIdInput.extend({query: assetQueryRequest.shape.query,});++const asRecord = (value: unknown): Record<string, unknown> | undefined =>+ typeof value === "object" && value !== null && Array.isArray(value) === false+ ? (value as Record<string, unknown>)+ : undefined;++const getAssetQueryApiIssues = (error: AssetResourceQueryError) => {+ const details = asRecord(error.details);+ const sourceDiagnostics = Array.isArray(details?.diagnostics)+ ? details.diagnostics+ : details?.path === undefined+ ? []+ : [details];+ const sourceIssues = sourceDiagnostics.flatMap((value) => {+ const diagnostic = asRecord(value);+ if (diagnostic === undefined || typeof diagnostic.path !== "string") {+ return [];+ }+ const code =+ typeof diagnostic.code === "string" ? diagnostic.code : error.code;+ const message =+ typeof diagnostic.message === "string"+ ? diagnostic.message+ : error.message;+ const detail = [+ typeof diagnostic.line === "number"+ ? `Line ${diagnostic.line}${+ typeof diagnostic.column === "number"+ ? `, column ${diagnostic.column}`+ : ""+ }`+ : undefined,+ typeof diagnostic.scope === "string"+ ? `Scope: ${diagnostic.scope}`+ : undefined,+ typeof diagnostic.severity === "string"+ ? `Severity: ${diagnostic.severity}`+ : undefined,+ typeof diagnostic.assetId === "string"+ ? `Asset: ${diagnostic.assetId}`+ : undefined,+ ]+ .filter((item) => item !== undefined)+ .join(". ");+ const parsedSourceRange =+ assetQueryDiagnosticIssue.shape.sourceRange.safeParse(+ diagnostic.sourceRange+ );+ const sourceRange = parsedSourceRange.success+ ? parsedSourceRange.data+ : undefined;+ const severity = diagnostic.severity === "warning" ? "warning" : "error";+ const scope = diagnostic.scope === "database" ? "database" : "query";+ const phase =+ diagnostic.phase === "metadata" || diagnostic.phase === "reference"+ ? diagnostic.phase+ : "source";+ return [+ {+ code,+ path: [diagnostic.path],+ message,+ constraint: code,+ ...(detail === "" ? {} : { detail }),+ severity,+ scope,+ phase,+ file: diagnostic.path,+ ...(typeof diagnostic.assetId === "string"+ ? { assetId: diagnostic.assetId }+ : {}),+ ...(typeof diagnostic.line === "number"+ ? { line: diagnostic.line }+ : {}),+ ...(typeof diagnostic.column === "number"+ ? { column: diagnostic.column }+ : {}),+ ...(typeof diagnostic.reference === "string"+ ? { reference: diagnostic.reference }+ : {}),+ ...(typeof diagnostic.nodeType === "string"+ ? { nodeType: diagnostic.nodeType }+ : {}),+ ...(typeof diagnostic.reason === "string"+ ? { reason: diagnostic.reason }+ : {}),+ ...(sourceRange === undefined ? {} : { sourceRange }),+ },+ ];+ });+ const queryIssues = Array.isArray(details?.issues)+ ? details.issues.flatMap((value) => {+ const parsedIssue = assetQuerySetupIssue.safeParse(value);+ if (parsedIssue.success === false) {+ return [];+ }+ const issue = parsedIssue.data;+ return [+ {+ code: issue.code,+ path: issue.path,+ message: issue.message,+ constraint: issue.code,+ severity: issue.severity,+ ...(issue.severity === "warning"+ ? { detail: "Severity: warning" }+ : {}),+ },+ ];+ })+ : [];+ return [...sourceIssues, ...queryIssues];+};+const throwAssetQueryApiError = (error: unknown): never => {- const queryError = getAssetResourceQueryError(error);+ const queryError = getDetailedAssetResourceQueryError(error);if (queryError !== undefined) {+ const issues = getAssetQueryApiIssues(queryError);return throwApiError(queryError.status === 409 ? "CONFLICT" : "BAD_REQUEST",queryError.message,{webstudioCode: queryError.code,+ ...(issues.length === 0 ? {} : { issues }),});}@@ -888,6 +1007,7 @@ export const apiRouter = router({.filters,sortCount: validated.query.sort.length,warnings: validated.warnings,+ issues: validated.warningIssues,};} catch (error) {return throwAssetQueryApiError(error);diff --git a/apps/builder/app/services/resource-list-loader.server.ts b/apps/builder/app/services/resource-list-loader.server.tsindex 79216c78c1..8a41395169 100644--- a/apps/builder/app/services/resource-list-loader.server.ts+++ b/apps/builder/app/services/resource-list-loader.server.ts@@ -4,6 +4,7 @@ import {isLocalResource,loadResource,} from "@webstudio-is/sdk/runtime";+import { getZodValidationIssues } from "@webstudio-is/project-build/runtime";import { executeAssetQueries } from "~/shared/$resources/assets-query.server";import { getResourceKey } from "~/shared/resource-utils";@@ -73,9 +74,16 @@ export const loadResourceRequestList = async (getResourceKey(item as ResourceRequest),{ok: false,- data: resource.error.format(),- status: 403,- statusText: "Resource validation error",+ data: {+ error: {+ code: "INVALID_REQUEST",+ message: "Resource request is invalid",+ retryable: false,+ details: { issues: getZodValidationIssues(resource.error) },+ },+ },+ status: 400,+ statusText: "Bad Request",},];}diff --git a/apps/builder/app/shared/$resources/assets-query.server.test.ts b/apps/builder/app/shared/$resources/assets-query.server.test.tsindex 122ca6fd1e..46bbf68829 100644--- a/apps/builder/app/shared/$resources/assets-query.server.test.ts+++ b/apps/builder/app/shared/$resources/assets-query.server.test.ts@@ -132,7 +132,11 @@ describe("configured Assets system resource", () => {});await expect(responses[1].json()).resolves.toMatchObject({ok: false,- error: { code: "INVALID_REQUEST" },+ error: {+ code: "INVALID_REQUEST",+ message:+ "Expected property name or '}' in JSON at position 1 (line 1 column 2)",+ },});await expect(responses[2].json()).resolves.toMatchObject({ok: false,@@ -413,6 +417,33 @@ describe("configured Assets system resource", () => {);expect(malformed.status).toBe(400);+ const invalidSetup = await executeAssetQuery(+ {+ request: outerRequest(),+ resourceRequest: innerRequest({+ query: {+ result: "first",+ limit: -1,+ output: { mode: "fields", includeMetadata: false, fields: [] },+ content: { mode: "none" },+ },+ }),+ },+ dependencies+ );+ await expect(invalidSetup.json()).resolves.toMatchObject({+ error: {+ code: "INVALID_REQUEST",+ details: {+ issues: [+ { path: ["query", "limit"] },+ { path: ["query"] },+ { path: ["query", "sort"] },+ ],+ },+ },+ });+dependencies.previewProjectAssetQuery.mockRejectedValueOnce(new AssetQueryExecutionError("Invalid pagination"));@@ -426,6 +457,69 @@ describe("configured Assets system resource", () => {});});+ test("shows sanitized internal messages only in authenticated diagnostics", async () => {+ dependencies.previewProjectAssetQuery.mockRejectedValue(+ new Error(+ "Document graph failed for content/broken.md?authToken=secret-token"+ )+ );+ dependencies.previewProjectAssetQueries.mockResolvedValue([+ {+ status: "rejected",+ reason: new Error("Document graph failed for content/broken.md"),+ },+ ]);++ dependencies.authorizeApiProject.mockRejectedValueOnce(+ new Error("Private authorization dependency failed")+ );+ const beforeAuthorization = await executeAssetQuery(+ {+ request: outerRequest(),+ resourceRequest: innerRequest({ query: {} }),+ includeDiagnostics: true,+ },+ dependencies+ );+ await expect(beforeAuthorization.json()).resolves.toMatchObject({+ error: {+ code: "INTERNAL_ERROR",+ message: "Asset query preview failed",+ },+ });++ const ordinary = await executeAssetQuery(+ {+ request: outerRequest(),+ resourceRequest: innerRequest({ query: {} }),+ includeDiagnostics: false,+ },+ dependencies+ );+ await expect(ordinary.json()).resolves.toMatchObject({+ error: {+ code: "INTERNAL_ERROR",+ message: "Asset query preview failed",+ },+ });++ const detailed = await executeAssetQuery(+ {+ request: outerRequest(),+ resourceRequest: innerRequest({ query: {} }),+ includeDiagnostics: true,+ },+ dependencies+ );+ await expect(detailed.json()).resolves.toMatchObject({+ error: {+ code: "INTERNAL_ERROR",+ message:+ "Document graph failed for content/broken.md?authToken=[redacted]",+ },+ });+ });+test("maps stale revisions to conflict responses", async () => {dependencies.previewProjectAssetQuery.mockRejectedValue(new AssetIndexRevisionError()diff --git a/apps/builder/app/shared/$resources/assets-query.server.ts b/apps/builder/app/shared/$resources/assets-query.server.tsindex 8b993e9ff6..311c388a75 100644--- a/apps/builder/app/shared/$resources/assets-query.server.ts+++ b/apps/builder/app/shared/$resources/assets-query.server.ts@@ -1,10 +1,11 @@import { json } from "@remix-run/server-runtime";import {- getAssetResourceQueryError,+ getDetailedAssetResourceQueryError,readAssetQueryRequest,type DocumentGraphRuntimeObserver,} from "@webstudio-is/content-engine";import type { AssetQueryPerformanceObserver } from "@webstudio-is/asset-uploader/server";+import { sanitizeValidationDetail } from "@webstudio-is/project-build/runtime";import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";import {authorizeApiProject,@@ -127,7 +128,11 @@ const createPerformanceCollector = () => {};};-const createFailureResponse = (error: unknown, request: Request) => {+const createFailureResponse = (+ error: unknown,+ request: Request,+ exposeInternalError = false+) => {if (request.signal.aborted) {return createAssetResourceFailureResponse({code: "REQUEST_CANCELLED",@@ -139,13 +144,17 @@ const createFailureResponse = (error: unknown, request: Request) => {if (authorizationFailure !== undefined) {return createAssetResourceFailureResponse(authorizationFailure);}- const queryError = getAssetResourceQueryError(error);+ const queryError = getDetailedAssetResourceQueryError(error);if (queryError !== undefined) {return createAssetResourceFailureResponse(queryError);}+ const message =+ exposeInternalError && error instanceof Error && error.message.trim() !== ""+ ? sanitizeValidationDetail(error.message)+ : "Asset query preview failed";return createAssetResourceFailureResponse({code: "INTERNAL_ERROR",- message: "Asset query preview failed",+ message,status: 500,retryable: true,});@@ -153,14 +162,16 @@ const createFailureResponse = (error: unknown, request: Request) => {const finalizeResponses = (responses: readonly (Response | undefined)[],- request: Request+ request: Request,+ exposeInternalError: boolean) =>responses.map((response) =>response ??createFailureResponse(new Error("Asset query batch response is missing"),- request+ request,+ exposeInternalError));@@ -211,18 +222,14 @@ export const executeAssetQueries = async (index,request: await readAssetQueryRequest(resourceRequest),});- } catch {- responses[index] = createAssetResourceFailureResponse({- code: "INVALID_REQUEST",- message: "Asset query preview requires a JSON request body",- status: 400,- });+ } catch (error) {+ responses[index] = createFailureResponse(error, request);}}));parsedRequests.sort((left, right) => left.index - right.index);if (parsedRequests.length === 0) {- return finalizeResponses(responses, request);+ return finalizeResponses(responses, request, false);}let context: Awaited<ReturnType<typeof authorizeApiProject>>;@@ -244,7 +251,7 @@ export const executeAssetQueries = async (for (const { index } of parsedRequests) {responses[index] = createFailureResponse(error, request);}- return finalizeResponses(responses, request);+ return finalizeResponses(responses, request, false);}let results: PromiseSettledResult<unknown>[];@@ -282,7 +289,8 @@ export const executeAssetQueries = async (if (result === undefined) {responses[index] = createFailureResponse(new Error("Asset query batch result is missing"),- request+ request,+ includeDiagnostics);} else if (result.status === "fulfilled") {const value =@@ -298,10 +306,14 @@ export const executeAssetQueries = async (headers: privateNoStoreResponseHeaders,});} else {- responses[index] = createFailureResponse(result.reason, request);+ responses[index] = createFailureResponse(+ result.reason,+ request,+ includeDiagnostics+ );}}- return finalizeResponses(responses, request);+ return finalizeResponses(responses, request, includeDiagnostics);};export const executeAssetQuery = async (diff --git a/apps/builder/app/shared/external-content-roots.test.ts b/apps/builder/app/shared/external-content-roots.test.tsindex 30e3da4419..917af1dd2f 100644--- a/apps/builder/app/shared/external-content-roots.test.ts+++ b/apps/builder/app/shared/external-content-roots.test.ts@@ -492,7 +492,10 @@ avatar:---`;const invalidAuthorSource = `----name: [+name: Ada+name: Grace+role: author+role: editor---`;const authorAsset: Asset = {@@ -611,7 +614,11 @@ name: [).toEqual([expect.objectContaining({severity: "error",- message: expect.stringContaining("Unable to resolve frontmatter"),+ message: expect.stringContaining("Map keys must be unique"),+ }),+ expect.objectContaining({+ severity: "error",+ message: expect.stringContaining("Map keys must be unique"),}),]);diff --git a/apps/builder/app/shared/external-content-roots.ts b/apps/builder/app/shared/external-content-roots.tsindex d6fbc30f4e..7831c7d68d 100644--- a/apps/builder/app/shared/external-content-roots.ts+++ b/apps/builder/app/shared/external-content-roots.ts@@ -1,5 +1,6 @@import {createCanonicalAssetPath,+ createMarkdownFrontmatterDiagnostics,parseMdxDocumentRecovering,replaceMdxFrontmatter,serializeMdxDocument,@@ -114,6 +115,44 @@ type AssetUpdate = (latestDocument: MdxDocument | undefined) => PreparedAssetUpdate | Promise<PreparedAssetUpdate>;+type MarkdownFrontmatterDiagnostic = Awaited<+ ReturnType<typeof createMarkdownFrontmatterDiagnostics>+>[number];++class ExternalContentFrontmatterDiagnosticsError extends Error {+ readonly assetId: string;+ readonly path: string;+ readonly diagnostics: readonly MarkdownFrontmatterDiagnostic[];++ constructor({+ assetId,+ path,+ diagnostics,+ }: {+ assetId: string;+ path: string;+ diagnostics: readonly MarkdownFrontmatterDiagnostic[];+ }) {+ super(`Frontmatter validation failed for ${path}`);+ this.name = "ExternalContentFrontmatterDiagnosticsError";+ this.assetId = assetId;+ this.path = path;+ this.diagnostics = diagnostics;+ }+}++const findExternalContentFrontmatterDiagnostics = (error: unknown) => {+ const visited = new Set<unknown>();+ let cause = error;+ while (cause !== undefined && visited.has(cause) === false) {+ if (cause instanceof ExternalContentFrontmatterDiagnosticsError) {+ return cause;+ }+ visited.add(cause);+ cause = cause instanceof Error ? cause.cause : undefined;+ }+};+const roots = new Map<string, RootEntry>();const rootOpenGenerations = new Map<string,@@ -519,11 +558,20 @@ const resolveExternalContentFrontmatter = async (format,source: {async *[Symbol.asyncIterator]() {- yield encoder.encode(+ const source =asset.id === entry.assetId? sourceState.source- : (await session.open(asset.id)).source- );+ : (await session.open(asset.id)).source;+ const diagnostics =+ await createMarkdownFrontmatterDiagnostics(source);+ if (diagnostics.length > 0) {+ throw new ExternalContentFrontmatterDiagnosticsError({+ assetId: asset.id,+ path,+ diagnostics,+ });+ }+ yield encoder.encode(source);},},})),@@ -659,6 +707,40 @@ const materialize = async ({};}} catch (error) {+ const frontmatterError = findExternalContentFrontmatterDiagnostics(error);+ if (frontmatterError !== undefined) {+ return {+ ...result,+ diagnostics: [+ ...result.diagnostics,+ ...frontmatterError.diagnostics.map(+ (diagnostic): ContentBlockDiagnostic => ({+ code: "invalid-mdx",+ severity: "error",+ blockInstanceId: entry.sourceBlockInstanceId,+ assetId: frontmatterError.assetId,+ renderScope: entry.renderScope,+ message: `${frontmatterError.path}: ${diagnostic.message}`,+ ...(diagnostic.line === undefined ||+ diagnostic.column === undefined+ ? {}+ : {+ sourceRange: {+ start: {+ line: diagnostic.line,+ column: diagnostic.column,+ },+ end: {+ line: diagnostic.line,+ column: diagnostic.column,+ },+ },+ }),+ })+ ),+ ],+ };+ }const diagnostic: ContentBlockDiagnostic = {code: "invalid-mdx",severity: "error",diff --git a/apps/builder/app/shared/resource-diagnostics.test.ts b/apps/builder/app/shared/resource-diagnostics.test.tsindex 44651e10af..7511f82fcb 100644--- a/apps/builder/app/shared/resource-diagnostics.test.ts+++ b/apps/builder/app/shared/resource-diagnostics.test.ts@@ -56,17 +56,54 @@ describe("resource diagnostics", () => {});});- test("strips malformed diagnostics instead of exposing them", () => {+ test("returns every schema issue for malformed diagnostics", () => {const separated = separateResourceDiagnostics({request: assetsRequest,result: {data: { items: [] },- __diagnostics__: { truncated: "yes" },+ __diagnostics__: {+ scope: "other",+ query: {+ usedBytes: "large",+ maxBytes: 500,+ unboundedBytes: 100,+ includedDocumentCount: 1,+ omittedDocumentCount: 0,+ truncated: false,+ },+ database: {+ usedBytes: 500,+ maxBytes: 500,+ unboundedBytes: 500,+ includedDocumentCount: 1,+ omittedDocumentCount: 0,+ truncated: false,+ },+ },},});expect(separated.result).toEqual({ data: { items: [] } });expect(separated.diagnostics).toBeUndefined();+ expect(separated.diagnosticsError).toMatchObject({+ ok: false,+ status: 500,+ data: {+ error: {+ code: "INVALID_DIAGNOSTICS_RESPONSE",+ message: "Resource diagnostics response is invalid",+ retryable: true,+ },+ },+ });+ expect(+ separated.diagnosticsError?.data.error.details.issues.map(+ ({ path }) => path+ )+ ).toEqual([+ ["__diagnostics__", "scope"],+ ["__diagnostics__", "query", "usedBytes"],+ ]);});test("preserves diagnostics fields returned by ordinary APIs", () => {diff --git a/apps/builder/app/shared/resource-diagnostics.ts b/apps/builder/app/shared/resource-diagnostics.tsindex 352c10abe0..192bd2e7c7 100644--- a/apps/builder/app/shared/resource-diagnostics.ts+++ b/apps/builder/app/shared/resource-diagnostics.ts@@ -44,6 +44,44 @@ export const resourcePerformance = z.object({export type ResourcePerformance = z.infer<typeof resourcePerformance>;+type ResourceDiagnosticsSchemaIssue = {+ code: string;+ path: string[];+ message: string;+};++export const createResourceDiagnosticsResponseError = ({+ message,+ issues,+}: {+ message: string;+ issues: readonly ResourceDiagnosticsSchemaIssue[];+}) => ({+ ok: false as const,+ status: 500,+ data: {+ error: {+ code: "INVALID_DIAGNOSTICS_RESPONSE",+ message,+ retryable: true,+ details: {+ issues: issues.map((issue) => ({+ ...issue,+ severity: "error" as const,+ scope: "diagnostics" as const,+ })),+ },+ },+ },+});++type SeparatedResourceDiagnostics = {+ result: unknown;+ diagnostics?: z.infer<typeof assetQueryPreviewDiagnostics>;+ diagnosticsError?: ReturnType<typeof createResourceDiagnosticsResponseError>;+ performance?: ResourcePerformance;+};+// Assets diagnostics may be shown by Builder, but must never enter the value// exposed to expressions. Ordinary APIs may legitimately use the same field.export const separateResourceDiagnostics = ({@@ -52,7 +90,7 @@ export const separateResourceDiagnostics = ({}: {request?: ResourceRequest;result: unknown;-}) => {+}): SeparatedResourceDiagnostics => {if (typeof result !== "object" || result === null) {return { result, diagnostics: undefined, performance: undefined };}@@ -73,9 +111,37 @@ export const separateResourceDiagnostics = ({};}const { __diagnostics__, ...resourceResult } = resultWithoutPerformance;+ const parsedDiagnostics =+ assetQueryPreviewDiagnostics.safeParse(__diagnostics__);+ if (parsedDiagnostics.success === false) {+ const issues: ResourceDiagnosticsSchemaIssue[] = [];+ for (const issue of parsedDiagnostics.error.issues) {+ const path = ["__diagnostics__", ...issue.path.map(String)];+ if (issue.code === "unrecognized_keys") {+ for (const key of issue.keys) {+ issues.push({+ code: issue.code,+ path: [...path, key],+ message: issue.message,+ });+ }+ continue;+ }+ issues.push({ code: issue.code, path, message: issue.message });+ }+ return {+ result: resourceResult,+ diagnostics: undefined,+ diagnosticsError: createResourceDiagnosticsResponseError({+ message: "Resource diagnostics response is invalid",+ issues,+ }),+ performance,+ };+ }return {result: resourceResult,- diagnostics: assetQueryPreviewDiagnostics.safeParse(__diagnostics__).data,+ diagnostics: parsedDiagnostics.data,performance,};};diff --git a/apps/builder/app/shared/resources.test.ts b/apps/builder/app/shared/resources.test.tsindex fd2b0481a3..2abffddc89 100644--- a/apps/builder/app/shared/resources.test.ts+++ b/apps/builder/app/shared/resources.test.ts@@ -3,7 +3,9 @@ import type { ResourceRequest } from "@webstudio-is/sdk";import {__testing__,$hasPendingResources,+ $pendingResourceKeys,$resourceDiagnosticsCache,+ $resourceDiagnosticsErrorCache,$resourcePerformanceCache,$resourcesCache,getResourceKey,@@ -39,6 +41,7 @@ test("removes obsolete queued requests but keeps cached results", () => {queueResources([request]);$resourcesCache.get().set(key, { stale: true });expect($hasPendingResources.get()).toBe(true);+ expect($pendingResourceKeys.get()).toEqual(new Set([key]));const resourceCacheListener = vi.fn();const unlisten = $resourcesCache.listen(resourceCacheListener);@@ -47,6 +50,7 @@ test("removes obsolete queued requests but keeps cached results", () => {expect($resourcesCache.get().has(key)).toBe(true);expect($hasPendingResources.get()).toBe(false);+ expect($pendingResourceKeys.get()).toEqual(new Set());expect(resourceCacheListener).not.toHaveBeenCalled();unlisten();});@@ -479,6 +483,163 @@ test("loads detailed Assets diagnostics and performance only on demand", async (expect($resourcesCache.get().has(key)).toBe(false);});+test("keeps a diagnostics-only failure separate from the resource value", async () => {+ const request: ResourceRequest = {+ name: "assets",+ method: "post",+ url: "/$resources/assets",+ searchParams: [],+ headers: [],+ body: { query: {} },+ };+ const key = getResourceKey(request);+ $resourcesCache.get().set(key, { data: { items: [] } });+ const failure = {+ ok: false,+ status: 400,+ data: {+ error: {+ code: "INVALID_REQUEST",+ message: "Unexpected closing tag",+ details: { path: "posts/broken.mdx", line: 7, column: 4 },+ },+ },+ };+ const fetch = vi.fn<typeof globalThis.fetch>(async () =>+ Response.json([[key, failure]])+ );++ await loadResourceDiagnostics(request, fetch);++ expect($resourcesCache.get().get(key)).toEqual({ data: { items: [] } });+ expect($resourceDiagnosticsCache.get().has(key)).toBe(false);+ expect($resourceDiagnosticsErrorCache.get().get(key)).toEqual(failure);+});++test("caches every malformed diagnostics schema issue", async () => {+ const request: ResourceRequest = {+ name: "assets",+ method: "post",+ url: "/$resources/assets",+ searchParams: [],+ headers: [],+ body: { query: {} },+ };+ const key = getResourceKey(request);+ const fetch = vi.fn<typeof globalThis.fetch>(async () =>+ Response.json([+ [+ key,+ {+ data: { items: [] },+ __diagnostics__: {+ scope: "other",+ query: {+ usedBytes: "large",+ maxBytes: 500,+ unboundedBytes: 100,+ includedDocumentCount: 1,+ omittedDocumentCount: 0,+ truncated: false,+ },+ database: {+ usedBytes: 500,+ maxBytes: 500,+ unboundedBytes: 500,+ includedDocumentCount: 1,+ omittedDocumentCount: 0,+ truncated: false,+ },+ },+ },+ ],+ ])+ );++ await loadResourceDiagnostics(request, fetch);++ const error = $resourceDiagnosticsErrorCache.get().get(key) as {+ data?: { error?: { details?: { issues?: Array<{ path: string[] }> } } };+ };+ expect(error).toMatchObject({+ ok: false,+ status: 500,+ data: {+ error: {+ code: "INVALID_DIAGNOSTICS_RESPONSE",+ message: "Resource diagnostics response is invalid",+ },+ },+ });+ expect(error.data?.error?.details?.issues?.map(({ path }) => path)).toEqual([+ ["__diagnostics__", "scope"],+ ["__diagnostics__", "query", "usedBytes"],+ ]);+});++test("reports a diagnostics response that omits the requested resource", async () => {+ const request: ResourceRequest = {+ name: "assets",+ method: "post",+ url: "/$resources/assets",+ searchParams: [],+ headers: [],+ body: { query: {} },+ };+ const key = getResourceKey(request);++ await loadResourceDiagnostics(+ request,+ vi.fn<typeof globalThis.fetch>(async () => Response.json([]))+ );++ expect($resourceDiagnosticsErrorCache.get().get(key)).toEqual({+ ok: false,+ data: {+ error: { message: "Resource diagnostics response is missing" },+ },+ });+});++test("reports a resource response that omits its diagnostics payload", async () => {+ const request: ResourceRequest = {+ name: "assets",+ method: "post",+ url: "/$resources/assets",+ searchParams: [],+ headers: [],+ body: { query: {} },+ };+ const key = getResourceKey(request);++ await loadResourceDiagnostics(+ request,+ vi.fn<typeof globalThis.fetch>(async () =>+ Response.json([[key, { data: { items: [] } }]])+ )+ );++ expect($resourceDiagnosticsErrorCache.get().get(key)).toMatchObject({+ ok: false,+ status: 500,+ data: {+ error: {+ code: "INVALID_DIAGNOSTICS_RESPONSE",+ message: "Resource diagnostics response is missing",+ details: {+ issues: [+ {+ path: ["__diagnostics__"],+ message:+ "The resource response does not contain diagnostics data",+ },+ ],+ },+ },+ },+ });+});+test("caches performance metrics separately from resource values", async () => {const request: ResourceRequest = {name: "Posts",diff --git a/apps/builder/app/shared/resources.ts b/apps/builder/app/shared/resources.tsindex cc6c446d4a..6148c1ff9d 100644--- a/apps/builder/app/shared/resources.ts+++ b/apps/builder/app/shared/resources.ts@@ -6,8 +6,11 @@ import { computeExpression } from "@webstudio-is/project-build/runtime";import { fetch } from "./fetch.client";import { getResourceKey } from "./resource-utils";import { type AssetQueryPreviewDiagnostics } from "@webstudio-is/content-engine";-import { separateResourceDiagnostics } from "./resource-diagnostics";-import type { ResourcePerformance } from "./resource-diagnostics";+import {+ createResourceDiagnosticsResponseError,+ separateResourceDiagnostics,+ type ResourcePerformance,+} from "./resource-diagnostics";const MAX_PENDING_RESOURCES = 5;@@ -27,6 +30,7 @@ const queue = new Map<string, ResourceRequest>();const pending = new Map<string, InFlightResourceBatch>();const cache = new Map<string, unknown>();const diagnosticsCache = new Map<string, AssetQueryPreviewDiagnostics>();+const diagnosticsErrorCache = new Map<string, unknown>();const performanceCache = new Map<string, ResourcePerformance>();const pendingDiagnostics = new Map<string, InFlightResourceDiagnostics>();const knownRequests = new Map<string, ResourceRequest>();@@ -35,10 +39,12 @@ const inFlightBatches = new Set<InFlightResourceBatch>();export const $resourcesCache = atom(cache);export const $resourceDiagnosticsCache = atom(diagnosticsCache);+export const $resourceDiagnosticsErrorCache = atom(diagnosticsErrorCache);export const $resourcePerformanceCache = atom(performanceCache);const updateMetadataCache = () => {$resourceDiagnosticsCache.set(new Map(diagnosticsCache));+ $resourceDiagnosticsErrorCache.set(new Map(diagnosticsErrorCache));$resourcePerformanceCache.set(new Map(performanceCache));};@@ -68,18 +74,21 @@ const cacheResourceMetadata = ({} else {diagnosticsCache.set(key, separated.diagnostics);}- return separated.result;+ if (separated.diagnosticsError !== undefined) {+ diagnosticsErrorCache.set(key, separated.diagnosticsError);+ }+ return separated;};-const $pendingUpdater = atom({});+export const $pendingResourceKeys = atom<ReadonlySet<string>>(new Set());const updatePending = () => {- $pendingUpdater.set({});+ $pendingResourceKeys.set(new Set([...queue.keys(), ...pending.keys()]));};export const $hasPendingResources = computed(- $pendingUpdater,- () => queue.size > 0 || pending.size > 0+ $pendingResourceKeys,+ (pendingResourceKeys) => pendingResourceKeys.size > 0);const loadResources = async (requestFetch: typeof fetch = fetch) => {@@ -127,15 +136,13 @@ const loadResources = async (requestFetch: typeof fetch = fetch) => {) {continue;}- cache.set(+ const separated = cacheResourceMetadata({key,- cacheResourceMetadata({- key,- request,- result,- loaderDurationMs,- })- );+ request,+ result,+ loaderDurationMs,+ });+ cache.set(key, separated.result);}} catch {if (controller.signal.aborted === false) {@@ -193,6 +200,7 @@ const preloadResource = (resource: ResourceRequest) => {const invalidateRequestState = (key: string) => {diagnosticsCache.delete(key);+ diagnosticsErrorCache.delete(key);performanceCache.delete(key);pendingDiagnostics.get(key)?.controller.abort();pendingDiagnostics.delete(key);@@ -280,6 +288,25 @@ export const loadResourceDiagnostics = (});if (response.ok === false) {+ let data: unknown;+ try {+ data = await response.json();+ } catch {+ data = undefined;+ }+ if (+ controller.signal.aborted === false &&+ pendingDiagnostics.get(key)?.controller === controller &&+ (resourceVersions.get(key) ?? 0) === version+ ) {+ diagnosticsErrorCache.set(key, {+ ok: false,+ status: response.status,+ statusText: response.statusText,+ data,+ });+ updateMetadataCache();+ }return;}const result = new Map<string, unknown>(await response.json()).get(key);@@ -291,16 +318,70 @@ export const loadResourceDiagnostics = () {return;}- cacheResourceMetadata({+ const separated = cacheResourceMetadata({key,request: resource,result,loaderDurationMs,});+ if (result === undefined) {+ diagnosticsErrorCache.set(key, {+ ok: false,+ data: {+ error: {+ message: "Resource diagnostics response is missing",+ },+ },+ });+ } else if (+ typeof result === "object" &&+ result !== null &&+ ((result as { ok?: unknown }).ok === false ||+ (typeof (result as { status?: unknown }).status === "number" &&+ ((result as { status: number }).status ?? 0) >= 400))+ ) {+ diagnosticsErrorCache.set(key, result);+ } else if (separated.diagnosticsError !== undefined) {+ diagnosticsErrorCache.set(key, separated.diagnosticsError);+ } else if (separated.diagnostics === undefined) {+ diagnosticsErrorCache.set(+ key,+ createResourceDiagnosticsResponseError({+ message: "Resource diagnostics response is missing",+ issues: [+ {+ code: "missing_diagnostics",+ path: ["__diagnostics__"],+ message:+ "The resource response does not contain diagnostics data",+ },+ ],+ })+ );+ } else {+ diagnosticsErrorCache.delete(key);+ }updateMetadataCache();- } catch {+ } catch (error) {if (controller.signal.aborted === false) {console.error("Resource diagnostics request failed");+ if (+ pendingDiagnostics.get(key)?.controller === controller &&+ (resourceVersions.get(key) ?? 0) === version+ ) {+ diagnosticsErrorCache.set(key, {+ ok: false,+ data: {+ error: {+ message:+ error instanceof Error+ ? error.message+ : "Resource diagnostics request failed",+ },+ },+ });+ updateMetadataCache();+ }}} finally {if (pendingDiagnostics.get(key)?.controller === controller) {@@ -361,6 +442,7 @@ const reset = () => {pending.clear();cache.clear();diagnosticsCache.clear();+ diagnosticsErrorCache.clear();performanceCache.clear();for (const { controller } of pendingDiagnostics.values()) {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.tsindex d13a59d7c2..ec104da971 100644--- a/apps/builder/app/shared/rest-resources-loader.node.test.ts+++ b/apps/builder/app/shared/rest-resources-loader.node.test.ts@@ -141,3 +141,46 @@ test("records non-bindable server duration and response size", async () => {],]);});++test("returns every invalid resource field as structured diagnostics", async () => {+ const request = new Request(+ "https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb.localhost/rest/resources-loader",+ { method: "POST" }+ );+ const invalidResource = {+ name: 42,+ method: "invalid",+ searchParams: "invalid",+ headers: "invalid",+ };++ const output = await loadResourceRequestList({+ request,+ requestList: [invalidResource],+ sourceOrigin: "https://source.example",+ includeDiagnostics: true,+ customFetch: vi.fn(),+ });++ expect(output[0]?.[1]).toMatchObject({+ ok: false,+ status: 400,+ statusText: "Bad Request",+ data: {+ error: {+ code: "INVALID_REQUEST",+ message: "Resource request is invalid",+ retryable: false,+ details: {+ issues: expect.arrayContaining([+ expect.objectContaining({ path: ["name"] }),+ expect.objectContaining({ path: ["method"] }),+ expect.objectContaining({ path: ["url"] }),+ expect.objectContaining({ path: ["searchParams"] }),+ expect.objectContaining({ path: ["headers"] }),+ ]),+ },+ },+ },+ });+});diff --git a/docs/university/foundations/content-engine-reference.md b/docs/university/foundations/content-engine-reference.mdindex 3fe37b8e2f..8ef4eaa743 100644--- a/docs/university/foundations/content-engine-reference.md+++ b/docs/university/foundations/content-engine-reference.md@@ -165,6 +165,11 @@ Only `database.usedBytes` counts toward `database.maxBytes`. Do not add the quer| `omittedDocumentCount` | Documents omitted from the compiled database. || `omissionReason` | Why documents were omitted: `size` or `unavailable`. || `truncated` | Whether the compiled database omitted content. |+| `queryIssues` | Structured nonfatal query warnings with a stable code and exact query path. |+| `queryWarnings` | Deprecated plain-text query warnings retained for compatibility. |+| `issues` | All content errors and warnings found in files matched by the current query. Each diagnostic identifies its phase, code, message, asset, path, and source location when available. |+| `issueCount` | Total errors and warnings in `issues`. |+| `issuesTruncated` | Always `false`; retained for response compatibility. || `artifacts` | Optional query and merged compiled artifacts used by detailed Builder diagnostics. || `unresolved` | Optional query result before document references are resolved. It helps inspect the authored `$ref` values behind resolved output. |diff --git a/docs/university/mcp.md b/docs/university/mcp.mdindex b5bda805c1..7e28784626 100644--- a/docs/university/mcp.md+++ b/docs/university/mcp.md@@ -2146,6 +2146,11 @@ Only `database.usedBytes` counts toward `database.maxBytes`. Do not add the quer| `omittedDocumentCount` | Documents omitted from the compiled database. || `omissionReason` | Why documents were omitted: `size` or `unavailable`. || `truncated` | Whether the compiled database omitted content. |+| `queryIssues` | Structured nonfatal query warnings with a stable code and exact query path. |+| `queryWarnings` | Deprecated plain-text query warnings retained for compatibility. |+| `issues` | All content errors and warnings found in files matched by the current query. Each diagnostic identifies its phase, code, message, asset, path, and source location when available. |+| `issueCount` | Total errors and warnings in `issues`. |+| `issuesTruncated` | Always `false`; retained for response compatibility. || `artifacts` | Optional query and merged compiled artifacts used by detailed Builder diagnostics. || `unresolved` | Optional query result before document references are resolved. It helps inspect the authored `$ref` values behind resolved output. |diff --git a/fixtures/react-router-cloudflare/.webstudio/data.json b/fixtures/react-router-cloudflare/.webstudio/data.jsonindex 5a29485a7c..e8960022b5 100644--- a/fixtures/react-router-cloudflare/.webstudio/data.json+++ b/fixtures/react-router-cloudflare/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1mym82p",+ "bundleVersion": "bundle-1xyq4y2","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-docker/.webstudio/data.json b/fixtures/react-router-docker/.webstudio/data.jsonindex 5a29485a7c..e8960022b5 100644--- a/fixtures/react-router-docker/.webstudio/data.json+++ b/fixtures/react-router-docker/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1mym82p",+ "bundleVersion": "bundle-1xyq4y2","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-netlify/.webstudio/data.json b/fixtures/react-router-netlify/.webstudio/data.jsonindex 5a29485a7c..e8960022b5 100644--- a/fixtures/react-router-netlify/.webstudio/data.json+++ b/fixtures/react-router-netlify/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1mym82p",+ "bundleVersion": "bundle-1xyq4y2","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-vercel/.webstudio/data.json b/fixtures/react-router-vercel/.webstudio/data.jsonindex 5a29485a7c..e8960022b5 100644--- a/fixtures/react-router-vercel/.webstudio/data.json+++ b/fixtures/react-router-vercel/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1mym82p",+ "bundleVersion": "bundle-1xyq4y2","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/ssg-cloudflare-pages/.webstudio/data.json b/fixtures/ssg-cloudflare-pages/.webstudio/data.jsonindex 842d2280d3..8f2d5c9b6e 100644--- a/fixtures/ssg-cloudflare-pages/.webstudio/data.json+++ b/fixtures/ssg-cloudflare-pages/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1mym82p",+ "bundleVersion": "bundle-1xyq4y2","build": {"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json b/fixtures/ssg-netlify-by-project-id/.webstudio/data.jsonindex 197ff4036e..0063d0d7d6 100644--- a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json+++ b/fixtures/ssg-netlify-by-project-id/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1mym82p",+ "bundleVersion": "bundle-1xyq4y2","build": {"id": "8f0fdff2-e76b-4f86-9203-ea7df5f1143c","projectId": "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e",diff --git a/fixtures/webstudio-cloudflare-template/.webstudio/data.json b/fixtures/webstudio-cloudflare-template/.webstudio/data.jsonindex 842d2280d3..8f2d5c9b6e 100644--- a/fixtures/webstudio-cloudflare-template/.webstudio/data.json+++ b/fixtures/webstudio-cloudflare-template/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1mym82p",+ "bundleVersion": "bundle-1xyq4y2","build": {"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/webstudio-features/.webstudio/data.json b/fixtures/webstudio-features/.webstudio/data.jsonindex 16bcfd47ca..0e39b766ab 100644--- a/fixtures/webstudio-features/.webstudio/data.json+++ b/fixtures/webstudio-features/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1mym82p",+ "bundleVersion": "bundle-1xyq4y2","build": {"id": "1b66ee06-8ea5-4420-9a0e-e0d3a67aca32","projectId": "cddc1d44-af37-4cb6-a430-d300cf6f932d",diff --git a/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.jsindex 1cf2180777..2277ceef36 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 id=Object.defineProperty;var ad=(t,e)=>{for(var n in e)id(t,n,{get:e[n],enumerable:!0})};var Ks;function g(t,e,n){function r(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=i.prototype,p=Object.keys(u);for(let l=0;l<p.length;l++){let f=p[l];f in a||(a[f]=u[f].bind(a))}}let o=n?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=n?.Parent?new s:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let p of u._zod.deferred)p();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var ty=Symbol("zod_brand"),Ce=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Et=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Ks=globalThis).__zod_globalConfig??(Ks.__zod_globalConfig={});var vt=globalThis.__zod_globalConfig;function ge(t){return t&&Object.assign(vt,t),vt}var M={};ad(M,{BIGINT_FORMAT_RANGES:()=>ei,Class:()=>mo,NUMBER_FORMAT_RANGES:()=>_o,aborted:()=>Xe,allowsEval:()=>go,assert:()=>dd,assertEqual:()=>cd,assertIs:()=>ld,assertNever:()=>fd,assertNotEqual:()=>ud,assignProp:()=>Ye,base64ToUint8Array:()=>ni,base64urlToUint8Array:()=>Cd,cached:()=>Rt,captureStackTrace:()=>Jn,cleanEnum:()=>Od,cleanRegex:()=>cn,clone:()=>be,cloneDef:()=>hd,createTransparentProxy:()=>xd,defineLazy:()=>P,esc:()=>Gn,escapeRegex:()=>Qe,explicitlyAborted:()=>xo,extend:()=>Ed,finalizeIssue:()=>me,floatSafeRemainder:()=>ho,getElementAtPath:()=>yd,getEnumValues:()=>sn,getLengthableOrigin:()=>un,getParsedType:()=>_d,getSizableOrigin:()=>ti,hexToUint8Array:()=>Td,isObject:()=>gt,isPlainObject:()=>He,issue:()=>kt,joinValues:()=>pd,jsonStringifyReplacer:()=>Dt,merge:()=>Dd,mergeDefs:()=>Ue,normalizeParams:()=>I,nullish:()=>an,numKeys:()=>wd,objectClone:()=>md,omit:()=>Ad,optionalKeys:()=>wo,parsedType:()=>Id,partial:()=>Rd,pick:()=>Sd,prefixIssues:()=>Ve,primitiveTypes:()=>Hs,promiseAllObject:()=>gd,propertyKeyTypes:()=>bo,randomString:()=>bd,required:()=>kd,safeExtend:()=>vd,shallowClone:()=>Ys,slugify:()=>yo,stringifyPrimitive:()=>Xs,uint8ArrayToBase64:()=>ri,uint8ArrayToBase64url:()=>Nd,uint8ArrayToHex:()=>$d,unwrapMessage:()=>on});function cd(t){return t}function ud(t){return t}function ld(t){}function fd(t){throw new Error("Unexpected value in exhaustive check")}function dd(t){}function sn(t){let e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,o])=>e.indexOf(+r)===-1).map(([r,o])=>o)}function pd(t,e="|"){return t.map(n=>Xs(n)).join(e)}function Dt(t,e){return typeof e=="bigint"?e.toString():e}function Rt(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function an(t){return t==null}function cn(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function ho(t,e){let n=t/e,r=Math.round(n),o=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<o?0:n-r}var Ws=Symbol("evaluating");function P(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==Ws)return r===void 0&&(r=Ws,r=n()),r},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function md(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Ye(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ue(...t){let e={};for(let n of t){let r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function hd(t){return Ue(t._zod.def)}function yd(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function gd(t){let e=Object.keys(t),n=e.map(r=>t[r]);return Promise.all(n).then(r=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=r[s];return o})}function bd(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<t;r++)n+=e[Math.floor(Math.random()*e.length)];return n}function Gn(t){return JSON.stringify(t)}function yo(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Jn="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function gt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var go=Rt(()=>{if(vt.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function He(t){if(gt(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let n=e.prototype;return!(gt(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Ys(t){return He(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function wd(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}var _d=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},bo=new Set(["string","number","symbol"]),Hs=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Qe(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function be(t,e,n){let r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function I(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function xd(t){let e;return new Proxy({},{get(n,r,o){return e??(e=t()),Reflect.get(e,r,o)},set(n,r,o,s){return e??(e=t()),Reflect.set(e,r,o,s)},has(n,r){return e??(e=t()),Reflect.has(e,r)},deleteProperty(n,r){return e??(e=t()),Reflect.deleteProperty(e,r)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,r){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,r)},defineProperty(n,r,o){return e??(e=t()),Reflect.defineProperty(e,r,o)}})}function Xs(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function wo(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var _o={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},ei={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Sd(t,e){let n=t._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=Ue(t._zod.def,{get shape(){let i={};for(let a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(i[a]=n.shape[a])}return Ye(this,"shape",i),i},checks:[]});return be(t,s)}function Ad(t,e){let n=t._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=Ue(t._zod.def,{get shape(){let i={...t._zod.def.shape};for(let a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete i[a]}return Ye(this,"shape",i),i},checks:[]});return be(t,s)}function Ed(t,e){if(!He(e))throw new Error("Invalid input to extend: expected a plain object");let n=t._zod.def.checks;if(n&&n.length>0){let s=t._zod.def.shape;for(let i in e)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Ue(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return Ye(this,"shape",s),s}});return be(t,o)}function vd(t,e){if(!He(e))throw new Error("Invalid input to safeExtend: expected a plain object");let n=Ue(t._zod.def,{get shape(){let r={...t._zod.def.shape,...e};return Ye(this,"shape",r),r}});return be(t,n)}function Dd(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=Ue(t._zod.def,{get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Ye(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return be(t,n)}function Rd(t,e,n){let o=e._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let i=Ue(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(n)for(let u in n){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(c[u]=t?new t({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)c[u]=t?new t({type:"optional",innerType:a[u]}):a[u];return Ye(this,"shape",c),c},checks:[]});return be(e,i)}function kd(t,e,n){let r=Ue(e._zod.def,{get shape(){let o=e._zod.def.shape,s={...o};if(n)for(let i in n){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(s[i]=new t({type:"nonoptional",innerType:o[i]}))}else for(let i in o)s[i]=new t({type:"nonoptional",innerType:o[i]});return Ye(this,"shape",s),s}});return be(e,r)}function Xe(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function xo(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue===!1)return!0;return!1}function Ve(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function on(t){return typeof t=="string"?t:t?.message}function me(t,e,n){let r=t.message?t.message:on(t.inst?._zod.def?.error?.(t))??on(e?.error?.(t))??on(n.customError?.(t))??on(n.localeError?.(t))??"Invalid input",{inst:o,continue:s,input:i,...a}=t;return a.path??(a.path=[]),a.message=r,e?.reportInput&&(a.input=i),a}function ti(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function un(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Id(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let n=t;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return e}function kt(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function Od(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function ni(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function ri(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}function Cd(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-e.length%4)%4);return ni(e+n)}function Nd(t){return ri(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Td(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let n=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)n[r/2]=Number.parseInt(e.slice(r,r+2),16);return n}function $d(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var mo=class{constructor(...e){}};var oi=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Dt,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},qn=g("$ZodError",oi),So=g("$ZodError",oi,{Parent:Error});function si(t,e=n=>n.message){let n={},r=[];for(let o of t.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:n}}function ii(t,e=n=>n.message){let n={_errors:[]},r=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>r({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")r({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")r({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)n._errors.push(e(i));else{let c=n,u=0;for(;u<a.length;){let p=a[u];u===a.length-1?(c[p]=c[p]||{_errors:[]},c[p]._errors.push(e(i))):c[p]=c[p]||{_errors:[]},c=c[p],u++}}}};return r(t),n}var Kn=t=>(e,n,r,o)=>{let s=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new Ce;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>me(c,s,ge())));throw Jn(a,o?.callee),a}return i.value};var Wn=t=>async(e,n,r,o)=>{let s=r?{...r,async:!0}:{async:!0},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>me(c,s,ge())));throw Jn(a,o?.callee),a}return i.value};var ln=t=>(e,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Ce;return s.issues.length?{success:!1,error:new(t??qn)(s.issues.map(i=>me(i,o,ge())))}:{success:!0,data:s.value}},ai=ln(So),fn=t=>async(e,n,r)=>{let o=r?{...r,async:!0}:{async:!0},s=e._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>me(i,o,ge())))}:{success:!0,data:s.value}},ci=fn(So),ui=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Kn(t)(e,n,o)};var li=t=>(e,n,r)=>Kn(t)(e,n,r);var fi=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Wn(t)(e,n,o)};var di=t=>async(e,n,r)=>Wn(t)(e,n,r);var pi=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return ln(t)(e,n,o)};var mi=t=>(e,n,r)=>ln(t)(e,n,r);var hi=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return fn(t)(e,n,o)};var yi=t=>async(e,n,r)=>fn(t)(e,n,r);var gi=/^[cC][0-9a-z]{6,}$/,bi=/^[0-9a-z]+$/,wi=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,_i=/^[0-9a-vA-V]{20}$/,xi=/^[A-Za-z0-9]{27}$/,Si=/^[a-zA-Z0-9_-]{21}$/,Ai=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Ei=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ao=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;var vi=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Pd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Di(){return new RegExp(Pd,"u")}var Ri=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ki=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var Ii=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Oi=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ci=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Eo=/^[A-Za-z0-9_-]*$/;var Ni=/^https?$/,Ti=/^\+[1-9]\d{6,14}$/,$i="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",zi=new RegExp(`^${$i}$`);function Pi(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Li(t){return new RegExp(`^${Pi(t)}$`)}function Mi(t){let e=Pi({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${e}(?:${n.join("|")})`;return new RegExp(`^${$i}T(?:${r})$`)}var Fi=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Zi=/^-?\d+$/,vo=/^-?\d+(?:\.\d+)?$/,Bi=/^(?:true|false)$/i,ji=/^null$/i;var Ui=/^[^A-Z]*$/,Qi=/^[^a-z]*$/;var X=g("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Vi={number:"number",bigint:"bigint",object:"date"},Do=g("$ZodCheckLessThan",(t,e)=>{X.init(t,e);let n=Vi[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Ro=g("$ZodCheckGreaterThan",(t,e)=>{X.init(t,e);let n=Vi[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Gi=g("$ZodCheckMultipleOf",(t,e)=>{X.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):ho(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),Ji=g("$ZodCheckNumberFormat",(t,e)=>{X.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,s]=_o[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,n&&(a.pattern=Zi)}),t._zod.check=i=>{let a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,inclusive:!0,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,inclusive:!0,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:t,continue:!e.abort})}});var qi=g("$ZodCheckMaxLength",(t,e)=>{var n;X.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!an(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let o=r.value;if(o.length<=e.maximum)return;let i=un(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Ki=g("$ZodCheckMinLength",(t,e)=>{var n;X.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!an(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let o=r.value;if(o.length>=e.minimum)return;let i=un(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Wi=g("$ZodCheckLengthEquals",(t,e)=>{var n;X.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!an(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=r=>{let o=r.value,s=o.length;if(s===e.length)return;let i=un(o),a=s>e.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),dn=g("$ZodCheckStringFormat",(t,e)=>{var n,r;X.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),Yi=g("$ZodCheckRegex",(t,e)=>{dn.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Hi=g("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Ui),dn.init(t,e)}),Xi=g("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Qi),dn.init(t,e)}),ea=g("$ZodCheckIncludes",(t,e)=>{X.init(t,e);let n=Qe(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),ta=g("$ZodCheckStartsWith",(t,e)=>{X.init(t,e);let n=new RegExp(`^${Qe(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),na=g("$ZodCheckEndsWith",(t,e)=>{X.init(t,e);let n=new RegExp(`.*${Qe(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}});var ra=g("$ZodCheckOverwrite",(t,e)=>{X.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});var Hn=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`+var md=Object.defineProperty;var hd=(t,e)=>{for(var n in e)md(t,n,{get:e[n],enumerable:!0})};var Xs;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 py=Symbol("zod_brand"),Oe=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},vt=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Xs=globalThis).__zod_globalConfig??(Xs.__zod_globalConfig={});var Dt=globalThis.__zod_globalConfig;function _e(t){return t&&Object.assign(Dt,t),Dt}var F={};hd(F,{BIGINT_FORMAT_RANGES:()=>ri,Class:()=>mo,NUMBER_FORMAT_RANGES:()=>_o,aborted:()=>He,allowsEval:()=>go,assert:()=>_d,assertEqual:()=>yd,assertIs:()=>bd,assertNever:()=>wd,assertNotEqual:()=>gd,assignProp:()=>Ye,base64ToUint8Array:()=>si,base64urlToUint8Array:()=>Fd,cached:()=>kt,captureStackTrace:()=>qn,cleanEnum:()=>Md,cleanRegex:()=>fn,clone:()=>xe,cloneDef:()=>Sd,createTransparentProxy:()=>Id,defineLazy:()=>M,esc:()=>Gn,escapeRegex:()=>Ue,explicitlyAborted:()=>xo,extend:()=>Td,finalizeIssue:()=>me,floatSafeRemainder:()=>ho,getElementAtPath:()=>Ad,getEnumValues:()=>un,getLengthableOrigin:()=>dn,getParsedType:()=>kd,getSizableOrigin:()=>oi,hexToUint8Array:()=>Bd,isObject:()=>gt,isPlainObject:()=>Xe,issue:()=>It,joinValues:()=>xd,jsonStringifyReplacer:()=>Rt,merge:()=>$d,mergeDefs:()=>je,normalizeParams:()=>I,nullish:()=>ln,numKeys:()=>Rd,objectClone:()=>Ed,omit:()=>Cd,optionalKeys:()=>wo,parsedType:()=>Ld,partial:()=>zd,pick:()=>Od,prefixIssues:()=>Qe,primitiveTypes:()=>ti,promiseAllObject:()=>vd,propertyKeyTypes:()=>bo,randomString:()=>Dd,required:()=>Pd,safeExtend:()=>Nd,shallowClone:()=>ei,slugify:()=>yo,stringifyPrimitive:()=>ni,uint8ArrayToBase64:()=>ii,uint8ArrayToBase64url:()=>Zd,uint8ArrayToHex:()=>jd,unwrapMessage:()=>cn});function yd(t){return t}function gd(t){return t}function bd(t){}function wd(t){throw new Error("Unexpected value in exhaustive check")}function _d(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 xd(t,e="|"){return t.map(n=>ni(n)).join(e)}function Rt(t,e){return typeof e=="bigint"?e.toString():e}function kt(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function 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 Hs=Symbol("evaluating");function M(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==Hs)return r===void 0&&(r=Hs,r=n()),r},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Ed(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 Sd(t){return je(t._zod.def)}function Ad(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function vd(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 Dd(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 gt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var go=kt(()=>{if(Dt.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(gt(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let n=e.prototype;return!(gt(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function ei(t){return Xe(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function Rd(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}var kd=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"]),ti=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 Id(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 ni(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]},ri={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Od(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 Cd(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 Td(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 Nd(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 $d(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 zd(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 Pd(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 oi(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 Ld(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 It(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function Md(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function si(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 ii(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}function Fd(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-e.length%4)%4);return si(e+n)}function Zd(t){return ii(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Bd(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 jd(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var mo=class{constructor(...e){}};var ai=(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,Rt,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Jn=b("$ZodError",ai),Eo=b("$ZodError",ai,{Parent:Error});function ci(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 ui(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}},li=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}},fi=mn(Eo),di=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Kn(t)(e,n,o)};var pi=t=>(e,n,r)=>Kn(t)(e,n,r);var mi=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Wn(t)(e,n,o)};var hi=t=>async(e,n,r)=>Wn(t)(e,n,r);var yi=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return pn(t)(e,n,o)};var gi=t=>(e,n,r)=>pn(t)(e,n,r);var bi=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return mn(t)(e,n,o)};var wi=t=>async(e,n,r)=>mn(t)(e,n,r);var _i=/^[cC][0-9a-z]{6,}$/,xi=/^[0-9a-z]+$/,Ei=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Si=/^[0-9a-vA-V]{20}$/,Ai=/^[A-Za-z0-9]{27}$/,vi=/^[a-zA-Z0-9_-]{21}$/,Di=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Ri=/^([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 ki=/^(?!\.)(?!.*\.\.)([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 Ii(){return new RegExp(Qd,"u")}var Oi=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ci=/^(([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 Ti=/^((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])$/,Ni=/^(([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])$/,$i=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ao=/^[A-Za-z0-9_-]*$/;var zi=/^https?$/,Pi=/^\+[1-9]\d{6,14}$/,Li="(?:(?:\\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])))",Mi=new RegExp(`^${Li}$`);function Fi(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 Zi(t){return new RegExp(`^${Fi(t)}$`)}function Bi(t){let e=Fi({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(`^${Li}T(?:${r})$`)}var ji=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Ui=/^-?\d+$/,vo=/^-?\d+(?:\.\d+)?$/,Qi=/^(?:true|false)$/i,Vi=/^null$/i;var Gi=/^[^A-Z]*$/,qi=/^[^a-z]*$/;var te=b("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Ji={number:"number",bigint:"bigint",object:"date"},Do=b("$ZodCheckLessThan",(t,e)=>{te.init(t,e);let n=Ji[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=Ji[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})}}),Ki=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})}}),Wi=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=Ui)}),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 Yi=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})}}),Xi=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})}}),Hi=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=()=>{})}),ea=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})}}),ta=b("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Gi),hn.init(t,e)}),na=b("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=qi),hn.init(t,e)}),ra=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})}}),oa=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})}}),sa=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 ia=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(``).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 sa={major:4,minor:4,patch:3};var j=g("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=sa;let r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(let o of r)for(let s of o._zod.onattach)s(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,a,c)=>{let u=Xe(i),p;for(let l of a){if(l._zod.def.when){if(xo(i)||!l._zod.def.when(i))continue}else if(u)continue;let f=i.issues.length,d=l._zod.check(i);if(d instanceof Promise&&c?.async===!1)throw new Ce;if(p||d instanceof Promise)p=(p??Promise.resolve()).then(async()=>{await d,i.issues.length!==f&&(u||(u=Xe(i,f)))});else{if(i.issues.length===f)continue;u||(u=Xe(i,f))}}return p?p.then(()=>i):i},s=(i,a,c)=>{if(Xe(i))return i.aborted=!0,i;let u=o(a,r,c);if(u instanceof Promise){if(c.async===!1)throw new Ce;return u.then(p=>t._zod.parse(p,c))}return t._zod.parse(u,c)};t._zod.run=(i,a)=>{if(a.skipChecks)return t._zod.parse(i,a);if(a.direction==="backward"){let u=t._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(p=>s(p,i,a)):s(u,i,a)}let c=t._zod.parse(i,a);if(c instanceof Promise){if(a.async===!1)throw new Ce;return c.then(u=>o(u,r,a))}return o(c,r,a)}}P(t,"~standard",()=>({validate:o=>{try{let s=ai(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return ci(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),tr=g("$ZodString",(t,e)=>{j.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Fi(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),U=g("$ZodStringFormat",(t,e)=>{dn.init(t,e),tr.init(t,e)}),ma=g("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Ei),U.init(t,e)}),ha=g("$ZodUUID",(t,e)=>{if(e.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Ao(r))}else e.pattern??(e.pattern=Ao());U.init(t,e)}),ya=g("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=vi),U.init(t,e)}),ga=g("$ZodURL",(t,e)=>{U.init(t,e),t._zod.check=n=>{try{let r=n.value.trim();if(!e.normalize&&e.protocol?.source===Ni.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:t,continue:!e.abort});return}let o=new URL(r);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),e.normalize?n.value=o.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),ba=g("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Di()),U.init(t,e)}),wa=g("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Si),U.init(t,e)}),_a=g("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=gi),U.init(t,e)}),xa=g("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=bi),U.init(t,e)}),Sa=g("$ZodULID",(t,e)=>{e.pattern??(e.pattern=wi),U.init(t,e)}),Aa=g("$ZodXID",(t,e)=>{e.pattern??(e.pattern=_i),U.init(t,e)}),Ea=g("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=xi),U.init(t,e)}),va=g("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Mi(e)),U.init(t,e)}),Da=g("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=zi),U.init(t,e)}),Ra=g("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Li(e)),U.init(t,e)}),ka=g("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Ai),U.init(t,e)}),Ia=g("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Ri),U.init(t,e),t._zod.bag.format="ipv4"}),Oa=g("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=ki),U.init(t,e),t._zod.bag.format="ipv6",t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}});var Ca=g("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Ii),U.init(t,e)}),Na=g("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Oi),U.init(t,e),t._zod.check=n=>{let r=n.value.split("/");try{if(r.length!==2)throw new Error;let[o,s]=r;if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function Ta(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var $a=g("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Ci),U.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{Ta(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function Ld(t){if(!Eo.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Ta(n)}var za=g("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Eo),U.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{Ld(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Pa=g("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Ti),U.init(t,e)});function Md(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var La=g("$ZodJWT",(t,e)=>{U.init(t,e),t._zod.check=n=>{Md(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}});var Io=g("$ZodNumber",(t,e)=>{j.init(t,e),t._zod.pattern=t._zod.bag.pattern??vo,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}let o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),n}}),Ma=g("$ZodNumberFormat",(t,e)=>{Ji.init(t,e),Io.init(t,e)}),Fa=g("$ZodBoolean",(t,e)=>{j.init(t,e),t._zod.pattern=Bi,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}let o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),n}});var Za=g("$ZodNull",(t,e)=>{j.init(t,e),t._zod.pattern=ji,t._zod.values=new Set([null]),t._zod.parse=(n,r)=>{let o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),n}});var Ba=g("$ZodUnknown",(t,e)=>{j.init(t,e),t._zod.parse=n=>n}),ja=g("$ZodNever",(t,e)=>{j.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function ia(t,e,n){t.issues.length&&e.issues.push(...Ve(n,t.issues)),e.value[n]=t.value}var Ua=g("$ZodArray",(t,e)=>{j.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),n;n.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},r);c instanceof Promise?s.push(c.then(u=>ia(u,n,i))):ia(c,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function er(t,e,n,r,o,s){let i=n in r;if(t.issues.length){if(o&&s&&!i)return;e.issues.push(...Ve(n,t.issues))}if(!i&&!o){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}t.value===void 0?i&&(e.value[n]=void 0):e.value[n]=t.value}function Qa(t){let e=Object.keys(t.shape);for(let r of e)if(!t.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);let n=wo(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Va(t,e,n,r,o,s){let i=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,p=c.optin==="optional",l=c.optout==="optional";for(let f in e){if(f==="__proto__"||a.has(f))continue;if(u==="never"){i.push(f);continue}let d=c.run({value:e[f],issues:[]},r);d instanceof Promise?t.push(d.then(y=>er(y,n,f,e,p,l))):er(d,n,f,e,p,l)}return i.length&&n.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:s}),t.length?Promise.all(t).then(()=>n):n}var Fd=g("$ZodObject",(t,e)=>{if(j.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let r=Rt(()=>Qa(e));P(t._zod,"propValues",()=>{let a=e.shape,c={};for(let u in a){let p=a[u]._zod;if(p.values){c[u]??(c[u]=new Set);for(let l of p.values)c[u].add(l)}}return c});let o=gt,s=e.catchall,i;t._zod.parse=(a,c)=>{i??(i=r.value);let u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let p=[],l=i.shape;for(let f of i.keys){let d=l[f],y=d._zod.optin==="optional",m=d._zod.optout==="optional",h=d._zod.run({value:u[f],issues:[]},c);h instanceof Promise?p.push(h.then(b=>er(b,a,f,u,y,m))):er(h,a,f,u,y,m)}return s?Va(p,u,a,c,r.value,t):p.length?Promise.all(p).then(()=>a):a}}),Ga=g("$ZodObjectJIT",(t,e)=>{Fd.init(t,e);let n=t._zod.parse,r=Rt(()=>Qa(e)),o=f=>{let d=new Hn(["shape","payload","ctx"]),y=r.value,m=A=>{let _=Gn(A);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};d.write("const input = payload.value;");let h=Object.create(null),b=0;for(let A of y.keys)h[A]=`key_${b++}`;d.write("const newResult = {};");for(let A of y.keys){let _=h[A],w=Gn(A),E=f[A],D=E?._zod?.optin==="optional",x=E?._zod?.optout==="optional";d.write(`const ${_} = ${m(A)};`),D&&x?d.write(`+`))}};var ca={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=ca;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=li(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return fi(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()??ji(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)}),ga=b("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Ri),Q.init(t,e)}),ba=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)}),wa=b("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=ki),Q.init(t,e)}),_a=b("$ZodURL",(t,e)=>{Q.init(t,e),t._zod.check=n=>{try{let r=n.value.trim();if(!e.normalize&&e.protocol?.source===zi.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})}}}),xa=b("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Ii()),Q.init(t,e)}),Ea=b("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=vi),Q.init(t,e)}),Sa=b("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=_i),Q.init(t,e)}),Aa=b("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=xi),Q.init(t,e)}),va=b("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Ei),Q.init(t,e)}),Da=b("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Si),Q.init(t,e)}),Ra=b("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Ai),Q.init(t,e)}),ka=b("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Bi(e)),Q.init(t,e)}),Ia=b("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Mi),Q.init(t,e)}),Oa=b("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Zi(e)),Q.init(t,e)}),Ca=b("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Di),Q.init(t,e)}),Ta=b("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Oi),Q.init(t,e),t._zod.bag.format="ipv4"}),Na=b("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Ci),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 $a=b("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Ti),Q.init(t,e)}),za=b("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Ni),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 Pa(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var La=b("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=$i),Q.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{Pa(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function Vd(t){if(!Ao.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Pa(n)}var Ma=b("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Ao),Q.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{Vd(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Fa=b("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Pi),Q.init(t,e)});function Gd(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 Za=b("$ZodJWT",(t,e)=>{Q.init(t,e),t._zod.check=n=>{Gd(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}}),Ba=b("$ZodNumberFormat",(t,e)=>{Wi.init(t,e),Io.init(t,e)}),ja=b("$ZodBoolean",(t,e)=>{U.init(t,e),t._zod.pattern=Qi,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 Ua=b("$ZodNull",(t,e)=>{U.init(t,e),t._zod.pattern=Vi,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 Qa=b("$ZodUnknown",(t,e)=>{U.init(t,e),t._zod.parse=n=>n}),Va=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 ua(t,e,n){t.issues.length&&e.issues.push(...Qe(n,t.issues)),e.value[n]=t.value}var Ga=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=>ua(u,n,i))):ua(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 qa(t){let e=Object.keys(t.shape);for(let r of e)if(!t.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);let n=wo(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Ja(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 qd=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=kt(()=>qa(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=gt,s=e.catchall,i;t._zod.parse=(a,c)=>{i??(i=r.value);let u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let 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?Ja(d,u,a,c,r.value,t):d.length?Promise.all(d).then(()=>a):a}}),Ka=b("$ZodObjectJIT",(t,e)=>{qd.init(t,e);let n=t._zod.parse,r=kt(()=>qa(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(`if (${_}.issues.length) {if (${w} in input) {payload.issues = payload.issues.concat(${_}.issues.map(iss => ({@@ -18,7 +18,7 @@ var id=Object.defineProperty;var ad=(t,e)=>{for(var n in e)id(t,n,{get:e[n],enumnewResult[${w}] = ${_}.value;}- `):D?d.write(`+ `):D?p.write(`if (${_}.issues.length) {payload.issues = payload.issues.concat(${_}.issues.map(iss => ({...iss,@@ -34,7 +34,7 @@ var id=Object.defineProperty;var ad=(t,e)=>{for(var n in e)id(t,n,{get:e[n],enumnewResult[${w}] = ${_}.value;}- `):d.write(`+ `):p.write(`const ${_}_present = ${w} in input;if (${_}.issues.length) {payload.issues = payload.issues.concat(${_}.issues.map(iss => ({@@ -59,136 +59,136 @@ var id=Object.defineProperty;var ad=(t,e)=>{for(var n in e)id(t,n,{get:e[n],enum}}- `)}d.write("payload.value = newResult;"),d.write("return payload;");let S=d.compile();return(A,_)=>S(f,A,_)},s,i=gt,a=!vt.jitless,u=a&&go.value,p=e.catchall,l;t._zod.parse=(f,d)=>{l??(l=r.value);let y=f.value;return i(y)?a&&u&&d?.async===!1&&d.jitless!==!0?(s||(s=o(e.shape)),f=s(f,d),p?Va([],y,f,d,l,t):f):n(f,d):(f.issues.push({expected:"object",code:"invalid_type",input:y,inst:t}),f)}});function aa(t,e,n,r){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;let o=t.filter(s=>!Xe(s));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(s=>s.issues.map(i=>me(i,r,ge())))}),e)}var Oo=g("$ZodUnion",(t,e)=>{j.init(t,e),P(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),P(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),P(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),P(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>cn(o.source)).join("|")})$`)}});let n=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(r,o)=>{if(n)return n(r,o);let s=!1,i=[];for(let a of e.options){let c=a._zod.run({value:r.value,issues:[]},o);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}return s?Promise.all(i).then(a=>aa(a,r,t,o)):aa(i,r,t,o)}});var Ja=g("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,Oo.init(t,e);let n=t._zod.parse;P(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let r=Rt(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!gt(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=r.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback||s.direction==="backward"?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(r.value.keys()),input:i,path:[e.discriminator],inst:t}),o)}}),qa=g("$ZodIntersection",(t,e)=>{j.init(t,e),t._zod.parse=(n,r)=>{let o=n.value,s=e.left._zod.run({value:o,issues:[]},r),i=e.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>ca(n,c,u)):ca(n,s,i)}});function ko(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(He(t)&&He(e)){let n=Object.keys(e),r=Object.keys(t).filter(s=>n.indexOf(s)!==-1),o={...t,...e};for(let s of r){let i=ko(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<t.length;r++){let o=t[r],s=e[r],i=ko(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function ca(t,e,n){let r=new Map,o;for(let a of e.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(let c of a.keys)r.has(c)||r.set(c,{}),r.get(c).l=!0}else t.issues.push(a);for(let a of n.issues)if(a.code==="unrecognized_keys")for(let c of a.keys)r.has(c)||r.set(c,{}),r.get(c).r=!0;else t.issues.push(a);let s=[...r].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&o&&t.issues.push({...o,keys:s}),Xe(t))return t;let i=ko(e.value,n.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return t.value=i.data,t}var Ka=g("$ZodRecord",(t,e)=>{j.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!He(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let s=[],i=e.keyType._zod.values;if(i){n.value={};let a=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let p=e.keyType._zod.run({value:u,issues:[]},r);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(p.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map(d=>me(d,r,ge())),input:u,path:[u],inst:t});continue}let l=p.value,f=e.valueType._zod.run({value:o[u],issues:[]},r);f instanceof Promise?s.push(f.then(d=>{d.issues.length&&n.issues.push(...Ve(u,d.issues)),n.value[l]=d.value})):(f.issues.length&&n.issues.push(...Ve(u,f.issues)),n.value[l]=f.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{n.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},r);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&vo.test(a)&&c.issues.length){let l=e.keyType._zod.run({value:Number(a),issues:[]},r);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");l.issues.length===0&&(c=l)}if(c.issues.length){e.mode==="loose"?n.value[a]=o[a]:n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(l=>me(l,r,ge())),input:a,path:[a],inst:t});continue}let p=e.valueType._zod.run({value:o[a],issues:[]},r);p instanceof Promise?s.push(p.then(l=>{l.issues.length&&n.issues.push(...Ve(a,l.issues)),n.value[c.value]=l.value})):(p.issues.length&&n.issues.push(...Ve(a,p.issues)),n.value[c.value]=p.value)}}return s.length?Promise.all(s).then(()=>n):n}});var Wa=g("$ZodEnum",(t,e)=>{j.init(t,e);let n=sn(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(o=>bo.has(typeof o)).map(o=>typeof o=="string"?Qe(o):o.toString()).join("|")})$`),t._zod.parse=(o,s)=>{let i=o.value;return r.has(i)||o.issues.push({code:"invalid_value",values:n,input:i,inst:t}),o}}),Ya=g("$ZodLiteral",(t,e)=>{if(j.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let n=new Set(e.values);t._zod.values=n,t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Qe(r):r?Qe(r.toString()):String(r)).join("|")})$`),t._zod.parse=(r,o)=>{let s=r.value;return n.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}});var Ha=g("$ZodTransform",(t,e)=>{j.init(t,e),t._zod.optin="optional",t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Et(t.constructor.name);let o=e.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n.fallback=!0,n));if(o instanceof Promise)throw new Ce;return n.value=o,n.fallback=!0,n}});function ua(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var Co=g("$ZodOptional",(t,e)=>{j.init(t,e),t._zod.optin="optional",t._zod.optout="optional",P(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),P(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${cn(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>{if(e.innerType._zod.optin==="optional"){let o=n.value,s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(i=>ua(i,o)):ua(s,o)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),Xa=g("$ZodExactOptional",(t,e)=>{Co.init(t,e),P(t._zod,"values",()=>e.innerType._zod.values),P(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(n,r)=>e.innerType._zod.run(n,r)}),ec=g("$ZodNullable",(t,e)=>{j.init(t,e),P(t._zod,"optin",()=>e.innerType._zod.optin),P(t._zod,"optout",()=>e.innerType._zod.optout),P(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${cn(n.source)}|null)$`):void 0}),P(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),tc=g("$ZodDefault",(t,e)=>{j.init(t,e),t._zod.optin="optional",P(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);if(n.value===void 0)return n.value=e.defaultValue,n;let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>la(s,e)):la(o,e)}});function la(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var nc=g("$ZodPrefault",(t,e)=>{j.init(t,e),t._zod.optin="optional",P(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),rc=g("$ZodNonOptional",(t,e)=>{j.init(t,e),P(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>fa(s,t)):fa(o,t)}});function fa(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var oc=g("$ZodCatch",(t,e)=>{j.init(t,e),t._zod.optin="optional",P(t._zod,"optout",()=>e.innerType._zod.optout),P(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(i=>me(i,r,ge()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(s=>me(s,r,ge()))},input:n.value}),n.issues=[],n.fallback=!0),n)}});var sc=g("$ZodPipe",(t,e)=>{j.init(t,e),P(t._zod,"values",()=>e.in._zod.values),P(t._zod,"optin",()=>e.in._zod.optin),P(t._zod,"optout",()=>e.out._zod.optout),P(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,r)=>{if(r.direction==="backward"){let s=e.out._zod.run(n,r);return s instanceof Promise?s.then(i=>Xn(i,e.in,r)):Xn(s,e.in,r)}let o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Xn(s,e.out,r)):Xn(o,e.out,r)}});function Xn(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},n)}var ic=g("$ZodReadonly",(t,e)=>{j.init(t,e),P(t._zod,"propValues",()=>e.innerType._zod.propValues),P(t._zod,"values",()=>e.innerType._zod.values),P(t._zod,"optin",()=>e.innerType?._zod?.optin),P(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(da):da(o)}});function da(t){return t.value=Object.freeze(t.value),t}var ac=g("$ZodLazy",(t,e)=>{j.init(t,e),P(t._zod,"innerType",()=>{let n=e;return n._cachedInner||(n._cachedInner=e.getter()),n._cachedInner}),P(t._zod,"pattern",()=>t._zod.innerType?._zod?.pattern),P(t._zod,"propValues",()=>t._zod.innerType?._zod?.propValues),P(t._zod,"optin",()=>t._zod.innerType?._zod?.optin??void 0),P(t._zod,"optout",()=>t._zod.innerType?._zod?.optout??void 0),t._zod.parse=(n,r)=>t._zod.innerType._zod.run(n,r)}),cc=g("$ZodCustom",(t,e)=>{X.init(t,e),j.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{let r=n.value,o=e.fn(r);if(o instanceof Promise)return o.then(s=>pa(s,n,r,t));pa(o,n,r,t)}});function pa(t,e,n,r){if(!t){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),e.issues.push(kt(o))}}var uc,by=Symbol("ZodOutput"),wy=Symbol("ZodInput"),No=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...n){let r=n[0];return this._map.set(e,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let r={...this.get(n)??{}};delete r.id;let o={...r,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Zd(){return new No}(uc=globalThis).__zod_globalRegistry??(uc.__zod_globalRegistry=Zd());var bt=globalThis.__zod_globalRegistry;function lc(t,e){return new t({type:"string",...I(e)})}function fc(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...I(e)})}function To(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...I(e)})}function dc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...I(e)})}function pc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(e)})}function mc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(e)})}function hc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(e)})}function yc(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...I(e)})}function gc(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...I(e)})}function bc(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(e)})}function wc(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...I(e)})}function _c(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(e)})}function xc(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...I(e)})}function Sc(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...I(e)})}function Ac(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(e)})}function Ec(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(e)})}function vc(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(e)})}function Dc(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(e)})}function Rc(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(e)})}function kc(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...I(e)})}function Ic(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...I(e)})}function Oc(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...I(e)})}function Cc(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...I(e)})}function Nc(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(e)})}function Tc(t,e){return new t({type:"string",format:"date",check:"string_format",...I(e)})}function $c(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...I(e)})}function zc(t,e){return new t({type:"string",format:"duration",check:"string_format",...I(e)})}function Pc(t,e){return new t({type:"number",checks:[],...I(e)})}function Lc(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...I(e)})}function Mc(t,e){return new t({type:"boolean",...I(e)})}function Fc(t,e){return new t({type:"null",...I(e)})}function Zc(t){return new t({type:"unknown"})}function Bc(t,e){return new t({type:"never",...I(e)})}function nr(t,e){return new Do({check:"less_than",...I(e),value:t,inclusive:!1})}function pn(t,e){return new Do({check:"less_than",...I(e),value:t,inclusive:!0})}function rr(t,e){return new Ro({check:"greater_than",...I(e),value:t,inclusive:!1})}function mn(t,e){return new Ro({check:"greater_than",...I(e),value:t,inclusive:!0})}function or(t,e){return new Gi({check:"multiple_of",...I(e),value:t})}function sr(t,e){return new qi({check:"max_length",...I(e),maximum:t})}function It(t,e){return new Ki({check:"min_length",...I(e),minimum:t})}function ir(t,e){return new Wi({check:"length_equals",...I(e),length:t})}function $o(t,e){return new Yi({check:"string_format",format:"regex",...I(e),pattern:t})}function zo(t){return new Hi({check:"string_format",format:"lowercase",...I(t)})}function Po(t){return new Xi({check:"string_format",format:"uppercase",...I(t)})}function Lo(t,e){return new ea({check:"string_format",format:"includes",...I(e),includes:t})}function Mo(t,e){return new ta({check:"string_format",format:"starts_with",...I(e),prefix:t})}function Fo(t,e){return new na({check:"string_format",format:"ends_with",...I(e),suffix:t})}function et(t){return new ra({check:"overwrite",tx:t})}function Zo(t){return et(e=>e.normalize(t))}function Bo(){return et(t=>t.trim())}function jo(){return et(t=>t.toLowerCase())}function Uo(){return et(t=>t.toUpperCase())}function Qo(){return et(t=>yo(t))}function jc(t,e,n){return new t({type:"array",element:e,...I(n)})}function Uc(t,e,n){return new t({type:"custom",check:"custom",fn:e,...I(n)})}function Qc(t,e){let n=Bd(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(kt(o,r.value,n._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),r.issues.push(kt(s))}},t(r.value,r)),e);return n}function Bd(t,e){let n=new X({check:"custom",...I(e)});return n._zod.check=t,n}function Vo(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??bt,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function q(t,e,n={path:[],schemaPath:[]}){var r;let o=t._zod.def,s=e.seen.get(t);if(s)return s.count++,n.schemaPath.includes(t)&&(s.cycle=n.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:n.path};e.seen.set(t,i);let a=t._zod.toJSONSchema?.();if(a)i.schema=a;else{let p={...n,schemaPath:[...n.schemaPath,t],path:n.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,i.schema,p);else{let f=i.schema,d=e.processors[o.type];if(!d)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);d(t,e,f,p)}let l=t._zod.parent;l&&(i.ref||(i.ref=l),q(l,e,p),e.seen.get(l).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),e.io==="input"&&ne(t)&&(delete i.schema.examples,delete i.schema.default),e.io==="input"&&"_prefault"in i.schema&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,e.seen.get(t).schema}function Go(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=new Map;for(let i of t.seen.entries()){let a=t.metadataRegistry.get(i[0])?.id;if(a){let c=r.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,i[0])}}let o=i=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let l=t.external.registry.get(i[0])?.id,f=t.external.uri??(y=>y);if(l)return{ref:f(l)};let d=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=d,{defId:d,ref:`${f("__shared")}#/${a}/${d}`}}if(i[1]===n)return{ref:"#"};let u=`#/${a}/`,p=i[1].schema.id??`__schema${t.counter++}`;return{defId:p,ref:u+p}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=o(i);a.def={...a.schema},u&&(a.defId=u);let p=a.schema;for(let l in p)delete p[l];p.$ref=c};if(t.cycles==="throw")for(let i of t.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>+ `)}p.write("payload.value = newResult;"),p.write("return payload;");let x=p.compile();return(S,_)=>x(f,S,_)},s,i=gt,a=!Dt.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?Ja([],y,f,p,l,t):f):n(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:y,inst:t}),f)}});function la(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=>la(a,r,t,o)):la(i,r,t,o)}});var Wa=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=kt(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!gt(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=r.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback||s.direction==="backward"?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(r.value.keys()),input:i,path:[e.discriminator],inst:t}),o)}}),Ya=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])=>fa(n,c,u)):fa(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 fa(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 Xa=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 Ha=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}}),ec=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 tc=b("$ZodTransform",(t,e)=>{U.init(t,e),t._zod.optin="optional",t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new vt(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 da(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=>da(i,o)):da(s,o)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),nc=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)}),rc=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)}),oc=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=>pa(s,e)):pa(o,e)}});function pa(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var sc=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))}),ic=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=>ma(s,t)):ma(o,t)}});function ma(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 ac=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 cc=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 uc=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(ha):ha(o)}});function ha(t){return t.value=Object.freeze(t.value),t}var lc=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)}),fc=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=>ya(s,n,r,t));ya(o,n,r,t)}});function ya(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(It(o))}}var dc,Oy=Symbol("ZodOutput"),Cy=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 Jd(){return new To}(dc=globalThis).__zod_globalRegistry??(dc.__zod_globalRegistry=Jd());var bt=globalThis.__zod_globalRegistry;function pc(t,e){return new t({type:"string",...I(e)})}function mc(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 hc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...I(e)})}function yc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(e)})}function gc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(e)})}function bc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(e)})}function wc(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...I(e)})}function _c(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...I(e)})}function xc(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(e)})}function Ec(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...I(e)})}function Sc(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(e)})}function Ac(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...I(e)})}function vc(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...I(e)})}function Dc(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(e)})}function Rc(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(e)})}function kc(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(e)})}function Ic(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(e)})}function Oc(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(e)})}function Cc(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...I(e)})}function Tc(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...I(e)})}function Nc(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...I(e)})}function $c(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...I(e)})}function zc(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(e)})}function Pc(t,e){return new t({type:"string",format:"date",check:"string_format",...I(e)})}function Lc(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...I(e)})}function Mc(t,e){return new t({type:"string",format:"duration",check:"string_format",...I(e)})}function Fc(t,e){return new t({type:"number",checks:[],...I(e)})}function Zc(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...I(e)})}function Bc(t,e){return new t({type:"boolean",...I(e)})}function jc(t,e){return new t({type:"null",...I(e)})}function Uc(t){return new t({type:"unknown"})}function Qc(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 Ki({check:"multiple_of",...I(e),value:t})}function sr(t,e){return new Yi({check:"max_length",...I(e),maximum:t})}function Ot(t,e){return new Xi({check:"min_length",...I(e),minimum:t})}function ir(t,e){return new Hi({check:"length_equals",...I(e),length:t})}function $o(t,e){return new ea({check:"string_format",format:"regex",...I(e),pattern:t})}function zo(t){return new ta({check:"string_format",format:"lowercase",...I(t)})}function Po(t){return new na({check:"string_format",format:"uppercase",...I(t)})}function Lo(t,e){return new ra({check:"string_format",format:"includes",...I(e),includes:t})}function Mo(t,e){return new oa({check:"string_format",format:"starts_with",...I(e),prefix:t})}function Fo(t,e){return new sa({check:"string_format",format:"ends_with",...I(e),suffix:t})}function et(t){return new ia({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 Vc(t,e,n){return new t({type:"array",element:e,...I(n)})}function Gc(t,e,n){return new t({type:"custom",check:"custom",fn:e,...I(n)})}function qc(t,e){let n=Kd(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(It(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(It(s))}},t(r.value,r)),e);return n}function Kd(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??bt,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function 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>-Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of t.seen.entries()){let a=i[1];if(e===i[0]){s(i);continue}if(t.external){let u=t.external.registry.get(i[0])?.id;if(e!==i[0]&&u){s(i);continue}}if(t.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&t.reused==="ref"){s(i);continue}}}function Jo(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,p={...u},l=c.ref;if(c.ref=null,l){r(l);let d=t.seen.get(l),y=d.schema;if(y.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(y)):Object.assign(u,y),Object.assign(u,p),a._zod.parent===l)for(let h in u)h==="$ref"||h==="allOf"||h in p||delete u[h];if(y.$ref&&d.def)for(let h in u)h==="$ref"||h==="allOf"||h in d.def&&JSON.stringify(u[h])===JSON.stringify(d.def[h])&&delete u[h]}let f=a._zod.parent;if(f&&f!==l){r(f);let d=t.seen.get(f);if(d?.schema.$ref&&(u.$ref=d.schema.$ref,d.def))for(let y in u)y==="$ref"||y==="allOf"||y in d.def&&JSON.stringify(u[y])===JSON.stringify(d.def[y])&&delete u[y]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())r(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,n.def??n.schema);let s=t.metadataRegistry.get(e)?.id;s!==void 0&&o.id===s&&delete o.id;let i=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:hn(e,"input",t.processors),output:hn(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function ne(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let r=t._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return ne(r.element,n);if(r.type==="set")return ne(r.valueType,n);if(r.type==="lazy")return ne(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return ne(r.innerType,n);if(r.type==="intersection")return ne(r.left,n)||ne(r.right,n);if(r.type==="record"||r.type==="map")return ne(r.keyType,n)||ne(r.valueType,n);if(r.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:ne(r.in,n)||ne(r.out,n);if(r.type==="object"){for(let o in r.shape)if(ne(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(ne(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(ne(o,n))return!0;return!!(r.rest&&ne(r.rest,n))}return!1}var Vc=(t,e={})=>n=>{let r=Vo({...n,processors:e});return q(t,r),Go(r,t),Jo(r,t)},hn=(t,e,n={})=>r=>{let{libraryOptions:o,target:s}=r??{},i=Vo({...o??{},target:s,io:e,processors:n});return q(t,i),Go(i,t),Jo(i,t)};var jd={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Gc=(t,e,n,r)=>{let o=n;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=jd[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),u&&(o.contentEncoding=u),c&&c.size>0){let p=[...c];p.length===1?o.pattern=p[0].source:p.length>1&&(o.allOf=[...p.map(l=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:l.source}))])}},Jc=(t,e,n,r)=>{let o=n,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:p}=t._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";let l=typeof p=="number"&&p>=(s??Number.NEGATIVE_INFINITY),f=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),d=e.target==="draft-04"||e.target==="openapi-3.0";l?d?(o.minimum=p,o.exclusiveMinimum=!0):o.exclusiveMinimum=p:typeof s=="number"&&(o.minimum=s),f?d?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof c=="number"&&(o.multipleOf=c)},qc=(t,e,n,r)=>{n.type="boolean"};var Kc=(t,e,n,r)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"};var Wc=(t,e,n,r)=>{n.not={}};var Yc=(t,e,n,r)=>{};var Hc=(t,e,n,r)=>{let o=t._zod.def,s=sn(o.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},Xc=(t,e,n,r)=>{let o=t._zod.def,s=[];for(let i of o.values)if(i===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){let i=s[0];n.type=i===null?"null":typeof i,e.target==="draft-04"||e.target==="openapi-3.0"?n.enum=[i]:n.const=i}else s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),s.every(i=>typeof i=="boolean")&&(n.type="boolean"),s.every(i=>i===null)&&(n.type="null"),n.enum=s};var eu=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var tu=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var nu=(t,e,n,r)=>{let o=n,s=t._zod.def,{minimum:i,maximum:a}=t._zod.bag;typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=q(s.element,e,{...r,path:[...r.path,"items"]})},ru=(t,e,n,r)=>{let o=n,s=t._zod.def;o.type="object",o.properties={};let i=s.shape;for(let u in i)o.properties[u]=q(i[u],e,{...r,path:[...r.path,"properties",u]});let a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{let p=s.shape[u]._zod;return e.io==="input"?p.optin===void 0:p.optout===void 0}));c.size>0&&(o.required=Array.from(c)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=q(s.catchall,e,{...r,path:[...r.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},ou=(t,e,n,r)=>{let o=t._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>q(a,e,{...r,path:[...r.path,s?"oneOf":"anyOf",c]}));s?n.oneOf=i:n.anyOf=i},su=(t,e,n,r)=>{let o=t._zod.def,s=q(o.left,e,{...r,path:[...r.path,"allOf",0]}),i=q(o.right,e,{...r,path:[...r.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];n.allOf=c};var iu=(t,e,n,r)=>{let o=n,s=t._zod.def;o.type="object";let i=s.keyType,c=i._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let p=q(s.valueType,e,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let l of c)o.patternProperties[l.source]=p}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(o.propertyNames=q(s.keyType,e,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=q(s.valueType,e,{...r,path:[...r.path,"additionalProperties"]});let u=i._zod.values;if(u){let p=[...u].filter(l=>typeof l=="string"||typeof l=="number");p.length>0&&(o.required=p)}},au=(t,e,n,r)=>{let o=t._zod.def,s=q(o.innerType,e,r),i=e.seen.get(t);e.target==="openapi-3.0"?(i.ref=o.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},cu=(t,e,n,r)=>{let o=t._zod.def;q(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType},uu=(t,e,n,r)=>{let o=t._zod.def;q(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},lu=(t,e,n,r)=>{let o=t._zod.def;q(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},fu=(t,e,n,r)=>{let o=t._zod.def;q(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i},du=(t,e,n,r)=>{let o=t._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=e.io==="input"?s?o.out:o.in:o.out;q(i,e,r);let a=e.seen.get(t);a.ref=i},pu=(t,e,n,r)=>{let o=t._zod.def;q(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType,n.readOnly=!0};var qo=(t,e,n,r)=>{let o=t._zod.def;q(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType},mu=(t,e,n,r)=>{let o=t._zod.innerType;q(o,e,r);let s=e.seen.get(t);s.ref=o};var Kd=g("ZodISODateTime",(t,e)=>{va.init(t,e),J.init(t,e)});function hu(t){return Nc(Kd,t)}var Wd=g("ZodISODate",(t,e)=>{Da.init(t,e),J.init(t,e)});function yu(t){return Tc(Wd,t)}var Yd=g("ZodISOTime",(t,e)=>{Ra.init(t,e),J.init(t,e)});function gu(t){return $c(Yd,t)}var Hd=g("ZodISODuration",(t,e)=>{ka.init(t,e),J.init(t,e)});function bu(t){return zc(Hd,t)}var tp=(t,e)=>{qn.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>ii(t,n)},flatten:{value:n=>si(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,Dt,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,Dt,2)}},isEmpty:{get(){return t.issues.length===0}}})};var ue=g("ZodError",tp,{Parent:Error});var wu=Kn(ue),_u=Wn(ue),xu=ln(ue),Su=fn(ue),Au=ui(ue),Eu=li(ue),vu=fi(ue),Du=di(ue),Ru=pi(ue),ku=mi(ue),Iu=hi(ue),Ou=yi(ue);var Cu=new WeakMap;function yn(t,e,n){let r=Object.getPrototypeOf(t),o=Cu.get(r);if(o||(o=new Set,Cu.set(r,o)),!o.has(e)){o.add(e);for(let s in n){let i=n[s];Object.defineProperty(r,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var Q=g("ZodType",(t,e)=>(j.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:hn(t,"input"),output:hn(t,"output")}}),t.toJSONSchema=Vc(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,r)=>wu(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>xu(t,n,r),t.parseAsync=async(n,r)=>_u(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Su(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>Au(t,n,r),t.decode=(n,r)=>Eu(t,n,r),t.encodeAsync=async(n,r)=>vu(t,n,r),t.decodeAsync=async(n,r)=>Du(t,n,r),t.safeEncode=(n,r)=>Ru(t,n,r),t.safeDecode=(n,r)=>ku(t,n,r),t.safeEncodeAsync=async(n,r)=>Iu(t,n,r),t.safeDecodeAsync=async(n,r)=>Ou(t,n,r),yn(t,"ZodType",{check(...n){let r=this.def;return this.clone(M.mergeDefs(r,{checks:[...r.checks??[],...n.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return be(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Kp(n,r))},superRefine(n,r){return this.check(Wp(n,r))},overwrite(n){return this.check(et(n))},optional(){return Pu(this)},exactOptional(){return zp(this)},nullable(){return Lu(this)},nullish(){return Pu(Lu(this))},nonoptional(n){return Bp(this,n)},array(){return V(this)},or(n){return Ot([this,n])},and(n){return Op(this,n)},transform(n){return Mu(this,Tp(n))},default(n){return Mp(this,n)},prefault(n){return Zp(this,n)},catch(n){return Up(this,n)},pipe(n){return Mu(this,n)},readonly(){return Gp(this)},describe(n){let r=this.clone();return bt.add(r,{description:n}),r},meta(...n){if(n.length===0)return bt.get(this);let r=this.clone();return bt.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(t,"description",{get(){return bt.get(t)?.description},configurable:!0}),t)),Fu=g("_ZodString",(t,e)=>{tr.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(r,o,s)=>Gc(t,r,o,s);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,yn(t,"_ZodString",{regex(...r){return this.check($o(...r))},includes(...r){return this.check(Lo(...r))},startsWith(...r){return this.check(Mo(...r))},endsWith(...r){return this.check(Fo(...r))},min(...r){return this.check(It(...r))},max(...r){return this.check(sr(...r))},length(...r){return this.check(ir(...r))},nonempty(...r){return this.check(It(1,...r))},lowercase(r){return this.check(zo(r))},uppercase(r){return this.check(Po(r))},trim(){return this.check(Bo())},normalize(...r){return this.check(Zo(...r))},toLowerCase(){return this.check(jo())},toUpperCase(){return this.check(Uo())},slugify(){return this.check(Qo())}})}),rp=g("ZodString",(t,e)=>{tr.init(t,e),Fu.init(t,e),t.email=n=>t.check(fc(op,n)),t.url=n=>t.check(yc(sp,n)),t.jwt=n=>t.check(Cc(_p,n)),t.emoji=n=>t.check(gc(ip,n)),t.guid=n=>t.check(To(Nu,n)),t.uuid=n=>t.check(dc(cr,n)),t.uuidv4=n=>t.check(pc(cr,n)),t.uuidv6=n=>t.check(mc(cr,n)),t.uuidv7=n=>t.check(hc(cr,n)),t.nanoid=n=>t.check(bc(ap,n)),t.guid=n=>t.check(To(Nu,n)),t.cuid=n=>t.check(wc(cp,n)),t.cuid2=n=>t.check(_c(up,n)),t.ulid=n=>t.check(xc(lp,n)),t.base64=n=>t.check(kc(gp,n)),t.base64url=n=>t.check(Ic(bp,n)),t.xid=n=>t.check(Sc(fp,n)),t.ksuid=n=>t.check(Ac(dp,n)),t.ipv4=n=>t.check(Ec(pp,n)),t.ipv6=n=>t.check(vc(mp,n)),t.cidrv4=n=>t.check(Dc(hp,n)),t.cidrv6=n=>t.check(Rc(yp,n)),t.e164=n=>t.check(Oc(wp,n)),t.datetime=n=>t.check(hu(n)),t.date=n=>t.check(yu(n)),t.time=n=>t.check(gu(n)),t.duration=n=>t.check(bu(n))});function v(t){return lc(rp,t)}var J=g("ZodStringFormat",(t,e)=>{U.init(t,e),Fu.init(t,e)}),op=g("ZodEmail",(t,e)=>{ya.init(t,e),J.init(t,e)});var Nu=g("ZodGUID",(t,e)=>{ma.init(t,e),J.init(t,e)});var cr=g("ZodUUID",(t,e)=>{ha.init(t,e),J.init(t,e)});var sp=g("ZodURL",(t,e)=>{ga.init(t,e),J.init(t,e)});var ip=g("ZodEmoji",(t,e)=>{ba.init(t,e),J.init(t,e)});var ap=g("ZodNanoID",(t,e)=>{wa.init(t,e),J.init(t,e)});var cp=g("ZodCUID",(t,e)=>{_a.init(t,e),J.init(t,e)});var up=g("ZodCUID2",(t,e)=>{xa.init(t,e),J.init(t,e)});var lp=g("ZodULID",(t,e)=>{Sa.init(t,e),J.init(t,e)});var fp=g("ZodXID",(t,e)=>{Aa.init(t,e),J.init(t,e)});var dp=g("ZodKSUID",(t,e)=>{Ea.init(t,e),J.init(t,e)});var pp=g("ZodIPv4",(t,e)=>{Ia.init(t,e),J.init(t,e)});var mp=g("ZodIPv6",(t,e)=>{Oa.init(t,e),J.init(t,e)});var hp=g("ZodCIDRv4",(t,e)=>{Ca.init(t,e),J.init(t,e)});var yp=g("ZodCIDRv6",(t,e)=>{Na.init(t,e),J.init(t,e)});var gp=g("ZodBase64",(t,e)=>{$a.init(t,e),J.init(t,e)});var bp=g("ZodBase64URL",(t,e)=>{za.init(t,e),J.init(t,e)});var wp=g("ZodE164",(t,e)=>{Pa.init(t,e),J.init(t,e)});var _p=g("ZodJWT",(t,e)=>{La.init(t,e),J.init(t,e)});var Zu=g("ZodNumber",(t,e)=>{Io.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(r,o,s)=>Jc(t,r,o,s),yn(t,"ZodNumber",{gt(r,o){return this.check(rr(r,o))},gte(r,o){return this.check(mn(r,o))},min(r,o){return this.check(mn(r,o))},lt(r,o){return this.check(nr(r,o))},lte(r,o){return this.check(pn(r,o))},max(r,o){return this.check(pn(r,o))},int(r){return this.check(Tu(r))},safe(r){return this.check(Tu(r))},positive(r){return this.check(rr(0,r))},nonnegative(r){return this.check(mn(0,r))},negative(r){return this.check(nr(0,r))},nonpositive(r){return this.check(pn(0,r))},multipleOf(r,o){return this.check(or(r,o))},step(r,o){return this.check(or(r,o))},finite(){return this}});let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function Z(t){return Pc(Zu,t)}var xp=g("ZodNumberFormat",(t,e)=>{Ma.init(t,e),Zu.init(t,e)});function Tu(t){return Lc(xp,t)}var Sp=g("ZodBoolean",(t,e)=>{Fa.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>qc(t,n,r,o)});function tt(t){return Mc(Sp,t)}var Ap=g("ZodNull",(t,e)=>{Za.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Kc(t,n,r,o)});function Ep(t){return Fc(Ap,t)}var vp=g("ZodUnknown",(t,e)=>{Ba.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Yc(t,n,r,o)});function $u(){return Zc(vp)}var Dp=g("ZodNever",(t,e)=>{ja.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Wc(t,n,r,o)});function Bu(t){return Bc(Dp,t)}var Rp=g("ZodArray",(t,e)=>{Ua.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>nu(t,n,r,o),t.element=e.element,yn(t,"ZodArray",{min(n,r){return this.check(It(n,r))},nonempty(n){return this.check(It(1,n))},max(n,r){return this.check(sr(n,r))},length(n,r){return this.check(ir(n,r))},unwrap(){return this.element}})});function V(t,e){return jc(Rp,t,e)}var ju=g("ZodObject",(t,e)=>{Ga.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ru(t,n,r,o),M.defineLazy(t,"shape",()=>e.shape),yn(t,"ZodObject",{keyof(){return ae(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:$u()})},loose(){return this.clone({...this._zod.def,catchall:$u()})},strict(){return this.clone({...this._zod.def,catchall:Bu()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return M.extend(this,n)},safeExtend(n){return M.safeExtend(this,n)},merge(n){return M.merge(this,n)},pick(n){return M.pick(this,n)},omit(n){return M.omit(this,n)},partial(...n){return M.partial(Qu,this,n[0])},required(...n){return M.required(Vu,this,n[0])}})});function he(t,e){let n={type:"object",shape:t??{},...M.normalizeParams(e)};return new ju(n)}function C(t,e){return new ju({type:"object",shape:t,catchall:Bu(),...M.normalizeParams(e)})}var Uu=g("ZodUnion",(t,e)=>{Oo.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ou(t,n,r,o),t.options=e.options});function Ot(t,e){return new Uu({type:"union",options:t,...M.normalizeParams(e)})}var kp=g("ZodDiscriminatedUnion",(t,e)=>{Uu.init(t,e),Ja.init(t,e)});function Ct(t,e,n){return new kp({type:"union",options:e,discriminator:t,...M.normalizeParams(n)})}var Ip=g("ZodIntersection",(t,e)=>{qa.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>su(t,n,r,o)});function Op(t,e){return new Ip({type:"intersection",left:t,right:e})}var zu=g("ZodRecord",(t,e)=>{Ka.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>iu(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType});function we(t,e,n){return!e||!e._zod?new zu({type:"record",keyType:v(),valueType:t,...M.normalizeParams(e)}):new zu({type:"record",keyType:t,valueType:e,...M.normalizeParams(n)})}var Ko=g("ZodEnum",(t,e)=>{Wa.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(r,o,s)=>Hc(t,r,o,s),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Ko({...e,checks:[],...M.normalizeParams(o),entries:s})},t.exclude=(r,o)=>{let s={...e.entries};for(let i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Ko({...e,checks:[],...M.normalizeParams(o),entries:s})}});function ae(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new Ko({type:"enum",entries:n,...M.normalizeParams(e)})}var Cp=g("ZodLiteral",(t,e)=>{Ya.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Xc(t,n,r,o),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function F(t,e){return new Cp({type:"literal",values:Array.isArray(t)?t:[t],...M.normalizeParams(e)})}var Np=g("ZodTransform",(t,e)=>{Ha.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>tu(t,n,r,o),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Et(t.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(M.issue(s,n.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),n.issues.push(M.issue(i))}};let o=e.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});function Tp(t){return new Np({type:"transform",transform:t})}var Qu=g("ZodOptional",(t,e)=>{Co.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>qo(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Pu(t){return new Qu({type:"optional",innerType:t})}var $p=g("ZodExactOptional",(t,e)=>{Xa.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>qo(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function zp(t){return new $p({type:"optional",innerType:t})}var Pp=g("ZodNullable",(t,e)=>{ec.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>au(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Lu(t){return new Pp({type:"nullable",innerType:t})}var Lp=g("ZodDefault",(t,e)=>{tc.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>uu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Mp(t,e){return new Lp({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():M.shallowClone(e)}})}var Fp=g("ZodPrefault",(t,e)=>{nc.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>lu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Zp(t,e){return new Fp({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():M.shallowClone(e)}})}var Vu=g("ZodNonOptional",(t,e)=>{rc.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>cu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Bp(t,e){return new Vu({type:"nonoptional",innerType:t,...M.normalizeParams(e)})}var jp=g("ZodCatch",(t,e)=>{oc.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>fu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Up(t,e){return new jp({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Qp=g("ZodPipe",(t,e)=>{sc.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>du(t,n,r,o),t.in=e.in,t.out=e.out});function Mu(t,e){return new Qp({type:"pipe",in:t,out:e})}var Vp=g("ZodReadonly",(t,e)=>{ic.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>pu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Gp(t){return new Vp({type:"readonly",innerType:t})}var Jp=g("ZodLazy",(t,e)=>{ac.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>mu(t,n,r,o),t.unwrap=()=>t._zod.def.getter()});function Wo(t){return new Jp({type:"lazy",getter:t})}var qp=g("ZodCustom",(t,e)=>{cc.init(t,e),Q.init(t,e),t._zod.processJSONSchema=(n,r,o)=>eu(t,n,r,o)});function Kp(t,e={}){return Uc(qp,t,e)}function Wp(t,e){return Qc(t,e)}function nt(t){let e=Wo(()=>Ot([v(t),Z(),tt(),Ep(),V(e),we(v(),e)]));return e}var Gu=t=>"field"in t?[t]:("all"in t?t.all:t.any).flatMap(Gu),gn=t=>Gu(t);var Nt=(t,e)=>{if("field"in t)return e(t);let n="all"in t?t.all:t.any,r=!1;if("all"in t){for(let o of n){let s=Nt(o,e);if(s===!1)return!1;r||=s===void 0}return r?void 0:!0}for(let o of n){let s=Nt(o,e);if(s===!0)return!0;r||=s===void 0}return r?void 0:!1},Ju=t=>JSON.stringify(t),Yo=t=>{if("field"in t)return{conditions:1,depth:0};let e="all"in t?t.all:t.any,n=0,r=1;for(let o of e){let s=Yo(o);n+=s.conditions,r=Math.max(r,s.depth+1)}return{conditions:n,depth:r}},qu=(t,e={})=>{let n=o=>{let s=V(o),i=e.maximumChildren===void 0?s:s.max(e.maximumChildren);return Ot([t,C({all:i}),C({any:i})])},r=Wo(()=>n(r));return e.maximumConditions===void 0&&e.maximumDepth===void 0?r:r.superRefine((o,s)=>{let{conditions:i,depth:a}=Yo(o);e.maximumConditions!==void 0&&i>e.maximumConditions&&s.addIssue({code:"custom",message:e.maximumConditionsMessage??"Query exceeds the condition limit"}),e.maximumDepth!==void 0&&a>e.maximumDepth&&s.addIssue({code:"custom",message:e.maximumDepthMessage??"Query exceeds the nesting limit"})})};var k={requestBytes:524288,filterCount:32,filterDepth:8,sortCount:8,outputFieldCount:256,fieldPathDepth:9,defaultResultCount:20,resultCount:1e3,resultBytes:16777216,candidateDocuments:1e3,databaseBytes:512e3,frontmatterBytes:65536,frontmatterDepth:8,frontmatterFields:256,frontmatterStringBytes:16384,jsonBytes:1048576,jsonDepth:8,jsonFields:256,jsonStringBytes:16384,indexedPropertiesBytes:65536,excerptBytes:2048,mdxDepth:100,mdxNodes:2e4,mdxProps:4e3,hydratedFileBytes:1048576,hydratedTotalBytes:2097152,hydratedFileCount:20,hydratedRangeBytes:262144,concurrentContentReads:8};function wt(t,e=new Set){if(typeof t=="number"&&isNaN(t))throw new Error("NaN is not allowed");if(typeof t=="number"&&!isFinite(t))throw new Error("Infinity is not allowed");if(t===null||typeof t!="object")return JSON.stringify(t);if(typeof t.toJSON=="function"){if(e.has(t))throw new Error("Circular reference detected");e.add(t);let r=wt(t.toJSON(),e);return e.delete(t),r}if(e.has(t))throw new Error("Circular reference detected");e.add(t);let n;if(Array.isArray(t))n=`[${t.map(o=>wt(o===void 0||typeof o=="symbol"?null:o,e)).join(",")}]`;else{let r=[];for(let o of Object.keys(t).sort())t[o]===void 0||typeof t[o]=="symbol"||r.push(`${wt(o)}:${wt(t[o],e)}`);n=`{${r.join(",")}}`}return e.delete(t),n}var Yp=new TextEncoder,Tt=t=>Yp.encode(t),Ne=t=>Tt(t).byteLength,re=class extends Error{constructor(){super("Byte stream exceeds the configured limit"),this.name="ByteLimitExceededError"}},Hp=(t,e)=>{let n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.byteLength;return n},$t=t=>typeof t=="string"?{async*[Symbol.asyncIterator](){yield Tt(t)}}:t instanceof Uint8Array?{async*[Symbol.asyncIterator](){yield t}}:t,Ku=t=>({async*[Symbol.asyncIterator](){let e=t.getReader(),n=!1;try{for(;;){let r=await e.read();if(r.done){n=!0;return}yield r.value}}finally{if(n===!1)try{await e.cancel()}catch{}e.releaseLock()}}}),Ho=async(t,e)=>{let n=[],r=0;for await(let o of $t(t)){let s=e-r;if(s<=0)break;let i=o.subarray(0,s);if(n.push(i),r+=i.byteLength,r===e)break}return Hp(n,r)},Te=async(t,e)=>{let n=await Ho(t,e+1);if(n.byteLength>e)throw new re;return n},le=t=>new TextDecoder("utf-8",{fatal:!0}).decode(t),zt=t=>t.charCodeAt(0)===65279?t.slice(1):t;var Wu=t=>{for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n>=55296&&n<=56319){let r=t.charCodeAt(e+1);if(e+1>=t.length||r<56320||r>57343)throw new Error("JSON strings cannot contain lone Unicode surrogates");e+=1;continue}if(n>=56320&&n<=57343)throw new Error("JSON strings cannot contain lone Unicode surrogates")}},Xo=(t,e)=>{if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return Wu(t),t;if(typeof t=="number"){if(Number.isFinite(t)===!1)throw new Error("JSON cannot contain non-finite numbers");return t}if(Array.isArray(t)){if(Object.getOwnPropertySymbols(t).length>0)throw new Error("JSON arrays cannot contain symbol properties");if(e.has(t))throw new Error("JSON cannot contain circular references");e.add(t);try{let n=[];for(let r=0;r<t.length;r+=1){if(Object.hasOwn(t,r)===!1)throw new Error("JSON arrays cannot be sparse");let o=t[r];if(o===void 0)throw new Error("JSON arrays cannot contain undefined values");n.push(Xo(o,e))}if(Object.keys(t).length!==t.length)throw new Error("JSON arrays cannot contain named properties");return n}finally{e.delete(t)}}if(typeof t=="object"){let n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw new Error("JSON can contain only plain objects");if(Object.getOwnPropertySymbols(t).length>0)throw new Error("JSON objects cannot contain symbol properties");if(e.has(t))throw new Error("JSON cannot contain circular references");e.add(t);let r={};try{for(let[o,s]of Object.entries(t))Wu(o),s!==void 0&&Object.defineProperty(r,o,{value:Xo(s,e),enumerable:!0,configurable:!0,writable:!0})}finally{e.delete(t)}return r}throw new Error("Value cannot be represented as JSON")},rt=t=>Xo(t,new Set),fe=t=>{let e=wt(rt(t));if(e===void 0)throw new Error("Value cannot be represented as canonical JSON");return e},bn=(t,e)=>t===void 0||e===void 0?t===e:fe(t)===fe(e),$e=(t,e)=>t<e?-1:t>e?1:0,es=async t=>{let e=typeof t=="string"?Tt(t):t,n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")},Yu=async t=>`sha256:${await es(t)}`;var Hu=Ct("type",[C({type:F("document")}),C({type:F("json"),path:V(v()).min(1)}),C({type:F("markdown-body")}),C({type:F("markdown-frontmatter")})]),ts=C({documentId:v().min(1),revision:v().min(1),representation:Hu}),Xp=t=>{let e=Hu.parse(t);return e.type==="json"?Object.freeze({...e,path:Object.freeze([...e.path])}):Object.freeze(e)},Xu=t=>{let e=ts.parse(t);return Object.freeze({...e,representation:Xp(e.representation)})};var wn=["json","markdown","mdx"],el=t=>typeof t=="string"&&wn.includes(t),tl=t=>{let e=t.split(";",1)[0].trim().toLowerCase();if(e==="application/json")return"json";if(e==="text/markdown")return"markdown";if(e==="text/mdx")return"mdx"};var ur=C({id:v().min(1),revision:v().min(1),contentRef:v().min(1),format:ae(wn).optional()}),lr=C({sourceId:v().min(1),referenceId:v().min(1),reference:ts});var Pt=t=>{let e=new Map;for(let n of t){let r=e.get(n.sourceId)??[];r.push(n),e.set(n.sourceId,r)}return e};var ze=class extends Error{code;documentIds;constructor({code:e,message:n,documentIds:r=[]}){super(n),this.name="DocumentGraphError",this.code=e,this.documentIds=Object.freeze([...r])}},em=(t,e)=>$e(t.sourceId,e.sourceId)||$e(t.referenceId,e.referenceId),_n=({nodes:t,edges:e})=>{let n=t.map(a=>Object.freeze(ur.parse(a))).sort((a,c)=>$e(a.id,c.id)),r=new Map,o=new Map;for(let a of n){if(r.has(a.id))throw new ze({code:"DUPLICATE_NODE",message:`Document graph contains duplicate node ${a.id}`,documentIds:[a.id]});r.set(a.id,a);let c=o.get(a.contentRef);if(c!==void 0&&(c.revision!==a.revision||c.format!==a.format))throw new ze({code:"CONTENT_IDENTITY_CONFLICT",message:`Document graph content reference ${a.contentRef} has conflicting identities`,documentIds:[c.id,a.id]});o.set(a.contentRef,a)}let s=e.map(a=>{let c=lr.parse(a);return Object.freeze({...c,reference:Xu(c.reference)})}).sort(em),i=new Set;for(let a of s){if(r.get(a.sourceId)===void 0)throw new ze({code:"SOURCE_NOT_FOUND",message:`Document graph source ${a.sourceId} does not exist`,documentIds:[a.sourceId]});let u=r.get(a.reference.documentId);if(u===void 0)throw new ze({code:"TARGET_NOT_FOUND",message:`Document graph target ${a.reference.documentId} does not exist`,documentIds:[a.sourceId,a.reference.documentId]});if(u.revision!==a.reference.revision)throw new ze({code:"TARGET_REVISION_MISMATCH",message:`Document graph target ${u.id} revision does not match its reference`,documentIds:[a.sourceId,u.id]});let p=`${a.sourceId}\0${a.referenceId}`;if(i.has(p))throw new ze({code:"DUPLICATE_REFERENCE",message:`Document ${a.sourceId} contains duplicate reference ID ${a.referenceId}`,documentIds:[a.sourceId]});i.add(p)}return Object.freeze({nodes:Object.freeze(n),edges:Object.freeze(s)})},tm=t=>new Map(t.nodes.map(e=>[e.id,e]));var fr=({graph:t,rootIds:e})=>{let n=tm(t),r=Pt(t.edges),o=new Map,s=[],i=[],a=c=>{let u=n.get(c);if(u===void 0)throw new ze({code:"ROOT_NOT_FOUND",message:`Document graph root ${c} does not exist`,documentIds:[c]});let p=o.get(c);if(p!=="visited"){if(p==="visiting"){let l=s.indexOf(c),f=[...s.slice(l),c];throw new ze({code:"CYCLE",message:`Document graph contains a cycle: ${f.join(" -> ")}`,documentIds:f})}o.set(c,"visiting"),s.push(c);for(let l of r.get(c)??[])a(l.reference.documentId);s.pop(),o.set(c,"visited"),i.push(u)}};for(let c of[...new Set(e)].sort($e))a(c);return Object.freeze(i)};var nm=v().regex(/^sha256:[a-f0-9]{64}$/),nl=C({format:F("webstudio-document-graph"),version:F(1),nodes:V(ur),edges:V(lr),integrity:C({algorithm:F("sha256"),checksum:nm})});var rm=v().min(1).refine(t=>t.startsWith("/")===!1,{error:"Asset path must be relative"}).refine(t=>t.includes("\\")===!1&&t.split("/").every(e=>e.length>0&&e!==".."&&e!=="."),{error:"Asset path must be normalized and must not contain dot segments"}),sl=C({_id:v().min(1),_type:F("asset.file"),name:v().min(1),description:v().optional(),path:rm,key:v(),folderId:v().min(1).optional(),extension:v().regex(/^[a-z0-9]*$/),mimeType:v().min(1),size:Z().int().nonnegative(),createdAt:v().datetime().optional(),revision:v().min(1),contentRef:v().min(1),properties:we(v(),nt()),excerpt:v().optional(),metadataError:C({code:v().min(1),message:v().min(1)}).optional()}),rs=sl.partial().required({_id:!0}),om=ae(["null","boolean","number","string","object","array"]),sm=he({format:F("webstudio-builder-asset-field-catalog"),version:F(1),canonicalRevision:v().regex(/^sha256:[a-f0-9]{64}$/),documentCount:Z().int().nonnegative(),fields:we(v().min(1),he({queryPath:V(v().min(1)).min(1).max(k.fieldPathDepth).optional(),types:V(om).min(1),occurrences:Z().int().positive(),optional:F(!0).optional(),mixed:F(!0).optional()}))}).superRefine((t,e)=>{for(let[n,r]of Object.entries(t.fields)){let o=[...new Set(r.types)].sort();JSON.stringify(r.types)!==JSON.stringify(o)&&e.addIssue({code:"custom",path:["fields",n,"types"],message:"Observed field types must be unique and sorted"}),r.occurrences>t.documentCount&&e.addIssue({code:"custom",path:["fields",n,"occurrences"],message:"Field occurrences cannot exceed the document count"});let s=r.occurrences<t.documentCount;r.optional===!0!==s&&e.addIssue({code:"custom",path:["fields",n,"optional"],message:"Field optionality must match its occurrence count"});let i=o.length>1;r.mixed===!0!==i&&e.addIssue({code:"custom",path:["fields",n,"mixed"],message:"Mixed status must match the observed types"})}}),dr=v().regex(/^sha256:[a-f0-9]{64}$/),il=C({fields:V(V(v().min(1)).min(1).max(k.fieldPathDepth)).min(1).max(k.outputFieldCount+1),rows:V(V(nt())).max(k.resultCount),totalCount:Z().int().nonnegative().max(k.candidateDocuments),hasMore:tt()}).superRefine(({fields:t,rows:e},n)=>{for(let[r,o]of e.entries())o.length!==t.length&&n.addIssue({code:"custom",path:["rows",r],message:"Materialized query rows must match the field count"})}),rl=C({format:F("webstudio-content-database"),version:F(1),assetRevision:dr,documents:V(rs),documentGraph:nl.optional(),contents:we(v().min(1),v()).optional(),assetReferences:we(v().min(1),V(C({start:Z().int().nonnegative(),end:Z().int().positive(),assetId:v().min(1),suffix:v().min(1).optional()}).refine(({start:t,end:e})=>e>t,{message:"Markdown asset reference range must not be empty"}))).optional(),assetValueReferences:we(v().min(1),V(C({path:V(v().min(1).or(Z().int().nonnegative())).min(1),assetId:v().min(1),suffix:v().min(1).optional(),structured:F(!0).optional()}))).optional(),fieldCatalog:sm,queries:we(dr,il).optional(),database:C({maxBytes:Z().int().positive(),unboundedBytes:Z().int().nonnegative(),sourceDocumentCount:Z().int().nonnegative(),includedDocumentCount:Z().int().nonnegative().optional()}).optional(),integrity:C({algorithm:F("sha256"),checksum:dr})}).superRefine((t,e)=>{t.documents.length>k.candidateDocuments&&e.addIssue({code:"custom",path:["documents"],message:"Asset index exceeds the document limit"}),(t.fieldCatalog.canonicalRevision!==t.assetRevision||t.fieldCatalog.documentCount!==t.documents.length)&&e.addIssue({code:"custom",path:["fieldCatalog"],message:"Asset index field catalog does not match its documents"}),t.database!==void 0&&t.database.sourceDocumentCount<t.documents.length&&e.addIssue({code:"custom",path:["database","sourceDocumentCount"],message:"Source document count cannot be smaller than the database"}),t.database?.includedDocumentCount!==void 0&&(t.database.includedDocumentCount<t.documents.length||t.database.includedDocumentCount>t.database.sourceDocumentCount)&&e.addIssue({code:"custom",path:["database","includedDocumentCount"],message:"Included document count must match the database bounds"});let n;for(let[o,s]of t.documents.entries())n!==void 0&&s._id<=n&&e.addIssue({code:"custom",path:["documents",o,"_id"],message:"Asset index documents must have unique sorted IDs"}),n=s._id;let r=new Set(t.documents.flatMap(({contentRef:o})=>o===void 0?[]:[o]));for(let o of t.documentGraph?.nodes??[])r.add(o.contentRef);for(let o of Object.keys(t.contents??{}))r.has(o)===!1&&e.addIssue({code:"custom",path:["contents",o],message:"Embedded content must belong to an indexed document"});for(let o of Object.keys(t.assetReferences??{}))r.has(o)===!1&&e.addIssue({code:"custom",path:["assetReferences",o],message:"Asset references must belong to an indexed document"})}),im=Ct("mode",[he({mode:F("none")}),he({mode:F("full"),maxBytes:Z().int().positive().max(k.hydratedFileBytes).optional()}),he({mode:F("range"),offset:Z().int().nonnegative(),length:Z().int().positive().max(k.hydratedRangeBytes)}),he({mode:F("markdown-body-ref"),maxBytes:Z().int().positive().max(k.hydratedFileBytes).optional()})]),os={id:["string"],url:["string"],width:["number"],height:["number"],name:["string"],description:["string"],path:["string"],key:["string"],folderId:["string"],extension:["string"],mimeType:["string"],size:["number"],createdAt:["string"],revision:["string"],excerpt:["string"]},al=Object.keys(os),cl=["url","width","height"],pr=t=>cl.includes(t),ul=al.filter(t=>pr(t)===!1&&t!=="excerpt"),ll=ul.filter(t=>t!=="id"),fl=t=>ul.includes(t),am=ae(al),xn=V(v().min(1)).min(1).max(k.fieldPathDepth).superRefine((t,e)=>{if(t[0]==="properties"){t.length<2&&e.addIssue({code:"custom",message:"A properties field path must select a property"});return}(t.length!==1||am.safeParse(t[0]).success===!1)&&e.addIssue({code:"custom",message:"Asset query field path is unsupported"})}),ns=tt().default(!0),cm=Ct("mode",[C({mode:F("all"),includeMetadata:ns}),C({mode:F("base"),includeMetadata:ns}),C({mode:F("fields"),includeMetadata:ns,fields:V(xn).max(k.outputFieldCount).refine(t=>new Set(t.map(Ju)).size===t.length,{error:"Selected output fields must be unique"})})]),um={mode:"fields",includeMetadata:!1,fields:cl.map(t=>[t])},dl=["eq","ne","contains","startsWith","endsWith","gt","gte","lt","lte"],Ob=[...dl,"in","exists","isEmpty"],lm=C({field:xn,operator:ae(dl),value:nt()}),fm=C({field:xn,operator:F("in"),value:V(nt()).max(k.resultCount)}),dm=C({field:xn,operator:ae(["exists","isEmpty"]),value:tt()}),pm=Ct("operator",[lm,fm,dm]),mm=qu(pm,{maximumChildren:k.filterCount,maximumConditions:k.filterCount,maximumDepth:k.filterDepth,maximumConditionsMessage:"Asset query exceeds the filter limit",maximumDepthMessage:"Asset query exceeds the filter nesting limit"});var hm=mm,pl=t=>{let e=new Set(["eq","ne","in","exists"]);return t.some(n=>n==="string"||n==="array")&&e.add("contains"),t.includes("string")&&(e.add("startsWith"),e.add("endsWith")),t.some(n=>n==="string"||n==="number")&&(e.add("gt"),e.add("gte"),e.add("lt"),e.add("lte")),t.some(n=>n==="string"||n==="array"||n==="object")&&e.add("isEmpty"),[...e]},ym=C({field:xn,direction:ae(["asc","desc"])}),gm=ae(["many","one","first","last"]),bm=({output:t,content:e})=>t.includeMetadata||t.mode==="all"||t.mode==="fields"&&t.fields.length>0||e.mode!=="none",ot=C({result:gm.default("many"),where:hm.default({all:[]}),sort:V(ym).max(k.sortCount).default([]),limit:Z().int().nonnegative().max(k.resultCount).default(k.defaultResultCount),offset:Z().int().nonnegative().max(k.candidateDocuments).default(0),output:cm.default(um),content:im.default({mode:"none"})}).superRefine((t,e)=>{bm(t)===!1&&e.addIssue({code:"custom",message:"Select at least one asset query output"}),(t.result==="first"||t.result==="last")&&t.sort.length===0&&e.addIssue({code:"custom",path:["sort"],message:"Add sorting to define which item is first."})}),ml=C({query:ot,indexRevision:v().min(1).max(255).optional()}),wm=he({_id:v().min(1),revision:v().min(1),contentRef:v().min(1),encoding:F("utf-8"),text:v(),range:he({offset:Z().int().nonnegative(),length:Z().int().nonnegative(),total:Z().int().nonnegative()}).optional()}),_m=wm.omit({_id:!0,revision:!0,contentRef:!0}),hl=sl.omit({_id:!0,_type:!0,contentRef:!0}).partial().extend({id:v().min(1),url:v().min(1).optional(),width:Z().positive().optional(),height:Z().positive().optional(),content:_m.optional()}).refine(t=>t.width===void 0==(t.height===void 0),{error:"Asset dimensions must include both width and height"}),xm=C({format:F("webstudio-content-database"),version:F(1),revision:dr,usedBytes:Z().int().nonnegative(),maxBytes:Z().int().positive(),unboundedBytes:Z().int().nonnegative(),includedDocumentCount:Z().int().nonnegative(),omittedDocumentCount:Z().int().nonnegative(),omissionReason:ae(["size","unavailable"]).optional(),truncated:tt()}),ol=xm.pick({usedBytes:!0,maxBytes:!0,unboundedBytes:!0,includedDocumentCount:!0,omittedDocumentCount:!0,omissionReason:!0,truncated:!0}),ss=C({items:V(hl),totalCount:Z().int().nonnegative(),hasMore:tt()}),Sm=C({item:hl.nullable(),totalCount:Z().int().nonnegative()}),yl=Ot([ss,Sm]),Am=C({scope:F("query-preview"),query:ol,database:ol,artifacts:C({query:rl,database:rl}).optional(),unresolved:yl.optional()}),Cb=C({data:yl,__diagnostics__:Am}),Em=ae(["INVALID_REQUEST","REQUEST_CANCELLED","UNAUTHORIZED","FORBIDDEN","STALE_INDEX","CONTENT_IDENTITY_REQUIRED","CONTENT_NOT_TEXT","CONTENT_DECODING_FAILED","CONTENT_LIMIT_EXCEEDED","MULTIPLE_RESULTS","INTERNAL_ERROR"]),vm=he({ok:F(!1),error:he({code:Em,message:v().min(1),retryable:tt(),details:we(v(),nt()).optional()}),meta:he({queryHash:v().min(1).optional(),indexRevision:v().min(1).optional(),assetRevision:v().min(1).optional()}).optional()}),gl=({code:t,message:e,retryable:n=!1,details:r})=>vm.parse({ok:!1,error:{code:t,message:e,retryable:n,details:r}});var bl=function*(t){if(t.length>0&&!t.startsWith("/")||/~(?![01])/.test(t))throw Error("Invalid JSON Pointer");let e=1,n=0;for(;n<t.length;){let r=t.indexOf("/",e);n=r===-1?t.length:r;let o=t.slice(e,n);e=n+1,yield Rm(o)}};var is=(t,e)=>e+"/"+Dm(t),Dm=t=>t.toString().replace(/~/g,"~0").replace(/\//g,"~1"),Rm=t=>t.toString().replace(/~1/g,"/").replace(/~0/g,"~");var mr=async(t,e,n)=>{if(Number.isSafeInteger(e)===!1||e<=0)throw new Error("Concurrency must be a positive safe integer");let r=0,o=new Array(t.length),s=async()=>{for(;r<t.length;){let u=r;r+=1,o[u]=await n(t[u])}},i=Array.from({length:Math.min(e,t.length)},s),c=(await Promise.allSettled(i)).find(u=>u.status==="rejected");if(c!==void 0)throw c.reason;return o};var Lt=t=>typeof t=="object"&&t!==null&&Array.isArray(t)===!1,hr=t=>{if(Lt(t)===!1)return;let e=Object.keys(t);if(!(e.length!==1||e[0]!=="$ref"))return t.$ref};var de=class extends Error{code;referenceId;constructor({code:e,message:n,referenceId:r,cause:o}){super(n,{cause:o}),this.name="JsonDocumentError",this.code=e,this.referenceId=r}},km=(t,e)=>{let n=hr(t);if(n!==void 0){if(typeof n!="string")throw new de({code:"INVALID_REFERENCE_MARKER",message:`JSON reference marker ${e} must contain a string $ref`,referenceId:e});return n}},Im=t=>`#${t}`;var wl=async({source:t,maximumBytes:e=k.hydratedFileBytes})=>{let n;try{n=await Te(t,e)}catch(o){throw o instanceof re?new de({code:"CONTENT_LIMIT_EXCEEDED",message:"JSON document exceeds the byte limit",cause:o}):o}let r;try{r=zt(le(n))}catch(o){throw new de({code:"CONTENT_DECODING_FAILED",message:"JSON document is not valid UTF-8",cause:o})}try{return rt(JSON.parse(r))}catch(o){throw new de({code:"INVALID_DOCUMENT",message:"JSON document is invalid",cause:o})}};var Om=(t,e)=>{let n=t;for(let r of e){if(Array.isArray(n)){let o=Number(r);if(Number.isSafeInteger(o)===!1||o<0||String(o)!==r||o>=n.length)return;n=n[o];continue}if(Lt(n)&&Object.hasOwn(n,r)){n=n[r];continue}return}return n},_l=({document:t,representation:e})=>{let n=rt(t);if(e.type==="document")return n;if(e.type!=="json")throw new de({code:"UNSUPPORTED_REPRESENTATION",message:`JSON documents do not support ${e.type}`});let r=Om(n,e.path);if(r===void 0)throw new de({code:"JSON_PATH_NOT_FOUND",message:"JSON document path does not exist"});return r},Cm=(t,e,n)=>{Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0})},yr=({document:t,references:e,allowUnresolvedReferences:n=!1})=>{let r=rt(t),o=new Set,s=(a,c)=>{let u=Im(c);if(km(a,u)!==void 0){if(e.has(u)===!1){if(n)return a;throw new de({code:"REFERENCE_NOT_FOUND",message:`Resolved JSON reference ${u} is unavailable`,referenceId:u})}o.add(u);try{return rt(e.get(u))}catch(l){throw new de({code:"INVALID_RESOLVED_VALUE",message:`Resolved JSON reference ${u} is not JSON-compatible`,referenceId:u,cause:l})}}if(Array.isArray(a))return a.map((l,f)=>s(l,is(String(f),c)));if(Lt(a)){let l={};for(let[f,d]of Object.entries(a))Cm(l,f,s(d,is(f,c)));return l}return a},i=s(r,"");for(let a of[...e.keys()].sort())if(o.has(a)===!1)throw new de({code:"UNUSED_REFERENCE",message:`Resolved JSON reference ${a} has no marker`,referenceId:a});return i};var gr=Symbol.for("yaml.alias"),br=Symbol.for("yaml.document"),_e=Symbol.for("yaml.map"),as=Symbol.for("yaml.pair"),pe=Symbol.for("yaml.scalar"),Ge=Symbol.for("yaml.seq"),oe=Symbol.for("yaml.node.type"),xe=t=>!!t&&typeof t=="object"&&t[oe]===gr,Pe=t=>!!t&&typeof t=="object"&&t[oe]===br,Se=t=>!!t&&typeof t=="object"&&t[oe]===_e,T=t=>!!t&&typeof t=="object"&&t[oe]===as,N=t=>!!t&&typeof t=="object"&&t[oe]===pe,Ae=t=>!!t&&typeof t=="object"&&t[oe]===Ge;function B(t){if(t&&typeof t=="object")switch(t[oe]){case _e:case Ge:return!0}return!1}function L(t){if(t&&typeof t=="object")switch(t[oe]){case gr:case _e:case pe:case Ge:return!0}return!1}var wr=t=>(N(t)||B(t))&&!!t.anchor;var ce=Symbol("break visit"),xl=Symbol("skip children"),Le=Symbol("remove node");function Me(t,e){let n=Sl(e);Pe(t)?Mt(null,t.contents,n,Object.freeze([t]))===Le&&(t.contents=null):Mt(null,t,n,Object.freeze([]))}Me.BREAK=ce;Me.SKIP=xl;Me.REMOVE=Le;function Mt(t,e,n,r){let o=Al(t,e,n,r);if(L(o)||T(o))return El(t,r,o),Mt(t,o,n,r);if(typeof o!="symbol"){if(B(e)){r=Object.freeze(r.concat(e));for(let s=0;s<e.items.length;++s){let i=Mt(s,e.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===ce)return ce;i===Le&&(e.items.splice(s,1),s-=1)}}}else if(T(e)){r=Object.freeze(r.concat(e));let s=Mt("key",e.key,n,r);if(s===ce)return ce;s===Le&&(e.key=null);let i=Mt("value",e.value,n,r);if(i===ce)return ce;i===Le&&(e.value=null)}}return o}async function _r(t,e){let n=Sl(e);Pe(t)?await Ft(null,t.contents,n,Object.freeze([t]))===Le&&(t.contents=null):await Ft(null,t,n,Object.freeze([]))}_r.BREAK=ce;_r.SKIP=xl;_r.REMOVE=Le;async function Ft(t,e,n,r){let o=await Al(t,e,n,r);if(L(o)||T(o))return El(t,r,o),Ft(t,o,n,r);if(typeof o!="symbol"){if(B(e)){r=Object.freeze(r.concat(e));for(let s=0;s<e.items.length;++s){let i=await Ft(s,e.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===ce)return ce;i===Le&&(e.items.splice(s,1),s-=1)}}}else if(T(e)){r=Object.freeze(r.concat(e));let s=await Ft("key",e.key,n,r);if(s===ce)return ce;s===Le&&(e.key=null);let i=await Ft("value",e.value,n,r);if(i===ce)return ce;i===Le&&(e.value=null)}}return o}function Sl(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function Al(t,e,n,r){if(typeof n=="function")return n(t,e,r);if(Se(e))return n.Map?.(t,e,r);if(Ae(e))return n.Seq?.(t,e,r);if(T(e))return n.Pair?.(t,e,r);if(N(e))return n.Scalar?.(t,e,r);if(xe(e))return n.Alias?.(t,e,r)}function El(t,e,n){let r=e[e.length-1];if(B(r))r.items[t]=n;else if(T(r))t==="key"?r.key=n:r.value=n;else if(Pe(r))r.contents=n;else{let o=xe(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}var Nm={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Tm=t=>t.replace(/[!,[\]{}]/g,e=>Nm[e]),Fe=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let r=e.trim().split(/[ \t]+/),o=r.shift();switch(o){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[s,i]=r;return this.tags[s]=i,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=r;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let i=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,i),!1}}default:return n(0,`Unknown directive ${o}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let i=e.slice(2,-1);return i==="!"||i==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),i)}let[,r,o]=e.match(/^(.*!)([^!]*)$/s);o||n(`The ${e} tag has no suffix`);let s=this.tags[r];if(s)try{return s+decodeURIComponent(o)}catch(i){return n(String(i)),null}return r==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,r]of Object.entries(this.tags))if(e.startsWith(r))return n+Tm(e.substring(r.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),o;if(e&&r.length>0&&L(e.contents)){let s={};Me(e.contents,(i,a)=>{L(a)&&a.tag&&(s[a.tag]=!0)}),o=Object.keys(s)}else o=[];for(let[s,i]of r)s==="!!"&&i==="tag:yaml.org,2002:"||(!e||o.some(a=>a.startsWith(i)))&&n.push(`%TAG ${s} ${i}`);return n.join(`-`)}};Fe.defaultYaml={explicit:!1,version:"1.2"};Fe.defaultTags={"!!":"tag:yaml.org,2002:"};function xr(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function cs(t){let e=new Set;return Me(t,{Value(n,r){r.anchor&&e.add(r.anchor)}}),e}function us(t,e){for(let n=1;;++n){let r=`${t}${n}`;if(!e.has(r))return r}}function vl(t,e){let n=[],r=new Map,o=null;return{onAnchor:s=>{n.push(s),o??(o=cs(t));let i=us(e,o);return o.add(i),i},setAnchors:()=>{for(let s of n){let i=r.get(s);if(typeof i=="object"&&i.anchor&&(N(i.node)||B(i.node)))i.node.anchor=i.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:r}}function st(t,e,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let o=0,s=r.length;o<s;++o){let i=r[o],a=st(t,r,String(o),i);a===void 0?delete r[o]:a!==i&&(r[o]=a)}else if(r instanceof Map)for(let o of Array.from(r.keys())){let s=r.get(o),i=st(t,r,o,s);i===void 0?r.delete(o):i!==s&&r.set(o,i)}else if(r instanceof Set)for(let o of Array.from(r)){let s=st(t,r,o,o);s===void 0?r.delete(o):s!==o&&(r.delete(o),r.add(s))}else for(let[o,s]of Object.entries(r)){let i=st(t,r,o,s);i===void 0?delete r[o]:i!==s&&(r[o]=i)}return t.call(e,n,r)}function Y(t,e,n){if(Array.isArray(t))return t.map((r,o)=>Y(r,String(o),n));if(t&&typeof t.toJSON=="function"){if(!n||!wr(t))return t.toJSON(e,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(t,r),n.onCreate=s=>{r.res=s,delete n.onCreate};let o=t.toJSON(e,n);return n.onCreate&&n.onCreate(o),o}return typeof t=="bigint"&&!n?.keep?Number(t):t}var it=class{constructor(e){Object.defineProperty(this,oe,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:r,onAnchor:o,reviver:s}={}){if(!Pe(e))throw new TypeError("A document argument is required");let i={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=Y(this,"",i);if(typeof o=="function")for(let{count:c,res:u}of i.anchors.values())o(u,c);return typeof s=="function"?st(s,{"":a},"",a):a}};var Je=class extends it{constructor(e){super(gr),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],Me(e,{Node:(s,i)=>{(xe(i)||wr(i))&&r.push(i)}}),n&&(n.aliasResolveCache=r));let o;for(let s of r){if(s===this)break;s.anchor===this.source&&(o=s)}return o}toJSON(e,n){if(!n)return{source:this.source};let{anchors:r,doc:o,maxAliasCount:s}=n,i=this.resolve(o,n);if(!i){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=r.get(i);if(a||(Y(i,null,n),a=r.get(i)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Sr(o,i,r)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,n,r){let o=`*${this.source}`;if(e){if(xr(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${o} `}return o}};function Sr(t,e,n){if(xe(e)){let r=e.resolve(t),o=n&&r&&n.get(r);return o?o.count*o.aliasCount:0}else if(B(e)){let r=0;for(let o of e.items){let s=Sr(t,o,n);s>r&&(r=s)}return r}else if(T(e)){let r=Sr(t,e.key,n),o=Sr(t,e.value,n);return Math.max(r,o)}return 1}var Ar=t=>!t||typeof t!="function"&&typeof t!="object",R=class extends it{constructor(e){super(pe),this.value=e}toJSON(e,n){return n?.keep?this.value:Y(this.value,e,n)}toString(){return String(this.value)}};R.BLOCK_FOLDED="BLOCK_FOLDED";R.BLOCK_LITERAL="BLOCK_LITERAL";R.PLAIN="PLAIN";R.QUOTE_DOUBLE="QUOTE_DOUBLE";R.QUOTE_SINGLE="QUOTE_SINGLE";var $m="tag:yaml.org,2002:";function zm(t,e,n){if(e){let r=n.filter(s=>s.tag===e),o=r.find(s=>!s.format)??r[0];if(!o)throw new Error(`Tag ${e} not found`);return o}return n.find(r=>r.identify?.(t)&&!r.format)}function qe(t,e,n){if(Pe(t)&&(t=t.contents),L(t))return t;if(T(t)){let l=n.schema[_e].createNode?.(n.schema,null,n);return l.items.push(t),l}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:r,onAnchor:o,onTagObj:s,schema:i,sourceObjects:a}=n,c;if(r&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=o(t)),new Je(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=$m+e.slice(2));let u=zm(t,e,i.tags);if(!u){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let l=new R(t);return c&&(c.node=l),l}u=t instanceof Map?i[_e]:Symbol.iterator in Object(t)?i[Ge]:i[_e]}s&&(s(u),delete n.onTagObj);let p=u?.createNode?u.createNode(n.schema,t,n):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(n.schema,t,n):new R(t);return e?p.tag=e:u.default||(p.tag=u.tag),c&&(c.node=p),p}function Sn(t,e,n){let r=n;for(let o=e.length-1;o>=0;--o){let s=e[o];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let i=[];i[s]=r,r=i}else r=new Map([[s,r]])}return qe(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Bt=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Zt=class extends it{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(r=>L(r)||T(r)?r.clone(e):r),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(Bt(e))this.add(n);else{let[r,...o]=e,s=this.get(r,!0);if(B(s))s.addIn(o,n);else if(s===void 0&&this.schema)this.set(r,Sn(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}deleteIn(e){let[n,...r]=e;if(r.length===0)return this.delete(n);let o=this.get(n,!0);if(B(o))return o.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(e,n){let[r,...o]=e,s=this.get(r,!0);return o.length===0?!n&&N(s)?s.value:s:B(s)?s.getIn(o,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!T(n))return!1;let r=n.value;return r==null||e&&N(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[n,...r]=e;if(r.length===0)return this.has(n);let o=this.get(n,!0);return B(o)?o.hasIn(r):!1}setIn(e,n){let[r,...o]=e;if(o.length===0)this.set(r,n);else{let s=this.get(r,!0);if(B(s))s.setIn(o,n);else if(s===void 0&&this.schema)this.set(r,Sn(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}};var Dl=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function ye(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Ze=(t,e,n)=>t.endsWith(`-`)?ye(n,e):n.includes(`+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 Jc=(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 Wd={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Kc=(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=Wd[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}))])}},Wc=(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)},Yc=(t,e,n,r)=>{n.type="boolean"};var Xc=(t,e,n,r)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"};var Hc=(t,e,n,r)=>{n.not={}};var eu=(t,e,n,r)=>{};var tu=(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},nu=(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 ru=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var ou=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var su=(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"]})},iu=(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)},au=(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},cu=(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 uu=(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)}},lu=(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"}]},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},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,n.default=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,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},mu=(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},hu=(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},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.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},gu=(t,e,n,r)=>{let o=t._zod.innerType;J(o,e,r);let s=e.seen.get(t);s.ref=o};var rp=b("ZodISODateTime",(t,e)=>{ka.init(t,e),q.init(t,e)});function bu(t){return zc(rp,t)}var op=b("ZodISODate",(t,e)=>{Ia.init(t,e),q.init(t,e)});function wu(t){return Pc(op,t)}var sp=b("ZodISOTime",(t,e)=>{Oa.init(t,e),q.init(t,e)});function _u(t){return Lc(sp,t)}var ip=b("ZodISODuration",(t,e)=>{Ca.init(t,e),q.init(t,e)});function xu(t){return Mc(ip,t)}var Eu=(t,e)=>{Jn.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>ui(t,n)},flatten:{value:n=>ci(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,Rt,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,Rt,2)}},isEmpty:{get(){return t.issues.length===0}}})},Su=b("ZodError",Eu),ue=b("ZodError",Eu,{Parent:Error});var Au=Kn(ue),vu=Wn(ue),Du=pn(ue),Ru=mn(ue),ku=di(ue),Iu=pi(ue),Ou=mi(ue),Cu=hi(ue),Tu=yi(ue),Nu=gi(ue),$u=bi(ue),zu=wi(ue);var Pu=new WeakMap;function wn(t,e,n){let r=Object.getPrototypeOf(t),o=Pu.get(r);if(o||(o=new Set,Pu.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=Jc(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,r)=>Au(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Du(t,n,r),t.parseAsync=async(n,r)=>vu(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Ru(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>ku(t,n,r),t.decode=(n,r)=>Iu(t,n,r),t.encodeAsync=async(n,r)=>Ou(t,n,r),t.decodeAsync=async(n,r)=>Cu(t,n,r),t.safeEncode=(n,r)=>Tu(t,n,r),t.safeDecode=(n,r)=>Nu(t,n,r),t.safeEncodeAsync=async(n,r)=>$u(t,n,r),t.safeDecodeAsync=async(n,r)=>zu(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(nm(n,r))},superRefine(n,r){return this.check(rm(n,r))},overwrite(n){return this.check(et(n))},optional(){return Bu(this)},exactOptional(){return jp(this)},nullable(){return ju(this)},nullish(){return Bu(ju(this))},nonoptional(n){return Jp(this,n)},array(){return j(this)},or(n){return Ct([this,n])},and(n){return Lp(this,n)},transform(n){return Uu(this,Zp(n))},default(n){return Vp(this,n)},prefault(n){return qp(this,n)},catch(n){return Wp(this,n)},pipe(n){return Uu(this,n)},readonly(){return Hp(this)},describe(n){let r=this.clone();return bt.add(r,{description:n}),r},meta(...n){if(n.length===0)return bt.get(this);let r=this.clone();return bt.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(t,"description",{get(){return bt.get(t)?.description},configurable:!0}),t)),Qu=b("_ZodString",(t,e)=>{tr.init(t,e),V.init(t,e),t._zod.processJSONSchema=(r,o,s)=>Kc(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(Ot(...r))},max(...r){return this.check(sr(...r))},length(...r){return this.check(ir(...r))},nonempty(...r){return this.check(Ot(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())}})}),lp=b("ZodString",(t,e)=>{tr.init(t,e),Qu.init(t,e),t.email=n=>t.check(mc(fp,n)),t.url=n=>t.check(wc(dp,n)),t.jwt=n=>t.check($c(Rp,n)),t.emoji=n=>t.check(_c(pp,n)),t.guid=n=>t.check(No(Lu,n)),t.uuid=n=>t.check(hc(cr,n)),t.uuidv4=n=>t.check(yc(cr,n)),t.uuidv6=n=>t.check(gc(cr,n)),t.uuidv7=n=>t.check(bc(cr,n)),t.nanoid=n=>t.check(xc(mp,n)),t.guid=n=>t.check(No(Lu,n)),t.cuid=n=>t.check(Ec(hp,n)),t.cuid2=n=>t.check(Sc(yp,n)),t.ulid=n=>t.check(Ac(gp,n)),t.base64=n=>t.check(Cc(Ap,n)),t.base64url=n=>t.check(Tc(vp,n)),t.xid=n=>t.check(vc(bp,n)),t.ksuid=n=>t.check(Dc(wp,n)),t.ipv4=n=>t.check(Rc(_p,n)),t.ipv6=n=>t.check(kc(xp,n)),t.cidrv4=n=>t.check(Ic(Ep,n)),t.cidrv6=n=>t.check(Oc(Sp,n)),t.e164=n=>t.check(Nc(Dp,n)),t.datetime=n=>t.check(bu(n)),t.date=n=>t.check(wu(n)),t.time=n=>t.check(_u(n)),t.duration=n=>t.check(xu(n))});function v(t){return pc(lp,t)}var q=b("ZodStringFormat",(t,e)=>{Q.init(t,e),Qu.init(t,e)}),fp=b("ZodEmail",(t,e)=>{wa.init(t,e),q.init(t,e)});var Lu=b("ZodGUID",(t,e)=>{ga.init(t,e),q.init(t,e)});var cr=b("ZodUUID",(t,e)=>{ba.init(t,e),q.init(t,e)});var dp=b("ZodURL",(t,e)=>{_a.init(t,e),q.init(t,e)});var pp=b("ZodEmoji",(t,e)=>{xa.init(t,e),q.init(t,e)});var mp=b("ZodNanoID",(t,e)=>{Ea.init(t,e),q.init(t,e)});var hp=b("ZodCUID",(t,e)=>{Sa.init(t,e),q.init(t,e)});var yp=b("ZodCUID2",(t,e)=>{Aa.init(t,e),q.init(t,e)});var gp=b("ZodULID",(t,e)=>{va.init(t,e),q.init(t,e)});var bp=b("ZodXID",(t,e)=>{Da.init(t,e),q.init(t,e)});var wp=b("ZodKSUID",(t,e)=>{Ra.init(t,e),q.init(t,e)});var _p=b("ZodIPv4",(t,e)=>{Ta.init(t,e),q.init(t,e)});var xp=b("ZodIPv6",(t,e)=>{Na.init(t,e),q.init(t,e)});var Ep=b("ZodCIDRv4",(t,e)=>{$a.init(t,e),q.init(t,e)});var Sp=b("ZodCIDRv6",(t,e)=>{za.init(t,e),q.init(t,e)});var Ap=b("ZodBase64",(t,e)=>{La.init(t,e),q.init(t,e)});var vp=b("ZodBase64URL",(t,e)=>{Ma.init(t,e),q.init(t,e)});var Dp=b("ZodE164",(t,e)=>{Fa.init(t,e),q.init(t,e)});var Rp=b("ZodJWT",(t,e)=>{Za.init(t,e),q.init(t,e)});var Vu=b("ZodNumber",(t,e)=>{Io.init(t,e),V.init(t,e),t._zod.processJSONSchema=(r,o,s)=>Wc(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(Mu(r))},safe(r){return this.check(Mu(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 Fc(Vu,t)}var kp=b("ZodNumberFormat",(t,e)=>{Ba.init(t,e),Vu.init(t,e)});function Mu(t){return Zc(kp,t)}var Ip=b("ZodBoolean",(t,e)=>{ja.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Yc(t,n,r,o)});function Ve(t){return Bc(Ip,t)}var Op=b("ZodNull",(t,e)=>{Ua.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Xc(t,n,r,o)});function Cp(t){return jc(Op,t)}var Tp=b("ZodUnknown",(t,e)=>{Qa.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>eu(t,n,r,o)});function Fu(){return Uc(Tp)}var Np=b("ZodNever",(t,e)=>{Va.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Hc(t,n,r,o)});function Gu(t){return Qc(Np,t)}var $p=b("ZodArray",(t,e)=>{Ga.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>su(t,n,r,o),t.element=e.element,wn(t,"ZodArray",{min(n,r){return this.check(Ot(n,r))},nonempty(n){return this.check(Ot(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 Vc($p,t,e)}var qu=b("ZodObject",(t,e)=>{Ka.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>iu(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:Fu()})},loose(){return this.clone({...this._zod.def,catchall:Fu()})},strict(){return this.clone({...this._zod.def,catchall:Gu()})},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(Ku,this,n[0])},required(...n){return F.required(Wu,this,n[0])}})});function tt(t,e){let n={type:"object",shape:t??{},...F.normalizeParams(e)};return new qu(n)}function O(t,e){return new qu({type:"object",shape:t,catchall:Gu(),...F.normalizeParams(e)})}var Ju=b("ZodUnion",(t,e)=>{Oo.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>au(t,n,r,o),t.options=e.options});function Ct(t,e){return new Ju({type:"union",options:t,...F.normalizeParams(e)})}var zp=b("ZodDiscriminatedUnion",(t,e)=>{Ju.init(t,e),Wa.init(t,e)});function Tt(t,e,n){return new zp({type:"union",options:e,discriminator:t,...F.normalizeParams(n)})}var Pp=b("ZodIntersection",(t,e)=>{Ya.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>cu(t,n,r,o)});function Lp(t,e){return new Pp({type:"intersection",left:t,right:e})}var Zu=b("ZodRecord",(t,e)=>{Xa.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>uu(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType});function Ee(t,e,n){return!e||!e._zod?new Zu({type:"record",keyType:v(),valueType:t,...F.normalizeParams(e)}):new Zu({type:"record",keyType:t,valueType:e,...F.normalizeParams(n)})}var Ko=b("ZodEnum",(t,e)=>{Ha.init(t,e),V.init(t,e),t._zod.processJSONSchema=(r,o,s)=>tu(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 Mp=b("ZodLiteral",(t,e)=>{ec.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>nu(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 Mp({type:"literal",values:Array.isArray(t)?t:[t],...F.normalizeParams(e)})}var Fp=b("ZodTransform",(t,e)=>{tc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ou(t,n,r,o),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new vt(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 Zp(t){return new Fp({type:"transform",transform:t})}var Ku=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 Bu(t){return new Ku({type:"optional",innerType:t})}var Bp=b("ZodExactOptional",(t,e)=>{nc.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 jp(t){return new Bp({type:"optional",innerType:t})}var Up=b("ZodNullable",(t,e)=>{rc.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 ju(t){return new Up({type:"nullable",innerType:t})}var Qp=b("ZodDefault",(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,t.removeDefault=t.unwrap});function Vp(t,e){return new Qp({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():F.shallowClone(e)}})}var Gp=b("ZodPrefault",(t,e)=>{sc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>pu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function qp(t,e){return new Gp({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():F.shallowClone(e)}})}var Wu=b("ZodNonOptional",(t,e)=>{ic.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>fu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Jp(t,e){return new Wu({type:"nonoptional",innerType:t,...F.normalizeParams(e)})}var Kp=b("ZodCatch",(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,t.removeCatch=t.unwrap});function Wp(t,e){return new Kp({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Yp=b("ZodPipe",(t,e)=>{cc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>hu(t,n,r,o),t.in=e.in,t.out=e.out});function Uu(t,e){return new Yp({type:"pipe",in:t,out:e})}var Xp=b("ZodReadonly",(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.innerType});function Hp(t){return new Xp({type:"readonly",innerType:t})}var em=b("ZodLazy",(t,e)=>{lc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>gu(t,n,r,o),t.unwrap=()=>t._zod.def.getter()});function Wo(t){return new em({type:"lazy",getter:t})}var tm=b("ZodCustom",(t,e)=>{fc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ru(t,n,r,o)});function nm(t,e={}){return Gc(tm,t,e)}function rm(t,e){return qc(t,e)}function nt(t){let e=Wo(()=>Ct([v(t),N(),Ve(),Cp(),j(e),Ee(v(),e)]));return e}var Yu=t=>"field"in t?[t]:("all"in t?t.all:t.any).flatMap(Yu),ur=t=>Yu(t);var Nt=(t,e)=>{if("field"in t)return e(t);let n="all"in t?t.all:t.any,r=!1;if("all"in t){for(let o of n){let s=Nt(o,e);if(s===!1)return!1;r||=s===void 0}return r?void 0:!0}for(let o of n){let s=Nt(o,e);if(s===!0)return!0;r||=s===void 0}return r?void 0:!1},Xu=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}},Hu=(t,e={})=>{let n=o=>{let s=j(o),i=e.maximumChildren===void 0?s:s.max(e.maximumChildren);return Ct([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 wt(t,e=new Set){if(typeof t=="number"&&isNaN(t))throw new Error("NaN is not allowed");if(typeof t=="number"&&!isFinite(t))throw new Error("Infinity is not allowed");if(t===null||typeof t!="object")return JSON.stringify(t);if(typeof t.toJSON=="function"){if(e.has(t))throw new Error("Circular reference detected");e.add(t);let r=wt(t.toJSON(),e);return e.delete(t),r}if(e.has(t))throw new Error("Circular reference detected");e.add(t);let n;if(Array.isArray(t))n=`[${t.map(o=>wt(o===void 0||typeof o=="symbol"?null:o,e)).join(",")}]`;else{let r=[];for(let o of Object.keys(t).sort())t[o]===void 0||typeof t[o]=="symbol"||r.push(`${wt(o)}:${wt(t[o],e)}`);n=`{${r.join(",")}}`}return e.delete(t),n}var om=new TextEncoder,$t=t=>om.encode(t),Ce=t=>$t(t).byteLength,se=class extends Error{constructor(){super("Byte stream exceeds the configured limit"),this.name="ByteLimitExceededError"}},sm=(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 $t(t)}}:t instanceof Uint8Array?{async*[Symbol.asyncIterator](){yield t}}:t,el=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 sm(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 tl=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 tl(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))tl(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")},rt=t=>Ho(t,new Set),fe=t=>{let e=wt(rt(t));if(e===void 0)throw new Error("Value cannot be represented as canonical JSON");return e},_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"?$t(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("")},nl=async t=>`sha256:${await es(t)}`;var rl=Tt("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:rl}),im=t=>{let e=rl.parse(t);return e.type==="json"?Object.freeze({...e,path:Object.freeze([...e.path])}):Object.freeze(e)},ol=t=>{let e=ts.parse(t);return Object.freeze({...e,representation:im(e.representation)})};var xn=["json","markdown","mdx"],sl=t=>typeof t=="string"&&xn.includes(t),il=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])}},am=(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:ol(c.reference)})}).sort(am),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)})},cm=t=>new Map(t.nodes.map(e=>[e.id,e]));var dr=({graph:t,rootIds:e})=>{let n=cm(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 um=v().regex(/^sha256:[a-f0-9]{64}$/),al=O({format:Z("webstudio-document-graph"),version:Z(1),nodes:j(lr),edges:j(fr),integrity:O({algorithm:Z("sha256"),checksum:um})});var lm=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"}),fl=O({_id:v().min(1),_type:Z("asset.file"),name:v().min(1),description:v().optional(),path:lm,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=fl.partial().required({_id:!0}),fm=ee(["null","boolean","number","string","object","array"]),dm=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(fm).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}$/),dl=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"})}),cl=O({format:Z("webstudio-content-database"),version:Z(1),assetRevision:pr,documents:j(rs),documentGraph:al.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:dm,queries:Ee(pr,dl).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"})}),pm=Tt("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"]},pl=Object.keys(os),ml=["url","width","height"],mr=t=>ml.includes(t),hl=pl.filter(t=>mr(t)===!1&&t!=="excerpt"),yl=hl.filter(t=>t!=="id"),gl=t=>hl.includes(t),mm=ee(pl),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||mm.safeParse(t[0]).success===!1)&&e.addIssue({code:"custom",message:"Asset query field path is unsupported"})}),ns=Ve().default(!0),hm=Tt("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(Xu)).size===t.length,{error:"Selected output fields must be unique"})})]),ym={mode:"fields",includeMetadata:!1,fields:ml.map(t=>[t])},bl=["eq","ne","contains","startsWith","endsWith","gt","gte","lt","lte"],jb=[...bl,"in","exists","isEmpty"],gm=O({field:Sn,operator:ee(bl),value:nt()}),bm=O({field:Sn,operator:Z("in"),value:j(nt()).max(k.resultCount)}),wm=O({field:Sn,operator:ee(["exists","isEmpty"]),value:Ve()}),_m=Tt("operator",[gm,bm,wm]),xm=Hu(_m,{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 Em=xm,wl=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]},Sm=O({field:Sn,direction:ee(["asc","desc"])}),Am=ee(["many","one","first","last"]),vm=({output:t,content:e})=>t.includeMetadata||t.mode==="all"||t.mode==="fields"&&t.fields.length>0||e.mode!=="none",ot=O({result:Am.default("many"),where:Em.default({all:[]}),sort:j(Sm).max(k.sortCount).default([]),limit:N().int().nonnegative().max(k.resultCount).default(k.defaultResultCount),offset:N().int().nonnegative().max(k.candidateDocuments).default(0),output:hm.default(ym),content:pm.default({mode:"none"})}).superRefine((t,e)=>{vm(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."})}),_l=O({query:ot,indexRevision:v().min(1).max(255).optional()}),Dm=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()}),Rm=Dm.omit({_id:!0,revision:!0,contentRef:!0}),xl=fl.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:Rm.optional()}).refine(t=>t.width===void 0==(t.height===void 0),{error:"Asset dimensions must include both width and height"}),km=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()}),ul=km.pick({usedBytes:!0,maxBytes:!0,unboundedBytes:!0,includedDocumentCount:!0,omittedDocumentCount:!0,omissionReason:!0,truncated:!0}),ss=O({items:j(xl),totalCount:N().int().nonnegative(),hasMore:Ve()}),Im=O({item:xl.nullable(),totalCount:N().int().nonnegative()}),El=Ct([ss,Im]),ll=O({line:N().int().positive(),column:N().int().positive(),offset:N().int().nonnegative().optional()}),Om=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:ll,end:ll}).optional()}),Cm=O({severity:ee(["error","warning"]),code:v().min(1),path:j(v()),message:v().min(1)}),Tm=O({scope:Z("query-preview"),queryIssues:j(Cm).optional(),queryWarnings:j(v().min(1)).optional(),query:ul,database:ul,artifacts:O({query:cl,database:cl}).optional(),unresolved:El.optional(),issues:j(Om).optional(),issueCount:N().int().nonnegative().optional(),issuesTruncated:Ve().optional()}),Ub=O({data:El,__diagnostics__:Tm}),Nm=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"]),$m=tt({ok:Z(!1),error:tt({code:Nm,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()}),Sl=({code:t,message:e,retryable:n=!1,details:r})=>$m.parse({ok:!1,error:{code:t,message:e,retryable:n,details:r}});var Al=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 Pm(o)}};var is=(t,e)=>e+"/"+zm(t),zm=t=>t.toString().replace(/~/g,"~0").replace(/\//g,"~1"),Pm=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}},Lm=(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}},Mm=t=>`#${t}`;var vl=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 rt(JSON.parse(r))}catch(o){throw new de({code:"INVALID_DOCUMENT",message:"JSON document is invalid",cause:o})}};var Fm=(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},Dl=({document:t,representation:e})=>{let n=rt(t);if(e.type==="document")return n;if(e.type!=="json")throw new de({code:"UNSUPPORTED_REPRESENTATION",message:`JSON documents do not support ${e.type}`});let r=Fm(n,e.path);if(r===void 0)throw new de({code:"JSON_PATH_NOT_FOUND",message:"JSON document path does not exist"});return r},Zm=(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=rt(t),o=new Set,s=(a,c)=>{let u=Mm(c);if(Lm(a,u)!==void 0){if(e.has(u)===!1){if(n)return a;throw new de({code:"REFERENCE_NOT_FOUND",message:`Resolved JSON reference ${u} is unavailable`,referenceId:u})}o.add(u);try{return rt(e.get(u))}catch(l){throw new de({code:"INVALID_RESOLVED_VALUE",message:`Resolved JSON reference ${u} is not JSON-compatible`,referenceId:u,cause:l})}}if(Array.isArray(a))return a.map((l,f)=>s(l,is(String(f),c)));if(Mt(a)){let l={};for(let[f,p]of Object.entries(a))Zm(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"),Rl=Symbol("skip children"),Pe=Symbol("remove node");function Le(t,e){let n=kl(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=Rl;Le.REMOVE=Pe;function Ft(t,e,n,r){let o=Il(t,e,n,r);if(z(o)||$(o))return Ol(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=kl(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=Rl;xr.REMOVE=Pe;async function Zt(t,e,n,r){let o=await Il(t,e,n,r);if(z(o)||$(o))return Ol(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 kl(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 Il(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 Ol(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 Bm={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},jm=t=>t.replace(/[!,[\]{}]/g,e=>Bm[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+jm(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 Cl(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 st(t,e,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let o=0,s=r.length;o<s;++o){let i=r[o],a=st(t,r,String(o),i);a===void 0?delete r[o]:a!==i&&(r[o]=a)}else if(r instanceof Map)for(let o of Array.from(r.keys())){let s=r.get(o),i=st(t,r,o,s);i===void 0?r.delete(o):i!==s&&r.set(o,i)}else if(r instanceof Set)for(let o of Array.from(r)){let s=st(t,r,o,o);s===void 0?r.delete(o):s!==o&&(r.delete(o),r.add(s))}else for(let[o,s]of Object.entries(r)){let i=st(t,r,o,s);i===void 0?delete r[o]:i!==s&&(r[o]=i)}return t.call(e,n,r)}function 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 it=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"?st(s,{"":a},"",a):a}};var qe=class extends it{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 it{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 Um="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=Um+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 it{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(r=>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 Tl=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(``)?`-`+ye(n,e):(t.endsWith(" ")?"":" ")+n;var ls="flow",Er="block",An="quoted";function En(t,e,n="flow",{indentAtStart:r,lineWidth:o=80,minContentWidth:s=20,onFold:i,onOverflow:a}={}){if(!o||o<0)return t;o<s&&(s=0);let c=Math.max(1+s,1+o-e.length);if(t.length<=c)return t;let u=[],p={},l=o-e.length;typeof r=="number"&&(r>o-Math.max(2,s)?u.push(0):l=o-r);let f,d,y=!1,m=-1,h=-1,b=-1;n===Er&&(m=Rl(t,m,e.length),m!==-1&&(l=m+c));for(let A;A=t[m+=1];){if(n===An&&A==="\\"){switch(h=m,t[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}b=m}if(A===`-`)n===Er&&(m=Rl(t,m,e.length)),l=m+e.length+c,f=void 0;else{if(A===" "&&d&&d!==" "&&d!==`-`&&d!==" "){let _=t[m+1];_&&_!==" "&&_!==`-`&&_!==" "&&(f=m)}if(m>=l)if(f)u.push(f),l=f+c,f=void 0;else if(n===An){for(;d===" "||d===" ";)d=A,A=t[m+=1],y=!0;let _=m>b+1?m-2:h-1;if(p[_])return t;u.push(_),p[_]=!0,l=_+c,f=void 0}else y=!0}d=A}if(y&&a&&a(),u.length===0)return t;i&&i();let S=t.slice(0,u[0]);for(let A=0;A<u.length;++A){let _=u[A],w=u[A+1]||t.length;_===0?S=`-${e}${t.slice(0,w)}`:(n===An&&p[_]&&(S+=`${t[_]}\\`),S+=`-${e}${t.slice(_+1,w)}`)}return S}function Rl(t,e,n){let r=e,o=e+1,s=t[o];for(;s===" "||s===" ";)if(e<o+n)s=t[++e];else{do s=t[++e];while(s&&s!==`-`);r=e,o=e+1,s=t[o]}return r}var Dr=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),Rr=t=>/^(%|---|\.\.\.)/m.test(t);function Pm(t,e,n){if(!e||e<0)return!1;let r=e-n,o=t.length;if(o<=r)return!1;for(let s=0,i=0;s<o;++s)if(t[s]===`-`){if(s-i>r)return!0;if(i=s+1,o-i<=r)return!1}return!0}function vn(t,e){let n=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=e,o=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(Rr(t)?" ":""),i="",a=0;for(let c=0,u=n[c];u;u=n[++c])if(u===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(i+=n.slice(a,c)+"\\ ",c+=1,a=c,u="\\"),u==="\\")switch(n[c+1]){case"u":{i+=n.slice(a,c);let p=n.substr(c+2,4);switch(p){case"0000":i+="\\0";break;case"0007":i+="\\a";break;case"000b":i+="\\v";break;case"001b":i+="\\e";break;case"0085":i+="\\N";break;case"00a0":i+="\\_";break;case"2028":i+="\\L";break;case"2029":i+="\\P";break;default:p.substr(0,2)==="00"?i+="\\x"+p.substr(2):i+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(r||n[c+2]==='"'||n.length<o)c+=1;else{for(i+=n.slice(a,c)+`+`+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=Nl(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=Nl(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 Nl(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 Vm(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)+``;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:En(i,s,An,Dr(e,!1))}function fs(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`-`)||/[ \t]\n|\n[ \t]/.test(t))return vn(t,e);let n=e.indent||(Rr(t)?" ":""),r="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&-${n}`)+"'";return e.implicitKey?r:En(r,n,ls,Dr(e,!1))}function jt(t,e){let{singleQuote:n}=e.options,r;if(n===!1)r=vn;else{let o=t.includes('"'),s=t.includes("'");o&&!s?r=fs:s&&!o?r=vn:r=n?fs:vn}return r(t,e)}var ds;try{ds=new RegExp(`(^|(?<!+`,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(`(^|(?<!))+(?!-|$)`,"g")}catch{ds=/\n+(?!\n|$)/g}function vr({comment:t,type:e,value:n},r,o,s){let{blockQuote:i,commentString:a,lineWidth:c}=r.options;if(!i||/\n[\t ]+$/.test(n))return jt(n,r);let u=r.indent||(r.forceBlockIndent||Rr(n)?" ":""),p=i==="literal"?!0:i==="folded"||e===R.BLOCK_FOLDED?!1:e===R.BLOCK_LITERAL?!0:!Pm(n,c,u.length);if(!n)return p?`|+|$)`,"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:!Vm(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 d=n.substring(f),y=d.indexOf(`-`);y===-1?l="-":n===d||y!==d.length-1?(l="+",s&&s()):l="",d&&(n=n.slice(0,-d.length),d[d.length-1]===`-`&&(d=d.slice(0,-1)),d=d.replace(ds,`$&${u}`));let m=!1,h,b=-1;for(h=0;h<n.length;++h){let w=n[h];if(w===" ")m=!0;else if(w===`-`)b=h;else break}let S=n.substring(0,b<h?b+1:h);S&&(n=n.substring(S.length),S=S.replace(/\n+/g,`$&${u}`));let _=(m?u?"2":"1":"")+l;if(t&&(_+=" "+a(t.replace(/ ?[\r\n]+/g," ")),o&&o()),!p){let w=n.replace(/\n+/g,`-$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`),E=!1,D=Dr(r,!0);i!=="folded"&&e!==R.BLOCK_FOLDED&&(D.onOverflow=()=>{E=!0});let x=En(`${S}${w}${d}`,u,Er,D);if(!E)return`>${_}-${u}${x}`}return n=n.replace(/\n+/g,`$&${u}`),`|${_}-${u}${S}${n}${d}`}function Lm(t,e,n,r){let{type:o,value:s}=t,{actualString:i,implicitKey:a,indent:c,indentStep:u,inFlow:p}=e;if(a&&s.includes(`-`)||p&&/[[\]{},]/.test(s))return jt(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||p||!s.includes(`-`)?jt(s,e):vr(t,e,n,r);if(!a&&!p&&o!==R.PLAIN&&s.includes(`-`))return vr(t,e,n,r);if(Rr(s)){if(c==="")return e.forceBlockIndent=!0,vr(t,e,n,r);if(a&&c===u)return jt(s,e)}let l=s.replace(/\n+/g,`$&-${c}`);if(i){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(l),{compat:d,tags:y}=e.doc.schema;if(y.some(f)||d?.some(f))return jt(s,e)}return a?l:En(l,c,ls,Dr(e,!1))}function _t(t,e,n,r){let{implicitKey:o,inFlow:s}=e,i=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==R.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(i.value)&&(a=R.QUOTE_DOUBLE);let c=p=>{switch(p){case R.BLOCK_FOLDED:case R.BLOCK_LITERAL:return o||s?jt(i.value,e):vr(i,e,n,r);case R.QUOTE_DOUBLE:return vn(i.value,e);case R.QUOTE_SINGLE:return fs(i.value,e);case R.PLAIN:return Lm(i,e,n,r);default:return null}},u=c(a);if(u===null){let{defaultKeyType:p,defaultStringType:l}=e.options,f=o&&p||l;if(u=c(f),u===null)throw new Error(`Unsupported default string type ${f}`)}return u}function kr(t,e){let n=Object.assign({blockQuote:!0,commentString:Dl,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:r,options:n}}function Mm(t,e){if(e.tag){let o=t.filter(s=>s.tag===e.tag);if(o.length>0)return o.find(s=>s.format===e.format)??o[0]}let n,r;if(N(e)){r=e.value;let o=t.filter(s=>s.identify?.(r));if(o.length>1){let s=o.filter(i=>i.test);s.length>0&&(o=s)}n=o.find(s=>s.format===e.format)??o.find(s=>!s.format)}else r=e,n=t.find(o=>o.nodeClass&&r instanceof o.nodeClass);if(!n){let o=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${o} value`)}return n}function Fm(t,e,{anchors:n,doc:r}){if(!r.directives)return"";let o=[],s=(N(t)||B(t))&&t.anchor;s&&xr(s)&&(n.add(s),o.push(`&${s}`));let i=t.tag??(e.default?null:e.tag);return i&&o.push(r.directives.tagString(i)),o.join(" ")}function Ke(t,e,n,r){if(T(t))return t.toString(e,n,r);if(xe(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let o,s=L(t)?t:e.doc.createNode(t,{onTagObj:c=>o=c});o??(o=Mm(e.doc.schema.tags,s));let i=Fm(s,o,e);i.length>0&&(e.indentAtStart=(e.indentAtStart??0)+i.length+1);let a=typeof o.stringify=="function"?o.stringify(s,e,n,r):N(s)?_t(s,e,n,r):s.toString(e,n,r);return i?N(s)||a[0]==="{"||a[0]==="["?`${i} ${a}`:`${i}-${e.indent}${a}`:a}function kl({key:t,value:e},n,r,o){let{allNullValues:s,doc:i,indent:a,indentStep:c,options:{commentString:u,indentSeq:p,simpleKeys:l}}=n,f=L(t)&&t.comment||null;if(l){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(B(t)||!L(t)&&typeof t=="object"){let D="With simple keys, collection cannot be used as a key value";throw new Error(D)}}let d=!l&&(!t||f&&e==null&&!n.inFlow||B(t)||(N(t)?t.type===R.BLOCK_FOLDED||t.type===R.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!d&&(l||!s),indent:a+c});let y=!1,m=!1,h=Ke(t,n,()=>y=!0,()=>m=!0);if(!d&&!n.inFlow&&h.length>1024){if(l)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");d=!0}if(n.inFlow){if(s||e==null)return y&&r&&r(),h===""?"?":d?`? ${h}`:h}else if(s&&!l||e==null&&d)return h=`? ${h}`,f&&!y?h+=Ze(h,n.indent,u(f)):m&&o&&o(),h;y&&(f=null),d?(f&&(h+=Ze(h,n.indent,u(f))),h=`? ${h}-${a}:`):(h=`${h}:`,f&&(h+=Ze(h,n.indent,u(f))));let b,S,A;L(e)?(b=!!e.spaceBefore,S=e.commentBefore,A=e.comment):(b=!1,S=null,A=null,e&&typeof e=="object"&&(e=i.createNode(e))),n.implicitKey=!1,!d&&!f&&N(e)&&(n.indentAtStart=h.length+1),m=!1,!p&&c.length>=2&&!n.inFlow&&!d&&Ae(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let _=!1,w=Ke(e,n,()=>_=!0,()=>m=!0),E=" ";if(f||b||S){if(E=b?`-`:"",S){let D=u(S);E+=`-${ye(D,n.indent)}`}w===""&&!n.inFlow?E===`-`&&A&&(E=`+`&&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 Gm(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 _t(t,e,n,r){let{implicitKey:o,inFlow:s}=e,i=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==R.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(i.value)&&(a=R.QUOTE_DOUBLE);let c=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 Gm(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:Tl,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 qm(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 Jm(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=qm(e.doc.schema.tags,s));let i=Jm(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)?_t(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 $l({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===`+`&&S&&(A=`-`):E+=`-${n.indent}`}else if(!d&&B(e)){let D=w[0],x=w.indexOf(`-`),O=x!==-1,$=n.inFlow??e.flow??e.items.length===0;if(O||!$){let G=!1;if(O&&(D==="&"||D==="!")){let z=w.indexOf(" ");D==="&"&&z!==-1&&z<x&&w[z+1]==="!"&&(z=w.indexOf(" ",z+1)),(z===-1||x<z)&&(G=!0)}G||(E=`+`):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(w===""||w[0]===`-`)&&(E="");return h+=E+w,n.inFlow?_&&r&&r():A&&!_?h+=Ze(h,n.indent,u(A)):m&&o&&o(),h}function ps(t,e){(t==="debug"||t==="warn")&&console.warn(e)}var Ir="<<",Ee={identify:t=>t===Ir||typeof t=="symbol"&&t.description===Ir,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new R(Symbol(Ir)),{addToJSMap:hs}),stringify:()=>Ir},Il=(t,e)=>(Ee.identify(e)||N(e)&&(!e.type||e.type===R.PLAIN)&&Ee.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===Ee.tag&&n.default);function hs(t,e,n){let r=Ol(t,n);if(Ae(r))for(let o of r.items)ms(t,e,o);else if(Array.isArray(r))for(let o of r)ms(t,e,o);else ms(t,e,r)}function ms(t,e,n){let r=Ol(t,n);if(!Se(r))throw new Error("Merge sources must be maps or map aliases");let o=r.toJSON(null,t,Map);for(let[s,i]of o)e instanceof Map?e.has(s)||e.set(s,i):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:i,writable:!0,enumerable:!0,configurable:!0});return e}function Ol(t,e){return t&&xe(e)?e.resolve(t.doc,t):e}function Or(t,e,{key:n,value:r}){if(L(n)&&n.addToJSMap)n.addToJSMap(t,e,r);else if(Il(t,n))hs(t,e,r);else{let o=Y(n,"",t);if(e instanceof Map)e.set(o,Y(r,o,t));else if(e instanceof Set)e.add(o);else{let s=Zm(n,o,t),i=Y(r,s,t);s in e?Object.defineProperty(e,s,{value:i,writable:!0,enumerable:!0,configurable:!0}):e[s]=i}}return e}function Zm(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(L(t)&&n?.doc){let r=kr(n.doc,{});r.anchors=new Set;for(let s of n.anchors.keys())r.anchors.add(s.anchor);r.inFlow=!0,r.inStringifyKey=!0;let o=t.toString(r);if(!n.mapKeyWarned){let s=JSON.stringify(o);s.length>40&&(s=s.substring(0,36)+'..."'),ps(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return o}return JSON.stringify(e)}function Ut(t,e,n){let r=qe(t,void 0,n),o=qe(e,void 0,n);return new K(r,o)}var K=class t{constructor(e,n=null){Object.defineProperty(this,oe,{value:as}),this.key=e,this.value=n}clone(e){let{key:n,value:r}=this;return L(n)&&(n=n.clone(e)),L(r)&&(r=r.clone(e)),new t(n,r)}toJSON(e,n){let r=n?.mapAsMap?new Map:{};return Or(n,r,this)}toString(e,n,r){return e?.doc?kl(this,e,n,r):JSON.stringify(this)}};function Nr(t,e,n){return(e.inFlow??t.flow?jm:Bm)(t,e,n)}function Bm({comment:t,items:e},n,{blockItemPrefix:r,flowChars:o,itemIndent:s,onChompKeep:i,onComment:a}){let{indent:c,options:{commentString:u}}=n,p=Object.assign({},n,{indent:s,type:null}),l=!1,f=[];for(let y=0;y<e.length;++y){let m=e[y],h=null;if(L(m))!l&&m.spaceBefore&&f.push(""),Cr(n,f,m.commentBefore,l),m.comment&&(h=m.comment);else if(T(m)){let S=L(m.key)?m.key:null;S&&(!l&&S.spaceBefore&&f.push(""),Cr(n,f,S.commentBefore,l))}l=!1;let b=Ke(m,p,()=>h=null,()=>l=!0);h&&(b+=Ze(b,s,u(h))),l&&h&&(l=!1),f.push(r+b)}let d;if(f.length===0)d=o.start+o.end;else{d=f[0];for(let y=1;y<f.length;++y){let m=f[y];d+=m?`+`)&&(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},zl=(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=Pl(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=Pl(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 Pl(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(zl(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=Km(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 Km(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?$l(this,e,n,r):JSON.stringify(this)}};function Nr(t,e,n){return(e.inFlow??t.flow?Ym:Wm)(t,e,n)}function Wm({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?`${c}${m}`:`-`}}return t?(d+=`-`+ye(u(t),c),a&&a()):l&&i&&i(),d}function jm({items:t},e,{flowChars:n,itemIndent:r}){let{indent:o,indentStep:s,flowCollectionPadding:i,options:{commentString:a}}=e;r+=s;let c=Object.assign({},e,{indent:r,inFlow:!0,type:null}),u=!1,p=0,l=[];for(let y=0;y<t.length;++y){let m=t[y],h=null;if(L(m))m.spaceBefore&&l.push(""),Cr(e,l,m.commentBefore,!1),m.comment&&(h=m.comment);else if(T(m)){let S=L(m.key)?m.key:null;S&&(S.spaceBefore&&l.push(""),Cr(e,l,S.commentBefore,!1),S.comment&&(u=!0));let A=L(m.value)?m.value:null;A?(A.comment&&(h=A.comment),A.commentBefore&&(u=!0)):m.value==null&&S?.comment&&(h=S.comment)}h&&(u=!0);let b=Ke(m,c,()=>h=null);u||(u=l.length>p||b.includes(`-`)),y<t.length-1?b+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(u||(u=l.reduce((S,A)=>S+A.length+2,2)+(b.length+2)>e.options.lineWidth)),u&&(b+=",")),h&&(b+=Ze(b,r,a(h))),l.push(b),p=l.length}let{start:f,end:d}=n;if(l.length===0)return f+d;if(!u){let y=l.reduce((m,h)=>m+h.length+2,2);u=e.options.lineWidth>0&&y>e.options.lineWidth}if(u){let y=f;for(let m of l)y+=m?`+`}}return t?(p+=`+`+be(u(t),c),a&&a()):l&&i&&i(),p}function Ym({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?`${s}${o}${m}`:``;return`${y}-${o}${d}`}else return`${f}${i}${l.join(" ")}${i}${d}`}function Cr({indent:t,options:{commentString:e}},n,r,o){if(r&&o&&(r=r.replace(/^\n+/,"")),r){let s=ye(e(r),t);n.push(s.trimStart())}}function at(t,e){let n=N(e)?e.value:e;for(let r of t)if(T(r)&&(r.key===e||r.key===n||N(r.key)&&r.key.value===n))return r}var W=class extends Zt{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(_e,e),this.items=[]}static from(e,n,r){let{keepUndefined:o,replacer:s}=r,i=new this(e),a=(c,u)=>{if(typeof s=="function")u=s.call(n,c,u);else if(Array.isArray(s)&&!s.includes(c))return;(u!==void 0||o)&&i.items.push(Ut(c,u,r))};if(n instanceof Map)for(let[c,u]of n)a(c,u);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&i.items.sort(e.sortMapEntries),i}add(e,n){let r;T(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new K(e,e?.value):r=new K(e.key,e.value);let o=at(this.items,r.key),s=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${r.key} already set`);N(o.value)&&Ar(r.value)?o.value.value=r.value:o.value=r.value}else if(s){let i=this.items.findIndex(a=>s(r,a)<0);i===-1?this.items.push(r):this.items.splice(i,0,r)}else this.items.push(r)}delete(e){let n=at(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let o=at(this.items,e)?.value;return(!n&&N(o)?o.value:o)??void 0}has(e){return!!at(this.items,e)}set(e,n){this.add(new K(e,n),!0)}toJSON(e,n,r){let o=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(o);for(let s of this.items)Or(n,o,s);return o}toString(e,n,r){if(!e)return JSON.stringify(this);for(let o of this.items)if(!T(o))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Nr(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:n})}};var ve={collection:"map",default:!0,nodeClass:W,tag:"tag:yaml.org,2002:map",resolve(t,e){return Se(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>W.from(t,e,n)};var ee=class extends Zt{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Ge,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=Tr(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let r=Tr(e);if(typeof r!="number")return;let o=this.items[r];return!n&&N(o)?o.value:o}has(e){let n=Tr(e);return typeof n=="number"&&n<this.items.length}set(e,n){let r=Tr(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);let o=this.items[r];N(o)&&Ar(n)?o.value=n:this.items[r]=n}toJSON(e,n){let r=[];n?.onCreate&&n.onCreate(r);let o=0;for(let s of this.items)r.push(Y(s,String(o++),n));return r}toString(e,n,r){return e?Nr(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:r,onComment:n}):JSON.stringify(this)}static from(e,n,r){let{replacer:o}=r,s=new this(e);if(n&&Symbol.iterator in Object(n)){let i=0;for(let a of n){if(typeof o=="function"){let c=n instanceof Set?a:String(i++);a=o.call(n,c,a)}s.items.push(qe(a,void 0,r))}}return s}};function Tr(t){let e=N(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}var De={collection:"seq",default:!0,nodeClass:ee,tag:"tag:yaml.org,2002:seq",resolve(t,e){return Ae(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>ee.from(t,e,n)};var ct={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,r){return e=Object.assign({actualString:!0},e),_t(t,e,n,r)}};var xt={identify:t=>t==null,createNode:()=>new R(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new R(null),stringify:({source:t},e)=>typeof t=="string"&&xt.test.test(t)?t:e.options.nullStr};var Dn={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new R(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&Dn.test.test(t)){let r=t[0]==="t"||t[0]==="T";if(e===r)return t}return e?n.options.trueStr:n.options.falseStr}};function te({format:t,minFractionDigits:e,tag:n,value:r}){if(typeof r=="bigint")return String(r);let o=typeof r=="number"?r:Number(r);if(!isFinite(o))return isNaN(o)?".nan":o<0?"-.inf":".inf";let s=Object.is(r,-0)?"-0":JSON.stringify(r);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let i=s.indexOf(".");i<0&&(i=s.length,s+=".");let a=e-(s.length-i-1);for(;a-- >0;)s+="0"}return s}var $r={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:te},zr={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():te(t)}},Pr={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new R(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:te};var Lr=t=>typeof t=="bigint"||Number.isInteger(t),ys=(t,e,n,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),n);function Cl(t,e,n){let{value:r}=t;return Lr(r)&&r>=0?n+r.toString(e):te(t)}var Mr={identify:t=>Lr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>ys(t,2,8,n),stringify:t=>Cl(t,8,"0o")},Fr={identify:Lr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>ys(t,0,10,n),stringify:te},Zr={identify:t=>Lr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>ys(t,2,16,n),stringify:t=>Cl(t,16,"0x")};var Nl=[ve,De,ct,xt,Dn,Mr,Fr,Zr,$r,zr,Pr];function Tl(t){return typeof t=="bigint"||Number.isInteger(t)}var Br=({value:t})=>JSON.stringify(t),Um=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:Br},{identify:t=>t==null,createNode:()=>new R(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Br},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:Br},{identify:Tl,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:n})=>n?BigInt(t):parseInt(t,10),stringify:({value:t})=>Tl(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:Br}],Qm={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},$l=[ve,De].concat(Um,Qm);var Rn={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),r=new Uint8Array(n.length);for(let o=0;o<n.length;++o)r[o]=n.charCodeAt(o);return r}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:n},r,o,s){if(!n)return"";let i=n,a;if(typeof btoa=="function"){let c="";for(let u=0;u<i.length;++u)c+=String.fromCharCode(i[u]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=R.BLOCK_LITERAL),e!==R.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),u=Math.ceil(a.length/c),p=new Array(u);for(let l=0,f=0;l<u;++l,f+=c)p[l]=a.substr(f,c);a=p.join(e===R.BLOCK_LITERAL?`-`:" ")}return _t({comment:t,type:e,value:a},r,o,s)}};function gs(t,e){if(Ae(t))for(let n=0;n<t.items.length;++n){let r=t.items[n];if(!T(r)){if(Se(r)){r.items.length>1&&e("Each pair must have its own sequence indicator");let o=r.items[0]||new K(new R(null));if(r.commentBefore&&(o.key.commentBefore=o.key.commentBefore?`${r.commentBefore}+${o}${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 at(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=at(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=at(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let o=at(this.items,e)?.value;return(!n&&T(o)?o.value:o)??void 0}has(e){return!!at(this.items,e)}set(e,n){this.add(new K(e,n),!0)}toJSON(e,n,r){let o=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(o);for(let s of this.items)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 ct={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,r){return e=Object.assign({actualString:!0},e),_t(t,e,n,r)}};var xt={identify:t=>t==null,createNode:()=>new R(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new R(null),stringify:({source:t},e)=>typeof t=="string"&&xt.test.test(t)?t:e.options.nullStr};var 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 Ll(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=>Ll(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=>Ll(t,16,"0x")};var Ml=[ve,De,ct,xt,kn,Fr,Zr,Br,zr,Pr,Lr];function Fl(t){return typeof t=="bigint"||Number.isInteger(t)}var jr=({value:t})=>JSON.stringify(t),Xm=[{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:Fl,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})=>Fl(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}],Hm={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Zl=[ve,De].concat(Xm,Hm);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 _t({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}${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]=T(r)?r:new K(r)}}else e("Expected a sequence for this tag");return t}function bs(t,e,n){let{replacer:r}=n,o=new ee(t);o.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let i of e){typeof r=="function"&&(i=r.call(e,String(s++),i));let a,c;if(Array.isArray(i))if(i.length===2)a=i[0],c=i[1];else throw new TypeError(`Expected [key, value] tuple: ${i}`);else if(i&&i instanceof Object){let u=Object.keys(i);if(u.length===1)a=u[0],c=i[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=i;o.items.push(Ut(a,c,n))}return o}var kn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:gs,createNode:bs};var Qt=class t extends ee{constructor(){super(),this.add=W.prototype.add.bind(this),this.delete=W.prototype.delete.bind(this),this.get=W.prototype.get.bind(this),this.has=W.prototype.has.bind(this),this.set=W.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let r=new Map;n?.onCreate&&n.onCreate(r);for(let o of this.items){let s,i;if(T(o)?(s=Y(o.key,"",n),i=Y(o.value,s,n)):s=Y(o,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,i)}return r}static from(e,n,r){let o=bs(e,n,r),s=new this;return s.items=o.items,s}};Qt.tag="tag:yaml.org,2002:omap";var In={collection:"seq",identify:t=>t instanceof Map,nodeClass:Qt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=gs(t,e),r=[];for(let{key:o}of n.items)N(o)&&(r.includes(o.value)?e(`Ordered maps must not include duplicate keys: ${o.value}`):r.push(o.value));return Object.assign(new Qt,n)},createNode:(t,e,n)=>Qt.from(t,e,n)};function zl({value:t,source:e},n){return e&&(t?ws:_s).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var ws={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new R(!0),stringify:zl},_s={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new R(!1),stringify:zl};var Pl={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:te},Ll={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():te(t)}},Ml={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new R(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let r=t.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:te};var On=t=>typeof t=="bigint"||Number.isInteger(t);function jr(t,e,n,{intAsBigInt:r}){let o=t[0];if((o==="-"||o==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),r){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let i=BigInt(t);return o==="-"?BigInt(-1)*i:i}let s=parseInt(t,n);return o==="-"?-1*s:s}function xs(t,e,n){let{value:r}=t;if(On(r)){let o=r.toString(e);return r<0?"-"+n+o.substr(1):n+o}return te(t)}var Fl={identify:On,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>jr(t,2,2,n),stringify:t=>xs(t,2,"0b")},Zl={identify:On,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>jr(t,1,8,n),stringify:t=>xs(t,8,"0")},Bl={identify:On,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>jr(t,0,10,n),stringify:te},jl={identify:On,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>jr(t,2,16,n),stringify:t=>xs(t,16,"0x")};var Vt=class t extends W{constructor(e){super(e),this.tag=t.tag}add(e){let n;T(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new K(e.key,null):n=new K(e,null),at(this.items,n.key)||this.items.push(n)}get(e,n){let r=at(this.items,e);return!n&&T(r)?N(r.key)?r.key.value:r.key:r}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=at(this.items,e);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new K(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(e,n,r){let{replacer:o}=r,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let i of n)typeof o=="function"&&(i=o.call(n,i,i)),s.items.push(Ut(i,null,r));return s}};Vt.tag="tag:yaml.org,2002:set";var Cn={collection:"map",identify:t=>t instanceof Set,nodeClass:Vt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>Vt.from(t,e,n),resolve(t,e){if(Se(t)){if(t.hasAllNullValues(!0))return Object.assign(new Vt,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};function Ss(t,e){let n=t[0],r=n==="-"||n==="+"?t.substring(1):t,o=i=>e?BigInt(i):Number(i),s=r.replace(/_/g,"").split(":").reduce((i,a)=>i*o(60)+o(a),o(0));return n==="-"?o(-1)*s:s}function Ul(t){let{value:e}=t,n=i=>i;if(typeof e=="bigint")n=i=>BigInt(i);else if(isNaN(e)||!isFinite(e))return te(t);let r="";e<0&&(r="-",e*=n(-1));let o=n(60),s=[e%o];return e<60?s.unshift(0):(e=(e-s[0])/o,s.unshift(e%o),e>=60&&(e=(e-s[0])/o,s.unshift(e))),r+s.map(i=>String(i).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Ur={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>Ss(t,n),stringify:Ul},Qr={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>Ss(t,!1),stringify:Ul},Gt={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(Gt.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,o,s,i,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,u=Date.UTC(n,r-1,o,s||0,i||0,a||0,c),p=e[8];if(p&&p!=="Z"){let l=Ss(p,!1);Math.abs(l)<30&&(l*=60),u-=6e4*l}return new Date(u)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};var As=[ve,De,ct,xt,ws,_s,Fl,Zl,Bl,jl,Pl,Ll,Ml,Rn,Ee,In,kn,Cn,Ur,Qr,Gt];var Ql=new Map([["core",Nl],["failsafe",[ve,De,ct]],["json",$l],["yaml11",As],["yaml-1.1",As]]),Vl={binary:Rn,bool:Dn,float:Pr,floatExp:zr,floatNaN:$r,floatTime:Qr,int:Fr,intHex:Zr,intOct:Mr,intTime:Ur,map:ve,merge:Ee,null:xt,omap:In,pairs:kn,seq:De,set:Cn,timestamp:Gt},Gl={"tag:yaml.org,2002:binary":Rn,"tag:yaml.org,2002:merge":Ee,"tag:yaml.org,2002:omap":In,"tag:yaml.org,2002:pairs":kn,"tag:yaml.org,2002:set":Cn,"tag:yaml.org,2002:timestamp":Gt};function Vr(t,e,n){let r=Ql.get(e);if(r&&!t)return n&&!r.includes(Ee)?r.concat(Ee):r.slice();let o=r;if(!o)if(Array.isArray(t))o=[];else{let s=Array.from(Ql.keys()).filter(i=>i!=="yaml11").map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(t))for(let s of t)o=o.concat(s);else typeof t=="function"&&(o=t(o.slice()));return n&&(o=o.concat(Ee)),o.reduce((s,i)=>{let a=typeof i=="string"?Vl[i]:i;if(!a){let c=JSON.stringify(i),u=Object.keys(Vl).map(p=>JSON.stringify(p)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${u}`)}return s.includes(a)||s.push(a),s},[])}var Vm=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,Nn=class t{constructor({compat:e,customTags:n,merge:r,resolveKnownTags:o,schema:s,sortMapEntries:i,toStringDefaults:a}){this.compat=Array.isArray(e)?Vr(e,"compat"):e?Vr(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=o?Gl:{},this.tags=Vr(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,_e,{value:ve}),Object.defineProperty(this,pe,{value:ct}),Object.defineProperty(this,Ge,{value:De}),this.sortMapEntries=typeof i=="function"?i:i===!0?Vm:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function Jl(t,e){let n=[],r=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),r=!0):t.directives.docStart&&(r=!0)}r&&n.push("---");let o=kr(t,e),{commentString:s}=o.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(ye(c,""))}let i=!1,a=null;if(t.contents){if(L(t.contents)){if(t.contents.spaceBefore&&r&&n.push(""),t.contents.commentBefore){let p=s(t.contents.commentBefore);n.push(ye(p,""))}o.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>i=!0,u=Ke(t.contents,o,()=>a=null,c);a&&(u+=Ze(u,"",s(a))),(u[0]==="|"||u[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${u}`:n.push(u)}else n.push(Ke(t.contents,o));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(`-`)?(n.push("..."),n.push(ye(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=t.comment;c&&i&&(c=c.replace(/^\n+/,"")),c&&((!i||a)&&n[n.length-1]!==""&&n.push(""),n.push(ye(s(c),"")))}return n.join(`+${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 Bl({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:Bl},_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:Bl};var jl={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},Ul={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)}},Ql={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 Vl={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")},Gl={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")},ql={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},Jl={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),at(this.items,n.key)||this.items.push(n)}get(e,n){let r=at(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=at(this.items,e);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new K(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(e,n,r){let{replacer:o}=r,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let i of n)typeof o=="function"&&(i=o.call(n,i,i)),s.items.push(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 Kl(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:Kl},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:Kl},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,ct,xt,ws,_s,Vl,Gl,ql,Jl,jl,Ul,Ql,In,Ae,Cn,On,Nn,Qr,Vr,qt];var Wl=new Map([["core",Ml],["failsafe",[ve,De,ct]],["json",Zl],["yaml11",Ss],["yaml-1.1",Ss]]),Yl={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:xt,omap:Cn,pairs:On,seq:De,set:Nn,timestamp:qt},Xl={"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=Wl.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(Wl.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"?Yl[i]:i;if(!a){let c=JSON.stringify(i),u=Object.keys(Yl).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 eh=(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?Xl:{},this.tags=Gr(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,Se,{value:ve}),Object.defineProperty(this,pe,{value:ct}),Object.defineProperty(this,Ge,{value:De}),this.sortMapEntries=typeof i=="function"?i:i===!0?eh:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function Hl(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(``)+`-`}var ut=class t{constructor(e,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,oe,{value:br});let o=null;typeof n=="function"||Array.isArray(n)?o=n:r===void 0&&n&&(r=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=s;let{version:i}=s;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(i=this.directives.yaml.version)):this.directives=new Fe({version:i}),this.setSchema(i,r),this.contents=e===void 0?null:this.createNode(e,o,r)}clone(){let e=Object.create(t.prototype,{[oe]:{value:br}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=L(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Jt(this.contents)&&this.contents.add(e)}addIn(e,n){Jt(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let r=cs(this);e.anchor=!n||r.has(n)?us(n||"a",r):n}return new Je(e.anchor)}createNode(e,n,r){let o;if(typeof n=="function")e=n.call({"":e},"",e),o=n;else if(Array.isArray(n)){let h=S=>typeof S=="number"||S instanceof String||S instanceof Number,b=n.filter(h).map(String);b.length>0&&(n=n.concat(b)),o=n}else r===void 0&&n&&(r=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:i,flow:a,keepUndefined:c,onTagObj:u,tag:p}=r??{},{onAnchor:l,setAnchors:f,sourceObjects:d}=vl(this,i||"a"),y={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:l,onTagObj:u,replacer:o,schema:this.schema,sourceObjects:d},m=qe(e,p,y);return a&&B(m)&&(m.flow=!0),f(),m}createPair(e,n,r={}){let o=this.createNode(e,null,r),s=this.createNode(n,null,r);return new K(o,s)}delete(e){return Jt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Bt(e)?this.contents==null?!1:(this.contents=null,!0):Jt(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return B(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return Bt(e)?!n&&N(this.contents)?this.contents.value:this.contents:B(this.contents)?this.contents.getIn(e,n):void 0}has(e){return B(this.contents)?this.contents.has(e):!1}hasIn(e){return Bt(e)?this.contents!==void 0:B(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=Sn(this.schema,[e],n):Jt(this.contents)&&this.contents.set(e,n)}setIn(e,n){Bt(e)?this.contents=n:this.contents==null?this.contents=Sn(this.schema,Array.from(e),n):Jt(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let r;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Fe({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Fe({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let o=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${o}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(r)this.schema=new Nn(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:r,maxAliasCount:o,onAnchor:s,reviver:i}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof o=="number"?o:100},c=Y(this.contents,n??"",a);if(typeof s=="function")for(let{count:u,res:p}of a.anchors.values())s(p,u);return typeof i=="function"?st(i,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return Jl(this,e)}};function Jt(t){if(B(t))return!0;throw new Error("Expected a YAML collection as document contents")}var Tn=class extends Error{constructor(e,n,r,o){super(),this.name=e,this.code=r,this.message=o,this.pos=n}},Re=class extends Tn{constructor(e,n,r){super("YAMLParseError",e,n,r)}},$n=class extends Tn{constructor(e,n,r){super("YAMLWarning",e,n,r)}},Es=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:r,col:o}=n.linePos[0];n.message+=` at line ${r}, column ${o}`;let s=o-1,i=t.substring(e.lineStarts[r-1],e.lineStarts[r]).replace(/[\n\r]+$/,"");if(s>=60&&i.length>80){let a=Math.min(s-39,i.length-79);i="\u2026"+i.substring(a),s-=a-1}if(i.length>80&&(i=i.substring(0,79)+"\u2026"),r>1&&/^ *$/.test(i.substring(0,s))){let a=t.substring(e.lineStarts[r-2],e.lineStarts[r-1]);a.length>80&&(a=a.substring(0,79)+`\u2026+`}var ut=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}=Cl(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"?st(i,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return Hl(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`),i=a+i}if(/[^ ]/.test(i)){let a=1,c=n.linePos[1];c?.line===r&&c.col>o&&(a=Math.max(1,Math.min(c.col-o,80-s)));let u=" ".repeat(s)+"^".repeat(a);n.message+=`:${i}${u}-`}};function Be(t,{flow:e,indicator:n,next:r,offset:o,onError:s,parentIndent:i,startOnNewline:a}){let c=!1,u=a,p=a,l="",f="",d=!1,y=!1,m=null,h=null,b=null,S=null,A=null,_=null,w=null;for(let x of t)switch(y&&(x.type!=="space"&&x.type!=="newline"&&x.type!=="comma"&&s(x.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),m&&(u&&x.type!=="comment"&&x.type!=="newline"&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),x.type){case"space":!e&&(n!=="doc-start"||r?.type!=="flow-collection")&&x.source.includes(" ")&&(m=x),p=!0;break;case"comment":{p||s(x,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let O=x.source.substring(1)||" ";l?l+=f+O:l=O,f="",u=!1;break}case"newline":u?l?l+=x.source:(!_||n!=="seq-item-ind")&&(c=!0):f+=x.source,u=!0,d=!0,(h||b)&&(S=x),p=!0;break;case"anchor":h&&s(x,"MULTIPLE_ANCHORS","A node can have at most one anchor"),x.source.endsWith(":")&&s(x.offset+x.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),h=x,w??(w=x.offset),u=!1,p=!1,y=!0;break;case"tag":{b&&s(x,"MULTIPLE_TAGS","A node can have at most one tag"),b=x,w??(w=x.offset),u=!1,p=!1,y=!0;break}case n:(h||b)&&s(x,"BAD_PROP_ORDER",`Anchors and tags must be after the ${x.source} indicator`),_&&s(x,"UNEXPECTED_TOKEN",`Unexpected ${x.source} in ${e??"collection"}`),_=x,u=n==="seq-item-ind"||n==="explicit-key-ind",p=!1;break;case"comma":if(e){A&&s(x,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),A=x,u=!1,p=!1;break}default:s(x,"UNEXPECTED_TOKEN",`Unexpected ${x.type} token`),u=!1,p=!1}let E=t[t.length-1],D=E?E.offset+E.source.length:o;return y&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&s(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(u&&m.indent<=i||r?.type==="block-map"||r?.type==="block-seq")&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:A,found:_,spaceBefore:c,comment:l,hasNewline:d,anchor:h,tag:b,newlineAfterProp:S,end:D,start:w??D}}function lt(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`-`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(lt(e.key)||lt(e.value))return!0}return!1;default:return!0}}function zn(t,e,n){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&<(e)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function Gr(t,e,n){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let o=typeof r=="function"?r:(s,i)=>s===i||N(s)&&N(i)&&s.value===i.value;return e.some(s=>o(s.key,n))}var ql="All mapping items must start at the same column";function Kl({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=s?.nodeClass??W,a=new i(n.schema);n.atRoot&&(n.atRoot=!1);let c=r.offset,u=null;for(let p of r.items){let{start:l,key:f,sep:d,value:y}=p,m=Be(l,{indicator:"explicit-key-ind",next:f??d?.[0],offset:c,onError:o,parentIndent:r.indent,startOnNewline:!0}),h=!m.found;if(h){if(f&&(f.type==="block-seq"?o(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&o(c,"BAD_INDENT",ql)),!m.anchor&&!m.tag&&!d){u=m.end,m.comment&&(a.comment?a.comment+=`-`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||lt(f))&&o(f??l[l.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==r.indent&&o(c,"BAD_INDENT",ql);n.atKey=!0;let b=m.end,S=f?t(n,f,m,o):e(n,b,l,null,m,o);n.schema.compat&&zn(r.indent,f,o),n.atKey=!1,Gr(n,a.items,S)&&o(b,"DUPLICATE_KEY","Map keys must be unique");let A=Be(d??[],{indicator:"map-value-ind",next:y,offset:S.range[2],onError:o,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=A.end,A.found){h&&(y?.type==="block-map"&&!A.hasNewline&&o(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&m.start<A.found.offset-1024&&o(S.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let _=y?t(n,y,A,o):e(n,c,d,null,A,o);n.schema.compat&&zn(r.indent,y,o),c=_.range[2];let w=new K(S,_);n.options.keepSourceTokens&&(w.srcToken=p),a.items.push(w)}else{h&&o(S.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),A.comment&&(S.comment?S.comment+=`-`+A.comment:S.comment=A.comment);let _=new K(S);n.options.keepSourceTokens&&(_.srcToken=p),a.items.push(_)}}return u&&u<c&&o(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,c,u??c],a}function Wl({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=s?.nodeClass??ee,a=new i(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=r.offset,u=null;for(let{start:p,value:l}of r.items){let f=Be(p,{indicator:"seq-item-ind",next:l,offset:c,onError:o,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||l)l?.type==="block-seq"?o(f.end,"BAD_INDENT","All sequence items must start at the same column"):o(c,"MISSING_CHAR","Sequence item without - indicator");else{u=f.end,f.comment&&(a.comment=f.comment);continue}let d=l?t(n,l,f,o):e(n,f.end,p,null,f,o);n.schema.compat&&zn(r.indent,l,o),c=d.range[2],a.items.push(d)}return a.range=[r.offset,c,u??c],a}function je(t,e,n,r){let o="";if(t){let s=!1,i="";for(let a of t){let{source:c,type:u}=a;switch(u){case"space":s=!0;break;case"comment":{n&&!s&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let p=c.substring(1)||" ";o?o+=i+p:o=p,i="";break}case"newline":o&&(i+=c),s=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=c.length}}return{comment:o,offset:e}}var vs="Block collections are not allowed within flow collections",Ds=t=>t&&(t.type==="block-map"||t.type==="block-seq");function Yl({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=r.start.source==="{",a=i?"flow map":"flow sequence",c=s?.nodeClass??(i?W:ee),u=new c(n.schema);u.flow=!0;let p=n.atRoot;p&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let l=r.offset+r.start.source.length;for(let h=0;h<r.items.length;++h){let b=r.items[h],{start:S,key:A,sep:_,value:w}=b,E=Be(S,{flow:a,indicator:"explicit-key-ind",next:A??_?.[0],offset:l,onError:o,parentIndent:r.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!_&&!w){h===0&&E.comma?o(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):h<r.items.length-1&&o(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),E.comment&&(u.comment?u.comment+=`-`+E.comment:u.comment=E.comment),l=E.end;continue}!i&&n.options.strict&<(A)&&o(A,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(h===0)E.comma&&o(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(E.comma||o(E.start,"MISSING_CHAR",`Missing , between ${a} items`),E.comment){let D="";e:for(let x of S)switch(x.type){case"comma":case"space":break;case"comment":D=x.source.substring(1);break e;default:break e}if(D){let x=u.items[u.items.length-1];T(x)&&(x=x.value??x.key),x.comment?x.comment+=`-`+D:x.comment=D,E.comment=E.comment.substring(D.length+1)}}if(!i&&!_&&!E.found){let D=w?t(n,w,E,o):e(n,E.end,_,null,E,o);u.items.push(D),l=D.range[2],Ds(w)&&o(D.range,"BLOCK_IN_FLOW",vs)}else{n.atKey=!0;let D=E.end,x=A?t(n,A,E,o):e(n,D,S,null,E,o);Ds(A)&&o(x.range,"BLOCK_IN_FLOW",vs),n.atKey=!1;let O=Be(_??[],{flow:a,indicator:"map-value-ind",next:w,offset:x.range[2],onError:o,parentIndent:r.indent,startOnNewline:!1});if(O.found){if(!i&&!E.found&&n.options.strict){if(_)for(let z of _){if(z===O.found)break;if(z.type==="newline"){o(z,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<O.found.offset-1024&&o(O.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else w&&("source"in w&&w.source?.[0]===":"?o(w,"MISSING_CHAR",`Missing space after : in ${a}`):o(O.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let $=w?t(n,w,O,o):O.found?e(n,O.end,_,null,O,o):null;$?Ds(w)&&o($.range,"BLOCK_IN_FLOW",vs):O.comment&&(x.comment?x.comment+=`-`+O.comment:x.comment=O.comment);let G=new K(x,$);if(n.options.keepSourceTokens&&(G.srcToken=b),i){let z=u;Gr(n,z.items,x)&&o(D,"DUPLICATE_KEY","Map keys must be unique"),z.items.push(G)}else{let z=new W(n.schema);z.flow=!0,z.items.push(G);let yt=($??x).range;z.range=[x.range[0],yt[1],yt[2]],u.items.push(z)}l=$?$.range[2]:O.end}}let f=i?"}":"]",[d,...y]=r.end,m=l;if(d?.source===f)m=d.offset+d.source.length;else{let h=a[0].toUpperCase()+a.substring(1),b=p?`${h} must end with a ${f}`:`${h} in block collection must be sufficiently indented and end with a ${f}`;o(l,p?"MISSING_CHAR":"BAD_INDENT",b),d&&d.source.length!==1&&y.unshift(d)}if(y.length>0){let h=je(y,m,n.options.strict,o);h.comment&&(u.comment?u.comment+=`-`+h.comment:u.comment=h.comment),u.range=[r.offset,m,h.offset]}else u.range=[r.offset,m,m];return u}function Rs(t,e,n,r,o,s){let i=n.type==="block-map"?Kl(t,e,n,r,s):n.type==="block-seq"?Wl(t,e,n,r,s):Yl(t,e,n,r,s),a=i.constructor;return o==="!"||o===a.tagName?(i.tag=a.tagName,i):(o&&(i.tag=o),i)}function Hl(t,e,n,r,o){let s=r.tag,i=s?e.directives.tagName(s.source,f=>o(s,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:d}=r,y=f&&s?f.offset>s.offset?f:s:f??s;y&&(!d||d.offset<y.offset)&&o(y,"MISSING_CHAR","Missing newline after block sequence props")}let a=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!s||!i||i==="!"||i===W.tagName&&a==="map"||i===ee.tagName&&a==="seq")return Rs(t,e,n,o,i);let c=e.schema.tags.find(f=>f.tag===i&&f.collection===a);if(!c){let f=e.schema.knownTags[i];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?o(s,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):o(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,!0),Rs(t,e,n,o,i)}let u=Rs(t,e,n,o,i,c),p=c.resolve?.(u,f=>o(s,"TAG_RESOLVE_FAILED",f),e.options)??u,l=L(p)?p:new R(p);return l.range=u.range,l.tag=i,c?.format&&(l.format=c.format),l}function ks(t,e,n){let r=e.offset,o=Gm(e,t.options.strict,n);if(!o)return{value:"",type:null,comment:"",range:[r,r,r]};let s=o.mode===">"?R.BLOCK_FOLDED:R.BLOCK_LITERAL,i=e.source?Jm(e.source):[],a=i.length;for(let m=i.length-1;m>=0;--m){let h=i[m][1];if(h===""||h==="\r")a=m;else break}if(a===0){let m=o.chomp==="+"&&i.length>0?`-`.repeat(Math.max(1,i.length-1)):"",h=r+o.length;return e.source&&(h+=e.source.length),{value:m,type:s,comment:o.comment,range:[r,h,h]}}let c=e.indent+o.indent,u=e.offset+o.length,p=0;for(let m=0;m<a;++m){let[h,b]=i[m];if(b===""||b==="\r")o.indent===0&&h.length>c&&(c=h.length);else{h.length<c&&n(u+h.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),o.indent===0&&(c=h.length),p=m,c===0&&!t.atRoot&&n(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=h.length+b.length+1}for(let m=i.length-1;m>=a;--m)i[m][0].length>c&&(a=m+1);let l="",f="",d=!1;for(let m=0;m<p;++m)l+=i[m][0].slice(c)+`-`;for(let m=p;m<a;++m){let[h,b]=i[m];u+=h.length+b.length+1;let S=b[b.length-1]==="\r";if(S&&(b=b.slice(0,-1)),b&&h.length<c){let _=`Block scalar lines must not be less indented than their ${o.indent?"explicit indentation indicator":"first line"}`;n(u-b.length-(S?2:1),"BAD_INDENT",_),h=""}s===R.BLOCK_LITERAL?(l+=f+h.slice(c)+b,f=`-`):h.length>c||b[0]===" "?(f===" "?f=`-`:!d&&f===`+`}};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 lt(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`+`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(lt(e.key)||lt(e.value))return!0}return!1;default:return!0}}function Ln(t,e,n){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&<(e)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function 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 ef="All mapping items must start at the same column";function tf({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",ef)),!m.anchor&&!m.tag&&!p){u=m.end,m.comment&&(a.comment?a.comment+=`+`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||lt(f))&&o(f??l[l.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==r.indent&&o(c,"BAD_INDENT",ef);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 nf({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 rf({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&<(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 yt=(P??E).range;L.range=[E.range[0],yt[1],yt[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"?tf(t,e,n,r,s):n.type==="block-seq"?nf(t,e,n,r,s):rf(t,e,n,r,s),a=i.constructor;return o==="!"||o===a.tagName?(i.tag=a.tagName,i):(o&&(i.tag=o),i)}function of(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=th(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?nh(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=`+`:!p&&f===``&&(f=`-`),l+=f+h.slice(c)+b,f=`-`,d=!0):b===""?f===`+`),l+=f+h.slice(c)+g,f=`+`,p=!0):g===""?f===``?l+=``:f=`-`:(l+=f+b,f=" ",d=!1)}switch(o.chomp){case"-":break;case"+":for(let m=a;m<i.length;++m)l+=`+`:(l+=f+g,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 Gm({offset:t,props:e},n,r){if(e[0].type!=="block-scalar-header")return r(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:o}=e[0],s=o[0],i=0,a="",c=-1;for(let f=1;f<o.length;++f){let d=o[f];if(!a&&(d==="-"||d==="+"))a=d;else{let y=Number(d);!i&&y?i=y:c===-1&&(c=t+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${o}`);let u=!1,p="",l=o.length;for(let f=1;f<e.length;++f){let d=e[f];switch(d.type){case"space":u=!0;case"newline":l+=d.source.length;break;case"comment":n&&!u&&r(d,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),l+=d.source.length,p=d.source.substring(1);break;case"error":r(d,"UNEXPECTED_TOKEN",d.message),l+=d.source.length;break;default:{let y=`Unexpected token in block scalar header: ${d.type}`;r(d,"UNEXPECTED_TOKEN",y);let m=d.source;m&&typeof m=="string"&&(l+=m.length)}}}return{mode:s,indent:i,chomp:a,comment:p,length:l}}function Jm(t){let e=t.split(/\n( *)/),n=e[0],r=n.match(/^( *)/),s=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let i=1;i<e.length;i+=2)s.push([e[i],e[i+1]]);return s}function Is(t,e,n){let{offset:r,type:o,source:s,end:i}=t,a,c,u=(f,d,y)=>n(r+f,d,y);switch(o){case"scalar":a=R.PLAIN,c=qm(s,u);break;case"single-quoted-scalar":a=R.QUOTE_SINGLE,c=Km(s,u);break;case"double-quoted-scalar":a=R.QUOTE_DOUBLE,c=Wm(s,u);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${o}`),{value:"",type:null,comment:"",range:[r,r+s.length,r+s.length]}}let p=r+s.length,l=je(i,p,e,n);return{value:c,type:a,comment:l.comment,range:[r,p,l.offset]}}function qm(t,e){let n="";switch(t[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),Xl(t)}function Km(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),Xl(t.slice(1,-1)).replace(/''/g,"'")}function Xl(t){let e,n;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?+`}let y=r+o.length+e.source.length;return{value:l,type:s,comment:o.comment,range:[r,y,y]}}function th({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 nh(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=rh(s,u);break;case"single-quoted-scalar":a=R.QUOTE_SINGLE,c=oh(s,u);break;case"double-quoted-scalar":a=R.QUOTE_DOUBLE,c=sh(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 rh(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}`),sf(t)}function oh(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),sf(t.slice(1,-1)).replace(/''/g,"'")}function sf(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 Wm(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 sh(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}=Ym(t,r);n+=s,r=i}else if(o==="\\"){let s=t[++r],i=Hm[s];if(i)n+=i;else if(s===`+`){let{fold:s,offset:i}=ih(t,r);n+=s,r=i}else if(o==="\\"){let s=t[++r],i=ah[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+=Xm(t,r+1,a,e),r+=a}else{let a=t.substr(r-1,2);e(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),n+=a}}else if(o===" "||o===" "){let s=r,i=t[r+1];for(;i===" "||i===" ";)i=t[++r+1];i!==`+`)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+=ch(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 Ym(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 ih(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 Hm={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`-`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Xm(t,e,n,r){let o=t.substr(e,n),i=o.length===n&&/^[0-9a-fA-F]+$/.test(o)?parseInt(o,16):NaN;try{return String.fromCodePoint(i)}catch{let a=t.substr(e-2,n+2);return r(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}function Os(t,e,n,r){let{value:o,type:s,comment:i,range:a}=e.type==="block-scalar"?ks(t,e,r):Is(e,t.options.strict,r),c=n?t.directives.tagName(n.source,l=>r(n,"TAG_RESOLVE_FAILED",l)):null,u;t.options.stringKeys&&t.atKey?u=t.schema[pe]:c?u=eh(t.schema,o,c,n,r):e.type==="scalar"?u=th(t,o,e,r):u=t.schema[pe];let p;try{let l=u.resolve(o,f=>r(n??e,"TAG_RESOLVE_FAILED",f),t.options);p=N(l)?l:new R(l)}catch(l){let f=l instanceof Error?l.message:String(l);r(n??e,"TAG_RESOLVE_FAILED",f),p=new R(o)}return p.range=a,p.source=o,s&&(p.type=s),c&&(p.tag=c),u.format&&(p.format=u.format),i&&(p.comment=i),p}function eh(t,e,n,r,o){if(n==="!")return t[pe];let s=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let i=t.knownTags[n];return i&&!i.collection?(t.tags.push(Object.assign({},i,{default:!1,test:void 0})),i):(o(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),t[pe])}function th({atKey:t,directives:e,schema:n},r,o,s){let i=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(r))||n[pe];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(r))??n[pe];if(i.tag!==a.tag){let c=e.tagString(i.tag),u=e.tagString(a.tag),p=`Value may be parsed as either ${c} or ${u}`;s(o,"TAG_RESOLVE_FAILED",p,!0)}}return i}function ef(t,e,n){if(e){n??(n=e.length);for(let r=n-1;r>=0;--r){let o=e[r];switch(o.type){case"space":case"comment":case"newline":t-=o.source.length;continue}for(o=e[++r];o?.type==="space";)t+=o.source.length,o=e[++r];break}}return t}var nh={composeNode:Cs,composeEmptyNode:Jr};function Cs(t,e,n,r){let o=t.atKey,{spaceBefore:s,comment:i,anchor:a,tag:c}=n,u,p=!0;switch(e.type){case"alias":u=rh(t,e,r),(a||c)&&r(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":u=Os(t,e,c,r),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{u=Hl(nh,t,e,n,r),a&&(u.anchor=a.source.substring(1))}catch(l){let f=l instanceof Error?l.message:String(l);r(e,"RESOURCE_EXHAUSTION",f)}break;default:{let l=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",l),p=!1}}return u??(u=Jr(t,e.offset,void 0,null,n,r)),a&&u.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),o&&t.options.stringKeys&&(!N(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&r(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(u.spaceBefore=!0),i&&(e.type==="scalar"&&e.source===""?u.comment=i:u.commentBefore=i),t.options.keepSourceTokens&&p&&(u.srcToken=e),u}function Jr(t,e,n,r,{spaceBefore:o,comment:s,anchor:i,tag:a,end:c},u){let p={type:"scalar",offset:ef(e,n,r),indent:-1,source:""},l=Os(t,p,a,u);return i&&(l.anchor=i.source.substring(1),l.anchor===""&&u(i,"BAD_ALIAS","Anchor cannot be an empty string")),o&&(l.spaceBefore=!0),s&&(l.comment=s,l.range[2]=c),l}function rh({options:t},{offset:e,source:n,end:r},o){let s=new Je(n.substring(1));s.source===""&&o(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&o(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let i=e+n.length,a=je(r,i,t.strict,o);return s.range=[e,i,a.offset],a.comment&&(s.comment=a.comment),s}function tf(t,e,{offset:n,start:r,value:o,end:s},i){let a=Object.assign({_directives:e},t),c=new ut(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},p=Be(r,{indicator:"doc-start",next:o??s?.[0],offset:n,onError:i,parentIndent:0,startOnNewline:!0});p.found&&(c.directives.docStart=!0,o&&(o.type==="block-map"||o.type==="block-seq")&&!p.hasNewline&&i(p.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=o?Cs(u,o,p,i):Jr(u,p.end,r,null,p,i);let l=c.contents.range[2],f=je(s,l,!1,i);return f.comment&&(c.comment=f.comment),c.range=[n,l,f.offset],c}function Pn(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function nf(t){let e="",n=!1,r=!1;for(let o=0;o<t.length;++o){let s=t[o];switch(s[0]){case"#":e+=(e===""?"":r?`+`),e+=1,r=t[e+1];return n||(n=" "),{fold:n,offset:e}}var ah={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`+`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function ch(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=uh(t.schema,o,c,n,r):e.type==="scalar"?u=lh(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 uh(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 lh({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 af(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 fh={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=dh(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=of(fh,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:af(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 dh({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 cf(t,e,{offset:n,start:r,value:o,end:s},i){let a=Object.assign({_directives:e},t),c=new ut(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=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 uf(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 Ln=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,o,s)=>{let i=Pn(n);s?this.warnings.push(new $n(i,r,o)):this.errors.push(new Re(i,r,o))},this.directives=new Fe({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:r,afterEmptyLine:o}=nf(this.prelude);if(r){let s=e.contents;if(n)e.comment=e.comment?`${e.comment}-${r}`:r;else if(o||e.directives.docStart||!s)e.commentBefore=r;else if(B(s)&&!s.flow&&s.items.length>0){let i=s.items[0];T(i)&&(i=i.key);let a=i.commentBefore;i.commentBefore=a?`${r}+`)+(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}=uf(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:nf(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,n=!1,r=-1){for(let o of e)yield*this.next(o);yield*this.end(n,r)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(n,r,o)=>{let s=Pn(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",r,o)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=tf(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,r=new Re(Pn(e),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new Re(Pn(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=je(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let r=this.doc.comment;this.doc.comment=r?`${r}-${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new Re(Pn(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),o=new ut(void 0,r);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),o.range=[0,n,n],this.decorate(o,!1),yield o}}};var Ns=Symbol("break visit"),oh=Symbol("skip children"),rf=Symbol("remove item");function St(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),of(Object.freeze([]),t,e)}St.BREAK=Ns;St.SKIP=oh;St.REMOVE=rf;St.itemAtPath=(t,e)=>{let n=t;for(let[r,o]of e){let s=n?.[r];if(s&&"items"in s)n=s.items[o];else return}return n};St.parentCollection=(t,e)=>{let n=St.itemAtPath(t,e.slice(0,-1)),r=e[e.length-1][0],o=n?.[r];if(o&&"items"in o)return o;throw new Error("Parent collection not found")};function of(t,e,n){let r=n(e,t);if(typeof r=="symbol")return r;for(let o of["key","value"]){let s=e[o];if(s&&"items"in s){for(let i=0;i<s.items.length;++i){let a=of(Object.freeze(t.concat([[o,i]])),s.items[i],n);if(typeof a=="number")i=a-1;else{if(a===Ns)return Ns;a===rf&&(s.items.splice(i,1),i-=1)}}typeof r=="function"&&o==="key"&&(r=r(e,t))}}return typeof r=="function"?r(e,t):r}var Ts="\uFEFF",$s="",zs="",qr="";function sf(t){switch(t){case Ts:return"byte-order-mark";case $s:return"doc-mode";case zs:return"flow-error-end";case qr:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`+${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:uf(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=cf(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 ut(void 0,r);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),o.range=[0,n,n],this.decorate(o,!1),yield o}}};var Ts=Symbol("break visit"),ph=Symbol("skip children"),lf=Symbol("remove item");function Et(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),ff(Object.freeze([]),t,e)}Et.BREAK=Ts;Et.SKIP=ph;Et.REMOVE=lf;Et.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};Et.parentCollection=(t,e)=>{let n=Et.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 ff(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=ff(Object.freeze(t.concat([[o,i]])),s.items[i],n);if(typeof a=="number")i=a-1;else{if(a===Ts)return Ts;a===lf&&(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 df(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``: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 af=new Set("0123456789ABCDEFabcdef"),ih=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Kr=new Set(",[]{}"),ah=new Set(` ,[]{}-\r `),Ps=t=>!t||ah.has(t),Mn=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===`+`:case"\r":case" ":return!0;default:return!1}}var pf=new Set("0123456789ABCDEFabcdef"),hh=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Wr=new Set(",[]{}"),yh=new Set(` ,[]{}+\r `),Ps=t=>!t||yh.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===``?!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]===Ts&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let n=e.length,r=e.indexOf("#");for(;r!==-1;){let s=e[r-1];if(s===" "||s===" "){n=r-1;break}else r=e.indexOf("#",r+1)}for(;;){let s=e[n-1];if(s===" "||s===" ")n-=1;else break}let o=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-o),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-n),yield*this.pushNewline(),"stream"}return yield $s,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let n=this.peek(3);if((n==="---"||n==="...")&&ke(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,n==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!ke(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&ke(n)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(e[n]){case"#":yield*this.pushCount(e.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Ps),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,n,r=-1;do e=yield*this.pushNewline(),e>0?(n=yield*this.pushSpaces(!1),this.indentValue=r=n):n=0,n+=yield*this.pushSpaces(!0);while(e+n>0);let o=this.getLine();if(o===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&o[0]!=="#"||r===0&&(o.startsWith("---")||o.startsWith("..."))&&ke(o[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(o[0]==="]"||o[0]==="}")))return this.flowLevel=0,yield zs,yield*this.parseLineStart();let s=0;for(;o[s]===",";)s+=yield*this.pushCount(1),s+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(s+=yield*this.pushIndicators(),o[s]){case void 0:return"flow";case"#":return yield*this.pushCount(o.length-s),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Ps),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let i=this.charAt(1);if(this.flowKey||ke(i)||i===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),n=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;n!==-1&&this.buffer[n+1]==="'";)n=this.buffer.indexOf("'",n+2);else for(;n!==-1;){let s=0;for(;this.buffer[n-1-s]==="\\";)s+=1;if(s%2===0)break;n=this.buffer.indexOf('"',n+1)}let r=this.buffer.substring(0,n),o=r.indexOf(`+`,this.pos),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(``,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``: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 qr,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,n=this.pos-1,r=this.pos-1,o;for(;o=this.buffer[++r];)if(o===":"){let s=this.buffer[r+1];if(ke(s)||e&&Kr.has(s))break;n=r}else if(ke(o)){let s=this.buffer[r+1];if(o==="\r"&&(s===`+`&&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===``?(r+=1,o=`-`,s=this.buffer[r+1]):n=r),s==="#"||e&&Kr.has(s))break;if(o===`-`){let i=this.continueScalar(r+1);if(i===-1)break;r=Math.max(r,i-2)}}else{if(e&&Kr.has(o))break;n=r}return!o&&!this.atEnd?this.setNext("plain-scalar"):(yield qr,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let r=this.buffer.slice(this.pos,e);return r?(yield r,this.pos+=r.length,r.length):(n&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Ps),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(ke(r)||n&&Kr.has(r)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!ke(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(ih.has(n))n=this.buffer[++e];else if(n==="%"&&af.has(this.buffer[e+1])&&af.has(this.buffer[e+2]))n=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`+`,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(hh.has(n))n=this.buffer[++e];else if(n==="%"&&pf.has(this.buffer[e+1])&&pf.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 Fn=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,r=this.lineStarts.length;for(;n<r;){let s=n+r>>1;this.lineStarts[s]<e?n=s+1:r=s}if(this.lineStarts[n]===e)return{line:n+1,col:1};if(n===0)return{line:0,col:e};let o=this.lineStarts[n-1];return{line:n,col:e-o+1}}}};function ft(t,e){for(let n=0;n<t.length;++n)if(t[n].type===e)return!0;return!1}function cf(t){for(let e=0;e<t.length;++e)switch(t[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function lf(t){switch(t?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Wr(t){switch(t.type){case"document":return t.start;case"block-map":{let e=t.items[t.items.length-1];return e.sep??e.start}case"block-seq":return t.items[t.items.length-1].start;default:return[]}}function qt(t){if(t.length===0)return[];let e=t.length;e:for(;--e>=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function Yr(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let n=0;n<e.length;++n)t.push(e[n])}function uf(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!ft(e.start,"explicit-key-ind")&&!ft(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,lf(e.value)?e.value.end?Yr(e.value.end,e.sep):e.value.end=e.sep:Yr(e.start,e.sep),delete e.sep)}var Zn=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Mn,this.onNewLine=e}*parse(e,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(e,n))yield*this.next(r);n||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let n=sf(e);if(n)if(n==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=n,yield*this.step(),n){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let r=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let n=e??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let r=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in r?r.indent:0:n.type==="flow-collection"&&r.type==="document"&&(n.indent=0),n.type==="flow-collection"&&uf(n),r.type){case"document":r.value=n;break;case"block-scalar":r.props.push(n);break;case"block-map":{let o=r.items[r.items.length-1];if(o.value){r.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(o.sep)o.value=n;else{Object.assign(o,{key:n,sep:[]}),this.onKeyLine=!o.explicitKey;return}break}case"block-seq":{let o=r.items[r.items.length-1];o.value?r.items.push({start:[],value:n}):o.value=n;break}case"flow-collection":{let o=r.items[r.items.length-1];!o||o.value?r.items.push({start:[],key:n,sep:[]}):o.sep?o.value=n:Object.assign(o,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let o=n.items[n.items.length-1];o&&!o.sep&&!o.value&&o.start.length>0&&cf(o.start)===-1&&(n.indent===0||o.start.every(s=>s.type!=="comment"||s.indent<n.indent))&&(r.type==="document"?r.end=o.start:r.items.push({start:o.start}),n.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{cf(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let n=Wr(this.peek(2)),r=qt(n),o;e.end?(o=e.end,o.push(this.sourceToken),delete e.end):o=[this.sourceToken];let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let n=this.source.indexOf(`+`?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 St=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,r=this.lineStarts.length;for(;n<r;){let s=n+r>>1;this.lineStarts[s]<e?n=s+1:r=s}if(this.lineStarts[n]===e)return{line:n+1,col:1};if(n===0)return{line:0,col:e};let o=this.lineStarts[n-1];return{line:n,col:e-o+1}}}};function ft(t,e){for(let n=0;n<t.length;++n)if(t[n].type===e)return!0;return!1}function mf(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 yf(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 hf(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!ft(e.start,"explicit-key-ind")&&!ft(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,yf(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=df(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"&&hf(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&&mf(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":{mf(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(``)+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)){Yr(o,n.start),o.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,o=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(o&&n.sep&&!n.value){let i=[];for(let a=0;a<n.sep.length;++a){let c=n.sep[a];switch(c.type){case"newline":i.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(i.length=0);break;default:i.length=0}}i.length>=2&&(s=n.sep.splice(i[1]))}switch(this.type){case"anchor":case"tag":o||n.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):o||n.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(ft(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(lf(n.key)&&!ft(n.sep,"newline")){let i=qt(n.start),a=n.key,c=n.sep;c.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:a,sep:c}]})}else s.length>0?n.sep=n.sep.concat(s,this.sourceToken):n.sep.push(this.sourceToken);else if(ft(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let i=qt(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||o?e.items.push({start:s,key:null,sep:[this.sourceToken]}):ft(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);o||n.value?(e.items.push({start:s,key:i,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(i):(Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!0);return}default:{let i=this.startBlockValue(e);if(i){if(i.type==="block-seq"){if(!n.explicitKey&&n.sep&&!ft(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&e.items.push({start:s});this.stack.push(i);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){Yr(o,n.start),o.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=e.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;n.value||ft(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?e.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);!n||n.value?e.items.push({start:[],key:o,sep:[]}):n.sep?this.stack.push(o):Object.assign(n,{key:o,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let o=Wr(r),s=qt(o);uf(e);let i=e.end.splice(1,e.end.length);i.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let n=this.source.indexOf(`+`,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(ft(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(yf(n.key)&&!ft(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(ft(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]}):ft(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);o||n.value?(e.items.push({start:s,key:i,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(i):(Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!0);return}default:{let i=this.startBlockValue(e);if(i){if(i.type==="block-seq"){if(!n.explicitKey&&n.sep&&!ft(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&e.items.push({start:s});this.stack.push(i);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){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||ft(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?e.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);!n||n.value?e.items.push({start:[],key:o,sep:[]}):n.sep?this.stack.push(o):Object.assign(n,{key:o,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let o=Yr(r),s=Kt(o);hf(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=Wr(e),r=qt(n);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Wr(e),r=qt(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};function ch(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Fn||null,prettyErrors:e}}function Ls(t,e={}){let{lineCounter:n,prettyErrors:r}=ch(e),o=new Zn(n?.addNewLine),s=new Ln(e),i=null;for(let a of s.compose(o.parse(t),!0,t.length))if(!i)i=a;else if(i.options.logLevel!=="silent"){i.errors.push(new Re(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(i.errors.forEach(Es(t,n)),i.warnings.forEach(Es(t,n))),i}var Ie=class extends Error{code;constructor(e){super(`Structured data failed validation: ${e}`),this.name="StructuredDataError",this.code=e}},fh=t=>Ne(JSON.stringify(t)),ff=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},df=(t,e)=>{if(ff(t)===!1)throw new Ie("INVALID");let n=0,r=(s,i)=>{if(i>e.depth)throw new Ie("DEPTH_EXCEEDED");if(typeof s=="string"){if(Ne(s)>e.stringBytes)throw new Ie("STRING_BYTES_EXCEEDED");return s}if(s===null||typeof s=="boolean"||typeof s=="number"&&Number.isFinite(s)&&(Number.isInteger(s)===!1||Number.isSafeInteger(s)))return s;if(Array.isArray(s))return s.map(a=>{if(n+=1,n>e.fields)throw new Ie("FIELDS_EXCEEDED");return r(a,i+1)});if(ff(s)){let a=Object.create(null);for(let[c,u]of Object.entries(s)){if(n+=1,n>e.fields)throw new Ie("FIELDS_EXCEEDED");a[c]=r(u,i+1)}return a}throw new Ie("INVALID")},o=r(t,1);if(fh(o)>e.serializedBytes)throw new Ie("SERIALIZED_BYTES_EXCEEDED");return o};var H=class extends Error{code;constructor(e,n){super(n),this.name="MarkdownMetadataError",this.code=e}};var Kt=new Uint8Array([239,187,191]),pf=Kt.byteLength+10,dh=(t,e,n=0)=>t.byteLength-n<e.byteLength?!1:e.every((r,o)=>t[n+o]===r),Bn=(t,e)=>{let n=0;if(dh(t,Kt))n=Kt.byteLength;else if(t.byteLength<Kt.byteLength&&Kt.slice(0,t.byteLength).every((s,i)=>s===t[i]))return e?null:void 0;if(t.byteLength<n+4)return e?null:void 0;if(t[n]!==45||t[n+1]!==45||t[n+2]!==45)return null;let r=n+3;if(t[r]===10)r+=1;else if(t[r]===13){if(t.byteLength===r+1)return e?null:void 0;if(t[r+1]!==10)return null;r+=2}else return null;let o=r;for(let s=r;s<=t.byteLength;s+=1){let i=s===t.byteLength;if(i===!1&&t[s]!==10)continue;if(i&&e===!1)return;let a=s;if(a>o&&t[a-1]===13&&(a-=1),a-o===3&&(t[o]===45&&t[o+1]===45&&t[o+2]===45||t[o]===46&&t[o+1]===46&&t[o+2]===46))return{yamlStart:r,yamlEnd:o,blockEnd:i?s:s+1};o=s+1}};var ph={bytes:k.frontmatterBytes,depth:k.frontmatterDepth,fields:k.frontmatterFields,stringBytes:k.frontmatterStringBytes,serializedBytes:k.indexedPropertiesBytes},mf=t=>{try{return le(t)}catch{throw new H("FRONTMATTER_DECODING_FAILED","Markdown frontmatter is not valid UTF-8")}},hf=(t,e)=>{let n=Ls(t,{schema:"core",uniqueKeys:!0});if(n.errors.length>0)throw new H("FRONTMATTER_INVALID","Markdown frontmatter contains invalid YAML");let r;try{r=n.toJS({maxAliasCount:0})}catch{throw new H("FRONTMATTER_INVALID","Markdown frontmatter contains unsupported YAML aliases")}if(r===null)return{};try{return df(r,e)}catch(o){throw o instanceof Ie?o.code==="DEPTH_EXCEEDED"?new H("FRONTMATTER_DEPTH_EXCEEDED","Markdown frontmatter exceeds the nesting limit"):o.code==="FIELDS_EXCEEDED"?new H("FRONTMATTER_FIELDS_EXCEEDED","Markdown frontmatter exceeds the field limit"):o.code==="STRING_BYTES_EXCEEDED"?new H("FRONTMATTER_STRING_BYTES_EXCEEDED","Markdown frontmatter contains a string that exceeds the byte limit"):o.code==="SERIALIZED_BYTES_EXCEEDED"?new H("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter properties exceed the indexed byte limit"):new H("FRONTMATTER_INVALID","Markdown frontmatter must contain a JSON-compatible object"):o}},yf=async(t,e={})=>{let n={...ph,...e},r=n.bytes+pf,o=new Uint8Array(r),s=0;for await(let c of $t(t)){let u=0;for(;u<c.byteLength;){let p=r-s;if(p<=0)break;let l=Math.max(0,6-s),f=Math.min(c.byteLength-u,l);if(l===0){let m=c.subarray(u,Math.min(c.byteLength,u+p)),h=m.indexOf(10);f=h===-1?m.byteLength:h+1}o.set(c.subarray(u,u+f),s),s+=f,u+=f;let d=o.subarray(0,s),y=Bn(d,!1);if(y===null)return{properties:{},frontmatterBytes:0,consumedBytes:d.length};if(y!==void 0){let m=y.yamlEnd-y.yamlStart;if(m>n.bytes)throw new H("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter exceeds the byte limit");let h=mf(d.subarray(y.yamlStart,y.yamlEnd));return{properties:hf(h,n),frontmatterBytes:m,consumedBytes:y.blockEnd}}}if(s>=r)break}let i=o.subarray(0,s),a=Bn(i,!0);if(a===null)return{properties:{},frontmatterBytes:0,consumedBytes:i.length};if(a!==void 0){let c=a.yamlEnd-a.yamlStart;if(c<=n.bytes){let u=mf(i.subarray(a.yamlStart,a.yamlEnd));return{properties:hf(u,n),frontmatterBytes:c,consumedBytes:a.blockEnd}}}throw new H("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter is not closed within the byte limit")};var Hr=async(t,e=k.hydratedFileBytes)=>{if(Number.isInteger(e)===!1||e<=0||e>k.hydratedFileBytes)throw new H("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown body byte limit is outside the supported range");let n;try{n=await Te(t,e)}catch(a){throw a instanceof re?new H("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown content exceeds the byte limit"):a}let r;try{r=le(n)}catch{throw new H("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}let s=Bn(n,!0)?.blockEnd??0,i;try{i=s===0?zt(r):le(n.subarray(s))}catch{throw new H("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}return{body:i,bodyBytes:Ne(i),sourceBytes:n.byteLength}};var dt=class extends Error{code;referenceId;constructor({code:e,message:n,referenceId:r,cause:o}){super(n,{cause:o}),this.name="MarkdownDocumentError",this.code=e,this.referenceId=r}},mh=C({source:v(),body:v(),frontmatter:we(v(),nt())}),eo=t=>{let e;try{e=mh.parse(t)}catch(n){throw new dt({code:"INVALID_DOCUMENT",message:"Markdown document is invalid",cause:n})}return Object.freeze({source:e.source,body:e.body,frontmatter:rt(e.frontmatter)})},Xr="#frontmatter",hh=t=>`${Xr}${t.slice(1)}`,yh=t=>{if(t!==Xr&&t.startsWith(`${Xr}/`)===!1)throw new dt({code:"UNUSED_REFERENCE",message:`Resolved Markdown reference ${t} is outside frontmatter`,referenceId:t});return`#${t.slice(Xr.length)}`},gh=t=>{let e=t.referenceId===void 0?void 0:hh(t.referenceId),n="INVALID_DOCUMENT";throw(t.code==="INVALID_REFERENCE_MARKER"||t.code==="INVALID_REFERENCE"||t.code==="REFERENCE_NOT_FOUND"||t.code==="INVALID_RESOLVED_VALUE"||t.code==="UNUSED_REFERENCE")&&(n=t.code),new dt({code:n,message:t.message,referenceId:e,cause:t})},gf=async({source:t,maximumBytes:e=k.hydratedFileBytes})=>{let n;try{n=await Te(t,e)}catch(i){throw i instanceof re?new dt({code:"CONTENT_LIMIT_EXCEEDED",message:"Markdown document exceeds the byte limit",cause:i}):i}let r;try{r=zt(le(n))}catch(i){throw new dt({code:"CONTENT_DECODING_FAILED",message:"Markdown document is not valid UTF-8",cause:i})}let[o,s]=await Promise.all([Hr(n,e),yf(n)]);return eo({source:r,body:o.body,frontmatter:s.properties})};var bf=({document:t,references:e,allowUnresolvedReferences:n=!1})=>{let r=eo(t),o=new Map;for(let[i,a]of e)o.set(yh(i),a);let s;try{s=yr({document:r.frontmatter,references:o,allowUnresolvedReferences:n})}catch(i){throw i instanceof de&&gh(i),i}return eo({...r,frontmatter:s})},wf=({document:t,representation:e})=>{let n=eo(t);if(e.type==="document")return n.source;if(e.type==="markdown-body")return n.body;if(e.type==="markdown-frontmatter")return n.frontmatter;throw new dt({code:"UNSUPPORTED_REPRESENTATION",message:`Markdown documents do not support ${e.type}`})};var _f=t=>Object.fromEntries(Object.entries(t??{}).map(([e,n])=>[e,n.url]));var to=(t,e)=>{if(e===void 0||e.length===0)return t;let n=new URL("https://content.webstudio.invalid/__assets__/"),r=new URL(t,n),o=new URL(e,n);for(let[a,c]of o.searchParams)r.searchParams.append(a,c);if(o.hash!==""&&(r.hash=o.hash),t.startsWith("//"))return`//${r.host}${r.pathname}${r.search}${r.hash}`;if(t.startsWith("/"))return`${r.pathname}${r.search}${r.hash}`;let s=!1;try{new URL(t),s=!0}catch{}return s?r.href:`${r.pathname.startsWith(n.pathname)?r.pathname.slice(n.pathname.length):r.pathname}${r.search}${r.hash}`},Ms=({value:t,path:e,replacement:n})=>{let[r,...o]=e;if(r===void 0)return n;if(typeof t!="object"||t===null||Object.hasOwn(t,r)===!1)return t;if(Array.isArray(t)){if(typeof r!="number")return t;let s=[...t];return s[r]=Ms({value:t[r],path:o,replacement:n}),s}return typeof r!="string"?t:{...t,[r]:Ms({value:t[r],path:o,replacement:n})}},bh=({reference:t,runtimeAsset:e})=>{let{url:n,contentRef:r,...o}=e;return{...o,id:t.assetId,src:to(n,t.suffix)}},pt=({value:t,references:e,runtimeAssets:n={},assetUrls:r})=>{let o=t;for(let s of e??[]){let i=r?.[s.assetId],a=n[s.assetId]??(i===void 0?void 0:{url:i});a!==void 0&&(o=Ms({value:o,path:s.path,replacement:s.structured===!0?bh({reference:s,runtimeAsset:a}):to(a.url,s.suffix)}))}return o};var ro=t=>{let e=t.format==="json"?t.value:t.value.frontmatter;return Lt(e)?e:void 0},Fs=({document:t,references:e,runtimeAssets:n})=>{let r=ro(t);if(r===void 0||e===void 0)return t;let o=pt({value:{properties:r},references:e,runtimeAssets:n}).properties;return t.format==="json"?Object.freeze({...t,value:o}):Object.freeze({...t,value:Object.freeze({...t.value,frontmatter:o})})},no=t=>Object.freeze(t),xf=async({format:t,source:e,maximumBytes:n=k.hydratedFileBytes})=>no(t==="json"?{format:t,value:await wl({source:e,maximumBytes:n})}:{format:t,value:await gf({source:e,maximumBytes:n})});var Sf=({document:t,references:e,allowUnresolvedReferences:n})=>t.format==="json"?no({format:t.format,value:yr({document:t.value,references:e,allowUnresolvedReferences:n})}):no({format:t.format,value:bf({document:t.value,references:e,allowUnresolvedReferences:n})}),Af=({document:t,representation:e})=>t.format==="json"?_l({document:t.value,representation:e}):wf({document:t.value,representation:e});var oo=class extends Error{code;documentId;expectedRevision;actualRevision;expectedFormat;actualFormat;constructor({code:e,documentId:n,expectedRevision:r,actualRevision:o,expectedFormat:s,actualFormat:i}){super(`Document ${n} source ${e==="REVISION_MISMATCH"?"revision":"format"} does not match its graph`),this.name="DocumentSourceError",this.code=e,this.documentId=n,this.expectedRevision=r,this.actualRevision=o,this.expectedFormat=s,this.actualFormat=i}},Wt=({node:t,source:e})=>{if(e.revision!==t.revision)throw new oo({code:"REVISION_MISMATCH",documentId:t.id,expectedRevision:t.revision,actualRevision:e.revision});if(t.format!==void 0&&e.format!==t.format)throw new oo({code:"FORMAT_MISMATCH",documentId:t.id,expectedFormat:t.format,actualFormat:e.format});return e};var Yt=t=>{if(typeof t=="object"&&t!==null){let e=Reflect.get(t,"code");if(typeof e=="string"&&e.length>0)return e;let n=Reflect.get(t,"name");if(typeof n=="string"&&n.length>0)return n}return"UNKNOWN"},se=(t,e)=>{try{t?.(e)}catch{}},Ef=({load:t,onEvent:e})=>async(n,r)=>{let o={documentId:n.id,revision:n.revision};se(e,{type:"document-fetch-started",...o});try{let s=await t(n,r);return se(e,{type:"document-fetch-completed",...o}),s}catch(s){throw se(e,{type:"document-fetch-failed",...o,errorCode:Yt(s)}),s}};var wh=C({format:ae(wn),revision:v().min(1)}),Ht=class extends Error{code;documentId;status;constructor({code:e,message:n,documentId:r,status:o,cause:s}){super(n,{cause:s}),this.name="HttpDocumentLoaderError",this.code=e,this.documentId=r,this.status=o}},vf=({fetch:t,getRequest:e,getMetadata:n,onEvent:r})=>Ef({load:async(s,{signal:i})=>{let a;try{a=await t(e(s),{signal:i})}catch(p){throw new Ht({code:"REQUEST_FAILED",message:`Document ${s.id} request failed`,documentId:s.id,cause:p})}if(a.ok===!1)throw new Ht({code:"HTTP_STATUS",message:`Document ${s.id} request returned status ${a.status}`,documentId:s.id,status:a.status});let c;try{c=wh.parse(n({node:s,response:a}))}catch(p){throw new Ht({code:"INVALID_METADATA",message:`Document ${s.id} response metadata is invalid`,documentId:s.id,cause:p})}let u=a.body;if(u===null)throw new Ht({code:"BODY_MISSING",message:`Document ${s.id} response body is unavailable`,documentId:s.id});return Object.freeze({...c,source:Ku(u)})},onEvent:r});var Xt=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Rf=new Set,Zs=typeof process=="object"&&process?process:{},kf=(t,e,n,r)=>{typeof Zs.emitWarning=="function"?Zs.emitWarning(t,e,n,r):console.error(`[${n}] ${e}: ${t}`)},so=globalThis.AbortController,Df=globalThis.AbortSignal;if(typeof so>"u"){Df=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},so=class{constructor(){e()}signal=new Df;abort(r){if(!this.signal.aborted){this.signal.reason=r,this.signal.aborted=!0;for(let o of this.signal._onabort)o(r);this.signal.onabort?.(r)}}};let t=Zs.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,kf("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var _h=t=>!Rf.has(t),dv=Symbol("type"),mt=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),If=t=>mt(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?en:null:null,en=class extends Array{constructor(e){super(e),this.fill(0)}},Bs=class t{heap;length;static#c=!1;static create(e){let n=If(e);if(!n)return[];t.#c=!0;let r=new t(e,n);return t.#c=!1,r}constructor(e,n){if(!t.#c)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new n(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},tn=class t{#c;#f;#h;#y;#O;#C;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#g;#r;#n;#e;#u;#d;#a;#s;#b;#i;#w;#_;#p;#x;#D;#l;static unsafeExposeInternals(e){return{starts:e.#_,ttls:e.#p,sizes:e.#w,keyMap:e.#r,keyList:e.#n,valList:e.#e,next:e.#u,prev:e.#d,get head(){return e.#a},get tail(){return e.#s},free:e.#b,isBackgroundFetch:n=>e.#t(n),backgroundFetch:(n,r,o,s)=>e.#$(n,r,o,s),moveToTail:n=>e.#I(n),indexes:n=>e.#S(n),rindexes:n=>e.#A(n),isStale:n=>e.#m(n)}}get max(){return this.#c}get maxSize(){return this.#f}get calculatedSize(){return this.#g}get size(){return this.#o}get fetchMethod(){return this.#O}get memoMethod(){return this.#C}get dispose(){return this.#h}get disposeAfter(){return this.#y}constructor(e){let{max:n=0,ttl:r,ttlResolution:o=1,ttlAutopurge:s,updateAgeOnGet:i,updateAgeOnHas:a,allowStale:c,dispose:u,disposeAfter:p,noDisposeOnSet:l,noUpdateTTL:f,maxSize:d=0,maxEntrySize:y=0,sizeCalculation:m,fetchMethod:h,memoMethod:b,noDeleteOnFetchRejection:S,noDeleteOnStaleGet:A,allowStaleOnFetchRejection:_,allowStaleOnFetchAbort:w,ignoreFetchAbort:E}=e;if(n!==0&&!mt(n))throw new TypeError("max option must be a nonnegative integer");let D=n?If(n):Array;if(!D)throw new Error("invalid max value: "+n);if(this.#c=n,this.#f=d,this.maxEntrySize=y||this.#f,this.sizeCalculation=m,this.sizeCalculation){if(!this.#f&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(b!==void 0&&typeof b!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#C=b,h!==void 0&&typeof h!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=h,this.#D=!!h,this.#r=new Map,this.#n=new Array(n).fill(void 0),this.#e=new Array(n).fill(void 0),this.#u=new D(n),this.#d=new D(n),this.#a=0,this.#s=0,this.#b=Bs.create(n),this.#o=0,this.#g=0,typeof u=="function"&&(this.#h=u),typeof p=="function"?(this.#y=p,this.#i=[]):(this.#y=void 0,this.#i=void 0),this.#x=!!this.#h,this.#l=!!this.#y,this.noDisposeOnSet=!!l,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!S,this.allowStaleOnFetchRejection=!!_,this.allowStaleOnFetchAbort=!!w,this.ignoreFetchAbort=!!E,this.maxEntrySize!==0){if(this.#f!==0&&!mt(this.#f))throw new TypeError("maxSize must be a positive integer if specified");if(!mt(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#B()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!A,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!a,this.ttlResolution=mt(o)||o===0?o:1,this.ttlAutopurge=!!s,this.ttl=r||0,this.ttl){if(!mt(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#z()}if(this.#c===0&&this.ttl===0&&this.#f===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#c&&!this.#f){let x="LRU_CACHE_UNBOUNDED";_h(x)&&(Rf.add(x),kf("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",x,t))}}getRemainingTTL(e){return this.#r.has(e)?1/0:0}#z(){let e=new en(this.#c),n=new en(this.#c);this.#p=e,this.#_=n,this.#P=(s,i,a=Xt.now())=>{if(n[s]=i!==0?a:0,e[s]=i,i!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#m(s)&&this.#E(this.#n[s],"expire")},i+1);c.unref&&c.unref()}},this.#R=s=>{n[s]=e[s]!==0?Xt.now():0},this.#v=(s,i)=>{if(e[i]){let a=e[i],c=n[i];if(!a||!c)return;s.ttl=a,s.start=c,s.now=r||o();let u=s.now-c;s.remainingTTL=a-u}};let r=0,o=()=>{let s=Xt.now();if(this.ttlResolution>0){r=s;let i=setTimeout(()=>r=0,this.ttlResolution);i.unref&&i.unref()}return s};this.getRemainingTTL=s=>{let i=this.#r.get(s);if(i===void 0)return 0;let a=e[i],c=n[i];if(!a||!c)return 1/0;let u=(r||o())-c;return a-u},this.#m=s=>{let i=n[s],a=e[s];return!!a&&!!i&&(r||o())-i>a}}#R=()=>{};#v=()=>{};#P=()=>{};#m=()=>!1;#B(){let e=new en(this.#c);this.#g=0,this.#w=e,this.#k=n=>{this.#g-=e[n],e[n]=0},this.#L=(n,r,o,s)=>{if(this.#t(r))return 0;if(!mt(o))if(s){if(typeof s!="function")throw new TypeError("sizeCalculation must be a function");if(o=s(r,n),!mt(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#N=(n,r,o)=>{if(e[n]=r,this.#f){let s=this.#f-e[n];for(;this.#g>s;)this.#T(!0)}this.#g+=e[n],o&&(o.entrySize=r,o.totalCalculatedSize=this.#g)}}#k=e=>{};#N=(e,n,r)=>{};#L=(e,n,r,o)=>{if(r||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#S({allowStale:e=this.allowStale}={}){if(this.#o)for(let n=this.#s;!(!this.#M(n)||((e||!this.#m(n))&&(yield n),n===this.#a));)n=this.#d[n]}*#A({allowStale:e=this.allowStale}={}){if(this.#o)for(let n=this.#a;!(!this.#M(n)||((e||!this.#m(n))&&(yield n),n===this.#s));)n=this.#u[n]}#M(e){return e!==void 0&&this.#r.get(this.#n[e])===e}*entries(){for(let e of this.#S())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*rentries(){for(let e of this.#A())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*keys(){for(let e of this.#S()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*rkeys(){for(let e of this.#A()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*values(){for(let e of this.#S())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#A())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,n={}){for(let r of this.#S()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;if(s!==void 0&&e(s,this.#n[r],this))return this.get(this.#n[r],n)}}forEach(e,n=this){for(let r of this.#S()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;s!==void 0&&e.call(n,s,this.#n[r],this)}}rforEach(e,n=this){for(let r of this.#A()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;s!==void 0&&e.call(n,s,this.#n[r],this)}}purgeStale(){let e=!1;for(let n of this.#A({allowStale:!0}))this.#m(n)&&(this.#E(this.#n[n],"expire"),e=!0);return e}info(e){let n=this.#r.get(e);if(n===void 0)return;let r=this.#e[n],o=this.#t(r)?r.__staleWhileFetching:r;if(o===void 0)return;let s={value:o};if(this.#p&&this.#_){let i=this.#p[n],a=this.#_[n];if(i&&a){let c=i-(Xt.now()-a);s.ttl=c,s.start=Date.now()}}return this.#w&&(s.size=this.#w[n]),s}dump(){let e=[];for(let n of this.#S({allowStale:!0})){let r=this.#n[n],o=this.#e[n],s=this.#t(o)?o.__staleWhileFetching:o;if(s===void 0||r===void 0)continue;let i={value:s};if(this.#p&&this.#_){i.ttl=this.#p[n];let a=Xt.now()-this.#_[n];i.start=Math.floor(Date.now()-a)}this.#w&&(i.size=this.#w[n]),e.unshift([r,i])}return e}load(e){this.clear();for(let[n,r]of e){if(r.start){let o=Date.now()-r.start;r.start=Xt.now()-o}this.set(n,r.value,r)}}set(e,n,r={}){if(n===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:s,noDisposeOnSet:i=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=r,{noUpdateTTL:u=this.noUpdateTTL}=r,p=this.#L(e,n,r.size||0,a);if(this.maxEntrySize&&p>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#E(e,"set"),this;let l=this.#o===0?void 0:this.#r.get(e);if(l===void 0)l=this.#o===0?this.#s:this.#b.length!==0?this.#b.pop():this.#o===this.#c?this.#T(!1):this.#o,this.#n[l]=e,this.#e[l]=n,this.#r.set(e,l),this.#u[this.#s]=l,this.#d[l]=this.#s,this.#s=l,this.#o++,this.#N(l,p,c),c&&(c.set="add"),u=!1;else{this.#I(l);let f=this.#e[l];if(n!==f){if(this.#D&&this.#t(f)){f.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:d}=f;d!==void 0&&!i&&(this.#x&&this.#h?.(d,e,"set"),this.#l&&this.#i?.push([d,e,"set"]))}else i||(this.#x&&this.#h?.(f,e,"set"),this.#l&&this.#i?.push([f,e,"set"]));if(this.#k(l),this.#N(l,p,c),this.#e[l]=n,c){c.set="replace";let d=f&&this.#t(f)?f.__staleWhileFetching:f;d!==void 0&&(c.oldValue=d)}}else c&&(c.set="update")}if(o!==0&&!this.#p&&this.#z(),this.#p&&(u||this.#P(l,o,s),c&&this.#v(c,l)),!i&&this.#l&&this.#i){let f=this.#i,d;for(;d=f?.shift();)this.#y?.(...d)}return this}pop(){try{for(;this.#o;){let e=this.#e[this.#a];if(this.#T(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#l&&this.#i){let e=this.#i,n;for(;n=e?.shift();)this.#y?.(...n)}}}#T(e){let n=this.#a,r=this.#n[n],o=this.#e[n];return this.#D&&this.#t(o)?o.__abortController.abort(new Error("evicted")):(this.#x||this.#l)&&(this.#x&&this.#h?.(o,r,"evict"),this.#l&&this.#i?.push([o,r,"evict"])),this.#k(n),e&&(this.#n[n]=void 0,this.#e[n]=void 0,this.#b.push(n)),this.#o===1?(this.#a=this.#s=0,this.#b.length=0):this.#a=this.#u[n],this.#r.delete(r),this.#o--,n}has(e,n={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:o}=n,s=this.#r.get(e);if(s!==void 0){let i=this.#e[s];if(this.#t(i)&&i.__staleWhileFetching===void 0)return!1;if(this.#m(s))o&&(o.has="stale",this.#v(o,s));else return r&&this.#R(s),o&&(o.has="hit",this.#v(o,s)),!0}else o&&(o.has="miss");return!1}peek(e,n={}){let{allowStale:r=this.allowStale}=n,o=this.#r.get(e);if(o===void 0||!r&&this.#m(o))return;let s=this.#e[o];return this.#t(s)?s.__staleWhileFetching:s}#$(e,n,r,o){let s=n===void 0?void 0:this.#e[n];if(this.#t(s))return s;let i=new so,{signal:a}=r;a?.addEventListener("abort",()=>i.abort(a.reason),{signal:i.signal});let c={signal:i.signal,options:r,context:o},u=(m,h=!1)=>{let{aborted:b}=i.signal,S=r.ignoreFetchAbort&&m!==void 0;if(r.status&&(b&&!h?(r.status.fetchAborted=!0,r.status.fetchError=i.signal.reason,S&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),b&&!S&&!h)return l(i.signal.reason);let A=d;return this.#e[n]===d&&(m===void 0?A.__staleWhileFetching?this.#e[n]=A.__staleWhileFetching:this.#E(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,m,c.options))),m},p=m=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=m),l(m)),l=m=>{let{aborted:h}=i.signal,b=h&&r.allowStaleOnFetchAbort,S=b||r.allowStaleOnFetchRejection,A=S||r.noDeleteOnFetchRejection,_=d;if(this.#e[n]===d&&(!A||_.__staleWhileFetching===void 0?this.#E(e,"fetch"):b||(this.#e[n]=_.__staleWhileFetching)),S)return r.status&&_.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),_.__staleWhileFetching;if(_.__returned===_)throw m},f=(m,h)=>{let b=this.#O?.(e,s,c);b&&b instanceof Promise&&b.then(S=>m(S===void 0?void 0:S),h),i.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(m(void 0),r.allowStaleOnFetchAbort&&(m=S=>u(S,!0)))})};r.status&&(r.status.fetchDispatched=!0);let d=new Promise(f).then(u,p),y=Object.assign(d,{__abortController:i,__staleWhileFetching:s,__returned:void 0});return n===void 0?(this.set(e,y,{...c.options,status:void 0}),n=this.#r.get(e)):this.#e[n]=y,y}#t(e){if(!this.#D)return!1;let n=e;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof so}async fetch(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:p=this.noUpdateTTL,noDeleteOnFetchRejection:l=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:d=this.ignoreFetchAbort,allowStaleOnFetchAbort:y=this.allowStaleOnFetchAbort,context:m,forceRefresh:h=!1,status:b,signal:S}=n;if(!this.#D)return b&&(b.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,status:b});let A={allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,ttl:i,noDisposeOnSet:a,size:c,sizeCalculation:u,noUpdateTTL:p,noDeleteOnFetchRejection:l,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:y,ignoreFetchAbort:d,status:b,signal:S},_=this.#r.get(e);if(_===void 0){b&&(b.fetch="miss");let w=this.#$(e,_,A,m);return w.__returned=w}else{let w=this.#e[_];if(this.#t(w)){let $=r&&w.__staleWhileFetching!==void 0;return b&&(b.fetch="inflight",$&&(b.returnedStale=!0)),$?w.__staleWhileFetching:w.__returned=w}let E=this.#m(_);if(!h&&!E)return b&&(b.fetch="hit"),this.#I(_),o&&this.#R(_),b&&this.#v(b,_),w;let D=this.#$(e,_,A,m),O=D.__staleWhileFetching!==void 0&&r;return b&&(b.fetch=E?"stale":"refresh",O&&E&&(b.returnedStale=!0)),O?D.__staleWhileFetching:D.__returned=D}}async forceFetch(e,n={}){let r=await this.fetch(e,n);if(r===void 0)throw new Error("fetch() returned undefined");return r}memo(e,n={}){let r=this.#C;if(!r)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:s,...i}=n,a=this.get(e,i);if(!s&&a!==void 0)return a;let c=r(e,a,{options:i,context:o});return this.set(e,c,i),c}get(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,status:i}=n,a=this.#r.get(e);if(a!==void 0){let c=this.#e[a],u=this.#t(c);return i&&this.#v(i,a),this.#m(a)?(i&&(i.get="stale"),u?(i&&r&&c.__staleWhileFetching!==void 0&&(i.returnedStale=!0),r?c.__staleWhileFetching:void 0):(s||this.#E(e,"expire"),i&&r&&(i.returnedStale=!0),r?c:void 0)):(i&&(i.get="hit"),u?c.__staleWhileFetching:(this.#I(a),o&&this.#R(a),c))}else i&&(i.get="miss")}#F(e,n){this.#d[n]=e,this.#u[e]=n}#I(e){e!==this.#s&&(e===this.#a?this.#a=this.#u[e]:this.#F(this.#d[e],this.#u[e]),this.#F(this.#s,e),this.#s=e)}delete(e){return this.#E(e,"delete")}#E(e,n){let r=!1;if(this.#o!==0){let o=this.#r.get(e);if(o!==void 0)if(r=!0,this.#o===1)this.#Z(n);else{this.#k(o);let s=this.#e[o];if(this.#t(s)?s.__abortController.abort(new Error("deleted")):(this.#x||this.#l)&&(this.#x&&this.#h?.(s,e,n),this.#l&&this.#i?.push([s,e,n])),this.#r.delete(e),this.#n[o]=void 0,this.#e[o]=void 0,o===this.#s)this.#s=this.#d[o];else if(o===this.#a)this.#a=this.#u[o];else{let i=this.#d[o];this.#u[i]=this.#u[o];let a=this.#u[o];this.#d[a]=this.#d[o]}this.#o--,this.#b.push(o)}}if(this.#l&&this.#i?.length){let o=this.#i,s;for(;s=o?.shift();)this.#y?.(...s)}return r}clear(){return this.#Z("delete")}#Z(e){for(let n of this.#A({allowStale:!0})){let r=this.#e[n];if(this.#t(r))r.__abortController.abort(new Error("deleted"));else{let o=this.#n[n];this.#x&&this.#h?.(r,o,e),this.#l&&this.#i?.push([r,o,e])}}if(this.#r.clear(),this.#e.fill(void 0),this.#n.fill(void 0),this.#p&&this.#_&&(this.#p.fill(0),this.#_.fill(0)),this.#w&&this.#w.fill(0),this.#a=0,this.#s=0,this.#b.length=0,this.#g=0,this.#o=0,this.#l&&this.#i){let n=this.#i,r;for(;r=n?.shift();)this.#y?.(...r)}}};var js=({maximumBytes:t=k.hydratedTotalBytes*4}={})=>{if(Number.isSafeInteger(t)===!1||t<=0)throw new TypeError("Document source cache byte limit must be positive");return new tn({maxSize:t,sizeCalculation:e=>Math.max(1,e.bytes.byteLength)})},jn=class extends Error{code="CONTENT_LIMIT_EXCEEDED";documentId;contentByteLimit;constructor({message:e,documentId:n,contentByteLimit:r,cause:o}){super(e,{cause:o}),this.name="CachedDocumentLoaderError",this.documentId=n,this.contentByteLimit=r}},io=({contentRef:t,revision:e,format:n})=>fe([t,e,n??null]),xh=t=>{if(typeof t!="object"||t===null)return!1;let e=t;return el(e.format)&&typeof e.revision=="string"&&e.revision.length>0&&e.bytes instanceof Uint8Array},Of=t=>Object.freeze({format:t.format,revision:t.revision,source:t.bytes}),Cf=({load:t,cache:e,maximumBytes:n=k.hydratedFileBytes,onEvent:r})=>{let o=new Map;return async(s,i)=>{let a=io(s),c=o.get(a)??new Map;o.set(a,c);let u=c.get(i.signal);if(u!==void 0)return await u;let p=(async()=>{let l;try{l=await e.get(a)}catch(m){se(r,{type:"document-cache-read-failed",documentId:s.id,revision:s.revision,errorCode:Yt(m)})}if(xh(l)&&l.revision===s.revision&&l.bytes.byteLength<=n&&(s.format===void 0||l.format===s.format))return se(r,{type:"document-cache-hit",documentId:s.id,revision:s.revision}),Of(l);se(r,{type:"document-cache-miss",documentId:s.id,revision:s.revision});let f=Wt({node:s,source:await t(s,i)}),d;try{d=await Te(f.source,n)}catch(m){throw m instanceof re?new jn({message:`Document ${s.id} exceeds the cache byte limit`,documentId:s.id,contentByteLimit:n,cause:m}):m}let y=Object.freeze({format:f.format,revision:f.revision,bytes:d});try{await e.set(a,y),se(r,{type:"document-cache-stored",documentId:s.id,revision:s.revision})}catch(m){se(r,{type:"document-cache-write-failed",documentId:s.id,revision:s.revision,errorCode:Yt(m)})}return Of(y)})();c.set(i.signal,p);try{return await p}finally{c.delete(i.signal),c.size===0&&o.delete(a)}}};var We=class extends Error{code;documentId;referenceId;constructor({code:e,message:n,documentId:r,referenceId:o,cause:s}){super(n,{cause:s}),this.name="DocumentGraphResolutionError",this.code=e,this.documentId=r,this.referenceId=o}},ao=t=>{if(t?.aborted)throw new We({code:"REQUEST_CANCELLED",message:"Document graph resolution was cancelled",cause:t.reason})},Nf=async({graph:t,rootIds:e,concurrency:n,signal:r,load:o,select:s,assemble:i})=>{ao(r);let a=fr({graph:t,rootIds:e}),c=new Map(a.map(d=>[d.id,d])),u=new Map,p=new Map;for(let d of a){let y=p.get(d.contentRef);y===void 0?p.set(d.contentRef,{representative:d,nodes:[d]}):y.nodes.push(d)}await mr([...p.values()],n,async d=>{ao(r);let y=d.representative;try{let m=await o(y,{signal:r});for(let h of d.nodes)u.set(h.id,m)}catch(m){throw r?.aborted&&ao(r),new We({code:"DOCUMENT_LOAD_FAILED",message:`Document ${y.id} could not be loaded`,documentId:y.id,cause:m})}});let l=Pt(t.edges),f=new Map;for(let d of a){ao(r);let y=new Map;for(let h of l.get(d.id)??[]){let b=c.get(h.reference.documentId);if(b===void 0||f.has(h.reference.documentId)===!1)throw new We({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${d.id} dependency ${h.reference.documentId} is unavailable`,documentId:d.id,referenceId:h.referenceId});let S=f.get(h.reference.documentId),A;if(s===void 0){if(h.reference.representation.type!=="document")throw new We({code:"REPRESENTATION_SELECTOR_REQUIRED",message:`Document ${d.id} reference ${h.referenceId} requires a representation selector`,documentId:d.id,referenceId:h.referenceId});A=S}else try{A=await s({reference:h.reference,value:S,sourceNode:d,targetNode:b})}catch(_){throw new We({code:"DOCUMENT_SELECTION_FAILED",message:`Document ${d.id} reference ${h.referenceId} could not be selected`,documentId:d.id,referenceId:h.referenceId,cause:_})}y.set(h.referenceId,A)}if(u.has(d.id)===!1)throw new We({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${d.id} source is unavailable`,documentId:d.id});let m=u.get(d.id);try{f.set(d.id,await i({node:d,source:m,references:y}))}catch(h){throw new We({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${d.id} could not be assembled`,documentId:d.id,cause:h})}}return Object.freeze({roots:Object.freeze(e.map(d=>f.get(d))),values:f})};var At=class extends Error{code;documentId;documentCount;documentLimit;contentByteLimit;totalBytes;totalByteLimit;constructor({code:e,message:n,documentId:r,documentCount:o,documentLimit:s,contentByteLimit:i,totalBytes:a,totalByteLimit:c,cause:u}){super(n,{cause:u}),this.name="DocumentResolutionLimitError",this.code=e,this.documentId=r,this.documentCount=o,this.documentLimit=s,this.contentByteLimit=i,this.totalBytes=a,this.totalByteLimit=c}},Sh=(t,e)=>{let n=0,r=[],o=async()=>{if(e?.throwIfAborted(),n<t){n+=1;return}await new Promise((i,a)=>{let c,u=()=>{let p=r.indexOf(c);p!==-1&&r.splice(p,1);try{e?.throwIfAborted()}catch(l){a(l)}};c={start:()=>{e?.removeEventListener("abort",u),i()}},r.push(c),e?.addEventListener("abort",u,{once:!0})})},s=()=>{let i=r.shift();if(i===void 0){n-=1;return}i.start()};return async i=>{await o();try{return await i()}finally{s()}}},Ah=async({graph:t,rootIds:e,concurrency:n,maximumBytes:r,maximumTotalBytes:o=k.hydratedTotalBytes,maximumDocuments:s=k.hydratedFileCount,signal:i,onEvent:a,allowUnresolvedReferences:c=!1,transformDocument:u,load:p})=>{let l=fr({graph:t,rootIds:e}).length,f={rootCount:e.length,documentCount:l};se(a,{type:"resolution-started",...f});try{if(l>s)throw new At({code:"DOCUMENT_COUNT_EXCEEDED",message:"Document graph resolution exceeds the document limit",documentCount:l,documentLimit:s});let d=0,y=Promise.resolve(),m=await Nf({graph:t,rootIds:e,concurrency:n,signal:i,load:async(h,b)=>{let S=y,A=()=>{};y=new Promise(w=>{A=w});let _;try{_={status:"fulfilled",value:await p(h,b)}}catch(w){_={status:"rejected",reason:w}}await S;try{if(_.status==="rejected")throw _.reason;if(_.value.byteLength>r)throw new At({code:"CONTENT_LIMIT_EXCEEDED",message:`Document ${h.id} exceeds the byte limit`,documentId:h.id,contentByteLimit:r,cause:new re});let w=d+_.value.byteLength;if(w>o)throw new At({code:"TOTAL_BYTES_EXCEEDED",message:"Document graph resolution exceeds the total byte limit",documentId:h.id,totalBytes:w,totalByteLimit:o});return d=w,await _.value.parse()}finally{A()}},select:({reference:h,value:b})=>Af({document:b,representation:h.representation}),assemble:({node:h,source:b,references:S})=>{let A=Sf({document:b,references:S,allowUnresolvedReferences:c});return u?.({node:h,document:A})??A}});return se(a,{type:"resolution-completed",...f}),m}catch(d){throw se(a,{type:"resolution-failed",...f,errorCode:Yt(d)}),d}},Tf=({load:t,concurrency:e,signal:n,maximumDocumentBytes:r=k.hydratedFileBytes,maximumCacheBytes:o=k.hydratedTotalBytes*4})=>{if(Number.isSafeInteger(e)===!1||e<=0)throw new TypeError("Document resolution concurrency must be positive");if(Number.isSafeInteger(r)===!1||r<=0)throw new TypeError("Document resolution byte limit must be positive");if(Number.isSafeInteger(o)===!1||o<=0)throw new TypeError("Document resolution cache byte limit must be positive");let s=new tn({maxSize:o,sizeCalculation:({byteLength:f})=>Math.max(1,f)}),i=new Map,a=Sh(e,n),c=f=>{if(f!==void 0&&f!==n)throw new TypeError("Document resolution session signal does not match");n?.throwIfAborted()},u=async f=>(c(),n===void 0?await f:await new Promise((d,y)=>{let m=()=>n.removeEventListener("abort",h),h=()=>{m();try{n.throwIfAborted()}catch(b){y(b)}};n.addEventListener("abort",h,{once:!0}),f.then(b=>{m(),d(b)},b=>{m(),y(b)}),n.aborted&&h()})),p=async(f,d)=>{c(d.signal);let y=io(f),m=s.get(y);if(m!==void 0)return m;let h=i.get(y);if(h!==void 0)return await u(h);let b=a(async()=>{c(d.signal);let S=Wt({node:f,source:await t(f,{signal:n})});c(d.signal);let A=await Ho(S.source,r+1);c(d.signal);let _,w=Object.freeze({format:S.format,revision:S.revision,bytes:A,byteLength:A.byteLength,parse:()=>(_??=xf({format:S.format,source:A,maximumBytes:r}),_)});return w.byteLength<=o&&s.set(y,w),w});i.set(y,b);try{return await u(b)}finally{i.delete(y)}};return Object.freeze({getCached:f=>{c();let d=s.get(io(f));if(!(d===void 0||d.byteLength>r))return Object.freeze({format:d.format,revision:d.revision,source:d.bytes.slice()})},resolve:async f=>await Ah({...f,concurrency:e,maximumBytes:r,signal:n,load:p})})};var $f=t=>{if(t.output.mode==="all")return"all";let e=[];for(let{field:n}of gn(t.where))n[0]==="properties"&&e.push(n);for(let{field:n}of t.sort)n[0]==="properties"&&e.push(n);if(t.output.mode==="fields")for(let n of t.output.fields)n[0]==="properties"&&e.push(n);return e},zf=t=>{let e;if(t==="#frontmatter")e="";else if(t.startsWith("#frontmatter/"))e=t.slice(12);else if(t==="#")e="";else if(t.startsWith("#/"))e=t.slice(1);else return;try{return["properties",...bl(e)]}catch{return}},Pf=(t,e)=>{let n=Math.min(t.length,e.length);for(let r=0;r<n;r+=1)if(t[r]!==e[r])return!1;return!0},Lf=({queryPaths:t,referenceId:e})=>{let n=zf(e);return n!==void 0&&(t==="all"||t.some(r=>Pf(r,n)))},Mf=({graph:t,sourceId:e,field:n})=>n[0]!=="properties"?!1:t.edges.some(r=>{if(r.sourceId!==e)return!1;let o=zf(r.referenceId);return o!==void 0&&Pf(n,o)}),Ff=({graph:t,query:e})=>{let n=$f(e),r=new Set;for(let o of t.edges)Lf({queryPaths:n,referenceId:o.referenceId})&&r.add(o.sourceId);return[...r]},Zf=({graph:t,query:e,rootIds:n})=>{let r=$f(e),o=new Set(n),s=new Map(t.nodes.map(l=>[l.id,l])),i=Pt(t.edges),a=new Set(n),c=new Set,u=new Set,p=l=>{if(a.add(l),!u.has(l)){u.add(l);for(let f of i.get(l)??[])c.add(f),p(f.reference.documentId)}};for(let l of t.edges)o.has(l.sourceId)&&Lf({queryPaths:r,referenceId:l.referenceId})&&(c.add(l),p(l.reference.documentId));return _n({nodes:[...a].map(l=>{let f=s.get(l);if(f===void 0)throw new Error(`Document graph query root ${l} does not exist`);return f}),edges:[...c]})};var Bf=({artifact:t})=>{if(t.documentGraph===void 0)return;let e=new Map(t.documents.map(s=>[s._id,s])),n=new Map(t.documentGraph.nodes.map(s=>[s.id,s])),r=new Map;for(let{sourceId:s}of t.documentGraph.edges){if(n.has(s))continue;let i=e.get(s);if(i?.properties===void 0)throw new Error(`Runtime document graph source ${s} is unavailable`);r.set(s,i),n.set(s,{id:s,revision:s,contentRef:s,format:"json"})}return{graph:_n({nodes:[...n.values()],edges:t.documentGraph.edges.map(({sourceId:s,referenceId:i,documentId:a,representation:c})=>{let u=n.get(a);if(u===void 0)throw new Error(`Runtime document graph target ${a} is unavailable`);return{sourceId:s,referenceId:i,reference:{documentId:a,revision:u.revision,representation:c}}})}),inlineDocuments:r}};var jf=({markdown:t,references:e,assetUrls:n})=>{let r=t.length,o=t;for(let s of[...e].sort((i,a)=>a.start-i.start)){if(s.start<0||s.end<=s.start||s.end>t.length||s.end>r)throw new Error("Markdown asset reference range is invalid");r=s.start;let i=n[s.assetId];if(i===void 0)continue;let a=to(i,s.suffix);o=`${o.slice(0,s.start)}${a}${o.slice(s.end)}`}return o};var ie=class extends Error{code;details;constructor({code:e,message:n,details:r}){super(n),this.name="AssetResourceHydrationError",this.code=e,this.details=r}},Eh=t=>{if(t===null)return[];let e=Array.isArray(t)?t:[t],n=new Map;for(let r of e){if(typeof r!="object"||r===null||!("_id"in r)||typeof r._id!="string"||!("revision"in r)||typeof r.revision!="string"||!("contentRef"in r)||typeof r.contentRef!="string")throw new ie({code:"CONTENT_IDENTITY_REQUIRED",message:"Hydrated query results must retain _id, revision, and contentRef"});let o=n.get(r._id);if(o!==void 0&&(o.revision!==r.revision||o.contentRef!==r.contentRef))throw new ie({code:"CONTENT_IDENTITY_REQUIRED",message:"A selected asset ID has conflicting content identity",details:{assetId:r._id}});n.set(r._id,{_id:r._id,revision:r.revision,contentRef:r.contentRef})}return Array.from(n.values())},vh=t=>typeof t.mimeType=="string"&&(t.mimeType.startsWith("text/")||["application/json","application/javascript","application/xml","image/svg+xml"].includes(t.mimeType)),Dh=async({read:t,contentRef:e,range:n,maximumBytes:r})=>{if(r===0)return new Uint8Array;let o=await t(e,n);try{return await Te(o.data,r)}catch(s){throw s instanceof re?new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Asset storage returned more content than requested"}):s}},Rh=t=>{try{return le(t)}catch{throw new ie({code:"CONTENT_DECODING_FAILED",message:"Selected asset content is not valid UTF-8"})}},kh=(t,e)=>{if(e.mode==="range")return Math.max(0,Math.min(e.length,t.size-e.offset));let n=e.maxBytes??k.hydratedFileBytes;if(t.size>n)throw new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected asset exceeds the per-file content limit",details:{assetId:t._id,assetBytes:t.size,fileByteLimit:n}});return t.size},Uf=async({result:t,documents:e,options:n,read:r,assetReferences:o,assetUrls:s})=>{if(n.mode==="none")return{content:{},hydratedFileCount:0,hydratedBytes:0};let i=Eh(t);if(i.length>k.hydratedFileCount)throw new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Too many selected assets requested content hydration",details:{fileCount:i.length,fileCountLimit:k.hydratedFileCount}});let a=new Map(e.map(l=>[l._id,l])),c=i.map(l=>{let f=a.get(l._id);if(f===void 0||f.revision!==l.revision||f.contentRef!==l.contentRef||typeof f.size!="number"||typeof f.mimeType!="string")throw new ie({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset content identity is stale or unavailable",details:{assetId:l._id}});let d={...f,size:f.size,mimeType:f.mimeType};if(vh(d)===!1)throw new ie({code:"CONTENT_NOT_TEXT",message:"Selected binary asset cannot be embedded as text",details:{assetId:l._id,mimeType:d.mimeType}});return{identity:l,document:d,readLength:kh(d,n)}}),u=c.reduce((l,f)=>l+f.readLength,0);if(u>k.hydratedTotalBytes)throw new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected assets exceed the total hydrated-content limit",details:{totalReadBytes:u,totalByteLimit:k.hydratedTotalBytes}});let p=await mr(c,k.concurrentContentReads,async l=>{let f=n.mode==="range"?{offset:n.offset,length:l.readLength}:l.readLength===0?void 0:{offset:0,length:l.readLength},d=await Dh({read:r,contentRef:l.identity.contentRef,range:f,maximumBytes:l.readLength});if(d.byteLength!==l.readLength)throw new ie({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset bytes do not match canonical metadata",details:{assetId:l.identity._id}});let y;if(n.mode==="markdown-body-ref")try{y=(await Hr(d,l.readLength||1)).body;let h=o?.[l.identity.contentRef];h!==void 0&&s!==void 0&&(y=jf({markdown:y,references:h,assetUrls:s}))}catch{throw new ie({code:"CONTENT_DECODING_FAILED",message:"Selected Markdown body could not be decoded",details:{assetId:l.identity._id}})}else y=Rh(d);let m=Ne(y);return{id:l.identity._id,returnedBytes:m,content:{...l.identity,encoding:"utf-8",text:y,...n.mode==="range"?{range:{offset:n.offset,length:d.byteLength,total:l.document.size}}:{}}}});return{content:Object.fromEntries(p.map(({id:l,content:f})=>[l,f])),hydratedFileCount:c.length,hydratedBytes:p.reduce((l,{returnedBytes:f})=>l+f,0)}};var Hv=v().datetime({offset:!0}).transform(t=>new Date(t).toISOString());var Ih=/^[A-Za-z_][A-Za-z0-9_]*$/,Qf=(t,e)=>Ih.test(e)?`${t}.${e}`:`${t}[${JSON.stringify(e)}]`;var Vf=({document:t,includes:e})=>{let n={};for(let r of ll){let o=t[r];o!==void 0&&e(r)&&(n[r]=o)}return n},ht=Symbol("missing property selection"),Us=(t,e)=>{if(e.some(r=>r.length===0)||typeof hr(t)=="string")return t;if(Array.isArray(t)){let r=e.filter(([s])=>s==="*").map(s=>s.slice(1));if(r.length===0)return ht;let o=t.map(s=>Us(s,r));return o.some(s=>s!==ht)?o.map(s=>s===ht?null:s):ht}if(typeof t!="object"||t===null)return ht;let n={};for(let[r,o]of Object.entries(t)){let s=e.filter(([a])=>a===r).map(a=>a.slice(1));if(s.length===0)continue;let i=Us(o,s);i!==ht&&(n[r]=i)}return Object.keys(n).length===0?ht:n},Gf=({properties:t,fields:e})=>{let n=e.filter(([o])=>o==="properties").map(o=>o.slice(1)),r=Us(t,n);return r===ht?{}:r};var Oe=class extends Error{constructor(e,n){super(e,n),this.name="AssetQueryExecutionError"}},Un=class extends Oe{code="MULTIPLE_RESULTS";matchedCount;constructor(e){super(`Expected at most one asset, but the query matched ${e}.`),this.matchedCount=e,this.name="AssetQueryMultipleResultsError"}},rn=class extends Error{constructor(){super("The requested asset index revision is stale"),this.name="AssetIndexRevisionError"}},Jf=t=>{if(t[0]!=="properties")return t[0];let e="properties";for(let n of t.slice(1))e=Qf(e,n);return e},qf=({filter:t,fieldTypes:e})=>pl(e).includes(t.operator),Kf=(t,e)=>t!==void 0&&Object.hasOwn(t.fields,e)?t.fields[e]:void 0,Oh=({query:t,catalog:e})=>{let n=ot.parse(t),r=new Map,o=[];for(let s of gn(n.where)){let i=Jf(s.field);if(r.set(i,s.field),s.field[0]==="properties"){let a=Kf(e,i);e!==void 0&&a===void 0?o.push(`Asset field ${i} is not currently observed`):a!==void 0&&qf({filter:s,fieldTypes:a.types})===!1&&o.push(`Operator ${s.operator} is not compatible with the currently observed types of ${i}`)}else if(qf({filter:s,fieldTypes:os[s.field[0]]})===!1)throw new Oe(`Operator ${s.operator} is incompatible with ${i}`)}for(let s of n.sort){let i=Jf(s.field);if(r.set(i,s.field),s.field[0]==="properties"){let a=Kf(e,i);e!==void 0&&a===void 0?o.push(`Asset field ${i} is not currently observed`):a!==void 0&&a.types.some(c=>c==="object"||c==="array")&&o.push(`Asset field ${i} currently includes structured values that use deterministic JSON sort order`)}}return{query:n,referencedFieldPaths:[...r.values()],warnings:[...new Set(o)]}},Vs=(t,e,n)=>{let r=e[0]==="id"?t._id:pr(e[0])?n?.[e[0]]:t[e[0]];for(let o of e.slice(1)){if(typeof r!="object"||r===null||Object.hasOwn(r,o)===!1)return;r=r[o]}return r},Ch=t=>typeof t=="string"||Array.isArray(t)?t.length===0:typeof t=="object"&&t!==null&&Object.keys(t).length===0,Nh=(t,e)=>{if(typeof t=="number"&&typeof e=="number")return t-e;if(typeof t=="string"&&typeof e=="string")return $e(t,e)},Gs=(t,e,n)=>{let r=Vs(t,e.field,n);if(e.operator==="exists")return r!=null===e.value;if(e.operator==="isEmpty")return Ch(r)===e.value;if(e.operator==="eq")return bn(r,e.value);if(e.operator==="ne")return bn(r,e.value)===!1;if(e.operator==="in")return e.value.some(s=>bn(r,s));if(e.operator==="contains")return typeof r=="string"&&typeof e.value=="string"?r.includes(e.value):Array.isArray(r)&&r.some(s=>bn(s,e.value));if(e.operator==="startsWith")return typeof r=="string"&&typeof e.value=="string"&&r.startsWith(e.value);if(e.operator==="endsWith")return typeof r=="string"&&typeof e.value=="string"&&r.endsWith(e.value);let o=Nh(r,e.value);return o===void 0?!1:e.operator==="gt"?o>0:e.operator==="gte"?o>=0:e.operator==="lt"?o<0:o<=0},Th=({document:t,where:e,runtimeAsset:n,filterKeys:r,filterResults:o})=>Nt(e,s=>{let i=r.get(s)??fe(s),a=o.get(i);if(a!==void 0)return a;let c=Gs(t,s,n);return o.set(i,c),c})===!0,$h=({document:t,content:e})=>{if(e.mode!=="markdown-body-ref")return!0;let n=t.mimeType===void 0?void 0:tl(t.mimeType);return n==="markdown"||n==="mdx"?!0:t.extension==="md"||t.extension==="mdx"},zh=(t,e)=>{let n=t==null,r=e==null;return n||r?n===r?0:n?1:-1:typeof t=="number"&&typeof e=="number"?t-e:(typeof t=="string"||typeof t=="boolean")&&(typeof e=="string"||typeof e=="boolean")?$e(String(t),String(e)):$e(fe(t),fe(e))},Ph=({left:t,right:e,sort:n,runtimeAssets:r})=>{for(let o of n){let s=zh(Vs(t,o.field,r?.[t._id]),Vs(e,o.field,r?.[e._id]));if(s!==0)return o.direction==="asc"?s:-s}return $e(t._id,e._id)};var Lh=(t,e)=>{if(t.properties===void 0)return;if(e.mode==="all")return Object.keys(t.properties).length===0?void 0:t.properties;if(e.mode!=="fields"||e.fields.some(r=>r[0]==="properties")===!1)return;let n=Gf({properties:t.properties,fields:e.fields});return Object.keys(n).length===0?void 0:n},nn=(t,e)=>t.includeMetadata&&fl(e)||t.mode==="fields"&&t.fields.some(n=>n.length===1&&n[0]===e),Mh=t=>t.mode==="all"||t.mode==="fields"&&t.fields.some(e=>e.length===1&&e[0]==="excerpt"),Fh=(t,e,n)=>{if(nn(e,"url")&&n===void 0)throw new Error(`Asset URL is unavailable for ${t._id}`);let r=Lh(t,e),o=n?.width!==void 0&&n.height!==void 0;return{...n!==void 0&&nn(e,"url")?{url:n.url}:{},...o&&nn(e,"width")?{width:n.width}:{},...o&&nn(e,"height")?{height:n.height}:{},...Vf({document:t,includes:s=>nn(e,s)}),...r===void 0?{}:{properties:r},...t.excerpt===void 0||Mh(e)===!1?{}:{excerpt:t.excerpt},...t.metadataError===void 0||e.includeMetadata===!1?{}:{metadataError:t.metadataError}}},Js=t=>{if(Ne(fe(t))>k.resultBytes)throw new Oe("Asset query result exceeds the byte limit")},co=(t,e,n)=>{t[e]={status:"rejected",reason:n}},Zh=({inputs:t,catalog:e,results:n})=>{let r=new Map,o=new Map,s=[];for(let[i,a]of t.entries()){let c;try{c=Oh({query:a,catalog:e}).query}catch(l){co(n,i,l);continue}for(let l of gn(c.where))o.set(l,fe(l));let u=fe(c.sort),p=r.get(u);p===void 0&&(p={sort:c.sort,documents:new Set,sorted:[]},r.set(u,p)),s.push({index:i,query:c,matches:new Map,sortGroup:p})}return{filterKeys:o,preparedQueries:s,sortGroups:r}},Wf=({preparedQueries:t,results:e,createReason:n})=>{for(let{index:r}of t)co(e,r,n())},Qs=t=>t.map(e=>{if(e===void 0)throw new Error("Asset query result was not settled");return e}),Bh=({preparedQueries:t,documents:e,filterKeys:n,sortGroups:r,results:o,runtimeAssets:s})=>{for(let i of e){let a=s?.[i._id],c=new Map;for(let u of t){if(o[u.index]!==void 0)continue;let{query:p}=u;try{if($h({document:i,content:p.content})===!1||Th({document:i,where:p.where,runtimeAsset:a,filterKeys:n,filterResults:c})===!1)continue;let l=Fh(i,p.output,a);if(p.content.mode==="none"&&Object.keys(l).length===0&&nn(p.output,"id")===!1)continue;let f={document:i,item:{id:i._id,...l}};u.matches.set(i,f),u.sortGroup.documents.add(i)}catch(l){co(o,u.index,l)}}}for(let i of r.values())i.sorted=[...i.documents].sort((a,c)=>Ph({left:a,right:c,sort:i.sort,runtimeAssets:s}))},jh=async({preparedQueries:t,results:e,read:n,assetReferences:r,assetUrls:o})=>{await Promise.all(t.map(async s=>{if(e[s.index]!==void 0)return;let{query:i}=s;try{let a=s.sortGroup.sorted.flatMap(d=>{let y=s.matches.get(d);return y===void 0?[]:[y]}),c=i.result??"many";if(c==="one"&&a.length>1)throw new Un(a.length);let u=c==="many"?a.slice(i.offset,i.offset+i.limit):c==="last"?a.slice(-1):a.slice(0,1),p=u.map(({document:d})=>d),l=u.map(({item:d})=>d);if(i.content.mode!=="none"){let d=i.content;if(n===void 0)throw new Oe("Asset content reader is unavailable");let y=await Uf({result:p,documents:p,options:d,read:n,assetReferences:r,assetUrls:r===void 0?void 0:o});l=p.map((m,h)=>{let b=y.content[m._id];if(b===void 0)throw new Oe("Selected asset content could not be read");return{...l[h],content:{encoding:b.encoding,text:b.text,...b.range===void 0?{}:{range:b.range}}}})}let f=c==="many"?{items:l,totalCount:a.length,hasMore:i.offset+u.length<a.length}:{item:l[0]??null,totalCount:a.length};Js(f),e[s.index]={status:"fulfilled",value:f}}catch(a){co(e,s.index,a)}}))},Yf=async({queries:t,catalog:e,documents:n,read:r,runtimeAssets:o,assetReferences:s,assetValueReferences:i})=>{let a=Array.from({length:t.length}),{filterKeys:c,preparedQueries:u,sortGroups:p}=Zh({inputs:t,catalog:e,results:a});if(n.length>k.candidateDocuments)return Wf({preparedQueries:u,results:a,createReason:()=>new Oe("Asset query document limit was exceeded")}),Qs(a);let l;try{l=n.map(d=>pt({value:d,references:i?.[d._id],runtimeAssets:o??{}}))}catch(d){return Wf({preparedQueries:u,results:a,createReason:()=>d}),Qs(a)}Bh({preparedQueries:u,documents:l,filterKeys:c,sortGroups:p,results:a,runtimeAssets:o});let f=_f(o);return await jh({preparedQueries:u,results:a,read:r,assetReferences:s,assetUrls:f}),Qs(a)};var Uh=async t=>await Yu(fe(ot.parse(t)));var Qh=({item:t,field:e,value:n})=>{let r=t;for(let[o,s]of e.entries()){if(o===e.length-1){Object.defineProperty(r,s,{value:n,enumerable:!0,configurable:!0,writable:!0});return}let i=Object.hasOwn(r,s)?r[s]:void 0;if(typeof i=="object"&&i!==null){r=i;continue}let a={};Object.defineProperty(r,s,{value:a,enumerable:!0,configurable:!0,writable:!0}),r=a}},Vh=t=>ss.parse({items:t.rows.map(e=>{let n={};for(let[r,o]of t.fields.entries())Qh({item:n,field:o,value:e[r]});return n}),totalCount:t.totalCount,hasMore:t.hasMore}),Hf=async({queries:t,query:e,assetValueReferences:n,runtimeAssets:r={}})=>{if(t===void 0)return;let o=t[await Uh(ot.parse(e))];if(o===void 0)return;let s=Vh(o),i={...s,items:s.items.map(a=>pt({value:a,references:n?.[a.id],runtimeAssets:r}))};return Js(i),i};var Gh=(t,e)=>e===void 0?$t(t):{async*[Symbol.asyncIterator](){let n=0,r=0;for await(let o of $t(t)){if(r===e.length)return;if(n+o.byteLength<=e.offset){n+=o.byteLength;continue}let s=Math.max(0,e.offset-n),i=Math.min(o.byteLength-s,e.length-r);i>0&&(yield o.subarray(s,s+i),r+=i),n+=o.byteLength}}},Jh=({graph:t,load:e,getCached:n,readFallback:r,signal:o})=>{let s=new Map(t.nodes.map(i=>[i.contentRef,i]));return async(i,a)=>{let c=s.get(i);if(c===void 0){if(r!==void 0)return await r(i,a);throw new Error(`Document content reference ${i} is unavailable`)}let u=Wt({node:c,source:n(c)??await e(c,{signal:o})});return{data:Gh(u.source,a),...a===void 0?{}:{contentLength:a.length}}}},qh=({artifact:t,revision:e,catalog:n,documentGraph:r,inlineDocuments:o,readContent:s})=>{let i=new Map(t.documents.map(w=>[w._id,w])),a=w=>{if(w.indexRevision!==void 0&&w.indexRevision!==e)throw new rn},c=w=>async(E,D)=>{let x=t.contents?.[E];if(x===void 0){let G=w??s;if(G===void 0)throw new Error("Content is not embedded in this database");return await G(E,D)}let O=Tt(x),$=D===void 0?O:O.slice(D.offset,D.offset+D.length);return{data:async function*(){yield $}(),contentLength:$.byteLength}},u=w=>{if(w.status==="rejected")throw w.reason;return w.value},p=async({requests:w,queryContentReader:E,runtimeAssets:D,documents:x=t.documents})=>await Yf({queries:w.map(({query:O})=>O),catalog:n,documents:x,read:c(E),runtimeAssets:D,assetReferences:t.assetReferences,assetValueReferences:t.assetValueReferences}),l=async({request:w,...E})=>u((await p({...E,requests:[w]}))[0]),f=async({requests:w,queryContentReader:E,runtimeAssets:D})=>{let x=Array.from({length:w.length}),O=[];for(let[$,G]of w.entries()){try{a(G);let z=await Hf({queries:t.queries,query:G.query,assetValueReferences:t.assetValueReferences,runtimeAssets:D});if(z!==void 0){x[$]={status:"fulfilled",value:z};continue}}catch(z){x[$]={status:"rejected",reason:z};continue}O.push($)}if(O.length>0){let $=await p({requests:O.map(G=>w[G]),queryContentReader:E,runtimeAssets:D});for(let[G,z]of O.entries())x[z]=$[G]}return x.map($=>{if($===void 0)throw new Error("Content database query was not settled");return $})},d=async(w,E,D)=>u((await f({requests:[w],queryContentReader:E,runtimeAssets:D}))[0]),y=async(...w)=>await d(...w),m=w=>async(E,D)=>{let x=o?.get(E.id);return x!==void 0?{format:"json",revision:E.revision,source:JSON.stringify(x.properties)}:await w(E,D)},h=({graph:w,query:E,runtimeAssets:D})=>Ff({graph:w,query:E}).filter(x=>{let O=i.get(x),$=O===void 0?void 0:pt({value:O,references:t.assetValueReferences?.[x],runtimeAssets:D??{}});return $===void 0?!1:Nt(E.where,G=>{if(!Mf({graph:w,sourceId:x,field:G.field}))return Gs($,G,D?.[x])})!==!1}),b=({rootIds:w,roots:E})=>{let D=new Map(w.flatMap((x,O)=>{let $=ro(E[O]);return $===void 0?[]:[[x,$]]}));return t.documents.map(x=>{let O=D.get(x._id);return O===void 0?x:rs.parse({...x,properties:O})})},S=async({request:w,graph:E,resolutionSession:D,contentReader:x,runtimeAssets:O,onEvent:$})=>{a(w);let G=ot.parse(w.query),z=h({graph:E,query:G,runtimeAssets:O});if(z.length===0)return await d(w,x,O);let yt=Zf({graph:E,query:G,rootIds:z});se($,{type:"roots-selected",rootCount:z.length});let lo=await D.resolve({graph:yt,rootIds:z,onEvent:$,allowUnresolvedReferences:!0,transformDocument:({node:od,document:sd})=>Fs({document:sd,references:t.assetValueReferences?.[od.id],runtimeAssets:O})}),fo=b({rootIds:z,roots:lo.roots});return await l({request:w,queryContentReader:x,runtimeAssets:O,documents:fo})},A=async({requests:w,load:E,resolutionSession:D,readContent:x,runtimeAssets:O,signal:$,onEvent:G})=>{if(r===void 0)return await f({requests:w,queryContentReader:x,runtimeAssets:O});let z=m(E),yt=D??Tf({load:z,concurrency:k.concurrentContentReads,signal:$}),lo=Jh({graph:r,load:z,getCached:yt.getCached,readFallback:x??s,signal:$});return await Promise.allSettled(w.map(fo=>S({request:fo,graph:r,resolutionSession:yt,contentReader:lo,runtimeAssets:O,onEvent:G})))};return{query:y,queryManyWithDocumentGraph:A,queryWithDocumentGraph:async({request:w,...E})=>u((await A({...E,requests:[w]}))[0])}};var qs=({artifact:t,readContent:e})=>{let n=Bf({artifact:t});return qh({artifact:t,revision:t.revision,documentGraph:n?.graph,inlineDocuments:n?.inlineDocuments,readContent:e})};var uo=class extends Error{constructor(e,n){super(e,n),this.name="AssetQueryRequestError"}},Qn=class extends Error{},Kh=async(t,e)=>{if(Number.isSafeInteger(e)===!1||e<0)throw new TypeError("Request byte limit must be a non-negative integer");let n=Number(t.headers.get("content-length"));if(Number.isFinite(n)&&n>e)throw new Qn("Request exceeds the byte limit");let r=t.body?.getReader(),o=[],s=0;if(r!==void 0)for(;;){let{done:c,value:u}=await r.read();if(c)break;if(s+=u.byteLength,s>e){try{await r.cancel()}catch{}throw new Qn("Request exceeds the byte limit")}o.push(u)}let i=new Uint8Array(s),a=0;for(let c of o)i.set(c,a),a+=c.byteLength;return i},Xf=async t=>{let e;try{e=await Kh(t,k.requestBytes)}catch(n){throw n instanceof Qn?new uo("Asset query request exceeds the byte limit",{cause:n}):n}try{return ml.parse(JSON.parse(le(e)))}catch(n){throw new uo("Asset query request is invalid",{cause:n})}};var ed=t=>{if(t instanceof rn)return{code:"STALE_INDEX",message:t.message,retryable:!1,status:409};if(t instanceof Un)return{code:t.code,message:t.message,retryable:!1,details:{matchedCount:t.matchedCount},status:409};if(t instanceof Oe)return{code:"INVALID_REQUEST",message:t.message,retryable:!1,status:400};if(t instanceof ie)return{code:t.code,message:t.message,retryable:!1,details:t.details,status:400};let e=new Set,n=t;for(;n!==void 0&&e.has(n)===!1;){if(n instanceof At){let r={};for(let[o,s]of Object.entries({assetId:n.documentId,documentCount:n.documentCount,documentLimit:n.documentLimit,contentByteLimit:n.contentByteLimit,totalBytes:n.totalBytes,totalByteLimit:n.totalByteLimit}))s!==void 0&&(r[o]=s);return{code:"CONTENT_LIMIT_EXCEEDED",message:n.message,retryable:!1,details:r,status:400}}if(n instanceof jn)return{code:"CONTENT_LIMIT_EXCEEDED",message:n.message,retryable:!1,details:{assetId:n.documentId,contentByteLimit:n.contentByteLimit},status:400};e.add(n),n=n instanceof Error?n.cause:void 0}};var Wh="/$resources/assets",td=(t,e=200)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json; charset=utf-8"}}),Vn=({code:t,message:e,status:n,retryable:r=!1,details:o})=>td(gl({code:t,message:e,retryable:r,details:o}),n),Yh=(t,e,n)=>typeof t=="string"||t instanceof URL?new Request(new URL(t,e),n):new Request(t,n),Hh=async({deploymentId:t,artifact:e,request:n})=>{let r=await n.clone().text(),o=n.headers.get("cache-control"),s=await es(JSON.stringify([t,e.revision,r,o])),i=new URL(n.url);return i.searchParams.set("ws-asset-resource",s),new Request(i,{method:"GET"})},VD=({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,fetchDocument:s=globalThis.fetch,onDocumentGraphEvent:i})=>{nd({artifact:e,runtimeAssets:n});let a=js();return rd({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,database:qs({artifact:e}),fetchDocument:s,documentCache:a,onDocumentGraphEvent:i})},Xh=({baseUrl:t,runtimeAssets:e,fetchDocument:n,cache:r,onEvent:o})=>Cf({cache:r,onEvent:o,load:vf({fetch:n,getRequest:s=>{let i=e[s.id];if(i===void 0)throw new Error(`Published document URL is unavailable for ${s.id}`);return new URL(i.url,t)},getMetadata:({node:s})=>({format:s.format,revision:s.revision}),onEvent:o})}),nd=({artifact:t,runtimeAssets:e})=>{let n=[t.assetReferences,t.assetValueReferences].flatMap(s=>Object.values(s??{}).flat()).map(({assetId:s})=>s).find(s=>e[s]===void 0);if(n!==void 0)throw new Error(`Published referenced asset URL is unavailable for ${n}`);let r=t.documentGraph?.nodes.find(({id:s})=>e[s]===void 0)?.id;if(r!==void 0)throw new Error(`Published document URL is unavailable for ${r}`);let o=t.documentGraph?.nodes.find(({id:s,contentRef:i})=>e[s]?.contentRef!==i)?.id;if(o!==void 0)throw new Error(`Published document identity does not match graph node ${o}`)},rd=({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,database:s,fetchDocument:i,documentCache:a,onDocumentGraphEvent:c})=>{let u=new URL(o).origin,p=Xh({baseUrl:o,runtimeAssets:n,fetchDocument:i,cache:a,onEvent:c});return async(l,f)=>{let d=Yh(l,o,f),y=new URL(d.url);if(y.origin!==u||y.pathname!==Wh||d.method.toUpperCase()!=="POST")return;let m;try{m=await Xf(d.clone())}catch{return Vn({code:"INVALID_REQUEST",message:"Asset resource request is invalid",status:400})}let h=r===void 0||d.headers.has("cache-control")===!1?void 0:await Hh({deploymentId:t,artifact:e,request:d});if(h!==void 0&&r!==void 0){let b=await r.match(h).catch(()=>{});if(b!==void 0)return new Response(b.body,b)}try{if(d.signal.aborted)return Vn({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let b=td(await s.queryWithDocumentGraph({request:m,load:p,runtimeAssets:n,signal:d.signal,onEvent:c}));return h!==void 0&&r!==void 0&&d.signal.aborted===!1&&(b.headers.set("cache-control",d.headers.get("cache-control")),await r.put(h,b.clone()).catch(()=>{})),b}catch(b){if(d.signal.aborted)return Vn({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let S=ed(b);return Vn(S!==void 0?S:{code:"INTERNAL_ERROR",message:"Published asset query failed",status:500,retryable:!0})}}},GD=({deploymentId:t,artifact:e,runtimeAssets:n,onDocumentGraphEvent:r=void 0})=>{let o=globalThis.caches,s,i=()=>(s??=o.open(`webstudio-assets-${t}`),s),a=o===void 0?void 0:{match:async p=>(await i()).match(p),put:async(p,l)=>(await i()).put(p,l)};nd({artifact:e,runtimeAssets:n});let c=qs({artifact:e}),u=js();return async({request:p,fallback:l})=>{let f=new URL(p.url).origin,d=rd({deploymentId:t,artifact:e,runtimeAssets:n,cache:a,baseUrl:f,database:c,fetchDocument:l,documentCache:u,onDocumentGraphEvent:r});return async(y,m)=>await d(y,m)??l(y,m)}};export{GD as createGeneratedAssetResourceRuntime,VD as createPublishedAssetResourceFetch};+`,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 gh(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new St||null,prettyErrors:e}}function Ls(t,e={}){let{lineCounter:n,prettyErrors:r}=gh(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}},bf=t=>Ce(JSON.stringify(t)),gf=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},wf=(t,e)=>{if(gf(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(gf(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(bf(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]),_f=Wt.byteLength+10,_h=(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(_h(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 xh={bytes:k.frontmatterBytes,depth:k.frontmatterDepth,fields:k.frontmatterFields,stringBytes:k.frontmatterStringBytes,serializedBytes:k.indexedPropertiesBytes},xf=t=>{try{return le(t)}catch{throw new Y("FRONTMATTER_DECODING_FAILED","Markdown frontmatter is not valid UTF-8")}},Eh=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"),Ef=(t,e)=>{let n=new St,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 wf(o,e)}catch(s){throw s instanceof Ie?Eh(s):s}};var Sf=async(t,e={})=>{let n={...xh,...e},r=n.bytes+_f,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=xf(p.subarray(y.yamlStart,y.yamlEnd));return{properties:Ef(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=xf(i.subarray(a.yamlStart,a.yamlEnd));return{properties:Ef(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 dt=class extends Error{code;referenceId;constructor({code:e,message:n,referenceId:r,cause:o}){super(n,{cause:o}),this.name="MarkdownDocumentError",this.code=e,this.referenceId=r}},Sh=O({source:v(),body:v(),frontmatter:Ee(v(),nt())}),to=t=>{let e;try{e=Sh.parse(t)}catch(n){throw new dt({code:"INVALID_DOCUMENT",message:"Markdown document is invalid",cause:n})}return Object.freeze({source:e.source,body:e.body,frontmatter:rt(e.frontmatter)})},eo="#frontmatter",Ah=t=>`${eo}${t.slice(1)}`,vh=t=>{if(t!==eo&&t.startsWith(`${eo}/`)===!1)throw new dt({code:"UNUSED_REFERENCE",message:`Resolved Markdown reference ${t} is outside frontmatter`,referenceId:t});return`#${t.slice(eo.length)}`},Dh=t=>{let e=t.referenceId===void 0?void 0:Ah(t.referenceId),n="INVALID_DOCUMENT";throw(t.code==="INVALID_REFERENCE_MARKER"||t.code==="INVALID_REFERENCE"||t.code==="REFERENCE_NOT_FOUND"||t.code==="INVALID_RESOLVED_VALUE"||t.code==="UNUSED_REFERENCE")&&(n=t.code),new dt({code:n,message:t.message,referenceId:e,cause:t})},Af=async({source:t,maximumBytes:e=k.hydratedFileBytes})=>{let n;try{n=await Te(t,e)}catch(i){throw i instanceof se?new dt({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 dt({code:"CONTENT_DECODING_FAILED",message:"Markdown document is not valid UTF-8",cause:i})}let[o,s]=await Promise.all([Hr(n,e),Sf(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 vf=({document:t,references:e,allowUnresolvedReferences:n=!1})=>{let r=to(t),o=new Map;for(let[i,a]of e)o.set(vh(i),a);let s;try{s=gr({document:r.frontmatter,references:o,allowUnresolvedReferences:n})}catch(i){throw i instanceof de&&Dh(i),i}return to({...r,frontmatter:s})},Df=({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 dt({code:"UNSUPPORTED_REPRESENTATION",message:`Markdown documents do not support ${e.type}`})};var Rf=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})}},Rh=({reference:t,runtimeAsset:e})=>{let{url:n,contentRef:r,...o}=e;return{...o,id:t.assetId,src:no(n,t.suffix)}},pt=({value:t,references:e,runtimeAssets:n={},assetUrls:r})=>{let o=t;for(let s of e??[]){let i=r?.[s.assetId],a=n[s.assetId]??(i===void 0?void 0:{url:i});a!==void 0&&(o=Ms({value:o,path:s.path,replacement:s.structured===!0?Rh({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=pt({value:{properties:r},references:e,runtimeAssets:n}).properties;return t.format==="json"?Object.freeze({...t,value:o}):Object.freeze({...t,value:Object.freeze({...t.value,frontmatter:o})})},ro=t=>Object.freeze(t),kf=async({format:t,source:e,maximumBytes:n=k.hydratedFileBytes})=>ro(t==="json"?{format:t,value:await vl({source:e,maximumBytes:n})}:{format:t,value:await Af({source:e,maximumBytes:n})});var If=({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:vf({document:t.value,references:e,allowUnresolvedReferences:n})}),Of=({document:t,representation:e})=>t.format==="json"?Dl({document:t.value,representation:e}):Df({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{}},Cf=({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 kh=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}},Tf=({fetch:t,getRequest:e,getMetadata:n,onEvent:r})=>Cf({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=kh.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:el(u)})},onEvent:r});var en=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,$f=new Set,Zs=typeof process=="object"&&process?process:{},zf=(t,e,n,r)=>{typeof Zs.emitWarning=="function"?Zs.emitWarning(t,e,n,r):console.error(`[${n}] ${e}: ${t}`)},io=globalThis.AbortController,Nf=globalThis.AbortSignal;if(typeof io>"u"){Nf=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},io=class{constructor(){e()}signal=new Nf;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,zf("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 Ih=t=>!$f.has(t),vv=Symbol("type"),mt=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Pf=t=>mt(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?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=Pf(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&&!mt(n))throw new TypeError("max option must be a nonnegative integer");let D=n?Pf(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&&!mt(this.#f))throw new TypeError("maxSize must be a positive integer if specified");if(!mt(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#B()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!S,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!a,this.ttlResolution=mt(o)||o===0?o:1,this.ttlAutopurge=!!s,this.ttl=r||0,this.ttl){if(!mt(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#z()}if(this.#c===0&&this.ttl===0&&this.#f===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#c&&!this.#f){let E="LRU_CACHE_UNBOUNDED";Ih(E)&&($f.add(E),zf("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(!mt(o))if(s){if(typeof s!="function")throw new TypeError("sizeCalculation must be a function");if(o=s(r,n),!mt(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#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]),Oh=t=>{if(typeof t!="object"||t===null)return!1;let e=t;return sl(e.format)&&typeof e.revision=="string"&&e.revision.length>0&&e.bytes instanceof Uint8Array},Lf=t=>Object.freeze({format:t.format,revision:t.revision,source:t.bytes}),Mf=({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(Oh(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}),Lf(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 Lf(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})},Ff=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 At=class extends Error{code;documentId;documentCount;documentLimit;contentByteLimit;totalBytes;totalByteLimit;constructor({code:e,message:n,documentId:r,documentCount:o,documentLimit:s,contentByteLimit:i,totalBytes:a,totalByteLimit:c,cause:u}){super(n,{cause:u}),this.name="DocumentResolutionLimitError",this.code=e,this.documentId=r,this.documentCount=o,this.documentLimit=s,this.contentByteLimit=i,this.totalBytes=a,this.totalByteLimit=c}},Ch=(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()}}},Th=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 At({code:"DOCUMENT_COUNT_EXCEEDED",message:"Document graph resolution exceeds the document limit",documentCount:l,documentLimit:s});let p=0,y=Promise.resolve(),m=await Ff({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 At({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 At({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})=>Of({document:g,representation:h.representation}),assemble:({node:h,source:g,references:x})=>{let S=If({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}},Zf=({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=Ch(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:()=>(_??=kf({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 Th({...f,concurrency:e,maximumBytes:r,signal:n,load:d})})};var Bf=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},jf=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",...Al(e)]}catch{return}},Uf=(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},Qf=({queryPaths:t,referenceId:e})=>{let n=jf(e);return n!==void 0&&(t==="all"||t.some(r=>Uf(r,n)))},Vf=({graph:t,sourceId:e,field:n})=>n[0]!=="properties"?!1:t.edges.some(r=>{if(r.sourceId!==e)return!1;let o=jf(r.referenceId);return o!==void 0&&Uf(n,o)}),Gf=({graph:t,query:e})=>{let n=Bf(e),r=new Set;for(let o of t.edges)Qf({queryPaths:n,referenceId:o.referenceId})&&r.add(o.sourceId);return[...r]},qf=({graph:t,query:e,rootIds:n})=>{let r=Bf(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)&&Qf({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 Jf=({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 Kf=({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}},Nh=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())},$h=t=>typeof t.mimeType=="string"&&(t.mimeType.startsWith("text/")||["application/json","application/javascript","application/xml","image/svg+xml"].includes(t.mimeType)),zh=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}},Ph=t=>{try{return le(t)}catch{throw new X({code:"CONTENT_DECODING_FAILED",message:"Selected asset content is not valid UTF-8"})}},Lh=(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},Wf=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}})},Yf=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=Nh(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($h(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:Lh(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&&Wf(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 zh({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=Kf({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=Ph(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&&Wf(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 fD=v().datetime({offset:!0}).transform(t=>new Date(t).toISOString());var Mh=/^[A-Za-z_][A-Za-z0-9_]*$/,Xf=(t,e)=>Mh.test(e)?`${t}.${e}`:`${t}[${JSON.stringify(e)}]`;var Hf=({document:t,includes:e})=>{let n={};for(let r of yl){let o=t[r];o!==void 0&&e(r)&&(n[r]=o)}return n},ht=Symbol("missing property selection"),Us=(t,e)=>{if(e.some(r=>r.length===0)||typeof 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 ht;let o=t.map(s=>Us(s,r));return o.some(s=>s!==ht)?o.map(s=>s===ht?null:s):ht}if(typeof t!="object"||t===null)return ht;let n={};for(let[r,o]of Object.entries(t)){let s=e.filter(([a])=>a===r).map(a=>a.slice(1));if(s.length===0)continue;let i=Us(o,s);i!==ht&&(n[r]=i)}return Object.keys(n).length===0?ht:n},ed=({properties:t,fields:e})=>{let n=e.filter(([o])=>o==="properties").map(o=>o.slice(1)),r=Us(t,n);return r===ht?{}:r};var 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=Xf(e,n);return e},td=({filter:t,fieldTypes:e})=>wl(e).includes(t.operator),Vs=(t,e)=>t!==void 0&&Object.hasOwn(t.fields,e)?t.fields[e]:void 0,Fh=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"},Zh=({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}},nd=({filter:t,fieldTypes:e,path:n})=>{let r=Zh({operator:t.operator,fieldTypes:e});return r===void 0?[]:(t.operator==="in"?t.value:[t.value]).flatMap((s,i)=>r.some(a=>a===Fh(s))?[]:[t.operator==="in"?[...n,"value",String(i)]:[...n,"value"]])},qs=(t,e=["query","where"])=>"field"in t?[{filter:t,path:e}]:"all"in t?t.all.flatMap((n,r)=>qs(n,[...e,"all",String(r)])):t.any.flatMap((n,r)=>qs(n,[...e,"any",String(r)])),Bh=({query:t,catalog:e})=>{let n=ot.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 qs(r.where)){let l=Qs(u.field);if(o.set(l,u.field),u.field[0]==="properties"){let f=Vs(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&&td({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 nd({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(td({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 nd({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=Vs(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,d]of r.output.fields.entries()){let l=Qs(d);o.set(l,d),d[0]==="properties"&&e!==void 0&&Vs(e,l)===void 0&&a("UNOBSERVED_FIELD",["query","output","fields",String(u)],`Asset field ${l} is not currently observed`)}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}},jh=({query:t,catalog:e})=>{let n=Bh({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}},Js=(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},Uh=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)},Ks=(t,e,n)=>{let r=Js(t,e.field,n);if(e.operator==="exists")return r!=null===e.value;if(e.operator==="isEmpty")return Uh(r)===e.value;if(e.operator==="eq")return _n(r,e.value);if(e.operator==="ne")return _n(r,e.value)===!1;if(e.operator==="in")return e.value.some(s=>_n(r,s));if(e.operator==="contains")return typeof r=="string"&&typeof e.value=="string"?r.includes(e.value):Array.isArray(r)&&r.some(s=>_n(s,e.value));if(e.operator==="startsWith")return typeof r=="string"&&typeof e.value=="string"&&r.startsWith(e.value);if(e.operator==="endsWith")return typeof r=="string"&&typeof e.value=="string"&&r.endsWith(e.value);let o=Qh(r,e.value);return o===void 0?!1:e.operator==="gt"?o>0:e.operator==="gte"?o>=0:e.operator==="lt"?o<0:o<=0},Vh=({document:t,where:e,runtimeAsset:n,filterKeys:r,filterResults:o})=>Nt(e,s=>{let i=r.get(s)??fe(s),a=o.get(i);if(a!==void 0)return a;let c=Ks(t,s,n);return o.set(i,c),c})===!0,Gh=({document:t,content:e})=>{if(e.mode!=="markdown-body-ref")return!0;let n=t.mimeType===void 0?void 0:il(t.mimeType);return n==="markdown"||n==="mdx"?!0:t.extension==="md"||t.extension==="mdx"},qh=(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))},Jh=({left:t,right:e,sort:n,runtimeAssets:r})=>{for(let o of n){let s=qh(Js(t,o.field,r?.[t._id]),Js(e,o.field,r?.[e._id]));if(s!==0)return o.direction==="asc"?s:-s}return Ne(t._id,e._id)};var Kh=(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=ed({properties:t.properties,fields:e.fields});return Object.keys(n).length===0?void 0:n},rn=(t,e)=>t.includeMetadata&&gl(e)||t.mode==="fields"&&t.fields.some(n=>n.length===1&&n[0]===e),Wh=t=>t.mode==="all"||t.mode==="fields"&&t.fields.some(e=>e.length===1&&e[0]==="excerpt"),Yh=(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=Kh(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}:{},...Hf({document:t,includes:s=>rn(e,s)}),...r===void 0?{}:{properties:r},...t.excerpt===void 0||Wh(e)===!1?{}:{excerpt:t.excerpt},...t.metadataError===void 0||e.includeMetadata===!1?{}:{metadataError:t.metadataError}}},Ws=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}},Xh=({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=jh({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}},rd=({preparedQueries:t,results:e,createReason:n})=>{for(let{index:r}of t)uo(e,r,n())},Gs=t=>t.map(e=>{if(e===void 0)throw new Error("Asset query result was not settled");return e}),Hh=({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(Gh({document:i,content:d.content})===!1||Vh({document:i,where:d.where,runtimeAsset:a,filterKeys:n,filterResults:c})===!1)continue;let l=Yh(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)=>Jh({left:a,right:c,sort:i.sort,runtimeAssets:s}))},ey=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 Yf({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};Ws(f),e[s.index]={status:"fulfilled",value:f}}catch(a){uo(e,s.index,a)}}))},od=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}=Xh({inputs:t,catalog:e,results:a});if(n.length>k.candidateDocuments)return rd({preparedQueries:u,results:a,createReason:()=>new we("Asset query document limit was exceeded",{code:"CONTENT_LIMIT_EXCEEDED",details:{documentCount:n.length,documentLimit:k.candidateDocuments}})}),Gs(a);let l;try{l=n.map(p=>pt({value:p,references:i?.[p._id],runtimeAssets:o??{}}))}catch(p){return rd({preparedQueries:u,results:a,createReason:()=>p}),Gs(a)}Hh({preparedQueries:u,documents:l,filterKeys:c,sortGroups:d,results:a,runtimeAssets:o});let f=Rf(o);return await ey({preparedQueries:u,results:a,read:r,assetReferences:s,assetUrls:f}),Gs(a)};var ty=async t=>await nl(fe(ot.parse(t)));var ny=({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}},ry=t=>ss.parse({items:t.rows.map(e=>{let n={};for(let[r,o]of t.fields.entries())ny({item:n,field:o,value:e[r]});return n}),totalCount:t.totalCount,hasMore:t.hasMore}),sd=async({queries:t,query:e,assetValueReferences:n,runtimeAssets:r={}})=>{if(t===void 0)return;let o=t[await ty(ot.parse(e))];if(o===void 0)return;let s=ry(o),i={...s,items:s.items.map(a=>pt({value:a,references:n?.[a.id],runtimeAssets:r}))};return Ws(i),i};var oy=(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}}},sy=({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:oy(u.source,a),...a===void 0?{}:{contentLength:a.length}}}},iy=({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=$t(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 od({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 sd({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})=>Gf({graph:w,query:A}).filter(E=>{let C=i.get(E),P=C===void 0?void 0:pt({value:C,references:t.assetValueReferences?.[E],runtimeAssets:D??{}});return P===void 0?!1:Nt(A.where,G=>{if(!Vf({graph:w,sourceId:E,field:G.field}))return Ks(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=ot.parse(w.query),L=h({graph:A,query:G,runtimeAssets:C});if(L.length===0)return await p(w,E,C);let yt=qf({graph:A,query:G,rootIds:L});ae(P,{type:"roots-selected",rootCount:L.length});let lo=await D.resolve({graph:yt,rootIds:L,onEvent:P,allowUnresolvedReferences:!0,transformDocument:({node:dd,document:pd})=>Fs({document:pd,references:t.assetValueReferences?.[dd.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),yt=D??Zf({load:L,concurrency:k.concurrentContentReads,signal:P}),lo=sy({graph:r,load:L,getCached:yt.getCached,readFallback:E??s,signal:P});return await Promise.allSettled(w.map(fo=>x({request:fo,graph:r,resolutionSession:yt,contentReader:lo,runtimeAssets:C,onEvent:G})))};return{query:y,queryManyWithDocumentGraph:S,queryWithDocumentGraph:async({request:w,...A})=>u((await S({...A,requests:[w]}))[0])}};var Ys=({artifact:t,readContent:e})=>{let n=Jf({artifact:t});return iy({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{},ay=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},id=async t=>{let e;try{e=await ay(t,k.requestBytes)}catch(n){throw n instanceof Vn?new sn("Asset query request exceeds the byte limit",{cause:n}):n}try{return _l.parse(JSON.parse(le(e)))}catch(n){throw new sn("Asset query request is invalid",{cause:n})}};var ad=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 Su)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}},cd=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 At){let r={};for(let[o,s]of Object.entries({assetId:n.documentId,documentCount:n.documentCount,documentLimit:n.documentLimit,contentByteLimit:n.contentByteLimit,totalBytes:n.totalBytes,totalByteLimit:n.totalByteLimit}))s!==void 0&&(r[o]=s);return{code:"CONTENT_LIMIT_EXCEEDED",message:n.message,retryable:!1,details:r,status:400}}if(n instanceof 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 cy="/$resources/assets",ud=(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})=>ud(Sl({code:t,message:e,retryable:r,details:o}),n),uy=(t,e,n)=>typeof t=="string"||t instanceof URL?new Request(new URL(t,e),n):new Request(t,n),ly=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"})},iR=({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,fetchDocument:s=globalThis.fetch,onDocumentGraphEvent:i})=>{ld({artifact:e,runtimeAssets:n});let a=js();return fd({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,database:Ys({artifact:e}),fetchDocument:s,documentCache:a,onDocumentGraphEvent:i})},fy=({baseUrl:t,runtimeAssets:e,fetchDocument:n,cache:r,onEvent:o})=>Mf({cache:r,onEvent:o,load:Tf({fetch:n,getRequest:s=>{let i=e[s.id];if(i===void 0)throw new Error(`Published document URL is unavailable for ${s.id}`);return new URL(i.url,t)},getMetadata:({node:s})=>({format:s.format,revision:s.revision}),onEvent:o})}),ld=({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}`)},fd=({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=fy({baseUrl:o,runtimeAssets:n,fetchDocument:i,cache:a,onEvent:c});return async(l,f)=>{let p=uy(l,o,f),y=new URL(p.url);if(y.origin!==u||y.pathname!==cy||p.method.toUpperCase()!=="POST")return;let m;try{m=await id(p.clone())}catch(g){let x=ad(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 ly({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=ud(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=cd(g);return an(x!==void 0?x:{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)};ld({artifact:e,runtimeAssets:n});let c=Ys({artifact:e}),u=js();return async({request:d,fallback:l})=>{let f=new URL(d.url).origin,p=fd({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{aR as createGeneratedAssetResourceRuntime,iR as createPublishedAssetResourceFetch};diff --git a/packages/asset-uploader/src/asset-repository.test.ts b/packages/asset-uploader/src/asset-repository.test.tsindex fdf62bba29..ab55aebbd1 100644--- a/packages/asset-uploader/src/asset-repository.test.ts+++ b/packages/asset-uploader/src/asset-repository.test.ts@@ -627,6 +627,74 @@ describe("PostgresAssetRepository", () => {});+ test("discards preparation warnings from an abandoned uncached snapshot", async () => {+ const dependencies = createDependencies();+ const initial: CanonicalAssetFileEntry = {+ projectId: "project-1",+ assetId: "removed",+ revision: "removed-r1",+ document: {+ _id: "removed",+ _type: "asset.file",+ name: "removed.md",+ path: "content/removed.md",+ key: "removed",+ extension: "md",+ mimeType: "text/markdown",+ size: 10,+ revision: "removed-r1",+ contentRef: "storage:removed",+ properties: {},+ },+ };+ dependencies.loadCanonicalAssetBaseEntries+ .mockResolvedValueOnce([initial])+ .mockResolvedValue([]);+ dependencies.synchronizeCanonicalAssets.mockResolvedValue({+ scanned: 1,+ indexed: 0,+ metadataUpdated: 0,+ unchanged: 0,+ removed: 0,+ skipped: 1,+ inconsistent: 0,+ issues: [+ {+ assetId: "removed",+ storageName: "storage:removed",+ revision: "removed-r1",+ message: "Object is missing",+ },+ ],+ });+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: assetClient,+ dependencies,+ });++ const result = await repository.query({+ query: {+ where: {+ field: ["properties", "title"],+ operator: "eq",+ value: "Healthy",+ },+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["id"]],+ },+ },+ });++ expect(result.data.items).toEqual([]);+ expect(result.__diagnostics__.issues).toBeUndefined();+ expect(dependencies.synchronizeCanonicalAssets).toHaveBeenCalledOnce();+ });+test("creates a base-only index without synchronizing or reading content", async () => {const dependencies = createDependencies();const entries = [@@ -1931,12 +1999,16 @@ describe("PostgresAssetRepository", () => {}))).rejects.toMatchObject({- name: "AssetIndexPreparationError",- issues: [- expect.objectContaining({+ name: "DocumentSourceDiagnosticsError",+ diagnostics: [+ {+ severity: "error",+ phase: "source",+ code: "MARKDOWN_BODY_DECODING_FAILED",+ message: "Markdown content is not valid UTF-8",assetId: "post",- message: "Selected asset content is not valid UTF-8",- }),+ path: "blog/post.md",+ },],});});@@ -1999,7 +2071,7 @@ describe("PostgresAssetRepository", () => {expect(dependencies.loadCanonicalAssetFileEntries).not.toHaveBeenCalled();});- test("keeps healthy indexed assets readable when another asset is broken", async () => {+ test("keeps unrelated broken assets out of query diagnostics", async () => {const dependencies = createDependencies();dependencies.synchronizeCanonicalAssets.mockResolvedValue({scanned: 2,@@ -2018,7 +2090,26 @@ describe("PostgresAssetRepository", () => {},],});- dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([]);+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([+ {+ projectId: "project-1",+ assetId: "broken",+ revision: "revision-broken",+ document: {+ _id: "broken",+ _type: "asset.file",+ name: "broken.md",+ path: "broken.md",+ key: "broken",+ extension: "md",+ mimeType: "text/markdown",+ size: 4,+ revision: "revision-broken",+ contentRef: "broken.md",+ properties: {},+ },+ },+ ]);dependencies.loadCanonicalAssetFileEntries.mockResolvedValue([]);dependencies.createAssetIndex.mockImplementation(createAssetIndex);const repository = new PostgresAssetRepository({@@ -2028,14 +2119,43 @@ describe("PostgresAssetRepository", () => {dependencies,});- await expect(- repository.query({- query: {- where: { all: [] },- output: { mode: "base", includeMetadata: true },+ const request = {+ query: {+ where: {+ all: [+ {+ field: ["properties", "title"],+ operator: "eq",+ value: "Healthy",+ },+ ],},- })- ).resolves.toMatchObject({ data: { items: [] } });+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["id"]],+ },+ },+ } satisfies Parameters<typeof repository.query>[0];+ const result = await repository.query(request);+ const cachedResult = await repository.query(request);++ expect(result).toMatchObject({+ data: { items: [] },+ __diagnostics__: {+ queryIssues: [+ expect.objectContaining({+ severity: "warning",+ code: "UNOBSERVED_FIELD",+ }),+ ],+ },+ });+ expect(result.__diagnostics__.issues).toBeUndefined();+ expect(cachedResult.__diagnostics__.queryIssues).toEqual(+ result.__diagnostics__.queryIssues+ );+ expect(dependencies.createAssetIndex).toHaveBeenCalledTimes(2);});test("updates metadata without eagerly maintaining query fields", async () => {@@ -2168,6 +2288,10 @@ describe("PostgresAssetRepository", () => {revision,contentRef: "post.md",properties: { title: "New post" },+ metadataError: {+ code: "FRONTMATTER_INVALID",+ message: "Invalid YAML in post.md",+ },},};const otherEntry = {@@ -2183,6 +2307,7 @@ describe("PostgresAssetRepository", () => {revision: "revision-2",contentRef: "other.md",properties: { title: "Other post" },+ metadataError: undefined,},};dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([@@ -2263,6 +2388,19 @@ describe("PostgresAssetRepository", () => {omittedDocumentCount: 0,truncated: false,},+ issues: [+ {+ severity: "warning",+ scope: "query",+ phase: "metadata",+ code: "FRONTMATTER_INVALID",+ message: "Invalid YAML in post.md",+ assetId: "asset-1",+ path: "post.md",+ },+ ],+ issueCount: 1,+ issuesTruncated: false,});expect(result.__diagnostics__.database.usedBytes).toBeGreaterThan(result.__diagnostics__.query.usedBytes@@ -2317,6 +2455,36 @@ describe("PostgresAssetRepository", () => {);expect(dependencies.loadAssetsByProjectWithClient).not.toHaveBeenCalled();+ const unobservedFieldResult = await repository.query({+ query: {+ where: {+ all: [+ {+ field: ["properties", "subtitle"],+ operator: "exists",+ value: false,+ },+ ],+ },+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["id"]],+ },+ },+ });+ expect(unobservedFieldResult.__diagnostics__.queryWarnings).toEqual([+ "Asset field properties.subtitle is not currently observed",+ ]);+ expect(unobservedFieldResult.__diagnostics__.queryIssues).toEqual([+ {+ severity: "warning",+ code: "UNOBSERVED_FIELD",+ path: ["query", "where", "all", "0", "field"],+ message: "Asset field properties.subtitle is not currently observed",+ },+ ]);+vi.mocked(assetClient.readFile).mockImplementation(async () => ({data: new Blob(["# New post"]).stream(),contentLength: 10,@@ -2368,6 +2536,802 @@ describe("PostgresAssetRepository", () => {});});+ test("reports every MDX error matched by a query without content output", async () => {+ const dependencies = createDependencies();+ const brokenSource = "<ws.element";+ const entries = ["one", "two"].map(+ (id): CanonicalAssetFileEntry => ({+ projectId: "project-1",+ assetId: id,+ revision: `${id}-r1`,+ document: {+ _id: id,+ _type: "asset.file",+ name: `${id}.mdx`,+ path: `content/${id}.mdx`,+ key: id,+ extension: "mdx",+ mimeType: "text/mdx",+ size: new TextEncoder().encode(brokenSource).byteLength,+ revision: `${id}-r1`,+ contentRef: `storage:${id}`,+ properties: {},+ },+ })+ );+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue(entries);+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue(entries);+ dependencies.loadCanonicalAssetFileEntriesForRecovery.mockResolvedValue({+ entries,+ inconsistentRows: [],+ });+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: {+ readFile: async () => ({+ data: new Blob([brokenSource]).stream(),+ contentLength: brokenSource.length,+ }),+ },+ dependencies,+ });++ await expect(+ repository.query({+ query: {+ where: { all: [] },+ limit: 2,+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["id"]],+ },+ content: { mode: "none" },+ },+ })+ ).rejects.toMatchObject({+ diagnostics: [+ { severity: "error", path: "content/one.mdx" },+ { severity: "error", path: "content/two.mdx" },+ ],+ });+ });++ test("validates every matching file before pagination", async () => {+ const dependencies = createDependencies();+ const brokenSource = "<ws.element";+ const entries: CanonicalAssetFileEntry[] = [+ {+ projectId: "project-1",+ assetId: "image",+ revision: "image-r1",+ document: {+ _id: "image",+ _type: "asset.file",+ name: "a.png",+ path: "content/a.png",+ key: "a",+ extension: "png",+ mimeType: "image/png",+ size: 1,+ revision: "image-r1",+ contentRef: "storage:image",+ properties: {},+ metadataError: {+ code: "FRONTMATTER_INVALID",+ message: "Image metadata could not be indexed",+ },+ },+ },+ {+ projectId: "project-1",+ assetId: "broken",+ revision: "broken-r1",+ document: {+ _id: "broken",+ _type: "asset.file",+ name: "b.mdx",+ path: "content/b.mdx",+ key: "b",+ extension: "mdx",+ mimeType: "text/mdx",+ size: brokenSource.length,+ revision: "broken-r1",+ contentRef: "storage:broken",+ properties: {},+ metadataError: {+ code: "FRONTMATTER_INVALID",+ message: "Broken metadata could not be indexed",+ },+ },+ },+ ];+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue(entries);+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue(entries);+ dependencies.loadCanonicalAssetFileEntriesForRecovery.mockResolvedValue({+ entries,+ inconsistentRows: [],+ });+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);+ const readFile = vi.fn(async () => ({+ data: new Blob([brokenSource]).stream(),+ contentLength: brokenSource.length,+ }));+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: { readFile },+ dependencies,+ });+ const query = {+ where: { all: [] },+ sort: [{ field: ["name"] as ["name"], direction: "asc" as const }],+ limit: 1,+ output: {+ mode: "fields" as const,+ includeMetadata: false,+ fields: [["id"] as ["id"]],+ },+ content: { mode: "none" as const },+ };++ await expect(repository.query({ query })).rejects.toMatchObject({+ diagnostics: [+ { severity: "warning", path: "content/a.png" },+ { severity: "warning", path: "content/b.mdx" },+ { severity: "error", path: "content/b.mdx" },+ ],+ });+ expect(readFile).toHaveBeenCalled();++ await expect(+ repository.query({ query: { ...query, offset: 1 } })+ ).rejects.toMatchObject({+ diagnostics: [+ { severity: "warning", path: "content/a.png" },+ { severity: "warning", path: "content/b.mdx" },+ { severity: "error", path: "content/b.mdx" },+ ],+ });+ });++ test("excludes diagnostics from files outside the query", async () => {+ const dependencies = createDependencies();+ const sources = {+ "storage:included": "# Included\n",+ "storage:unrelated": "<ws.element",+ } as const;+ const entries: CanonicalAssetFileEntry[] = [+ {+ projectId: "project-1",+ assetId: "included",+ revision: "included-r1",+ document: {+ _id: "included",+ _type: "asset.file",+ name: "included.md",+ path: "content/included.md",+ key: "included",+ extension: "md",+ mimeType: "text/markdown",+ size: sources["storage:included"].length,+ revision: "included-r1",+ contentRef: "storage:included",+ properties: {},+ },+ },+ {+ projectId: "project-1",+ assetId: "unrelated",+ revision: "unrelated-r1",+ document: {+ _id: "unrelated",+ _type: "asset.file",+ name: "unrelated.mdx",+ path: "content/unrelated.mdx",+ key: "unrelated",+ extension: "mdx",+ mimeType: "text/mdx",+ size: sources["storage:unrelated"].length,+ revision: "unrelated-r1",+ contentRef: "storage:unrelated",+ properties: {},+ metadataError: {+ code: "FRONTMATTER_INVALID",+ message: "Unrelated metadata is invalid",+ },+ },+ },+ ];+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue(entries);+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue(entries);+ dependencies.loadCanonicalAssetFileEntriesForRecovery.mockResolvedValue({+ entries,+ inconsistentRows: [],+ });+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);+ const readFile = vi.fn(async (contentRef: string) => ({+ data: new Blob([sources[contentRef as keyof typeof sources]]).stream(),+ contentLength: sources[contentRef as keyof typeof sources].length,+ }));+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: { readFile },+ dependencies,+ });++ const result = await repository.query(+ {+ query: {+ where: { field: ["id"], operator: "eq", value: "included" },+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["id"]],+ },+ content: { mode: "none" },+ },+ },+ {+ diagnosticsPlan: createCompilationPlan({+ where: { all: [] },+ output: { mode: "all", includeMetadata: true },+ }),+ }+ );++ expect(result.__diagnostics__.issues).toBeUndefined();+ expect(readFile).not.toHaveBeenCalledWith("storage:unrelated");+ });++ test("keeps source warnings when one matching document reference is invalid", async () => {+ const dependencies = createDependencies();+ const sources = {+ "storage:warning": "{1 + 1}",+ "storage:broken": '{"author":{"$ref":"./missing.md#frontmatter"}}',+ } as const;+ const entries: CanonicalAssetFileEntry[] = [+ {+ projectId: "project-1",+ assetId: "warning",+ revision: "warning-r1",+ document: {+ _id: "warning",+ _type: "asset.file",+ name: "warning.mdx",+ path: "content/warning.mdx",+ key: "warning",+ extension: "mdx",+ mimeType: "text/mdx",+ size: sources["storage:warning"].length,+ revision: "warning-r1",+ contentRef: "storage:warning",+ properties: {},+ },+ },+ {+ projectId: "project-1",+ assetId: "broken",+ revision: "broken-r1",+ document: {+ _id: "broken",+ _type: "asset.file",+ name: "broken.json",+ path: "content/broken.json",+ key: "broken",+ extension: "json",+ mimeType: "application/json",+ size: sources["storage:broken"].length,+ revision: "broken-r1",+ contentRef: "storage:broken",+ properties: {+ author: { $ref: "./missing.md#frontmatter" },+ },+ },+ },+ ];+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue(entries);+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue(entries);+ dependencies.loadCanonicalAssetFileEntriesForRecovery.mockResolvedValue({+ entries,+ inconsistentRows: [],+ });+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: {+ readFile: async (contentRef: string) => ({+ data: new Blob([+ sources[contentRef as keyof typeof sources],+ ]).stream(),+ contentLength: sources[contentRef as keyof typeof sources].length,+ }),+ },+ dependencies,+ });++ await expect(+ repository.query({+ query: {+ where: { all: [] },+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["properties", "author"]],+ },+ content: { mode: "full" },+ },+ })+ ).rejects.toMatchObject({+ diagnostics: expect.arrayContaining([+ expect.objectContaining({+ severity: "warning",+ code: "unsafe-mdx",+ assetId: "warning",+ path: "content/warning.mdx",+ }),+ expect.objectContaining({+ severity: "error",+ code: "TARGET_NOT_FOUND",+ assetId: "broken",+ path: "content/broken.json",+ reference: "#/author",+ }),+ ]),+ });+ });++ test("ignores one unrelated saved-plan reference failure", async () => {+ const dependencies = createDependencies();+ const sources = {+ "storage:included": "# Included\n",+ "storage:unrelated": '{"author":{"$ref":"./missing.md#frontmatter"}}',+ } as const;+ const entries: CanonicalAssetFileEntry[] = [+ {+ projectId: "project-1",+ assetId: "included",+ revision: "included-r1",+ document: {+ _id: "included",+ _type: "asset.file",+ name: "included.md",+ path: "content/included.md",+ key: "included",+ extension: "md",+ mimeType: "text/markdown",+ size: sources["storage:included"].length,+ revision: "included-r1",+ contentRef: "storage:included",+ properties: {},+ },+ },+ {+ projectId: "project-1",+ assetId: "unrelated",+ revision: "unrelated-r1",+ document: {+ _id: "unrelated",+ _type: "asset.file",+ name: "unrelated.json",+ path: "content/unrelated.json",+ key: "unrelated",+ extension: "json",+ mimeType: "application/json",+ size: sources["storage:unrelated"].length,+ revision: "unrelated-r1",+ contentRef: "storage:unrelated",+ properties: {+ author: { $ref: "./missing.md#frontmatter" },+ },+ },+ },+ ];+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue(entries);+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue(entries);+ dependencies.loadCanonicalAssetFileEntriesForRecovery.mockResolvedValue({+ entries,+ inconsistentRows: [],+ });+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: {+ readFile: async (contentRef: string) => ({+ data: new Blob([+ sources[contentRef as keyof typeof sources],+ ]).stream(),+ contentLength: sources[contentRef as keyof typeof sources].length,+ }),+ },+ dependencies,+ });++ const result = await repository.query(+ {+ query: {+ where: { field: ["id"], operator: "eq", value: "included" },+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["id"]],+ },+ content: { mode: "none" },+ },+ },+ {+ diagnosticsPlan: createCompilationPlan({+ where: { field: ["id"], operator: "eq", value: "unrelated" },+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["properties", "author"]],+ },+ }),+ }+ );++ expect(result.data).toMatchObject({+ items: [{ id: "included" }],+ });+ expect(result.__diagnostics__.issues).toBeUndefined();+ });++ test("validates the file returned by a single-result query", async () => {+ const dependencies = createDependencies();+ const brokenSource = "<ws.element";+ const entry: CanonicalAssetFileEntry = {+ projectId: "project-1",+ assetId: "broken",+ revision: "broken-r1",+ document: {+ _id: "broken",+ _type: "asset.file",+ name: "broken.mdx",+ path: "content/broken.mdx",+ key: "broken",+ extension: "mdx",+ mimeType: "text/mdx",+ size: brokenSource.length,+ revision: "broken-r1",+ contentRef: "storage:broken",+ properties: {},+ },+ };+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([entry]);+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue([entry]);+ dependencies.loadCanonicalAssetFileEntriesForRecovery.mockResolvedValue({+ entries: [entry],+ inconsistentRows: [],+ });+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: {+ readFile: async () => ({+ data: new Blob([brokenSource]).stream(),+ contentLength: brokenSource.length,+ }),+ },+ dependencies,+ });++ await expect(+ repository.query({+ query: {+ result: "one",+ where: { field: ["id"], operator: "eq", value: "broken" },+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["id"]],+ },+ content: { mode: "none" },+ },+ })+ ).rejects.toMatchObject({+ diagnostics: [{ severity: "error", path: "content/broken.mdx" }],+ });+ });++ test("shows the file when diagnostics cannot read its content", async () => {+ const dependencies = createDependencies();+ const entry: CanonicalAssetFileEntry = {+ projectId: "project-1",+ assetId: "post",+ revision: "post-r1",+ document: {+ _id: "post",+ _type: "asset.file",+ name: "post.md",+ path: "content/post.md",+ key: "post",+ extension: "md",+ mimeType: "text/markdown",+ size: 10,+ revision: "post-r1",+ contentRef: "storage:post",+ properties: {},+ },+ };+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([entry]);+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue([entry]);+ dependencies.loadCanonicalAssetFileEntriesForRecovery.mockResolvedValue({+ entries: [entry],+ inconsistentRows: [],+ });+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: {+ readFile: vi.fn().mockRejectedValue(new Error("Object is missing")),+ },+ dependencies,+ });++ const result = await repository.query({+ query: {+ where: { field: ["id"], operator: "eq", value: "post" },+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["id"]],+ },+ },+ });++ expect(result.__diagnostics__.issues).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ severity: "warning",+ code: "CONTENT_READ_FAILED",+ message: "Object is missing",+ assetId: "post",+ path: "content/post.md",+ }),+ ])+ );+ });++ test("returns fatal UTF-8 diagnostics from the shared byte validator", async () => {+ const dependencies = createDependencies();+ const entry: CanonicalAssetFileEntry = {+ projectId: "project-1",+ assetId: "invalid-utf8",+ revision: "invalid-utf8-r1",+ document: {+ _id: "invalid-utf8",+ _type: "asset.file",+ name: "invalid.md",+ path: "content/invalid.md",+ key: "invalid",+ extension: "md",+ mimeType: "text/markdown",+ size: 2,+ revision: "invalid-utf8-r1",+ contentRef: "storage:invalid-utf8",+ properties: {},+ },+ };+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([entry]);+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue([entry]);+ dependencies.loadCanonicalAssetFileEntriesForRecovery.mockResolvedValue({+ entries: [entry],+ inconsistentRows: [],+ });+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: {+ readFile: async () => ({+ data: new Blob([new Uint8Array([0xc3, 0x28])]).stream(),+ contentLength: 2,+ }),+ },+ dependencies,+ });++ await expect(+ repository.query({+ query: {+ where: { field: ["id"], operator: "eq", value: "invalid-utf8" },+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["id"]],+ },+ content: { mode: "none" },+ },+ })+ ).rejects.toMatchObject({+ diagnostics: [+ {+ severity: "error",+ phase: "source",+ code: "MARKDOWN_BODY_DECODING_FAILED",+ message: "Markdown content is not valid UTF-8",+ assetId: "invalid-utf8",+ path: "content/invalid.md",+ },+ ],+ });+ });++ test("preserves complete nonfatal MDX diagnostics", async () => {+ const dependencies = createDependencies();+ const source = "{1 + 1}";+ const entry: CanonicalAssetFileEntry = {+ projectId: "project-1",+ assetId: "unsafe-mdx",+ revision: "unsafe-mdx-r1",+ document: {+ _id: "unsafe-mdx",+ _type: "asset.file",+ name: "unsafe.mdx",+ path: "content/unsafe.mdx",+ key: "unsafe",+ extension: "mdx",+ mimeType: "text/mdx",+ size: source.length,+ revision: "unsafe-mdx-r1",+ contentRef: "storage:unsafe-mdx",+ properties: {},+ },+ };+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([entry]);+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue([entry]);+ dependencies.loadCanonicalAssetFileEntriesForRecovery.mockResolvedValue({+ entries: [entry],+ inconsistentRows: [],+ });+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: {+ readFile: async () => ({+ data: new Blob([source]).stream(),+ contentLength: source.length,+ }),+ },+ dependencies,+ });++ const result = await repository.query({+ query: {+ where: {+ field: ["extension"],+ operator: "contains",+ value: "mdx",+ },+ output: {+ mode: "all",+ includeMetadata: false,+ },+ content: { mode: "none" },+ },+ });++ expect(result.data.items).toEqual([{ id: "unsafe-mdx" }]);+ expect(result.__diagnostics__.issues).toEqual([+ expect.objectContaining({+ severity: "warning",+ code: "unsafe-mdx",+ assetId: "unsafe-mdx",+ path: "content/unsafe.mdx",+ nodeType: "mdxFlowExpression",+ reason: "Executable MDX expressions are not supported",+ sourceRange: {+ start: { line: 1, column: 1, offset: 0 },+ end: { line: 1, column: 8, offset: 7 },+ },+ }),+ ]);+ });++ test("keeps exact content read warnings when another file is fatal", async () => {+ const dependencies = createDependencies();+ const brokenSource = "<ws.element";+ const entries: CanonicalAssetFileEntry[] = [+ {+ projectId: "project-1",+ assetId: "missing",+ revision: "missing-r1",+ document: {+ _id: "missing",+ _type: "asset.file",+ name: "missing.md",+ path: "content/missing.md",+ key: "missing",+ extension: "md",+ mimeType: "text/markdown",+ size: 10,+ revision: "missing-r1",+ contentRef: "storage:missing",+ properties: {},+ },+ },+ {+ projectId: "project-1",+ assetId: "broken",+ revision: "broken-r1",+ document: {+ _id: "broken",+ _type: "asset.file",+ name: "broken.mdx",+ path: "content/broken.mdx",+ key: "broken",+ extension: "mdx",+ mimeType: "text/mdx",+ size: brokenSource.length,+ revision: "broken-r1",+ contentRef: "storage:broken",+ properties: {},+ },+ },+ ];+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue(entries);+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue(entries);+ dependencies.loadCanonicalAssetFileEntriesForRecovery.mockResolvedValue({+ entries,+ inconsistentRows: [],+ });+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: {+ readFile: async (contentRef) => {+ if (contentRef === "storage:missing") {+ throw new Error("Object is missing");+ }+ return {+ data: new Blob([brokenSource]).stream(),+ contentLength: brokenSource.length,+ };+ },+ },+ dependencies,+ });++ await expect(+ repository.query({+ query: {+ where: { all: [] },+ limit: 2,+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["id"]],+ },+ content: { mode: "none" },+ },+ })+ ).rejects.toMatchObject({+ diagnostics: expect.arrayContaining([+ expect.objectContaining({+ severity: "warning",+ code: "CONTENT_READ_FAILED",+ message: "Object is missing",+ path: "content/missing.md",+ }),+ expect.objectContaining({+ severity: "error",+ code: "invalid-mdx",+ path: "content/broken.mdx",+ }),+ ]),+ });+ });+test("assembles document graph references in local query preview", async () => {const dependencies = createDependencies();const postSource =diff --git a/packages/asset-uploader/src/asset-repository.ts b/packages/asset-uploader/src/asset-repository.tsindex 2b27891761..f4b2fe63e1 100644--- a/packages/asset-uploader/src/asset-repository.ts+++ b/packages/asset-uploader/src/asset-repository.ts@@ -1,22 +1,27 @@import {assetQuery,+ AssetResourceHydrationError,contentEngineLimits,createContentCompilationPlan,createContentFieldCatalogCompilationPlan,createDocumentResolutionSession,createLiteralContentCompilationQuery,getContentArtifactRuntimeAssetIds,+ getAssetQueryErrorDiagnosticIssue,getDocumentFormatByContentType,+ DocumentSourceCompilationAggregateError,isAssetQueryCoveredByCompilationPlan,isContentDocumentCandidate,prepareContentCompilerEntries,requiresRuntimeDocumentData,requiresStructuredProperties,+ validateAssetQueryAgainstCatalog,type AssetQueryRequestInput,type AssetQueryPreviewResult,type AssetQueryExecutionPreviewResult,type AssetQuery,type AssetQueryExecutionResult,+ type AssetQueryDiagnosticIssue,type AssetRuntimeData,type BuilderAssetFieldCatalog,type ContentArtifactV1,@@ -35,6 +40,7 @@ import {materializeContentSource,materializeContentSnapshot,ContentSourceChangedError,+ DocumentSourceDiagnosticsError,readBoundedBytes,serializeJsonDeterministically,toBuilderAssetFieldCatalog,@@ -106,6 +112,8 @@ import {type AssetQueryPerformancePhase,} from "./query-performance";import type { AssetContentRead as SharedAssetContentRead } from "@webstudio-is/content-engine/asset-content-repository";+import { validateTextAssetSourceBytes } from "@webstudio-is/content-engine/mdx";+import { removeMetadataIssuesDuplicatedBySource } from "./diagnostic-utils";type CreateId = () => Asset["id"];type RepositoryObjectStore = AssetObjectReader & Partial<AssetObjectWriter>;@@ -115,6 +123,119 @@ type ContentBytesReference = {revision: string;};+type PreparedDiagnosticIssue = Omit<AssetQueryDiagnosticIssue, "scope">;+type DiagnosticIssueIdentity = Pick<+ AssetQueryDiagnosticIssue,+ | "severity"+ | "code"+ | "assetId"+ | "path"+ | "line"+ | "column"+ | "reference"+ | "nodeType"+ | "reason"+ | "sourceRange"+ | "message"+> &+ Partial<Pick<AssetQueryDiagnosticIssue, "phase">>;++const diagnosticIssuesByArtifact = new WeakMap<+ ContentArtifactV1,+ readonly PreparedDiagnosticIssue[]+>();+const diagnosticPathsByArtifact = new WeakMap<+ ContentArtifactV1,+ ReadonlyMap<string, string>+>();++const getDiagnosticIssueKey = (issue: DiagnosticIssueIdentity) =>+ JSON.stringify([+ issue.severity,+ issue.phase,+ issue.code,+ issue.assetId,+ issue.path,+ issue.line,+ issue.column,+ issue.reference,+ issue.nodeType,+ issue.reason,+ issue.sourceRange,+ issue.message,+ ]);++const getPreparedDiagnosticIssues = ({+ entries,+ assetReferenceIssues,+ sourceIssues,+ preparationIssues,+}: {+ entries: Parameters<typeof createAssetIndex>[0]["entries"];+ assetReferenceIssues: Awaited<+ ReturnType<typeof materializeContentSource>+ >["assetReferenceIssues"];+ sourceIssues: Awaited<+ ReturnType<typeof materializeContentSource>+ >["sourceIssues"];+ preparationIssues: readonly PreparedDiagnosticIssue[];+}): PreparedDiagnosticIssue[] => {+ const pathsById = new Map(+ entries.map(({ assetId, document }) => [assetId, document.path])+ );+ const metadataIssues = removeMetadataIssuesDuplicatedBySource({+ metadataIssues: entries.flatMap(({ assetId, document }) =>+ document.metadataError === undefined+ ? []+ : [+ {+ severity: "warning" as const,+ phase: "metadata" as const,+ code: document.metadataError.code,+ message: document.metadataError.message,+ assetId,+ path: document.path,+ ...(document.metadataError.reason === undefined+ ? {}+ : { reason: document.metadataError.reason }),+ ...(document.metadataError.line === undefined+ ? {}+ : { line: document.metadataError.line }),+ ...(document.metadataError.column === undefined+ ? {}+ : { column: document.metadataError.column }),+ },+ ]+ ),+ sourceIssues,+ });+ const referenceIssues = assetReferenceIssues.flatMap((issue) => {+ const path = pathsById.get(issue.sourceDocumentId);+ return path === undefined+ ? []+ : [+ {+ severity: "warning" as const,+ phase: "reference" as const,+ code: issue.code,+ message: `Referenced asset was not found: ${issue.assetUrl}`,+ assetId: issue.sourceDocumentId,+ path,+ reference: issue.assetUrl,+ },+ ];+ });+ const issues = [...metadataIssues, ...referenceIssues, ...preparationIssues];+ issues.push(+ ...sourceIssues.map((issue) => ({ ...issue, phase: "source" as const }))+ );+ return [+ ...new Map(+ issues.map((issue) => [getDiagnosticIssueKey(issue), issue])+ ).values(),+ ];+};+class RequestContentBytesCache {private values = new Map<string, Uint8Array>();private byteLength = 0;@@ -203,6 +324,29 @@ type AssetQueryPreviewOptions = {};type AssetQueryResultOnly = { data: AssetQueryExecutionResult };++const getAssetQueryResultIds = (result: AssetQueryExecutionResult) =>+ "items" in result+ ? result.items.map(({ id }) => id)+ : result.item === null+ ? []+ : [result.item.id];++const createAssetQueryDiagnosticMatchQuery = (+ query: AssetQuery+): AssetQuery => ({+ ...query,+ result: "many",+ limit: contentEngineLimits.candidateDocuments,+ offset: 0,+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["id"]],+ },+ content: { mode: "none" },+});+type AssetQueryOptionsWithoutDiagnostics = AssetQueryPreviewOptions & {includeDiagnostics: false;};@@ -686,7 +830,60 @@ export class PostgresAssetRepository implements AssetRepository {strict: boolean,contentBytesCache = new RequestContentBytesCache()) {- const source = this.createContentSource(strict, contentBytesCache);+ const preparationIssues: PreparedDiagnosticIssue[] = [];+ const preservePreparationIssues = async <Value>(+ operation: () => Promise<Value>+ ) => {+ try {+ return await operation();+ } catch (error) {+ if (error instanceof DocumentSourceCompilationAggregateError) {+ const diagnostics = error.errors.flatMap((nestedError) => {+ const diagnostic = getAssetQueryErrorDiagnosticIssue({+ error: nestedError,+ });+ return diagnostic === undefined ? [] : [diagnostic];+ });+ if (diagnostics.length === error.errors.length) {+ throw new DocumentSourceDiagnosticsError([+ ...preparationIssues,+ ...diagnostics,+ ]);+ }+ }+ const diagnostic = getAssetQueryErrorDiagnosticIssue({ error });+ if (diagnostic !== undefined) {+ throw new DocumentSourceDiagnosticsError([+ ...new Map(+ [...preparationIssues, diagnostic].map((issue) => [+ getDiagnosticIssueKey(issue),+ issue,+ ])+ ).values(),+ ]);+ }+ if (+ error instanceof DocumentSourceDiagnosticsError === false ||+ preparationIssues.length === 0+ ) {+ throw error;+ }+ const diagnostics = [+ ...new Map(+ [...preparationIssues, ...error.diagnostics].map((diagnostic) => [+ getDiagnosticIssueKey(diagnostic),+ diagnostic,+ ])+ ).values(),+ ];+ throw new DocumentSourceDiagnosticsError(diagnostics, error.scope);+ }+ };+ const source = this.createContentSource(+ strict,+ contentBytesCache,+ preparationIssues+ );const compile = async (entries: Parameters<typeof createAssetIndex>[0]["entries"],assetReferences: Parameters<@@ -695,9 +892,15 @@ export class PostgresAssetRepository implements AssetRepository {assetValueReferences: Parameters<typeof createAssetIndex>[0]["assetValueReferences"],- documentGraph: Parameters<typeof createAssetIndex>[0]["documentGraph"]- ) =>- await this.measurePerformance(+ documentGraph: Parameters<typeof createAssetIndex>[0]["documentGraph"],+ assetReferenceIssues: Awaited<+ ReturnType<typeof materializeContentSource>+ >["assetReferenceIssues"],+ sourceIssues: Awaited<+ ReturnType<typeof materializeContentSource>+ >["sourceIssues"]+ ) => {+ const artifact = await this.measurePerformance("artifact-compilation",async () =>await this.dependencies.createAssetIndex({@@ -713,24 +916,51 @@ export class PostgresAssetRepository implements AssetRepository {...(requirements === undefined ? {} : { plan: requirements }),}));+ diagnosticIssuesByArtifact.set(+ artifact,+ getPreparedDiagnosticIssues({+ entries,+ assetReferenceIssues,+ sourceIssues,+ preparationIssues,+ })+ );+ diagnosticPathsByArtifact.set(+ artifact,+ new Map(+ entries.map(({ assetId, document }) => [assetId, document.path])+ )+ );+ return artifact;+ };if (this.compilationCache === undefined) {emitAssetQueryPerformanceEvent(this.onPerformanceEvent, {type: "compilation-cache",status: "disabled",});- const { entries, assetReferences, assetValueReferences, documentGraph } =- await materializeContentSource({+ const {+ entries,+ assetReferences,+ assetValueReferences,+ documentGraph,+ assetReferenceIssues,+ sourceIssues,+ } = await preservePreparationIssues(() =>+ materializeContentSource({source,plan: requirements,maximumContentBytes: this.contentDatabaseMaxBytes,onPerformanceEvent: this.onPerformanceEvent,performanceNow: this.dependencies.performanceNow,- });+ })+ );return await compile(entries,assetReferences,assetValueReferences,- documentGraph+ documentGraph,+ assetReferenceIssues,+ sourceIssues);}for (let attempt = 0; attempt < 2; attempt += 1) {@@ -754,18 +984,24 @@ export class PostgresAssetRepository implements AssetRepository {assetReferences,assetValueReferences,documentGraph,- } = await materializeContentSnapshot({- snapshot,- plan: requirements,- maximumContentBytes: this.contentDatabaseMaxBytes,- onPerformanceEvent: this.onPerformanceEvent,- performanceNow: this.dependencies.performanceNow,- });+ assetReferenceIssues,+ sourceIssues,+ } = await preservePreparationIssues(() =>+ materializeContentSnapshot({+ snapshot,+ plan: requirements,+ maximumContentBytes: this.contentDatabaseMaxBytes,+ onPerformanceEvent: this.onPerformanceEvent,+ performanceNow: this.dependencies.performanceNow,+ })+ );return await compile(entries,assetReferences,assetValueReferences,- documentGraph+ documentGraph,+ assetReferenceIssues,+ sourceIssues);});@@ -785,7 +1021,8 @@ export class PostgresAssetRepository implements AssetRepository {private createContentSource(strict: boolean,- contentBytesCache = new RequestContentBytesCache()+ contentBytesCache = new RequestContentBytesCache(),+ preparationIssues: PreparedDiagnosticIssue[] = []): ContentSource {const readFile = this.assetStore.readFile;const onPerformanceEvent = this.onPerformanceEvent;@@ -797,6 +1034,9 @@ export class PostgresAssetRepository implements AssetRepository {});return {openSnapshot: async () => {+ // Each snapshot must report only issues observed during its own+ // preparation, including when uncached materialization retries.+ preparationIssues.length = 0;const baseEntries = await loadBaseEntries();const revision = await computeCanonicalAssetRevision(baseEntries);return {@@ -863,6 +1103,7 @@ export class PostgresAssetRepository implements AssetRepository {strict,maximumContentBytes: options?.maximumContentBytes,contentBytesCache,+ preparationIssues,}),isCurrent: async () =>(await computeCanonicalAssetRevision(await loadBaseEntries())) ===@@ -878,12 +1119,14 @@ export class PostgresAssetRepository implements AssetRepository {strict,maximumContentBytes,contentBytesCache,+ preparationIssues,}: {baseEntries: Awaited<ReturnType<typeof loadCanonicalAssetBaseEntries>>;requirements?: ContentCompilationPlan;strict: boolean;maximumContentBytes?: number;contentBytesCache: RequestContentBytesCache;+ preparationIssues: PreparedDiagnosticIssue[];}) {const candidateBaseEntries =requirements === undefined@@ -939,6 +1182,19 @@ export class PostgresAssetRepository implements AssetRepository {if (strict && result.issues.length > 0) {throw new AssetIndexPreparationError(result.issues);}+ const pathsById = new Map(+ baseEntries.map(({ assetId, document }) => [assetId, document.path])+ );+ for (const issue of result.issues) {+ preparationIssues.push({+ severity: "warning",+ phase: "metadata",+ code: "METADATA_PREPARATION_FAILED",+ message: issue.message,+ assetId: issue.assetId,+ path: pathsById.get(issue.assetId) ?? issue.storageName,+ });+ }return await this.dependencies.loadCanonicalAssetFileEntries({client: this.context.postgrest.client,projectId: this.projectId,@@ -947,41 +1203,116 @@ export class PostgresAssetRepository implements AssetRepository {});}- return await this.measurePerformance(+ const byteSourceDiagnostics: PreparedDiagnosticIssue[] = [];+ const preparedEntries = await this.measurePerformance("compiler-entries",async () =>await prepareContentCompilerEntries({entries,plan: requirements,loadContent: async (entry) => {- const startedAt = this.dependencies.performanceNow();- const response = await this.assetStore.readFile(- entry.document.contentRef,- { offset: 0, length: entry.document.size }- );- const bytes = await readBoundedBytes(- response.data,- entry.document.size- );- if (bytes.byteLength !== entry.document.size) {- throw new Error(- "Asset content does not match its canonical size"- );- }- contentBytesCache.set({+ let bytes = contentBytesCache.get({contentRef: entry.document.contentRef,revision: entry.revision,- bytes,- });- emitAssetQueryPerformanceEvent(this.onPerformanceEvent, {- type: "content-read",- purpose: "compiler-entry",- byteLength: bytes.byteLength,- durationMs: Math.max(- 0,- this.dependencies.performanceNow() - startedAt- ),});+ if (bytes === undefined) {+ const startedAt = this.dependencies.performanceNow();+ try {+ const response = await this.assetStore.readFile(+ entry.document.contentRef,+ { offset: 0, length: entry.document.size }+ );+ bytes = await readBoundedBytes(+ response.data,+ entry.document.size+ );+ if (bytes.byteLength !== entry.document.size) {+ throw new Error(+ "Asset content does not match its canonical size"+ );+ }+ } catch (error) {+ const message =+ error instanceof Error && error.message !== ""+ ? error.message+ : "Selected asset content could not be read";+ if (strict) {+ throw new AssetIndexPreparationError([+ {+ assetId: entry.assetId,+ storageName: entry.document.contentRef,+ revision: entry.revision,+ message,+ },+ ]);+ }+ preparationIssues.push({+ severity: "warning",+ phase: "source",+ code: "CONTENT_READ_FAILED",+ message,+ assetId: entry.assetId,+ path: entry.document.path,+ });+ return;+ }+ contentBytesCache.set({+ contentRef: entry.document.contentRef,+ revision: entry.revision,+ bytes,+ });+ emitAssetQueryPerformanceEvent(this.onPerformanceEvent, {+ type: "content-read",+ purpose: "compiler-entry",+ byteLength: bytes.byteLength,+ durationMs: Math.max(+ 0,+ this.dependencies.performanceNow() - startedAt+ ),+ });+ }+ const documentFormat = getDocumentFormatByContentType(+ entry.document.mimeType+ );+ if (documentFormat === "markdown" || documentFormat === "mdx") {+ const validation = await validateTextAssetSourceBytes({+ source: bytes,+ format: documentFormat === "markdown" ? "md" : "mdx",+ });+ byteSourceDiagnostics.push(+ ...validation.diagnostics.map((diagnostic) => ({+ severity: diagnostic.severity,+ phase: "source" as const,+ code: diagnostic.code,+ message: diagnostic.message,+ assetId: entry.assetId,+ path: entry.document.path,+ ...("nodeType" in diagnostic &&+ diagnostic.nodeType !== undefined+ ? { nodeType: diagnostic.nodeType }+ : {}),+ ...("reason" in diagnostic && diagnostic.reason !== undefined+ ? { reason: diagnostic.reason }+ : {}),+ ...("sourceRange" in diagnostic &&+ diagnostic.sourceRange !== undefined+ ? {+ line: diagnostic.sourceRange.start.line,+ column: diagnostic.sourceRange.start.column,+ sourceRange: diagnostic.sourceRange,+ }+ : "line" in diagnostic && diagnostic.line !== undefined+ ? {+ line: diagnostic.line,+ ...(diagnostic.column === undefined+ ? {}+ : { column: diagnostic.column }),+ }+ : {}),+ }))+ );+ return validation.source;+ }let content: string;try {content = decodeUtf8(bytes);@@ -996,6 +1327,14 @@ export class PostgresAssetRepository implements AssetRepository {},]);}+ preparationIssues.push({+ severity: "warning",+ phase: "metadata",+ code: "CONTENT_DECODING_FAILED",+ message: "Selected asset content is not valid UTF-8",+ assetId: entry.assetId,+ path: entry.document.path,+ });return;}return content;@@ -1003,6 +1342,11 @@ export class PostgresAssetRepository implements AssetRepository {maximumContentBytes,}));+ preparationIssues.push(...byteSourceDiagnostics);+ if (byteSourceDiagnostics.some(({ severity }) => severity === "error")) {+ throw new DocumentSourceDiagnosticsError(byteSourceDiagnostics);+ }+ return preparedEntries;}async readFieldCatalog() {@@ -1266,6 +1610,26 @@ export class PostgresAssetRepository implements AssetRepository {): Promise<AssetQueryExecutionPreviewResult | AssetQueryResultOnly> {signal?.throwIfAborted();const contentBytesCache = new RequestContentBytesCache();+ const executeDocumentGraphQuery = async <Result>({+ artifact,+ operation,+ }: {+ artifact: ContentArtifactV1;+ operation: () => Promise<Result>;+ }) => {+ try {+ return await operation();+ } catch (error) {+ const diagnostic = getAssetQueryErrorDiagnosticIssue({+ error,+ pathsByAssetId: diagnosticPathsByArtifact.get(artifact),+ });+ if (diagnostic !== undefined) {+ throw new DocumentSourceDiagnosticsError([diagnostic]);+ }+ throw error;+ }+ };const query = assetQuery.parse(request.query);const plan = createContentCompilationPlan([createLiteralContentCompilationQuery({ id: "preview", query }),@@ -1287,6 +1651,39 @@ export class PostgresAssetRepository implements AssetRepository {);signal?.throwIfAborted();const database = getContentDatabaseForArtifact(index);+ const contentRevisions = new Map(+ index.documents.flatMap((document) =>+ typeof document.contentRef === "string" &&+ typeof document.revision === "string"+ ? [[document.contentRef, document.revision] as const]+ : []+ )+ );+ const readQueryContent = async (+ contentRef: string,+ range?: AssetReadRange+ ) => {+ const revision = contentRevisions.get(contentRef);+ const cachedBytes =+ revision === undefined+ ? undefined+ : contentBytesCache.get({ contentRef, revision });+ if (cachedBytes === undefined) {+ return await this.assetStore.readFile(contentRef, range);+ }+ const bytes =+ range === undefined+ ? cachedBytes+ : cachedBytes.subarray(range.offset, range.offset + range.length);+ return {+ contentLength: bytes.byteLength,+ data: {+ async *[Symbol.asyncIterator]() {+ yield bytes;+ },+ },+ };+ };const queryIndex =includeDiagnostics && usePublishedIndex? await this.prepareIndexAfterAuthorization(@@ -1310,30 +1707,192 @@ export class PostgresAssetRepository implements AssetRepository {): undefined;signal?.throwIfAborted();- const data = await this.measurePerformance("document-resolution", () =>- database.queryWithDocumentGraph({- request,- readContent: this.assetStore.readFile,- runtimeAssets,- load: this.createQueryDocumentLoader(contentBytesCache),- signal,- onEvent: this.onDocumentGraphEvent,- })+ const executeData = () =>+ this.measurePerformance("document-resolution", () =>+ executeDocumentGraphQuery({+ artifact: index,+ operation: () =>+ database.queryWithDocumentGraph({+ request,+ readContent: readQueryContent,+ runtimeAssets,+ load: this.createQueryDocumentLoader(contentBytesCache),+ signal,+ onEvent: this.onDocumentGraphEvent,+ }),+ })+ );+ if (includeDiagnostics === false) {+ const data = await executeData();+ signal?.throwIfAborted();+ return { data };+ }+ const diagnosticMatchQuery = createAssetQueryDiagnosticMatchQuery(query);+ const diagnosticMatchPlan = createContentCompilationPlan([+ createLiteralContentCompilationQuery({+ id: "preview-diagnostic-matches",+ query: diagnosticMatchQuery,+ }),+ ]);+ const diagnosticMatchIndex = await this.prepareIndexAfterAuthorization(+ diagnosticMatchPlan,+ false,+ contentBytesCache);signal?.throwIfAborted();- let publishedIndex: typeof index | undefined;- if (includeDiagnostics) {- const publishedPlan = diagnosticsPlan ?? databasePlan;- if (publishedPlan === undefined) {- publishedIndex = queryIndex;- } else {- const diagnosticsRepository = new PostgresAssetRepository({- projectId: this.projectId,- context: this.context,- assetStore: this.assetStore,- dependencies: this.dependencies,- contentDatabaseMaxBytes: this.contentDatabaseMaxBytes,+ const diagnosticRuntimeAssets = await this.measurePerformance(+ "runtime-assets",+ () =>+ this.loadQueryRuntimeAssets({+ artifact: diagnosticMatchIndex,+ plan: diagnosticMatchPlan,+ })+ );+ signal?.throwIfAborted();+ const diagnosticMatchResult = await this.measurePerformance(+ "document-resolution",+ () =>+ executeDocumentGraphQuery({+ artifact: diagnosticMatchIndex,+ operation: () =>+ getContentDatabaseForArtifact(+ diagnosticMatchIndex+ ).queryWithDocumentGraph({+ request: { query: diagnosticMatchQuery },+ readContent: this.assetStore.readFile,+ runtimeAssets: diagnosticRuntimeAssets,+ load: this.createQueryDocumentLoader(contentBytesCache),+ signal,+ onEvent: this.onDocumentGraphEvent,+ }),+ })+ );+ const matchingIds = getAssetQueryResultIds(diagnosticMatchResult);+ const matchingIdSet = new Set(matchingIds);+ const queryIndexIssues = [+ ...(diagnosticIssuesByArtifact.get(queryIndex) ?? []),+ ...(diagnosticIssuesByArtifact.get(diagnosticMatchIndex) ?? []),+ ].filter((issue) => matchingIdSet.has(issue.assetId));+ let sourceDiagnosticsIndex = queryIndex;+ if (matchingIds.length > 0) {+ const sourceDiagnosticsPlan = createContentCompilationPlan([+ createLiteralContentCompilationQuery({+ id: "preview-source-diagnostics",+ query: {+ result: "many",+ where: {+ all: [+ { field: ["id"], operator: "in", value: matchingIds },+ {+ field: ["extension"],+ operator: "in",+ value: ["md", "markdown", "mdx"],+ },+ ],+ },+ sort: [],+ limit: matchingIds.length,+ offset: 0,+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["id"]],+ },+ content: { mode: "full" },+ },+ }),+ ]);+ try {+ sourceDiagnosticsIndex = await this.prepareIndexAfterAuthorization(+ sourceDiagnosticsPlan,+ false,+ contentBytesCache+ );+ } catch (error) {+ if (error instanceof DocumentSourceDiagnosticsError) {+ const diagnostics = [+ ...queryIndexIssues.map((issue) => ({+ ...issue,+ scope: "query" as const,+ })),+ ...error.diagnostics.map((diagnostic) => ({+ ...diagnostic,+ scope: "query" as const,+ phase: diagnostic.phase ?? ("source" as const),+ })),+ ];+ throw new DocumentSourceDiagnosticsError([+ ...new Map(+ diagnostics.map((diagnostic) => [+ getDiagnosticIssueKey(diagnostic),+ diagnostic,+ ])+ ).values(),+ ]);+ }+ throw error;+ }+ }+ signal?.throwIfAborted();+ const queryIssues = [+ ...new Map(+ [+ ...queryIndexIssues,+ ...(sourceDiagnosticsIndex === queryIndex+ ? []+ : (diagnosticIssuesByArtifact.get(sourceDiagnosticsIndex) ?? [])),+ ].map((issue) => [getDiagnosticIssueKey(issue), issue])+ ).values(),+ ].map((issue) => ({ ...issue, scope: "query" as const }));+ let data: AssetQueryExecutionResult;+ try {+ data = await executeData();+ } catch (error) {+ if (+ error instanceof DocumentSourceDiagnosticsError &&+ queryIssues.length > 0+ ) {+ throw new DocumentSourceDiagnosticsError([+ ...new Map(+ [...queryIssues, ...error.diagnostics].map((diagnostic) => [+ getDiagnosticIssueKey(diagnostic),+ diagnostic,+ ])+ ).values(),+ ]);+ }+ if (+ error instanceof AssetResourceHydrationError &&+ queryIssues.length > 0+ ) {+ const hydrationDiagnostics = Array.isArray(error.details?.diagnostics)+ ? error.details.diagnostics+ : [];+ throw new AssetResourceHydrationError({+ code: error.code,+ message: error.message,+ details: {+ ...error.details,+ diagnostics: [...queryIssues, ...hydrationDiagnostics],+ },});+ }+ throw error;+ }+ signal?.throwIfAborted();+ let publishedIndex: typeof index;+ const publishedPlan = diagnosticsPlan ?? databasePlan;+ if (publishedPlan === undefined) {+ publishedIndex = queryIndex;+ } else {+ const diagnosticsRepository = new PostgresAssetRepository({+ projectId: this.projectId,+ context: this.context,+ assetStore: this.assetStore,+ dependencies: this.dependencies,+ contentDatabaseMaxBytes: this.contentDatabaseMaxBytes,+ });+ try {publishedIndex = await this.measurePerformance("diagnostics-preparation",() =>@@ -1342,6 +1901,14 @@ export class PostgresAssetRepository implements AssetRepository {false));+ } catch (error) {+ if (error instanceof DocumentSourceDiagnosticsError) {+ // Published-plan diagnostics can contain files selected by other+ // resources. Keep this preview scoped to the current query.+ publishedIndex = queryIndex;+ } else {+ throw error;+ }}}signal?.throwIfAborted();@@ -1362,24 +1929,42 @@ export class PostgresAssetRepository implements AssetRepository {...(omissionReason === undefined ? {} : { omissionReason }),truncated,});- if (includeDiagnostics === false) {- return { data };- }- if (publishedIndex === undefined) {- throw new Error("Diagnostics index was not prepared");- }const queryDatabase = getContentDatabaseForArtifact(queryIndex);const publishedDatabase = getContentDatabaseForArtifact(publishedIndex);+ const queryValidation = validateAssetQueryAgainstCatalog({+ query,+ catalog: queryDatabase.getFieldCatalog(),+ });+ // Source diagnostics in this panel belong only to the current query.+ const issues = queryIssues.sort(+ (left, right) =>+ left.path.localeCompare(right.path) ||+ left.code.localeCompare(right.code) ||+ left.message.localeCompare(right.message)+ );return {data,__diagnostics__: {scope: "query-preview",+ ...(queryValidation.warnings.length === 0+ ? {}+ : { queryWarnings: queryValidation.warnings }),+ ...(queryValidation.warningIssues.length === 0+ ? {}+ : { queryIssues: queryValidation.warningIssues }),query: toCapacityStats(queryDatabase.getStats()),database: toCapacityStats(publishedDatabase.getStats()),...(includeUnresolvedDiagnostics? { artifacts: { query: queryIndex, database: publishedIndex } }: {}),...(unresolved === undefined ? {} : { unresolved }),+ ...(issues.length === 0+ ? {}+ : {+ issues,+ issueCount: issues.length,+ issuesTruncated: false,+ }),},};}diff --git a/packages/asset-uploader/src/diagnostic-utils.test.ts b/packages/asset-uploader/src/diagnostic-utils.test.tsnew file mode 100644index 0000000000..e6f3574a1c--- /dev/null+++ b/packages/asset-uploader/src/diagnostic-utils.test.ts@@ -0,0 +1,38 @@+import { expect, test } from "vitest";+import { removeMetadataIssuesDuplicatedBySource } from "./diagnostic-utils";++test("prefers the complete source diagnostic over duplicate cached metadata", () => {+ const metadataIssue = {+ severity: "warning" as const,+ phase: "metadata" as const,+ code: "FRONTMATTER_INVALID",+ message: "Cached metadata error without a reason",+ assetId: "broken",+ path: "broken.md",+ line: 4,+ column: 1,+ };+ const sourceIssue = {+ severity: "warning" as const,+ code: "FRONTMATTER_INVALID",+ message: "Missing closing quote",+ reason: "Missing closing quote",+ assetId: "broken",+ path: "broken.md",+ line: 4,+ column: 1,+ };++ expect(+ removeMetadataIssuesDuplicatedBySource({+ metadataIssues: [metadataIssue],+ sourceIssues: [sourceIssue],+ })+ ).toEqual([]);+ expect(+ removeMetadataIssuesDuplicatedBySource({+ metadataIssues: [metadataIssue],+ sourceIssues: [{ ...sourceIssue, line: 5 }],+ })+ ).toEqual([metadataIssue]);+});diff --git a/packages/asset-uploader/src/diagnostic-utils.ts b/packages/asset-uploader/src/diagnostic-utils.tsnew file mode 100644index 0000000000..7700a73138--- /dev/null+++ b/packages/asset-uploader/src/diagnostic-utils.ts@@ -0,0 +1,34 @@+type SourceDiagnosticIdentity = {+ code: string;+ assetId?: string;+ path: string;+ line?: number;+ column?: number;+};++const getSourceDiagnosticIdentityKey = (issue: SourceDiagnosticIdentity) =>+ JSON.stringify([+ issue.code,+ issue.assetId,+ issue.path,+ issue.line,+ issue.column,+ ]);++export const removeMetadataIssuesDuplicatedBySource = <+ MetadataIssue extends SourceDiagnosticIdentity,+>({+ metadataIssues,+ sourceIssues,+}: {+ metadataIssues: readonly MetadataIssue[];+ sourceIssues: readonly SourceDiagnosticIdentity[];+}) => {+ const sourceIssueKeys = new Set(+ sourceIssues.map(getSourceDiagnosticIdentityKey)+ );+ return metadataIssues.filter(+ (issue) =>+ sourceIssueKeys.has(getSourceDiagnosticIdentityKey(issue)) === false+ );+};diff --git a/packages/cli/src/commands/mcp.test.ts b/packages/cli/src/commands/mcp.test.tsindex 0dd3f07bb5..0a890d2470 100644--- a/packages/cli/src/commands/mcp.test.ts+++ b/packages/cli/src/commands/mcp.test.ts@@ -1,8 +1,10 @@-import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import path from "node:path";import { afterEach, expect, test, vi } from "vitest";import {+ blockComponent,+ blockTemplateComponent,getInputJsonSchemaMetadata,getInputJsonSchemaProperties,} from "@webstudio-is/sdk";@@ -13,6 +15,7 @@ import {listProjectSessionMcpTools,} from "@webstudio-is/project-build/mcp";import { publicApiOperations } from "@webstudio-is/protocol";+import { contentEngineLimits } from "@webstudio-is/content-engine/limits";import { updatePersistedMcpCheckpoint } from "./mcp-checkpoint";import {__testing__,@@ -31,7 +34,10 @@ const {createMcpStatusReporter,getLoadedProjectSessionSnapshot,getMcpOperationInput,- withMdxAssetWriteFeedback,+ prepareTextAssetWriteFeedback,+ withTextAssetWriteFeedback,+ validateDownloadedTextAsset,+ materializeValidatedDownloadedAsset,reportMcpSingleOpCallTermination,reportMcpRunTermination,createMcpRunTerminationController,@@ -776,6 +782,44 @@ test("formats MCP run failures as structured JSON payloads", () => {});});+test("preserves specific nested query errors at single-op and run boundaries", () => {+ const error = {+ code: "BAD_REQUEST",+ message: "The Asset query index changed.",+ data: {+ code: "BAD_REQUEST",+ webstudioCode: "STALE_INDEX",+ issues: [+ {+ code: "STALE_INDEX",+ path: ["indexRevision"],+ message: "Refresh the Asset index and retry.",+ constraint: "current_index_revision",+ },+ ],+ },+ };++ expect(+ createMcpSingleOpCallErrorPayload({ error, elapsedMs: 1 }).error+ ).toMatchObject({+ code: "STALE_INDEX",+ issues: [expect.objectContaining({ path: ["indexRevision"] })],+ });+ expect(+ createMcpRunErrorPayload({+ error,+ completedCalls: 0,+ totalCalls: 1,+ results: [],+ elapsedMs: 1,+ }).error+ ).toMatchObject({+ code: "STALE_INDEX",+ issues: [expect.objectContaining({ path: ["indexRevision"] })],+ });+});+test("reports termination while inserting a styled nested SVG", async () => {const operation = publicApiOperations.find(({ command }) => command === "insert-fragment"@@ -1151,6 +1195,102 @@ test("adapts MCP upload assets input to public API upload input", () => {expect(input).toHaveProperty("readAssetData", expect.any(Function));});+test("rejects every Markdown and MDX upload filename/format mismatch", () => {+ let error: unknown;+ try {+ getMcpOperationInput("upload-assets", {+ assets: [+ { name: "article.txt", type: "file", format: "md", meta: {} },+ { name: "page.mdx", type: "file", format: "md", meta: {} },+ ],+ });+ } catch (caught) {+ error = caught;+ }++ expect(createMcpSingleOpCallErrorPayload({ error, elapsedMs: 1 })).toEqual({+ ok: false,+ error: {+ code: "INVALID_INPUT",+ message: expect.stringContaining("Asset filename and format must match"),+ issues: [+ expect.objectContaining({ path: ["assets", "0", "format"] }),+ expect.objectContaining({ path: ["assets", "1", "format"] }),+ ],+ },+ meta: { elapsedMs: 1 },+ });+});++test("aggregates every invalid upload descriptor field before reading files", () => {+ let error: unknown;+ try {+ getMcpOperationInput("upload-assets", {+ assetsDir: 42,+ assets: [+ { type: "file" },+ {+ name: "article.md",+ type: "image",+ format: "txt",+ extra: true,+ },+ ],+ });+ } catch (caught) {+ error = caught;+ }++ expect(createMcpSingleOpCallErrorPayload({ error, elapsedMs: 1 })).toEqual({+ ok: false,+ error: {+ code: "INVALID_INPUT",+ message: expect.stringContaining("Asset operation input is invalid."),+ issues: expect.arrayContaining([+ expect.objectContaining({ path: ["assetsDir"] }),+ expect.objectContaining({ path: ["assets", "0", "name"] }),+ expect.objectContaining({ path: ["assets", "1", "extra"] }),+ expect.objectContaining({ path: ["assets", "1", "format"] }),+ expect.objectContaining({ path: ["assets", "1", "type"] }),+ ]),+ },+ meta: { elapsedMs: 1 },+ });+});++test("reports every invalid update content selector field", () => {+ let error: unknown;+ try {+ getMcpOperationInput("update-asset-content", {+ assetId: "",+ expectedName: 42,+ path: "article.md",+ content: "# duplicate source",+ extra: true,+ });+ } catch (caught) {+ error = caught;+ }++ expect(createMcpSingleOpCallErrorPayload({ error, elapsedMs: 1 })).toEqual({+ ok: false,+ error: {+ code: "INVALID_INPUT",+ message: expect.stringContaining("Asset operation input is invalid."),+ issues: expect.arrayContaining([+ expect.objectContaining({ path: ["extra"] }),+ expect.objectContaining({ path: ["assetId"] }),+ expect.objectContaining({ path: ["expectedName"] }),+ expect.objectContaining({+ path: [],+ code: "invalid_source_selection",+ }),+ ]),+ },+ meta: { elapsedMs: 1 },+ });+});+test("adapts MCP asset content input to the shared revision client", async () => {const input = getMcpOperationInput("update-asset-content", {assetId: "asset-id",@@ -1181,7 +1321,7 @@ test("returns diagnostics without rejecting an invalid MDX Asset write", async (});await expect(- withMdxAssetWriteFeedback({+ withTextAssetWriteFeedback({command: "update-asset-content",input: {assetId: "asset-id",@@ -1205,6 +1345,574 @@ test("returns diagnostics without rejecting an invalid MDX Asset write", async (});});+test("rejects invalid UTF-8 before an Asset write can start", async () => {+ const assets = [+ { name: "article.md", type: "file", format: "md", meta: {} },+ { name: "page.mdx", type: "file", format: "mdx", meta: {} },+ ];+ const operationInput = {+ assets,+ readAssetData: vi.fn(async () => new Uint8Array([0xc3, 0x28])),+ };++ await expect(+ prepareTextAssetWriteFeedback({+ command: "upload-assets",+ input: { assets },+ operationInput,+ })+ ).rejects.toMatchObject({+ code: "CONTENT_DECODING_FAILED",+ issues: [+ expect.objectContaining({+ code: "MARKDOWN_BODY_DECODING_FAILED",+ path: ["assets", "0", "name"],+ severity: "error",+ }),+ expect.objectContaining({+ code: "invalid-mdx",+ path: ["assets", "1", "name"],+ severity: "error",+ }),+ ],+ });+ expect(operationInput.readAssetData).toHaveBeenCalledTimes(2);+});++test("rejects oversized inline Markdown before an Asset write can start", async () => {+ const input = {+ assetId: "asset-id",+ expectedName: "article_hash.md",+ content: "x".repeat(contentEngineLimits.hydratedFileBytes + 1),+ };++ await expect(+ prepareTextAssetWriteFeedback({+ command: "update-asset-content",+ input,+ operationInput: getMcpOperationInput("update-asset-content", input),+ })+ ).rejects.toMatchObject({+ code: "CONTENT_LIMIT_EXCEEDED",+ issues: [+ expect.objectContaining({+ code: "MARKDOWN_BODY_BYTES_EXCEEDED",+ path: ["content"],+ severity: "error",+ }),+ ],+ });+});++test("returns complete prepared diagnostics after an Asset write", async () => {+ const source = "{run()}";+ const input = {+ assetId: "asset-id",+ expectedName: "article_hash.mdx",+ content: source,+ };+ const operationInput = getMcpOperationInput("update-asset-content", input);+ const feedback = await prepareTextAssetWriteFeedback({+ command: "update-asset-content",+ input,+ operationInput,+ });++ await expect(+ withTextAssetWriteFeedback({+ command: "update-asset-content",+ input,+ operationInput,+ result: { result: { assetId: "asset-id" } },+ feedback,+ })+ ).resolves.toMatchObject({+ result: {+ assetId: "asset-id",+ source,+ diagnostics: [+ {+ code: "unsafe-mdx",+ severity: "warning",+ message: "Executable MDX expressions are not supported",+ nodeType: "mdxFlowExpression",+ reason: "Executable MDX expressions are not supported",+ sourceRange: {+ start: { line: 1, column: 1, offset: 0 },+ end: { line: 1, column: 8, offset: 7 },+ },+ },+ ],+ },+ });+});++test("rejects invalid UTF-8 downloads with the asset identity", async () => {+ await expect(+ validateDownloadedTextAsset({+ assetId: "asset-1",+ path: "/tmp/broken.md",+ format: "md",+ content: new Uint8Array([0xc3, 0x28]),+ })+ ).rejects.toMatchObject({+ code: "CONTENT_DECODING_FAILED",+ assetId: "asset-1",+ path: "/tmp/broken.md",+ issues: [+ expect.objectContaining({+ code: "MARKDOWN_BODY_DECODING_FAILED",+ severity: "error",+ assetId: "asset-1",+ }),+ ],+ });+});++test("materializes validated remote Asset content without overwriting a conflict", async () => {+ const directory = await mkdtemp(+ path.join(tmpdir(), "webstudio-mcp-download-")+ );+ const remotePath = path.join(directory, "remote.md");+ const localPath = path.join(directory, "local", "article.md");+ await writeFile(remotePath, "# Remote");++ await expect(+ materializeValidatedDownloadedAsset({+ assetId: "asset-1",+ remotePath,+ localPath,+ diagnostics: [],+ })+ ).resolves.toEqual(Buffer.from("# Remote"));+ await expect(readFile(localPath, "utf8")).resolves.toBe("# Remote");++ await writeFile(remotePath, "{unsafe()}");+ await expect(+ materializeValidatedDownloadedAsset({+ assetId: "asset-1",+ remotePath,+ localPath,+ diagnostics: [+ {+ code: "unsafe-mdx",+ severity: "warning",+ message: "Executable MDX expressions are not supported",+ nodeType: "mdxFlowExpression",+ reason: "Executable MDX expressions are not supported",+ },+ ],+ })+ ).rejects.toMatchObject({+ code: "CONFLICT",+ assetId: "asset-1",+ path: localPath,+ issues: [+ expect.objectContaining({+ code: "unsafe-mdx",+ assetId: "asset-1",+ file: localPath,+ }),+ expect.objectContaining({+ code: "local_asset_conflict",+ assetId: "asset-1",+ file: localPath,+ }),+ ],+ });+ await expect(readFile(localPath, "utf8")).resolves.toBe("# Remote");++ await rm(directory, { recursive: true, force: true });+});++test("returns every Markdown frontmatter diagnostic after an Asset write", async () => {+ const source = "---\na: 1\na: 2\nb: 1\nb: 2\n---\n\n# Kept\n";+ const operationInput = getMcpOperationInput("update-asset-content", {+ assetId: "asset-id",+ expectedName: "article_hash.md",+ content: source,+ });++ const response = await withTextAssetWriteFeedback({+ command: "update-asset-content",+ input: {+ assetId: "asset-id",+ expectedName: "article_hash.md",+ content: source,+ },+ operationInput,+ result: { result: { assetId: "asset-id" } },+ });++ expect(response.result).toMatchObject({+ assetId: "asset-id",+ source,+ diagnostics: [+ { code: "FRONTMATTER_INVALID", severity: "warning", line: 3 },+ { code: "FRONTMATTER_INVALID", severity: "warning", line: 5 },+ ],+ });+});++test("returns source diagnostics for every Markdown and MDX upload", async () => {+ const markdown = "---\na: 1\na: 2\n---\n";+ const mdx = "{first()}\n\n{second()}\n";+ const assets = [+ { name: "article.md", type: "file", format: "md", meta: {} },+ { name: "page.mdx", type: "file", format: "mdx", meta: {} },+ ];+ const operationInput = {+ assets,+ readAssetData: async (asset: { name: string }) =>+ asset.name === "article.md" ? markdown : mdx,+ };++ const response = await withTextAssetWriteFeedback({+ command: "upload-assets",+ input: { assets },+ operationInput,+ result: { result: { uploaded: [] } },+ });++ expect(response.result).toMatchObject({+ sourceDiagnostics: [+ {+ index: 0,+ name: "article.md",+ diagnostics: [+ { code: "FRONTMATTER_INVALID", severity: "warning", line: 3 },+ ],+ },+ {+ index: 1,+ name: "page.mdx",+ diagnostics: [+ { code: "unsafe-mdx", severity: "warning" },+ { code: "unsafe-mdx", severity: "warning" },+ ],+ },+ ],+ });+});++test("runs contextual MDX validation with every uploaded Asset id", async () => {+ const source = '<ws.element ws:name="Missing" />';+ const asset = {+ id: "uploaded-id",+ projectId: "project",+ name: "page.mdx",+ type: "file" as const,+ format: "mdx",+ size: source.length,+ createdAt: "2026-01-01T00:00:00.000Z",+ };+ const assets = [{ name: asset.name, type: "file", format: "mdx", meta: {} }];+ const operationInput = {+ assets,+ readAssetData: async () => source,+ };+ const ensureNamespaces = vi.fn(async () => ({+ projectId: "project",+ state: {+ pages: {+ meta: {},+ homePageId: "home",+ rootFolderId: "root",+ pages: new Map([+ [+ "home",+ {+ id: "home",+ name: "Home",+ path: "",+ title: '"Home"',+ meta: {},+ rootInstanceId: "block",+ },+ ],+ ]),+ folders: new Map([+ ["root", { id: "root", name: "Root", slug: "", children: ["home"] }],+ ]),+ },+ instances: new Map([+ [+ "block",+ {+ type: "instance" as const,+ id: "block",+ component: blockComponent,+ children: [{ type: "id" as const, value: "templates" }],+ },+ ],+ [+ "templates",+ {+ type: "instance" as const,+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ ]),+ props: new Map([+ [+ "src",+ {+ id: "src",+ instanceId: "block",+ name: "src",+ type: "asset" as const,+ value: asset.id,+ },+ ],+ ]),+ dataSources: new Map(),+ resources: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ breakpoints: new Map(),+ assets: new Map([[asset.id, asset]]),+ },+ }));++ const response = await withTextAssetWriteFeedback({+ command: "upload-assets",+ input: { assets },+ operationInput,+ result: { result: { uploaded: [asset] } },+ session: { ensureNamespaces } as never,+ });++ expect(ensureNamespaces).toHaveBeenCalledOnce();+ expect(response.result).toMatchObject({+ sourceDiagnostics: [+ {+ index: 0,+ name: "page.mdx",+ diagnostics: [+ {+ code: "unresolved-template",+ severity: "warning",+ assetId: "uploaded-id",+ blockInstanceId: "block",+ templateName: "Missing",+ },+ ],+ },+ ],+ });+});++test("validates query setup with the same schema before calling MCP", () => {+ const filter = { field: ["id"], operator: "eq", value: "asset" };+ let nestedWhere: unknown = filter;+ for (let depth = 0; depth < 9; depth += 1) {+ nestedWhere = { all: [nestedWhere] };+ }+ const invalidQueries: Array<[string, unknown]> = [+ ["missing query", {}],+ ["unknown query key", { query: { unknown: true } }],+ ["result mode", { query: { result: "middle" } }],+ ["where shape", { query: { where: {} } }],+ [+ "filter count",+ { query: { where: { all: Array.from({ length: 33 }, () => filter) } } },+ ],+ ["filter depth", { query: { where: nestedWhere } }],+ [+ "empty field path",+ { query: { where: { all: [{ ...filter, field: [] }] } } },+ ],+ [+ "deep field path",+ {+ query: {+ where: {+ all: [{ ...filter, field: Array.from({ length: 10 }, () => "x") }],+ },+ },+ },+ ],+ [+ "bare properties field",+ { query: { where: { all: [{ ...filter, field: ["properties"] }] } } },+ ],+ [+ "unsupported standard field",+ { query: { where: { all: [{ ...filter, field: ["bogus"] }] } } },+ ],+ [+ "operator",+ { query: { where: { all: [{ ...filter, operator: "matches" }] } } },+ ],+ [+ "in value",+ {+ query: {+ where: { all: [{ field: ["id"], operator: "in", value: "asset" }] },+ },+ },+ ],+ [+ "in value count",+ {+ query: {+ where: {+ all: [+ {+ field: ["id"],+ operator: "in",+ value: Array.from({ length: 1_001 }, () => "asset"),+ },+ ],+ },+ },+ },+ ],+ [+ "boolean operator value",+ {+ query: {+ where: {+ all: [{ field: ["id"], operator: "exists", value: "yes" }],+ },+ },+ },+ ],+ [+ "sort count",+ {+ query: {+ sort: Array.from({ length: 9 }, () => ({+ field: ["id"],+ direction: "asc",+ })),+ },+ },+ ],+ [+ "sort direction",+ { query: { sort: [{ field: ["id"], direction: "up" }] } },+ ],+ ["first without sort", { query: { result: "first" } }],+ [+ "empty output",+ {+ query: {+ output: { mode: "fields", includeMetadata: false, fields: [] },+ content: { mode: "none" },+ },+ },+ ],+ [+ "duplicate output fields",+ {+ query: {+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["id"], ["id"]],+ },+ },+ },+ ],+ [+ "output field count",+ {+ query: {+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: Array.from({ length: 257 }, (_, index) => [+ "properties",+ String(index),+ ]),+ },+ },+ },+ ],+ ["negative limit", { query: { limit: -1 } }],+ ["fractional limit", { query: { limit: 1.5 } }],+ ["large limit", { query: { limit: 1_001 } }],+ ["negative offset", { query: { offset: -1 } }],+ ["fractional offset", { query: { offset: 1.5 } }],+ ["large offset", { query: { offset: 1_001 } }],+ ["content mode", { query: { content: { mode: "body" } } }],+ [+ "full content bytes",+ { query: { content: { mode: "full", maxBytes: 0 } } },+ ],+ [+ "large full content",+ { query: { content: { mode: "full", maxBytes: 1_048_577 } } },+ ],+ [+ "range offset",+ { query: { content: { mode: "range", offset: -1, length: 1 } } },+ ],+ [+ "range length",+ { query: { content: { mode: "range", offset: 0, length: 0 } } },+ ],+ [+ "large range",+ { query: { content: { mode: "range", offset: 0, length: 262_145 } } },+ ],+ ["empty index revision", { query: {}, indexRevision: "" }],+ ["large index revision", { query: {}, indexRevision: "x".repeat(256) }],+ ];++ for (const [label, input] of invalidQueries) {+ if (label.includes("index revision")) {+ expect(+ () => getMcpOperationInput("preview-asset-query", input),+ label+ ).toThrow();+ continue;+ }+ expect(+ () => getMcpOperationInput("validate-asset-query", input),+ label+ ).toThrow();+ expect(+ () => getMcpOperationInput("preview-asset-query", input),+ label+ ).toThrow();+ }+});++test("formats local query schema failures as structured MCP input errors", () => {+ let error: unknown;+ try {+ getMcpOperationInput("validate-asset-query", {+ query: {+ result: "first",+ limit: -1,+ output: { mode: "fields", includeMetadata: false, fields: [] },+ content: { mode: "none" },+ },+ });+ } catch (caught) {+ error = caught;+ }++ expect(createMcpSingleOpCallErrorPayload({ error, elapsedMs: 1 })).toEqual({+ ok: false,+ error: {+ code: "INVALID_INPUT",+ message: expect.stringContaining("query.limit"),+ issues: [+ expect.objectContaining({ path: ["query", "limit"] }),+ expect.objectContaining({ path: ["query"] }),+ expect.objectContaining({ path: ["query", "sort"] }),+ ],+ },+ meta: { elapsedMs: 1 },+ });+});+test("exposes asset content editing through MCP discovery", () => {const tool = listProjectSessionMcpTools(publicApiOperations).find(({ name }) => name === "update-asset-content"diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.tsindex e069290d47..4dce7039e9 100644--- a/packages/cli/src/commands/mcp.ts+++ b/packages/cli/src/commands/mcp.ts@@ -1,5 +1,13 @@import { cwd, stdin, stdout, stderr } from "node:process";-import { mkdir, readFile, writeFile } from "node:fs/promises";+import {+ copyFile,+ mkdir,+ mkdtemp,+ readFile,+ rm,+ writeFile,+} from "node:fs/promises";+import { tmpdir } from "node:os";import path from "node:path";import {connectProjectSessionMcpServer,@@ -20,17 +28,22 @@ import {import * as httpClient from "@webstudio-is/http-client";import packageJson from "../../package.json" with { type: "json" };import type { ProjectSessionSnapshot } from "@webstudio-is/project-build/project-session";-import type { SemanticValidationIssue } from "@webstudio-is/project-build/runtime";+import {+ formatValidationErrorMessage,+ type SemanticValidationIssue,+} from "@webstudio-is/project-build/runtime";import {inspectMdxAssetSource,mdxAssetInspectionNamespaces,} from "@webstudio-is/project-build/runtime";import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";import {- createMdxSourceDiagnostics,- parseMdxDocumentRecovering,+ validateTextAssetSourceBytes,+ type TextAssetSourceDiagnostic,} from "@webstudio-is/content-engine/mdx";-import { getFileExtension, isMdxFileAsset } from "@webstudio-is/sdk";+import { contentEngineLimits } from "@webstudio-is/content-engine/limits";+import { assetQueryRequest } from "@webstudio-is/content-engine";+import { assetType, getFileExtension } from "@webstudio-is/sdk";import { resolveApiConnection } from "../api-connection";import {getCliErrorIssues,@@ -184,43 +197,385 @@ const createMcpInputError = (message: string, code: string) =>const hasAssetName = (value: unknown): value is { name: string } =>isPlainRecord(value) && typeof value.name === "string";+const createAssetInputIssue = ({+ path,+ message,+ code,+}: {+ path: string[];+ message: string;+ code: string;+}) => ({+ path,+ code,+ message,+ constraint: code,+});++const getTextAssetFormat = (value: string): "md" | "mdx" | undefined => {+ const extension = (getFileExtension(value) ?? value).toLowerCase();+ return extension === "md" || extension === "mdx" ? extension : undefined;+};++const getTextAssetDescriptorIssues = ({+ assets,+ pathPrefix,+}: {+ assets: unknown[];+ pathPrefix: string[];+}) => {+ const issues: SemanticValidationIssue[] = [];+ for (const [index, value] of assets.entries()) {+ const assetPath =+ pathPrefix[0] === "asset" ? pathPrefix : [...pathPrefix, String(index)];+ if (isPlainRecord(value) === false) {+ issues.push(+ createAssetInputIssue({+ path: assetPath,+ code: "invalid_type",+ message: "Asset descriptor must be an object.",+ })+ );+ continue;+ }+ const asset = value;+ const allowedFields = new Set([+ "name",+ "type",+ "format",+ "description",+ "folderId",+ "force",+ "meta",+ ]);+ for (const field of Object.keys(asset)) {+ if (allowedFields.has(field) === false) {+ issues.push(+ createAssetInputIssue({+ path: [...assetPath, field],+ code: "unknown_field",+ message: `Asset descriptor field ${JSON.stringify(field)} is not supported.`,+ })+ );+ }+ }+ if (typeof asset.name !== "string") {+ issues.push(+ createAssetInputIssue({+ path: [...assetPath, "name"],+ code: "invalid_type",+ message: "Asset name must be a string.",+ })+ );+ }+ if (+ typeof asset.type !== "string" ||+ assetType.options.includes(+ asset.type as (typeof assetType.options)[number]+ ) === false+ ) {+ issues.push(+ createAssetInputIssue({+ path: [...assetPath, "type"],+ code: "invalid_value",+ message: `Asset type must be one of ${assetType.options.join(", ")}.`,+ })+ );+ }+ for (const field of ["format", "description", "folderId"] as const) {+ if (asset[field] !== undefined && typeof asset[field] !== "string") {+ issues.push(+ createAssetInputIssue({+ path: [...assetPath, field],+ code: "invalid_type",+ message: `Asset ${field} must be a string.`,+ })+ );+ }+ }+ if (asset.folderId === "") {+ issues.push(+ createAssetInputIssue({+ path: [...assetPath, "folderId"],+ code: "too_small",+ message: "Asset folderId must not be empty.",+ })+ );+ }+ if (asset.force !== undefined && typeof asset.force !== "boolean") {+ issues.push(+ createAssetInputIssue({+ path: [...assetPath, "force"],+ code: "invalid_type",+ message: "Asset force must be a boolean.",+ })+ );+ }+ if (asset.meta !== undefined && isPlainRecord(asset.meta) === false) {+ issues.push(+ createAssetInputIssue({+ path: [...assetPath, "meta"],+ code: "invalid_type",+ message: "Asset meta must be an object.",+ })+ );+ }+ const name = typeof asset.name === "string" ? asset.name : "";+ const filenameFormat = getFileExtension(name)?.toLowerCase();+ const declaredFormat =+ typeof asset.format === "string" ? asset.format.toLowerCase() : undefined;+ const mentionsTextFormat =+ filenameFormat === "md" ||+ filenameFormat === "mdx" ||+ declaredFormat === "md" ||+ declaredFormat === "mdx";+ if (+ mentionsTextFormat &&+ declaredFormat !== undefined &&+ declaredFormat !== filenameFormat+ ) {+ issues.push(+ createAssetInputIssue({+ path: [...assetPath, "format"],+ code: "asset_filename_format_mismatch",+ message: `Asset filename and format must match. ${JSON.stringify(name)} has extension ${JSON.stringify(filenameFormat ?? "(none)")} but format is ${JSON.stringify(declaredFormat ?? "(missing)")}.`,+ })+ );+ }+ if (+ mentionsTextFormat &&+ typeof asset.type === "string" &&+ asset.type !== "file"+ ) {+ issues.push(+ createAssetInputIssue({+ path: [...assetPath, "type"],+ code: "markdown_asset_type_mismatch",+ message: `Markdown and MDX Assets must use type "file", not ${JSON.stringify(asset.type)}.`,+ })+ );+ }+ }+ return issues;+};++const assertTextAssetDescriptorFormats = ({+ assets,+ pathPrefix,+}: {+ assets: unknown[];+ pathPrefix: string[];+}) => {+ const issues = getTextAssetDescriptorIssues({ assets, pathPrefix });+ if (issues.length > 0) {+ throw Object.assign(+ new Error("Markdown and MDX Asset descriptors are invalid."),+ { code: "INVALID_INPUT", issues }+ );+ }+};++const throwAssetInputIssues = (issues: readonly SemanticValidationIssue[]) => {+ if (issues.length > 0) {+ throw Object.assign(new Error("Asset operation input is invalid."), {+ code: "INVALID_INPUT",+ issues,+ });+ }+};++const getRootAssetInputIssues = ({+ input,+ allowedFields,+}: {+ input: Record<string, unknown>;+ allowedFields: readonly string[];+}) =>+ Object.keys(input).flatMap((field) =>+ allowedFields.includes(field)+ ? []+ : [+ createAssetInputIssue({+ path: [field],+ code: "unknown_field",+ message: `Asset operation field ${JSON.stringify(field)} is not supported.`,+ }),+ ]+ );+const getMcpUploadAssetInput = (input: unknown) => {- if (isPlainRecord(input) === false || hasAssetName(input.asset) === false) {- throw new Error("upload-asset requires an asset object.");+ if (isPlainRecord(input) === false) {+ throwAssetInputIssues([+ createAssetInputIssue({+ path: [],+ code: "invalid_type",+ message: "upload-asset input must be an object.",+ }),+ ]);+ throw new Error("Unreachable invalid upload input");}- return createLocalUploadAssetInput({- asset: input.asset,+ throwAssetInputIssues([+ ...getRootAssetInputIssues({+ input,+ allowedFields: ["asset", "assetsDir"],+ }),+ ...(input.assetsDir === undefined || typeof input.assetsDir === "string"+ ? []+ : [+ createAssetInputIssue({+ path: ["assetsDir"],+ code: "invalid_type",+ message: "assetsDir must be a string.",+ }),+ ]),+ ...getTextAssetDescriptorIssues({+ assets: [input.asset],+ pathPrefix: ["asset"],+ }),+ ]);+ const asset = input.asset;+ if (hasAssetName(asset) === false) {+ throw new Error("Unreachable invalid Asset descriptor");+ }+ const prepared = createLocalUploadAssetInput({+ asset,assetsDir:typeof input.assetsDir === "string" ? input.assetsDir : undefined,readFile,});+ let content: Promise<unknown> | undefined;+ return {+ ...prepared,+ readAssetData: () => (content ??= prepared.readAssetData(asset)),+ };};const getMcpUploadAssetsInput = (input: unknown) => {- if (- isPlainRecord(input) === false ||- Array.isArray(input.assets) === false ||- input.assets.every(hasAssetName) === false- ) {- throw new Error("upload-assets requires an assets array.");+ if (isPlainRecord(input) === false) {+ throwAssetInputIssues([+ createAssetInputIssue({+ path: [],+ code: "invalid_type",+ message: "upload-assets input must be an object.",+ }),+ ]);+ throw new Error("Unreachable invalid upload input");}- return createLocalUploadAssetsInput({- assets: input.assets,+ const assets = Array.isArray(input.assets) ? input.assets : [];+ throwAssetInputIssues([+ ...getRootAssetInputIssues({+ input,+ allowedFields: ["assets", "assetsDir"],+ }),+ ...(Array.isArray(input.assets)+ ? []+ : [+ createAssetInputIssue({+ path: ["assets"],+ code: "invalid_type",+ message: "upload-assets requires an assets array.",+ }),+ ]),+ ...(input.assetsDir === undefined || typeof input.assetsDir === "string"+ ? []+ : [+ createAssetInputIssue({+ path: ["assetsDir"],+ code: "invalid_type",+ message: "assetsDir must be a string.",+ }),+ ]),+ ...getTextAssetDescriptorIssues({ assets, pathPrefix: ["assets"] }),+ ]);+ if (assets.every(hasAssetName) === false) {+ throw new Error("Unreachable invalid Asset descriptors");+ }+ const prepared = createLocalUploadAssetsInput({+ assets,assetsDir:typeof input.assetsDir === "string" ? input.assetsDir : undefined,readFile,});+ const contentByAsset = new Map<object, Promise<unknown>>();+ return {+ ...prepared,+ readAssetData: (asset: { name: string }) => {+ let content = contentByAsset.get(asset);+ if (content === undefined) {+ content = prepared.readAssetData(asset);+ contentByAsset.set(asset, content);+ }+ return content;+ },+ };};const getMcpUpdateAssetContentInput = (input: unknown) => {+ if (isPlainRecord(input) === false) {+ throwAssetInputIssues([+ createAssetInputIssue({+ path: [],+ code: "invalid_type",+ message: "update-asset-content input must be an object.",+ }),+ ]);+ throw new Error("Unreachable invalid update input");+ }+ const issues = getRootAssetInputIssues({+ input,+ allowedFields: ["assetId", "expectedName", "extension", "path", "content"],+ });+ for (const field of ["assetId", "expectedName"] as const) {+ if (typeof input[field] !== "string" || input[field].length === 0) {+ issues.push(+ createAssetInputIssue({+ path: [field],+ code: typeof input[field] === "string" ? "too_small" : "invalid_type",+ message: `${field} must be a non-empty string.`,+ })+ );+ }+ }+ for (const field of ["extension", "path"] as const) {+ if (+ input[field] !== undefined &&+ (typeof input[field] !== "string" || input[field].length === 0)+ ) {+ issues.push(+ createAssetInputIssue({+ path: [field],+ code: typeof input[field] === "string" ? "too_small" : "invalid_type",+ message: `${field} must be a non-empty string.`,+ })+ );+ }+ }+ if (input.content !== undefined && typeof input.content !== "string") {+ issues.push(+ createAssetInputIssue({+ path: ["content"],+ code: "invalid_type",+ message: "content must be a string.",+ })+ );+ }+ const hasPath = typeof input.path === "string" && input.path.length > 0;+ const hasContent = typeof input.content === "string";+ if (hasPath === hasContent) {+ issues.push(+ createAssetInputIssue({+ path: [],+ code: "invalid_source_selection",+ message: "Provide exactly one of path or content.",+ })+ );+ }+ throwAssetInputIssues(issues);if (- isPlainRecord(input) === false ||typeof input.assetId !== "string" ||typeof input.expectedName !== "string") {- throw new Error(- "update-asset-content requires assetId and expectedName strings."- );+ throw new Error("Unreachable invalid update input");}const prepared = createLocalUpdateAssetContentInput({assetId: input.assetId,@@ -238,77 +593,453 @@ const getMcpUpdateAssetContentInput = (input: unknown) => {};};-const inspectMdxSource = async (source: string) => {- const parsed = await parseMdxDocumentRecovering({ source });- return createMdxSourceDiagnostics(parsed.diagnostics);+type TextAssetDiagnostic =+ | TextAssetSourceDiagnostic+ | Awaited<ReturnType<typeof inspectMdxAssetSource>>[number];++type TextAssetWriteFeedback =+ | Readonly<{+ type: "uploads";+ sourceDiagnostics: readonly Readonly<{+ index: number;+ name: string;+ source: string;+ format: "md" | "mdx";+ issuePath: string[];+ diagnostics: readonly TextAssetDiagnostic[];+ }>[];+ }>+ | Readonly<{+ type: "update";+ source: string;+ diagnostics: readonly TextAssetDiagnostic[];+ }>;++const createTextAssetContentError = ({+ assetId,+ name,+ path: filePath,+ issuePath,+ diagnostic,+ code,+}: {+ assetId?: string;+ name?: string;+ path?: string;+ issuePath: string[];+ diagnostic: TextAssetSourceDiagnostic;+ code: "CONTENT_DECODING_FAILED" | "CONTENT_LIMIT_EXCEEDED";+}) => {+ const location = name ?? filePath ?? assetId ?? "Markdown or MDX Asset";+ const issue = {+ ...diagnostic,+ path: issuePath,+ constraint: diagnostic.code,+ ...(assetId === undefined ? {} : { assetId }),+ ...(name === undefined ? {} : { name }),+ ...(filePath === undefined ? {} : { file: filePath }),+ };+ return Object.assign(new Error(`${location}: ${diagnostic.message}`), {+ code,+ issues: [issue],+ ...(assetId === undefined ? {} : { assetId }),+ ...(name === undefined ? {} : { name }),+ ...(filePath === undefined ? {} : { path: filePath }),+ });};-const decodeMdxSource = (value: unknown) => {- if (typeof value === "string") {- return value;+const validateTextAssetContent = async ({+ content,+ format,+ assetId,+ name,+ path: filePath,+ issuePath,+ session,+}: {+ content: unknown;+ format: "md" | "mdx";+ assetId?: string;+ name?: string;+ path?: string;+ issuePath: string[];+ session?: Pick<CliProjectSession, "ensureNamespaces">;+}): Promise<{+ source: string;+ diagnostics: readonly TextAssetDiagnostic[];+}> => {+ const bytes =+ typeof content === "string"+ ? new TextEncoder().encode(content)+ : content instanceof Uint8Array+ ? content+ : undefined;+ const validation =+ bytes === undefined+ ? undefined+ : await validateTextAssetSourceBytes({ source: bytes, format });+ if (bytes === undefined || validation === undefined) {+ throw createTextAssetContentError({+ assetId,+ name,+ path: filePath,+ issuePath,+ code: "CONTENT_DECODING_FAILED",+ diagnostic: {+ code: format === "md" ? "MARKDOWN_BODY_DECODING_FAILED" : "invalid-mdx",+ severity: "error",+ message: `${format === "md" ? "Markdown" : "MDX"} content must be UTF-8 text`,+ },+ });+ }+ const source = validation.source;+ if (source === undefined) {+ const diagnostic = validation.diagnostics[0];+ if (diagnostic === undefined) {+ throw new Error("Text Asset validation did not return decoded source.");+ }+ throw createTextAssetContentError({+ assetId,+ name,+ path: filePath,+ issuePath,+ diagnostic,+ code:+ bytes.byteLength > contentEngineLimits.hydratedFileBytes+ ? "CONTENT_LIMIT_EXCEEDED"+ : "CONTENT_DECODING_FAILED",+ });}- if (value instanceof Uint8Array) {- return new TextDecoder("utf-8", { fatal: true }).decode(value);+ if (format !== "mdx" || assetId === undefined || session === undefined) {+ return { source, diagnostics: validation.diagnostics };}- throw new Error("MDX Asset content must be UTF-8 text.");+ const snapshot = await session.ensureNamespaces(mdxAssetInspectionNamespaces);+ return {+ source,+ diagnostics: await inspectMdxAssetSource({+ source,+ assetId,+ state: snapshot.state,+ metas: componentMetas,+ projectId: snapshot.projectId,+ }),+ };};-const withMdxAssetWriteFeedback = async <Envelope extends { result: unknown }>({+const prepareTextAssetWriteFeedback = async ({command,input,operationInput,- result,session,}: {command: string;input: unknown;operationInput: unknown;- result: Envelope;session?: Pick<CliProjectSession, "ensureNamespaces">;-}): Promise<Envelope> => {+}): Promise<TextAssetWriteFeedback | undefined> => {+ if (+ (command === "upload-asset" || command === "upload-assets") &&+ isPlainRecord(input) &&+ isPlainRecord(operationInput) &&+ typeof operationInput.readAssetData === "function"+ ) {+ const assets =+ command === "upload-asset"+ ? isPlainRecord(input.asset)+ ? [input.asset]+ : []+ : Array.isArray(input.assets)+ ? input.assets.filter(isPlainRecord)+ : [];+ const sourceDiagnostics = [];+ const validationIssues: Array<{+ index: number;+ issues: NonNullable<ReturnType<typeof getCliErrorIssues>>;+ }> = [];+ const fatalErrors: unknown[] = [];+ for (const [index, asset] of assets.entries()) {+ if (typeof asset.name !== "string") {+ continue;+ }+ const assetName = asset.name;+ const format = getTextAssetFormat(+ typeof asset.format === "string" ? asset.format : assetName+ );+ if (format === undefined) {+ continue;+ }+ const issuePath =+ command === "upload-asset"+ ? ["asset", "name"]+ : ["assets", String(index), "name"];+ try {+ const { source, diagnostics } = await validateTextAssetContent({+ content: await operationInput.readAssetData(asset),+ format,+ name: assetName,+ issuePath,+ });+ sourceDiagnostics.push({+ index,+ name: assetName,+ source,+ format,+ issuePath,+ diagnostics,+ });+ validationIssues.push({+ index,+ issues: diagnostics.map((diagnostic) => ({+ ...diagnostic,+ path: issuePath,+ constraint: diagnostic.code,+ message:+ "message" in diagnostic && typeof diagnostic.message === "string"+ ? diagnostic.message+ : "reason" in diagnostic &&+ typeof diagnostic.reason === "string"+ ? diagnostic.reason+ : diagnostic.code,+ name: assetName,+ })),+ });+ } catch (error) {+ const issues = getCliErrorIssues(error);+ const code = getStableErrorCode(error);+ if (+ issues === undefined ||+ (code !== "CONTENT_DECODING_FAILED" &&+ code !== "CONTENT_LIMIT_EXCEEDED")+ ) {+ throw error;+ }+ validationIssues.push({ index, issues });+ fatalErrors.push(error);+ }+ }+ if (fatalErrors.length > 0) {+ const code = fatalErrors.some(+ (error) => getStableErrorCode(error) === "CONTENT_DECODING_FAILED"+ )+ ? "CONTENT_DECODING_FAILED"+ : "CONTENT_LIMIT_EXCEEDED";+ throw Object.assign(+ new Error(+ `${fatalErrors.length} Markdown or MDX Asset${fatalErrors.length === 1 ? "" : "s"} could not be read before upload.`+ ),+ {+ code,+ issues: validationIssues+ .sort((left, right) => left.index - right.index)+ .flatMap(({ issues }) => issues),+ }+ );+ }+ return sourceDiagnostics.length === 0+ ? undefined+ : { type: "uploads", sourceDiagnostics };+ }if (command !== "update-asset-content" ||isPlainRecord(input) === false ||isPlainRecord(operationInput) === false ||- typeof operationInput.readAssetData !== "function" ||- (typeof input.extension === "string"+ typeof operationInput.readAssetData !== "function"+ ) {+ return;+ }+ const format = getTextAssetFormat(+ typeof input.extension === "string"? input.extension: typeof input.expectedName === "string"- ? getFileExtension(input.expectedName)- : undefined- )?.toLowerCase() !== "mdx"- ) {+ ? input.expectedName+ : ""+ );+ if (format === undefined) {+ return;+ }+ const assetId = typeof input.assetId === "string" ? input.assetId : undefined;+ const { source, diagnostics } = await validateTextAssetContent({+ content: await operationInput.readAssetData(),+ format,+ assetId,+ name:+ typeof input.expectedName === "string" ? input.expectedName : undefined,+ issuePath: ["content"],+ session,+ });+ return { type: "update", source, diagnostics };+};++const validateDownloadedTextAsset = async ({+ assetId,+ path: filePath,+ format,+ content,+ session,+}: {+ assetId: string;+ path: string;+ format: "md" | "mdx";+ content: Uint8Array;+ session?: Pick<CliProjectSession, "ensureNamespaces">;+}) =>+ validateTextAssetContent({+ content,+ format,+ assetId,+ path: filePath,+ issuePath: [filePath],+ session,+ });++const materializeValidatedDownloadedAsset = async ({+ assetId,+ remotePath,+ localPath,+ diagnostics,+}: {+ assetId: string;+ remotePath: string;+ localPath: string;+ diagnostics: readonly TextAssetDiagnostic[];+}) => {+ const remote = await readFile(remotePath);+ let local: Uint8Array | undefined;+ try {+ local = await readFile(localPath);+ } catch (error) {+ if (+ typeof error !== "object" ||+ error === null ||+ !("code" in error) ||+ error.code !== "ENOENT"+ ) {+ throw error;+ }+ }+ if (local !== undefined && Buffer.from(local).equals(remote) === false) {+ const issues = [+ ...diagnostics.map((diagnostic) => ({+ ...diagnostic,+ path: [localPath],+ constraint: diagnostic.code,+ assetId,+ file: localPath,+ message:+ "message" in diagnostic && typeof diagnostic.message === "string"+ ? diagnostic.message+ : "reason" in diagnostic && typeof diagnostic.reason === "string"+ ? diagnostic.reason+ : diagnostic.code,+ })),+ {+ code: "local_asset_conflict",+ severity: "error" as const,+ path: [localPath],+ constraint: "remote_content_matches_local_file",+ assetId,+ file: localPath,+ message:+ "The existing local file differs from the current project Asset. Move or remove it, then download again.",+ },+ ];+ throw Object.assign(+ new Error(+ `The existing local file differs from the current project Asset: ${localPath}`+ ),+ { code: "CONFLICT", assetId, path: localPath, issues }+ );+ }+ if (local === undefined) {+ await mkdir(path.dirname(localPath), { recursive: true });+ await copyFile(remotePath, localPath);+ }+ return remote;+};++const withTextAssetWriteFeedback = async <+ Envelope extends { result: unknown },+>({+ command,+ input,+ operationInput,+ result,+ session,+ feedback,+}: {+ command: string;+ input: unknown;+ operationInput: unknown;+ result: Envelope;+ session?: Pick<CliProjectSession, "ensureNamespaces">;+ feedback?: TextAssetWriteFeedback;+}): Promise<Envelope> => {+ const prepared =+ feedback ??+ (await prepareTextAssetWriteFeedback({+ command,+ input,+ operationInput,+ session,+ }));+ if (prepared?.type === "uploads") {+ const uploaded =+ isPlainRecord(result.result) && Array.isArray(result.result.uploaded)+ ? result.result.uploaded+ : [];+ const uploadedByName = new Map<string, Array<Record<string, unknown>>>();+ for (const asset of uploaded) {+ if (isPlainRecord(asset) === false || typeof asset.name !== "string") {+ continue;+ }+ const matches = uploadedByName.get(asset.name) ?? [];+ matches.push(asset);+ uploadedByName.set(asset.name, matches);+ }+ const sourceDiagnostics = await Promise.all(+ prepared.sourceDiagnostics.map(async (entry) => {+ let diagnostics = entry.diagnostics;+ if (entry.format === "mdx" && session !== undefined) {+ const uploadedAsset = uploadedByName.get(entry.name)?.shift();+ if (typeof uploadedAsset?.id === "string") {+ ({ diagnostics } = await validateTextAssetContent({+ content: entry.source,+ format: entry.format,+ assetId: uploadedAsset.id,+ name: entry.name,+ issuePath: entry.issuePath,+ session,+ }));+ }+ }+ return {+ index: entry.index,+ name: entry.name,+ diagnostics,+ };+ })+ );+ return {+ ...result,+ result: {+ ...(isPlainRecord(result.result)+ ? result.result+ : { result: result.result }),+ sourceDiagnostics,+ },+ };+ }+ if (prepared?.type !== "update") {return result;}- const source = decodeMdxSource(await operationInput.readAssetData());- const assetId =- typeof input.assetId === "string"- ? input.assetId- : isPlainRecord(result.result) &&- typeof result.result.assetId === "string"- ? result.result.assetId- : undefined;- const snapshot =- assetId === undefined || session === undefined- ? undefined- : await session.ensureNamespaces(mdxAssetInspectionNamespaces);return {...result,result: {...(isPlainRecord(result.result)? result.result: { result: result.result }),- source,- diagnostics:- assetId === undefined || snapshot === undefined- ? await inspectMdxSource(source)- : await inspectMdxAssetSource({- source,- assetId,- state: snapshot.state,- metas: componentMetas,- projectId: snapshot.projectId,- }),+ source: prepared.source,+ diagnostics: prepared.diagnostics,},};};@@ -323,6 +1054,12 @@ const getMcpOperationInput = (command: string, input: unknown) => {if (command === "update-asset-content") {return getMcpUpdateAssetContentInput(input);}+ if (command === "validate-asset-query") {+ return assetQueryRequest.pick({ query: true }).parse(input);+ }+ if (command === "preview-asset-query") {+ return assetQueryRequest.parse(input);+ }return input;};@@ -694,6 +1431,15 @@ const createMcpRunCheckpointStopPayload = ({const getMcpRunError = (error: unknown) => {const issues = getCliErrorIssues(error);+ const isValidationError =+ error instanceof Error && error.name === "ZodError" && issues !== undefined;+ if (isValidationError) {+ return {+ code: "INVALID_INPUT",+ message: formatValidationErrorMessage("Tool input is invalid.", issues),+ issues,+ };+ }if (isPlainRecord(error) &&typeof error.message === "string" &&@@ -702,7 +1448,7 @@ const getMcpRunError = (error: unknown) => {return {code: isMissingApiAccessError(error)? "UNAUTHORIZED"- : (error.code ?? "MCP_TOOL_FAILED"),+ : (getStableErrorCode(error) ?? "MCP_TOOL_FAILED"),message: getCliErrorMessage(error),...(issues === undefined ? {} : { issues }),};@@ -1153,6 +1899,12 @@ const createCliMcpHost = async ({onProjectSessionChange: previewFreshness.markStale,executeOperation: async ({ command, input, dryRun }) => {const operationInput = getMcpOperationInput(command, input);+ const textAssetFeedback = await prepareTextAssetWriteFeedback({+ command,+ input,+ operationInput,+ session,+ });const result = await executeProjectSessionApiOperation({command,input: operationInput,@@ -1163,12 +1915,13 @@ const createCliMcpHost = async ({if (dryRun !== true && shouldInvalidatePreview(command)) {previewFreshness.markStale();}- return withMdxAssetWriteFeedback({+ return withTextAssetWriteFeedback({command,input,operationInput,result,session,+ feedback: textAssetFeedback,});},restorePoints: {@@ -1236,30 +1989,51 @@ const createCliMcpHost = async ({if (asset === undefined) {throw new Error(`Asset not found: ${input.assetId}`);}- await downloadAssetFile({- asset,- assetsDirectory: input.assetsDir,- origin: connection.origin,+ assertTextAssetDescriptorFormats({+ assets: [asset as unknown as Record<string, unknown>],+ pathPrefix: ["asset"],});const localPath = getLocalAssetPath(asset.name, input.assetsDir);- if (isMdxFileAsset(asset)) {- const source = await readFile(localPath, "utf8");- const inspectionSnapshot = await session.ensureNamespaces(- mdxAssetInspectionNamespaces+ const format = getTextAssetFormat(asset.format);+ if (format !== undefined) {+ const temporaryDirectory = await mkdtemp(+ path.join(tmpdir(), "webstudio-asset-download-"));- return {- assetId: asset.id,- path: localPath,- source,- diagnostics: await inspectMdxAssetSource({- source,+ try {+ await downloadAssetFile({+ asset,+ assetsDirectory: temporaryDirectory,+ origin: connection.origin,+ });+ const remotePath = getLocalAssetPath(asset.name, temporaryDirectory);+ const { source, diagnostics } = await validateDownloadedTextAsset({assetId: asset.id,- state: inspectionSnapshot.state,- metas: componentMetas,- projectId: inspectionSnapshot.projectId,- }),- };+ path: localPath,+ format,+ content: await readFile(remotePath),+ session,+ });+ await materializeValidatedDownloadedAsset({+ assetId: asset.id,+ remotePath,+ localPath,+ diagnostics,+ });+ return {+ assetId: asset.id,+ path: localPath,+ source,+ diagnostics,+ };+ } finally {+ await rm(temporaryDirectory, { recursive: true, force: true });+ }}+ await downloadAssetFile({+ asset,+ assetsDirectory: input.assetsDir,+ origin: connection.origin,+ });return {assetId: asset.id,path: localPath,@@ -1985,7 +2759,10 @@ export const __testing__ = {createMcpRunCheckpointStopPayload,getLoadedProjectSessionSnapshot,getMcpOperationInput,- withMdxAssetWriteFeedback,+ prepareTextAssetWriteFeedback,+ withTextAssetWriteFeedback,+ validateDownloadedTextAsset,+ materializeValidatedDownloadedAsset,parseMcpSingleOpCallInput,validateSingleOpCallInput,isMcpToolCallFailure,diff --git a/packages/cli/src/content-engine-reference.ts b/packages/cli/src/content-engine-reference.tsindex 29c63d4442..b2ee9b1b06 100644--- a/packages/cli/src/content-engine-reference.ts+++ b/packages/cli/src/content-engine-reference.ts@@ -72,15 +72,21 @@ const contentRows = [},{value: "full",- description: `Embeds the complete UTF-8 file content in the content database. \`maxBytes\` defaults to ${formatBytes(contentEngineLimits.hydratedFileBytes)} and cannot be set higher. The query fails if a selected file is larger.`,+ description: `Embeds the complete UTF-8 file content in the content database. \`maxBytes\` defaults to ${formatBytes(+ contentEngineLimits.hydratedFileBytes+ )} and cannot be set higher. The query fails if a selected file is larger.`,},{value: "range",- description: `Embeds a byte range selected by \`offset\` and \`length\` in the content database. \`length\` cannot exceed ${formatBytes(contentEngineLimits.hydratedRangeBytes)}.`,+ description: `Embeds a byte range selected by \`offset\` and \`length\` in the content database. \`length\` cannot exceed ${formatBytes(+ contentEngineLimits.hydratedRangeBytes+ )}.`,},{value: "markdown-body-ref",- description: `Stores a reference to a Markdown or MDX body. Webstudio filters and paginates first, then reads only the selected bodies from Assets. \`maxBytes\` defaults to ${formatBytes(contentEngineLimits.hydratedFileBytes)} and cannot be set higher. The query fails if a selected source file is larger.`,+ description: `Stores a reference to a Markdown or MDX body. Webstudio filters and paginates first, then reads only the selected bodies from Assets. \`maxBytes\` defaults to ${formatBytes(+ contentEngineLimits.hydratedFileBytes+ )} and cannot be set higher. The query fails if a selected source file is larger.`,},] as const satisfies readonly ReferenceRow[];@@ -95,6 +101,20 @@ const diagnosticRows = [] as const;const optionalDiagnosticRows = [+ [+ "`queryIssues`",+ "Structured nonfatal query warnings with a stable code and exact query path.",+ ],+ [+ "`queryWarnings`",+ "Deprecated plain-text query warnings retained for compatibility.",+ ],+ [+ "`issues`",+ "All content errors and warnings found in files matched by the current query. Each diagnostic identifies its phase, code, message, asset, path, and source location when available.",+ ],+ ["`issueCount`", "Total errors and warnings in `issues`."],+ ["`issuesTruncated`", "Always `false`; retained for response compatibility."],["`artifacts`","Optional query and merged compiled artifacts used by detailed Builder diagnostics.",@@ -156,7 +176,9 @@ const assertSameValues = ({const implementedValues = [...implemented].sort();if (JSON.stringify(documentedValues) !== JSON.stringify(implementedValues)) {throw new Error(- `${label} documentation is out of sync: documented ${documentedValues.join(", ")}; implemented ${implementedValues.join(", ")}`+ `${label} documentation is out of sync: documented ${documentedValues.join(+ ", "+ )}; implemented ${implementedValues.join(", ")}`);}};diff --git a/packages/cli/src/content-runtime-bundle.test.ts b/packages/cli/src/content-runtime-bundle.test.tsnew file mode 100644index 0000000000..f9820108a7--- /dev/null+++ b/packages/cli/src/content-runtime-bundle.test.ts@@ -0,0 +1,21 @@+import { build } from "esbuild";+import { expect, test } from "vitest";++test("keeps the MDX authoring parser out of the published content runtime", async () => {+ const result = await build({+ entryPoints: ["@webstudio-is/content-engine/runtime"],+ bundle: true,+ format: "esm",+ platform: "browser",+ target: "es2022",+ conditions: ["webstudio", "worker"],+ metafile: true,+ write: false,+ });+ const inputs = Object.keys(result.metafile.inputs);++ expect(inputs.some((path) => path.endsWith("/src/mdx.ts"))).toBe(false);+ expect(inputs.some((path) => path.includes("/node_modules/acorn/"))).toBe(+ false+ );+});diff --git a/packages/cli/src/error-codes.test.ts b/packages/cli/src/error-codes.test.tsindex a3e65958a9..947b3e19c7 100644--- a/packages/cli/src/error-codes.test.ts+++ b/packages/cli/src/error-codes.test.ts@@ -1,5 +1,6 @@import { describe, expect, test } from "vitest";import {+ getCliErrorIssues,getCliErrorMessage,getStableErrorCode,isMissingApiAccessError,@@ -21,6 +22,37 @@ describe("getStableErrorCode", () => {).toBe("NOT_FOUND");});+ test("prefers a specific nested Webstudio error code", () => {+ expect(+ getStableErrorCode({+ code: "BAD_REQUEST",+ data: { code: "BAD_REQUEST", webstudioCode: "STALE_INDEX" },+ })+ ).toBe("STALE_INDEX");+ });++ test("reads a stable Webstudio error code from an error cause", () => {+ expect(+ getStableErrorCode(+ Object.assign(new Error("Asset query failed"), {+ cause: { webstudioCode: "CONTENT_DECODING_FAILED" },+ })+ )+ ).toBe("CONTENT_DECODING_FAILED");+ });++ test("looks through generic MCP and internal error wrappers", () => {+ expect(+ getStableErrorCode({+ code: "MCP_TOOL_FAILED",+ cause: {+ code: "INTERNAL_ERROR",+ cause: { webstudioCode: "INVALID_REQUEST" },+ },+ })+ ).toBe("INVALID_REQUEST");+ });+test("rejects dynamic values as stable error codes", () => {expect(getStableErrorCode({ code: "customer-specific-code" })).toBe(undefined@@ -28,6 +60,54 @@ describe("getStableErrorCode", () => {});});+describe("getCliErrorIssues", () => {+ test("preserves complete asset diagnostic fields", () => {+ expect(+ getCliErrorIssues({+ data: {+ issues: [+ {+ code: "invalid-mdx",+ path: ["posts/broken.mdx"],+ message: "Unexpected end of file",+ constraint: "invalid-mdx",+ severity: "error",+ scope: "query",+ phase: "source",+ assetId: "asset-1",+ line: 4,+ column: 9,+ nodeType: "mdxJsxFlowElement",+ reason: "Closing tag is missing",+ sourceRange: {+ start: { line: 4, column: 1, offset: 30 },+ end: { line: 4, column: 9, offset: 38 },+ },+ },+ ],+ },+ })+ ).toEqual([+ expect.objectContaining({+ code: "invalid-mdx",+ path: ["posts/broken.mdx"],+ severity: "error",+ scope: "query",+ phase: "source",+ assetId: "asset-1",+ line: 4,+ column: 9,+ nodeType: "mdxJsxFlowElement",+ reason: "Closing tag is missing",+ sourceRange: {+ start: { line: 4, column: 1, offset: 30 },+ end: { line: 4, column: 9, offset: 38 },+ },+ }),+ ]);+ });+});+describe("getCliErrorMessage", () => {test("formats actionable semantic issues for human output", () => {const error = new BuilderRuntimeError(diff --git a/packages/cli/src/error-codes.ts b/packages/cli/src/error-codes.tsindex 2f57785ad7..f1243a0ed8 100644--- a/packages/cli/src/error-codes.ts+++ b/packages/cli/src/error-codes.ts@@ -21,15 +21,55 @@ const getErrorMessage = (error: unknown) =>? error.message: String(error);-export const getStableErrorCode = (error: unknown) => {- const directErrorCode =- typeof error === "object" && error !== null && "code" in error- ? (error as { code?: unknown }).code- : undefined;- const code = getApiErrorCode(error) ?? directErrorCode;- return typeof code === "string" && stableErrorCodePattern.test(code)- ? code+const genericTransportErrorCodes = new Set([+ "BAD_REQUEST",+ "CONFLICT",+ "FORBIDDEN",+ "INTERNAL_ERROR",+ "INTERNAL_SERVER_ERROR",+ "MCP_RESOURCE_FAILED",+ "MCP_TOOL_FAILED",+ "NOT_FOUND",+ "UNAUTHORIZED",+ "UNKNOWN",+]);++const getStableCode = (value: unknown) =>+ typeof value === "string" && stableErrorCodePattern.test(value)+ ? value: undefined;++export const getStableErrorCode = (error: unknown) => {+ const visited = new Set<unknown>();+ const visit = (value: unknown): string | undefined => {+ if (typeof value !== "object" || value === null || visited.has(value)) {+ return;+ }+ visited.add(value);+ const record = value as Record<string, unknown>;+ const data =+ typeof record.data === "object" && record.data !== null+ ? (record.data as Record<string, unknown>)+ : undefined;+ const webstudioCode =+ getStableCode(record.webstudioCode) ?? getStableCode(data?.webstudioCode);+ if (webstudioCode !== undefined) {+ return webstudioCode;+ }+ const directCode = getStableCode(record.code);+ if (+ directCode !== undefined &&+ genericTransportErrorCodes.has(directCode) === false+ ) {+ return directCode;+ }+ const nestedCode = visit(record.cause) ?? visit(data?.cause);+ if (nestedCode !== undefined) {+ return nestedCode;+ }+ return directCode ?? getApiErrorCode(value);+ };+ return visit(error);};export const isMissingApiAccessError = (error: unknown) => {diff --git a/packages/content-engine/src/asset-index.ts b/packages/content-engine/src/asset-index.tsindex 7e00c4021a..15fc50b380 100644--- a/packages/content-engine/src/asset-index.ts+++ b/packages/content-engine/src/asset-index.ts@@ -61,6 +61,22 @@ export type ContentCompilerDiagnostics = {referenceId: string;assetUrl: string;}[];+ sourceIssues?: readonly {+ severity: "error" | "warning";+ code: string;+ message: string;+ assetId: string;+ path: string;+ line?: number;+ column?: number;+ reference?: string;+ nodeType?: string;+ reason?: string;+ sourceRange?: Readonly<{+ start: Readonly<{ line: number; column: number; offset?: number }>;+ end: Readonly<{ line: number; column: number; offset?: number }>;+ }>;+ }[];};const getDocumentBytes = (diff --git a/packages/content-engine/src/compilation-plan.ts b/packages/content-engine/src/compilation-plan.tsindex 4d266d7553..0f4486a2b4 100644--- a/packages/content-engine/src/compilation-plan.ts+++ b/packages/content-engine/src/compilation-plan.ts@@ -483,7 +483,7 @@ const getStandardFieldPaths = (query: ContentCompilationQuery) => {}}if (query.content.mode !== "none") {- for (const field of ["mimeType", "size", "revision"] as const) {+ for (const field of ["mimeType", "path", "size", "revision"] as const) {addField(fields, [field]);}}diff --git a/packages/content-engine/src/content-source.test.ts b/packages/content-engine/src/content-source.test.tsindex aad4747fe4..21f3489577 100644--- a/packages/content-engine/src/content-source.test.ts+++ b/packages/content-engine/src/content-source.test.ts@@ -121,6 +121,138 @@ const createDocumentSource = ({});describe("content source snapshots", () => {+ test("reports all fatal MDX errors from selected files", async () => {+ const files = [+ createFile({ id: "one", path: "blog/one.mdx", contentType: "text/mdx" }),+ createFile({ id: "two", path: "blog/two.mdx", contentType: "text/mdx" }),+ ];+ const source: ContentSource = {+ async openSnapshot() {+ return {+ revision: "snapshot",+ files,+ async loadEntries() {+ return files.map((file) => ({+ ...createEntry(file),+ content: "<ws.element",+ }));+ },+ async loadDocumentSources() {+ return files.map(({ id }) => ({ id, source: "<ws.element" }));+ },+ async isCurrent() {+ return true;+ },+ };+ },+ };++ await expect(+ compileContentSource({ source, projectId })+ ).rejects.toMatchObject({+ diagnostics: [+ { severity: "error", assetId: "one", path: "blog/one.mdx" },+ { severity: "error", assetId: "two", path: "blog/two.mdx" },+ ],+ });+ });++ test("keeps all nonfatal Markdown errors as warnings", async () => {+ const file = createFile({ id: "post" });+ const source: ContentSource = {+ async openSnapshot() {+ return {+ revision: "snapshot",+ files: [file],+ async loadEntries() {+ return [+ {+ ...createEntry(file),+ content: "---\na: 1\na: 2\nb: 1\nb: 2\n---\n",+ },+ ];+ },+ async isCurrent() {+ return true;+ },+ };+ },+ };++ const result = await compileContentSource({ source, projectId });+ expect(result.diagnostics.sourceIssues).toMatchObject([+ { severity: "warning", path: "blog/post.md", line: 3 },+ { severity: "warning", path: "blog/post.md", line: 5 },+ ]);+ });++ test("preserves complete MDX warning context", async () => {+ const file = createFile({+ id: "post",+ path: "blog/post.mdx",+ contentType: "text/mdx",+ });+ const source: ContentSource = {+ async openSnapshot() {+ return {+ revision: "snapshot",+ files: [file],+ async loadEntries() {+ return [{ ...createEntry(file), content: "{1 + 1}" }];+ },+ async isCurrent() {+ return true;+ },+ };+ },+ };++ const result = await compileContentSource({ source, projectId });+ expect(result.diagnostics.sourceIssues).toEqual([+ expect.objectContaining({+ severity: "warning",+ code: "unsafe-mdx",+ assetId: "post",+ path: "blog/post.mdx",+ nodeType: "mdxFlowExpression",+ reason: "Executable MDX expressions are not supported",+ sourceRange: {+ start: { line: 1, column: 1, offset: 0 },+ end: { line: 1, column: 8, offset: 7 },+ },+ }),+ ]);+ });++ test("warns when a selected source cannot be validated within limits", async () => {+ const file = createFile({ id: "post" });+ const source: ContentSource = {+ async openSnapshot() {+ return {+ revision: "snapshot",+ files: [file],+ async loadEntries() {+ return [{ ...createEntry(file), contentRequired: true }];+ },+ async isCurrent() {+ return true;+ },+ };+ },+ };++ const result = await compileContentSource({ source, projectId });+ expect(result.diagnostics.sourceIssues).toEqual([+ {+ severity: "warning",+ code: "SOURCE_VALIDATION_UNAVAILABLE",+ message: "File content could not be validated within the query limits",+ assetId: "post",+ path: "blog/post.md",+ },+ ]);+ });+test("compiles MDX sources into the document graph", async () => {const mdx ='---\nauthor:\n $ref: ./author.json#/profile\n---\n<ws.element ws:name="Hero">Hello</ws.element>\n';diff --git a/packages/content-engine/src/content-source.ts b/packages/content-engine/src/content-source.tsindex b8a9b3ff76..225d4e7c3d 100644--- a/packages/content-engine/src/content-source.ts+++ b/packages/content-engine/src/content-source.ts@@ -9,7 +9,7 @@ import {type ContentCompilerDiagnostics,type ContentCompilerInput,} from "./asset-index";-import type { ContentArtifactV1 } from "./schema";+import type { AssetQueryDiagnosticIssue, ContentArtifactV1 } from "./schema";import { discoverMarkdownAssetReferenceRanges } from "./markdown-assets";import { createUniqueAssetIdsByPath } from "./asset-path-resolution";import type { MarkdownAssetReferences } from "./markdown-references";@@ -26,7 +26,11 @@ import {} from "./byte-stream";import { extractMarkdownBody } from "./markdown-body";import { contentEngineLimits } from "./limits";-import { discoverMdxBodyAssetReferences, parseMdxDocument } from "./mdx";+import {+ discoverMdxBodyAssetReferences,+ validateTextAssetSource,+ type MdxDocument,+} from "./mdx";import {compileDocumentSourceGraph,createDocumentSourceUrl,@@ -127,6 +131,34 @@ export class ContentSourceChangedError extends Error {}}+type SourceIssue = NonNullable<+ ContentCompilerDiagnostics["sourceIssues"]+>[number];+type DocumentSourceDiagnostic = SourceIssue &+ Partial<Pick<AssetQueryDiagnosticIssue, "scope" | "phase" | "reference">>;++export class DocumentSourceDiagnosticsError extends Error {+ readonly diagnostics: readonly DocumentSourceDiagnostic[];+ readonly scope: "query" | "database";++ constructor(+ diagnostics: readonly DocumentSourceDiagnostic[],+ scope: "query" | "database" = "query"+ ) {+ const errorCount = diagnostics.filter(+ ({ severity }) => severity === "error"+ ).length;+ super(+ `${errorCount} document source ${+ errorCount === 1 ? "error" : "errors"+ } found`+ );+ this.name = "DocumentSourceDiagnosticsError";+ this.diagnostics = diagnostics;+ this.scope = scope;+ }+}+const validateSnapshot = (snapshot: ContentSourceSnapshot) => {if (snapshot.revision.length === 0) {throw new Error("Content source snapshot revision cannot be empty");@@ -226,15 +258,95 @@ const discoverSnapshotAssetReferences = async ({return references;};+const validateSnapshotDocumentSources = async (+ entries: readonly ContentCompilerInput[]+): Promise<{+ sourceIssues: readonly SourceIssue[];+ mdxDocuments: ReadonlyMap<string, MdxDocument>;+}> => {+ const sourceIssues: SourceIssue[] = [];+ const mdxDocuments = new Map<string, MdxDocument>();+ for (const entry of entries) {+ const format = getDocumentFormatByContentType(entry.document.mimeType);+ if (+ entry.contentRequired &&+ entry.content === undefined &&+ (format === "markdown" || format === "mdx")+ ) {+ sourceIssues.push({+ severity: "warning",+ code: "SOURCE_VALIDATION_UNAVAILABLE",+ message: "File content could not be validated within the query limits",+ assetId: entry.assetId,+ path: entry.document.path,+ });+ }+ if (+ entry.content === undefined ||+ (format !== "markdown" && format !== "mdx")+ ) {+ continue;+ }+ const validation = await validateTextAssetSource({+ source: entry.content,+ format: format === "markdown" ? "md" : "mdx",+ });+ sourceIssues.push(+ ...validation.diagnostics.map((diagnostic) => ({+ severity: diagnostic.severity,+ code: diagnostic.code,+ message: diagnostic.message,+ assetId: entry.assetId,+ path: entry.document.path,+ ...("nodeType" in diagnostic && diagnostic.nodeType !== undefined+ ? { nodeType: diagnostic.nodeType }+ : {}),+ ...("reason" in diagnostic && diagnostic.reason !== undefined+ ? { reason: diagnostic.reason }+ : {}),+ ...("sourceRange" in diagnostic && diagnostic.sourceRange !== undefined+ ? {+ line: diagnostic.sourceRange.start.line,+ column: diagnostic.sourceRange.start.column,+ sourceRange: diagnostic.sourceRange,+ }+ : "line" in diagnostic && diagnostic.line !== undefined+ ? {+ line: diagnostic.line,+ ...(diagnostic.column === undefined+ ? {}+ : { column: diagnostic.column }),+ }+ : {}),+ }))+ );+ if (+ validation.format === "mdx" &&+ validation.recovery.status === "parsed"+ ) {+ mdxDocuments.set(entry.assetId, validation.recovery.document);+ }+ }+ if (sourceIssues.some(({ severity }) => severity === "error")) {+ throw new DocumentSourceDiagnosticsError(sourceIssues);+ }+ return { sourceIssues, mdxDocuments };+};+const discoverSnapshotAssetValueReferences = async ({snapshot,entries,analyzedProperties,+ validation,}: {snapshot: ContentSourceSnapshot;entries: readonly ContentCompilerInput[];analyzedProperties: ReadonlyMap<string, Readonly<Record<string, unknown>>>;-}): Promise<AssetValueReferences> => {+ validation: Awaited<ReturnType<typeof validateSnapshotDocumentSources>>;+}): Promise<{+ references: AssetValueReferences;+ sourceIssues: readonly SourceIssue[];+}> => {const assetIdsByPath = createUniqueAssetIdsByPath(snapshot.files);const structuredAssetIds = new Set(snapshot.files@@ -263,14 +375,11 @@ const discoverSnapshotAssetValueReferences = async ({path: entry.document.path,properties: entry.document.properties ?? {},});- if (- entry.content !== undefined &&- getDocumentFormatByContentType(entry.document.mimeType) === "mdx"- ) {- const document = await parseMdxDocument({ source: entry.content });+ const mdxDocument = validation.mdxDocuments.get(entry.assetId);+ if (mdxDocument !== undefined) {discovered.push(...discoverMdxBodyAssetReferences({- document,+ document: mdxDocument,sourcePath: entry.document.path,assetIdsByPath,})@@ -297,7 +406,7 @@ const discoverSnapshotAssetValueReferences = async ({}}}- return references;+ return { references, sourceIssues: validation.sourceIssues };};const queryNeedsDocumentGraph = (@@ -422,6 +531,7 @@ const discoverSnapshotDocumentGraph = async (return {id: file.id,documentUrl: createDocumentSourceUrl(file.path),+ documentPath: file.path,revision: file.revision,contentRef: file.contentRef,format,@@ -498,6 +608,7 @@ export const materializeContentSnapshot = async ({string,Readonly<Record<string, unknown>>>();+ const validation = await validateSnapshotDocumentSources(entries);const documentGraphResult = await measureContentSourcePerformance({phase: "document-graph",observer: onPerformanceEvent,@@ -518,11 +629,13 @@ export const materializeContentSnapshot = async ({operation: () =>discoverSnapshotAssetReferences({ snapshot, entries, plan }),});- const assetValueReferences = await discoverSnapshotAssetValueReferences({- snapshot,- entries,- analyzedProperties,- });+ const assetValueReferenceResult =+ await discoverSnapshotAssetValueReferences({+ snapshot,+ entries,+ analyzedProperties,+ validation,+ });if (await measureContentSourcePerformance({phase: "source-validation",@@ -535,7 +648,8 @@ export const materializeContentSnapshot = async ({sourceRevision: snapshot.revision,entries,assetReferences,- assetValueReferences,+ assetValueReferences: assetValueReferenceResult.references,+ sourceIssues: assetValueReferenceResult.sourceIssues,documentGraph,documentContents: documentGraphResult?.contents,assetReferenceIssues: documentGraphResult?.assetReferenceIssues ?? [],@@ -581,6 +695,7 @@ export const compileContentSource = async ({entries,assetReferences,assetValueReferences,+ sourceIssues,documentGraph,documentContents,assetReferenceIssues,@@ -608,6 +723,7 @@ export const compileContentSource = async ({diagnostics: {...compiled.diagnostics,...(assetReferenceIssues.length === 0 ? {} : { assetReferenceIssues }),+ ...(sourceIssues.length === 0 ? {} : { sourceIssues }),},};};@@ -632,6 +748,7 @@ export const materializeContentSource = async ({documentGraph?: DocumentGraph;documentContents?: Readonly<Record<string, string>>;assetReferenceIssues: readonly AssetReferenceIssue[];+ sourceIssues: readonly SourceIssue[];}> => {for (let attempt = 0; attempt < 2; attempt += 1) {const snapshot = await source.openSnapshot();diff --git a/packages/content-engine/src/document-graph/compiler.ts b/packages/content-engine/src/document-graph/compiler.tsindex d9e3bcdceb..4b2dba319e 100644--- a/packages/content-engine/src/document-graph/compiler.ts+++ b/packages/content-engine/src/document-graph/compiler.ts@@ -11,6 +11,7 @@ import type { SourceReferenceOccurrence } from "./reference-codec";export type DocumentDescriptor = Readonly<{id: string;documentUrl: string;+ documentPath?: string;revision: string;contentRef: string;format?: DocumentFormat;@@ -31,6 +32,7 @@ export class DocumentGraphCompilationError extends Error {readonly sourceDocumentId?: string;readonly referenceId?: string;readonly documentUrl?: string;+ readonly documentPath?: string;readonly documentIds: readonly string[];constructor({@@ -39,6 +41,7 @@ export class DocumentGraphCompilationError extends Error {sourceDocumentId,referenceId,documentUrl,+ documentPath,documentIds = [],cause,}: {@@ -47,6 +50,7 @@ export class DocumentGraphCompilationError extends Error {sourceDocumentId?: string;referenceId?: string;documentUrl?: string;+ documentPath?: string;documentIds?: readonly string[];cause?: unknown;}) {@@ -56,6 +60,7 @@ export class DocumentGraphCompilationError extends Error {this.sourceDocumentId = sourceDocumentId;this.referenceId = referenceId;this.documentUrl = documentUrl;+ this.documentPath = documentPath;this.documentIds = Object.freeze([...documentIds]);}}diff --git a/packages/content-engine/src/document-graph/markdown-document.test.ts b/packages/content-engine/src/document-graph/markdown-document.test.tsindex d09e0f8621..0915efb585 100644--- a/packages/content-engine/src/document-graph/markdown-document.test.ts+++ b/packages/content-engine/src/document-graph/markdown-document.test.ts@@ -21,6 +21,17 @@ The body can contain { "$ref": "ordinary text" }.`;describe("Markdown document adapter", () => {+ test("keeps the body available when frontmatter is invalid", async () => {+ const analyzed = await analyzeMarkdownDocument({+ source: "---\ntitle: [broken\n---\n# Visible body\n",+ sourceDocumentId: "post",+ documentUrl,+ });++ expect(analyzed.document.frontmatter).toEqual({});+ expect(analyzed.document.body).toBe("# Visible body\n");+ });+test("parses source, body, frontmatter, and compiler-ready references", async () => {const analyzed = await analyzeMarkdownDocument({source,diff --git a/packages/content-engine/src/document-graph/markdown-document.ts b/packages/content-engine/src/document-graph/markdown-document.tsindex cf6e7a9056..2e998ba554 100644--- a/packages/content-engine/src/document-graph/markdown-document.ts+++ b/packages/content-engine/src/document-graph/markdown-document.ts@@ -8,6 +8,7 @@ import {} from "../byte-stream";import { normalizeJsonValue, type JsonValue } from "../canonical-json";import { extractMarkdownFrontmatter } from "../frontmatter";+import { MarkdownMetadataError } from "../markdown-errors";import { contentEngineLimits } from "../limits";import { extractMarkdownBody } from "../markdown-body";import type { DocumentRepresentation } from "./reference";@@ -158,7 +159,12 @@ export const parseMarkdownDocumentSource = async ({}const [body, frontmatter] = await Promise.all([extractMarkdownBody(bytes, maximumBytes),- extractMarkdownFrontmatter(bytes),+ extractMarkdownFrontmatter(bytes).catch((error) => {+ if (error instanceof MarkdownMetadataError) {+ return { properties: {}, frontmatterBytes: 0, consumedBytes: 0 };+ }+ throw error;+ }),]);return normalizeMarkdownDocument({source: sourceText,diff --git a/packages/content-engine/src/document-graph/source-compiler.test.ts b/packages/content-engine/src/document-graph/source-compiler.test.tsindex 019b2d4d1a..1ab4a7893f 100644--- a/packages/content-engine/src/document-graph/source-compiler.test.ts+++ b/packages/content-engine/src/document-graph/source-compiler.test.ts@@ -109,6 +109,54 @@ describe("document source graph compiler", () => {} satisfies Partial<DocumentSourceCompilationError>);});+ test("ignores invalid catalog entries outside the selected root closure", async () => {+ const graph = await compileDocumentSourceGraph({+ documents: [+ { ...documents[0], source: '{"title":"Selected"}' },+ {+ ...documents[1],+ id: "unrelated-one",+ documentUrl: "https://content.webstudio.test/unrelated.md",+ },+ {+ ...documents[1],+ id: "unrelated-two",+ documentUrl: "https://content.webstudio.test/unrelated.md",+ },+ ],+ rootIds: ["post"],+ });++ expect(graph.nodes.map(({ id }) => id)).toEqual(["post"]);+ });++ test("reports every reachable reference failure", async () => {+ await expect(+ compileDocumentSourceGraph({+ documents: [+ {+ ...documents[0],+ id: "first",+ documentUrl: "https://content.webstudio.test/posts/first.json",+ source: '{"author":{"$ref":"../missing/first.md#frontmatter"}}',+ },+ {+ ...documents[0],+ id: "second",+ documentUrl: "https://content.webstudio.test/posts/second.json",+ source: '{"author":{"$ref":"../missing/second.md#frontmatter"}}',+ },+ ],+ rootIds: ["first", "second"],+ })+ ).rejects.toMatchObject({+ errors: [+ { code: "TARGET_NOT_FOUND", sourceDocumentId: "first" },+ { code: "TARGET_NOT_FOUND", sourceDocumentId: "second" },+ ],+ });+ });+test("rejects an already-cancelled compilation before reading sources", async () => {const controller = new AbortController();controller.abort("cancelled");diff --git a/packages/content-engine/src/document-graph/source-compiler.ts b/packages/content-engine/src/document-graph/source-compiler.tsindex 3f7bc7ee7a..36eca4415c 100644--- a/packages/content-engine/src/document-graph/source-compiler.ts+++ b/packages/content-engine/src/document-graph/source-compiler.ts@@ -2,7 +2,11 @@ import { mapBounded } from "../async-utils";import type { ByteSource } from "../byte-stream";import { contentEngineLimits } from "../limits";import { compareStrings } from "../canonical-json";-import { compileDocumentGraph, type DocumentDescriptor } from "./compiler";+import {+ compileDocumentGraph,+ DocumentGraphCompilationError,+ type DocumentDescriptor,+} from "./compiler";import {analyzeDocumentSource,getAdaptedDocumentProperties,@@ -31,22 +35,48 @@ export type DocumentSourceCompilationErrorCode =export class DocumentSourceCompilationError extends Error {readonly code: DocumentSourceCompilationErrorCode;readonly documentId?: string;+ readonly documentPath?: string;constructor({code,message,documentId,+ documentPath,cause,}: {code: DocumentSourceCompilationErrorCode;message: string;documentId?: string;+ documentPath?: string;cause?: unknown;}) {super(message, { cause });this.name = "DocumentSourceCompilationError";this.code = code;this.documentId = documentId;+ this.documentPath = documentPath;+ }+}++export class DocumentSourceCompilationAggregateError extends Error {+ readonly errors: readonly (+ | DocumentSourceCompilationError+ | DocumentGraphCompilationError+ )[];++ constructor(+ errors: readonly (+ | DocumentSourceCompilationError+ | DocumentGraphCompilationError+ )[]+ ) {+ super(+ `${errors.length} document source ${+ errors.length === 1 ? "error" : "errors"+ } found`+ );+ this.name = "DocumentSourceCompilationAggregateError";+ this.errors = Object.freeze([...errors]);}}@@ -84,35 +114,104 @@ export const compileDocumentSourceGraph = async ({signal?: AbortSignal;}): Promise<DocumentGraph> => {assertActive(signal);- // Validate the complete catalog without reading document payloads.- compileDocumentGraph({ documents, references: [] });+ const getDocumentPath = (documentId: string | undefined) => {+ const document =+ documentId === undefined+ ? undefined+ : documents.find(({ id }) => id === documentId);+ if (document === undefined) {+ return;+ }+ if (document.documentPath !== undefined) {+ return document.documentPath;+ }+ try {+ return decodeURIComponent(+ new URL(document.documentUrl).pathname.slice(1)+ );+ } catch {+ return;+ }+ };+ const compileGraph = (+ input: Parameters<typeof compileDocumentGraph>[0]+ ): DocumentGraph => {+ try {+ return compileDocumentGraph(input);+ } catch (error) {+ if (+ error instanceof DocumentGraphCompilationError &&+ error.documentPath === undefined+ ) {+ throw new DocumentGraphCompilationError({+ code: error.code,+ message: error.message,+ sourceDocumentId: error.sourceDocumentId,+ referenceId: error.referenceId,+ documentUrl: error.documentUrl,+ documentPath: getDocumentPath(+ error.sourceDocumentId ?? error.documentIds[0]+ ),+ documentIds: error.documentIds,+ cause: error.cause,+ });+ }+ throw error;+ }+ };+ // A scoped query must not fail because of duplicate or malformed catalog+ // entries that cannot be reached from its roots.+ const selectedRootIds = rootIds === undefined ? undefined : new Set(rootIds);+ compileGraph({+ documents:+ selectedRootIds === undefined+ ? documents+ : documents.filter(({ id }) => selectedRootIds.has(id)),+ references: [],+ });const documentsById = new Map(documents.map((document) => [document.id, document]));- const documentsByUrl = new Map(- documents.map((document) => [new URL(document.documentUrl).href, document])- );+ const documentsByUrl = new Map<string, DocumentSourceDescriptor[]>();+ for (const document of documents) {+ let documentUrl: string;+ try {+ documentUrl = new URL(document.documentUrl).href;+ } catch {+ // Invalid unreachable descriptors are outside a scoped compilation.+ // A selected root is validated above and a referenced target is+ // reported as missing below.+ continue;+ }+ const values = documentsByUrl.get(documentUrl) ?? [];+ values.push(document);+ documentsByUrl.set(documentUrl, values);+ }const pendingIds = new Set(rootIds ?? documents.map(({ id }) => id));const analyzedIds = new Set<string>();+ const failedIds = new Set<string>();const references: SourceReferenceOccurrence[] = [];+ const compilationErrors: Array<+ DocumentSourceCompilationError | DocumentGraphCompilationError+ > = [];while (pendingIds.size > 0) {const frontier = [...pendingIds].sort(compareStrings);pendingIds.clear();- const analyzed = await mapBounded(+ const settlements = await mapBounded(frontier,concurrency,async (documentId) => {- const document = documentsById.get(documentId);- if (document === undefined) {- throw new DocumentSourceCompilationError({- code: "ROOT_NOT_FOUND",- message: `Document source graph root ${documentId} does not exist`,- documentId,- });- }- assertActive(signal);try {+ const document = documentsById.get(documentId);+ if (document === undefined) {+ throw new DocumentSourceCompilationError({+ code: "ROOT_NOT_FOUND",+ message: `Document source graph root ${documentId} does not exist`,+ documentId,+ });+ }+ assertActive(signal);const result = await analyzeDocumentSource({format: document.format,source: document.source,@@ -121,20 +220,40 @@ export const compileDocumentSourceGraph = async ({maximumBytes,});return {- document,- analyzedDocument: result,+ status: "fulfilled" as const,+ value: { document, analyzedDocument: result },};} catch (cause) {assertActive(signal);- throw new DocumentSourceCompilationError({- code: "DOCUMENT_ANALYSIS_FAILED",- message: `Document ${document.id} could not be analyzed`,- documentId: document.id,- cause,- });+ if (cause instanceof DocumentSourceCompilationError) {+ return { status: "rejected" as const, reason: cause, documentId };+ }+ const document = documentsById.get(documentId);+ return {+ status: "rejected" as const,+ reason: new DocumentSourceCompilationError({+ code: "DOCUMENT_ANALYSIS_FAILED",+ message: `Document ${documentId} could not be analyzed`,+ documentId,+ documentPath:+ document === undefined+ ? undefined+ : getDocumentPath(document.id),+ cause,+ }),+ documentId,+ };}});+ const analyzed = settlements.flatMap((settlement) => {+ if (settlement.status === "fulfilled") {+ return [settlement.value];+ }+ failedIds.add(settlement.documentId);+ compilationErrors.push(settlement.reason);+ return [];+ });for (const { document, analyzedDocument } of analyzed) {analyzedIds.add(document.id);const properties = getAdaptedDocumentProperties(analyzedDocument);@@ -150,16 +269,54 @@ export const compileDocumentSourceGraph = async ({) {continue;}+ const targets = documentsByUrl.get(occurrence.reference.documentUrl);+ if (targets !== undefined && targets.length > 1) {+ compilationErrors.push(+ new DocumentGraphCompilationError({+ code: "DUPLICATE_DOCUMENT_URL",+ message: `Documents ${targets.map(({ id }) => id).join(" and ")} have the same canonical URL`,+ sourceDocumentId: occurrence.sourceDocumentId,+ referenceId: occurrence.referenceId,+ documentUrl: occurrence.reference.documentUrl,+ documentPath: getDocumentPath(occurrence.sourceDocumentId),+ documentIds: targets.map(({ id }) => id),+ })+ );+ continue;+ }+ const target = targets?.[0];+ if (target === undefined) {+ compilationErrors.push(+ new DocumentGraphCompilationError({+ code: "TARGET_NOT_FOUND",+ message: `Document ${occurrence.sourceDocumentId} reference ${occurrence.referenceId} target does not exist`,+ sourceDocumentId: occurrence.sourceDocumentId,+ referenceId: occurrence.referenceId,+ documentUrl: occurrence.reference.documentUrl,+ documentPath: getDocumentPath(occurrence.sourceDocumentId),+ documentIds: [occurrence.sourceDocumentId],+ })+ );+ continue;+ }references.push(occurrence);- const target = documentsByUrl.get(occurrence.reference.documentUrl);- if (target !== undefined && analyzedIds.has(target.id) === false) {+ if (+ analyzedIds.has(target.id) === false &&+ failedIds.has(target.id) === false+ ) {pendingIds.add(target.id);}}}}assertActive(signal);- return compileDocumentGraph({+ if (compilationErrors.length === 1) {+ throw compilationErrors[0];+ }+ if (compilationErrors.length > 0) {+ throw new DocumentSourceCompilationAggregateError(compilationErrors);+ }+ return compileGraph({documents: documents.filter(({ id }) => analyzedIds.has(id)),references,});diff --git a/packages/content-engine/src/document-metadata.test.ts b/packages/content-engine/src/document-metadata.test.tsindex 9c3d0fffb0..be36ff9d45 100644--- a/packages/content-engine/src/document-metadata.test.ts+++ b/packages/content-engine/src/document-metadata.test.ts@@ -133,7 +133,17 @@ describe("content metadata cache", () => {expect(prepared.document).not.toHaveProperty("excerpt");expect(prepared.document.metadataError).toMatchObject({code: "FRONTMATTER_INVALID",+ line: 3,+ column: 1,});+ expect(+ prepared.document.metadataError?.message.startsWith(+ "Map keys must be unique"+ )+ ).toBe(true);+ expect(prepared.document.metadataError?.reason).toBe(+ prepared.document.metadataError?.message+ );});test("removes stale excerpts from non-Markdown cache entries", async () => {diff --git a/packages/content-engine/src/document-metadata.ts b/packages/content-engine/src/document-metadata.tsindex e5875c97d0..2b3d3edf07 100644--- a/packages/content-engine/src/document-metadata.ts+++ b/packages/content-engine/src/document-metadata.ts@@ -137,7 +137,15 @@ export const prepareCanonicalContentMetadata = async ({if (error instanceof MarkdownMetadataError === false) {throw error;}- metadataError = { code: error.code, message: error.message };+ const reason =+ error.cause instanceof Error ? error.cause.message : undefined;+ metadataError = {+ code: error.code,+ message: reason ?? error.message,+ ...(reason === undefined ? {} : { reason }),+ ...(error.line === undefined ? {} : { line: error.line }),+ ...(error.column === undefined ? {} : { column: error.column }),+ };}}if (isMarkdown(base) && needsExcerpt) {@@ -147,7 +155,12 @@ export const prepareCanonicalContentMetadata = async ({if (error instanceof MarkdownMetadataError === false) {throw error;}- metadataError ??= { code: error.code, message: error.message };+ metadataError ??= {+ code: error.code,+ message: error.message,+ ...(error.line === undefined ? {} : { line: error.line }),+ ...(error.column === undefined ? {} : { column: error.column }),+ };}}} else if (isJson(base) && needsProperties) {diff --git a/packages/content-engine/src/field-catalog.ts b/packages/content-engine/src/field-catalog.tsindex 70c12d73b3..78ec233487 100644--- a/packages/content-engine/src/field-catalog.ts+++ b/packages/content-engine/src/field-catalog.ts@@ -88,6 +88,7 @@ const getStandardFieldContributions = ({ path: "metadataError", type: "object" } as const,{ path: "metadataError.code", type: "string" } as const,{ path: "metadataError.message", type: "string" } as const,+ { path: "metadataError.reason", type: "string" } as const,]),];diff --git a/packages/content-engine/src/frontmatter.ts b/packages/content-engine/src/frontmatter.tsindex 421459cf03..1b4f412794 100644--- a/packages/content-engine/src/frontmatter.ts+++ b/packages/content-engine/src/frontmatter.ts@@ -1,11 +1,22 @@import { contentEngineLimits } from "./limits";-import { parseDocument, stringify as stringifyYaml } from "yaml";+import {+ isAlias,+ isMap,+ isNode,+ isScalar,+ isSeq,+ LineCounter,+ parseDocument,+ stringify as stringifyYaml,+ type Node,+} from "yaml";import {decodeUtf8 as decodeUtf8Bytes,toByteChunks,type ByteSource,} from "./byte-stream";import {+ getStructuredDataByteLength,normalizeStructuredDataObject,StructuredDataError,} from "./structured-data";@@ -49,18 +60,56 @@ const decodeUtf8 = (bytes: Uint8Array) => {}};+const toMarkdownMetadataError = (error: StructuredDataError) => {+ if (error.code === "DEPTH_EXCEEDED") {+ return new MarkdownMetadataError(+ "FRONTMATTER_DEPTH_EXCEEDED",+ "Markdown frontmatter exceeds the nesting limit"+ );+ }+ if (error.code === "FIELDS_EXCEEDED") {+ return new MarkdownMetadataError(+ "FRONTMATTER_FIELDS_EXCEEDED",+ "Markdown frontmatter exceeds the field limit"+ );+ }+ if (error.code === "STRING_BYTES_EXCEEDED") {+ return new MarkdownMetadataError(+ "FRONTMATTER_STRING_BYTES_EXCEEDED",+ "Markdown frontmatter contains a string that exceeds the byte limit"+ );+ }+ if (error.code === "SERIALIZED_BYTES_EXCEEDED") {+ return new MarkdownMetadataError(+ "FRONTMATTER_BYTES_EXCEEDED",+ "Markdown frontmatter properties exceed the indexed byte limit"+ );+ }+ return new MarkdownMetadataError(+ "FRONTMATTER_INVALID",+ "Markdown frontmatter must contain a JSON-compatible object"+ );+};+const parseYamlProperties = (source: string,limits: FrontmatterLimits): Record<string, unknown> => {+ const lineCounter = new LineCounter();const document = parseDocument(source, {schema: "core",uniqueKeys: true,+ lineCounter,});if (document.errors.length > 0) {+ const error = document.errors[0];+ const location = lineCounter.linePos(error.pos[0]);throw new MarkdownMetadataError("FRONTMATTER_INVALID",- "Markdown frontmatter contains invalid YAML"+ `Markdown frontmatter contains invalid YAML: ${error.message}`,+ // YAML starts after the opening frontmatter delimiter.+ { line: location.line + 1, column: location.col },+ error);}@@ -80,37 +129,221 @@ const parseYamlProperties = (return normalizeStructuredDataObject(value, limits);} catch (error) {if (error instanceof StructuredDataError) {- if (error.code === "DEPTH_EXCEEDED") {- throw new MarkdownMetadataError(- "FRONTMATTER_DEPTH_EXCEEDED",- "Markdown frontmatter exceeds the nesting limit"- );+ throw toMarkdownMetadataError(error);+ }+ throw error;+ }+};++export type MarkdownFrontmatterDiagnostic = Readonly<{+ code: MarkdownMetadataError["code"];+ severity: "warning";+ message: string;+ reason?: string;+ line?: number;+ column?: number;+}>;++const toFrontmatterDiagnostic = (+ error: MarkdownMetadataError,+ reason?: string+): MarkdownFrontmatterDiagnostic => ({+ code: error.code,+ severity: "warning",+ message: reason ?? error.message,+ ...(reason === undefined ? {} : { reason }),+ ...(error.line === undefined ? {} : { line: error.line }),+ ...(error.column === undefined ? {} : { column: error.column }),+});++const createStructuredFrontmatterDiagnostics = (+ root: Node,+ lineCounter: LineCounter,+ value: unknown+): MarkdownFrontmatterDiagnostic[] => {+ const diagnostics: MarkdownFrontmatterDiagnostic[] = [];+ let fields = 0;+ let fieldsExceeded = false;+ const addDiagnostic = (+ error: StructuredDataError,+ node?: Node,+ message?: string+ ) => {+ const location =+ node?.range === undefined || node.range === null+ ? undefined+ : lineCounter.linePos(node.range[0]);+ const metadataError = toMarkdownMetadataError(error);+ const diagnosticMessage = message ?? metadataError.message;+ diagnostics.push(+ toFrontmatterDiagnostic(+ location === undefined+ ? new MarkdownMetadataError(metadataError.code, diagnosticMessage)+ : new MarkdownMetadataError(+ metadataError.code,+ diagnosticMessage,+ // YAML starts after the opening frontmatter delimiter.+ { line: location.line + 1, column: location.col },+ error+ )+ )+ );+ };+ const countField = (node?: Node) => {+ fields += 1;+ if (fieldsExceeded === false && fields > defaultFrontmatterLimits.fields) {+ fieldsExceeded = true;+ addDiagnostic(new StructuredDataError("FIELDS_EXCEEDED"), node);+ }+ };+ const visit = (node: Node, depth: number) => {+ if (depth > defaultFrontmatterLimits.depth) {+ addDiagnostic(new StructuredDataError("DEPTH_EXCEEDED"), node);+ return;+ }+ if (isAlias(node)) {+ addDiagnostic(+ new StructuredDataError("INVALID"),+ node,+ "Markdown frontmatter contains an unsupported YAML alias"+ );+ return;+ }+ if (isScalar(node)) {+ const scalar = node.value;+ if (+ scalar === null ||+ typeof scalar === "boolean" ||+ (typeof scalar === "number" &&+ Number.isFinite(scalar) &&+ (Number.isInteger(scalar) === false || Number.isSafeInteger(scalar)))+ ) {+ return;}- if (error.code === "FIELDS_EXCEEDED") {- throw new MarkdownMetadataError(- "FRONTMATTER_FIELDS_EXCEEDED",- "Markdown frontmatter exceeds the field limit"- );+ if (typeof scalar === "string") {+ if (+ new TextEncoder().encode(scalar).byteLength >+ defaultFrontmatterLimits.stringBytes+ ) {+ addDiagnostic(new StructuredDataError("STRING_BYTES_EXCEEDED"), node);+ }+ return;}- if (error.code === "STRING_BYTES_EXCEEDED") {- throw new MarkdownMetadataError(- "FRONTMATTER_STRING_BYTES_EXCEEDED",- "Markdown frontmatter contains a string that exceeds the byte limit"- );+ addDiagnostic(+ new StructuredDataError("INVALID"),+ node,+ typeof scalar === "number"+ ? Number.isFinite(scalar)+ ? "Markdown frontmatter contains an integer outside the safe range"+ : "Markdown frontmatter contains a non-finite number"+ : "Markdown frontmatter contains a value that JSON cannot represent"+ );+ return;+ }+ if (isMap(node)) {+ for (const pair of node.items) {+ const child = isNode(pair.value) ? pair.value : undefined;+ countField(child ?? (isNode(pair.key) ? pair.key : undefined));+ if (child !== undefined) {+ visit(child, depth + 1);+ }}- if (error.code === "SERIALIZED_BYTES_EXCEEDED") {- throw new MarkdownMetadataError(- "FRONTMATTER_BYTES_EXCEEDED",- "Markdown frontmatter properties exceed the indexed byte limit"- );+ return;+ }+ if (isSeq(node)) {+ for (const value of node.items) {+ const child = isNode(value) ? value : undefined;+ countField(child);+ if (child !== undefined) {+ visit(child, depth + 1);+ }}- throw new MarkdownMetadataError(- "FRONTMATTER_INVALID",- "Markdown frontmatter must contain a JSON-compatible object"- );}- throw error;+ };++ if (isMap(root) === false) {+ addDiagnostic(new StructuredDataError("INVALID"), root);+ }+ visit(root, 1);+ try {+ if (+ getStructuredDataByteLength(value) >+ defaultFrontmatterLimits.serializedBytes+ ) {+ addDiagnostic(new StructuredDataError("SERIALIZED_BYTES_EXCEEDED"));+ }+ } catch {+ // A value that JSON cannot serialize already has a source-positioned+ // INVALID diagnostic from the scalar traversal above.+ }+ return diagnostics;+};++/** Validates authored Markdown frontmatter with the production YAML parser. */+export const createMarkdownFrontmatterDiagnostics = async (+ source: string+): Promise<MarkdownFrontmatterDiagnostic[]> => {+ const bytes = new TextEncoder().encode(source);+ const located = findMarkdownFrontmatter(bytes, true);+ if (located === null) {+ return [];+ }+ if (located === undefined) {+ return [+ toFrontmatterDiagnostic(+ new MarkdownMetadataError(+ "FRONTMATTER_BYTES_EXCEEDED",+ "Markdown frontmatter is not closed within the byte limit"+ )+ ),+ ];+ }+ if (located.yamlEnd - located.yamlStart > defaultFrontmatterLimits.bytes) {+ return [+ toFrontmatterDiagnostic(+ new MarkdownMetadataError(+ "FRONTMATTER_BYTES_EXCEEDED",+ "Markdown frontmatter exceeds the byte limit"+ )+ ),+ ];+ }+ const yaml = new TextDecoder("utf-8", { ignoreBOM: true }).decode(+ bytes.subarray(located.yamlStart, located.yamlEnd)+ );+ const lineCounter = new LineCounter();+ const document = parseDocument(yaml, {+ schema: "core",+ uniqueKeys: true,+ lineCounter,+ });+ if (document.errors.length > 0) {+ return document.errors.map((error) => {+ const location = lineCounter.linePos(error.pos[0]);+ return toFrontmatterDiagnostic(+ new MarkdownMetadataError(+ "FRONTMATTER_INVALID",+ `Markdown frontmatter contains invalid YAML: ${error.message}`,+ { line: location.line + 1, column: location.col },+ error+ ),+ error.message+ );+ });+ }+ const root = document.contents;+ if (root === null) {+ return [];+ }+ let value: unknown;+ try {+ value = document.toJS({ maxAliasCount: 0 });+ } catch {+ // Alias nodes are located and reported individually by the shared AST+ // validation below. The value is not needed for non-serializable input.+ value = undefined;}+ return createStructuredFrontmatterDiagnostics(root, lineCounter, value);};/**diff --git a/packages/content-engine/src/hydration.test.ts b/packages/content-engine/src/hydration.test.tsindex 04c1740513..2a346910c6 100644--- a/packages/content-engine/src/hydration.test.ts+++ b/packages/content-engine/src/hydration.test.ts@@ -250,6 +250,41 @@ describe("selected asset content hydration", () => {});});+ test("reports every selected file hydration failure", async () => {+ const first = createDocument("first-invalid", "xx", { size: 2 });+ const second = createDocument("second-invalid", "xx", { size: 2 });+ const read = createReader({+ [first.contentRef]: new Uint8Array([0xc3, 0x28]),+ [second.contentRef]: new Uint8Array([0xc3, 0x28]),+ });++ await expect(+ hydrateAssetResourceResult({+ result: [identity(first), identity(second)],+ documents: [first, second],+ options: { mode: "full" },+ read,+ })+ ).rejects.toMatchObject({+ code: "CONTENT_DECODING_FAILED",+ details: {+ diagnostics: [+ {+ code: "CONTENT_DECODING_FAILED",+ assetId: "first-invalid",+ path: "blog/first-invalid.md",+ },+ {+ code: "CONTENT_DECODING_FAILED",+ assetId: "second-invalid",+ path: "blog/second-invalid.md",+ },+ ],+ },+ });+ expect(read).toHaveBeenCalledTimes(2);+ });+test("hydrates SVG assets as supported UTF-8 text", async () => {const source = '<svg xmlns="http://www.w3.org/2000/svg"></svg>';const document = createDocument("vector", source, {@@ -302,7 +337,19 @@ describe("selected asset content hydration", () => {await expect.poll(() => release).toBeTypeOf("function");release?.();- await expect(pending).rejects.toThrow("read failed");+ await expect(pending).rejects.toMatchObject({+ code: "INVALID_REQUEST",+ message: "read failed",+ details: {+ diagnostics: [+ {+ code: "CONTENT_READ_FAILED",+ assetId: "failed",+ path: "blog/failed.md",+ },+ ],+ },+ });expect(slowReadCompleted).toBe(true);});});diff --git a/packages/content-engine/src/hydration.ts b/packages/content-engine/src/hydration.tsindex d1bedf9487..ffa671c570 100644--- a/packages/content-engine/src/hydration.ts+++ b/packages/content-engine/src/hydration.ts@@ -1,5 +1,7 @@import type {+ AssetQueryDiagnosticIssue,AssetResourceContentOptions,+ AssetResourceQueryFailure,ContentDatabaseDocument,HydratedAssetContent,} from "./schema";@@ -19,11 +21,12 @@ import {export class AssetResourceHydrationError extends Error {readonly code:+ | "INVALID_REQUEST"| "CONTENT_IDENTITY_REQUIRED"| "CONTENT_NOT_TEXT"| "CONTENT_DECODING_FAILED"| "CONTENT_LIMIT_EXCEEDED";- readonly details?: Record<string, string | number>;+ readonly details?: NonNullable<AssetResourceQueryFailure["error"]["details"]>;constructor({code,@@ -174,6 +177,78 @@ const getAssetResourceHydrationReadLength = (return document.size;};+const throwHydrationFailures = (+ failures: readonly {+ reason: unknown;+ document: ContentDatabaseDocument;+ }[]+): never => {+ const diagnostics = failures.flatMap(+ ({ reason, document }): AssetQueryDiagnosticIssue[] => {+ if (typeof document.path !== "string") {+ return [];+ }+ const code =+ reason instanceof AssetResourceHydrationError+ ? reason.code+ : "CONTENT_READ_FAILED";+ const message =+ reason instanceof Error && reason.message !== ""+ ? reason.message+ : "Selected asset content could not be read";+ return [+ {+ severity: "error",+ scope: "query",+ phase: "source",+ code,+ message,+ assetId: document._id,+ path: document.path,+ },+ ];+ }+ );+ if (diagnostics.length !== failures.length) {+ throw failures[0].reason;+ }+ if (failures.length === 1) {+ const reason = failures[0].reason;+ const diagnostic = diagnostics[0];+ if (diagnostic === undefined) {+ throw reason;+ }+ throw new AssetResourceHydrationError({+ code:+ reason instanceof AssetResourceHydrationError+ ? reason.code+ : "INVALID_REQUEST",+ message: diagnostic.message,+ details: {+ ...(reason instanceof AssetResourceHydrationError+ ? reason.details+ : {}),+ diagnostics,+ },+ });+ }+ const codes = new Set(diagnostics.map(({ code }) => code));+ const commonCode = diagnostics[0]?.code;+ const code =+ codes.size === 1 &&+ (commonCode === "CONTENT_IDENTITY_REQUIRED" ||+ commonCode === "CONTENT_NOT_TEXT" ||+ commonCode === "CONTENT_DECODING_FAILED" ||+ commonCode === "CONTENT_LIMIT_EXCEEDED")+ ? commonCode+ : "INVALID_REQUEST";+ throw new AssetResourceHydrationError({+ code,+ message: `${diagnostics.length} selected asset content errors found`,+ details: { diagnostics },+ });+};+export const hydrateAssetResourceResult = async ({result,documents,@@ -206,45 +281,66 @@ export const hydrateAssetResourceResult = async ({const documentsById = new Map(documents.map((document) => [document._id, document]));- const selected = identities.map((identity) => {+ const selectionSettlements = identities.map((identity) => {const document = documentsById.get(identity._id);- if (- document === undefined ||- document.revision !== identity.revision ||- document.contentRef !== identity.contentRef ||- typeof document.size !== "number" ||- typeof document.mimeType !== "string"- ) {- throw new AssetResourceHydrationError({- code: "CONTENT_IDENTITY_REQUIRED",- message: "Selected asset content identity is stale or unavailable",- details: { assetId: identity._id },- });- }- const hydratableDocument = {- ...document,- size: document.size,- mimeType: document.mimeType,- };- if (isTextDocument(hydratableDocument) === false) {- throw new AssetResourceHydrationError({- code: "CONTENT_NOT_TEXT",- message: "Selected binary asset cannot be embedded as text",- details: {- assetId: identity._id,- mimeType: hydratableDocument.mimeType,+ try {+ if (+ document === undefined ||+ document.revision !== identity.revision ||+ document.contentRef !== identity.contentRef ||+ typeof document.size !== "number" ||+ typeof document.mimeType !== "string"+ ) {+ throw new AssetResourceHydrationError({+ code: "CONTENT_IDENTITY_REQUIRED",+ message: "Selected asset content identity is stale or unavailable",+ details: { assetId: identity._id },+ });+ }+ const hydratableDocument = {+ ...document,+ size: document.size,+ mimeType: document.mimeType,+ };+ if (isTextDocument(hydratableDocument) === false) {+ throw new AssetResourceHydrationError({+ code: "CONTENT_NOT_TEXT",+ message: "Selected binary asset cannot be embedded as text",+ details: {+ assetId: identity._id,+ mimeType: hydratableDocument.mimeType,+ },+ });+ }+ return {+ status: "fulfilled" as const,+ value: {+ identity,+ document: hydratableDocument,+ readLength: getAssetResourceHydrationReadLength(+ hydratableDocument,+ options+ ),},- });+ };+ } catch (reason) {+ return {+ status: "rejected" as const,+ reason,+ document:+ document ?? ({ _id: identity._id } as ContentDatabaseDocument),+ };}- return {- identity,- document: hydratableDocument,- readLength: getAssetResourceHydrationReadLength(- hydratableDocument,- options- ),- };});+ const selectionFailures = selectionSettlements.flatMap((settlement) =>+ settlement.status === "rejected" ? [settlement] : []+ );+ if (selectionFailures.length > 0) {+ throwHydrationFailures(selectionFailures);+ }+ const selected = selectionSettlements.flatMap((settlement) =>+ settlement.status === "fulfilled" ? [settlement.value] : []+ );const totalReadBytes = selected.reduce((total, item) => total + item.readLength,0@@ -260,72 +356,89 @@ export const hydrateAssetResourceResult = async ({});}- const hydrated = await mapBounded(+ const settlements = await mapBounded(selected,contentEngineLimits.concurrentContentReads,async (item) => {- const range =- options.mode === "range"- ? { offset: options.offset, length: item.readLength }- : item.readLength === 0- ? undefined- : { offset: 0, length: item.readLength };- const bytes = await readBytes({- read,- contentRef: item.identity.contentRef,- range,- maximumBytes: item.readLength,- });- if (bytes.byteLength !== item.readLength) {- throw new AssetResourceHydrationError({- code: "CONTENT_IDENTITY_REQUIRED",- message: "Selected asset bytes do not match canonical metadata",- details: { assetId: item.identity._id },+ try {+ const range =+ options.mode === "range"+ ? { offset: options.offset, length: item.readLength }+ : item.readLength === 0+ ? undefined+ : { offset: 0, length: item.readLength };+ const bytes = await readBytes({+ read,+ contentRef: item.identity.contentRef,+ range,+ maximumBytes: item.readLength,});- }- let text: string;- if (options.mode === "markdown-body-ref") {- try {- text = (await extractMarkdownBody(bytes, item.readLength || 1)).body;- const references = assetReferences?.[item.identity.contentRef];- if (references !== undefined && assetUrls !== undefined) {- text = rewriteMarkdownAssetReferenceRanges({- markdown: text,- references,- assetUrls,- });- }- } catch {+ if (bytes.byteLength !== item.readLength) {throw new AssetResourceHydrationError({- code: "CONTENT_DECODING_FAILED",- message: "Selected Markdown body could not be decoded",+ code: "CONTENT_IDENTITY_REQUIRED",+ message: "Selected asset bytes do not match canonical metadata",details: { assetId: item.identity._id },});}- } else {- text = decodeText(bytes);+ let text: string;+ if (options.mode === "markdown-body-ref") {+ try {+ text = (await extractMarkdownBody(bytes, item.readLength || 1))+ .body;+ const references = assetReferences?.[item.identity.contentRef];+ if (references !== undefined && assetUrls !== undefined) {+ text = rewriteMarkdownAssetReferenceRanges({+ markdown: text,+ references,+ assetUrls,+ });+ }+ } catch {+ throw new AssetResourceHydrationError({+ code: "CONTENT_DECODING_FAILED",+ message: "Selected Markdown body could not be decoded",+ details: { assetId: item.identity._id },+ });+ }+ } else {+ text = decodeText(bytes);+ }+ const returnedBytes = getUtf8ByteLength(text);+ return {+ status: "fulfilled" as const,+ value: {+ id: item.identity._id,+ returnedBytes,+ content: {+ ...item.identity,+ encoding: "utf-8" as const,+ text,+ ...(options.mode === "range"+ ? {+ range: {+ offset: options.offset,+ length: bytes.byteLength,+ total: item.document.size,+ },+ }+ : {}),+ },+ },+ };+ } catch (reason) {+ return { status: "rejected" as const, reason, document: item.document };}- const returnedBytes = getUtf8ByteLength(text);- return {- id: item.identity._id,- returnedBytes,- content: {- ...item.identity,- encoding: "utf-8" as const,- text,- ...(options.mode === "range"- ? {- range: {- offset: options.offset,- length: bytes.byteLength,- total: item.document.size,- },- }- : {}),- },- };});+ const failures = settlements.flatMap((settlement) =>+ settlement.status === "rejected" ? [settlement] : []+ );+ if (failures.length > 0) {+ throwHydrationFailures(failures);+ }+ const hydrated = settlements.flatMap((settlement) =>+ settlement.status === "fulfilled" ? [settlement.value] : []+ );return {content: Object.fromEntries(hydrated.map(({ id, content }) => [id, content])diff --git a/packages/content-engine/src/index.ts b/packages/content-engine/src/index.tsindex 89e4611164..e4da5922ec 100644--- a/packages/content-engine/src/index.ts+++ b/packages/content-engine/src/index.ts@@ -10,7 +10,9 @@ export * from "./content-database";export * from "./request";export * from "./query-source";export * from "./query-error";+export * from "./query-error-details";export * from "./document-graph";export * from "./asset-value-references";export * from "./json-assets";export { createUniqueAssetIdsByPath } from "./asset-path-resolution";+export { appendAssetFieldPath } from "./canonical";diff --git a/packages/content-engine/src/markdown-errors.ts b/packages/content-engine/src/markdown-errors.tsindex 8d3bde407b..fbad9cf726 100644--- a/packages/content-engine/src/markdown-errors.ts+++ b/packages/content-engine/src/markdown-errors.ts@@ -11,10 +11,19 @@ export type MarkdownMetadataErrorCode =export class MarkdownMetadataError extends Error {code: MarkdownMetadataErrorCode;+ readonly line?: number;+ readonly column?: number;- constructor(code: MarkdownMetadataErrorCode, message: string) {- super(message);+ constructor(+ code: MarkdownMetadataErrorCode,+ message: string,+ location?: { line: number; column: number },+ cause?: unknown+ ) {+ super(message, { cause });this.name = "MarkdownMetadataError";this.code = code;+ this.line = location?.line;+ this.column = location?.column;}}diff --git a/packages/content-engine/src/markdown.test.ts b/packages/content-engine/src/markdown.test.tsindex f9688eb777..e30a3b6335 100644--- a/packages/content-engine/src/markdown.test.ts+++ b/packages/content-engine/src/markdown.test.ts@@ -1,11 +1,13 @@import { describe, expect, test, vi } from "vitest";import {+ createMarkdownFrontmatterDiagnostics,extractMarkdownBody,extractMarkdownBodyAndExcerpt,extractMarkdownExcerpt,extractMarkdownFrontmatter,MarkdownMetadataError,} from "./markdown";+import { contentEngineLimits } from "./limits";describe("extractMarkdownFrontmatter", () => {test("parses schema-less nested YAML without retaining the body", async () => {@@ -84,9 +86,67 @@ tags: [web, studio]extractMarkdownFrontmatter("---\ntitle: [broken\n---\n")).rejects.toMatchObject({code: "FRONTMATTER_INVALID",+ line: 3,+ column: 1,} satisfies Partial<MarkdownMetadataError>);});+ test("reports every YAML parser error", async () => {+ await expect(+ createMarkdownFrontmatterDiagnostics("---\na: 1\na: 2\nb: 1\nb: 2\n---\n")+ ).resolves.toMatchObject([+ { code: "FRONTMATTER_INVALID", line: 3, column: 1 },+ { code: "FRONTMATTER_INVALID", line: 5, column: 1 },+ ]);+ });++ test("uses the YAML parser error as the frontmatter title and reason", async () => {+ const [diagnostic] = await createMarkdownFrontmatterDiagnostics(+ '---\ntitle: "Broken article\npublished: true\n---\n'+ );++ expect(diagnostic.message.startsWith("Missing closing")).toBe(true);+ expect(diagnostic.reason).toBe(diagnostic.message);+ });++ test("reports every independent post-parse frontmatter limit", async () => {+ const fields = Array.from(+ { length: contentEngineLimits.frontmatterFields + 1 },+ (_, index) => `field${index}: ${index}`+ ).join("\n");+ const depth = Array.from(+ { length: contentEngineLimits.frontmatterDepth + 1 },+ (_, index) => `${" ".repeat(index)}depth${index}:`+ ).join("\n");+ const longString = "x".repeat(+ contentEngineLimits.frontmatterStringBytes + 1+ );+ const compactValues = Array.from({ length: 17_000 }, () => "x").join(",");++ await expect(+ createMarkdownFrontmatterDiagnostics(+ `---\n${depth}\n${" ".repeat(contentEngineLimits.frontmatterDepth + 1)}value\n${fields}\nlong: ${longString}\ncompact: [${compactValues}]\n---\n`+ )+ ).resolves.toMatchObject([+ { code: "FRONTMATTER_DEPTH_EXCEEDED", severity: "warning" },+ { code: "FRONTMATTER_FIELDS_EXCEEDED", severity: "warning" },+ { code: "FRONTMATTER_STRING_BYTES_EXCEEDED", severity: "warning" },+ { code: "FRONTMATTER_BYTES_EXCEEDED", severity: "warning" },+ ]);+ });++ test("reports every non-JSON frontmatter value at its source location", async () => {+ await expect(+ createMarkdownFrontmatterDiagnostics(+ "---\nfirst: .nan\nsecond: .inf\nthird: 9007199254740993\n---\n"+ )+ ).resolves.toMatchObject([+ { code: "FRONTMATTER_INVALID", line: 2, column: 8 },+ { code: "FRONTMATTER_INVALID", line: 3, column: 9 },+ { code: "FRONTMATTER_INVALID", line: 4, column: 8 },+ ]);+ });+test("rejects an unclosed block at the byte boundary", async () => {await expect(extractMarkdownFrontmatter("---\ntitle: too large", { bytes: 8 })diff --git a/packages/content-engine/src/markdown.ts b/packages/content-engine/src/markdown.tsindex 967874a4bc..e53cea6e0a 100644--- a/packages/content-engine/src/markdown.ts+++ b/packages/content-engine/src/markdown.ts@@ -14,7 +14,9 @@ export {} from "./markdown-errors";export { extractMarkdownBody, type MarkdownBody } from "./markdown-body";export {+ createMarkdownFrontmatterDiagnostics,extractMarkdownFrontmatter,+ type MarkdownFrontmatterDiagnostic,type MarkdownFrontmatter,} from "./frontmatter";diff --git a/packages/content-engine/src/mdx.test.ts b/packages/content-engine/src/mdx.test.tsindex d41e3c51a5..a0d4085e42 100644--- a/packages/content-engine/src/mdx.test.ts+++ b/packages/content-engine/src/mdx.test.ts@@ -8,13 +8,17 @@ import {MdxDocumentError,parseMdxDocument,parseMdxDocumentRecovering,+ validateMdxDocumentSource,preferMarkdownSyntax,readMdxCodeBlock,replaceMdxFrontmatter,rewriteMdxAssetReferences,serializeMdxDocument,+ validateTextAssetSource,+ validateTextAssetSourceBytes,type MdxAuthoredNode,} from "./mdx";+import { contentEngineLimits } from "./limits";test("creates and reads canonical fenced code blocks", async () => {const node = createMdxCodeBlock({@@ -1127,6 +1131,154 @@ describe("replaceMdxFrontmatter", () => {});describe("parseMdxDocumentRecovering", () => {+ test("uses fatal UTF-8 decoding for byte source validation", async () => {+ const invalidUtf8 = new Uint8Array([0xc3, 0x28]);++ await expect(+ validateTextAssetSourceBytes({ format: "md", source: invalidUtf8 })+ ).resolves.toEqual({+ format: "md",+ diagnostics: [+ {+ code: "MARKDOWN_BODY_DECODING_FAILED",+ severity: "error",+ message: "Markdown content is not valid UTF-8",+ },+ ],+ });+ await expect(+ validateTextAssetSourceBytes({ format: "mdx", source: invalidUtf8 })+ ).resolves.toEqual({+ format: "mdx",+ diagnostics: [+ {+ code: "invalid-mdx",+ severity: "error",+ message: "MDX content is not valid UTF-8",+ },+ ],+ recovery: {+ status: "unrecoverable",+ diagnostics: [+ expect.objectContaining({+ code: "invalid-mdx",+ message: "MDX content is not valid UTF-8",+ }),+ ],+ },+ });+ });++ test("returns decoded source with byte source validation", async () => {+ await expect(+ validateTextAssetSourceBytes({+ format: "mdx",+ source: new TextEncoder().encode("# Valid\n"),+ })+ ).resolves.toMatchObject({+ format: "mdx",+ source: "# Valid\n",+ diagnostics: [],+ recovery: { status: "parsed" },+ });+ });++ test("uses the shared text validator for Markdown file size errors", async () => {+ await expect(+ validateTextAssetSource({+ format: "md",+ source: "x".repeat(contentEngineLimits.hydratedFileBytes + 1),+ })+ ).resolves.toMatchObject({+ diagnostics: [+ {+ code: "MARKDOWN_BODY_BYTES_EXCEEDED",+ severity: "error",+ },+ ],+ });+ });++ test("reports every recoverable problem as a warning", async () => {+ const result = await validateMdxDocumentSource({+ source: "---\na: 1\na: 2\nb: 1\nb: 2\n---\n\n{first()}\n\n{second()}\n",+ });++ expect(result.diagnostics).toMatchObject([+ { severity: "warning", code: "FRONTMATTER_INVALID", line: 3 },+ { severity: "warning", code: "FRONTMATTER_INVALID", line: 5 },+ {+ severity: "warning",+ message: "Executable MDX expressions are not supported",+ },+ {+ severity: "warning",+ message: "Executable MDX expressions are not supported",+ },+ ]);+ });++ test("continues after an unsupported component to report every sibling", async () => {+ const result = await validateMdxDocumentSource({+ source: "{first()}\n\n<Card />\n\n{second()}\n",+ });++ expect(result.diagnostics).toEqual([+ {+ code: "unsafe-mdx",+ severity: "warning",+ message: "Executable MDX expressions are not supported",+ nodeType: "mdxFlowExpression",+ reason: "Executable MDX expressions are not supported",+ sourceRange: {+ start: { line: 1, column: 1, offset: 0 },+ end: { line: 1, column: 10, offset: 9 },+ },+ },+ {+ code: "unsafe-mdx",+ severity: "warning",+ message: "Only the ws.element component is supported in authored MDX",+ nodeType: "mdxJsxFlowElement",+ reason: "Only the ws.element component is supported in authored MDX",+ sourceRange: {+ start: { line: 3, column: 1, offset: 11 },+ end: { line: 3, column: 9, offset: 19 },+ },+ },+ {+ code: "unsafe-mdx",+ severity: "warning",+ message: "Executable MDX expressions are not supported",+ nodeType: "mdxFlowExpression",+ reason: "Executable MDX expressions are not supported",+ sourceRange: {+ start: { line: 5, column: 1, offset: 21 },+ end: { line: 5, column: 11, offset: 31 },+ },+ },+ ]);+ });++ test("reports diagnostics nested inside an unsupported component", async () => {+ const result = await validateMdxDocumentSource({+ source: "<Card>{danger()}<Other /></Card>\n",+ });++ expect(result.diagnostics.map(({ message }) => message)).toEqual([+ "Only the ws.element component is supported in authored MDX",+ "Executable MDX expressions are not supported",+ "Only the ws.element component is supported in authored MDX",+ ]);+ expect(+ result.diagnostics.map((diagnostic) =>+ "sourceRange" in diagnostic+ ? diagnostic.sourceRange?.start.offset+ : undefined+ )+ ).toEqual([0, 6, 16]);+ });+test("ignores invalid JSX properties without dropping the element", async () => {const source ='<ws.element ws:tag="a" href="/safe" onclick="alert(1)">Kept</ws.element>\n';diff --git a/packages/content-engine/src/mdx.ts b/packages/content-engine/src/mdx.tsindex 6700def18d..601d684c92 100644--- a/packages/content-engine/src/mdx.ts+++ b/packages/content-engine/src/mdx.ts@@ -17,11 +17,14 @@ import {} from "./asset-reference-utils";import { createUniqueAssetIdsByPath } from "./asset-path-resolution";import { getInstancePropName } from "./jsx-attributes";-import { getUtf8ByteLength } from "./byte-stream";+import { decodeUtf8, getUtf8ByteLength } from "./byte-stream";import {+ createMarkdownFrontmatterDiagnostics,extractMarkdownFrontmatter,replaceMarkdownFrontmatter,} from "./frontmatter";++export { createMarkdownFrontmatterDiagnostics } from "./frontmatter";import { contentEngineLimits } from "./limits";import {getSyntaxTreeChildren,@@ -30,7 +33,9 @@ import {type SyntaxTreeNode,} from "./markdown-ast";import { findMarkdownFrontmatter } from "./markdown-scanner";+import { extractMarkdownBody } from "./markdown-body";import { serializeMdxDocument } from "./mdx-serialization";+import { MarkdownMetadataError } from "./markdown-errors";export type MdxSourcePoint = Readonly<{line: number;@@ -240,18 +245,35 @@ export const createMdxSourceDiagnostics = (code: error.code,severity: "error",message: error.message,- sourceRange: error.sourceRange,+ ...(error.sourceRange === undefined+ ? {}+ : { sourceRange: error.sourceRange }),}: {code: error.code,severity: "warning",message: error.reason ?? error.message,- nodeType: error.nodeType,- reason: error.reason,- sourceRange: error.sourceRange,+ ...(error.nodeType === undefined ? {} : { nodeType: error.nodeType }),+ ...(error.reason === undefined ? {} : { reason: error.reason }),+ ...(error.sourceRange === undefined+ ? {}+ : { sourceRange: error.sourceRange }),});+const hasMarkdownMetadataCause = (error: MdxDocumentError) => {+ const visited = new Set<unknown>();+ let cause = error.cause;+ while (cause !== undefined && visited.has(cause) === false) {+ if (cause instanceof MarkdownMetadataError) {+ return true;+ }+ visited.add(cause);+ cause = cause instanceof Error ? cause.cause : undefined;+ }+ return false;+};+const isRecord = (value: unknown): value is Record<string, unknown> =>typeof value === "object" && value !== null;@@ -766,6 +788,10 @@ const createRecoveringHandlers = ({if (start === undefined || end === undefined) {throw error;}+ // The rejected parent is preserved as opaque source, but its children+ // still need validation so one unsupported component cannot hide later+ // diagnostics inside that component.+ state.all(value);diagnostics.push(error);const opaque = {type: "opaque",@@ -786,12 +812,12 @@ const createRecoveringHandlers = ({recover(handler),])) as Handlers;- handlers.mdxJsxFlowElement = createMdxJsxElementHandler({- shouldOmitUnsafePart,- });- handlers.mdxJsxTextElement = createMdxJsxElementHandler({- shouldOmitUnsafePart,- });+ handlers.mdxJsxFlowElement = recover(+ createMdxJsxElementHandler({ shouldOmitUnsafePart })+ );+ handlers.mdxJsxTextElement = recover(+ createMdxJsxElementHandler({ shouldOmitUnsafePart })+ );return {handlers,unknownHandler: recover(rejectUnsupportedNode),@@ -799,6 +825,20 @@ const createRecoveringHandlers = ({};};+const sortMdxDocumentErrors = (errors: readonly MdxDocumentError[]) =>+ [...errors].sort((left, right) => {+ const leftOffset = left.sourceRange?.start.offset;+ const rightOffset = right.sourceRange?.start.offset;+ if (leftOffset === undefined || rightOffset === undefined) {+ return leftOffset === undefined+ ? rightOffset === undefined+ ? 0+ : 1+ : -1;+ }+ return leftOffset - rightOffset;+ });+const createMarkdownHastForMdx = (root: SyntaxTreeNode) => {const hast = toHast(root as Parameters<typeof toHast>[0], {allowDangerousHtml: true,@@ -1420,7 +1460,7 @@ export const parseMdxDocumentRecovering = async ({frontmatter,children: mapAuthoredChildren(root, recovery),},- diagnostics,+ diagnostics: sortMdxDocumentErrors(diagnostics),};} catch (cause) {const error =@@ -1436,6 +1476,170 @@ export const parseMdxDocumentRecovering = async ({}};+export type MdxDocumentSourceDiagnostic =+ | MdxSourceDiagnostic+ | Awaited<ReturnType<typeof createMarkdownFrontmatterDiagnostics>>[number];++/** Validates MDX once and returns every diagnostic with its fatality. */+export const validateMdxDocumentSource = async ({+ source,+}: {+ source: string;+}) => {+ const recovery = await parseMdxDocumentRecovering({ source });+ const frontmatterDiagnostics =+ await createMarkdownFrontmatterDiagnostics(source);+ const mdxDiagnostics = createMdxSourceDiagnostics(+ recovery.diagnostics+ ).filter(+ (_diagnostic, index) =>+ frontmatterDiagnostics.length === 0 ||+ hasMarkdownMetadataCause(recovery.diagnostics[index]) === false+ );+ return {+ recovery,+ diagnostics: [+ ...frontmatterDiagnostics,+ ...mdxDiagnostics,+ ] satisfies readonly MdxDocumentSourceDiagnostic[],+ };+};++export type MarkdownTextAssetSourceDiagnostic =+ | Awaited<ReturnType<typeof createMarkdownFrontmatterDiagnostics>>[number]+ | Readonly<{+ code: "MARKDOWN_BODY_BYTES_EXCEEDED" | "MARKDOWN_BODY_DECODING_FAILED";+ severity: "error";+ message: string;+ }>;++export type TextAssetSourceDiagnostic =+ | MarkdownTextAssetSourceDiagnostic+ | MdxDocumentSourceDiagnostic;++export type TextAssetSourceValidation =+ | Readonly<{+ format: "md";+ diagnostics: readonly MarkdownTextAssetSourceDiagnostic[];+ }>+ | Readonly<{+ format: "mdx";+ diagnostics: readonly MdxDocumentSourceDiagnostic[];+ recovery: Awaited<ReturnType<typeof parseMdxDocumentRecovering>>;+ }>;++export type TextAssetByteSourceValidation = TextAssetSourceValidation &+ Readonly<{+ /** Available only when the complete byte input is valid UTF-8. */+ source?: string;+ }>;++/** Shared source validation contract for the editor, query engine, and MCP. */+export const validateTextAssetSource = async ({+ source,+ format,+}: {+ source: string;+ format: "md" | "mdx";+}): Promise<TextAssetSourceValidation> => {+ if (format === "md") {+ const diagnostics: MarkdownTextAssetSourceDiagnostic[] = [+ ...(await createMarkdownFrontmatterDiagnostics(source)),+ ];+ try {+ await extractMarkdownBody(source);+ } catch (error) {+ if (+ error instanceof MarkdownMetadataError &&+ error.code === "MARKDOWN_BODY_BYTES_EXCEEDED"+ ) {+ return {+ format,+ diagnostics: [+ ...diagnostics,+ {+ code: error.code,+ severity: "error",+ message: error.message,+ },+ ],+ };+ }+ throw error;+ }+ return {+ format,+ diagnostics,+ };+ }+ const validation = await validateMdxDocumentSource({ source });+ return { format, ...validation };+};++/**+ * Fatal-decodes one complete byte source before running the shared source+ * validator. This is the byte-input entry point for query and MCP callers.+ */+export const validateTextAssetSourceBytes = async ({+ source: bytes,+ format,+}: {+ source: Uint8Array;+ format: "md" | "mdx";+}): Promise<TextAssetByteSourceValidation> => {+ if (bytes.byteLength > contentEngineLimits.hydratedFileBytes) {+ if (format === "md") {+ return {+ format,+ diagnostics: [+ {+ code: "MARKDOWN_BODY_BYTES_EXCEEDED",+ severity: "error",+ message: "Markdown content exceeds the byte limit",+ },+ ],+ };+ }+ const error = new MdxDocumentError({+ code: "invalid-mdx",+ message: "MDX content exceeds the byte limit",+ });+ return {+ format,+ diagnostics: createMdxSourceDiagnostics([error]),+ recovery: { status: "unrecoverable", diagnostics: [error] },+ };+ }++ let source: string;+ try {+ source = decodeUtf8(bytes);+ } catch {+ if (format === "md") {+ return {+ format,+ diagnostics: [+ {+ code: "MARKDOWN_BODY_DECODING_FAILED",+ severity: "error",+ message: "Markdown content is not valid UTF-8",+ },+ ],+ };+ }+ const error = new MdxDocumentError({+ code: "invalid-mdx",+ message: "MDX content is not valid UTF-8",+ });+ return {+ format,+ diagnostics: createMdxSourceDiagnostics([error]),+ recovery: { status: "unrecoverable", diagnostics: [error] },+ };+ }+ return { ...(await validateTextAssetSource({ source, format })), source };+};+const withMarkdownSyntax = (node: MdxAuthoredNode): MdxAuthoredNode => {if (node.type !== "element" || node.syntax !== "mdx") {return node;diff --git a/packages/content-engine/src/published-runtime.test.ts b/packages/content-engine/src/published-runtime.test.tsindex 135fe702b9..1b2e3c4dd3 100644--- a/packages/content-engine/src/published-runtime.test.ts+++ b/packages/content-engine/src/published-runtime.test.ts@@ -1052,6 +1052,31 @@ describe("published asset resource runtime", () => {});expect(malformed?.status).toBe(400);+ const structurallyInvalid = await runtimeFetch("/$resources/assets", {+ method: "POST",+ body: JSON.stringify({+ query: {+ result: "first",+ limit: -1,+ output: { mode: "fields", includeMetadata: false, fields: [] },+ content: { mode: "none" },+ },+ }),+ });+ expect(structurallyInvalid?.status).toBe(400);+ await expect(structurallyInvalid?.json()).resolves.toMatchObject({+ error: {+ code: "INVALID_REQUEST",+ details: {+ issues: [+ { path: ["query", "limit"] },+ { path: ["query"] },+ { path: ["query", "sort"] },+ ],+ },+ },+ });+const stale = await runtimeFetch("/$resources/assets", {method: "POST",body: JSON.stringify({diff --git a/packages/content-engine/src/published-runtime.ts b/packages/content-engine/src/published-runtime.tsindex 201cdfb791..ea6b842cda 100644--- a/packages/content-engine/src/published-runtime.ts+++ b/packages/content-engine/src/published-runtime.ts@@ -6,7 +6,10 @@ import { sha256Hex } from "./canonical-json";import { createRuntimeContentDatabase } from "./content-database";import { readAssetQueryRequest } from "./request";import type { AssetRuntimeData } from "./structured-query";-import { getAssetResourceQueryError } from "./query-error";+import {+ getAssetQueryRequestError,+ getAssetResourceQueryError,+} from "./query-error";import {createCachedDocumentSourceLoader,createHttpDocumentSourceLoader,@@ -35,7 +38,7 @@ const failure = ({message: string;status: number;retryable?: boolean;- details?: Record<string, string | number>;+ details?: AssetResourceQueryFailure["error"]["details"];}) =>jsonResponse(createAssetResourceQueryFailure({ code, message, retryable, details }),@@ -219,7 +222,11 @@ const createPublishedAssetResourceHandler = ({let parsedRequest;try {parsedRequest = await readAssetQueryRequest(request.clone());- } catch {+ } catch (error) {+ const queryError = getAssetQueryRequestError(error);+ if (queryError !== undefined) {+ return failure(queryError);+ }return failure({code: "INVALID_REQUEST",message: "Asset resource request is invalid",diff --git a/packages/content-engine/src/query-error-details.ts b/packages/content-engine/src/query-error-details.tsnew file mode 100644index 0000000000..83574e55f6--- /dev/null+++ b/packages/content-engine/src/query-error-details.ts@@ -0,0 +1,381 @@+import { DocumentSourceCompilationError } from "./document-graph/source-compiler";+import { DocumentSourceCompilationAggregateError } from "./document-graph/source-compiler";+import { MdxDocumentError, type MdxSourceRange } from "./mdx";+import { MarkdownMetadataError } from "./markdown-errors";+import {+ DocumentGraphCompilationError,+ DocumentGraphError,+ DocumentGraphResolutionError,+ DocumentReferenceSyntaxError,+ DocumentResolutionLimitError,+ DocumentSourceError,+ HttpDocumentLoaderError,+ JsonDocumentError,+ MarkdownDocumentError,+} from "./document-graph";+import {+ getAssetQueryRequestError,+ getAssetResourceQueryError,+ type AssetResourceQueryError,+} from "./query-error";+import { DocumentSourceDiagnosticsError } from "./content-source";+import type { AssetQueryDiagnosticIssue } from "./schema";++const createInvalidRequestError = (+ message: string,+ details?: AssetResourceQueryError["details"]+): AssetResourceQueryError => ({+ code: "INVALID_REQUEST",+ message,+ retryable: false,+ ...(details === undefined ? {} : { details }),+ status: 400,+});++const findNestedSourceError = (error: unknown) => {+ const visited = new Set<unknown>();+ let current = error;+ let documentError: Error | undefined;+ while (current !== undefined && visited.has(current) === false) {+ if (current instanceof MdxDocumentError) {+ return current;+ }+ if (current instanceof MarkdownMetadataError) {+ return current;+ }+ if (current instanceof Error) {+ documentError ??= current;+ }+ visited.add(current);+ current = current instanceof Error ? current.cause : undefined;+ }+ return documentError;+};++type AssetQueryErrorDiagnosticContext = Readonly<{+ code: string;+ message: string;+ assetId?: string;+ path?: string;+ line?: number;+ column?: number;+ reference?: string;+ nodeType?: string;+ reason?: string;+ sourceRange?: MdxSourceRange;+}>;++const isReferenceErrorCode = (code: string) =>+ code.includes("REFERENCE") ||+ code.includes("TARGET") ||+ code.includes("CYCLE") ||+ code.includes("SELECTION") ||+ code.includes("ASSEMBLY") ||+ code.includes("REPRESENTATION") ||+ code.includes("FRAGMENT") ||+ code.includes("JSON_PATH") ||+ code.includes("JSON_POINTER") ||+ code.includes("RESOLVED_VALUE") ||+ code === "UNUSED_REFERENCE";++const getAssetQueryErrorDiagnosticContext = (+ error: unknown+): AssetQueryErrorDiagnosticContext | undefined => {+ const mapped = getAssetResourceQueryError(error);+ if (mapped !== undefined && mapped.code !== "INVALID_REQUEST") {+ return;+ }+ let code: string | undefined;+ let message: string | undefined;+ let assetId: string | undefined;+ let path: string | undefined;+ let line: number | undefined;+ let column: number | undefined;+ let reference: string | undefined;+ let nodeType: string | undefined;+ let reason: string | undefined;+ let sourceRange: MdxSourceRange | undefined;+ let recognized = false;+ const visited = new Set<unknown>();+ let current = error;+ while (current !== undefined && visited.has(current) === false) {+ if (current instanceof DocumentResolutionLimitError) {+ return;+ }+ if (current instanceof DocumentSourceCompilationError) {+ if (current.code === "REQUEST_CANCELLED") {+ return;+ }+ recognized = true;+ code = current.code;+ message = current.message;+ assetId ??= current.documentId;+ path ??= current.documentPath;+ } else if (current instanceof DocumentGraphCompilationError) {+ recognized = true;+ code = current.code;+ message = current.message;+ assetId ??= current.sourceDocumentId ?? current.documentIds[0];+ path ??= current.documentPath;+ reference ??= current.referenceId ?? current.documentUrl;+ } else if (current instanceof DocumentGraphResolutionError) {+ if (current.code === "REQUEST_CANCELLED") {+ return;+ }+ recognized = true;+ code = current.code;+ message = current.message;+ assetId ??= current.documentId;+ reference ??= current.referenceId;+ } else if (current instanceof DocumentGraphError) {+ recognized = true;+ code = current.code;+ message = current.message;+ assetId ??= current.documentIds[0];+ } else if (+ current instanceof JsonDocumentError ||+ current instanceof MarkdownDocumentError+ ) {+ recognized = true;+ code = current.code;+ message = current.message;+ reference ??= current.referenceId;+ } else if (current instanceof DocumentReferenceSyntaxError) {+ recognized = true;+ code = current.code;+ message = current.message;+ if (typeof current.value === "string" && current.value.length > 0) {+ reference ??= current.value;+ }+ } else if (current instanceof DocumentSourceError) {+ recognized = true;+ code = current.code;+ message = current.message;+ assetId ??= current.documentId;+ } else if (current instanceof HttpDocumentLoaderError) {+ recognized = true;+ code = current.code;+ message = current.message;+ assetId ??= current.documentId;+ } else if (current instanceof MdxDocumentError) {+ recognized = true;+ code = current.code;+ message = current.message;+ line ??= current.sourceRange?.start.line;+ column ??= current.sourceRange?.start.column;+ nodeType ??= current.nodeType;+ reason ??= current.reason;+ sourceRange ??= current.sourceRange;+ } else if (current instanceof MarkdownMetadataError) {+ recognized = true;+ code = current.code;+ message = current.message;+ line ??= current.line;+ column ??= current.column;+ } else if (recognized && current instanceof Error) {+ // Authenticated diagnostics should preserve the deepest concrete cause.+ message = current.message || message;+ }+ visited.add(current);+ current = current instanceof Error ? current.cause : undefined;+ }+ if (recognized === false || code === undefined || message === undefined) {+ return;+ }+ return {+ code,+ message,+ ...(assetId === undefined ? {} : { assetId }),+ ...(path === undefined ? {} : { path }),+ ...(line === undefined ? {} : { line }),+ ...(column === undefined ? {} : { column }),+ ...(reference === undefined ? {} : { reference }),+ ...(nodeType === undefined ? {} : { nodeType }),+ ...(reason === undefined ? {} : { reason }),+ ...(sourceRange === undefined ? {} : { sourceRange }),+ };+};++export const getAssetQueryErrorDiagnosticIssue = ({+ error,+ pathsByAssetId,+}: {+ error: unknown;+ pathsByAssetId?: ReadonlyMap<string, string>;+}): AssetQueryDiagnosticIssue | undefined => {+ const context = getAssetQueryErrorDiagnosticContext(error);+ const path =+ context?.path ??+ (context?.assetId === undefined+ ? undefined+ : pathsByAssetId?.get(context.assetId));+ if (+ context === undefined ||+ context.assetId === undefined ||+ path === undefined+ ) {+ return;+ }+ return {+ severity: "error",+ scope: "query",+ phase: isReferenceErrorCode(context.code) ? "reference" : "source",+ code: context.code,+ message: context.message,+ assetId: context.assetId,+ path,+ ...(context.line === undefined ? {} : { line: context.line }),+ ...(context.column === undefined ? {} : { column: context.column }),+ ...(context.reference === undefined+ ? {}+ : { reference: context.reference }),+ ...(context.nodeType === undefined ? {} : { nodeType: context.nodeType }),+ ...(context.reason === undefined ? {} : { reason: context.reason }),+ ...(context.sourceRange === undefined+ ? {}+ : { sourceRange: context.sourceRange }),+ };+};++export const getDetailedAssetResourceQueryError = (+ error: unknown+): AssetResourceQueryError | undefined => {+ const requestError = getAssetQueryRequestError(error);+ if (requestError !== undefined) {+ return requestError;+ }+ if (error instanceof DocumentSourceDiagnosticsError) {+ return createInvalidRequestError(error.message, {+ diagnostics: error.diagnostics.map((diagnostic) => ({+ ...diagnostic,+ scope: diagnostic.scope ?? error.scope,+ phase: diagnostic.phase ?? "source",+ })),+ });+ }+ if (error instanceof DocumentSourceCompilationAggregateError) {+ const diagnostics = error.errors.flatMap((nestedError) => {+ const diagnostic = getAssetQueryErrorDiagnosticIssue({+ error: nestedError,+ });+ return diagnostic === undefined ? [] : [diagnostic];+ });+ if (diagnostics.length === error.errors.length) {+ return createInvalidRequestError(error.message, { diagnostics });+ }+ return createInvalidRequestError(error.message, {+ errors: error.errors.map((nestedError) => {+ const context = getAssetQueryErrorDiagnosticContext(nestedError);+ return (+ context ?? {+ code: "DOCUMENT_SOURCE_ERROR",+ message:+ nestedError.message || "Document source compilation failed",+ }+ );+ }),+ });+ }+ const exactDiagnostic = getAssetQueryErrorDiagnosticIssue({ error });+ if (exactDiagnostic !== undefined) {+ return createInvalidRequestError(exactDiagnostic.message, {+ diagnostics: [exactDiagnostic],+ });+ }+ const visited = new Set<unknown>();+ let cause = error;+ while (cause !== undefined && visited.has(cause) === false) {+ if (cause instanceof MdxDocumentError) {+ const details: NonNullable<AssetResourceQueryError["details"]> = {};+ const position = cause.sourceRange?.start;+ if (position !== undefined) {+ details.line = position.line;+ details.column = position.column;+ }+ if (cause.reason !== undefined) {+ details.reason = cause.reason;+ }+ if (cause.nodeType !== undefined) {+ details.nodeType = cause.nodeType;+ }+ if (cause.sourceRange !== undefined) {+ details.sourceRange = cause.sourceRange;+ }+ return createInvalidRequestError(cause.message, details);+ }+ if (+ cause instanceof DocumentSourceCompilationError &&+ cause.code !== "REQUEST_CANCELLED"+ ) {+ const details: NonNullable<AssetResourceQueryError["details"]> = {};+ if (cause.documentId !== undefined) {+ details.assetId = cause.documentId;+ }+ if (cause.documentPath !== undefined) {+ details.path = cause.documentPath;+ }+ if (cause.code !== "DOCUMENT_ANALYSIS_FAILED") {+ return createInvalidRequestError(cause.message, details);+ }+ const sourceError = findNestedSourceError(cause.cause);+ if (sourceError instanceof MdxDocumentError) {+ const position = sourceError.sourceRange?.start;+ if (position !== undefined) {+ details.line = position.line;+ details.column = position.column;+ }+ if (sourceError.reason !== undefined) {+ details.reason = sourceError.reason;+ }+ if (sourceError.nodeType !== undefined) {+ details.nodeType = sourceError.nodeType;+ }+ if (sourceError.sourceRange !== undefined) {+ details.sourceRange = sourceError.sourceRange;+ }+ }+ if (sourceError instanceof MarkdownMetadataError) {+ if (sourceError.line !== undefined) {+ details.line = sourceError.line;+ }+ if (sourceError.column !== undefined) {+ details.column = sourceError.column;+ }+ }+ if (sourceError instanceof Error) {+ return createInvalidRequestError(sourceError.message, details);+ }+ return createInvalidRequestError(cause.message, details);+ }+ visited.add(cause);+ cause = cause instanceof Error ? cause.cause : undefined;+ }+ const graphContext = getAssetQueryErrorDiagnosticContext(error);+ if (graphContext !== undefined) {+ const diagnostic = getAssetQueryErrorDiagnosticIssue({ error });+ if (diagnostic !== undefined) {+ return createInvalidRequestError(graphContext.message, {+ diagnostics: [diagnostic],+ });+ }+ return createInvalidRequestError(graphContext.message, {+ code: graphContext.code,+ ...(graphContext.assetId === undefined+ ? {}+ : { assetId: graphContext.assetId }),+ ...(graphContext.reference === undefined+ ? {}+ : { reference: graphContext.reference }),+ ...(graphContext.nodeType === undefined+ ? {}+ : { nodeType: graphContext.nodeType }),+ ...(graphContext.reason === undefined+ ? {}+ : { reason: graphContext.reason }),+ ...(graphContext.sourceRange === undefined+ ? {}+ : { sourceRange: graphContext.sourceRange }),+ });+ }+ return getAssetResourceQueryError(error);+};diff --git a/packages/content-engine/src/query-error.test.ts b/packages/content-engine/src/query-error.test.tsindex f065b3e874..f69e8daade 100644--- a/packages/content-engine/src/query-error.test.ts+++ b/packages/content-engine/src/query-error.test.ts@@ -1,12 +1,113 @@import { describe, expect, test } from "vitest";import {+ DocumentSourceCompilationError,+ DocumentSourceCompilationAggregateError,+ DocumentGraphCompilationError,DocumentGraphResolutionError,+ DocumentReferenceSyntaxError,DocumentResolutionLimitError,+ JsonDocumentError,} from "./document-graph";+import { MdxDocumentError } from "./mdx";+import { MarkdownMetadataError } from "./markdown";+import { MarkdownDocumentError } from "./document-graph/markdown-document";import { getAssetResourceQueryError } from "./query-error";-import { AssetQueryMultipleResultsError } from "./structured-query";+import {+ getAssetQueryErrorDiagnosticIssue,+ getDetailedAssetResourceQueryError,+} from "./query-error-details";+import { AssetQueryRequestError } from "./request";+import {+ AssetQueryExecutionError,+ AssetQueryMultipleResultsError,+} from "./structured-query";+import { DocumentSourceDiagnosticsError } from "./content-source";+import { assetQueryRequest } from "./schema";describe("asset resource graph query errors", () => {+ test("preserves every document source diagnostic", () => {+ const diagnostics = [+ {+ severity: "error" as const,+ code: "invalid-mdx",+ message: "Broken first file",+ assetId: "one",+ path: "posts/one.mdx",+ line: 2,+ column: 1,+ },+ {+ severity: "error" as const,+ code: "invalid-mdx",+ message: "Broken second file",+ assetId: "two",+ path: "posts/two.mdx",+ line: 4,+ column: 3,+ },+ ];++ expect(+ getDetailedAssetResourceQueryError(+ new DocumentSourceDiagnosticsError(diagnostics)+ )+ ).toEqual({+ code: "INVALID_REQUEST",+ message: "2 document source errors found",+ retryable: false,+ status: 400,+ details: {+ diagnostics: diagnostics.map((diagnostic) => ({+ ...diagnostic,+ scope: "query",+ phase: "source",+ })),+ },+ });+ });++ test("preserves the published database scope for source diagnostics", () => {+ const diagnostics = [+ {+ severity: "warning" as const,+ scope: "query" as const,+ phase: "metadata" as const,+ code: "FRONTMATTER_INVALID",+ message: "Current query warning",+ assetId: "current",+ path: "posts/current.md",+ },+ {+ severity: "error" as const,+ code: "invalid-mdx",+ message: "Broken published file",+ assetId: "published",+ path: "posts/published.mdx",+ },+ ];++ expect(+ getDetailedAssetResourceQueryError(+ new DocumentSourceDiagnosticsError(diagnostics, "database")+ )+ ).toMatchObject({+ details: {+ diagnostics: [+ {+ scope: "query",+ phase: "metadata",+ path: "posts/current.md",+ },+ {+ scope: "database",+ phase: "source",+ path: "posts/published.mdx",+ },+ ],+ },+ });+ });+test("maps ambiguous exactly-one queries to a structured error", () => {expect(getAssetResourceQueryError(new AssetQueryMultipleResultsError(2))@@ -19,6 +120,121 @@ describe("asset resource graph query errors", () => {});});+ test("preserves every semantic query setup issue", () => {+ expect(+ getAssetResourceQueryError(+ new AssetQueryExecutionError("2 invalid query operations found", {+ issues: [+ {+ severity: "error",+ code: "INCOMPATIBLE_OPERATOR",+ path: ["query", "where"],+ message: "First incompatible operator",+ },+ {+ severity: "warning",+ code: "UNOBSERVED_FIELD",+ path: ["query", "where"],+ message: "Unobserved field",+ },+ ],+ })+ )+ ).toMatchObject({+ code: "INVALID_REQUEST",+ details: {+ issues: [+ { severity: "error", message: "First incompatible operator" },+ { severity: "warning", message: "Unobserved field" },+ ],+ },+ });+ });++ test("preserves stable execution error codes and details", () => {+ expect(+ getAssetResourceQueryError(+ new AssetQueryExecutionError(+ "Asset query document limit was exceeded",+ {+ code: "CONTENT_LIMIT_EXCEEDED",+ details: { documentCount: 1001, documentLimit: 1000 },+ } as never+ )+ )+ ).toEqual({+ code: "CONTENT_LIMIT_EXCEEDED",+ message: "Asset query document limit was exceeded",+ retryable: false,+ details: { documentCount: 1001, documentLimit: 1000 },+ status: 400,+ });++ expect(+ getAssetResourceQueryError(+ new AssetQueryExecutionError("Asset URL is unavailable for post", {+ details: { assetId: "post" },+ } as never)+ )+ ).toEqual({+ code: "INVALID_REQUEST",+ message: "Asset URL is unavailable for post",+ retryable: false,+ details: { assetId: "post" },+ status: 400,+ });+ });++ test("includes query parser details only for authenticated diagnostics", () => {+ const error = new AssetQueryRequestError("Asset query request is invalid", {+ cause: new SyntaxError(+ "Expected property name or '}' in JSON at position 1"+ ),+ });++ expect(getAssetResourceQueryError(error)).toBeUndefined();+ expect(getDetailedAssetResourceQueryError(error)).toEqual({+ code: "INVALID_REQUEST",+ message: "Expected property name or '}' in JSON at position 1",+ retryable: false,+ status: 400,+ });+ });++ test("preserves every query schema error for authenticated diagnostics", () => {+ const parsed = assetQueryRequest.safeParse({+ query: {+ result: "first",+ limit: -1,+ output: { mode: "fields", includeMetadata: false, fields: [] },+ content: { mode: "none" },+ },+ });+ if (parsed.success) {+ throw new Error("Expected an invalid Asset query request");+ }++ expect(+ getDetailedAssetResourceQueryError(+ new AssetQueryRequestError("Asset query request is invalid", {+ cause: parsed.error,+ })+ )+ ).toMatchObject({+ code: "INVALID_REQUEST",+ message: "Asset query request is invalid",+ retryable: false,+ status: 400,+ details: {+ issues: [+ { path: ["query", "limit"] },+ { path: ["query"] },+ { path: ["query", "sort"] },+ ],+ },+ });+ });+test("maps nested document graph limits to structured content errors", () => {const error = new DocumentGraphResolutionError({code: "DOCUMENT_LOAD_FAILED",@@ -45,4 +261,233 @@ describe("asset resource graph query errors", () => {},});});++ test("maps graph compilation failures to exact file diagnostics", () => {+ const error = new DocumentGraphCompilationError({+ code: "TARGET_NOT_FOUND",+ message: "Referenced author does not exist",+ sourceDocumentId: "post",+ referenceId: "#frontmatter/author",+ documentUrl: "https://content.webstudio.local/authors/missing.md",+ documentPath: "posts/post.md",+ });++ expect(getDetailedAssetResourceQueryError(error)).toEqual({+ code: "INVALID_REQUEST",+ message: "Referenced author does not exist",+ retryable: false,+ status: 400,+ details: {+ diagnostics: [+ {+ severity: "error",+ scope: "query",+ phase: "reference",+ code: "TARGET_NOT_FOUND",+ message: "Referenced author does not exist",+ assetId: "post",+ path: "posts/post.md",+ reference: "#frontmatter/author",+ },+ ],+ },+ });+ });++ test("maps every aggregated graph failure to its exact file", () => {+ const error = new DocumentSourceCompilationAggregateError([+ new DocumentGraphCompilationError({+ code: "TARGET_NOT_FOUND",+ message: "First target does not exist",+ sourceDocumentId: "first",+ referenceId: "#/author",+ documentPath: "posts/first.json",+ }),+ new DocumentGraphCompilationError({+ code: "TARGET_NOT_FOUND",+ message: "Second target does not exist",+ sourceDocumentId: "second",+ referenceId: "#/author",+ documentPath: "posts/second.json",+ }),+ ]);++ expect(getDetailedAssetResourceQueryError(error)).toMatchObject({+ code: "INVALID_REQUEST",+ details: {+ diagnostics: [+ {+ code: "TARGET_NOT_FOUND",+ assetId: "first",+ path: "posts/first.json",+ reference: "#/author",+ },+ {+ code: "TARGET_NOT_FOUND",+ assetId: "second",+ path: "posts/second.json",+ reference: "#/author",+ },+ ],+ },+ });+ });++ test("maps nested graph runtime causes to exact file diagnostics", () => {+ const error = new DocumentGraphResolutionError({+ code: "DOCUMENT_ASSEMBLY_FAILED",+ message: "Post could not be assembled",+ documentId: "post",+ referenceId: "#/author",+ cause: new JsonDocumentError({+ code: "REFERENCE_NOT_FOUND",+ message: "Resolved JSON reference #/author is unavailable",+ referenceId: "#/author",+ }),+ });++ expect(+ getAssetQueryErrorDiagnosticIssue({+ error,+ pathsByAssetId: new Map([["post", "posts/post.json"]]),+ })+ ).toEqual({+ severity: "error",+ scope: "query",+ phase: "reference",+ code: "REFERENCE_NOT_FOUND",+ message: "Resolved JSON reference #/author is unavailable",+ assetId: "post",+ path: "posts/post.json",+ reference: "#/author",+ });+ });++ test("classifies malformed reference fragments as reference diagnostics", () => {+ const error = new DocumentSourceCompilationError({+ code: "DOCUMENT_ANALYSIS_FAILED",+ message: "Document could not be analyzed",+ documentId: "post",+ documentPath: "posts/post.json",+ cause: new DocumentReferenceSyntaxError({+ code: "INVALID_FRAGMENT",+ message: "Document reference fragment is invalid",+ value: "author",+ }),+ });++ expect(getAssetQueryErrorDiagnosticIssue({ error })).toMatchObject({+ phase: "reference",+ code: "INVALID_FRAGMENT",+ assetId: "post",+ path: "posts/post.json",+ reference: "author",+ });+ });++ test("includes source details only for authenticated diagnostics", () => {+ const error = new DocumentSourceCompilationError({+ code: "DOCUMENT_ANALYSIS_FAILED",+ message: "Document could not be analyzed",+ documentId: "post",+ documentPath: "posts/broken.mdx",+ cause: new MdxDocumentError({+ code: "invalid-mdx",+ message: "Unexpected closing tag",+ nodeType: "mdxJsxFlowElement",+ reason: "Unexpected closing tag",+ sourceRange: {+ start: { line: 7, column: 4, offset: 42 },+ end: { line: 7, column: 8, offset: 46 },+ },+ }),+ });++ expect(getAssetResourceQueryError(error)).toBeUndefined();+ expect(getDetailedAssetResourceQueryError(error)).toEqual({+ code: "INVALID_REQUEST",+ message: "Unexpected closing tag",+ retryable: false,+ status: 400,+ details: {+ diagnostics: [+ {+ severity: "error",+ scope: "query",+ phase: "source",+ code: "invalid-mdx",+ message: "Unexpected closing tag",+ assetId: "post",+ path: "posts/broken.mdx",+ line: 7,+ column: 4,+ nodeType: "mdxJsxFlowElement",+ reason: "Unexpected closing tag",+ sourceRange: {+ start: { line: 7, column: 4, offset: 42 },+ end: { line: 7, column: 8, offset: 46 },+ },+ },+ ],+ },+ });+ });++ test("preserves nested Markdown frontmatter errors and file context", () => {+ const error = new DocumentSourceCompilationError({+ code: "DOCUMENT_ANALYSIS_FAILED",+ message: "Document could not be analyzed",+ documentId: "post",+ documentPath: "posts/broken.md",+ cause: new MarkdownDocumentError({+ code: "INVALID_DOCUMENT",+ message: "Markdown document is invalid",+ cause: new MarkdownMetadataError(+ "FRONTMATTER_INVALID",+ "Map keys must be unique",+ { line: 4, column: 1 }+ ),+ }),+ });++ expect(getDetailedAssetResourceQueryError(error)).toEqual({+ code: "INVALID_REQUEST",+ message: "Map keys must be unique",+ retryable: false,+ status: 400,+ details: {+ diagnostics: [+ {+ severity: "error",+ scope: "query",+ phase: "source",+ code: "FRONTMATTER_INVALID",+ message: "Map keys must be unique",+ assetId: "post",+ path: "posts/broken.md",+ line: 4,+ column: 1,+ },+ ],+ },+ });+ });++ test("preserves document source failures that have no nested parser error", () => {+ expect(+ getDetailedAssetResourceQueryError(+ new DocumentSourceCompilationError({+ code: "ROOT_NOT_FOUND",+ message: "Document source graph root missing does not exist",+ documentId: "missing",+ })+ )+ ).toEqual({+ code: "INVALID_REQUEST",+ message: "Document source graph root missing does not exist",+ retryable: false,+ details: { assetId: "missing" },+ status: 400,+ });+ });});diff --git a/packages/content-engine/src/query-error.ts b/packages/content-engine/src/query-error.tsindex 7bbce7ef5e..0dfa283e1e 100644--- a/packages/content-engine/src/query-error.ts+++ b/packages/content-engine/src/query-error.ts@@ -7,15 +7,54 @@ import {} from "./structured-query";import { DocumentResolutionLimitError } from "./document-graph/document-resolution";import { CachedDocumentLoaderError } from "./document-graph/cached-document-loader";+import { AssetQueryRequestError } from "./request";+import { ZodError } from "zod";export type AssetResourceQueryError = Omit<AssetResourceQueryFailure["error"],"details"> & {- details?: Record<string, string | number>;+ details?: NonNullable<AssetResourceQueryFailure["error"]["details"]>;status: 400 | 409;};+export const getAssetQueryRequestError = (+ error: unknown+): AssetResourceQueryError | undefined => {+ if (error instanceof AssetQueryRequestError === false) {+ return;+ }+ let message = error.message;+ const visited = new Set<unknown>();+ let cause = error.cause;+ while (cause instanceof Error && visited.has(cause) === false) {+ if (cause instanceof ZodError) {+ return {+ code: "INVALID_REQUEST",+ message: error.message,+ retryable: false,+ status: 400,+ details: {+ issues: cause.issues.map((issue) => ({+ code: issue.code,+ path: issue.path.map(String),+ message: issue.message,+ })),+ },+ };+ }+ message = cause.message;+ visited.add(cause);+ cause = cause.cause;+ }+ return {+ code: "INVALID_REQUEST",+ message,+ retryable: false,+ status: 400,+ };+};+/** Classifies content-query failures independently of an HTTP or RPC transport. */export const getAssetResourceQueryError = (error: unknown@@ -38,10 +77,22 @@ export const getAssetResourceQueryError = (};}if (error instanceof AssetQueryExecutionError) {+ const details = {+ ...error.details,+ ...(error.issues === undefined+ ? {}+ : {+ issues: error.issues.map((issue) => ({+ ...issue,+ path: [...issue.path],+ })),+ }),+ };return {- code: "INVALID_REQUEST",+ code: error.code,message: error.message,retryable: false,+ ...(Object.keys(details).length === 0 ? {} : { details }),status: 400,};}diff --git a/packages/content-engine/src/schema.test.ts b/packages/content-engine/src/schema.test.tsindex 0839e1dbab..f01af15aab 100644--- a/packages/content-engine/src/schema.test.ts+++ b/packages/content-engine/src/schema.test.ts@@ -1,6 +1,10 @@import { describe, expect, test } from "vitest";import { contentEngineLimits } from "./limits";-import { assetQuery, type AssetQueryWhere } from "./schema";+import {+ assetQuery,+ assetQueryDiagnosticIssue,+ type AssetQueryWhere,+} from "./schema";const condition = {field: ["properties", "slug"],@@ -17,6 +21,24 @@ const nestCondition = (depth: number): AssetQueryWhere => {};describe("assetQuery", () => {+ test("rejects unknown content option fields", () => {+ expect(+ assetQuery.safeParse({+ content: { mode: "none", maxBytes: 1 },+ }).success+ ).toBe(false);+ expect(+ assetQuery.safeParse({+ content: { mode: "full", offset: 0 },+ }).success+ ).toBe(false);+ expect(+ assetQuery.safeParse({+ content: { mode: "range", offset: 0, length: 1, maxBytes: 1 },+ }).success+ ).toBe(false);+ });+test("enforces the filter nesting limit in the request schema", () => {expect(assetQuery.safeParse({@@ -42,3 +64,36 @@ describe("assetQuery", () => {).toBe(false);});});++describe("assetQueryDiagnosticIssue", () => {+ test("preserves complete source locations and parser context", () => {+ expect(+ assetQueryDiagnosticIssue.parse({+ severity: "warning",+ scope: "query",+ phase: "source",+ code: "unsafe-mdx",+ message: "Executable MDX expressions are not supported",+ assetId: "post",+ path: "blog/post.mdx",+ line: 4,+ column: 2,+ reference: "#/body",+ nodeType: "mdxFlowExpression",+ reason: "Executable MDX expressions are not supported",+ sourceRange: {+ start: { line: 4, column: 2, offset: 40 },+ end: { line: 4, column: 9, offset: 47 },+ },+ })+ ).toMatchObject({+ reference: "#/body",+ nodeType: "mdxFlowExpression",+ reason: "Executable MDX expressions are not supported",+ sourceRange: {+ start: { line: 4, column: 2, offset: 40 },+ end: { line: 4, column: 9, offset: 47 },+ },+ });+ });+});diff --git a/packages/content-engine/src/schema.ts b/packages/content-engine/src/schema.tsindex dea28db455..5a56a02f1c 100644--- a/packages/content-engine/src/schema.ts+++ b/packages/content-engine/src/schema.ts@@ -65,6 +65,9 @@ export const assetFileDocument = strictObject({metadataError: strictObject({code: string().min(1),message: string().min(1),+ reason: string().min(1).optional(),+ line: number().int().positive().optional(),+ column: number().int().positive().optional(),}).optional(),});@@ -297,8 +300,8 @@ export const contentArtifactV1 = strictObject({export type ContentArtifactV1 = Infer<typeof contentArtifactV1>;export const assetResourceContentOptions = discriminatedUnion("mode", [- object({ mode: literal("none") }),- object({+ strictObject({ mode: literal("none") }),+ strictObject({mode: literal("full"),maxBytes: number().int()@@ -306,7 +309,7 @@ export const assetResourceContentOptions = discriminatedUnion("mode", [.max(contentEngineLimits.hydratedFileBytes).optional(),}),- object({+ strictObject({mode: literal("range"),offset: number().int().nonnegative(),length: number()@@ -314,7 +317,7 @@ export const assetResourceContentOptions = discriminatedUnion("mode", [.positive().max(contentEngineLimits.hydratedRangeBytes),}),- object({+ strictObject({mode: literal("markdown-body-ref"),maxBytes: number().int()@@ -680,8 +683,49 @@ export type AssetQueryExecutionResult = Infer<typeof assetQueryResult>;/** Backward-compatible collection result type for existing many-result APIs. */export type AssetQueryResult = AssetQueryCollectionResult;+const assetQueryDiagnosticSourcePoint = strictObject({+ line: number().int().positive(),+ column: number().int().positive(),+ offset: number().int().nonnegative().optional(),+});++export const assetQueryDiagnosticIssue = strictObject({+ severity: zEnum(["error", "warning"]),+ scope: zEnum(["query", "database"]),+ phase: zEnum(["metadata", "reference", "source"]),+ code: string().min(1),+ message: string().min(1),+ assetId: string().min(1),+ // Diagnostics must preserve even legacy or storage-derived paths that do+ // not satisfy the canonical asset path grammar.+ path: string().min(1),+ line: number().int().positive().optional(),+ column: number().int().positive().optional(),+ reference: string().min(1).optional(),+ nodeType: string().min(1).optional(),+ reason: string().min(1).optional(),+ sourceRange: strictObject({+ start: assetQueryDiagnosticSourcePoint,+ end: assetQueryDiagnosticSourcePoint,+ }).optional(),+});++export type AssetQueryDiagnosticIssue = Infer<typeof assetQueryDiagnosticIssue>;++export const assetQuerySetupIssue = strictObject({+ severity: zEnum(["error", "warning"]),+ code: string().min(1),+ path: array(string()),+ message: string().min(1),+});++export type AssetQuerySetupIssue = Infer<typeof assetQuerySetupIssue>;+export const assetQueryPreviewDiagnostics = strictObject({scope: literal("query-preview"),+ queryIssues: array(assetQuerySetupIssue).optional(),+ /** @deprecated Use queryIssues for codes and exact query paths. */+ queryWarnings: array(string().min(1)).optional(),query: contentDatabaseCapacityStats,database: contentDatabaseCapacityStats,artifacts: strictObject({@@ -689,6 +733,9 @@ export const assetQueryPreviewDiagnostics = strictObject({database: contentArtifactV1,}).optional(),unresolved: assetQueryResult.optional(),+ issues: array(assetQueryDiagnosticIssue).optional(),+ issueCount: number().int().nonnegative().optional(),+ issuesTruncated: boolean().optional(),});export type AssetQueryPreviewDiagnostics = Infer<diff --git a/packages/content-engine/src/structured-query.test.ts b/packages/content-engine/src/structured-query.test.tsindex 568f9c1374..174f22ea35 100644--- a/packages/content-engine/src/structured-query.test.ts+++ b/packages/content-engine/src/structured-query.test.ts@@ -9,6 +9,7 @@ import {executeAssetQueries,getAssetQueryFieldValue,supportsAssetQueryContent,+ validateAssetQuery,validateAssetQueryAgainstCatalog,} from "./structured-query";import { contentEngineLimits } from "./limits";@@ -830,6 +831,134 @@ describe("structured asset query", () => {expect(result.totalCount).toBe(0);});+ test("reports every fatal query operation together with nonfatal warnings", () => {+ expect(() =>+ validateAssetQueryAgainstCatalog({+ catalog,+ query: {+ where: {+ all: [+ { field: ["width"], operator: "contains", value: 1 },+ { field: ["height"], operator: "startsWith", value: "1" },+ {+ field: ["properties", "missing"],+ operator: "eq",+ value: true,+ },+ ],+ },+ },+ })+ ).toThrowError(+ expect.objectContaining({+ message: "2 invalid query operations found",+ issues: [+ expect.objectContaining({+ severity: "error",+ path: ["query", "where", "all", "0", "operator"],+ message: "Operator contains is incompatible with width",+ }),+ expect.objectContaining({+ severity: "error",+ path: ["query", "where", "all", "1", "operator"],+ message: "Operator startsWith is incompatible with height",+ }),+ expect.objectContaining({+ severity: "warning",+ path: ["query", "where", "all", "2", "field"],+ message: "Asset field properties.missing is not currently observed",+ }),+ ],+ })+ );+ });++ test("reports invalid standard-field values and output-only unobserved fields", () => {+ expect(() =>+ validateAssetQueryAgainstCatalog({+ catalog,+ query: {+ where: {+ all: [+ { field: ["size"], operator: "gt", value: "large" },+ { field: ["extension"], operator: "in", value: ["md", 1] },+ ],+ },+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["properties", "summary"]],+ },+ },+ })+ ).toThrowError(+ expect.objectContaining({+ message: "2 invalid query operations found",+ issues: [+ expect.objectContaining({+ severity: "error",+ code: "INCOMPATIBLE_VALUE",+ path: ["query", "where", "all", "0", "value"],+ }),+ expect.objectContaining({+ severity: "error",+ code: "INCOMPATIBLE_VALUE",+ path: ["query", "where", "all", "1", "value", "1"],+ }),+ expect.objectContaining({+ severity: "warning",+ code: "UNOBSERVED_FIELD",+ path: ["query", "output", "fields", "0"],+ }),+ ],+ })+ );+ });++ test("preserves structural issue codes and warns about observed value types", () => {+ expect(+ validateAssetQuery({+ catalog,+ query: {+ limit: -1,+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [],+ },+ },+ })+ ).toMatchObject({+ success: false,+ issues: [+ { code: "too_small", path: ["query", "limit"] },+ { code: "custom", path: ["query"] },+ ],+ });++ expect(+ validateAssetQuery({+ catalog,+ query: {+ where: {+ field: ["properties", "draft"],+ operator: "eq",+ value: "yes",+ },+ },+ })+ ).toMatchObject({+ success: true,+ issues: [+ {+ severity: "warning",+ code: "INCOMPATIBLE_OBSERVED_VALUE",+ path: ["query", "where", "value"],+ },+ ],+ });+ });+test("keeps sorting deterministic when a dynamic field becomes mixed", async () => {const mixedDocuments = [...documents,@@ -1073,7 +1202,7 @@ describe("structured asset query", () => {});});- test("omits empty properties from query results", async () => {+ test("returns IDs for all-fields results without properties", async () => {const empty = document({ id: "empty", properties: {} });const withExcerpt = document({id: "excerpt",@@ -1090,7 +1219,7 @@ describe("structured asset query", () => {query: {where: { all: [] },sort: [],- limit: 1,+ limit: 2,offset: 0,output: { mode: "all", includeMetadata: false },content: { mode: "none" },@@ -1098,8 +1227,8 @@ describe("structured asset query", () => {});expect(result).toMatchObject({- items: [{ id: "excerpt", excerpt: "Excerpt" }],- totalCount: 1,+ items: [{ id: "empty" }, { id: "excerpt", excerpt: "Excerpt" }],+ totalCount: 2,hasMore: false,});});diff --git a/packages/content-engine/src/structured-query.ts b/packages/content-engine/src/structured-query.tsindex aad47c8a2a..dfd620a071 100644--- a/packages/content-engine/src/structured-query.ts+++ b/packages/content-engine/src/structured-query.ts@@ -22,6 +22,9 @@ import {type AssetResourceContentOptions,type AssetResourceOutputSelection,type BuilderAssetFieldCatalog,+ type AssetQuerySetupIssue,+ type AssetResourceErrorCode,+ type AssetResourceQueryFailure,} from "./schema";import { contentEngineLimits } from "./limits";import {@@ -48,9 +51,23 @@ import {export type { AssetRuntimeData } from "./asset-value-references";export class AssetQueryExecutionError extends Error {- constructor(message: string, options?: ErrorOptions) {+ readonly code: AssetResourceErrorCode;+ readonly issues?: readonly AssetQuerySetupIssue[];+ readonly details?: NonNullable<AssetResourceQueryFailure["error"]["details"]>;++ constructor(+ message: string,+ options?: ErrorOptions & {+ code?: AssetResourceErrorCode;+ issues?: readonly AssetQuerySetupIssue[];+ details?: NonNullable<AssetResourceQueryFailure["error"]["details"]>;+ }+ ) {super(message, options);this.name = "AssetQueryExecutionError";+ this.code = options?.code ?? "INVALID_REQUEST";+ this.issues = options?.issues;+ this.details = options?.details;}}@@ -100,17 +117,145 @@ const getCatalogField = (? catalog.fields[path]: undefined;-export const validateAssetQueryAgainstCatalog = ({+const getObservedValueType = (+ value: unknown+): AssetObservedFieldType | undefined => {+ if (value === null) {+ return "null";+ }+ if (Array.isArray(value)) {+ return "array";+ }+ if (typeof value === "object") {+ return "object";+ }+ if (typeof value === "boolean") {+ return "boolean";+ }+ if (typeof value === "number") {+ return "number";+ }+ if (typeof value === "string") {+ return "string";+ }+};++const getCompatibleFilterValueTypes = ({+ operator,+ fieldTypes,+}: {+ operator: AssetQueryFilter["operator"];+ fieldTypes: readonly AssetObservedFieldType[];+}) => {+ if (operator === "contains" && fieldTypes.includes("array")) {+ return;+ }+ if (+ operator === "startsWith" ||+ operator === "endsWith" ||+ operator === "contains"+ ) {+ return ["string"] as const;+ }+ if (+ operator === "gt" ||+ operator === "gte" ||+ operator === "lt" ||+ operator === "lte"+ ) {+ return fieldTypes.filter(+ (type): type is "string" | "number" =>+ type === "string" || type === "number"+ );+ }+ if (operator === "eq" || operator === "ne" || operator === "in") {+ return fieldTypes;+ }+};++const getIncompatibleFilterValuePaths = ({+ filter,+ fieldTypes,+ path,+}: {+ filter: AssetQueryFilter;+ fieldTypes: readonly AssetObservedFieldType[];+ path: string[];+}) => {+ const compatibleTypes = getCompatibleFilterValueTypes({+ operator: filter.operator,+ fieldTypes,+ });+ if (compatibleTypes === undefined) {+ return [];+ }+ const values = filter.operator === "in" ? filter.value : [filter.value];+ return values.flatMap((value, index) =>+ compatibleTypes.some((type) => type === getObservedValueType(value))+ ? []+ : [+ filter.operator === "in"+ ? [...path, "value", String(index)]+ : [...path, "value"],+ ]+ );+};++const getQueryConditionsWithPaths = (+ where: AssetQueryWhere,+ path: string[] = ["query", "where"]+): Array<{ filter: AssetQueryFilter; path: string[] }> => {+ if ("field" in where) {+ return [{ filter: where, path }];+ }+ if ("all" in where) {+ return where.all.flatMap((child, index) =>+ getQueryConditionsWithPaths(child, [...path, "all", String(index)])+ );+ }+ return where.any.flatMap((child, index) =>+ getQueryConditionsWithPaths(child, [...path, "any", String(index)])+ );+};++export const validateAssetQuery = ({query: input,catalog,}: {- query: AssetQueryInput;+ query: unknown;catalog?: BuilderAssetFieldCatalog;}) => {- const query = assetQuery.parse(input);+ const parsed = assetQuery.safeParse(input);+ if (parsed.success === false) {+ return {+ success: false as const,+ issues: parsed.error.issues.map(+ (issue): AssetQuerySetupIssue => ({+ severity: "error",+ code: issue.code,+ path: ["query", ...issue.path.map(String)],+ message: issue.message,+ })+ ),+ };+ }+ const query = parsed.data;const referencedFieldPaths = new Map<string, AssetQueryFieldPath>();const warnings: string[] = [];- for (const filter of getQueryConditions(query.where)) {+ const issues: AssetQuerySetupIssue[] = [];+ const addWarning = (+ code:+ | "UNOBSERVED_FIELD"+ | "INCOMPATIBLE_OBSERVED_TYPES"+ | "INCOMPATIBLE_OBSERVED_VALUE"+ | "STRUCTURED_SORT_ORDER",+ path: string[],+ message: string+ ) => {+ warnings.push(message);+ issues.push({ severity: "warning", code, path, message });+ };+ for (const { filter, path } of getQueryConditionsWithPaths(query.where)) {const catalogPath = getCatalogPath(filter.field);referencedFieldPaths.set(catalogPath, filter.field);if (filter.field[0] === "properties") {@@ -119,33 +264,68 @@ export const validateAssetQueryAgainstCatalog = ({// observed documents for authoring assistance, but deleting the last// matching file must not invalidate an otherwise valid saved query.if (catalog !== undefined && field === undefined) {- warnings.push(`Asset field ${catalogPath} is not currently observed`);+ addWarning(+ "UNOBSERVED_FIELD",+ [...path, "field"],+ `Asset field ${catalogPath} is not currently observed`+ );} else if (field !== undefined &&isFilterOperatorCompatible({ filter, fieldTypes: field.types }) ===false) {- warnings.push(+ addWarning(+ "INCOMPATIBLE_OBSERVED_TYPES",+ [...path, "operator"],`Operator ${filter.operator} is not compatible with the currently observed types of ${catalogPath}`);+ } else if (field !== undefined) {+ for (const valuePath of getIncompatibleFilterValuePaths({+ filter,+ fieldTypes: field.types,+ path,+ })) {+ addWarning(+ "INCOMPATIBLE_OBSERVED_VALUE",+ valuePath,+ `Filter value is not compatible with the currently observed types of ${catalogPath}`+ );+ }}} else {+ const fieldTypes =+ assetQueryStandardFieldTypes[+ filter.field[0] as keyof typeof assetQueryStandardFieldTypes+ ];if (isFilterOperatorCompatible({filter,- fieldTypes:- assetQueryStandardFieldTypes[- filter.field[0] as keyof typeof assetQueryStandardFieldTypes- ],+ fieldTypes,}) === false) {- throw new AssetQueryExecutionError(- `Operator ${filter.operator} is incompatible with ${catalogPath}`- );+ issues.push({+ severity: "error",+ code: "INCOMPATIBLE_OPERATOR",+ path: [...path, "operator"],+ message: `Operator ${filter.operator} is incompatible with ${catalogPath}`,+ });+ } else {+ for (const valuePath of getIncompatibleFilterValuePaths({+ filter,+ fieldTypes,+ path,+ })) {+ issues.push({+ severity: "error",+ code: "INCOMPATIBLE_VALUE",+ path: valuePath,+ message: `Filter value is incompatible with ${catalogPath}`,+ });+ }}}}- for (const order of query.sort) {+ for (const [index, order] of query.sort.entries()) {const catalogPath = getCatalogPath(order.field);referencedFieldPaths.set(catalogPath, order.field);// Sorting is defined for every JSON value by compareSortValues below.@@ -154,21 +334,82 @@ export const validateAssetQueryAgainstCatalog = ({if (order.field[0] === "properties") {const field = getCatalogField(catalog, catalogPath);if (catalog !== undefined && field === undefined) {- warnings.push(`Asset field ${catalogPath} is not currently observed`);+ addWarning(+ "UNOBSERVED_FIELD",+ ["query", "sort", String(index), "field"],+ `Asset field ${catalogPath} is not currently observed`+ );} else if (field !== undefined &&field.types.some((type) => type === "object" || type === "array")) {- warnings.push(+ addWarning(+ "STRUCTURED_SORT_ORDER",+ ["query", "sort", String(index), "field"],`Asset field ${catalogPath} currently includes structured values that use deterministic JSON sort order`);}}}+ if (query.output.mode === "fields") {+ for (const [index, fieldPath] of query.output.fields.entries()) {+ const catalogPath = getCatalogPath(fieldPath);+ referencedFieldPaths.set(catalogPath, fieldPath);+ if (+ fieldPath[0] === "properties" &&+ catalog !== undefined &&+ getCatalogField(catalog, catalogPath) === undefined+ ) {+ addWarning(+ "UNOBSERVED_FIELD",+ ["query", "output", "fields", String(index)],+ `Asset field ${catalogPath} is not currently observed`+ );+ }+ }+ }+ const uniqueIssues = [+ ...new Map(+ issues.map((issue) => [+ JSON.stringify([issue.code, issue.path, issue.message]),+ issue,+ ])+ ).values(),+ ];return {+ success:+ uniqueIssues.some(({ severity }) => severity === "error") === false,query,referencedFieldPaths: [...referencedFieldPaths.values()],warnings: [...new Set(warnings)],+ issues: uniqueIssues,+ };+};++export const validateAssetQueryAgainstCatalog = ({+ query,+ catalog,+}: {+ query: AssetQueryInput;+ catalog?: BuilderAssetFieldCatalog;+}) => {+ const validation = validateAssetQuery({ query, catalog });+ if (validation.success === false) {+ const errors = validation.issues.filter(+ ({ severity }) => severity === "error"+ );+ throw new AssetQueryExecutionError(+ errors.length === 1+ ? errors[0].message+ : `${errors.length} invalid query operations found`,+ { issues: validation.issues }+ );+ }+ return {+ query: validation.query,+ referencedFieldPaths: validation.referencedFieldPaths,+ warnings: validation.warnings,+ warningIssues: validation.issues,};};@@ -420,7 +661,10 @@ const toQueryItem = (runtimeAsset?: AssetRuntimeData) => {if (includesOutputField(output, "url") && runtimeAsset === undefined) {- throw new Error(`Asset URL is unavailable for ${document._id}`);+ throw new AssetQueryExecutionError(+ `Asset URL is unavailable for ${document._id}`,+ { details: { assetId: document._id } }+ );}const properties = selectProperties(document, output);const hasDimensions =@@ -452,12 +696,17 @@ const toQueryItem = (export const assertAssetQueryResultSize = (result: AssetQueryExecutionResult) => {- if (- getUtf8ByteLength(serializeJsonDeterministically(result)) >- contentEngineLimits.resultBytes- ) {+ const resultBytes = getUtf8ByteLength(serializeJsonDeterministically(result));+ if (resultBytes > contentEngineLimits.resultBytes) {throw new AssetQueryExecutionError(- "Asset query result exceeds the byte limit"+ "Asset query result exceeds the byte limit",+ {+ code: "CONTENT_LIMIT_EXCEEDED",+ details: {+ resultBytes,+ resultByteLimit: contentEngineLimits.resultBytes,+ },+ });}};@@ -600,6 +849,7 @@ const scanAndSortAssetQueryDocuments = ({if (query.content.mode === "none" &&Object.keys(projected).length === 0 &&+ query.output.mode !== "all" &&includesOutputField(query.output, "id") === false) {continue;@@ -747,7 +997,16 @@ export const executeAssetQueries = async ({preparedQueries,results,createReason: () =>- new AssetQueryExecutionError("Asset query document limit was exceeded"),+ new AssetQueryExecutionError(+ "Asset query document limit was exceeded",+ {+ code: "CONTENT_LIMIT_EXCEEDED",+ details: {+ documentCount: documents.length,+ documentLimit: contentEngineLimits.candidateDocuments,+ },+ }+ ),});return requireSettledAssetQueryResults(results);}diff --git a/packages/project-build/src/content-database.ts b/packages/project-build/src/content-database.tsindex c8bb2b5bee..9c3fc85a6a 100644--- a/packages/project-build/src/content-database.ts+++ b/packages/project-build/src/content-database.ts@@ -18,6 +18,7 @@ import {blockComponent,collectionComponent,createReachableAssetContentCompilationPlan,+ createReachableAssetContentCompilationPlanResult,decodeDataSourceVariable,findTreeInstanceIdsExcludingBlockTemplates,getContentBlockSource,@@ -107,6 +108,15 @@ export const createBuildContentCompilationPlan = (resources: getBuildValues<Resource>(build.resources),});+export const createBuildContentCompilationPlanResult = (+ build: ContentDatabaseBuild+) =>+ createReachableAssetContentCompilationPlanResult({+ props: getBuildValues<Prop>(build.props),+ dataSources: getBuildValues<DataSource>(build.dataSources),+ resources: getBuildValues<Resource>(build.resources),+ });+const getPublishedContentBlockSources = (build: PublishedContentDatabaseBuild,publishedInstanceIds: ReadonlySet<string> = getPublishedInstanceIds(build)diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.tsindex 941359624e..396bc12291 100644--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts@@ -72365,6 +72365,7 @@ export const runtimeOperationContractData = [},},required: ["mode"],+ additionalProperties: false,},{type: "object",@@ -72380,6 +72381,7 @@ export const runtimeOperationContractData = [},},required: ["mode"],+ additionalProperties: false,},{type: "object",@@ -72400,6 +72402,7 @@ export const runtimeOperationContractData = [},},required: ["mode", "offset", "length"],+ additionalProperties: false,},{type: "object",@@ -72415,6 +72418,7 @@ export const runtimeOperationContractData = [},},required: ["mode"],+ additionalProperties: false,},],},@@ -72762,6 +72766,7 @@ export const runtimeOperationContractData = [},},required: ["mode"],+ additionalProperties: false,},{type: "object",@@ -72777,6 +72782,7 @@ export const runtimeOperationContractData = [},},required: ["mode"],+ additionalProperties: false,},{type: "object",@@ -72797,6 +72803,7 @@ export const runtimeOperationContractData = [},},required: ["mode", "offset", "length"],+ additionalProperties: false,},{type: "object",@@ -72812,6 +72819,7 @@ export const runtimeOperationContractData = [},},required: ["mode"],+ additionalProperties: false,},],},@@ -73239,6 +73247,7 @@ export const runtimeOperationContractData = [},},required: ["mode"],+ additionalProperties: false,},{type: "object",@@ -73254,6 +73263,7 @@ export const runtimeOperationContractData = [},},required: ["mode"],+ additionalProperties: false,},{type: "object",@@ -73274,6 +73284,7 @@ export const runtimeOperationContractData = [},},required: ["mode", "offset", "length"],+ additionalProperties: false,},{type: "object",@@ -73289,6 +73300,7 @@ export const runtimeOperationContractData = [},},required: ["mode"],+ additionalProperties: false,},],},@@ -73800,6 +73812,7 @@ export const runtimeOperationContractData = [},},required: ["mode"],+ additionalProperties: false,},{type: "object",@@ -73815,6 +73828,7 @@ export const runtimeOperationContractData = [},},required: ["mode"],+ additionalProperties: false,},{type: "object",@@ -73835,6 +73849,7 @@ export const runtimeOperationContractData = [},},required: ["mode", "offset", "length"],+ additionalProperties: false,},{type: "object",@@ -73850,6 +73865,7 @@ export const runtimeOperationContractData = [},},required: ["mode"],+ additionalProperties: false,},],},diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.tsindex 233b54271d..d69fc45fb0 100644--- a/packages/project-build/src/mcp.test.ts+++ b/packages/project-build/src/mcp.test.ts@@ -11,6 +11,7 @@ import { describe, expect, test, vi } from "vitest";import { z } from "zod";import type { WsComponentMeta } from "@webstudio-is/sdk";import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";+import { validateAssetQuery } from "@webstudio-is/content-engine";import { builderPatchTransactionSchema } from "./contracts/patch";import { runtimeOperationContracts } from "./contracts/builder-runtime";import { getInputSchemaMetadata } from "./contracts/input-schema";@@ -1310,6 +1311,15 @@ describe("project session mcp adapter", () => {end: { line: 3, column: 11, offset: 18 },},},+ {+ code: "unresolved-template" as const,+ severity: "warning" as const,+ blockInstanceId: "content-block-1",+ assetId,+ contentRef: "asset:hero",+ renderScope: "asset:hero:block:content-block-1",+ templateName: "MissingCard",+ },],}));const adapter = createProjectSessionMcpCore({@@ -1335,6 +1345,15 @@ describe("project session mcp adapter", () => {code: "unsafe-mdx",severity: "warning",}),+ expect.objectContaining({+ code: "unresolved-template",+ severity: "warning",+ blockInstanceId: "content-block-1",+ assetId: "hero",+ contentRef: "asset:hero",+ renderScope: "asset:hero:block:content-block-1",+ templateName: "MissingCard",+ }),],},});@@ -2399,6 +2418,88 @@ describe("project session mcp adapter", () => {expect(executeOperation).not.toHaveBeenCalled();});+ test("reports unknown, missing, and wrong-type input fields together", async () => {+ const createPageOperation = publicOperation({+ command: "create-page",+ id: "pages.create",+ description: "Create a page",+ method: "mutation",+ inputSchema: getTestInputSchema(+ z.object({ name: z.string(), path: z.string() })+ ),+ });+ const executeOperation: ExecuteOperation = vi.fn();+ const adapter = createProjectSessionMcpCore({+ operations: [...publicMcpOperations, createPageOperation],+ createProjectSession: createSessionFactory(),+ executeOperation,+ });++ let error: unknown;+ try {+ await adapter.callTool({+ name: "create-page",+ input: { name: 42, unexpected: true },+ });+ } catch (caught) {+ error = caught;+ }++ expect(error).toMatchObject({+ code: "INVALID_INPUT",+ issues: [+ expect.objectContaining({ path: ["path"], constraint: "required" }),+ expect.objectContaining({ path: ["name"], constraint: "type:string" }),+ expect.objectContaining({ path: ["unexpected"] }),+ ],+ });+ expect(executeOperation).not.toHaveBeenCalled();+ });++ test("uses the shared query validator and keeps root input errors", async () => {+ const operation = publicOperation({+ command: "validate-asset-query",+ id: "assetQueries.validate",+ description: "Validate an Asset query",+ inputSchema: getTestInputSchema(z.object({ query: z.unknown() })),+ });+ const executeOperation: ExecuteOperation = vi.fn();+ const adapter = createProjectSessionMcpCore({+ operations: [operation],+ createProjectSession: createSessionFactory(),+ executeOperation,+ });+ const query = {+ result: "first",+ limit: -1,+ output: { mode: "fields", includeMetadata: false, fields: [] },+ content: { mode: "none" },+ unexpected: true,+ };+ const sharedIssues = validateAssetQuery({ query })+ .issues.filter(({ severity }) => severity === "error")+ .map((issue) => ({ ...issue, constraint: issue.code }));++ let error: unknown;+ try {+ await adapter.callTool({+ name: "validate-asset-query",+ input: { query, unexpectedRoot: true },+ });+ } catch (caught) {+ error = caught;+ }++ expect(error).toMatchObject({+ code: "INVALID_INPUT",+ issues: [+ ...sharedIssues,+ expect.objectContaining({ path: ["unexpectedRoot"] }),+ ],+ });+ expect(executeOperation).not.toHaveBeenCalled();+ });+test("converts jsx fragments before executing insert operation", async () => {const executeOperation = createExecuteOperation(async () =>createEnvelope({@@ -8697,6 +8798,180 @@ describe("project session mcp adapter", () => {}});+ test("returns all input shape errors through the MCP server", async () => {+ const executeOperation = createExecuteOperation();+ const createPageOperation = publicOperation({+ command: "create-page",+ id: "pages.create",+ description: "Create a page",+ method: "mutation",+ inputSchema: getTestInputSchema(+ z.object({ name: z.string(), path: z.string() })+ ),+ });+ const server = await createProjectSessionMcpServer({+ operations: [...publicMcpOperations, createPageOperation],+ createProjectSession: createSessionFactory(),+ executeOperation,+ });+ const { client, close } = await createConnectedClient(server);++ try {+ const result = await client.callTool({+ name: "create-page",+ arguments: { name: 42, unexpected: true },+ });+ expect(result.structuredContent).toMatchObject({+ ok: false,+ error: {+ code: "INVALID_INPUT",+ issues: [+ expect.objectContaining({ path: ["path"], constraint: "required" }),+ expect.objectContaining({+ path: ["name"],+ constraint: "type:string",+ }),+ expect.objectContaining({ path: ["unexpected"] }),+ ],+ },+ });+ expect(executeOperation).not.toHaveBeenCalled();+ } finally {+ await close();+ }+ });++ test("returns every Markdown upload input error through the MCP server", async () => {+ const executeOperation = createExecuteOperation();+ const uploadAssetsOperation = publicOperation({+ command: "upload-assets",+ id: "assets.uploadMany",+ description: "Upload Assets",+ method: "mutation",+ inputSchema: getTestInputSchema(+ z.object({+ assets: z.array(+ z.object({+ name: z.string(),+ type: z.string(),+ format: z.string().optional(),+ })+ ),+ assetsDir: z.string().optional(),+ })+ ),+ });+ const server = await createProjectSessionMcpServer({+ operations: [...publicMcpOperations, uploadAssetsOperation],+ createProjectSession: createSessionFactory(),+ executeOperation,+ });+ const { client, close } = await createConnectedClient(server);++ try {+ const result = await client.callTool({+ name: "upload-assets",+ arguments: {+ assets: [+ { name: 42, type: "file", format: "md" },+ { name: "page.mdx", type: "image", format: "md" },+ ],+ unexpected: true,+ },+ });+ expect(result.structuredContent).toMatchObject({+ ok: false,+ error: {+ code: "INVALID_INPUT",+ issues: expect.arrayContaining([+ expect.objectContaining({+ path: ["assets", "0", "name"],+ constraint: "type:string",+ }),+ expect.objectContaining({+ path: ["assets", "1", "format"],+ code: "asset_filename_format_mismatch",+ }),+ expect.objectContaining({+ path: ["assets", "1", "type"],+ code: "markdown_asset_type_mismatch",+ }),+ expect.objectContaining({ path: ["unexpected"] }),+ ]),+ },+ });+ expect(executeOperation).not.toHaveBeenCalled();+ } finally {+ await close();+ }+ });++ test("returns every Asset content update input error through the MCP server", async () => {+ const executeOperation = createExecuteOperation();+ const baseInputSchema = getTestInputSchema(+ z.object({+ assetId: z.string().min(1),+ expectedName: z.string().min(1),+ extension: z.string().min(1).optional(),+ path: z.string().min(1).optional(),+ content: z.string().optional(),+ })+ );+ const updateAssetContentOperation = publicOperation({+ command: "update-asset-content",+ id: "assets.updateContent",+ description: "Update Asset content",+ method: "mutation",+ inputSchema: {+ ...baseInputSchema,+ oneOf: [{ required: ["path"] }, { required: ["content"] }],+ },+ });+ const server = await createProjectSessionMcpServer({+ operations: [...publicMcpOperations, updateAssetContentOperation],+ createProjectSession: createSessionFactory(),+ executeOperation,+ });+ const { client, close } = await createConnectedClient(server);++ try {+ const result = await client.callTool({+ name: "update-asset-content",+ arguments: {+ assetId: 42,+ expectedName: "",+ path: "article.md",+ content: "# Duplicate source",+ unexpected: true,+ },+ });+ expect(result.structuredContent).toMatchObject({+ ok: false,+ error: {+ code: "INVALID_INPUT",+ issues: expect.arrayContaining([+ expect.objectContaining({+ path: ["assetId"],+ constraint: "type:string",+ }),+ expect.objectContaining({+ path: ["expectedName"],+ constraint: "minLength:1",+ }),+ expect.objectContaining({+ path: [],+ constraint: "exactly_one_of:path|content",+ }),+ expect.objectContaining({ path: ["unexpected"] }),+ ]),+ },+ });+ expect(executeOperation).not.toHaveBeenCalled();+ } finally {+ await close();+ }+ });+test("returns equivalent structured runtime validation issues", async () => {const issue = {code: "invalid_expression",diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.tsindex c5e6faf837..488807765c 100644--- a/packages/project-build/src/mcp.ts+++ b/packages/project-build/src/mcp.ts@@ -6,6 +6,7 @@ import {import {getInputJsonSchemaMetadata,getInputJsonSchemaProperties,+ getFileExtension,inputJsonSchemaAcceptsType,parseComponentName,toInputJsonSchemaObject,@@ -17,6 +18,8 @@ import {allowedArrayMethods,allowedStringMethods,} from "@webstudio-is/expression";+import type { TextAssetSourceDiagnostic } from "@webstudio-is/content-engine/mdx";+import { validateAssetQuery } from "@webstudio-is/content-engine";import { distance as getLevenshteinDistance } from "fastest-levenshtein";import type { BuilderApiCapability } from "./contracts/permissions";import path from "node:path";@@ -297,20 +300,7 @@ export type ProjectSessionDownloadAssetResult = {assetId: string;path: string;source?: string;- diagnostics?: readonly (- | ContentBlockDiagnostic- | Readonly<{- code: "invalid-mdx" | "unsafe-mdx";- severity: "error" | "warning";- message: string;- nodeType?: string;- reason?: string;- sourceRange?: Readonly<{- start: Readonly<{ line: number; column: number; offset?: number }>;- end: Readonly<{ line: number; column: number; offset?: number }>;- }>;- }>- )[];+ diagnostics?: readonly (ContentBlockDiagnostic | TextAssetSourceDiagnostic)[];};type DownloadAsset = (@@ -1024,7 +1014,95 @@ const getUnsupportedInputFieldHint = ({return "";};-const assertKnownInputFields = ({+export const getMcpTextAssetFormat = (+ value: string+): "md" | "mdx" | undefined => {+ const extension = (getFileExtension(value) ?? value).toLowerCase();+ return extension === "md" || extension === "mdx" ? extension : undefined;+};++export const getMcpTextAssetDescriptorIssues = ({+ assets,+ pathPrefix,+}: {+ assets: readonly Record<string, unknown>[];+ pathPrefix: readonly string[];+}): SemanticValidationIssue[] => {+ const issues: SemanticValidationIssue[] = [];+ for (const [index, asset] of assets.entries()) {+ const name = typeof asset.name === "string" ? asset.name : undefined;+ const filenameFormat =+ name === undefined ? undefined : getFileExtension(name)?.toLowerCase();+ const declaredFormat =+ typeof asset.format === "string" ? asset.format.toLowerCase() : undefined;+ const mentionsTextFormat =+ filenameFormat === "md" ||+ filenameFormat === "mdx" ||+ declaredFormat === "md" ||+ declaredFormat === "mdx";+ const assetPath =+ pathPrefix[0] === "asset"+ ? [...pathPrefix]+ : [...pathPrefix, String(index)];+ if (+ name !== undefined &&+ mentionsTextFormat &&+ declaredFormat !== undefined &&+ declaredFormat !== filenameFormat+ ) {+ issues.push({+ path: [...assetPath, "format"],+ code: "asset_filename_format_mismatch",+ message: `Asset filename and format must match. ${JSON.stringify(name)} has extension ${JSON.stringify(filenameFormat ?? "(none)")} but format is ${JSON.stringify(declaredFormat)}.`,+ constraint: "asset_filename_format_mismatch",+ });+ }+ if (+ mentionsTextFormat &&+ typeof asset.type === "string" &&+ asset.type !== "file"+ ) {+ issues.push({+ path: [...assetPath, "type"],+ code: "markdown_asset_type_mismatch",+ message: `Markdown and MDX Assets must use type "file", not ${JSON.stringify(asset.type)}.`,+ constraint: "markdown_asset_type_mismatch",+ });+ }+ }+ return issues;+};++const getLocalTextAssetInputIssues = ({+ command,+ input,+}: {+ command: string;+ input: unknown;+}) => {+ if (isPlainRecord(input) === false) {+ return [];+ }+ if (command === "upload-asset") {+ return isPlainRecord(input.asset)+ ? getMcpTextAssetDescriptorIssues({+ assets: [input.asset],+ pathPrefix: ["asset"],+ })+ : [];+ }+ if (command === "upload-assets") {+ return Array.isArray(input.assets)+ ? getMcpTextAssetDescriptorIssues({+ assets: input.assets.filter(isPlainRecord),+ pathPrefix: ["assets"],+ })+ : [];+ }+ return [];+};++const collectUnknownInputFields = ({command,input,schema,@@ -1034,30 +1112,38 @@ const assertKnownInputFields = ({input: unknown;schema: InputJsonSchema | undefined;path?: string[];-}) => {+}): Array<{ message: string; issue: SemanticValidationIssue }> => {+ const results: Array<{ message: string; issue: SemanticValidationIssue }> =+ [];if (Array.isArray(input)) {for (const [index, item] of input.entries()) {- assertKnownInputFields({- command,- input: item,- schema: toInputJsonSchemaObject(schema?.items),- path: [...path, String(index)],- });+ results.push(+ ...collectUnknownInputFields({+ command,+ input: item,+ schema: toInputJsonSchemaObject(schema?.items),+ path: [...path, String(index)],+ })+ );}- return;+ return results;}if (isPlainRecord(input) === false) {- return;+ return results;}const properties = getInputJsonSchemaProperties(schema);const additionalProperties = schema?.additionalProperties;- if (additionalProperties !== false) {- return;- }const allowedFields = Object.keys(properties ?? {});for (const [field, value] of Object.entries(input)) {- const fieldSchema = toInputJsonSchemaObject(properties?.[field]);- if (fieldSchema === undefined) {+ const isKnownField =+ properties !== undefined &&+ Object.prototype.hasOwnProperty.call(properties, field);+ const fieldSchema = isKnownField+ ? toInputJsonSchemaObject(properties[field])+ : typeof additionalProperties === "object"+ ? toInputJsonSchemaObject(additionalProperties)+ : undefined;+ if (isKnownField === false && additionalProperties === false) {const inputPath = ["input", ...path, field].join(".");const expected =allowedFields.length === 0@@ -1067,17 +1153,403 @@ const assertKnownInputFields = ({const suggestion =closestField === undefined ? "" : ` Did you mean ${closestField}?`;const hint = getUnsupportedInputFieldHint({ command, field });- throw new Error(- `${command} ${inputPath} is not supported. ${expected}${suggestion}${hint}`- );+ const message = `${command} ${inputPath} is not supported. ${expected}${suggestion}${hint}`;+ results.push({+ message,+ issue: {+ code: "unknown_field",+ path: [...path, field],+ message,+ constraint: "known_input_field",+ ...(closestField === undefined ? {} : { example: closestField }),+ },+ });+ continue;}- assertKnownInputFields({+ if (fieldSchema === undefined) {+ continue;+ }+ results.push(+ ...collectUnknownInputFields({+ command,+ input: value,+ schema: fieldSchema,+ path: [...path, field],+ })+ );+ }+ return results;+};++const getJsonValueType = (value: unknown) => {+ if (value === null) {+ return "null";+ }+ if (Array.isArray(value)) {+ return "array";+ }+ if (typeof value === "number" && Number.isInteger(value)) {+ return "integer";+ }+ return typeof value;+};++const collectInputSchemaIssues = ({+ command,+ input,+ schema,+ path = [],+ depth = 0,+}: {+ command: string;+ input: unknown;+ schema: InputJsonSchema | undefined;+ path?: string[];+ depth?: number;+}): SemanticValidationIssue[] => {+ if (schema === undefined || depth > 64) {+ return [];+ }+ const inputPath = ["input", ...path].join(".");+ const issue = ({+ code,+ message,+ constraint,+ example,+ }: {+ code: string;+ message: string;+ constraint: string;+ example?: unknown;+ }): SemanticValidationIssue => ({+ code,+ path,+ message: `${command} ${inputPath} ${message}`,+ constraint,+ ...(example === undefined ? {} : { example }),+ });+ const discriminatedSchema = resolveDiscriminatedInputSchema(schema, input);+ if (discriminatedSchema !== schema) {+ return collectInputSchemaIssues({command,- input: value,- schema: fieldSchema,- path: [...path, field],+ input,+ schema: discriminatedSchema,+ path,+ depth: depth + 1,});}+ const allowedTypes =+ schema.type === undefined+ ? []+ : Array.isArray(schema.type)+ ? schema.type+ : [schema.type];+ if (allowedTypes.length > 0) {+ const actualType = getJsonValueType(input);+ const matches = allowedTypes.some(+ (type) =>+ type === actualType || (type === "number" && actualType === "integer")+ );+ if (matches === false) {+ return [+ issue({+ code: "invalid_type",+ message: `must be ${allowedTypes.join(" or ")}, not ${actualType}.`,+ constraint: `type:${allowedTypes.join("|")}`,+ }),+ ];+ }+ }+ if ("const" in schema && Object.is(input, schema.const) === false) {+ return [+ issue({+ code: "invalid_value",+ message: `must equal ${JSON.stringify(schema.const)}.`,+ constraint: "const",+ example: schema.const,+ }),+ ];+ }+ if (+ Array.isArray(schema.enum) &&+ schema.enum.some((value) => Object.is(value, input)) === false+ ) {+ return [+ issue({+ code: "invalid_value",+ message: `must be one of ${schema.enum.map((value) => JSON.stringify(value)).join(", ")}.`,+ constraint: "enum",+ example: schema.enum[0],+ }),+ ];+ }+ const issues: SemanticValidationIssue[] = [];+ if (typeof input === "string") {+ if (+ typeof schema.minLength === "number" &&+ input.length < schema.minLength+ ) {+ issues.push(+ issue({+ code: "too_small",+ message: `must contain at least ${schema.minLength} characters.`,+ constraint: `minLength:${schema.minLength}`,+ })+ );+ }+ if (+ typeof schema.maxLength === "number" &&+ input.length > schema.maxLength+ ) {+ issues.push(+ issue({+ code: "too_big",+ message: `must contain at most ${schema.maxLength} characters.`,+ constraint: `maxLength:${schema.maxLength}`,+ })+ );+ }+ }+ if (typeof input === "number") {+ if (typeof schema.minimum === "number" && input < schema.minimum) {+ issues.push(+ issue({+ code: "too_small",+ message: `must be at least ${schema.minimum}.`,+ constraint: `minimum:${schema.minimum}`,+ })+ );+ }+ if (typeof schema.maximum === "number" && input > schema.maximum) {+ issues.push(+ issue({+ code: "too_big",+ message: `must be at most ${schema.maximum}.`,+ constraint: `maximum:${schema.maximum}`,+ })+ );+ }+ if (+ typeof schema.exclusiveMinimum === "number" &&+ input <= schema.exclusiveMinimum+ ) {+ issues.push(+ issue({+ code: "too_small",+ message: `must be greater than ${schema.exclusiveMinimum}.`,+ constraint: `exclusiveMinimum:${schema.exclusiveMinimum}`,+ })+ );+ }+ if (+ typeof schema.exclusiveMaximum === "number" &&+ input >= schema.exclusiveMaximum+ ) {+ issues.push(+ issue({+ code: "too_big",+ message: `must be less than ${schema.exclusiveMaximum}.`,+ constraint: `exclusiveMaximum:${schema.exclusiveMaximum}`,+ })+ );+ }+ }+ if (isPlainRecord(input)) {+ for (const requiredField of schema.required ?? []) {+ if (typeof requiredField !== "string" || requiredField in input) {+ continue;+ }+ issues.push({+ code: "invalid_type",+ path: [...path, requiredField],+ message: `${command} ${["input", ...path, requiredField].join(".")} is required.`,+ constraint: "required",+ });+ }+ const properties = getInputJsonSchemaProperties(schema);+ for (const [field, value] of Object.entries(input)) {+ const fieldSchema = toInputJsonSchemaObject(properties?.[field]);+ if (fieldSchema === undefined) {+ continue;+ }+ issues.push(+ ...collectInputSchemaIssues({+ command,+ input: value,+ schema: fieldSchema,+ path: [...path, field],+ depth: depth + 1,+ })+ );+ }+ }+ if (Array.isArray(input)) {+ if (typeof schema.minItems === "number" && input.length < schema.minItems) {+ issues.push(+ issue({+ code: "too_small",+ message: `must contain at least ${schema.minItems} items.`,+ constraint: `minItems:${schema.minItems}`,+ })+ );+ }+ if (typeof schema.maxItems === "number" && input.length > schema.maxItems) {+ issues.push(+ issue({+ code: "too_big",+ message: `must contain at most ${schema.maxItems} items.`,+ constraint: `maxItems:${schema.maxItems}`,+ })+ );+ }+ const itemSchema = toInputJsonSchemaObject(schema.items);+ if (itemSchema !== undefined) {+ for (const [index, value] of input.entries()) {+ issues.push(+ ...collectInputSchemaIssues({+ command,+ input: value,+ schema: itemSchema,+ path: [...path, String(index)],+ depth: depth + 1,+ })+ );+ }+ }+ }+ for (const branch of schema.allOf ?? []) {+ issues.push(+ ...collectInputSchemaIssues({+ command,+ input,+ schema: toInputJsonSchemaObject(branch),+ path,+ depth: depth + 1,+ })+ );+ }+ const oneOfBranches = (schema.oneOf ?? []).flatMap((branch) => {+ const branchSchema = toInputJsonSchemaObject(branch);+ return branchSchema === undefined+ ? []+ : [+ collectInputSchemaIssues({+ command,+ input,+ schema: branchSchema,+ path,+ depth: depth + 1,+ }),+ ];+ });+ if (oneOfBranches.length > 0) {+ const matchingBranches = oneOfBranches.filter(+ (branchIssues) => branchIssues.length === 0+ ).length;+ if (matchingBranches !== 1) {+ const requiredFields = (schema.oneOf ?? []).flatMap((branch) => {+ const branchSchema = toInputJsonSchemaObject(branch);+ return branchSchema?.required?.length === 1 &&+ typeof branchSchema.required[0] === "string"+ ? [branchSchema.required[0]]+ : [];+ });+ issues.push(+ issue({+ code: "invalid_union",+ message:+ requiredFields.length === oneOfBranches.length+ ? `must provide exactly one of ${requiredFields.join(", ")}.`+ : "must match exactly one allowed input shape.",+ constraint:+ requiredFields.length === oneOfBranches.length+ ? `exactly_one_of:${requiredFields.join("|")}`+ : "oneOf",+ })+ );+ }+ }+ const anyOfBranches = (schema.anyOf ?? []).flatMap((branch) => {+ const branchSchema = toInputJsonSchemaObject(branch);+ return branchSchema === undefined+ ? []+ : [+ collectInputSchemaIssues({+ command,+ input,+ schema: branchSchema,+ path,+ depth: depth + 1,+ }),+ ];+ });+ if (+ anyOfBranches.length > 0 &&+ anyOfBranches.some((branchIssues) => branchIssues.length === 0) === false+ ) {+ issues.push(+ ...anyOfBranches.reduce((best, current) =>+ current.length < best.length ? current : best+ )+ );+ }+ return issues;+};++const assertKnownInputFields = (+ options: Parameters<typeof collectUnknownInputFields>[0]+) => {+ const validatesAssetQuery =+ options.command === "validate-asset-query" ||+ options.command === "preview-asset-query";+ const queryValidation =+ validatesAssetQuery && isPlainRecord(options.input)+ ? validateAssetQuery({ query: options.input.query })+ : undefined;+ const queryIssues = (queryValidation?.issues ?? [])+ .filter(({ severity }) => severity === "error")+ .map(+ (issue): SemanticValidationIssue => ({+ ...issue,+ constraint: issue.code,+ })+ );+ const outsideQuery = (issue: SemanticValidationIssue) =>+ validatesAssetQuery === false || issue.path[0] !== "query";+ const unknownFields = collectUnknownInputFields(options).filter(({ issue }) =>+ outsideQuery(issue)+ );+ const localTextAssetIssues = getLocalTextAssetInputIssues(options);+ const validatesLocalTextAssetInput =+ options.command === "upload-asset" ||+ options.command === "upload-assets" ||+ options.command === "update-asset-content";+ // The operation executor remains the source of truth for ordinary schema+ // validation. Only validate the JSON-schema shape here when this boundary+ // must already reject the call, so its unknown-field error does not hide+ // simultaneous missing or wrong-type fields. Query validation is also owned+ // here because both MCP query tools must use the shared query validator.+ const schemaIssues =+ unknownFields.length > 0 ||+ queryIssues.length > 0 ||+ validatesLocalTextAssetInput+ ? collectInputSchemaIssues(options).filter(outsideQuery)+ : [];+ const issues = [+ ...queryIssues,+ ...schemaIssues,+ ...localTextAssetIssues,+ ...unknownFields.map(({ issue }) => issue),+ ];+ if (issues.length > 0) {+ const messages = [+ ...queryIssues.map(({ message }) => message),+ ...schemaIssues.map(({ message }) => message),+ ...localTextAssetIssues.map(({ message }) => message),+ ...unknownFields.map(({ message }) => message),+ ];+ throwBuilderValidationError(messages.join("\n"), issues);+ }};const normalizeOperationInputAliases = ({@@ -1659,7 +2131,7 @@ const importInputSchema = {const downloadAssetInputSchema = {...emptyInputSchema,description:- "Download one project Asset. MDX results also include source and diagnostics.",+ "Download one project Asset. Markdown and MDX results also include source and diagnostics.",properties: {assetId: {type: "string",@@ -3335,7 +3807,7 @@ const importTool = createProjectSessionMcpTool({const downloadAssetTool = createProjectSessionMcpTool({name: "download-asset",description:- "Download one project Asset. MDX includes source and diagnostics.",+ "Download one project Asset. Markdown and MDX include source and diagnostics.",inputSchema: downloadAssetInputSchema,outputSchema: getMcpOutputSchema({type: "object",@@ -3348,11 +3820,19 @@ const downloadAssetTool = createProjectSessionMcpTool({items: {type: "object",properties: {- code: { type: "string", enum: ["invalid-mdx", "unsafe-mdx"] },+ code: { type: "string" },severity: { type: "string", enum: ["error", "warning"] },message: { type: "string" },nodeType: { type: "string" },reason: { type: "string" },+ assetId: { type: "string" },+ blockInstanceId: { type: "string" },+ contentRef: { type: "string" },+ renderScope: { type: "string" },+ templateName: { type: "string" },+ propName: { type: "string" },+ line: { type: "number" },+ column: { type: "number" },sourceRange: {type: "object",properties: {@@ -3378,7 +3858,7 @@ const downloadAssetTool = createProjectSessionMcpTool({required: ["start", "end"],},},- required: ["code", "severity", "message"],+ required: ["code", "severity"],},},},diff --git a/packages/project-build/src/runtime/asset-resources.test.ts b/packages/project-build/src/runtime/asset-resources.test.tsindex eb59d4c4e3..7235ac0ade 100644--- a/packages/project-build/src/runtime/asset-resources.test.ts+++ b/packages/project-build/src/runtime/asset-resources.test.ts@@ -2,9 +2,39 @@ import { describe, expect, test } from "vitest";import {assetsResourceCreateInput,assetsResourceUpdateInput,+ getAssetsResource,} from "./asset-resources";describe("Assets resource mutation input", () => {+ test("returns the exact stored query decoding error", () => {+ expect(+ getAssetsResource(+ {+ resources: new Map([+ [+ "posts",+ {+ id: "posts",+ name: "Posts",+ control: "system" as const,+ method: "post" as const,+ url: '"/$resources/assets"',+ headers: [],+ body: "({ query: { where: 1 } })",+ },+ ],+ ]),+ dataSources: new Map(),+ },+ { resourceId: "posts" }+ ).resource+ ).toMatchObject({+ mode: "invalid",+ configurationError:+ "Stored Assets query is invalid: Enter valid filters.",+ });+ });+test("rejects unsupported field paths", () => {const result = assetsResourceCreateInput.safeParse({name: "Posts",diff --git a/packages/project-build/src/runtime/asset-resources.ts b/packages/project-build/src/runtime/asset-resources.tsindex 19f52c3c7c..c9d6f437ec 100644--- a/packages/project-build/src/runtime/asset-resources.ts+++ b/packages/project-build/src/runtime/asset-resources.ts@@ -4,7 +4,7 @@ import {createDefaultStructuredAssetQueryResourceConfiguration,createStructuredAssetQueryResourceBody,isAssetsResource,- parseStructuredAssetQueryResourceBody,+ parseStructuredAssetQueryResourceBodyResult,SYSTEM_VARIABLE_ID,type AssetQueryWhereExpression,type Resource,@@ -92,7 +92,12 @@ const serializeAssetResource = ({resource: Resource;state: Pick<BuilderState, "dataSources">;}) => {- const configuration = parseStructuredAssetQueryResourceBody(resource.body);+ const parsedConfiguration = parseStructuredAssetQueryResourceBodyResult(+ resource.body+ );+ const configuration = parsedConfiguration.success+ ? parsedConfiguration.value+ : undefined;const dataSources = Array.from(state.dataSources?.values() ?? []);const unsetNameById = new Map(dataSources.map(({ id, name }) => [id, name]));unsetNameById.set(SYSTEM_VARIABLE_ID, "system");@@ -111,7 +116,9 @@ const serializeAssetResource = ({...(configuration === undefined? {configurationError:- "Stored Assets query configuration could not be decoded.",+ parsedConfiguration.success === false+ ? parsedConfiguration.message+ : "Stored Assets query configuration could not be decoded.",}: {query: {@@ -218,13 +225,20 @@ export const updateAssetsResource = (return throwBuilderRuntimeError("NOT_FOUND", "Assets resource not found");}const { name, query: queryUpdate } = input.values;- const storedConfiguration = parseStructuredAssetQueryResourceBody(+ const parsedConfiguration = parseStructuredAssetQueryResourceBodyResult(resource.body);+ const storedConfiguration = parsedConfiguration.success+ ? parsedConfiguration.value+ : undefined;if (storedConfiguration === undefined && queryUpdate === undefined) {return throwBuilderRuntimeError("BAD_REQUEST",- "Stored Assets query configuration could not be decoded; replace or remove the query to repair it"+ `${+ parsedConfiguration.success === false+ ? parsedConfiguration.message+ : "Stored Assets query configuration could not be decoded."+ } Replace or remove the query to repair it.`);}const currentQuery = storedConfiguration;diff --git a/packages/project-build/src/runtime/content-block-application.ts b/packages/project-build/src/runtime/content-block-application.tsindex 6a7ee638ba..db247d179a 100644--- a/packages/project-build/src/runtime/content-block-application.ts+++ b/packages/project-build/src/runtime/content-block-application.ts@@ -1,7 +1,6 @@import {- createMdxSourceDiagnostics,- parseMdxDocumentRecovering,replaceMdxFrontmatter,+ validateTextAssetSource,} from "@webstudio-is/content-engine/mdx";import type { AssetContentSession } from "@webstudio-is/content-engine/asset-content-session";import {@@ -76,18 +75,23 @@ export const inspectMdxAssetSource = async ({metas: Map<string, WsComponentMeta>;projectId: string;}) => {- const parsed = await parseMdxDocumentRecovering({ source });- const sourceDiagnostics = createMdxSourceDiagnostics(parsed.diagnostics);+ const validation = await validateTextAssetSource({ source, format: "mdx" });+ if (validation.format !== "mdx") {+ throw new Error("MDX source validation returned the wrong format");+ }+ const parsed = validation.recovery;+ const sourceDiagnostics = validation.diagnostics;const diagnostics: Array<- | ReturnType<typeof createMdxSourceDiagnostics>[number]- | ContentBlockDiagnostic+ (typeof sourceDiagnostics)[number] | ContentBlockDiagnostic> = [...sourceDiagnostics];const sourceDiagnosticKeys = new Set(sourceDiagnostics.map((diagnostic) =>JSON.stringify([diagnostic.code,diagnostic.message,- diagnostic.sourceRange,+ "sourceRange" in diagnostic ? diagnostic.sourceRange : undefined,+ "line" in diagnostic ? diagnostic.line : undefined,+ "column" in diagnostic ? diagnostic.column : undefined,])));@@ -139,7 +143,13 @@ export const inspectMdxAssetSource = async ({: diagnostic.reason;return (sourceDiagnosticKeys.has(- JSON.stringify([diagnostic.code, message, diagnostic.sourceRange])+ JSON.stringify([+ diagnostic.code,+ message,+ diagnostic.sourceRange,+ undefined,+ undefined,+ ])) === false);})diff --git a/packages/project-build/src/runtime/errors.test.ts b/packages/project-build/src/runtime/errors.test.tsindex 4191121626..bb0fe3442f 100644--- a/packages/project-build/src/runtime/errors.test.ts+++ b/packages/project-build/src/runtime/errors.test.ts@@ -211,3 +211,49 @@ test("reads validation issues from serialized API error data", () => {}),]);});++test("preserves complete source diagnostic fields from serialized API errors", () => {+ expect(+ getValidationIssues({+ data: {+ issues: [+ {+ code: "invalid-mdx",+ path: ["posts/broken.mdx"],+ message: "Unexpected end of file",+ constraint: "invalid-mdx",+ severity: "error",+ scope: "query",+ phase: "source",+ assetId: "asset-1",+ file: "posts/broken.mdx",+ line: 4,+ column: 9,+ nodeType: "mdxJsxFlowElement",+ reason: "Closing tag is missing",+ sourceRange: {+ start: { line: 4, column: 1, offset: 30 },+ end: { line: 4, column: 9, offset: 38 },+ },+ },+ ],+ },+ })+ ).toEqual([+ expect.objectContaining({+ severity: "error",+ scope: "query",+ phase: "source",+ assetId: "asset-1",+ file: "posts/broken.mdx",+ line: 4,+ column: 9,+ nodeType: "mdxJsxFlowElement",+ reason: "Closing tag is missing",+ sourceRange: {+ start: { line: 4, column: 1, offset: 30 },+ end: { line: 4, column: 9, offset: 38 },+ },+ }),+ ]);+});diff --git a/packages/project-build/src/runtime/errors.ts b/packages/project-build/src/runtime/errors.tsindex a08d91fe40..26c6ec2fb1 100644--- a/packages/project-build/src/runtime/errors.ts+++ b/packages/project-build/src/runtime/errors.ts@@ -11,6 +11,12 @@ export type BuilderRuntimeErrorCode =| "NOT_FOUND"| "CONFLICT";+const sourcePointSchema = z.object({+ line: z.number().int().positive(),+ column: z.number().int().positive(),+ offset: z.number().int().nonnegative().optional(),+});+const semanticValidationIssueSchema = z.object({code: z.string(),path: z.array(z.string()),@@ -18,6 +24,25 @@ const semanticValidationIssueSchema = z.object({constraint: z.string(),example: z.unknown().optional(),detail: z.string().optional(),+ severity: z.enum(["error", "warning"]).optional(),+ scope: z.string().optional(),+ phase: z.string().optional(),+ assetId: z.string().optional(),+ file: z.string().optional(),+ name: z.string().optional(),+ line: z.number().int().positive().optional(),+ column: z.number().int().positive().optional(),+ reference: z.string().optional(),+ nodeType: z.string().optional(),+ reason: z.string().optional(),+ sourceRange: z+ .object({ start: sourcePointSchema, end: sourcePointSchema })+ .optional(),+ blockInstanceId: z.string().optional(),+ contentRef: z.string().optional(),+ renderScope: z.string().optional(),+ templateName: z.string().optional(),+ propName: z.string().optional(),});const semanticValidationIssuesSchema = z.array(semanticValidationIssueSchema);@@ -54,6 +79,12 @@ const sanitizeValidationIssues = (...(issue.detail === undefined? {}: { detail: sanitizeValidationDetail(issue.detail) }),+ ...(issue.reason === undefined+ ? {}+ : { reason: sanitizeValidationDetail(issue.reason) }),+ ...(issue.reference === undefined+ ? {}+ : { reference: sanitizeValidationDetail(issue.reference) }),}));type BuilderRuntimeErrorOptions = {@@ -377,26 +408,34 @@ export const prefixValidationIssuePaths = (}));export const getValidationIssues = (error: unknown) => {- if (error instanceof BuilderRuntimeError) {- return error.issues === undefined- ? undefined- : sanitizeValidationIssues(error.issues);- }- if (error instanceof z.ZodError) {- return getZodValidationIssues(error);- }- if (typeof error === "object" && error !== null) {- const directIssues = "issues" in error ? error.issues : undefined;- const data = "data" in error ? error.data : undefined;- const nestedIssues =- typeof data === "object" && data !== null && "issues" in data- ? data.issues+ const visited = new Set<unknown>();+ let current = error;+ while (+ typeof current === "object" &&+ current !== null &&+ visited.has(current) === false+ ) {+ visited.add(current);+ if (current instanceof BuilderRuntimeError) {+ if (current.issues !== undefined) {+ return sanitizeValidationIssues(current.issues);+ }+ }+ if (current instanceof z.ZodError) {+ return getZodValidationIssues(current);+ }+ const record = current as Record<string, unknown>;+ const directIssues = record.issues;+ const data =+ typeof record.data === "object" && record.data !== null+ ? (record.data as Record<string, unknown>): undefined;const result = semanticValidationIssuesSchema.safeParse(- directIssues ?? nestedIssues+ directIssues ?? data?.issues);if (result.success) {return sanitizeValidationIssues(result.data);}+ current = record.cause ?? data?.cause;}};diff --git a/packages/project/src/asset-query-preview.server.test.ts b/packages/project/src/asset-query-preview.server.test.tsindex 8afa9ddab9..2a13f1f355 100644--- a/packages/project/src/asset-query-preview.server.test.ts+++ b/packages/project/src/asset-query-preview.server.test.ts@@ -142,6 +142,85 @@ describe("project asset query preview", () => {expect(dependencies.previewAssetResourceQueries).not.toHaveBeenCalled();});+ test("does not let an unrelated invalid saved query block a batch", async () => {+ const validBody = createStructuredAssetQueryResourceBody({+ where: { all: [] },+ sort: [],+ limit: "10",+ offset: "0",+ output: { mode: "base", includeMetadata: true },+ content: { mode: "none" },+ });+ const build = {+ props: [+ {+ id: "valid-prop",+ instanceId: "collection",+ name: "valid",+ type: "resource",+ value: "valid-resource",+ },+ {+ id: "invalid-prop",+ instanceId: "collection",+ name: "invalid",+ type: "resource",+ value: "invalid-resource",+ },+ ],+ dataSources: [],+ resources: [+ {+ id: "valid-resource",+ name: "Valid",+ control: "system",+ method: "post",+ url: '"/$resources/assets"',+ headers: [],+ body: validBody,+ },+ {+ id: "invalid-resource",+ name: "Invalid",+ control: "system",+ method: "post",+ url: '"/$resources/assets"',+ headers: [],+ body: "invalid",+ },+ ],+ } as never;+ const result = [+ { status: "fulfilled", value: { data: { items: [] } } },+ ] as never;+ const previewAssetResourceQueries = vi.fn().mockResolvedValue(result);++ await expect(+ previewProjectAssetQueries(+ {+ projectId: "project-1",+ requests: [{ query: { limit: 5 } }] as never,+ context: {} as never,+ assetClient: {} as never,+ },+ {+ loadDevBuildContentEngineDataByProjectId: vi+ .fn()+ .mockResolvedValue(build),+ previewAssetResourceQueries,+ }+ )+ ).resolves.toBe(result);++ expect(previewAssetResourceQueries).toHaveBeenCalledWith(+ expect.objectContaining({+ databasePlan: expect.objectContaining({+ queries: [expect.objectContaining({ id: "valid-resource" })],+ }),+ })+ );+ });+test("previews a query against the current Build database plan", async () => {const context = {} as never;const build = { props: [], dataSources: [], resources: [] } as never;@@ -188,6 +267,90 @@ describe("project asset query preview", () => {});});+ test("ignores an unrelated invalid saved Assets query in the current preview", async () => {+ const validBody = createStructuredAssetQueryResourceBody({+ where: { all: [] },+ sort: [],+ limit: "10",+ offset: "0",+ output: { mode: "base", includeMetadata: true },+ content: { mode: "none" },+ });+ const build = {+ props: [+ {+ id: "valid-prop",+ instanceId: "collection",+ name: "valid",+ type: "resource",+ value: "valid-resource",+ },+ {+ id: "invalid-prop",+ instanceId: "collection",+ name: "invalid",+ type: "resource",+ value: "invalid-resource",+ },+ ],+ dataSources: [],+ resources: [+ {+ id: "valid-resource",+ name: "Valid",+ control: "system",+ method: "post",+ url: '"/$resources/assets"',+ headers: [],+ body: validBody,+ },+ {+ id: "invalid-resource",+ name: "Invalid",+ control: "system",+ method: "post",+ url: '"/$resources/assets"',+ headers: [],+ body: "invalid",+ },+ ],+ } as never;+ const previewAssetResourceQuery = vi+ .fn()+ .mockResolvedValue({ data: { items: [] } });++ await expect(+ previewProjectAssetQuery(+ {+ projectId: "project-1",+ request: { query: { limit: 5 } },+ context: {} as never,+ assetClient: {} as never,+ },+ {+ loadDevBuildContentEngineDataByProjectId: vi+ .fn()+ .mockResolvedValue(build),+ previewAssetResourceQuery,+ }+ )+ ).resolves.toEqual({ data: { items: [] } });++ expect(previewAssetResourceQuery).toHaveBeenCalledWith(+ expect.objectContaining({+ databasePlan: expect.objectContaining({+ queries: [expect.objectContaining({ id: "valid-resource" })],+ }),+ diagnosticsPlan: expect.objectContaining({+ queries: expect.arrayContaining([+ expect.objectContaining({ id: "valid-resource" }),+ expect.objectContaining({ id: "__query-preview__" }),+ ]),+ }),+ })+ );+ });+test("stops a cancelled query before loading Build data", async () => {const controller = new AbortController();controller.abort();diff --git a/packages/project/src/asset-query-preview.server.ts b/packages/project/src/asset-query-preview.server.tsindex c29704bc91..edcd67f4a3 100644--- a/packages/project/src/asset-query-preview.server.ts+++ b/packages/project/src/asset-query-preview.server.ts@@ -8,7 +8,7 @@ import {} from "@webstudio-is/asset-uploader/server";import {createAssetQueryPreviewCompilationPlan,- createBuildContentCompilationPlan,+ createBuildContentCompilationPlanResult,} from "@webstudio-is/project-build";import { loadDevBuildContentEngineDataByProjectId } from "@webstudio-is/project-build/server";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";@@ -66,7 +66,7 @@ export const previewProjectAssetQueries = async (context,assetClient,contentDatabaseMaxBytes,- databasePlan: createBuildContentCompilationPlan(build),+ databasePlan: createBuildContentCompilationPlanResult(build).plan,signal,onPerformanceEvent,onDocumentGraphEvent,@@ -104,7 +104,7 @@ export const previewProjectAssetQuery = async (),});signal?.throwIfAborted();- const databasePlan = createBuildContentCompilationPlan(build);+ const databasePlan = createBuildContentCompilationPlanResult(build).plan;return await dependencies.previewAssetResourceQuery({projectId,request,diff --git a/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts b/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.tsindex 02232e8b52..40551f8215 100644--- a/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts+++ b/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts@@ -681,6 +681,7 @@ export const serverOnlyRouterOperationMetadata = {},},required: ["mode"],+ additionalProperties: false,},{type: "object",@@ -696,6 +697,7 @@ export const serverOnlyRouterOperationMetadata = {},},required: ["mode"],+ additionalProperties: false,},{type: "object",@@ -716,6 +718,7 @@ export const serverOnlyRouterOperationMetadata = {},},required: ["mode", "offset", "length"],+ additionalProperties: false,},{type: "object",@@ -731,6 +734,7 @@ export const serverOnlyRouterOperationMetadata = {},},required: ["mode"],+ additionalProperties: false,},],},@@ -1067,6 +1071,7 @@ export const serverOnlyRouterOperationMetadata = {},},required: ["mode"],+ additionalProperties: false,},{type: "object",@@ -1082,6 +1087,7 @@ export const serverOnlyRouterOperationMetadata = {},},required: ["mode"],+ additionalProperties: false,},{type: "object",@@ -1102,6 +1108,7 @@ export const serverOnlyRouterOperationMetadata = {},},required: ["mode", "offset", "length"],+ additionalProperties: false,},{type: "object",@@ -1117,6 +1124,7 @@ export const serverOnlyRouterOperationMetadata = {},},required: ["mode"],+ additionalProperties: false,},],},diff --git a/packages/protocol/src/builder-api/operation-docs.ts b/packages/protocol/src/builder-api/operation-docs.tsindex f29e4f6469..1af6e23341 100644--- a/packages/protocol/src/builder-api/operation-docs.ts+++ b/packages/protocol/src/builder-api/operation-docs.ts@@ -647,7 +647,7 @@ const curatedPublicApiOperationDocumentation = [{command: "validate-asset-query",description:- "Validate a structured Assets query and return its referenced dynamic fields and bounded operation counts.",+ "Validate a structured Assets query and return every setup error or warning, referenced dynamic fields, and bounded operation counts.",examples: ['webstudio validate-asset-query \'{"query":{"where":{"all":[{"field":["properties","slug"],"operator":"eq","value":"hello-world"}]},"limit":1}}\'',],@@ -813,7 +813,7 @@ const curatedPublicApiOperationDocumentation = [{command: "upload-asset",description:- "Upload one local asset file from a descriptor, optionally into an Asset Manager folder",+ "Upload one local asset file from a descriptor, optionally into an Asset Manager folder. Markdown and MDX uploads return source diagnostics",requiredOptions: ["input", "json"],examples: ["webstudio upload-asset --input asset.json --assets-dir .webstudio/assets --json",@@ -822,7 +822,7 @@ const curatedPublicApiOperationDocumentation = [{command: "upload-assets",description:- "Upload local asset files from descriptors, optionally into Asset Manager folders; returns uploaded, retryable failures, and commit-ambiguous forced uploads separately so only safe retries are suggested",+ "Upload local asset files from descriptors, optionally into Asset Manager folders; returns uploaded, retryable failures, commit-ambiguous forced uploads, and Markdown or MDX source diagnostics",requiredOptions: ["input", "json"],examples: ["webstudio upload-assets --input assets.json --assets-dir .webstudio/assets --json",@@ -831,7 +831,7 @@ const curatedPublicApiOperationDocumentation = [{command: "update-asset-content",description:- "Replace a text Asset's content or extension without changing its ID. Provide path or content and its current name as expectedName. Invalid MDX is saved with diagnostics",+ "Replace a text Asset's content or extension without changing its ID. Provide path or content and its current name as expectedName. Markdown and MDX validation diagnostics are returned without blocking the save",examples: [`MCP/API: update-asset-content {"assetId":"asset-id","expectedName":"settings_hash.json","content":"{theme:'dark'}"}`,`MCP/API: update-asset-content {"assetId":"asset-id","expectedName":"settings_hash.md","extension":"json","content":"{theme:'dark'}"}`,diff --git a/packages/sdk/src/asset-resource-config.test.ts b/packages/sdk/src/asset-resource-config.test.tsindex bd589c5260..c1d47a8042 100644--- a/packages/sdk/src/asset-resource-config.test.ts+++ b/packages/sdk/src/asset-resource-config.test.ts@@ -7,9 +7,11 @@ import {createAssetResourceRequest,createDefaultStructuredAssetQueryResourceConfiguration,createReachableAssetContentCompilationPlan,+ createReachableAssetContentCompilationPlanResult,createStructuredAssetQueryResourceBody,isAssetsResource,parseStructuredAssetQueryResourceBody,+ parseStructuredAssetQueryResourceBodyResult,} from "./asset-resource-config";import { loadResource } from "./resource-loader";import { assetResourceLimits } from "./asset-resource-limits";@@ -152,7 +154,51 @@ describe("asset query resource configuration", () => {dataSources: [],resources: [createResource({ body: "invalid" })],})- ).toThrow('Assets resource "posts" has an invalid query configuration');+ ).toThrow(+ 'Assets resource "posts" has an invalid query configuration: Stored Assets query body is not a valid object expression.'+ );+ });++ test("collects invalid reachable queries while compiling valid queries", () => {+ const body = createStructuredAssetQueryResourceBody({+ where: { all: [] },+ sort: [],+ limit: "10",+ offset: "0",+ output: { mode: "base", includeMetadata: true },+ content: { mode: "none" },+ });+ const result = createReachableAssetContentCompilationPlanResult({+ props: [+ {+ id: "valid-prop",+ instanceId: "instance",+ name: "valid",+ type: "resource",+ value: "valid",+ },+ {+ id: "invalid-prop",+ instanceId: "instance",+ name: "invalid",+ type: "resource",+ value: "invalid",+ },+ ],+ dataSources: [],+ resources: [+ createResource({ id: "valid", body }),+ createResource({ id: "invalid", body: "invalid" }),+ ],+ });++ expect(result.plan?.queries.map(({ id }) => id)).toEqual(["valid"]);+ expect(result.issues).toEqual([+ {+ resourceId: "invalid",+ message: "Stored Assets query body is not a valid object expression.",+ },+ ]);});test("rejects fractional pagination values", () => {@@ -346,6 +392,38 @@ describe("asset query resource configuration", () => {).toThrow("Select at least one asset query output");});+ test("explains why a stored Assets query cannot be decoded", () => {+ expect(parseStructuredAssetQueryResourceBodyResult("invalid")).toEqual({+ success: false,+ message: "Stored Assets query body is not a valid object expression.",+ });+ expect(+ parseStructuredAssetQueryResourceBodyResult("({ unexpected: true })")+ ).toEqual({+ success: false,+ message:+ 'Stored Assets query body has an unsupported field: "unexpected".',+ });+ expect(parseStructuredAssetQueryResourceBodyResult("({})")).toEqual({+ success: false,+ message: 'Stored Assets query body is missing the "query" field.',+ });+ expect(+ parseStructuredAssetQueryResourceBodyResult(+ "({ query: { where: 1 }, other: true })"+ )+ ).toEqual({+ success: false,+ message: 'Stored Assets query body has an unsupported field: "other".',+ });+ expect(+ parseStructuredAssetQueryResourceBodyResult("({ query: { where: 1 } })")+ ).toEqual({+ success: false,+ message: "Stored Assets query is invalid: Enter valid filters.",+ });+ });+test("preserves explicit output and defaults to URL and optional image dimensions", () => {expect(parseStructuredAssetQueryResourceBody(`{diff --git a/packages/sdk/src/asset-resource-config.ts b/packages/sdk/src/asset-resource-config.tsindex 51284010e7..3393af915f 100644--- a/packages/sdk/src/asset-resource-config.ts+++ b/packages/sdk/src/asset-resource-config.ts@@ -129,15 +129,20 @@ const createAssetContentCompilationQuery = ({content: configuration.content,});-export const createReachableAssetContentCompilationPlan = ({- props,- dataSources,- resources,-}: {+type ReachableAssetContentCompilationPlanInput = {props: Iterable<Prop>;dataSources: Iterable<DataSource>;resources: Iterable<Resource>;-}): ContentCompilationPlan | undefined => {+};++export const createReachableAssetContentCompilationPlanResult = ({+ props,+ dataSources,+ resources,+}: ReachableAssetContentCompilationPlanInput): {+ plan: ContentCompilationPlan | undefined;+ issues: readonly Readonly<{ resourceId: string; message: string }>[];+} => {const reachableResourceIds = new Set<string>();for (const prop of props) {if (prop.type === "resource") {@@ -150,6 +155,7 @@ export const createReachableAssetContentCompilationPlan = ({}}const queries = [];+ const issues: Array<{ resourceId: string; message: string }> = [];for (const resource of resources) {if (reachableResourceIds.has(resource.id) === false ||@@ -157,12 +163,17 @@ export const createReachableAssetContentCompilationPlan = ({) {continue;}- const configuration = parseStructuredAssetQueryResourceBody(resource.body);- if (configuration === undefined) {- throw new Error(- `Assets resource ${JSON.stringify(resource.id)} has an invalid query configuration`- );+ const parsedConfiguration = parseStructuredAssetQueryResourceBodyResult(+ resource.body+ );+ if (parsedConfiguration.success === false) {+ issues.push({+ resourceId: resource.id,+ message: parsedConfiguration.message,+ });+ continue;}+ const configuration = parsedConfiguration.value;queries.push(createAssetContentCompilationQuery({resourceId: resource.id,@@ -170,7 +181,24 @@ export const createReachableAssetContentCompilationPlan = ({}));}- return createContentCompilationPlan(queries);+ return { plan: createContentCompilationPlan(queries), issues };+};++export const createReachableAssetContentCompilationPlan = (+ input: ReachableAssetContentCompilationPlanInput+): ContentCompilationPlan | undefined => {+ const result = createReachableAssetContentCompilationPlanResult(input);+ if (result.issues.length > 0) {+ throw new Error(+ result.issues+ .map(+ ({ resourceId, message }) =>+ `Assets resource ${JSON.stringify(resourceId)} has an invalid query configuration: ${message}`+ )+ .join("\n")+ );+ }+ return result.plan;};const assetQuerySourceCodec = createQuerySourceCodec<@@ -184,22 +212,62 @@ export const createDefaultStructuredAssetQueryResourceConfiguration = () =>assetQuerySourceDefinition);-export const parseStructuredAssetQueryResourceBody = (+export const parseStructuredAssetQueryResourceBodyResult = (body: string | undefined-): StructuredAssetQueryResourceConfiguration | undefined => {+):+ | Readonly<{+ success: true;+ value: StructuredAssetQueryResourceConfiguration;+ }>+ | Readonly<{ success: false; message: string }> => {const request = parseExpressionObject(body ?? "");if (request === undefined) {- return;+ return {+ success: false,+ message: "Stored Assets query body is not a valid object expression.",+ };+ }+ const unsupportedFields = [...request.keys()].filter(+ (field) => field !== "query"+ );+ if (unsupportedFields.length > 0) {+ return {+ success: false,+ message: `Stored Assets query body has ${+ unsupportedFields.length === 1+ ? "an unsupported field"+ : "unsupported fields"+ }: ${unsupportedFields.map((field) => JSON.stringify(field)).join(", ")}.`,+ };}const query = request.get("query");- if (request.size !== 1 || query === undefined) {- return;+ if (query === undefined) {+ return {+ success: false,+ message: 'Stored Assets query body is missing the "query" field.',+ };}const parsed = assetQuerySourceCodec.parse(query);- if (parsed.success === false || hasAssetQueryOutput(parsed.value) === false) {- return;+ if (parsed.success === false) {+ return {+ success: false,+ message: `Stored Assets query is invalid: ${parsed.message}`,+ };}- return parsed.value;+ if (hasAssetQueryOutput(parsed.value) === false) {+ return {+ success: false,+ message: "Stored Assets query is invalid: Select at least one output.",+ };+ }+ return { success: true, value: parsed.value };+};++export const parseStructuredAssetQueryResourceBody = (+ body: string | undefined+): StructuredAssetQueryResourceConfiguration | undefined => {+ const result = parseStructuredAssetQueryResourceBodyResult(body);+ return result.success ? result.value : undefined;};export const createStructuredAssetQueryResourceBody = ({