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
perf: Keep article indexing out of publish API requests (#6427)
Oleg Isonend78e770d828b
diff --git a/apps/builder/app/services/build-router.server.test.ts b/apps/builder/app/services/build-router.server.test.tsindex 857887d86f..de19b0f95e 100644--- a/apps/builder/app/services/build-router.server.test.ts+++ b/apps/builder/app/services/build-router.server.test.ts@@ -8,6 +8,7 @@ import { getApiCompatibilityPayload } from "@webstudio-is/trpc-interface/api-comconst {assertCliBundleVersion,createImportProjectBundleHandler,+ createLoadProjectBundleByBuildIdHandler,loadContentDatabasePublishDiagnostics,prepareProjectBundleForClient,} = __testing__;@@ -17,6 +18,32 @@ afterEach(() => {});describe("build router project bundle compatibility", () => {+ test("passes client content preparation to the build bundle loader", async () => {+ const bundle = createPublishedProjectBundleFixture();+ const loadProjectBundleByBuildId = vi.fn().mockResolvedValue(bundle);+ const prepareProjectBundleForClient = vi.fn((_, value) => value);+ const handler = createLoadProjectBundleByBuildIdHandler({+ loadProjectBundleByBuildId: loadProjectBundleByBuildId as never,+ prepareProjectBundleForClient: prepareProjectBundleForClient as never,+ });+ const context = { apiClient: { type: "cli" } } as never;++ await expect(+ handler(context, {+ buildId: bundle.build.id,+ bundleVersion,+ contentIndex: "client",+ })+ ).resolves.toBe(bundle);++ expect(loadProjectBundleByBuildId).toHaveBeenCalledWith(+ bundle.build.id,+ context,+ { contentIndex: "client" }+ );+ expect(prepareProjectBundleForClient).toHaveBeenCalledWith(context, bundle);+ });+test("requires the current bundle contract from CLI clients", () => {const ctx = { apiClient: { type: "cli" } } as never;let error: unknown;diff --git a/apps/builder/app/services/build-router.server.ts b/apps/builder/app/services/build-router.server.tsindex a5672d8c60..b9c0032562 100644--- a/apps/builder/app/services/build-router.server.ts+++ b/apps/builder/app/services/build-router.server.ts@@ -59,6 +59,7 @@ const projectBundleInput = z.object({const buildBundleInput = z.object({buildId: z.string(),bundleVersion: z.union([z.string(), z.number()]).optional(),+ contentIndex: z.literal("client").optional(),});const assertCliBundleVersion = (@@ -102,6 +103,27 @@ const prepareProjectBundleForClient = async (};};+const createLoadProjectBundleByBuildIdHandler =+ (dependencies: {+ loadProjectBundleByBuildId: typeof loadProjectBundleByBuildId;+ prepareProjectBundleForClient: typeof prepareProjectBundleForClient;+ }) =>+ async (ctx: AppContext, input: z.infer<typeof buildBundleInput>) => {+ assertCliBundleVersion(ctx, input.bundleVersion);+ return await dependencies.prepareProjectBundleForClient(+ ctx,+ await dependencies.loadProjectBundleByBuildId(input.buildId, ctx, {+ contentIndex: input.contentIndex,+ })+ );+ };++const loadProjectBundleByBuildIdHandler =+ createLoadProjectBundleByBuildIdHandler({+ loadProjectBundleByBuildId,+ prepareProjectBundleForClient,+ });+type ImportProjectBundleDependencies = {importPublishedProjectBundle: typeof importPublishedProjectBundle;readStagedUploadText: typeof readStagedUploadText;@@ -272,11 +294,7 @@ export const buildRouter = router({loadProjectBundleByBuildId: procedure.input(buildBundleInput).query(async ({ ctx, input }) => {- assertCliBundleVersion(ctx, input.bundleVersion);- return await prepareProjectBundleForClient(- ctx,- await loadProjectBundleByBuildId(input.buildId, ctx)- );+ return await loadProjectBundleByBuildIdHandler(ctx, input);}),loadProjectBundleByProjectId: procedure@@ -430,6 +448,7 @@ export const buildRouter = router({export const __testing__ = {createImportProjectBundleHandler,+ createLoadProjectBundleByBuildIdHandler,assertCliBundleVersion,loadContentDatabasePublishDiagnostics,prepareProjectBundleForClient,diff --git a/apps/builder/app/shared/db/canvas.server.test.ts b/apps/builder/app/shared/db/canvas.server.test.tsindex 8b9d09e97a..e21f6d4bd8 100644--- a/apps/builder/app/shared/db/canvas.server.test.ts+++ b/apps/builder/app/shared/db/canvas.server.test.ts@@ -180,6 +180,79 @@ test("validates collections when publication does not need a content index", asyexpect(result.assetFolders).toBe(currentAssetFolders);});+test("build-id bundles do not read MDX bodies while preparing the RPC response", async () => {+ const build = createBundleBuild();+ const rootInstanceId = build.pages.pages.get(+ build.pages.homePageId+ )?.rootInstanceId;+ if (rootInstanceId === undefined) {+ throw new Error("Home page root is missing");+ }+ build.instances = [+ {+ type: "instance",+ id: rootInstanceId,+ component: "ws:block",+ children: [],+ },+ ];+ build.props = [+ {+ id: "article-source",+ instanceId: rootInstanceId,+ name: "src",+ type: "asset",+ value: "article",+ },+ ];+ const article: Asset = {+ ...createImageAssetFixture({ projectId: build.projectId }),+ id: "article",+ name: "article.mdx",+ type: "file",+ format: "mdx",+ meta: {},+ };+ const preparePublishedAssetData = vi.fn(() => {+ throw new Error("RPC attempted to read article content");+ });+ const validatePublishedAssetCollections = vi.fn().mockResolvedValue({+ assets: [article],+ assetFolders: [],+ });+ const data = serializeProjectBundle({ build, assets: [article] });+ const project = {+ id: build.projectId,+ userId: null,+ domain: "example.com",+ title: "Example",+ } as never;+ const dependencies = {+ getUserById: vi.fn(),+ preparePublishedAssetData,+ validatePublishedAssetCollections,+ createAssetClient: vi.fn(() => ({}) as never),+ };++ await expect(+ addProjectMetadata(data, project, {} as never, dependencies)+ ).rejects.toThrow("RPC attempted to read article content");+ preparePublishedAssetData.mockClear();++ const result = await addProjectMetadata(+ data,+ project,+ {} as never,+ dependencies,+ { prepareContentIndex: false }+ );++ expect(preparePublishedAssetData).not.toHaveBeenCalled();+ expect(validatePublishedAssetCollections).toHaveBeenCalledOnce();+ expect(result.assetIndex).toBeUndefined();+ expect(result.assets).toContainEqual(article);+});+test("loads project-id bundles from the published build", async () => {const data = createPublishedProjectBundleFixture();const project = {diff --git a/apps/builder/app/shared/db/canvas.server.ts b/apps/builder/app/shared/db/canvas.server.tsindex d9a0518374..0922275931 100644--- a/apps/builder/app/shared/db/canvas.server.ts+++ b/apps/builder/app/shared/db/canvas.server.ts@@ -178,6 +178,7 @@ const addProjectMetadata = async (onMdxTemplateOmissions?: (issues: readonly PublishedMdxTemplateOmission[]) => void;+ prepareContentIndex?: boolean;} = {}): Promise<PublishedProjectBundle> => {const user =@@ -185,33 +186,44 @@ const addProjectMetadata = async (? undefined: await dependencies.getUserById(context, project.userId);- const publicationBuild = {- ...data.build,- pages: migratePages(data.build.pages),- };- const dynamicBlockIds =- getDynamicPublishedMdxSourceBlockIds(publicationBuild);- const projectCandidates = resolvePublishedMdxAssetCandidates({- build: publicationBuild,- allowUnresolved: true,- });- const needsCandidateDiscovery = dynamicBlockIds.some(- (blockId) => projectCandidates.has(blockId) === false- );- const candidateDiscoveryPlan = needsCandidateDiscovery- ? createBuildContentCompilationPlan(data.build)- : undefined;- const assetRequirements =- candidateDiscoveryPlan ??- createPublishedBuildContentCompilationPlan(- publicationBuild,- projectCandidates+ let publicationBuild:+ | Parameters<typeof createPublishedBuildContentCompilationPlan>[0]+ | undefined;+ let candidateDiscoveryPlan: ReturnType<+ typeof createBuildContentCompilationPlan+ >;+ let assetRequirements: ReturnType<+ typeof createPublishedBuildContentCompilationPlan+ >;+ if (options.prepareContentIndex !== false) {+ publicationBuild = {+ ...data.build,+ pages: migratePages(data.build.pages),+ };+ const dynamicBlockIds =+ getDynamicPublishedMdxSourceBlockIds(publicationBuild);+ const projectCandidates = resolvePublishedMdxAssetCandidates({+ build: publicationBuild,+ allowUnresolved: true,+ });+ const needsCandidateDiscovery = dynamicBlockIds.some(+ (blockId) => projectCandidates.has(blockId) === false);+ candidateDiscoveryPlan = needsCandidateDiscovery+ ? createBuildContentCompilationPlan(data.build)+ : undefined;+ assetRequirements =+ candidateDiscoveryPlan ??+ createPublishedBuildContentCompilationPlan(+ publicationBuild,+ projectCandidates+ );+ }let assetIndex: PublishedProjectBundle["assetIndex"];let publishedAssets = data.assets;let publishedAssetFolders = data.assetFolders;let mdxTemplateOmissions: PublishedMdxTemplateOmission[] = [];- if (assetRequirements !== undefined) {+ if (assetRequirements !== undefined && publicationBuild !== undefined) {const resolveMdxDependencies =createPublishedMdxDependencyClosureResolver();const publishedAssetData = await dependencies.preparePublishedAssetData({@@ -342,7 +354,8 @@ export const loadPublishedProjectBundleByProjectId =export const loadProjectBundleByBuildId = async (buildId: string,- context: AppContext+ context: AppContext,+ { contentIndex }: { contentIndex?: "client" } = {}): Promise<PublishedProjectBundle> => {const build = await loadBuildById(context, buildId);const project = await loadById(build.projectId, context);@@ -352,7 +365,9 @@ export const loadProjectBundleByBuildId = async (return await addProjectMetadata(await createProjectBundle(build, context),project,- context+ context,+ addProjectMetadataDependencies,+ { prepareContentIndex: contentIndex !== "client" });};diff --git a/docs/university/core-components/content-block.md b/docs/university/core-components/content-block.mdindex d973fa9bd9..2c878a20e4 100644--- a/docs/university/core-components/content-block.md+++ b/docs/university/core-components/content-block.md@@ -74,6 +74,12 @@ Editors can delete top-level content instances. In MDX-connected blocks, these aConnect a `.mdx` file when the Content Block's body should live in Assets instead of the project's regular instance data. The designed shell and Templates list remain in the project. Markdown `.md` files cannot be connected to a Content Block.+Publishing a site with connected MDX articles downloads and compiles each+reachable article, which can increase publish time. A `.md` file with Markdown+Embed avoids that compilation but supports source editing instead of visual+body editing. See [Choose Markdown or MDX](../foundations/content-engine.md#choose-markdown-or-mdx)+for the full comparison.+To insert a custom component such as Accordion into **MDX content**, first add its design to **Templates**, then insert it from the template picker. Inserting custom components directly from the Add panel into MDX content is blocked. Basic Markdown elements, images, and code blocks can still be inserted directly. Place designer-owned, one-off components outside **MDX content**; they remain in the project and are not saved to the file.Moving, pasting, or duplicating content into an MDX region also checks the destination's Templates. Unsupported components are rejected before the tree changes, including components nested inside a pasted container.diff --git a/docs/university/foundations/content-engine.md b/docs/university/foundations/content-engine.mdindex de423a4d97..4383239d00 100644--- a/docs/university/foundations/content-engine.md+++ b/docs/university/foundations/content-engine.md@@ -38,6 +38,22 @@ structured collection entries:<figure><img src="../../.gitbook/assets/content-engine-assets-structure.png" alt="Assets panel showing Markdown articles and their assets folder"><figcaption><p>Markdown articles stored alongside their assets</p></figcaption></figure>+## Choose Markdown or MDX++Choose the file format based on how editors will work with the article body:++| Format | Publishing | Editing in Content mode |+| --- | --- | --- |+| `.mdx` with a Content Block | Publishing downloads the article files and compiles the MDX for every article the page can render. More articles can make publishing slower. | Editors can change the article visually on the canvas with a Notion-style experience, or edit the MDX source file. |+| `.md` with Markdown Embed | No per-article MDX compilation is needed. A hosted page reads the selected Markdown body when it is requested. | Editors can edit the `.md` file in the Markdown source editor in Assets, but cannot edit its body visually on the canvas. |++The publish runner currently synchronizes Asset files for either format. That+transfer still takes time; the difference is the additional per-article MDX+compilation. Static pages can also read Markdown bodies while generating their+HTML. Use [Content Block](../core-components/content-block.md) when visual+article editing matters, or [Markdown Embed](../core-components/markdown-embed.md)+when source editing is enough.+## Decide if the Content Engine fitsUse the Content Engine for bounded, file-based content that should live with@@ -522,13 +538,16 @@ In Page Settings, bind the fields needed for search and sharing:The status expression returns a real 404 when no article matches the URL.-### Render a read-only Markdown body+### Render a Markdown body without visual editing-Use a `.md` file and [Markdown Embed](../core-components/markdown-embed.md) only-when the article body does not need visual editing. Set the article resource's+Use a `.md` file and [Markdown Embed](../core-components/markdown-embed.md) when+editors can work in the Markdown source editor instead of editing the body on+the canvas. Content mode editors can still open and edit the `.md` file in+Assets. Set the article resource's`extension` filter to `md` and **Content** to **Markdown body reference**, thenbind the Markdown Embed code to `post.data.content.text`. Style its nested-document elements once for every article.+document elements once for every article. See [Choose Markdown or MDX](#choose-markdown-or-mdx)+for the publishing tradeoff.## 7. Publish the articlediff --git a/docs/university/mcp.md b/docs/university/mcp.mdindex 4d9c5d4c90..d55d13a9e3 100644--- a/docs/university/mcp.md+++ b/docs/university/mcp.md@@ -167,6 +167,8 @@ Rules:Use a connected `.mdx` Asset when editors should change a Content Block body visually while the document remains stored as a file.+Choose this format before building a blog: each reachable connected MDX article is downloaded and compiled when publishing, so publishing can take longer as the blog grows. If editors only need to edit Markdown source in Assets, use `.md` with Markdown Embed instead. Content mode editors can edit those files in the Markdown file editor, but cannot edit the article body visually on the canvas. `.md` does not need per-article MDX compilation; the current publish sync still transfers Asset files for either format, and static generation may read Markdown bodies.+### Connect a collection to its entry pageWhen MDX files belong to a content collection, connect the collection to its dynamic entry page explicitly. Read the page ID after finding or creating the page, verify that its path has exactly one URL parameter, and store the ID at `x-webstudio.entryPageId` in `collection.json`. Do not assume Webstudio infers the page from its path, Assets query, or Content Block source. Preserve the rest of `collection.json`, and verify **Open on canvas** from both an entry asset menu and **Entry settings** before handoff. If no compatible page exists, leave the field unset and report that entry navigation still needs configuration.diff --git a/fixtures/react-router-cloudflare/.webstudio/data.json b/fixtures/react-router-cloudflare/.webstudio/data.jsonindex 797d7f0fea..83a8bd3120 100644--- a/fixtures/react-router-cloudflare/.webstudio/data.json+++ b/fixtures/react-router-cloudflare/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1he6g9u",+ "bundleVersion": "bundle-1e81gg6","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",@@ -23,7 +23,9 @@"id": "WPPAbLFyJD_02vhjRd8P4","name": "Another page","title": "\"Another page\"",- "history": ["/another-page"],+ "history": [+ "/another-page"+ ],"rootInstanceId": "n_VBMr7klpx25buS0NV7R","systemDataSourceId": "tdXe9gFf83hSo9BLWU6xl","meta": {@@ -53,7 +55,10 @@"id": "root","name": "Root","slug": "",- "children": ["9di_L14CzctvSruIoKVvE", "WPPAbLFyJD_02vhjRd8P4"]+ "children": [+ "9di_L14CzctvSruIoKVvE",+ "WPPAbLFyJD_02vhjRd8P4"+ ]}]},@@ -194,21 +199,27 @@"MMimeobf_zi4ZkRGXapju",{"instanceId": "MMimeobf_zi4ZkRGXapju",- "values": ["7_QL45cpvP-zG8Hkgf4cr"]+ "values": [+ "7_QL45cpvP-zG8Hkgf4cr"+ ]}],["BMJfjOzunWs8XkQgvvx1e",{"instanceId": "BMJfjOzunWs8XkQgvvx1e",- "values": ["0KA68BwP9gdTzE1ESO2Zp"]+ "values": [+ "0KA68BwP9gdTzE1ESO2Zp"+ ]}],["uHB3Fjb7-NELG-bnH7bXB",{"instanceId": "uHB3Fjb7-NELG-bnH7bXB",- "values": ["mf2C07UBmGT7y_G4Du3yg"]+ "values": [+ "mf2C07UBmGT7y_G4Du3yg"+ ]}]],@@ -416,7 +427,9 @@},"deployment": {"destination": "saas",- "domains": ["cli-basic-test-d0osr"],+ "domains": [+ "cli-basic-test-d0osr"+ ],"assetsDomain": "cli-basic-test-d0osr","excludeWstdDomainFromSearch": false}@@ -444,7 +457,9 @@"id": "WPPAbLFyJD_02vhjRd8P4","name": "Another page","title": "\"Another page\"",- "history": ["/another-page"],+ "history": [+ "/another-page"+ ],"rootInstanceId": "n_VBMr7klpx25buS0NV7R","systemDataSourceId": "tdXe9gFf83hSo9BLWU6xl","meta": {diff --git a/fixtures/react-router-cloudflare/app/__generated__/$resources.headers.server.ts b/fixtures/react-router-cloudflare/app/__generated__/$resources.headers.server.tsnew file mode 100644index 0000000000..a1c2be60fc--- /dev/null+++ b/fixtures/react-router-cloudflare/app/__generated__/$resources.headers.server.ts@@ -0,0 +1,2 @@+// Generated response header configuration for hosting adapters.+export const customHeaders: Array<{ route?: string; name: string; value: string }> = [];diff --git a/fixtures/react-router-docker/.webstudio/data.json b/fixtures/react-router-docker/.webstudio/data.jsonindex 797d7f0fea..83a8bd3120 100644--- a/fixtures/react-router-docker/.webstudio/data.json+++ b/fixtures/react-router-docker/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1he6g9u",+ "bundleVersion": "bundle-1e81gg6","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",@@ -23,7 +23,9 @@"id": "WPPAbLFyJD_02vhjRd8P4","name": "Another page","title": "\"Another page\"",- "history": ["/another-page"],+ "history": [+ "/another-page"+ ],"rootInstanceId": "n_VBMr7klpx25buS0NV7R","systemDataSourceId": "tdXe9gFf83hSo9BLWU6xl","meta": {@@ -53,7 +55,10 @@"id": "root","name": "Root","slug": "",- "children": ["9di_L14CzctvSruIoKVvE", "WPPAbLFyJD_02vhjRd8P4"]+ "children": [+ "9di_L14CzctvSruIoKVvE",+ "WPPAbLFyJD_02vhjRd8P4"+ ]}]},@@ -194,21 +199,27 @@"MMimeobf_zi4ZkRGXapju",{"instanceId": "MMimeobf_zi4ZkRGXapju",- "values": ["7_QL45cpvP-zG8Hkgf4cr"]+ "values": [+ "7_QL45cpvP-zG8Hkgf4cr"+ ]}],["BMJfjOzunWs8XkQgvvx1e",{"instanceId": "BMJfjOzunWs8XkQgvvx1e",- "values": ["0KA68BwP9gdTzE1ESO2Zp"]+ "values": [+ "0KA68BwP9gdTzE1ESO2Zp"+ ]}],["uHB3Fjb7-NELG-bnH7bXB",{"instanceId": "uHB3Fjb7-NELG-bnH7bXB",- "values": ["mf2C07UBmGT7y_G4Du3yg"]+ "values": [+ "mf2C07UBmGT7y_G4Du3yg"+ ]}]],@@ -416,7 +427,9 @@},"deployment": {"destination": "saas",- "domains": ["cli-basic-test-d0osr"],+ "domains": [+ "cli-basic-test-d0osr"+ ],"assetsDomain": "cli-basic-test-d0osr","excludeWstdDomainFromSearch": false}@@ -444,7 +457,9 @@"id": "WPPAbLFyJD_02vhjRd8P4","name": "Another page","title": "\"Another page\"",- "history": ["/another-page"],+ "history": [+ "/another-page"+ ],"rootInstanceId": "n_VBMr7klpx25buS0NV7R","systemDataSourceId": "tdXe9gFf83hSo9BLWU6xl","meta": {diff --git a/fixtures/react-router-docker/app/__generated__/$resources.headers.server.ts b/fixtures/react-router-docker/app/__generated__/$resources.headers.server.tsnew file mode 100644index 0000000000..a1c2be60fc--- /dev/null+++ b/fixtures/react-router-docker/app/__generated__/$resources.headers.server.ts@@ -0,0 +1,2 @@+// Generated response header configuration for hosting adapters.+export const customHeaders: Array<{ route?: string; name: string; value: string }> = [];diff --git a/fixtures/react-router-netlify/.webstudio/data.json b/fixtures/react-router-netlify/.webstudio/data.jsonindex 797d7f0fea..83a8bd3120 100644--- a/fixtures/react-router-netlify/.webstudio/data.json+++ b/fixtures/react-router-netlify/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1he6g9u",+ "bundleVersion": "bundle-1e81gg6","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",@@ -23,7 +23,9 @@"id": "WPPAbLFyJD_02vhjRd8P4","name": "Another page","title": "\"Another page\"",- "history": ["/another-page"],+ "history": [+ "/another-page"+ ],"rootInstanceId": "n_VBMr7klpx25buS0NV7R","systemDataSourceId": "tdXe9gFf83hSo9BLWU6xl","meta": {@@ -53,7 +55,10 @@"id": "root","name": "Root","slug": "",- "children": ["9di_L14CzctvSruIoKVvE", "WPPAbLFyJD_02vhjRd8P4"]+ "children": [+ "9di_L14CzctvSruIoKVvE",+ "WPPAbLFyJD_02vhjRd8P4"+ ]}]},@@ -194,21 +199,27 @@"MMimeobf_zi4ZkRGXapju",{"instanceId": "MMimeobf_zi4ZkRGXapju",- "values": ["7_QL45cpvP-zG8Hkgf4cr"]+ "values": [+ "7_QL45cpvP-zG8Hkgf4cr"+ ]}],["BMJfjOzunWs8XkQgvvx1e",{"instanceId": "BMJfjOzunWs8XkQgvvx1e",- "values": ["0KA68BwP9gdTzE1ESO2Zp"]+ "values": [+ "0KA68BwP9gdTzE1ESO2Zp"+ ]}],["uHB3Fjb7-NELG-bnH7bXB",{"instanceId": "uHB3Fjb7-NELG-bnH7bXB",- "values": ["mf2C07UBmGT7y_G4Du3yg"]+ "values": [+ "mf2C07UBmGT7y_G4Du3yg"+ ]}]],@@ -416,7 +427,9 @@},"deployment": {"destination": "saas",- "domains": ["cli-basic-test-d0osr"],+ "domains": [+ "cli-basic-test-d0osr"+ ],"assetsDomain": "cli-basic-test-d0osr","excludeWstdDomainFromSearch": false}@@ -444,7 +457,9 @@"id": "WPPAbLFyJD_02vhjRd8P4","name": "Another page","title": "\"Another page\"",- "history": ["/another-page"],+ "history": [+ "/another-page"+ ],"rootInstanceId": "n_VBMr7klpx25buS0NV7R","systemDataSourceId": "tdXe9gFf83hSo9BLWU6xl","meta": {diff --git a/fixtures/react-router-netlify/app/__generated__/$resources.headers.server.ts b/fixtures/react-router-netlify/app/__generated__/$resources.headers.server.tsnew file mode 100644index 0000000000..a1c2be60fc--- /dev/null+++ b/fixtures/react-router-netlify/app/__generated__/$resources.headers.server.ts@@ -0,0 +1,2 @@+// Generated response header configuration for hosting adapters.+export const customHeaders: Array<{ route?: string; name: string; value: string }> = [];diff --git a/fixtures/react-router-vercel/.webstudio/data.json b/fixtures/react-router-vercel/.webstudio/data.jsonindex 797d7f0fea..83a8bd3120 100644--- a/fixtures/react-router-vercel/.webstudio/data.json+++ b/fixtures/react-router-vercel/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1he6g9u",+ "bundleVersion": "bundle-1e81gg6","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",@@ -23,7 +23,9 @@"id": "WPPAbLFyJD_02vhjRd8P4","name": "Another page","title": "\"Another page\"",- "history": ["/another-page"],+ "history": [+ "/another-page"+ ],"rootInstanceId": "n_VBMr7klpx25buS0NV7R","systemDataSourceId": "tdXe9gFf83hSo9BLWU6xl","meta": {@@ -53,7 +55,10 @@"id": "root","name": "Root","slug": "",- "children": ["9di_L14CzctvSruIoKVvE", "WPPAbLFyJD_02vhjRd8P4"]+ "children": [+ "9di_L14CzctvSruIoKVvE",+ "WPPAbLFyJD_02vhjRd8P4"+ ]}]},@@ -194,21 +199,27 @@"MMimeobf_zi4ZkRGXapju",{"instanceId": "MMimeobf_zi4ZkRGXapju",- "values": ["7_QL45cpvP-zG8Hkgf4cr"]+ "values": [+ "7_QL45cpvP-zG8Hkgf4cr"+ ]}],["BMJfjOzunWs8XkQgvvx1e",{"instanceId": "BMJfjOzunWs8XkQgvvx1e",- "values": ["0KA68BwP9gdTzE1ESO2Zp"]+ "values": [+ "0KA68BwP9gdTzE1ESO2Zp"+ ]}],["uHB3Fjb7-NELG-bnH7bXB",{"instanceId": "uHB3Fjb7-NELG-bnH7bXB",- "values": ["mf2C07UBmGT7y_G4Du3yg"]+ "values": [+ "mf2C07UBmGT7y_G4Du3yg"+ ]}]],@@ -416,7 +427,9 @@},"deployment": {"destination": "saas",- "domains": ["cli-basic-test-d0osr"],+ "domains": [+ "cli-basic-test-d0osr"+ ],"assetsDomain": "cli-basic-test-d0osr","excludeWstdDomainFromSearch": false}@@ -444,7 +457,9 @@"id": "WPPAbLFyJD_02vhjRd8P4","name": "Another page","title": "\"Another page\"",- "history": ["/another-page"],+ "history": [+ "/another-page"+ ],"rootInstanceId": "n_VBMr7klpx25buS0NV7R","systemDataSourceId": "tdXe9gFf83hSo9BLWU6xl","meta": {diff --git a/fixtures/react-router-vercel/app/__generated__/$resources.headers.server.ts b/fixtures/react-router-vercel/app/__generated__/$resources.headers.server.tsnew file mode 100644index 0000000000..a1c2be60fc--- /dev/null+++ b/fixtures/react-router-vercel/app/__generated__/$resources.headers.server.ts@@ -0,0 +1,2 @@+// Generated response header configuration for hosting adapters.+export const customHeaders: Array<{ route?: string; name: string; value: string }> = [];diff --git a/fixtures/ssg-cloudflare-pages/.webstudio/data.json b/fixtures/ssg-cloudflare-pages/.webstudio/data.jsonindex cb2cc8b4e6..c2cbe7fbae 100644--- a/fixtures/ssg-cloudflare-pages/.webstudio/data.json+++ b/fixtures/ssg-cloudflare-pages/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1he6g9u",+ "bundleVersion": "bundle-1e81gg6","build": {"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",@@ -23,7 +23,9 @@"id": "WPPAbLFyJD_02vhjRd8P4","name": "Another page","title": "\"Another page\"",- "history": ["/another-page"],+ "history": [+ "/another-page"+ ],"rootInstanceId": "n_VBMr7klpx25buS0NV7R","systemDataSourceId": "tdXe9gFf83hSo9BLWU6xl","meta": {@@ -53,7 +55,10 @@"id": "root","name": "Root","slug": "",- "children": ["9di_L14CzctvSruIoKVvE", "WPPAbLFyJD_02vhjRd8P4"]+ "children": [+ "9di_L14CzctvSruIoKVvE",+ "WPPAbLFyJD_02vhjRd8P4"+ ]}]},@@ -194,21 +199,27 @@"MMimeobf_zi4ZkRGXapju",{"instanceId": "MMimeobf_zi4ZkRGXapju",- "values": ["7_QL45cpvP-zG8Hkgf4cr"]+ "values": [+ "7_QL45cpvP-zG8Hkgf4cr"+ ]}],["BMJfjOzunWs8XkQgvvx1e",{"instanceId": "BMJfjOzunWs8XkQgvvx1e",- "values": ["0KA68BwP9gdTzE1ESO2Zp"]+ "values": [+ "0KA68BwP9gdTzE1ESO2Zp"+ ]}],["uHB3Fjb7-NELG-bnH7bXB",{"instanceId": "uHB3Fjb7-NELG-bnH7bXB",- "values": ["mf2C07UBmGT7y_G4Du3yg"]+ "values": [+ "mf2C07UBmGT7y_G4Du3yg"+ ]}]],@@ -442,7 +453,9 @@"id": "WPPAbLFyJD_02vhjRd8P4","name": "Another page","title": "\"Another page\"",- "history": ["/another-page"],+ "history": [+ "/another-page"+ ],"rootInstanceId": "n_VBMr7klpx25buS0NV7R","systemDataSourceId": "tdXe9gFf83hSo9BLWU6xl","meta": {diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.headers.server.ts b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.headers.server.tsnew file mode 100644index 0000000000..a1c2be60fc--- /dev/null+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.headers.server.ts@@ -0,0 +1,2 @@+// Generated response header configuration for hosting adapters.+export const customHeaders: Array<{ route?: string; name: string; value: string }> = [];diff --git a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json b/fixtures/ssg-netlify-by-project-id/.webstudio/data.jsonindex 7138a5d242..acd4a7e1ac 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-1he6g9u",+ "bundleVersion": "bundle-1e81gg6","build": {"id": "823cc69d-b2ed-418b-823c-2efc717319cd","projectId": "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e",@@ -51,7 +51,10 @@"id": "root","name": "Root","slug": "",- "children": ["Y60VJnVZMU_ifI0GnAR1N", "fOBamlMdmM461hLaITmV7"]+ "children": [+ "Y60VJnVZMU_ifI0GnAR1N",+ "fOBamlMdmM461hLaITmV7"+ ]}]},diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.headers.server.ts b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.headers.server.tsnew file mode 100644index 0000000000..a1c2be60fc--- /dev/null+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.headers.server.ts@@ -0,0 +1,2 @@+// Generated response header configuration for hosting adapters.+export const customHeaders: Array<{ route?: string; name: string; value: string }> = [];diff --git a/fixtures/webstudio-cloudflare-template/.webstudio/data.json b/fixtures/webstudio-cloudflare-template/.webstudio/data.jsonindex cb2cc8b4e6..c2cbe7fbae 100644--- a/fixtures/webstudio-cloudflare-template/.webstudio/data.json+++ b/fixtures/webstudio-cloudflare-template/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1he6g9u",+ "bundleVersion": "bundle-1e81gg6","build": {"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",@@ -23,7 +23,9 @@"id": "WPPAbLFyJD_02vhjRd8P4","name": "Another page","title": "\"Another page\"",- "history": ["/another-page"],+ "history": [+ "/another-page"+ ],"rootInstanceId": "n_VBMr7klpx25buS0NV7R","systemDataSourceId": "tdXe9gFf83hSo9BLWU6xl","meta": {@@ -53,7 +55,10 @@"id": "root","name": "Root","slug": "",- "children": ["9di_L14CzctvSruIoKVvE", "WPPAbLFyJD_02vhjRd8P4"]+ "children": [+ "9di_L14CzctvSruIoKVvE",+ "WPPAbLFyJD_02vhjRd8P4"+ ]}]},@@ -194,21 +199,27 @@"MMimeobf_zi4ZkRGXapju",{"instanceId": "MMimeobf_zi4ZkRGXapju",- "values": ["7_QL45cpvP-zG8Hkgf4cr"]+ "values": [+ "7_QL45cpvP-zG8Hkgf4cr"+ ]}],["BMJfjOzunWs8XkQgvvx1e",{"instanceId": "BMJfjOzunWs8XkQgvvx1e",- "values": ["0KA68BwP9gdTzE1ESO2Zp"]+ "values": [+ "0KA68BwP9gdTzE1ESO2Zp"+ ]}],["uHB3Fjb7-NELG-bnH7bXB",{"instanceId": "uHB3Fjb7-NELG-bnH7bXB",- "values": ["mf2C07UBmGT7y_G4Du3yg"]+ "values": [+ "mf2C07UBmGT7y_G4Du3yg"+ ]}]],@@ -442,7 +453,9 @@"id": "WPPAbLFyJD_02vhjRd8P4","name": "Another page","title": "\"Another page\"",- "history": ["/another-page"],+ "history": [+ "/another-page"+ ],"rootInstanceId": "n_VBMr7klpx25buS0NV7R","systemDataSourceId": "tdXe9gFf83hSo9BLWU6xl","meta": {diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.headers.server.ts b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.headers.server.tsnew file mode 100644index 0000000000..a1c2be60fc--- /dev/null+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.headers.server.ts@@ -0,0 +1,2 @@+// Generated response header configuration for hosting adapters.+export const customHeaders: Array<{ route?: string; name: string; value: string }> = [];diff --git a/fixtures/webstudio-features/.webstudio/data.json b/fixtures/webstudio-features/.webstudio/data.jsonindex 2ed5f73d73..a47e19ff2c 100644--- a/fixtures/webstudio-features/.webstudio/data.json+++ b/fixtures/webstudio-features/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1he6g9u",+ "bundleVersion": "bundle-1e81gg6","build": {"id": "1b66ee06-8ea5-4420-9a0e-e0d3a67aca32","projectId": "cddc1d44-af37-4cb6-a430-d300cf6f932d",@@ -45,7 +45,9 @@"id": "szYLvBduHPmbtqQKCDY0b","name": "RouteWithSymbols","title": "\"RouteWithSymbols\"",- "history": ["/_route_with_symbols_"],+ "history": [+ "/_route_with_symbols_"+ ],"rootInstanceId": "EDEfpMPRqDejthtwkH7ws","systemDataSourceId": "UiZtSC5BK8Ub-Ow7-XOdW","meta": {@@ -345,7 +347,9 @@"id": "42cWhASQ3tTtKDnsvzhUF","name": "Nested","slug": "nested",- "children": ["Pnz-BxUm6XmvFygk_XdEy"]+ "children": [+ "Pnz-BxUm6XmvFygk_XdEy"+ ]}]},@@ -2530,322 +2534,414 @@"nVMWvMsaLCcb0o1wuNQgg",{"instanceId": "nVMWvMsaLCcb0o1wuNQgg",- "values": ["y3sBN2gB0KCBXkheM6GMm"]+ "values": [+ "y3sBN2gB0KCBXkheM6GMm"+ ]}],["f0kF-WmL7DQg7MSyRvqY1",{"instanceId": "f0kF-WmL7DQg7MSyRvqY1",- "values": ["NeVTA8c7vqOjhHotkd0Dv"]+ "values": [+ "NeVTA8c7vqOjhHotkd0Dv"+ ]}],["5XDbqPrZDeCwq4YJ3CHsc",{"instanceId": "5XDbqPrZDeCwq4YJ3CHsc",- "values": ["ureLSWiLGOYeWpki2JUeu"]+ "values": [+ "ureLSWiLGOYeWpki2JUeu"+ ]}],["qPnkiFGDj8dITWb1kmpGl",{"instanceId": "qPnkiFGDj8dITWb1kmpGl",- "values": ["7HeiD-PCsn4VW6_fz5Skr"]+ "values": [+ "7HeiD-PCsn4VW6_fz5Skr"+ ]}],["pX1ovPI7NdC0HRjkw6Kpw",{"instanceId": "pX1ovPI7NdC0HRjkw6Kpw",- "values": ["8VVhDFG7dmCfwcwD4DH8D"]+ "values": [+ "8VVhDFG7dmCfwcwD4DH8D"+ ]}],["On9cvWCxr5rdZtY9O1Bv0",{"instanceId": "On9cvWCxr5rdZtY9O1Bv0",- "values": ["_t7PW0R2Naz9Zy7J1f8eQ"]+ "values": [+ "_t7PW0R2Naz9Zy7J1f8eQ"+ ]}],["zJ927zk9txwUbYycKB7QA",{"instanceId": "zJ927zk9txwUbYycKB7QA",- "values": ["dPMbxwoxmuFjloniiOQb-"]+ "values": [+ "dPMbxwoxmuFjloniiOQb-"+ ]}],["sMxg7xT1hwYt05hbOvoPL",{"instanceId": "sMxg7xT1hwYt05hbOvoPL",- "values": ["wVw5XxXIHCKE0ye-4HNeK"]+ "values": [+ "wVw5XxXIHCKE0ye-4HNeK"+ ]}],["qQSA4NoyKC88O68mBiQe2",{"instanceId": "qQSA4NoyKC88O68mBiQe2",- "values": ["h9BV0WW02L74rm4w_yY7e"]+ "values": [+ "h9BV0WW02L74rm4w_yY7e"+ ]}],["RSk81lLj2IGXgchTuXF7V",{"instanceId": "RSk81lLj2IGXgchTuXF7V",- "values": ["8Mg2sVpRQaHDWI8DG7Qjz"]+ "values": [+ "8Mg2sVpRQaHDWI8DG7Qjz"+ ]}],["IUftdfjK-ilSzfOTdIx1u",{"instanceId": "IUftdfjK-ilSzfOTdIx1u",- "values": ["ZLyayr_Puk3HM35c44F2J"]+ "values": [+ "ZLyayr_Puk3HM35c44F2J"+ ]}],["C838wkvIcA1BQu30Xu2G8",{"instanceId": "C838wkvIcA1BQu30Xu2G8",- "values": ["n6w3ORlRsss2eBGMq3bW1"]+ "values": [+ "n6w3ORlRsss2eBGMq3bW1"+ ]}],["fYUOB_brm6s0Ky68lzMfU",{"instanceId": "fYUOB_brm6s0Ky68lzMfU",- "values": ["ANkU37d5ZGfcSzPhzwnGD"]+ "values": [+ "ANkU37d5ZGfcSzPhzwnGD"+ ]}],["dfd4gonev_AX6BpuCsxjb",{"instanceId": "dfd4gonev_AX6BpuCsxjb",- "values": ["s6cuBxkGT20NUG_kWpsQI"]+ "values": [+ "s6cuBxkGT20NUG_kWpsQI"+ ]}],["wRw75kuvFzl5NWD8IGJoI",{"instanceId": "wRw75kuvFzl5NWD8IGJoI",- "values": ["eIzOGCjVa5lQceZUhtIVK"]+ "values": [+ "eIzOGCjVa5lQceZUhtIVK"+ ]}],["wNRVuu0L5E8TVufKdswp1",{"instanceId": "wNRVuu0L5E8TVufKdswp1",- "values": ["4pgxDxhhX5AvMmL4olZw0"]+ "values": [+ "4pgxDxhhX5AvMmL4olZw0"+ ]}],["65djoTmSBGemZ2L5izQ5M",{"instanceId": "65djoTmSBGemZ2L5izQ5M",- "values": ["dWnaFMuWYYTjdOgCbt0LQ"]+ "values": [+ "dWnaFMuWYYTjdOgCbt0LQ"+ ]}],["UJYfe6kH7HqhH0YYeJwe7",{"instanceId": "UJYfe6kH7HqhH0YYeJwe7",- "values": ["rpyoufLHt2eYUBYVUvsvU"]+ "values": [+ "rpyoufLHt2eYUBYVUvsvU"+ ]}],["600nGddaNxGGdsuGgpxJR",{"instanceId": "600nGddaNxGGdsuGgpxJR",- "values": ["T633SDU2F_Tk_BEOYeis6"]+ "values": [+ "T633SDU2F_Tk_BEOYeis6"+ ]}],["Ta70VqUb_fGJXBT_zsnxQ",{"instanceId": "Ta70VqUb_fGJXBT_zsnxQ",- "values": ["-tj0IHwf7a17jeBULU-OR"]+ "values": [+ "-tj0IHwf7a17jeBULU-OR"+ ]}],["mOVPnIrlt6IwVAzI_i2Fc",{"instanceId": "mOVPnIrlt6IwVAzI_i2Fc",- "values": ["EG1HUMyU4Rw4xD2pnGi28"]+ "values": [+ "EG1HUMyU4Rw4xD2pnGi28"+ ]}],["AdXSAYCx4QDo5QN6nLoGs",{"instanceId": "AdXSAYCx4QDo5QN6nLoGs",- "values": ["49DYl_wcHv6juFsJK5Qv3"]+ "values": [+ "49DYl_wcHv6juFsJK5Qv3"+ ]}],["9I4GRU1sev48hREkQcKQ-",{"instanceId": "9I4GRU1sev48hREkQcKQ-",- "values": ["USUcfFPW4YwsvbvNORkpm"]+ "values": [+ "USUcfFPW4YwsvbvNORkpm"+ ]}],["81ejLVXyFEV1SxiJrWhyw",{"instanceId": "81ejLVXyFEV1SxiJrWhyw",- "values": ["y8DFYnVCeQ_smp3u6CSTn"]+ "values": [+ "y8DFYnVCeQ_smp3u6CSTn"+ ]}],["drCx7m8q_gnNQLrhPDA-g",{"instanceId": "drCx7m8q_gnNQLrhPDA-g",- "values": ["o9VRyqmvIarF6HrGMccU8"]+ "values": [+ "o9VRyqmvIarF6HrGMccU8"+ ]}],["T-rqx2b12pRrWcafRRoIG",{"instanceId": "T-rqx2b12pRrWcafRRoIG",- "values": ["g6Z7dAxi6LYB-XtI6SaRR"]+ "values": [+ "g6Z7dAxi6LYB-XtI6SaRR"+ ]}],["LYBzzBvHLrfSOmPLs52dP",{"instanceId": "LYBzzBvHLrfSOmPLs52dP",- "values": ["LnOCG1kkSViZaAVoz4GXw"]+ "values": [+ "LnOCG1kkSViZaAVoz4GXw"+ ]}],["3rtiNx74sdhz1rNTQBmRA",{"instanceId": "3rtiNx74sdhz1rNTQBmRA",- "values": ["MX5X3_9QBk2KNCj9_oKWA"]+ "values": [+ "MX5X3_9QBk2KNCj9_oKWA"+ ]}],["Dwv02N8aJoxXacL58cmf-",{"instanceId": "Dwv02N8aJoxXacL58cmf-",- "values": ["9manQUfGxXPqfUvJR7nx_"]+ "values": [+ "9manQUfGxXPqfUvJR7nx_"+ ]}],["TNyJ2G7r6h267foLukveQ",{"instanceId": "TNyJ2G7r6h267foLukveQ",- "values": ["FdQDnQuBGdJjsbJJkurgl"]+ "values": [+ "FdQDnQuBGdJjsbJJkurgl"+ ]}],["YCTo59XfqTGNPH7ow1rvU",{"instanceId": "YCTo59XfqTGNPH7ow1rvU",- "values": ["-S9zvxalqR_PGnY3STOlK"]+ "values": [+ "-S9zvxalqR_PGnY3STOlK"+ ]}],["VJAhRG8CDslSQStNf0C_A",{"instanceId": "VJAhRG8CDslSQStNf0C_A",- "values": ["2fMK05sbKQLCp_N7ES5cH"]+ "values": [+ "2fMK05sbKQLCp_N7ES5cH"+ ]}],["67Te7ahXi4mbqb0CMC6Xh",{"instanceId": "67Te7ahXi4mbqb0CMC6Xh",- "values": ["w3UQay-q-ZxidA7tiKjlT"]+ "values": [+ "w3UQay-q-ZxidA7tiKjlT"+ ]}],["RHGykFKK2R4PyjNtIuSEk",{"instanceId": "RHGykFKK2R4PyjNtIuSEk",- "values": ["nlUHVVdPJqX4ucX3QvPHQ"]+ "values": [+ "nlUHVVdPJqX4ucX3QvPHQ"+ ]}],["ccyTkEM40ar6Z2UTXhFvY",{"instanceId": "ccyTkEM40ar6Z2UTXhFvY",- "values": ["z9mqrlxshNacx8dvtUKFI"]+ "values": [+ "z9mqrlxshNacx8dvtUKFI"+ ]}],["1e-3lR1XsDg2IsPu4mSNr",{"instanceId": "1e-3lR1XsDg2IsPu4mSNr",- "values": ["Eboa64A1ivGBt9vVhHdkx"]+ "values": [+ "Eboa64A1ivGBt9vVhHdkx"+ ]}],["YrVDoWK0I_9hpQs5yJzLt",{"instanceId": "YrVDoWK0I_9hpQs5yJzLt",- "values": ["C-HNDjw4PJgh2x3Xt-zaT"]+ "values": [+ "C-HNDjw4PJgh2x3Xt-zaT"+ ]}],["Qrpsu4yKLKARA-82TnhLI",{"instanceId": "Qrpsu4yKLKARA-82TnhLI",- "values": ["iseTqeMVub0Y6Q_3eOQ0S"]+ "values": [+ "iseTqeMVub0Y6Q_3eOQ0S"+ ]}],["3hPo1LW5P_4VAyXUmVtpY",{"instanceId": "3hPo1LW5P_4VAyXUmVtpY",- "values": ["Uhs5fZ65aKJ2wz5eB2fCJ"]+ "values": [+ "Uhs5fZ65aKJ2wz5eB2fCJ"+ ]}],["KCX8plaeWZXn98-4qmHBW",{"instanceId": "KCX8plaeWZXn98-4qmHBW",- "values": ["9GVBj1HWWhCsENaCEZID-"]+ "values": [+ "9GVBj1HWWhCsENaCEZID-"+ ]}],["81TW-o_0QLHlfmBAKFyCQ",{"instanceId": "81TW-o_0QLHlfmBAKFyCQ",- "values": ["mcplLi9TYqk__JBKYzuss"]+ "values": [+ "mcplLi9TYqk__JBKYzuss"+ ]}],["cvCjIfx9TJ3XeeSpCnW1w",{"instanceId": "cvCjIfx9TJ3XeeSpCnW1w",- "values": ["8WyGOidmbyXhMWoXUdEkK"]+ "values": [+ "8WyGOidmbyXhMWoXUdEkK"+ ]}],["hi1l-ro0pCVQpHFIwIhFO",{"instanceId": "hi1l-ro0pCVQpHFIwIhFO",- "values": ["hSMd0d2O_5ogkTfvV8g8B"]+ "values": [+ "hSMd0d2O_5ogkTfvV8g8B"+ ]}],["tOdjbQbLEf52thwmubL7R",{"instanceId": "tOdjbQbLEf52thwmubL7R",- "values": ["SdJcDQJhrZ0zxtPqj546x"]+ "values": [+ "SdJcDQJhrZ0zxtPqj546x"+ ]}],["g__o13UKOkD0KImnp-sWp",{"instanceId": "g__o13UKOkD0KImnp-sWp",- "values": ["hEVSzkOEBn_3dNyo65PAM"]+ "values": [+ "hEVSzkOEBn_3dNyo65PAM"+ ]}],["Ol5bklKKxyJaS7Q3jcCfD",{"instanceId": "Ol5bklKKxyJaS7Q3jcCfD",- "values": ["U6kV-2LTnN9kR4jWfLb1c"]+ "values": [+ "U6kV-2LTnN9kR4jWfLb1c"+ ]}]],@@ -2890,7 +2986,9 @@"value": [{"type": "execute",- "args": ["value"],+ "args": [+ "value"+ ],"code": "$ws$dataSource$RR_FthRebEUcAKUJIXl0j = value"}]@@ -2966,7 +3064,9 @@"value": [{"type": "execute",- "args": ["state"],+ "args": [+ "state"+ ],"code": "$ws$dataSource$KvfuNNCNslj7nAGsD69Fl = state"}]@@ -3042,7 +3142,9 @@"value": [{"type": "execute",- "args": ["state"],+ "args": [+ "state"+ ],"code": "$ws$dataSource$Ip0FRY7L24QrIMdtuMN5j = state"}]@@ -6896,7 +6998,9 @@},"deployment": {"destination": "saas",- "domains": ["webstudio-fixture-project-a-0su3o"],+ "domains": [+ "webstudio-fixture-project-a-0su3o"+ ],"assetsDomain": "webstudio-fixture-project-a-0su3o","excludeWstdDomainFromSearch": false}@@ -6955,7 +7059,9 @@"id": "szYLvBduHPmbtqQKCDY0b","name": "RouteWithSymbols","title": "\"RouteWithSymbols\"",- "history": ["/_route_with_symbols_"],+ "history": [+ "/_route_with_symbols_"+ ],"rootInstanceId": "EDEfpMPRqDejthtwkH7ws","systemDataSourceId": "UiZtSC5BK8Ub-Ow7-XOdW","meta": {diff --git a/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.jsindex 2008885fa2..d2872d9a1c 100644--- a/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js+++ b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js@@ -1,194 +1,197 @@-var Rd=Object.defineProperty;var kd=(t,e)=>{for(var n in e)Rd(t,n,{get:e[n],enumerable:!0})};var si;function w(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 Ry=Symbol("zod_brand"),Te=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Rt=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(si=globalThis).__zod_globalConfig??(si.__zod_globalConfig={});var kt=globalThis.__zod_globalConfig;function xe(t){return t&&Object.assign(kt,t),kt}var F={};kd(F,{BIGINT_FORMAT_RANGES:()=>li,Class:()=>Eo,NUMBER_FORMAT_RANGES:()=>Ro,aborted:()=>et,allowsEval:()=>Ao,assert:()=>Nd,assertEqual:()=>Id,assertIs:()=>Cd,assertNever:()=>Td,assertNotEqual:()=>Od,assignProp:()=>Xe,base64ToUint8Array:()=>di,base64urlToUint8Array:()=>Xd,cached:()=>Ot,captureStackTrace:()=>Wn,cleanEnum:()=>Yd,cleanRegex:()=>dn,clone:()=>Se,cloneDef:()=>Pd,createTransparentProxy:()=>jd,defineLazy:()=>M,esc:()=>Kn,escapeRegex:()=>Ve,explicitlyAborted:()=>ko,extend:()=>Vd,finalizeIssue:()=>he,floatSafeRemainder:()=>xo,getElementAtPath:()=>Ld,getEnumValues:()=>ln,getLengthableOrigin:()=>pn,getParsedType:()=>Bd,getSizableOrigin:()=>fi,hexToUint8Array:()=>ep,isObject:()=>wt,isPlainObject:()=>He,issue:()=>Ct,joinValues:()=>$d,jsonStringifyReplacer:()=>It,merge:()=>qd,mergeDefs:()=>Qe,normalizeParams:()=>I,nullish:()=>fn,numKeys:()=>Zd,objectClone:()=>zd,omit:()=>Qd,optionalKeys:()=>Do,parsedType:()=>Wd,partial:()=>Jd,pick:()=>Ud,prefixIssues:()=>Ge,primitiveTypes:()=>ci,promiseAllObject:()=>Md,propertyKeyTypes:()=>vo,randomString:()=>Fd,required:()=>Kd,safeExtend:()=>Gd,shallowClone:()=>ai,slugify:()=>So,stringifyPrimitive:()=>ui,uint8ArrayToBase64:()=>pi,uint8ArrayToBase64url:()=>Hd,uint8ArrayToHex:()=>tp,unwrapMessage:()=>un});function Id(t){return t}function Od(t){return t}function Cd(t){}function Td(t){throw new Error("Unexpected value in exhaustive check")}function Nd(t){}function ln(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 $d(t,e="|"){return t.map(n=>ui(n)).join(e)}function It(t,e){return typeof e=="bigint"?e.toString():e}function Ot(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function fn(t){return t==null}function dn(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function xo(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 ii=Symbol("evaluating");function M(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==ii)return r===void 0&&(r=ii,r=n()),r},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function zd(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Xe(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Qe(...t){let e={};for(let n of t){let r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function Pd(t){return Qe(t._zod.def)}function Ld(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function Md(t){let e=Object.keys(t),n=e.map(r=>t[r]);return Promise.all(n).then(r=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=r[s];return o})}function Fd(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<t;r++)n+=e[Math.floor(Math.random()*e.length)];return n}function Kn(t){return JSON.stringify(t)}function So(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Wn="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function wt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Ao=Ot(()=>{if(kt.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function He(t){if(wt(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let n=e.prototype;return!(wt(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function ai(t){return He(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function Zd(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}var Bd=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}`)}},vo=new Set(["string","number","symbol"]),ci=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ve(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Se(t,e,n){let r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function I(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function jd(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 ui(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Do(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Ro={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},li={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Ud(t,e){let n=t._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=Qe(t._zod.def,{get shape(){let i={};for(let a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(i[a]=n.shape[a])}return Xe(this,"shape",i),i},checks:[]});return Se(t,s)}function Qd(t,e){let n=t._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=Qe(t._zod.def,{get shape(){let i={...t._zod.def.shape};for(let a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete i[a]}return Xe(this,"shape",i),i},checks:[]});return Se(t,s)}function Vd(t,e){if(!He(e))throw new Error("Invalid input to extend: expected a plain object");let n=t._zod.def.checks;if(n&&n.length>0){let s=t._zod.def.shape;for(let i in e)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Qe(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return Xe(this,"shape",s),s}});return Se(t,o)}function Gd(t,e){if(!He(e))throw new Error("Invalid input to safeExtend: expected a plain object");let n=Qe(t._zod.def,{get shape(){let r={...t._zod.def.shape,...e};return Xe(this,"shape",r),r}});return Se(t,n)}function qd(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=Qe(t._zod.def,{get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Xe(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return Se(t,n)}function Jd(t,e,n){let o=e._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let i=Qe(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(n)for(let u in n){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(c[u]=t?new t({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)c[u]=t?new t({type:"optional",innerType:a[u]}):a[u];return Xe(this,"shape",c),c},checks:[]});return Se(e,i)}function Kd(t,e,n){let r=Qe(e._zod.def,{get shape(){let o=e._zod.def.shape,s={...o};if(n)for(let i in n){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(s[i]=new t({type:"nonoptional",innerType:o[i]}))}else for(let i in o)s[i]=new t({type:"nonoptional",innerType:o[i]});return Xe(this,"shape",s),s}});return Se(e,r)}function et(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function ko(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue===!1)return!0;return!1}function Ge(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function un(t){return typeof t=="string"?t:t?.message}function he(t,e,n){let r=t.message?t.message:un(t.inst?._zod.def?.error?.(t))??un(e?.error?.(t))??un(n.customError?.(t))??un(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 fi(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function pn(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Wd(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let n=t;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return e}function Ct(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function Yd(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function di(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 pi(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}function Xd(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-e.length%4)%4);return di(e+n)}function Hd(t){return pi(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function ep(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 tp(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var Eo=class{constructor(...e){}};var mi=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,It,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Yn=w("$ZodError",mi),Io=w("$ZodError",mi,{Parent:Error});function hi(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 yi(t,e=n=>n.message){let n={_errors:[]},r=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>r({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")r({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")r({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)n._errors.push(e(i));else{let c=n,u=0;for(;u<a.length;){let d=a[u];u===a.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(e(i))):c[d]=c[d]||{_errors:[]},c=c[d],u++}}}};return r(t),n}var Xn=t=>(e,n,r,o)=>{let s=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new Te;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>he(c,s,xe())));throw Wn(a,o?.callee),a}return i.value};var Hn=t=>async(e,n,r,o)=>{let s=r?{...r,async:!0}:{async:!0},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>he(c,s,xe())));throw Wn(a,o?.callee),a}return i.value};var mn=t=>(e,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Te;return s.issues.length?{success:!1,error:new(t??Yn)(s.issues.map(i=>he(i,o,xe())))}:{success:!0,data:s.value}},gi=mn(Io),hn=t=>async(e,n,r)=>{let o=r?{...r,async:!0}:{async:!0},s=e._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>he(i,o,xe())))}:{success:!0,data:s.value}},bi=hn(Io),wi=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Xn(t)(e,n,o)};var _i=t=>(e,n,r)=>Xn(t)(e,n,r);var Ei=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Hn(t)(e,n,o)};var xi=t=>async(e,n,r)=>Hn(t)(e,n,r);var Si=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return mn(t)(e,n,o)};var Ai=t=>(e,n,r)=>mn(t)(e,n,r);var vi=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return hn(t)(e,n,o)};var Di=t=>async(e,n,r)=>hn(t)(e,n,r);var Ri=/^[cC][0-9a-z]{6,}$/,ki=/^[0-9a-z]+$/,Ii=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Oi=/^[0-9a-vA-V]{20}$/,Ci=/^[A-Za-z0-9]{27}$/,Ti=/^[a-zA-Z0-9_-]{21}$/,Ni=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var $i=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Oo=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 zi=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var rp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Pi(){return new RegExp(rp,"u")}var Li=/^(?:(?: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])$/,Mi=/^(([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 Fi=/^((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])$/,Zi=/^(([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])$/,Bi=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Co=/^[A-Za-z0-9_-]*$/;var ji=/^https?$/,Ui=/^\+[1-9]\d{6,14}$/,Qi="(?:(?:\\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])))",Vi=new RegExp(`^${Qi}$`);function Gi(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function qi(t){return new RegExp(`^${Gi(t)}$`)}function Ji(t){let e=Gi({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(`^${Qi}T(?:${r})$`)}var Ki=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Wi=/^-?\d+$/,To=/^-?\d+(?:\.\d+)?$/,Yi=/^(?:true|false)$/i,Xi=/^null$/i;var Hi=/^[^A-Z]*$/,ea=/^[^a-z]*$/;var te=w("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),ta={number:"number",bigint:"bigint",object:"date"},No=w("$ZodCheckLessThan",(t,e)=>{te.init(t,e);let n=ta[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})}}),$o=w("$ZodCheckGreaterThan",(t,e)=>{te.init(t,e);let n=ta[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})}}),na=w("$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):xo(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})}}),ra=w("$ZodCheckNumberFormat",(t,e)=>{te.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,s]=Ro[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=Wi)}),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 oa=w("$ZodCheckMaxLength",(t,e)=>{var n;te.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!fn(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=pn(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),sa=w("$ZodCheckMinLength",(t,e)=>{var n;te.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!fn(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=pn(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),ia=w("$ZodCheckLengthEquals",(t,e)=>{var n;te.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!fn(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=pn(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})}}),yn=w("$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=()=>{})}),aa=w("$ZodCheckRegex",(t,e)=>{yn.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})}}),ca=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Hi),yn.init(t,e)}),ua=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=ea),yn.init(t,e)}),la=w("$ZodCheckIncludes",(t,e)=>{te.init(t,e);let n=Ve(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),fa=w("$ZodCheckStartsWith",(t,e)=>{te.init(t,e);let n=new RegExp(`^${Ve(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),da=w("$ZodCheckEndsWith",(t,e)=>{te.init(t,e);let n=new RegExp(`.*${Ve(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}});var pa=w("$ZodCheckOverwrite",(t,e)=>{te.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});var tr=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`-`).filter(i=>i),o=Math.min(...r.map(i=>i.length-i.trimStart().length)),s=r.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,n=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...n,o.join(`-`))}};var ha={major:4,minor:4,patch:3};var U=w("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=ha;let r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(let o of r)for(let s of o._zod.onattach)s(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,a,c)=>{let u=et(i),d;for(let l of a){if(l._zod.def.when){if(ko(i)||!l._zod.def.when(i))continue}else if(u)continue;let f=i.issues.length,p=l._zod.check(i);if(p instanceof Promise&&c?.async===!1)throw new Te;if(d||p instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await p,i.issues.length!==f&&(u||(u=et(i,f)))});else{if(i.issues.length===f)continue;u||(u=et(i,f))}}return d?d.then(()=>i):i},s=(i,a,c)=>{if(et(i))return i.aborted=!0,i;let u=o(a,r,c);if(u instanceof Promise){if(c.async===!1)throw new Te;return u.then(d=>t._zod.parse(d,c))}return t._zod.parse(u,c)};t._zod.run=(i,a)=>{if(a.skipChecks)return t._zod.parse(i,a);if(a.direction==="backward"){let u=t._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(d=>s(d,i,a)):s(u,i,a)}let c=t._zod.parse(i,a);if(c instanceof Promise){if(a.async===!1)throw new Te;return c.then(u=>o(u,r,a))}return o(c,r,a)}}M(t,"~standard",()=>({validate:o=>{try{let s=gi(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return bi(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),or=w("$ZodString",(t,e)=>{U.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Ki(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=w("$ZodStringFormat",(t,e)=>{yn.init(t,e),or.init(t,e)}),Aa=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=$i),Q.init(t,e)}),va=w("$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=Oo(r))}else e.pattern??(e.pattern=Oo());Q.init(t,e)}),Da=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=zi),Q.init(t,e)}),Ra=w("$ZodURL",(t,e)=>{Q.init(t,e),t._zod.check=n=>{try{let r=n.value.trim();if(!e.normalize&&e.protocol?.source===ji.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})}}}),ka=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Pi()),Q.init(t,e)}),Ia=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Ti),Q.init(t,e)}),Oa=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Ri),Q.init(t,e)}),Ca=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=ki),Q.init(t,e)}),Ta=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Ii),Q.init(t,e)}),Na=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Oi),Q.init(t,e)}),$a=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Ci),Q.init(t,e)}),za=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Ji(e)),Q.init(t,e)}),Pa=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Vi),Q.init(t,e)}),La=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=qi(e)),Q.init(t,e)}),Ma=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Ni),Q.init(t,e)}),Fa=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Li),Q.init(t,e),t._zod.bag.format="ipv4"}),Za=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Mi),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 Ba=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Fi),Q.init(t,e)}),ja=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Zi),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 Ua(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Qa=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Bi),Q.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{Ua(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function op(t){if(!Co.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Ua(n)}var Va=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Co),Q.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{op(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Ga=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Ui),Q.init(t,e)});function sp(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var qa=w("$ZodJWT",(t,e)=>{Q.init(t,e),t._zod.check=n=>{sp(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}});var Po=w("$ZodNumber",(t,e)=>{U.init(t,e),t._zod.pattern=t._zod.bag.pattern??To,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}}),Ja=w("$ZodNumberFormat",(t,e)=>{ra.init(t,e),Po.init(t,e)}),Ka=w("$ZodBoolean",(t,e)=>{U.init(t,e),t._zod.pattern=Yi,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 Wa=w("$ZodNull",(t,e)=>{U.init(t,e),t._zod.pattern=Xi,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 Ya=w("$ZodUnknown",(t,e)=>{U.init(t,e),t._zod.parse=n=>n}),Xa=w("$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 ya(t,e,n){t.issues.length&&e.issues.push(...Ge(n,t.issues)),e.value[n]=t.value}var Ha=w("$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=>ya(u,n,i))):ya(c,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function rr(t,e,n,r,o,s){let i=n in r;if(t.issues.length){if(o&&s&&!i)return;e.issues.push(...Ge(n,t.issues))}if(!i&&!o){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}t.value===void 0?i&&(e.value[n]=void 0):e.value[n]=t.value}function ec(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=Do(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function tc(t,e,n,r,o,s){let i=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,d=c.optin==="optional",l=c.optout==="optional";for(let f in e){if(f==="__proto__"||a.has(f))continue;if(u==="never"){i.push(f);continue}let p=c.run({value:e[f],issues:[]},r);p instanceof Promise?t.push(p.then(g=>rr(g,n,f,e,d,l))):rr(p,n,f,e,d,l)}return i.length&&n.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:s}),t.length?Promise.all(t).then(()=>n):n}var ip=w("$ZodObject",(t,e)=>{if(U.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let r=Ot(()=>ec(e));M(t._zod,"propValues",()=>{let a=e.shape,c={};for(let u in a){let d=a[u]._zod;if(d.values){c[u]??(c[u]=new Set);for(let l of d.values)c[u].add(l)}}return c});let o=wt,s=e.catchall,i;t._zod.parse=(a,c)=>{i??(i=r.value);let u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let d=[],l=i.shape;for(let f of i.keys){let p=l[f],g=p._zod.optin==="optional",m=p._zod.optout==="optional",h=p._zod.run({value:u[f],issues:[]},c);h instanceof Promise?d.push(h.then(y=>rr(y,a,f,u,g,m))):rr(h,a,f,u,g,m)}return s?tc(d,u,a,c,r.value,t):d.length?Promise.all(d).then(()=>a):a}}),nc=w("$ZodObjectJIT",(t,e)=>{ip.init(t,e);let n=t._zod.parse,r=Ot(()=>ec(e)),o=f=>{let p=new tr(["shape","payload","ctx"]),g=r.value,m=S=>{let _=Kn(S);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),y=0;for(let S of g.keys)h[S]=`key_${y++}`;p.write("const newResult = {};");for(let S of g.keys){let _=h[S],b=Kn(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 (${b} in input) {- payload.issues = payload.issues.concat(${_}.issues.map(iss => ({+var mm=Object.defineProperty;var wa=(e,t)=>{for(var n in t)mm(e,n,{get:t[n],enumerable:!0})};var xa;function k(e,t,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(e))return;a._zod.traits.add(e),t(a,c);let u=i.prototype,f=Object.keys(u);for(let l=0;l<f.length;l++){let p=f[l];p in a||(a[p]=u[p].bind(a))}}let o=n?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function i(a){var c;let u=n?.Parent?new s:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let f of u._zod.deferred)f();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(e)}),Object.defineProperty(i,"name",{value:e}),i}var Bw=Symbol("zod_brand"),He=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},en=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(xa=globalThis).__zod_globalConfig??(xa.__zod_globalConfig={});var tn=globalThis.__zod_globalConfig;function qe(e){return e&&Object.assign(tn,e),tn}var J={};wa(J,{BIGINT_FORMAT_RANGES:()=>ka,Class:()=>ys,NUMBER_FORMAT_RANGES:()=>Es,aborted:()=>_t,allowsEval:()=>xs,assert:()=>wm,assertEqual:()=>hm,assertIs:()=>ym,assertNever:()=>bm,assertNotEqual:()=>gm,assignProp:()=>wt,base64ToUint8Array:()=>Ra,base64urlToUint8Array:()=>Fm,cached:()=>rn,captureStackTrace:()=>zr,cleanEnum:()=>Pm,cleanRegex:()=>Bn,clone:()=>Ze,cloneDef:()=>Sm,createTransparentProxy:()=>Dm,defineLazy:()=>G,esc:()=>Nr,escapeRegex:()=>ft,explicitlyAborted:()=>As,extend:()=>Tm,finalizeIssue:()=>Oe,floatSafeRemainder:()=>bs,getElementAtPath:()=>Em,getEnumValues:()=>Fn,getLengthableOrigin:()=>qn,getParsedType:()=>Rm,getSizableOrigin:()=>va,hexToUint8Array:()=>Bm,isObject:()=>Ut,isPlainObject:()=>xt,issue:()=>on,joinValues:()=>xm,jsonStringifyReplacer:()=>nn,merge:()=>Nm,mergeDefs:()=>lt,normalizeParams:()=>$,nullish:()=>Mn,numKeys:()=>vm,objectClone:()=>_m,omit:()=>Cm,optionalKeys:()=>Ss,parsedType:()=>Lm,partial:()=>zm,pick:()=>Im,prefixIssues:()=>dt,primitiveTypes:()=>Ea,promiseAllObject:()=>Am,propertyKeyTypes:()=>_s,randomString:()=>km,required:()=>$m,safeExtend:()=>Om,shallowClone:()=>Sa,slugify:()=>ws,stringifyPrimitive:()=>Aa,uint8ArrayToBase64:()=>Da,uint8ArrayToBase64url:()=>Mm,uint8ArrayToHex:()=>qm,unwrapMessage:()=>Pn});function hm(e){return e}function gm(e){return e}function ym(e){}function bm(e){throw new Error("Unexpected value in exhaustive check")}function wm(e){}function Fn(e){let t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function xm(e,t="|"){return e.map(n=>Aa(n)).join(t)}function nn(e,t){return typeof t=="bigint"?t.toString():t}function rn(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function Mn(e){return e==null}function Bn(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function bs(e,t){let n=e/t,r=Math.round(n),o=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<o?0:n-r}var _a=Symbol("evaluating");function G(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==_a)return r===void 0&&(r=_a,r=n()),r},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function _m(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function wt(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function lt(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function Sm(e){return lt(e._zod.def)}function Em(e,t){return t?t.reduce((n,r)=>n?.[r],e):e}function Am(e){let t=Object.keys(e),n=t.map(r=>e[r]);return Promise.all(n).then(r=>{let o={};for(let s=0;s<t.length;s++)o[t[s]]=r[s];return o})}function km(e=10){let t="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<e;r++)n+=t[Math.floor(Math.random()*t.length)];return n}function Nr(e){return JSON.stringify(e)}function ws(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var zr="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var xs=rn(()=>{if(tn.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function xt(e){if(Ut(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let n=t.prototype;return!(Ut(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Sa(e){return xt(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function vm(e){let t=0;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}var Rm=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},_s=new Set(["string","number","symbol"]),Ea=new Set(["string","number","bigint","boolean","symbol","undefined"]);function ft(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ze(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function $(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Dm(e){let t;return new Proxy({},{get(n,r,o){return t??(t=e()),Reflect.get(t,r,o)},set(n,r,o,s){return t??(t=e()),Reflect.set(t,r,o,s)},has(n,r){return t??(t=e()),Reflect.has(t,r)},deleteProperty(n,r){return t??(t=e()),Reflect.deleteProperty(t,r)},ownKeys(n){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,r){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,r)},defineProperty(n,r,o){return t??(t=e()),Reflect.defineProperty(t,r,o)}})}function Aa(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Ss(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Es={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]},ka={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Im(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=lt(e._zod.def,{get shape(){let i={};for(let a in t){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(i[a]=n.shape[a])}return wt(this,"shape",i),i},checks:[]});return Ze(e,s)}function Cm(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=lt(e._zod.def,{get shape(){let i={...e._zod.def.shape};for(let a in t){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete i[a]}return wt(this,"shape",i),i},checks:[]});return Ze(e,s)}function Tm(e,t){if(!xt(t))throw new Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let s=e._zod.def.shape;for(let i in t)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=lt(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return wt(this,"shape",s),s}});return Ze(e,o)}function Om(e,t){if(!xt(t))throw new Error("Invalid input to safeExtend: expected a plain object");let n=lt(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return wt(this,"shape",r),r}});return Ze(e,n)}function Nm(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=lt(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return wt(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Ze(e,n)}function zm(e,t,n){let o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let i=lt(t._zod.def,{get shape(){let a=t._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]=e?new e({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)c[u]=e?new e({type:"optional",innerType:a[u]}):a[u];return wt(this,"shape",c),c},checks:[]});return Ze(t,i)}function $m(e,t,n){let r=lt(t._zod.def,{get shape(){let o=t._zod.def.shape,s={...o};if(n)for(let i in n){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(s[i]=new e({type:"nonoptional",innerType:o[i]}))}else for(let i in o)s[i]=new e({type:"nonoptional",innerType:o[i]});return wt(this,"shape",s),s}});return Ze(t,r)}function _t(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function As(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function dt(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Pn(e){return typeof e=="string"?e:e?.message}function Oe(e,t,n){let r=e.message?e.message:Pn(e.inst?._zod.def?.error?.(e))??Pn(t?.error?.(e))??Pn(n.customError?.(e))??Pn(n.localeError?.(e))??"Invalid input",{inst:o,continue:s,input:i,...a}=e;return a.path??(a.path=[]),a.message=r,t?.reportInput&&(a.input=i),a}function va(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function qn(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Lm(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function on(...e){let[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}function Pm(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function Ra(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function Da(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Fm(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4);return Ra(t+n)}function Mm(e){return Da(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Bm(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=Number.parseInt(t.slice(r,r+2),16);return n}function qm(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var ys=class{constructor(...t){}};var Ia=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,nn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},$r=k("$ZodError",Ia),ks=k("$ZodError",Ia,{Parent:Error});function Ca(e,t=n=>n.message){let n={},r=[];for(let o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}function Ta(e,t=n=>n.message){let n={_errors:[]},r=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(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(t(i));else{let c=n,u=0;for(;u<a.length;){let f=a[u];u===a.length-1?(c[f]=c[f]||{_errors:[]},c[f]._errors.push(t(i))):c[f]=c[f]||{_errors:[]},c=c[f],u++}}}};return r(e),n}var Lr=e=>(t,n,r,o)=>{let s=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new He;if(i.issues.length){let a=new(o?.Err??e)(i.issues.map(c=>Oe(c,s,qe())));throw zr(a,o?.callee),a}return i.value};var Pr=e=>async(t,n,r,o)=>{let s=r?{...r,async:!0}:{async:!0},i=t._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??e)(i.issues.map(c=>Oe(c,s,qe())));throw zr(a,o?.callee),a}return i.value};var Zn=e=>(t,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new He;return s.issues.length?{success:!1,error:new(e??$r)(s.issues.map(i=>Oe(i,o,qe())))}:{success:!0,data:s.value}},Oa=Zn(ks),Un=e=>async(t,n,r)=>{let o=r?{...r,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(i=>Oe(i,o,qe())))}:{success:!0,data:s.value}},Na=Un(ks),za=e=>(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Lr(e)(t,n,o)};var $a=e=>(t,n,r)=>Lr(e)(t,n,r);var La=e=>async(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Pr(e)(t,n,o)};var Pa=e=>async(t,n,r)=>Pr(e)(t,n,r);var Fa=e=>(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Zn(e)(t,n,o)};var Ma=e=>(t,n,r)=>Zn(e)(t,n,r);var Ba=e=>async(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Un(e)(t,n,o)};var qa=e=>async(t,n,r)=>Un(e)(t,n,r);var Za=/^[cC][0-9a-z]{6,}$/,Ua=/^[0-9a-z]+$/,ja=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Va=/^[0-9a-vA-V]{20}$/,Qa=/^[A-Za-z0-9]{27}$/,Ga=/^[a-zA-Z0-9_-]{21}$/,Ja=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Wa=/^([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})$/,vs=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;var Ka=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Um="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Ha(){return new RegExp(Um,"u")}var Ya=/^(?:(?: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])$/,Xa=/^(([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 ec=/^((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])$/,tc=/^(([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])$/,nc=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Rs=/^[A-Za-z0-9_-]*$/;var rc=/^https?$/,oc=/^\+[1-9]\d{6,14}$/,sc="(?:(?:\\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])))",ic=new RegExp(`^${sc}$`);function ac(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function cc(e){return new RegExp(`^${ac(e)}$`)}function uc(e){let t=ac({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${t}(?:${n.join("|")})`;return new RegExp(`^${sc}T(?:${r})$`)}var lc=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var fc=/^-?\d+$/,Ds=/^-?\d+(?:\.\d+)?$/,dc=/^(?:true|false)$/i,pc=/^null$/i;var mc=/^[^A-Z]*$/,hc=/^[^a-z]*$/;var de=k("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),gc={number:"number",bigint:"bigint",object:"date"},Is=k("$ZodCheckLessThan",(e,t)=>{de.init(e,t);let n=gc[typeof t.value];e._zod.onattach.push(r=>{let o=r._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Cs=k("$ZodCheckGreaterThan",(e,t)=>{de.init(e,t);let n=gc[typeof t.value];e._zod.onattach.push(r=>{let o=r._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),yc=k("$ZodCheckMultipleOf",(e,t)=>{de.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):bs(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),bc=k("$ZodCheckNumberFormat",(e,t)=>{de.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[o,s]=Es[t.format];e._zod.onattach.push(i=>{let a=i._zod.bag;a.format=t.format,a.minimum=o,a.maximum=s,n&&(a.pattern=fc)}),e._zod.check=i=>{let a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});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:e,origin:r,inclusive:!0,continue:!t.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var wc=k("$ZodCheckMaxLength",(e,t)=>{var n;de.init(e,t),(n=e._zod.def).when??(n.when=r=>{let o=r.value;return!Mn(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{let o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let o=r.value;if(o.length<=t.maximum)return;let i=qn(o);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),xc=k("$ZodCheckMinLength",(e,t)=>{var n;de.init(e,t),(n=e._zod.def).when??(n.when=r=>{let o=r.value;return!Mn(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{let o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let o=r.value;if(o.length>=t.minimum)return;let i=qn(o);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),_c=k("$ZodCheckLengthEquals",(e,t)=>{var n;de.init(e,t),(n=e._zod.def).when??(n.when=r=>{let o=r.value;return!Mn(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{let o=r._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=r=>{let o=r.value,s=o.length;if(s===t.length)return;let i=qn(o),a=s>t.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),jn=k("$ZodCheckStringFormat",(e,t)=>{var n,r;de.init(e,t),e._zod.onattach.push(o=>{let s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Sc=k("$ZodCheckRegex",(e,t)=>{jn.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ec=k("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=mc),jn.init(e,t)}),Ac=k("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=hc),jn.init(e,t)}),kc=k("$ZodCheckIncludes",(e,t)=>{de.init(e,t);let n=ft(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),vc=k("$ZodCheckStartsWith",(e,t)=>{de.init(e,t);let n=new RegExp(`^${ft(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),Rc=k("$ZodCheckEndsWith",(e,t)=>{de.init(e,t);let n=new RegExp(`.*${ft(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});var Dc=k("$ZodCheckOverwrite",(e,t)=>{de.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});var Mr=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let r=t.split(`+`).filter(i=>i),o=Math.min(...r.map(i=>i.length-i.trimStart().length)),s=r.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let t=Function,n=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...n,o.join(`+`))}};var Cc={major:4,minor:4,patch:3};var Y=k("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Cc;let r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(let o of r)for(let s of o._zod.onattach)s(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(i,a,c)=>{let u=_t(i),f;for(let l of a){if(l._zod.def.when){if(As(i)||!l._zod.def.when(i))continue}else if(u)continue;let p=i.issues.length,d=l._zod.check(i);if(d instanceof Promise&&c?.async===!1)throw new He;if(f||d instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await d,i.issues.length!==p&&(u||(u=_t(i,p)))});else{if(i.issues.length===p)continue;u||(u=_t(i,p))}}return f?f.then(()=>i):i},s=(i,a,c)=>{if(_t(i))return i.aborted=!0,i;let u=o(a,r,c);if(u instanceof Promise){if(c.async===!1)throw new He;return u.then(f=>e._zod.parse(f,c))}return e._zod.parse(u,c)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction==="backward"){let u=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(f=>s(f,i,a)):s(u,i,a)}let c=e._zod.parse(i,a);if(c instanceof Promise){if(a.async===!1)throw new He;return c.then(u=>o(u,r,a))}return o(c,r,a)}}G(e,"~standard",()=>({validate:o=>{try{let s=Oa(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Na(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),Zr=k("$ZodString",(e,t)=>{Y.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??lc(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),X=k("$ZodStringFormat",(e,t)=>{jn.init(e,t),Zr.init(e,t)}),Mc=k("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Wa),X.init(e,t)}),Bc=k("$ZodUUID",(e,t)=>{if(t.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=vs(r))}else t.pattern??(t.pattern=vs());X.init(e,t)}),qc=k("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ka),X.init(e,t)}),Zc=k("$ZodURL",(e,t)=>{X.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===rc.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}let o=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=o.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Uc=k("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Ha()),X.init(e,t)}),jc=k("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Ga),X.init(e,t)}),Vc=k("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Za),X.init(e,t)}),Qc=k("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Ua),X.init(e,t)}),Gc=k("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ja),X.init(e,t)}),Jc=k("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Va),X.init(e,t)}),Wc=k("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Qa),X.init(e,t)}),Kc=k("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=uc(t)),X.init(e,t)}),Hc=k("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ic),X.init(e,t)}),Yc=k("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=cc(t)),X.init(e,t)}),Xc=k("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Ja),X.init(e,t)}),eu=k("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ya),X.init(e,t),e._zod.bag.format="ipv4"}),tu=k("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Xa),X.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}});var nu=k("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ec),X.init(e,t)}),ru=k("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=tc),X.init(e,t),e._zod.check=n=>{let r=n.value.split("/");try{if(r.length!==2)throw new Error;let[o,s]=r;if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function ou(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var su=k("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=nc),X.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{ou(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function jm(e){if(!Rs.test(e))return!1;let t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return ou(n)}var iu=k("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Rs),X.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{jm(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),au=k("$ZodE164",(e,t)=>{t.pattern??(t.pattern=oc),X.init(e,t)});function Vm(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}var cu=k("$ZodJWT",(e,t)=>{X.init(e,t),e._zod.check=n=>{Vm(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}});var Os=k("$ZodNumber",(e,t)=>{Y.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ds,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),n}}),uu=k("$ZodNumberFormat",(e,t)=>{bc.init(e,t),Os.init(e,t)}),lu=k("$ZodBoolean",(e,t)=>{Y.init(e,t),e._zod.pattern=dc,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}});var fu=k("$ZodNull",(e,t)=>{Y.init(e,t),e._zod.pattern=pc,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{let o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}});var du=k("$ZodUnknown",(e,t)=>{Y.init(e,t),e._zod.parse=n=>n}),pu=k("$ZodNever",(e,t)=>{Y.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Tc(e,t,n){e.issues.length&&t.issues.push(...dt(n,e.issues)),t.value[n]=e.value}var mu=k("$ZodArray",(e,t)=>{Y.init(e,t),e._zod.parse=(n,r)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=t.element._zod.run({value:a,issues:[]},r);c instanceof Promise?s.push(c.then(u=>Tc(u,n,i))):Tc(c,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function qr(e,t,n,r,o,s){let i=n in r;if(e.issues.length){if(o&&s&&!i)return;t.issues.push(...dt(n,e.issues))}if(!i&&!o){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?i&&(t.value[n]=void 0):t.value[n]=e.value}function hu(e){let t=Object.keys(e.shape);for(let r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);let n=Ss(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function gu(e,t,n,r,o,s){let i=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,f=c.optin==="optional",l=c.optout==="optional";for(let p in t){if(p==="__proto__"||a.has(p))continue;if(u==="never"){i.push(p);continue}let d=c.run({value:t[p],issues:[]},r);d instanceof Promise?e.push(d.then(w=>qr(w,n,p,t,f,l))):qr(d,n,p,t,f,l)}return i.length&&n.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:s}),e.length?Promise.all(e).then(()=>n):n}var Qm=k("$ZodObject",(e,t)=>{if(Y.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let c={...a};return Object.defineProperty(t,"shape",{value:c}),c}})}let r=rn(()=>hu(t));G(e._zod,"propValues",()=>{let a=t.shape,c={};for(let u in a){let f=a[u]._zod;if(f.values){c[u]??(c[u]=new Set);for(let l of f.values)c[u].add(l)}}return c});let o=Ut,s=t.catchall,i;e._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:e}),a;a.value={};let f=[],l=i.shape;for(let p of i.keys){let d=l[p],w=d._zod.optin==="optional",h=d._zod.optout==="optional",y=d._zod.run({value:u[p],issues:[]},c);y instanceof Promise?f.push(y.then(m=>qr(m,a,p,u,w,h))):qr(y,a,p,u,w,h)}return s?gu(f,u,a,c,r.value,e):f.length?Promise.all(f).then(()=>a):a}}),yu=k("$ZodObjectJIT",(e,t)=>{Qm.init(e,t);let n=e._zod.parse,r=rn(()=>hu(t)),o=p=>{let d=new Mr(["shape","payload","ctx"]),w=r.value,h=S=>{let E=Nr(S);return`shape[${E}]._zod.run({ value: input[${E}], issues: [] }, ctx)`};d.write("const input = payload.value;");let y=Object.create(null),m=0;for(let S of w.keys)y[S]=`key_${m++}`;d.write("const newResult = {};");for(let S of w.keys){let E=y[S],_=Nr(S),x=p[S],R=x?._zod?.optin==="optional",v=x?._zod?.optout==="optional";d.write(`const ${E} = ${h(S)};`),R&&v?d.write(`+ if (${E}.issues.length) {+ if (${_} in input) {+ payload.issues = payload.issues.concat(${E}.issues.map(iss => ({...iss,- path: iss.path ? [${b}, ...iss.path] : [${b}]+ path: iss.path ? [${_}, ...iss.path] : [${_}]})));}}- if (${_}.value === undefined) {- if (${b} in input) {- newResult[${b}] = undefined;+ if (${E}.value === undefined) {+ if (${_} in input) {+ newResult[${_}] = undefined;}} else {- newResult[${b}] = ${_}.value;+ newResult[${_}] = ${E}.value;}- `):D?p.write(`- if (${_}.issues.length) {- payload.issues = payload.issues.concat(${_}.issues.map(iss => ({+ `):R?d.write(`+ if (${E}.issues.length) {+ payload.issues = payload.issues.concat(${E}.issues.map(iss => ({...iss,- path: iss.path ? [${b}, ...iss.path] : [${b}]+ path: iss.path ? [${_}, ...iss.path] : [${_}]})));}- if (${_}.value === undefined) {- if (${b} in input) {- newResult[${b}] = undefined;+ if (${E}.value === undefined) {+ if (${_} in input) {+ newResult[${_}] = undefined;}} else {- newResult[${b}] = ${_}.value;+ newResult[${_}] = ${E}.value;}- `):p.write(`- const ${_}_present = ${b} in input;- if (${_}.issues.length) {- payload.issues = payload.issues.concat(${_}.issues.map(iss => ({+ `):d.write(`+ const ${E}_present = ${_} in input;+ if (${E}.issues.length) {+ payload.issues = payload.issues.concat(${E}.issues.map(iss => ({...iss,- path: iss.path ? [${b}, ...iss.path] : [${b}]+ path: iss.path ? [${_}, ...iss.path] : [${_}]})));}- if (!${_}_present && !${_}.issues.length) {+ if (!${E}_present && !${E}.issues.length) {payload.issues.push({code: "invalid_type",expected: "nonoptional",input: undefined,- path: [${b}]+ path: [${_}]});}- if (${_}_present) {- if (${_}.value === undefined) {- newResult[${b}] = undefined;+ if (${E}_present) {+ if (${E}.value === undefined) {+ newResult[${_}] = undefined;} else {- newResult[${b}] = ${_}.value;+ newResult[${_}] = ${E}.value;}}- `)}p.write("payload.value = newResult;"),p.write("return payload;");let x=p.compile();return(S,_)=>x(f,S,_)},s,i=wt,a=!kt.jitless,u=a&&Ao.value,d=e.catchall,l;t._zod.parse=(f,p)=>{l??(l=r.value);let g=f.value;return i(g)?a&&u&&p?.async===!1&&p.jitless!==!0?(s||(s=o(e.shape)),f=s(f,p),d?tc([],g,f,p,l,t):f):n(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:g,inst:t}),f)}});function ga(t,e,n,r){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;let o=t.filter(s=>!et(s));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(s=>s.issues.map(i=>he(i,r,xe())))}),e)}var Lo=w("$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=>dn(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=>ga(a,r,t,o)):ga(i,r,t,o)}});var rc=w("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,Lo.init(t,e);let n=t._zod.parse;M(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let r=Ot(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!wt(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=r.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback||s.direction==="backward"?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(r.value.keys()),input:i,path:[e.discriminator],inst:t}),o)}}),oc=w("$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])=>ba(n,c,u)):ba(n,s,i)}});function zo(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=zo(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=zo(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 ba(t,e,n){let r=new Map,o;for(let a of e.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(let c of a.keys)r.has(c)||r.set(c,{}),r.get(c).l=!0}else t.issues.push(a);for(let a of n.issues)if(a.code==="unrecognized_keys")for(let c of a.keys)r.has(c)||r.set(c,{}),r.get(c).r=!0;else t.issues.push(a);let s=[...r].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&o&&t.issues.push({...o,keys:s}),et(t))return t;let i=zo(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 sc=w("$ZodRecord",(t,e)=>{U.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!He(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let s=[],i=e.keyType._zod.values;if(i){n.value={};let a=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let d=e.keyType._zod.run({value:u,issues:[]},r);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(d.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(p=>he(p,r,xe())),input:u,path:[u],inst:t});continue}let l=d.value,f=e.valueType._zod.run({value:o[u],issues:[]},r);f instanceof Promise?s.push(f.then(p=>{p.issues.length&&n.issues.push(...Ge(u,p.issues)),n.value[l]=p.value})):(f.issues.length&&n.issues.push(...Ge(u,f.issues)),n.value[l]=f.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{n.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},r);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&To.test(a)&&c.issues.length){let l=e.keyType._zod.run({value:Number(a),issues:[]},r);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");l.issues.length===0&&(c=l)}if(c.issues.length){e.mode==="loose"?n.value[a]=o[a]:n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(l=>he(l,r,xe())),input:a,path:[a],inst:t});continue}let d=e.valueType._zod.run({value:o[a],issues:[]},r);d instanceof Promise?s.push(d.then(l=>{l.issues.length&&n.issues.push(...Ge(a,l.issues)),n.value[c.value]=l.value})):(d.issues.length&&n.issues.push(...Ge(a,d.issues)),n.value[c.value]=d.value)}}return s.length?Promise.all(s).then(()=>n):n}});var ic=w("$ZodEnum",(t,e)=>{U.init(t,e);let n=ln(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(o=>vo.has(typeof o)).map(o=>typeof o=="string"?Ve(o):o.toString()).join("|")})$`),t._zod.parse=(o,s)=>{let i=o.value;return r.has(i)||o.issues.push({code:"invalid_value",values:n,input:i,inst:t}),o}}),ac=w("$ZodLiteral",(t,e)=>{if(U.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let n=new Set(e.values);t._zod.values=n,t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Ve(r):r?Ve(r.toString()):String(r)).join("|")})$`),t._zod.parse=(r,o)=>{let s=r.value;return n.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}});var cc=w("$ZodTransform",(t,e)=>{U.init(t,e),t._zod.optin="optional",t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Rt(t.constructor.name);let o=e.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n.fallback=!0,n));if(o instanceof Promise)throw new Te;return n.value=o,n.fallback=!0,n}});function wa(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var Mo=w("$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(`^(${dn(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=>wa(i,o)):wa(s,o)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),uc=w("$ZodExactOptional",(t,e)=>{Mo.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)}),lc=w("$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(`^(${dn(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)}),fc=w("$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=>_a(s,e)):_a(o,e)}});function _a(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var dc=w("$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))}),pc=w("$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=>Ea(s,t)):Ea(o,t)}});function Ea(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 mc=w("$ZodCatch",(t,e)=>{U.init(t,e),t._zod.optin="optional",M(t._zod,"optout",()=>e.innerType._zod.optout),M(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(i=>he(i,r,xe()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(s=>he(s,r,xe()))},input:n.value}),n.issues=[],n.fallback=!0),n)}});var hc=w("$ZodPipe",(t,e)=>{U.init(t,e),M(t._zod,"values",()=>e.in._zod.values),M(t._zod,"optin",()=>e.in._zod.optin),M(t._zod,"optout",()=>e.out._zod.optout),M(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,r)=>{if(r.direction==="backward"){let s=e.out._zod.run(n,r);return s instanceof Promise?s.then(i=>nr(i,e.in,r)):nr(s,e.in,r)}let o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>nr(s,e.out,r)):nr(o,e.out,r)}});function nr(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},n)}var yc=w("$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(xa):xa(o)}});function xa(t){return t.value=Object.freeze(t.value),t}var gc=w("$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)}),bc=w("$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=>Sa(s,n,r,t));Sa(o,n,r,t)}});function Sa(t,e,n,r){if(!t){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),e.issues.push(Ct(o))}}var wc,Qy=Symbol("ZodOutput"),Vy=Symbol("ZodInput"),Fo=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 ap(){return new Fo}(wc=globalThis).__zod_globalRegistry??(wc.__zod_globalRegistry=ap());var _t=globalThis.__zod_globalRegistry;function _c(t,e){return new t({type:"string",...I(e)})}function Ec(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...I(e)})}function Zo(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...I(e)})}function xc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...I(e)})}function Sc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(e)})}function Ac(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(e)})}function vc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(e)})}function Dc(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...I(e)})}function Rc(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...I(e)})}function kc(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(e)})}function Ic(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...I(e)})}function Oc(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(e)})}function Cc(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...I(e)})}function Tc(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...I(e)})}function Nc(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(e)})}function $c(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(e)})}function zc(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(e)})}function Pc(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(e)})}function Lc(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(e)})}function Mc(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...I(e)})}function Fc(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...I(e)})}function Zc(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...I(e)})}function Bc(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...I(e)})}function jc(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(e)})}function Uc(t,e){return new t({type:"string",format:"date",check:"string_format",...I(e)})}function Qc(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...I(e)})}function Vc(t,e){return new t({type:"string",format:"duration",check:"string_format",...I(e)})}function Gc(t,e){return new t({type:"number",checks:[],...I(e)})}function qc(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...I(e)})}function Jc(t,e){return new t({type:"boolean",...I(e)})}function Kc(t,e){return new t({type:"null",...I(e)})}function Wc(t){return new t({type:"unknown"})}function Yc(t,e){return new t({type:"never",...I(e)})}function sr(t,e){return new No({check:"less_than",...I(e),value:t,inclusive:!1})}function gn(t,e){return new No({check:"less_than",...I(e),value:t,inclusive:!0})}function ir(t,e){return new $o({check:"greater_than",...I(e),value:t,inclusive:!1})}function bn(t,e){return new $o({check:"greater_than",...I(e),value:t,inclusive:!0})}function ar(t,e){return new na({check:"multiple_of",...I(e),value:t})}function cr(t,e){return new oa({check:"max_length",...I(e),maximum:t})}function Tt(t,e){return new sa({check:"min_length",...I(e),minimum:t})}function ur(t,e){return new ia({check:"length_equals",...I(e),length:t})}function Bo(t,e){return new aa({check:"string_format",format:"regex",...I(e),pattern:t})}function jo(t){return new ca({check:"string_format",format:"lowercase",...I(t)})}function Uo(t){return new ua({check:"string_format",format:"uppercase",...I(t)})}function Qo(t,e){return new la({check:"string_format",format:"includes",...I(e),includes:t})}function Vo(t,e){return new fa({check:"string_format",format:"starts_with",...I(e),prefix:t})}function Go(t,e){return new da({check:"string_format",format:"ends_with",...I(e),suffix:t})}function tt(t){return new pa({check:"overwrite",tx:t})}function qo(t){return tt(e=>e.normalize(t))}function Jo(){return tt(t=>t.trim())}function Ko(){return tt(t=>t.toLowerCase())}function Wo(){return tt(t=>t.toUpperCase())}function Yo(){return tt(t=>So(t))}function Xc(t,e,n){return new t({type:"array",element:e,...I(n)})}function Hc(t,e,n){return new t({type:"custom",check:"custom",fn:e,...I(n)})}function eu(t,e){let n=cp(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(Ct(o,r.value,n._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),r.issues.push(Ct(s))}},t(r.value,r)),e);return n}function cp(t,e){let n=new te({check:"custom",...I(e)});return n._zod.check=t,n}function Xo(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??_t,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function J(t,e,n={path:[],schemaPath:[]}){var r;let o=t._zod.def,s=e.seen.get(t);if(s)return s.count++,n.schemaPath.includes(t)&&(s.cycle=n.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:n.path};e.seen.set(t,i);let a=t._zod.toJSONSchema?.();if(a)i.schema=a;else{let d={...n,schemaPath:[...n.schemaPath,t],path:n.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,i.schema,d);else{let f=i.schema,p=e.processors[o.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);p(t,e,f,d)}let l=t._zod.parent;l&&(i.ref||(i.ref=l),J(l,e,d),e.seen.get(l).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),e.io==="input"&&oe(t)&&(delete i.schema.examples,delete i.schema.default),e.io==="input"&&"_prefault"in i.schema&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,e.seen.get(t).schema}function Ho(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=new Map;for(let i of t.seen.entries()){let a=t.metadataRegistry.get(i[0])?.id;if(a){let c=r.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,i[0])}}let o=i=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let l=t.external.registry.get(i[0])?.id,f=t.external.uri??(g=>g);if(l)return{ref:f(l)};let p=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=p,{defId:p,ref:`${f("__shared")}#/${a}/${p}`}}if(i[1]===n)return{ref:"#"};let u=`#/${a}/`,d=i[1].schema.id??`__schema${t.counter++}`;return{defId:d,ref:u+d}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=o(i);a.def={...a.schema},u&&(a.defId=u);let d=a.schema;for(let l in d)delete d[l];d.$ref=c};if(t.cycles==="throw")for(let i of t.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>+ `)}d.write("payload.value = newResult;"),d.write("return payload;");let A=d.compile();return(S,E)=>A(p,S,E)},s,i=Ut,a=!tn.jitless,u=a&&xs.value,f=t.catchall,l;e._zod.parse=(p,d)=>{l??(l=r.value);let w=p.value;return i(w)?a&&u&&d?.async===!1&&d.jitless!==!0?(s||(s=o(t.shape)),p=s(p,d),f?gu([],w,p,d,l,e):p):n(p,d):(p.issues.push({expected:"object",code:"invalid_type",input:w,inst:e}),p)}});function Oc(e,t,n,r){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let o=e.filter(s=>!_t(s));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(s=>s.issues.map(i=>Oe(i,r,qe())))}),t)}var Ns=k("$ZodUnion",(e,t)=>{Y.init(e,t),G(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),G(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),G(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),G(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){let r=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>Bn(o.source)).join("|")})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,o)=>{if(n)return n(r,o);let s=!1,i=[];for(let a of t.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=>Oc(a,r,e,o)):Oc(i,r,e,o)}});var bu=k("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Ns.init(e,t);let n=e._zod.parse;G(e._zod,"propValues",()=>{let o={};for(let s of t.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let[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=rn(()=>{let o=t.options,s=new Map;for(let i of o){let a=i._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.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});e._zod.parse=(o,s)=>{let i=o.value;if(!Ut(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;let a=r.value.get(i?.[t.discriminator]);return a?a._zod.run(o,s):t.unionFallback||s.direction==="backward"?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(r.value.keys()),input:i,path:[t.discriminator],inst:e}),o)}}),wu=k("$ZodIntersection",(e,t)=>{Y.init(e,t),e._zod.parse=(n,r)=>{let o=n.value,s=t.left._zod.run({value:o,issues:[]},r),i=t.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Nc(n,c,u)):Nc(n,s,i)}});function Ts(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(xt(e)&&xt(t)){let n=Object.keys(t),r=Object.keys(e).filter(s=>n.indexOf(s)!==-1),o={...e,...t};for(let s of r){let i=Ts(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let o=e[r],s=t[r],i=Ts(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 Nc(e,t,n){let r=new Map,o;for(let a of t.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 e.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 e.issues.push(a);let s=[...r].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&o&&e.issues.push({...o,keys:s}),_t(e))return e;let i=Ts(t.value,n.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}var xu=k("$ZodRecord",(e,t)=>{Y.init(e,t),e._zod.parse=(n,r)=>{let o=n.value;if(!xt(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;let s=[],i=t.keyType._zod.values;if(i){n.value={};let 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 f=t.keyType._zod.run({value:u,issues:[]},r);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(f.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map(d=>Oe(d,r,qe())),input:u,path:[u],inst:e});continue}let l=f.value,p=t.valueType._zod.run({value:o[u],issues:[]},r);p instanceof Promise?s.push(p.then(d=>{d.issues.length&&n.issues.push(...dt(u,d.issues)),n.value[l]=d.value})):(p.issues.length&&n.issues.push(...dt(u,p.issues)),n.value[l]=p.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:e,keys:c})}else{n.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=t.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"&&Ds.test(a)&&c.issues.length){let l=t.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){t.mode==="loose"?n.value[a]=o[a]:n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(l=>Oe(l,r,qe())),input:a,path:[a],inst:e});continue}let f=t.valueType._zod.run({value:o[a],issues:[]},r);f instanceof Promise?s.push(f.then(l=>{l.issues.length&&n.issues.push(...dt(a,l.issues)),n.value[c.value]=l.value})):(f.issues.length&&n.issues.push(...dt(a,f.issues)),n.value[c.value]=f.value)}}return s.length?Promise.all(s).then(()=>n):n}});var _u=k("$ZodEnum",(e,t)=>{Y.init(e,t);let n=Fn(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(o=>_s.has(typeof o)).map(o=>typeof o=="string"?ft(o):o.toString()).join("|")})$`),e._zod.parse=(o,s)=>{let i=o.value;return r.has(i)||o.issues.push({code:"invalid_value",values:n,input:i,inst:e}),o}}),Su=k("$ZodLiteral",(e,t)=>{if(Y.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");let n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?ft(r):r?ft(r.toString()):String(r)).join("|")})$`),e._zod.parse=(r,o)=>{let s=r.value;return n.has(s)||r.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),r}});var Eu=k("$ZodTransform",(e,t)=>{Y.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new en(e.constructor.name);let o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n.fallback=!0,n));if(o instanceof Promise)throw new He;return n.value=o,n.fallback=!0,n}});function zc(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var zs=k("$ZodOptional",(e,t)=>{Y.init(e,t),e._zod.optin="optional",e._zod.optout="optional",G(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),G(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bn(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){let o=n.value,s=t.innerType._zod.run(n,r);return s instanceof Promise?s.then(i=>zc(i,o)):zc(s,o)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),Au=k("$ZodExactOptional",(e,t)=>{zs.init(e,t),G(e._zod,"values",()=>t.innerType._zod.values),G(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),ku=k("$ZodNullable",(e,t)=>{Y.init(e,t),G(e._zod,"optin",()=>t.innerType._zod.optin),G(e._zod,"optout",()=>t.innerType._zod.optout),G(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bn(n.source)}|null)$`):void 0}),G(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),vu=k("$ZodDefault",(e,t)=>{Y.init(e,t),e._zod.optin="optional",G(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>$c(s,t)):$c(o,t)}});function $c(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Ru=k("$ZodPrefault",(e,t)=>{Y.init(e,t),e._zod.optin="optional",G(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),Du=k("$ZodNonOptional",(e,t)=>{Y.init(e,t),G(e._zod,"values",()=>{let n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Lc(s,e)):Lc(o,e)}});function Lc(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var Iu=k("$ZodCatch",(e,t)=>{Y.init(e,t),e._zod.optin="optional",G(e._zod,"optout",()=>t.innerType._zod.optout),G(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(i=>Oe(i,r,qe()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(s=>Oe(s,r,qe()))},input:n.value}),n.issues=[],n.fallback=!0),n)}});var Cu=k("$ZodPipe",(e,t)=>{Y.init(e,t),G(e._zod,"values",()=>t.in._zod.values),G(e._zod,"optin",()=>t.in._zod.optin),G(e._zod,"optout",()=>t.out._zod.optout),G(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){let s=t.out._zod.run(n,r);return s instanceof Promise?s.then(i=>Br(i,t.in,r)):Br(s,t.in,r)}let o=t.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Br(s,t.out,r)):Br(o,t.out,r)}});function Br(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var Tu=k("$ZodReadonly",(e,t)=>{Y.init(e,t),G(e._zod,"propValues",()=>t.innerType._zod.propValues),G(e._zod,"values",()=>t.innerType._zod.values),G(e._zod,"optin",()=>t.innerType?._zod?.optin),G(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(Pc):Pc(o)}});function Pc(e){return e.value=Object.freeze(e.value),e}var Ou=k("$ZodLazy",(e,t)=>{Y.init(e,t),G(e._zod,"innerType",()=>{let n=t;return n._cachedInner||(n._cachedInner=t.getter()),n._cachedInner}),G(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),G(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),G(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),G(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),Nu=k("$ZodCustom",(e,t)=>{de.init(e,t),Y.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{let r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(s=>Fc(s,n,r,e));Fc(o,n,r,e)}});function Fc(e,t,n,r){if(!e){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(on(o))}}var zu,rx=Symbol("ZodOutput"),ox=Symbol("ZodInput"),$s=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){let r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){let n=t._zod.parent;if(n){let r={...this.get(n)??{}};delete r.id;let o={...r,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};function Gm(){return new $s}(zu=globalThis).__zod_globalRegistry??(zu.__zod_globalRegistry=Gm());var jt=globalThis.__zod_globalRegistry;function $u(e,t){return new e({type:"string",...$(t)})}function Lu(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...$(t)})}function Ls(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...$(t)})}function Pu(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...$(t)})}function Fu(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...$(t)})}function Mu(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...$(t)})}function Bu(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...$(t)})}function qu(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...$(t)})}function Zu(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...$(t)})}function Uu(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...$(t)})}function ju(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...$(t)})}function Vu(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...$(t)})}function Qu(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...$(t)})}function Gu(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...$(t)})}function Ju(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...$(t)})}function Wu(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...$(t)})}function Ku(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...$(t)})}function Hu(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...$(t)})}function Yu(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...$(t)})}function Xu(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...$(t)})}function el(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...$(t)})}function tl(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...$(t)})}function nl(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...$(t)})}function rl(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...$(t)})}function ol(e,t){return new e({type:"string",format:"date",check:"string_format",...$(t)})}function sl(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...$(t)})}function il(e,t){return new e({type:"string",format:"duration",check:"string_format",...$(t)})}function al(e,t){return new e({type:"number",checks:[],...$(t)})}function cl(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...$(t)})}function ul(e,t){return new e({type:"boolean",...$(t)})}function ll(e,t){return new e({type:"null",...$(t)})}function fl(e){return new e({type:"unknown"})}function dl(e,t){return new e({type:"never",...$(t)})}function Ur(e,t){return new Is({check:"less_than",...$(t),value:e,inclusive:!1})}function Vn(e,t){return new Is({check:"less_than",...$(t),value:e,inclusive:!0})}function jr(e,t){return new Cs({check:"greater_than",...$(t),value:e,inclusive:!1})}function Qn(e,t){return new Cs({check:"greater_than",...$(t),value:e,inclusive:!0})}function Vr(e,t){return new yc({check:"multiple_of",...$(t),value:e})}function Qr(e,t){return new wc({check:"max_length",...$(t),maximum:e})}function sn(e,t){return new xc({check:"min_length",...$(t),minimum:e})}function Gr(e,t){return new _c({check:"length_equals",...$(t),length:e})}function Ps(e,t){return new Sc({check:"string_format",format:"regex",...$(t),pattern:e})}function Fs(e){return new Ec({check:"string_format",format:"lowercase",...$(e)})}function Ms(e){return new Ac({check:"string_format",format:"uppercase",...$(e)})}function Bs(e,t){return new kc({check:"string_format",format:"includes",...$(t),includes:e})}function qs(e,t){return new vc({check:"string_format",format:"starts_with",...$(t),prefix:e})}function Zs(e,t){return new Rc({check:"string_format",format:"ends_with",...$(t),suffix:e})}function St(e){return new Dc({check:"overwrite",tx:e})}function Us(e){return St(t=>t.normalize(e))}function js(){return St(e=>e.trim())}function Vs(){return St(e=>e.toLowerCase())}function Qs(){return St(e=>e.toUpperCase())}function Gs(){return St(e=>ws(e))}function pl(e,t,n){return new e({type:"array",element:t,...$(n)})}function ml(e,t,n){return new e({type:"custom",check:"custom",fn:t,...$(n)})}function hl(e,t){let n=Jm(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(on(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(on(s))}},e(r.value,r)),t);return n}function Jm(e,t){let n=new de({check:"custom",...$(t)});return n._zod.check=e,n}function Js(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??jt,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function re(e,t,n={path:[],schemaPath:[]}){var r;let o=e._zod.def,s=t.seen.get(e);if(s)return s.count++,n.schemaPath.includes(e)&&(s.cycle=n.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,i);let a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{let f={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,f);else{let p=i.schema,d=t.processors[o.type];if(!d)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);d(e,t,p,f)}let l=e._zod.parent;l&&(i.ref||(i.ref=l),re(l,t,f),t.seen.get(l).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(i.schema,c),t.io==="input"&&be(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&"_prefault"in i.schema&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function Ws(e,t){let n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=new Map;for(let i of e.seen.entries()){let a=e.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=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let l=e.external.registry.get(i[0])?.id,p=e.external.uri??(w=>w);if(l)return{ref:p(l)};let d=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=d,{defId:d,ref:`${p("__shared")}#/${a}/${d}`}}if(i[1]===n)return{ref:"#"};let u=`#/${a}/`,f=i[1].schema.id??`__schema${e.counter++}`;return{defId:f,ref:u+f}},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 f=a.schema;for(let l in f)delete f[l];f.$ref=c};if(e.cycles==="throw")for(let i of e.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 es(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,d={...u},l=c.ref;if(c.ref=null,l){r(l);let p=t.seen.get(l),g=p.schema;if(g.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(g)):Object.assign(u,g),Object.assign(u,d),a._zod.parent===l)for(let h in u)h==="$ref"||h==="allOf"||h in d||delete u[h];if(g.$ref&&p.def)for(let h in u)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(u[h])===JSON.stringify(p.def[h])&&delete u[h]}let f=a._zod.parent;if(f&&f!==l){r(f);let p=t.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let g in u)g==="$ref"||g==="allOf"||g in p.def&&JSON.stringify(u[g])===JSON.stringify(p.def[g])&&delete u[g]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())r(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,n.def??n.schema);let s=t.metadataRegistry.get(e)?.id;s!==void 0&&o.id===s&&delete o.id;let i=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:wn(e,"input",t.processors),output:wn(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 tu=(t,e={})=>n=>{let r=Xo({...n,processors:e});return J(t,r),Ho(r,t),es(r,t)},wn=(t,e,n={})=>r=>{let{libraryOptions:o,target:s}=r??{},i=Xo({...o??{},target:s,io:e,processors:n});return J(t,i),Ho(i,t),es(i,t)};var up={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},nu=(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=up[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}))])}},ru=(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)},ou=(t,e,n,r)=>{n.type="boolean"};var su=(t,e,n,r)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"};var iu=(t,e,n,r)=>{n.not={}};var au=(t,e,n,r)=>{};var cu=(t,e,n,r)=>{let o=t._zod.def,s=ln(o.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},uu=(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 lu=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var fu=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var du=(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"]})},pu=(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)},mu=(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},hu=(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 yu=(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)}},gu=(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"}]},bu=(t,e,n,r)=>{let o=t._zod.def;J(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType},wu=(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))},_u=(t,e,n,r)=>{let o=t._zod.def;J(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},Eu=(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},xu=(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},Su=(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 ts=(t,e,n,r)=>{let o=t._zod.def;J(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType},Au=(t,e,n,r)=>{let o=t._zod.innerType;J(o,e,r);let s=e.seen.get(t);s.ref=o};var yp=w("ZodISODateTime",(t,e)=>{za.init(t,e),q.init(t,e)});function vu(t){return jc(yp,t)}var gp=w("ZodISODate",(t,e)=>{Pa.init(t,e),q.init(t,e)});function Du(t){return Uc(gp,t)}var bp=w("ZodISOTime",(t,e)=>{La.init(t,e),q.init(t,e)});function Ru(t){return Qc(bp,t)}var wp=w("ZodISODuration",(t,e)=>{Ma.init(t,e),q.init(t,e)});function ku(t){return Vc(wp,t)}var Iu=(t,e)=>{Yn.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>yi(t,n)},flatten:{value:n=>hi(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,It,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,It,2)}},isEmpty:{get(){return t.issues.length===0}}})},Ou=w("ZodError",Iu),ue=w("ZodError",Iu,{Parent:Error});var Cu=Xn(ue),Tu=Hn(ue),Nu=mn(ue),$u=hn(ue),zu=wi(ue),Pu=_i(ue),Lu=Ei(ue),Mu=xi(ue),Fu=Si(ue),Zu=Ai(ue),Bu=vi(ue),ju=Di(ue);var Uu=new WeakMap;function _n(t,e,n){let r=Object.getPrototypeOf(t),o=Uu.get(r);if(o||(o=new Set,Uu.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=w("ZodType",(t,e)=>(U.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:wn(t,"input"),output:wn(t,"output")}}),t.toJSONSchema=tu(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,r)=>Cu(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Nu(t,n,r),t.parseAsync=async(n,r)=>Tu(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>$u(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>zu(t,n,r),t.decode=(n,r)=>Pu(t,n,r),t.encodeAsync=async(n,r)=>Lu(t,n,r),t.decodeAsync=async(n,r)=>Mu(t,n,r),t.safeEncode=(n,r)=>Fu(t,n,r),t.safeDecode=(n,r)=>Zu(t,n,r),t.safeEncodeAsync=async(n,r)=>Bu(t,n,r),t.safeDecodeAsync=async(n,r)=>ju(t,n,r),_n(t,"ZodType",{check(...n){let r=this.def;return this.clone(F.mergeDefs(r,{checks:[...r.checks??[],...n.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return Se(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(hm(n,r))},superRefine(n,r){return this.check(ym(n,r))},overwrite(n){return this.check(tt(n))},optional(){return Ju(this)},exactOptional(){return tm(this)},nullable(){return Ku(this)},nullish(){return Ju(Ku(this))},nonoptional(n){return am(this,n)},array(){return j(this)},or(n){return Nt([this,n])},and(n){return Wp(this,n)},transform(n){return Wu(this,Hp(n))},default(n){return om(this,n)},prefault(n){return im(this,n)},catch(n){return um(this,n)},pipe(n){return Wu(this,n)},readonly(){return dm(this)},describe(n){let r=this.clone();return _t.add(r,{description:n}),r},meta(...n){if(n.length===0)return _t.get(this);let r=this.clone();return _t.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(t,"description",{get(){return _t.get(t)?.description},configurable:!0}),t)),Yu=w("_ZodString",(t,e)=>{or.init(t,e),V.init(t,e),t._zod.processJSONSchema=(r,o,s)=>nu(t,r,o,s);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,_n(t,"_ZodString",{regex(...r){return this.check(Bo(...r))},includes(...r){return this.check(Qo(...r))},startsWith(...r){return this.check(Vo(...r))},endsWith(...r){return this.check(Go(...r))},min(...r){return this.check(Tt(...r))},max(...r){return this.check(cr(...r))},length(...r){return this.check(ur(...r))},nonempty(...r){return this.check(Tt(1,...r))},lowercase(r){return this.check(jo(r))},uppercase(r){return this.check(Uo(r))},trim(){return this.check(Jo())},normalize(...r){return this.check(qo(...r))},toLowerCase(){return this.check(Ko())},toUpperCase(){return this.check(Wo())},slugify(){return this.check(Yo())}})}),Sp=w("ZodString",(t,e)=>{or.init(t,e),Yu.init(t,e),t.email=n=>t.check(Ec(Ap,n)),t.url=n=>t.check(Dc(vp,n)),t.jwt=n=>t.check(Bc(Zp,n)),t.emoji=n=>t.check(Rc(Dp,n)),t.guid=n=>t.check(Zo(Qu,n)),t.uuid=n=>t.check(xc(fr,n)),t.uuidv4=n=>t.check(Sc(fr,n)),t.uuidv6=n=>t.check(Ac(fr,n)),t.uuidv7=n=>t.check(vc(fr,n)),t.nanoid=n=>t.check(kc(Rp,n)),t.guid=n=>t.check(Zo(Qu,n)),t.cuid=n=>t.check(Ic(kp,n)),t.cuid2=n=>t.check(Oc(Ip,n)),t.ulid=n=>t.check(Cc(Op,n)),t.base64=n=>t.check(Mc(Lp,n)),t.base64url=n=>t.check(Fc(Mp,n)),t.xid=n=>t.check(Tc(Cp,n)),t.ksuid=n=>t.check(Nc(Tp,n)),t.ipv4=n=>t.check($c(Np,n)),t.ipv6=n=>t.check(zc($p,n)),t.cidrv4=n=>t.check(Pc(zp,n)),t.cidrv6=n=>t.check(Lc(Pp,n)),t.e164=n=>t.check(Zc(Fp,n)),t.datetime=n=>t.check(vu(n)),t.date=n=>t.check(Du(n)),t.time=n=>t.check(Ru(n)),t.duration=n=>t.check(ku(n))});function v(t){return _c(Sp,t)}var q=w("ZodStringFormat",(t,e)=>{Q.init(t,e),Yu.init(t,e)}),Ap=w("ZodEmail",(t,e)=>{Da.init(t,e),q.init(t,e)});var Qu=w("ZodGUID",(t,e)=>{Aa.init(t,e),q.init(t,e)});var fr=w("ZodUUID",(t,e)=>{va.init(t,e),q.init(t,e)});var vp=w("ZodURL",(t,e)=>{Ra.init(t,e),q.init(t,e)});var Dp=w("ZodEmoji",(t,e)=>{ka.init(t,e),q.init(t,e)});var Rp=w("ZodNanoID",(t,e)=>{Ia.init(t,e),q.init(t,e)});var kp=w("ZodCUID",(t,e)=>{Oa.init(t,e),q.init(t,e)});var Ip=w("ZodCUID2",(t,e)=>{Ca.init(t,e),q.init(t,e)});var Op=w("ZodULID",(t,e)=>{Ta.init(t,e),q.init(t,e)});var Cp=w("ZodXID",(t,e)=>{Na.init(t,e),q.init(t,e)});var Tp=w("ZodKSUID",(t,e)=>{$a.init(t,e),q.init(t,e)});var Np=w("ZodIPv4",(t,e)=>{Fa.init(t,e),q.init(t,e)});var $p=w("ZodIPv6",(t,e)=>{Za.init(t,e),q.init(t,e)});var zp=w("ZodCIDRv4",(t,e)=>{Ba.init(t,e),q.init(t,e)});var Pp=w("ZodCIDRv6",(t,e)=>{ja.init(t,e),q.init(t,e)});var Lp=w("ZodBase64",(t,e)=>{Qa.init(t,e),q.init(t,e)});var Mp=w("ZodBase64URL",(t,e)=>{Va.init(t,e),q.init(t,e)});var Fp=w("ZodE164",(t,e)=>{Ga.init(t,e),q.init(t,e)});var Zp=w("ZodJWT",(t,e)=>{qa.init(t,e),q.init(t,e)});var Xu=w("ZodNumber",(t,e)=>{Po.init(t,e),V.init(t,e),t._zod.processJSONSchema=(r,o,s)=>ru(t,r,o,s),_n(t,"ZodNumber",{gt(r,o){return this.check(ir(r,o))},gte(r,o){return this.check(bn(r,o))},min(r,o){return this.check(bn(r,o))},lt(r,o){return this.check(sr(r,o))},lte(r,o){return this.check(gn(r,o))},max(r,o){return this.check(gn(r,o))},int(r){return this.check(Vu(r))},safe(r){return this.check(Vu(r))},positive(r){return this.check(ir(0,r))},nonnegative(r){return this.check(bn(0,r))},negative(r){return this.check(sr(0,r))},nonpositive(r){return this.check(gn(0,r))},multipleOf(r,o){return this.check(ar(r,o))},step(r,o){return this.check(ar(r,o))},finite(){return this}});let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function N(t){return Gc(Xu,t)}var Bp=w("ZodNumberFormat",(t,e)=>{Ja.init(t,e),Xu.init(t,e)});function Vu(t){return qc(Bp,t)}var jp=w("ZodBoolean",(t,e)=>{Ka.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ou(t,n,r,o)});function qe(t){return Jc(jp,t)}var Up=w("ZodNull",(t,e)=>{Wa.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>su(t,n,r,o)});function Qp(t){return Kc(Up,t)}var Vp=w("ZodUnknown",(t,e)=>{Ya.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>au(t,n,r,o)});function Gu(){return Wc(Vp)}var Gp=w("ZodNever",(t,e)=>{Xa.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>iu(t,n,r,o)});function Hu(t){return Yc(Gp,t)}var qp=w("ZodArray",(t,e)=>{Ha.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>du(t,n,r,o),t.element=e.element,_n(t,"ZodArray",{min(n,r){return this.check(Tt(n,r))},nonempty(n){return this.check(Tt(1,n))},max(n,r){return this.check(cr(n,r))},length(n,r){return this.check(ur(n,r))},unwrap(){return this.element}})});function j(t,e){return Xc(qp,t,e)}var el=w("ZodObject",(t,e)=>{nc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>pu(t,n,r,o),F.defineLazy(t,"shape",()=>e.shape),_n(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:Gu()})},loose(){return this.clone({...this._zod.def,catchall:Gu()})},strict(){return this.clone({...this._zod.def,catchall:Hu()})},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(nl,this,n[0])},required(...n){return F.required(rl,this,n[0])}})});function nt(t,e){let n={type:"object",shape:t??{},...F.normalizeParams(e)};return new el(n)}function O(t,e){return new el({type:"object",shape:t,catchall:Hu(),...F.normalizeParams(e)})}var tl=w("ZodUnion",(t,e)=>{Lo.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>mu(t,n,r,o),t.options=e.options});function Nt(t,e){return new tl({type:"union",options:t,...F.normalizeParams(e)})}var Jp=w("ZodDiscriminatedUnion",(t,e)=>{tl.init(t,e),rc.init(t,e)});function $t(t,e,n){return new Jp({type:"union",options:e,discriminator:t,...F.normalizeParams(n)})}var Kp=w("ZodIntersection",(t,e)=>{oc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>hu(t,n,r,o)});function Wp(t,e){return new Kp({type:"intersection",left:t,right:e})}var qu=w("ZodRecord",(t,e)=>{sc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>yu(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType});function Ae(t,e,n){return!e||!e._zod?new qu({type:"record",keyType:v(),valueType:t,...F.normalizeParams(e)}):new qu({type:"record",keyType:t,valueType:e,...F.normalizeParams(n)})}var ns=w("ZodEnum",(t,e)=>{ic.init(t,e),V.init(t,e),t._zod.processJSONSchema=(r,o,s)=>cu(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 ns({...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 ns({...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 ns({type:"enum",entries:n,...F.normalizeParams(e)})}var Yp=w("ZodLiteral",(t,e)=>{ac.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>uu(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 Yp({type:"literal",values:Array.isArray(t)?t:[t],...F.normalizeParams(e)})}var Xp=w("ZodTransform",(t,e)=>{cc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>fu(t,n,r,o),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Rt(t.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(F.issue(s,n.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),n.issues.push(F.issue(i))}};let o=e.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});function Hp(t){return new Xp({type:"transform",transform:t})}var nl=w("ZodOptional",(t,e)=>{Mo.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ts(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Ju(t){return new nl({type:"optional",innerType:t})}var em=w("ZodExactOptional",(t,e)=>{uc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ts(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function tm(t){return new em({type:"optional",innerType:t})}var nm=w("ZodNullable",(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.innerType});function Ku(t){return new nm({type:"nullable",innerType:t})}var rm=w("ZodDefault",(t,e)=>{fc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>wu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function om(t,e){return new rm({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():F.shallowClone(e)}})}var sm=w("ZodPrefault",(t,e)=>{dc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>_u(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function im(t,e){return new sm({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():F.shallowClone(e)}})}var rl=w("ZodNonOptional",(t,e)=>{pc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>bu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function am(t,e){return new rl({type:"nonoptional",innerType:t,...F.normalizeParams(e)})}var cm=w("ZodCatch",(t,e)=>{mc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Eu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function um(t,e){return new cm({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var lm=w("ZodPipe",(t,e)=>{hc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>xu(t,n,r,o),t.in=e.in,t.out=e.out});function Wu(t,e){return new lm({type:"pipe",in:t,out:e})}var fm=w("ZodReadonly",(t,e)=>{yc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Su(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function dm(t){return new fm({type:"readonly",innerType:t})}var pm=w("ZodLazy",(t,e)=>{gc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Au(t,n,r,o),t.unwrap=()=>t._zod.def.getter()});function rs(t){return new pm({type:"lazy",getter:t})}var mm=w("ZodCustom",(t,e)=>{bc.init(t,e),V.init(t,e),t._zod.processJSONSchema=(n,r,o)=>lu(t,n,r,o)});function hm(t,e={}){return Hc(mm,t,e)}function ym(t,e){return eu(t,e)}function rt(t){let e=rs(()=>Nt([v(t),N(),qe(),Qp(),j(e),Ae(v(),e)]));return e}var ol=t=>"field"in t?[t]:("all"in t?t.all:t.any).flatMap(ol),dr=t=>ol(t);var zt=(t,e)=>{if("field"in t)return e(t);let n="all"in t?t.all:t.any,r=!1;if("all"in t){for(let o of n){let s=zt(o,e);if(s===!1)return!1;r||=s===void 0}return r?void 0:!0}for(let o of n){let s=zt(o,e);if(s===!0)return!0;r||=s===void 0}return r?void 0:!1},sl=t=>JSON.stringify(t),os=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=os(o);n+=s.conditions,r=Math.max(r,s.depth+1)}return{conditions:n,depth:r}},il=(t,e={})=>{let n=o=>{let s=j(o),i=e.maximumChildren===void 0?s:s.max(e.maximumChildren);return Nt([t,O({all:i}),O({any:i})])},r=rs(()=>n(r));return e.maximumConditions===void 0&&e.maximumDepth===void 0?r:r.superRefine((o,s)=>{let{conditions:i,depth:a}=os(o);e.maximumConditions!==void 0&&i>e.maximumConditions&&s.addIssue({code:"custom",message:e.maximumConditionsMessage??"Query exceeds the condition limit"}),e.maximumDepth!==void 0&&a>e.maximumDepth&&s.addIssue({code:"custom",message:e.maximumDepthMessage??"Query exceeds the nesting limit"})})};var k={requestBytes:524288,filterCount:32,filterDepth:8,sortCount:8,outputFieldCount:256,fieldPathDepth:9,defaultResultCount:20,resultCount:1e3,resultBytes:16777216,candidateDocuments:1e3,databaseBytes:512e3,frontmatterBytes:65536,frontmatterDepth:8,frontmatterFields:256,frontmatterStringBytes:16384,jsonBytes:1048576,jsonDepth:8,jsonFields:256,jsonStringBytes:16384,indexedPropertiesBytes:65536,excerptBytes:2048,mdxDepth:100,mdxNodes:2e4,mdxProps:4e3,hydratedFileBytes:1048576,hydratedTotalBytes:2097152,hydratedFileCount:20,hydratedRangeBytes:262144,concurrentContentReads:8};function Et(t,e=new Set){if(typeof t=="number"&&isNaN(t))throw new Error("NaN is not allowed");if(typeof t=="number"&&!isFinite(t))throw new Error("Infinity is not allowed");if(t===null||typeof t!="object")return JSON.stringify(t);if(typeof t.toJSON=="function"){if(e.has(t))throw new Error("Circular reference detected");e.add(t);let r=Et(t.toJSON(),e);return e.delete(t),r}if(e.has(t))throw new Error("Circular reference detected");e.add(t);let n;if(Array.isArray(t))n=`[${t.map(o=>Et(o===void 0||typeof o=="symbol"?null:o,e)).join(",")}]`;else{let r=[];for(let o of Object.keys(t).sort())t[o]===void 0||typeof t[o]=="symbol"||r.push(`${Et(o)}:${Et(t[o],e)}`);n=`{${r.join(",")}}`}return e.delete(t),n}var gm=new TextEncoder,ot=t=>gm.encode(t),Ne=t=>ot(t).byteLength,se=class extends Error{constructor(){super("Byte stream exceeds the configured limit"),this.name="ByteLimitExceededError"}},bm=(t,e)=>{let n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.byteLength;return n},En=t=>typeof t=="string"?{async*[Symbol.asyncIterator](){yield ot(t)}}:t instanceof Uint8Array?{async*[Symbol.asyncIterator](){yield t}}:t,pr=(t,e)=>e===void 0?En(t):{async*[Symbol.asyncIterator](){let n=0,r=0;for await(let o of En(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}}},mr=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()}}}),ss=async(t,e)=>{let n=[],r=0;for await(let o of En(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 bm(n,r)},$e=async(t,e)=>{let n=await ss(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 al=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")}},is=(t,e)=>{if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return al(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(is(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))al(o),s!==void 0&&Object.defineProperty(r,o,{value:is(s,e),enumerable:!0,configurable:!0,writable:!0})}finally{e.delete(t)}return r}throw new Error("Value cannot be represented as JSON")},st=t=>is(t,new Set),fe=t=>{let e=Et(st(t));if(e===void 0)throw new Error("Value cannot be represented as canonical JSON");return e},xn=(t,e)=>t===void 0||e===void 0?t===e:fe(t)===fe(e),ze=(t,e)=>t<e?-1:t>e?1:0,as=async t=>{let e=typeof t=="string"?ot(t):t,n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")},cl=async t=>`sha256:${await as(t)}`;var ul=$t("type",[O({type:Z("document")}),O({type:Z("json"),path:j(v()).min(1)}),O({type:Z("markdown-body")}),O({type:Z("markdown-frontmatter")})]),cs=O({documentId:v().min(1),revision:v().min(1),representation:ul}),wm=t=>{let e=ul.parse(t);return e.type==="json"?Object.freeze({...e,path:Object.freeze([...e.path])}):Object.freeze(e)},ll=t=>{let e=cs.parse(t);return Object.freeze({...e,representation:wm(e.representation)})};var Sn=["json","markdown","mdx"],fl=t=>typeof t=="string"&&Sn.includes(t),dl=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 hr=O({id:v().min(1),revision:v().min(1),contentRef:v().min(1),format:ee(Sn).optional()}),yr=O({sourceId:v().min(1),referenceId:v().min(1),reference:cs});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 Pe=class extends Error{code;documentIds;constructor({code:e,message:n,documentIds:r=[]}){super(n),this.name="DocumentGraphError",this.code=e,this.documentIds=Object.freeze([...r])}},_m=(t,e)=>ze(t.sourceId,e.sourceId)||ze(t.referenceId,e.referenceId),An=({nodes:t,edges:e})=>{let n=t.map(a=>Object.freeze(hr.parse(a))).sort((a,c)=>ze(a.id,c.id)),r=new Map,o=new Map;for(let a of n){if(r.has(a.id))throw new Pe({code:"DUPLICATE_NODE",message:`Document graph contains duplicate node ${a.id}`,documentIds:[a.id]});r.set(a.id,a);let c=o.get(a.contentRef);if(c!==void 0&&(c.revision!==a.revision||c.format!==a.format))throw new Pe({code:"CONTENT_IDENTITY_CONFLICT",message:`Document graph content reference ${a.contentRef} has conflicting identities`,documentIds:[c.id,a.id]});o.set(a.contentRef,a)}let s=e.map(a=>{let c=yr.parse(a);return Object.freeze({...c,reference:ll(c.reference)})}).sort(_m),i=new Set;for(let a of s){if(r.get(a.sourceId)===void 0)throw new Pe({code:"SOURCE_NOT_FOUND",message:`Document graph source ${a.sourceId} does not exist`,documentIds:[a.sourceId]});let u=r.get(a.reference.documentId);if(u===void 0)throw new Pe({code:"TARGET_NOT_FOUND",message:`Document graph target ${a.reference.documentId} does not exist`,documentIds:[a.sourceId,a.reference.documentId]});if(u.revision!==a.reference.revision)throw new Pe({code:"TARGET_REVISION_MISMATCH",message:`Document graph target ${u.id} revision does not match its reference`,documentIds:[a.sourceId,u.id]});let d=`${a.sourceId}\0${a.referenceId}`;if(i.has(d))throw new Pe({code:"DUPLICATE_REFERENCE",message:`Document ${a.sourceId} contains duplicate reference ID ${a.referenceId}`,documentIds:[a.sourceId]});i.add(d)}return Object.freeze({nodes:Object.freeze(n),edges:Object.freeze(s)})},Em=t=>new Map(t.nodes.map(e=>[e.id,e]));var gr=({graph:t,rootIds:e})=>{let n=Em(t),r=Lt(t.edges),o=new Map,s=[],i=[],a=c=>{let u=n.get(c);if(u===void 0)throw new Pe({code:"ROOT_NOT_FOUND",message:`Document graph root ${c} does not exist`,documentIds:[c]});let d=o.get(c);if(d!=="visited"){if(d==="visiting"){let l=s.indexOf(c),f=[...s.slice(l),c];throw new Pe({code:"CYCLE",message:`Document graph contains a cycle: ${f.join(" -> ")}`,documentIds:f})}o.set(c,"visiting"),s.push(c);for(let l of r.get(c)??[])a(l.reference.documentId);s.pop(),o.set(c,"visited"),i.push(u)}};for(let c of[...new Set(e)].sort(ze))a(c);return Object.freeze(i)};var xm=v().regex(/^sha256:[a-f0-9]{64}$/),pl=O({format:Z("webstudio-document-graph"),version:Z(1),nodes:j(hr),edges:j(yr),integrity:O({algorithm:Z("sha256"),checksum:xm})});var Sm=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"}),gl=O({_id:v().min(1),_type:Z("asset.file"),name:v().min(1),description:v().optional(),path:Sm,key:v(),folderId:v().min(1).optional(),extension:v().regex(/^[a-z0-9]*$/),mimeType:v().min(1),size:N().int().nonnegative(),createdAt:v().datetime().optional(),revision:v().min(1),contentRef:v().min(1),properties:Ae(v(),rt()),excerpt:v().optional(),metadataError:O({code:v().min(1),message:v().min(1),reason:v().min(1).optional(),line:N().int().positive().optional(),column:N().int().positive().optional()}).optional()}),ls=gl.partial().required({_id:!0}),Am=ee(["null","boolean","number","string","object","array"]),vm=nt({format:Z("webstudio-builder-asset-field-catalog"),version:Z(1),canonicalRevision:v().regex(/^sha256:[a-f0-9]{64}$/),documentCount:N().int().nonnegative(),fields:Ae(v().min(1),nt({queryPath:j(v().min(1)).min(1).max(k.fieldPathDepth).optional(),types:j(Am).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"})}}),br=v().regex(/^sha256:[a-f0-9]{64}$/),bl=O({fields:j(j(v().min(1)).min(1).max(k.fieldPathDepth)).min(1).max(k.outputFieldCount+1),rows:j(j(rt())).max(k.resultCount),totalCount:N().int().nonnegative().max(k.candidateDocuments),hasMore:qe()}).superRefine(({fields:t,rows:e},n)=>{for(let[r,o]of e.entries())o.length!==t.length&&n.addIssue({code:"custom",path:["rows",r],message:"Materialized query rows must match the field count"})}),ml=O({format:Z("webstudio-content-database"),version:Z(1),assetRevision:br,documents:j(ls),documentGraph:pl.optional(),contents:Ae(v().min(1),v()).optional(),assetReferences:Ae(v().min(1),j(O({start:N().int().nonnegative(),end:N().int().positive(),assetId:v().min(1),suffix:v().min(1).optional()}).refine(({start:t,end:e})=>e>t,{message:"Markdown asset reference range must not be empty"}))).optional(),assetValueReferences:Ae(v().min(1),j(O({path:j(v().min(1).or(N().int().nonnegative())).min(1),assetId:v().min(1),suffix:v().min(1).optional(),structured:Z(!0).optional()}))).optional(),fieldCatalog:vm,queries:Ae(br,bl).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:br})}).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"})}),Dm=$t("mode",[O({mode:Z("none")}),O({mode:Z("full"),maxBytes:N().int().positive().max(k.hydratedFileBytes).optional()}),O({mode:Z("range"),offset:N().int().nonnegative(),length:N().int().positive().max(k.hydratedRangeBytes)}),O({mode:Z("markdown-body-ref"),maxBytes:N().int().positive().max(k.hydratedFileBytes).optional()})]),fs={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"]},wl=Object.keys(fs),_l=["url","width","height"],wr=t=>_l.includes(t),El=wl.filter(t=>wr(t)===!1&&t!=="excerpt"),xl=El.filter(t=>t!=="id"),Sl=t=>El.includes(t),Rm=ee(wl),vn=j(v().min(1)).min(1).max(k.fieldPathDepth).superRefine((t,e)=>{if(t[0]==="properties"){t.length<2&&e.addIssue({code:"custom",message:"A properties field path must select a property"});return}(t.length!==1||Rm.safeParse(t[0]).success===!1)&&e.addIssue({code:"custom",message:"Asset query field path is unsupported"})}),us=qe().default(!0),km=$t("mode",[O({mode:Z("all"),includeMetadata:us}),O({mode:Z("base"),includeMetadata:us}),O({mode:Z("fields"),includeMetadata:us,fields:j(vn).max(k.outputFieldCount).refine(t=>new Set(t.map(sl)).size===t.length,{error:"Selected output fields must be unique"})})]),Im={mode:"fields",includeMetadata:!1,fields:_l.map(t=>[t])},Al=["eq","ne","contains","startsWith","endsWith","gt","gte","lt","lte"],nw=[...Al,"in","exists","isEmpty"],Om=O({field:vn,operator:ee(Al),value:rt()}),Cm=O({field:vn,operator:Z("in"),value:j(rt()).max(k.resultCount)}),Tm=O({field:vn,operator:ee(["exists","isEmpty"]),value:qe()}),Nm=$t("operator",[Om,Cm,Tm]),$m=il(Nm,{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 zm=$m,vl=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]},Pm=O({field:vn,direction:ee(["asc","desc"])}),Lm=ee(["many","one","first","last"]),Mm=({output:t,content:e})=>t.includeMetadata||t.mode==="all"||t.mode==="fields"&&t.fields.length>0||e.mode!=="none",it=O({result:Lm.default("many"),where:zm.default({all:[]}),sort:j(Pm).max(k.sortCount).default([]),limit:N().int().nonnegative().max(k.resultCount).default(k.defaultResultCount),offset:N().int().nonnegative().max(k.candidateDocuments).default(0),output:km.default(Im),content:Dm.default({mode:"none"})}).superRefine((t,e)=>{Mm(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."})}),Dl=O({query:it,indexRevision:v().min(1).max(255).optional()}),Fm=nt({_id:v().min(1),revision:v().min(1),contentRef:v().min(1),encoding:Z("utf-8"),text:v(),range:nt({offset:N().int().nonnegative(),length:N().int().nonnegative(),total:N().int().nonnegative()}).optional()}),Zm=Fm.omit({_id:!0,revision:!0,contentRef:!0}),Rl=gl.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:Zm.optional()}).refine(t=>t.width===void 0==(t.height===void 0),{error:"Asset dimensions must include both width and height"}),Bm=O({format:Z("webstudio-content-database"),version:Z(1),revision:br,usedBytes:N().int().nonnegative(),maxBytes:N().int().positive(),unboundedBytes:N().int().nonnegative(),includedDocumentCount:N().int().nonnegative(),omittedDocumentCount:N().int().nonnegative(),omissionReason:ee(["size","unavailable"]).optional(),truncated:qe()}),hl=Bm.pick({usedBytes:!0,maxBytes:!0,unboundedBytes:!0,includedDocumentCount:!0,omittedDocumentCount:!0,omissionReason:!0,truncated:!0}),ds=O({items:j(Rl),totalCount:N().int().nonnegative(),hasMore:qe()}),jm=O({item:Rl.nullable(),totalCount:N().int().nonnegative()}),kl=Nt([ds,jm]),yl=O({line:N().int().positive(),column:N().int().positive(),offset:N().int().nonnegative().optional()}),Um=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:yl,end:yl}).optional()}),Qm=O({severity:ee(["error","warning"]),code:v().min(1),path:j(v()),message:v().min(1)}),Vm=O({scope:Z("query-preview"),queryIssues:j(Qm).optional(),queryWarnings:j(v().min(1)).optional(),query:hl,database:hl,artifacts:O({query:ml,database:ml}).optional(),unresolved:kl.optional(),issues:j(Um).optional(),issueCount:N().int().nonnegative().optional(),issuesTruncated:qe().optional()}),rw=O({data:kl,__diagnostics__:Vm}),Gm=ee(["INVALID_REQUEST","REQUEST_CANCELLED","UNAUTHORIZED","FORBIDDEN","STALE_INDEX","CONTENT_IDENTITY_REQUIRED","CONTENT_NOT_TEXT","CONTENT_DECODING_FAILED","CONTENT_LIMIT_EXCEEDED","MULTIPLE_RESULTS","INTERNAL_ERROR"]),qm=nt({ok:Z(!1),error:nt({code:Gm,message:v().min(1),retryable:qe(),details:Ae(v(),rt()).optional()}),meta:nt({queryHash:v().min(1).optional(),indexRevision:v().min(1).optional(),assetRevision:v().min(1).optional()}).optional()}),Il=({code:t,message:e,retryable:n=!1,details:r})=>qm.parse({ok:!1,error:{code:t,message:e,retryable:n,details:r}});var Ol=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 Km(o)}};var ps=(t,e)=>e+"/"+Jm(t),Jm=t=>t.toString().replace(/~/g,"~0").replace(/\//g,"~1"),Km=t=>t.toString().replace(/~1/g,"/").replace(/~0/g,"~");var _r=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},ms=t=>t.reason??new DOMException("The operation was aborted","AbortError"),Cl=t=>{if(t?.aborted)throw ms(t)},Mt=async(t,e)=>e===void 0?await t:await new Promise((n,r)=>{let o=()=>e.removeEventListener("abort",s),s=()=>{o(),r(ms(e))};e.addEventListener("abort",s,{once:!0}),Promise.resolve(t).then(i=>{o(),n(i)},i=>{o(),r(i)}),e.aborted&&s()}),Er=({concurrency:t,signal:e})=>{if(Number.isSafeInteger(t)===!1||t<=0)throw new TypeError("Concurrency must be a positive safe integer");let n=0,r=[],o=async()=>{if(Cl(e),n<t){n+=1;return}await new Promise((i,a)=>{let c,u=()=>{let d=r.indexOf(c);d!==-1&&r.splice(d,1),e!==void 0&&a(ms(e))};c={start:()=>{e?.removeEventListener("abort",u),i()}},r.push(c),e?.addEventListener("abort",u,{once:!0})})},s=()=>{let i=r.shift();if(i===void 0){n-=1;return}i.start()};return async i=>{await o();try{return Cl(e),await i()}finally{s()}}};var Ft=t=>typeof t=="object"&&t!==null&&Array.isArray(t)===!1,xr=t=>{if(Ft(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}},Wm=(t,e)=>{let n=xr(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}},Ym=t=>`#${t}`;var Tl=async({source:t,maximumBytes:e=k.hydratedFileBytes})=>{let n;try{n=await $e(t,e)}catch(o){throw o instanceof se?new de({code:"CONTENT_LIMIT_EXCEEDED",message:"JSON document exceeds the byte limit",cause:o}):o}let r;try{r=Pt(le(n))}catch(o){throw new de({code:"CONTENT_DECODING_FAILED",message:"JSON document is not valid UTF-8",cause:o})}try{return st(JSON.parse(r))}catch(o){throw new de({code:"INVALID_DOCUMENT",message:"JSON document is invalid",cause:o})}};var Xm=(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(Ft(n)&&Object.hasOwn(n,r)){n=n[r];continue}return}return n},Nl=({document:t,representation:e})=>{let n=st(t);if(e.type==="document")return n;if(e.type!=="json")throw new de({code:"UNSUPPORTED_REPRESENTATION",message:`JSON documents do not support ${e.type}`});let r=Xm(n,e.path);if(r===void 0)throw new de({code:"JSON_PATH_NOT_FOUND",message:"JSON document path does not exist"});return r},Hm=(t,e,n)=>{Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0})},Sr=({document:t,references:e,allowUnresolvedReferences:n=!1})=>{let r=st(t),o=new Set,s=(a,c)=>{let u=Ym(c);if(Wm(a,u)!==void 0){if(e.has(u)===!1){if(n)return a;throw new de({code:"REFERENCE_NOT_FOUND",message:`Resolved JSON reference ${u} is unavailable`,referenceId:u})}o.add(u);try{return st(e.get(u))}catch(l){throw new de({code:"INVALID_RESOLVED_VALUE",message:`Resolved JSON reference ${u} is not JSON-compatible`,referenceId:u,cause:l})}}if(Array.isArray(a))return a.map((l,f)=>s(l,ps(String(f),c)));if(Ft(a)){let l={};for(let[f,p]of Object.entries(a))Hm(l,f,s(p,ps(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 Ar=Symbol.for("yaml.alias"),vr=Symbol.for("yaml.document"),ve=Symbol.for("yaml.map"),hs=Symbol.for("yaml.pair"),pe=Symbol.for("yaml.scalar"),Je=Symbol.for("yaml.seq"),ie=Symbol.for("yaml.node.type"),ye=t=>!!t&&typeof t=="object"&&t[ie]===Ar,Le=t=>!!t&&typeof t=="object"&&t[ie]===vr,ge=t=>!!t&&typeof t=="object"&&t[ie]===ve,$=t=>!!t&&typeof t=="object"&&t[ie]===hs,T=t=>!!t&&typeof t=="object"&&t[ie]===pe,be=t=>!!t&&typeof t=="object"&&t[ie]===Je;function B(t){if(t&&typeof t=="object")switch(t[ie]){case ve:case Je:return!0}return!1}function z(t){if(t&&typeof t=="object")switch(t[ie]){case Ar:case ve:case pe:case Je:return!0}return!1}var Dr=t=>(T(t)||B(t))&&!!t.anchor;var ce=Symbol("break visit"),$l=Symbol("skip children"),Me=Symbol("remove node");function Fe(t,e){let n=zl(e);Le(t)?Zt(null,t.contents,n,Object.freeze([t]))===Me&&(t.contents=null):Zt(null,t,n,Object.freeze([]))}Fe.BREAK=ce;Fe.SKIP=$l;Fe.REMOVE=Me;function Zt(t,e,n,r){let o=Pl(t,e,n,r);if(z(o)||$(o))return Ll(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=Zt(s,e.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===ce)return ce;i===Me&&(e.items.splice(s,1),s-=1)}}}else if($(e)){r=Object.freeze(r.concat(e));let s=Zt("key",e.key,n,r);if(s===ce)return ce;s===Me&&(e.key=null);let i=Zt("value",e.value,n,r);if(i===ce)return ce;i===Me&&(e.value=null)}}return o}async function Rr(t,e){let n=zl(e);Le(t)?await Bt(null,t.contents,n,Object.freeze([t]))===Me&&(t.contents=null):await Bt(null,t,n,Object.freeze([]))}Rr.BREAK=ce;Rr.SKIP=$l;Rr.REMOVE=Me;async function Bt(t,e,n,r){let o=await Pl(t,e,n,r);if(z(o)||$(o))return Ll(t,r,o),Bt(t,o,n,r);if(typeof o!="symbol"){if(B(e)){r=Object.freeze(r.concat(e));for(let s=0;s<e.items.length;++s){let i=await Bt(s,e.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===ce)return ce;i===Me&&(e.items.splice(s,1),s-=1)}}}else if($(e)){r=Object.freeze(r.concat(e));let s=await Bt("key",e.key,n,r);if(s===ce)return ce;s===Me&&(e.key=null);let i=await Bt("value",e.value,n,r);if(i===ce)return ce;i===Me&&(e.value=null)}}return o}function zl(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 Pl(t,e,n,r){if(typeof n=="function")return n(t,e,r);if(ge(e))return n.Map?.(t,e,r);if(be(e))return n.Seq?.(t,e,r);if($(e))return n.Pair?.(t,e,r);if(T(e))return n.Scalar?.(t,e,r);if(ye(e))return n.Alias?.(t,e,r)}function Ll(t,e,n){let r=e[e.length-1];if(B(r))r.items[t]=n;else if($(r))t==="key"?r.key=n:r.value=n;else if(Le(r))r.contents=n;else{let o=ye(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}var eh={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},th=t=>t.replace(/[!,[\]{}]/g,e=>eh[e]),Ze=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let r=e.trim().split(/[ \t]+/),o=r.shift();switch(o){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[s,i]=r;return this.tags[s]=i,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=r;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let i=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,i),!1}}default:return n(0,`Unknown directive ${o}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let i=e.slice(2,-1);return i==="!"||i==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),i)}let[,r,o]=e.match(/^(.*!)([^!]*)$/s);o||n(`The ${e} tag has no suffix`);let s=this.tags[r];if(s)try{return s+decodeURIComponent(o)}catch(i){return n(String(i)),null}return r==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,r]of Object.entries(this.tags))if(e.startsWith(r))return n+th(e.substring(r.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),o;if(e&&r.length>0&&z(e.contents)){let s={};Fe(e.contents,(i,a)=>{z(a)&&a.tag&&(s[a.tag]=!0)}),o=Object.keys(s)}else o=[];for(let[s,i]of r)s==="!!"&&i==="tag:yaml.org,2002:"||(!e||o.some(a=>a.startsWith(i)))&&n.push(`%TAG ${s} ${i}`);return n.join(`-`)}};Ze.defaultYaml={explicit:!1,version:"1.2"};Ze.defaultTags={"!!":"tag:yaml.org,2002:"};function kr(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 ys(t){let e=new Set;return Fe(t,{Value(n,r){r.anchor&&e.add(r.anchor)}}),e}function gs(t,e){for(let n=1;;++n){let r=`${t}${n}`;if(!e.has(r))return r}}function Ml(t,e){let n=[],r=new Map,o=null;return{onAnchor:s=>{n.push(s),o??(o=ys(t));let i=gs(e,o);return o.add(i),i},setAnchors:()=>{for(let s of n){let i=r.get(s);if(typeof i=="object"&&i.anchor&&(T(i.node)||B(i.node)))i.node.anchor=i.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:r}}function at(t,e,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let o=0,s=r.length;o<s;++o){let i=r[o],a=at(t,r,String(o),i);a===void 0?delete r[o]:a!==i&&(r[o]=a)}else if(r instanceof Map)for(let o of Array.from(r.keys())){let s=r.get(o),i=at(t,r,o,s);i===void 0?r.delete(o):i!==s&&r.set(o,i)}else if(r instanceof Set)for(let o of Array.from(r)){let s=at(t,r,o,o);s===void 0?r.delete(o):s!==o&&(r.delete(o),r.add(s))}else for(let[o,s]of Object.entries(r)){let i=at(t,r,o,s);i===void 0?delete r[o]:i!==s&&(r[o]=i)}return t.call(e,n,r)}function H(t,e,n){if(Array.isArray(t))return t.map((r,o)=>H(r,String(o),n));if(t&&typeof t.toJSON=="function"){if(!n||!Dr(t))return t.toJSON(e,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(t,r),n.onCreate=s=>{r.res=s,delete n.onCreate};let o=t.toJSON(e,n);return n.onCreate&&n.onCreate(o),o}return typeof t=="bigint"&&!n?.keep?Number(t):t}var ct=class{constructor(e){Object.defineProperty(this,ie,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:r,onAnchor:o,reviver:s}={}){if(!Le(e))throw new TypeError("A document argument is required");let i={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=H(this,"",i);if(typeof o=="function")for(let{count:c,res:u}of i.anchors.values())o(u,c);return typeof s=="function"?at(s,{"":a},"",a):a}};var Ke=class extends ct{constructor(e){super(Ar),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],Fe(e,{Node:(s,i)=>{(ye(i)||Dr(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=Ir(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(kr(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 Ir(t,e,n){if(ye(e)){let r=e.resolve(t),o=n&&r&&n.get(r);return o?o.count*o.aliasCount:0}else if(B(e)){let r=0;for(let o of e.items){let s=Ir(t,o,n);s>r&&(r=s)}return r}else if($(e)){let r=Ir(t,e.key,n),o=Ir(t,e.value,n);return Math.max(r,o)}return 1}var Or=t=>!t||typeof t!="function"&&typeof t!="object",R=class extends ct{constructor(e){super(pe),this.value=e}toJSON(e,n){return n?.keep?this.value:H(this.value,e,n)}toString(){return String(this.value)}};R.BLOCK_FOLDED="BLOCK_FOLDED";R.BLOCK_LITERAL="BLOCK_LITERAL";R.PLAIN="PLAIN";R.QUOTE_DOUBLE="QUOTE_DOUBLE";R.QUOTE_SINGLE="QUOTE_SINGLE";var nh="tag:yaml.org,2002:";function rh(t,e,n){if(e){let r=n.filter(s=>s.tag===e),o=r.find(s=>!s.format)??r[0];if(!o)throw new Error(`Tag ${e} not found`);return o}return n.find(r=>r.identify?.(t)&&!r.format)}function We(t,e,n){if(Le(t)&&(t=t.contents),z(t))return t;if($(t)){let l=n.schema[ve].createNode?.(n.schema,null,n);return l.items.push(t),l}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:r,onAnchor:o,onTagObj:s,schema:i,sourceObjects:a}=n,c;if(r&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=o(t)),new Ke(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=nh+e.slice(2));let u=rh(t,e,i.tags);if(!u){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let l=new R(t);return c&&(c.node=l),l}u=t instanceof Map?i[ve]:Symbol.iterator in Object(t)?i[Je]:i[ve]}s&&(s(u),delete n.onTagObj);let d=u?.createNode?u.createNode(n.schema,t,n):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(n.schema,t,n):new R(t);return e?d.tag=e:u.default||(d.tag=u.tag),c&&(c.node=d),d}function Dn(t,e,n){let r=n;for(let o=e.length-1;o>=0;--o){let s=e[o];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let i=[];i[s]=r,r=i}else r=new Map([[s,r]])}return We(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Ut=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,jt=class extends ct{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(r=>z(r)||$(r)?r.clone(e):r),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(Ut(e))this.add(n);else{let[r,...o]=e,s=this.get(r,!0);if(B(s))s.addIn(o,n);else if(s===void 0&&this.schema)this.set(r,Dn(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}deleteIn(e){let[n,...r]=e;if(r.length===0)return this.delete(n);let o=this.get(n,!0);if(B(o))return o.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(e,n){let[r,...o]=e,s=this.get(r,!0);return o.length===0?!n&&T(s)?s.value:s:B(s)?s.getIn(o,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!$(n))return!1;let r=n.value;return r==null||e&&T(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[n,...r]=e;if(r.length===0)return this.has(n);let o=this.get(n,!0);return B(o)?o.hasIn(r):!1}setIn(e,n){let[r,...o]=e;if(o.length===0)this.set(r,n);else{let s=this.get(r,!0);if(B(s))s.setIn(o,n);else if(s===void 0&&this.schema)this.set(r,Dn(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}};var Fl=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function we(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Be=(t,e,n)=>t.endsWith(`-`)?we(n,e):n.includes(`+Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){s(i);continue}if(e.external){let u=e.external.registry.get(i[0])?.id;if(t!==i[0]&&u){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&e.reused==="ref"){s(i);continue}}}function Ks(e,t){let n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=a=>{let c=e.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,f={...u},l=c.ref;if(c.ref=null,l){r(l);let d=e.seen.get(l),w=d.schema;if(w.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(w)):Object.assign(u,w),Object.assign(u,f),a._zod.parent===l)for(let y in u)y==="$ref"||y==="allOf"||y in f||delete u[y];if(w.$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]}let p=a._zod.parent;if(p&&p!==l){r(p);let d=e.seen.get(p);if(d?.schema.$ref&&(u.$ref=d.schema.$ref,d.def))for(let w in u)w==="$ref"||w==="allOf"||w in d.def&&JSON.stringify(u[w])===JSON.stringify(d.def[w])&&delete u[w]}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...e.seen.entries()].reverse())r(a[0]);let o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Object.assign(o,n.def??n.schema);let s=e.metadataRegistry.get(t)?.id;s!==void 0&&o.id===s&&delete o.id;let i=e.external?.defs??{};for(let a of e.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Gn(t,"input",e.processors),output:Gn(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function be(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return be(r.element,n);if(r.type==="set")return be(r.valueType,n);if(r.type==="lazy")return be(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 be(r.innerType,n);if(r.type==="intersection")return be(r.left,n)||be(r.right,n);if(r.type==="record"||r.type==="map")return be(r.keyType,n)||be(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:be(r.in,n)||be(r.out,n);if(r.type==="object"){for(let o in r.shape)if(be(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(be(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(be(o,n))return!0;return!!(r.rest&&be(r.rest,n))}return!1}var gl=(e,t={})=>n=>{let r=Js({...n,processors:t});return re(e,r),Ws(r,e),Ks(r,e)},Gn=(e,t,n={})=>r=>{let{libraryOptions:o,target:s}=r??{},i=Js({...o??{},target:s,io:t,processors:n});return re(e,i),Ws(i,e),Ks(i,e)};var Wm={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},yl=(e,t,n,r)=>{let o=n;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=Wm[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),u&&(o.contentEncoding=u),c&&c.size>0){let f=[...c];f.length===1?o.pattern=f[0].source:f.length>1&&(o.allOf=[...f.map(l=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:l.source}))])}},bl=(e,t,n,r)=>{let o=n,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:f}=e._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";let l=typeof f=="number"&&f>=(s??Number.NEGATIVE_INFINITY),p=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),d=t.target==="draft-04"||t.target==="openapi-3.0";l?d?(o.minimum=f,o.exclusiveMinimum=!0):o.exclusiveMinimum=f:typeof s=="number"&&(o.minimum=s),p?d?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof c=="number"&&(o.multipleOf=c)},wl=(e,t,n,r)=>{n.type="boolean"};var xl=(e,t,n,r)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"};var _l=(e,t,n,r)=>{n.not={}};var Sl=(e,t,n,r)=>{};var El=(e,t,n,r)=>{let o=e._zod.def,s=Fn(o.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},Al=(e,t,n,r)=>{let o=e._zod.def,s=[];for(let i of o.values)if(i===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){let i=s[0];n.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[i]:n.const=i}else s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),s.every(i=>typeof i=="boolean")&&(n.type="boolean"),s.every(i=>i===null)&&(n.type="null"),n.enum=s};var kl=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var vl=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var Rl=(e,t,n,r)=>{let o=n,s=e._zod.def,{minimum:i,maximum:a}=e._zod.bag;typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=re(s.element,t,{...r,path:[...r.path,"items"]})},Dl=(e,t,n,r)=>{let o=n,s=e._zod.def;o.type="object",o.properties={};let i=s.shape;for(let u in i)o.properties[u]=re(i[u],t,{...r,path:[...r.path,"properties",u]});let a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{let f=s.shape[u]._zod;return t.io==="input"?f.optin===void 0:f.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=re(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},Il=(e,t,n,r)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>re(a,t,{...r,path:[...r.path,s?"oneOf":"anyOf",c]}));s?n.oneOf=i:n.anyOf=i},Cl=(e,t,n,r)=>{let o=e._zod.def,s=re(o.left,t,{...r,path:[...r.path,"allOf",0]}),i=re(o.right,t,{...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 Tl=(e,t,n,r)=>{let o=n,s=e._zod.def;o.type="object";let i=s.keyType,c=i._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let f=re(s.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let l of c)o.patternProperties[l.source]=f}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=re(s.keyType,t,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=re(s.valueType,t,{...r,path:[...r.path,"additionalProperties"]});let u=i._zod.values;if(u){let f=[...u].filter(l=>typeof l=="string"||typeof l=="number");f.length>0&&(o.required=f)}},Ol=(e,t,n,r)=>{let o=e._zod.def,s=re(o.innerType,t,r),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=o.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},Nl=(e,t,n,r)=>{let o=e._zod.def;re(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType},zl=(e,t,n,r)=>{let o=e._zod.def;re(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},$l=(e,t,n,r)=>{let o=e._zod.def;re(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},Ll=(e,t,n,r)=>{let o=e._zod.def;re(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i},Pl=(e,t,n,r)=>{let o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?o.out:o.in:o.out;re(i,t,r);let a=t.seen.get(e);a.ref=i},Fl=(e,t,n,r)=>{let o=e._zod.def;re(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType,n.readOnly=!0};var Hs=(e,t,n,r)=>{let o=e._zod.def;re(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType},Ml=(e,t,n,r)=>{let o=e._zod.innerType;re(o,t,r);let s=t.seen.get(e);s.ref=o};var nh=k("ZodISODateTime",(e,t)=>{Kc.init(e,t),te.init(e,t)});function Bl(e){return rl(nh,e)}var rh=k("ZodISODate",(e,t)=>{Hc.init(e,t),te.init(e,t)});function ql(e){return ol(rh,e)}var oh=k("ZodISOTime",(e,t)=>{Yc.init(e,t),te.init(e,t)});function Zl(e){return sl(oh,e)}var sh=k("ZodISODuration",(e,t)=>{Xc.init(e,t),te.init(e,t)});function Ul(e){return il(sh,e)}var jl=(e,t)=>{$r.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Ta(e,n)},flatten:{value:n=>Ca(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,nn,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,nn,2)}},isEmpty:{get(){return e.issues.length===0}}})},Vl=k("ZodError",jl),ke=k("ZodError",jl,{Parent:Error});var Ql=Lr(ke),Gl=Pr(ke),Jl=Zn(ke),Wl=Un(ke),Kl=za(ke),Hl=$a(ke),Yl=La(ke),Xl=Pa(ke),ef=Fa(ke),tf=Ma(ke),nf=Ba(ke),rf=qa(ke);var of=new WeakMap;function Jn(e,t,n){let r=Object.getPrototypeOf(e),o=of.get(r);if(o||(o=new Set,of.set(r,o)),!o.has(t)){o.add(t);for(let s in n){let i=n[s];Object.defineProperty(r,s,{configurable:!0,enumerable:!1,get(){let 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 ee=k("ZodType",(e,t)=>(Y.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Gn(e,"input"),output:Gn(e,"output")}}),e.toJSONSchema=gl(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>Ql(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>Jl(e,n,r),e.parseAsync=async(n,r)=>Gl(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Wl(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>Kl(e,n,r),e.decode=(n,r)=>Hl(e,n,r),e.encodeAsync=async(n,r)=>Yl(e,n,r),e.decodeAsync=async(n,r)=>Xl(e,n,r),e.safeEncode=(n,r)=>ef(e,n,r),e.safeDecode=(n,r)=>tf(e,n,r),e.safeEncodeAsync=async(n,r)=>nf(e,n,r),e.safeDecodeAsync=async(n,r)=>rf(e,n,r),Jn(e,"ZodType",{check(...n){let r=this.def;return this.clone(J.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 Ze(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(tg(n,r))},superRefine(n,r){return this.check(ng(n,r))},overwrite(n){return this.check(St(n))},optional(){return lf(this)},exactOptional(){return qh(this)},nullable(){return ff(this)},nullish(){return lf(ff(this))},nonoptional(n){return Gh(this,n)},array(){return H(this)},or(n){return an([this,n])},and(n){return Lh(this,n)},transform(n){return df(this,Mh(n))},default(n){return jh(this,n)},prefault(n){return Qh(this,n)},catch(n){return Wh(this,n)},pipe(n){return df(this,n)},readonly(){return Yh(this)},describe(n){let r=this.clone();return jt.add(r,{description:n}),r},meta(...n){if(n.length===0)return jt.get(this);let r=this.clone();return jt.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return jt.get(e)?.description},configurable:!0}),e)),pf=k("_ZodString",(e,t)=>{Zr.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,s)=>yl(e,r,o,s);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Jn(e,"_ZodString",{regex(...r){return this.check(Ps(...r))},includes(...r){return this.check(Bs(...r))},startsWith(...r){return this.check(qs(...r))},endsWith(...r){return this.check(Zs(...r))},min(...r){return this.check(sn(...r))},max(...r){return this.check(Qr(...r))},length(...r){return this.check(Gr(...r))},nonempty(...r){return this.check(sn(1,...r))},lowercase(r){return this.check(Fs(r))},uppercase(r){return this.check(Ms(r))},trim(){return this.check(js())},normalize(...r){return this.check(Us(...r))},toLowerCase(){return this.check(Vs())},toUpperCase(){return this.check(Qs())},slugify(){return this.check(Gs())}})}),uh=k("ZodString",(e,t)=>{Zr.init(e,t),pf.init(e,t),e.email=n=>e.check(Lu(lh,n)),e.url=n=>e.check(qu(fh,n)),e.jwt=n=>e.check(nl(vh,n)),e.emoji=n=>e.check(Zu(dh,n)),e.guid=n=>e.check(Ls(sf,n)),e.uuid=n=>e.check(Pu(Wr,n)),e.uuidv4=n=>e.check(Fu(Wr,n)),e.uuidv6=n=>e.check(Mu(Wr,n)),e.uuidv7=n=>e.check(Bu(Wr,n)),e.nanoid=n=>e.check(Uu(ph,n)),e.guid=n=>e.check(Ls(sf,n)),e.cuid=n=>e.check(ju(mh,n)),e.cuid2=n=>e.check(Vu(hh,n)),e.ulid=n=>e.check(Qu(gh,n)),e.base64=n=>e.check(Xu(Eh,n)),e.base64url=n=>e.check(el(Ah,n)),e.xid=n=>e.check(Gu(yh,n)),e.ksuid=n=>e.check(Ju(bh,n)),e.ipv4=n=>e.check(Wu(wh,n)),e.ipv6=n=>e.check(Ku(xh,n)),e.cidrv4=n=>e.check(Hu(_h,n)),e.cidrv6=n=>e.check(Yu(Sh,n)),e.e164=n=>e.check(tl(kh,n)),e.datetime=n=>e.check(Bl(n)),e.date=n=>e.check(ql(n)),e.time=n=>e.check(Zl(n)),e.duration=n=>e.check(Ul(n))});function D(e){return $u(uh,e)}var te=k("ZodStringFormat",(e,t)=>{X.init(e,t),pf.init(e,t)}),lh=k("ZodEmail",(e,t)=>{qc.init(e,t),te.init(e,t)});var sf=k("ZodGUID",(e,t)=>{Mc.init(e,t),te.init(e,t)});var Wr=k("ZodUUID",(e,t)=>{Bc.init(e,t),te.init(e,t)});var fh=k("ZodURL",(e,t)=>{Zc.init(e,t),te.init(e,t)});var dh=k("ZodEmoji",(e,t)=>{Uc.init(e,t),te.init(e,t)});var ph=k("ZodNanoID",(e,t)=>{jc.init(e,t),te.init(e,t)});var mh=k("ZodCUID",(e,t)=>{Vc.init(e,t),te.init(e,t)});var hh=k("ZodCUID2",(e,t)=>{Qc.init(e,t),te.init(e,t)});var gh=k("ZodULID",(e,t)=>{Gc.init(e,t),te.init(e,t)});var yh=k("ZodXID",(e,t)=>{Jc.init(e,t),te.init(e,t)});var bh=k("ZodKSUID",(e,t)=>{Wc.init(e,t),te.init(e,t)});var wh=k("ZodIPv4",(e,t)=>{eu.init(e,t),te.init(e,t)});var xh=k("ZodIPv6",(e,t)=>{tu.init(e,t),te.init(e,t)});var _h=k("ZodCIDRv4",(e,t)=>{nu.init(e,t),te.init(e,t)});var Sh=k("ZodCIDRv6",(e,t)=>{ru.init(e,t),te.init(e,t)});var Eh=k("ZodBase64",(e,t)=>{su.init(e,t),te.init(e,t)});var Ah=k("ZodBase64URL",(e,t)=>{iu.init(e,t),te.init(e,t)});var kh=k("ZodE164",(e,t)=>{au.init(e,t),te.init(e,t)});var vh=k("ZodJWT",(e,t)=>{cu.init(e,t),te.init(e,t)});var mf=k("ZodNumber",(e,t)=>{Os.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,s)=>bl(e,r,o,s),Jn(e,"ZodNumber",{gt(r,o){return this.check(jr(r,o))},gte(r,o){return this.check(Qn(r,o))},min(r,o){return this.check(Qn(r,o))},lt(r,o){return this.check(Ur(r,o))},lte(r,o){return this.check(Vn(r,o))},max(r,o){return this.check(Vn(r,o))},int(r){return this.check(af(r))},safe(r){return this.check(af(r))},positive(r){return this.check(jr(0,r))},nonnegative(r){return this.check(Qn(0,r))},negative(r){return this.check(Ur(0,r))},nonpositive(r){return this.check(Vn(0,r))},multipleOf(r,o){return this.check(Vr(r,o))},step(r,o){return this.check(Vr(r,o))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function U(e){return al(mf,e)}var Rh=k("ZodNumberFormat",(e,t)=>{uu.init(e,t),mf.init(e,t)});function af(e){return cl(Rh,e)}var Dh=k("ZodBoolean",(e,t)=>{lu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>wl(e,n,r,o)});function pt(e){return ul(Dh,e)}var Ih=k("ZodNull",(e,t)=>{fu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>xl(e,n,r,o)});function Ch(e){return ll(Ih,e)}var Th=k("ZodUnknown",(e,t)=>{du.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Sl(e,n,r,o)});function cf(){return fl(Th)}var Oh=k("ZodNever",(e,t)=>{pu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>_l(e,n,r,o)});function hf(e){return dl(Oh,e)}var Nh=k("ZodArray",(e,t)=>{mu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Rl(e,n,r,o),e.element=t.element,Jn(e,"ZodArray",{min(n,r){return this.check(sn(n,r))},nonempty(n){return this.check(sn(1,n))},max(n,r){return this.check(Qr(n,r))},length(n,r){return this.check(Gr(n,r))},unwrap(){return this.element}})});function H(e,t){return pl(Nh,e,t)}var gf=k("ZodObject",(e,t)=>{yu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Dl(e,n,r,o),J.defineLazy(e,"shape",()=>t.shape),Jn(e,"ZodObject",{keyof(){return fe(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:cf()})},loose(){return this.clone({...this._zod.def,catchall:cf()})},strict(){return this.clone({...this._zod.def,catchall:hf()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return J.extend(this,n)},safeExtend(n){return J.safeExtend(this,n)},merge(n){return J.merge(this,n)},pick(n){return J.pick(this,n)},omit(n){return J.omit(this,n)},partial(...n){return J.partial(bf,this,n[0])},required(...n){return J.required(wf,this,n[0])}})});function Et(e,t){let n={type:"object",shape:e??{},...J.normalizeParams(t)};return new gf(n)}function L(e,t){return new gf({type:"object",shape:e,catchall:hf(),...J.normalizeParams(t)})}var yf=k("ZodUnion",(e,t)=>{Ns.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Il(e,n,r,o),e.options=t.options});function an(e,t){return new yf({type:"union",options:e,...J.normalizeParams(t)})}var zh=k("ZodDiscriminatedUnion",(e,t)=>{yf.init(e,t),bu.init(e,t)});function cn(e,t,n){return new zh({type:"union",options:t,discriminator:e,...J.normalizeParams(n)})}var $h=k("ZodIntersection",(e,t)=>{wu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Cl(e,n,r,o)});function Lh(e,t){return new $h({type:"intersection",left:e,right:t})}var uf=k("ZodRecord",(e,t)=>{xu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Tl(e,n,r,o),e.keyType=t.keyType,e.valueType=t.valueType});function Ne(e,t,n){return!t||!t._zod?new uf({type:"record",keyType:D(),valueType:e,...J.normalizeParams(t)}):new uf({type:"record",keyType:e,valueType:t,...J.normalizeParams(n)})}var Ys=k("ZodEnum",(e,t)=>{_u.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,s)=>El(e,r,o,s),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Ys({...t,checks:[],...J.normalizeParams(o),entries:s})},e.exclude=(r,o)=>{let s={...t.entries};for(let i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Ys({...t,checks:[],...J.normalizeParams(o),entries:s})}});function fe(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Ys({type:"enum",entries:n,...J.normalizeParams(t)})}var Ph=k("ZodLiteral",(e,t)=>{Su.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Al(e,n,r,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function W(e,t){return new Ph({type:"literal",values:Array.isArray(e)?e:[e],...J.normalizeParams(t)})}var Fh=k("ZodTransform",(e,t)=>{Eu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>vl(e,n,r,o),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new en(e.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(J.issue(s,n.value,t));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),n.issues.push(J.issue(i))}};let o=t.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});function Mh(e){return new Fh({type:"transform",transform:e})}var bf=k("ZodOptional",(e,t)=>{zs.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Hs(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function lf(e){return new bf({type:"optional",innerType:e})}var Bh=k("ZodExactOptional",(e,t)=>{Au.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Hs(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function qh(e){return new Bh({type:"optional",innerType:e})}var Zh=k("ZodNullable",(e,t)=>{ku.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ol(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function ff(e){return new Zh({type:"nullable",innerType:e})}var Uh=k("ZodDefault",(e,t)=>{vu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>zl(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function jh(e,t){return new Uh({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():J.shallowClone(t)}})}var Vh=k("ZodPrefault",(e,t)=>{Ru.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>$l(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Qh(e,t){return new Vh({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():J.shallowClone(t)}})}var wf=k("ZodNonOptional",(e,t)=>{Du.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Nl(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Gh(e,t){return new wf({type:"nonoptional",innerType:e,...J.normalizeParams(t)})}var Jh=k("ZodCatch",(e,t)=>{Iu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ll(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Wh(e,t){return new Jh({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Kh=k("ZodPipe",(e,t)=>{Cu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Pl(e,n,r,o),e.in=t.in,e.out=t.out});function df(e,t){return new Kh({type:"pipe",in:e,out:t})}var Hh=k("ZodReadonly",(e,t)=>{Tu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Fl(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Yh(e){return new Hh({type:"readonly",innerType:e})}var Xh=k("ZodLazy",(e,t)=>{Ou.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ml(e,n,r,o),e.unwrap=()=>e._zod.def.getter()});function Xs(e){return new Xh({type:"lazy",getter:e})}var eg=k("ZodCustom",(e,t)=>{Nu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>kl(e,n,r,o)});function tg(e,t={}){return ml(eg,e,t)}function ng(e,t){return hl(e,t)}function At(e){let t=Xs(()=>an([D(e),U(),pt(),Ch(),H(t),Ne(D(),t)]));return t}var xf=e=>"field"in e?[e]:("all"in e?e.all:e.any).flatMap(xf),Kr=e=>xf(e);var un=(e,t)=>{if("field"in e)return t(e);let n="all"in e?e.all:e.any,r=!1;if("all"in e){for(let o of n){let s=un(o,t);if(s===!1)return!1;r||=s===void 0}return r?void 0:!0}for(let o of n){let s=un(o,t);if(s===!0)return!0;r||=s===void 0}return r?void 0:!1},_f=e=>JSON.stringify(e),ei=e=>{if("field"in e)return{conditions:1,depth:0};let t="all"in e?e.all:e.any,n=0,r=1;for(let o of t){let s=ei(o);n+=s.conditions,r=Math.max(r,s.depth+1)}return{conditions:n,depth:r}},Sf=(e,t={})=>{let n=o=>{let s=H(o),i=t.maximumChildren===void 0?s:s.max(t.maximumChildren);return an([e,L({all:i}),L({any:i})])},r=Xs(()=>n(r));return t.maximumConditions===void 0&&t.maximumDepth===void 0?r:r.superRefine((o,s)=>{let{conditions:i,depth:a}=ei(o);t.maximumConditions!==void 0&&i>t.maximumConditions&&s.addIssue({code:"custom",message:t.maximumConditionsMessage??"Query exceeds the condition limit"}),t.maximumDepth!==void 0&&a>t.maximumDepth&&s.addIssue({code:"custom",message:t.maximumDepthMessage??"Query exceeds the nesting limit"})})};var N={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 Vt(e,t=new Set){if(typeof e=="number"&&isNaN(e))throw new Error("NaN is not allowed");if(typeof e=="number"&&!isFinite(e))throw new Error("Infinity is not allowed");if(e===null||typeof e!="object")return JSON.stringify(e);if(typeof e.toJSON=="function"){if(t.has(e))throw new Error("Circular reference detected");t.add(e);let r=Vt(e.toJSON(),t);return t.delete(e),r}if(t.has(e))throw new Error("Circular reference detected");t.add(e);let n;if(Array.isArray(e))n=`[${e.map(o=>Vt(o===void 0||typeof o=="symbol"?null:o,t)).join(",")}]`;else{let r=[];for(let o of Object.keys(e).sort())e[o]===void 0||typeof e[o]=="symbol"||r.push(`${Vt(o)}:${Vt(e[o],t)}`);n=`{${r.join(",")}}`}return t.delete(e),n}var rg=new TextEncoder,kt=e=>rg.encode(e),Ye=e=>kt(e).byteLength,we=class extends Error{constructor(){super("Byte stream exceeds the configured limit"),this.name="ByteLimitExceededError"}},og=(e,t)=>{let n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.byteLength;return n},Wn=e=>typeof e=="string"?{async*[Symbol.asyncIterator](){yield kt(e)}}:e instanceof Uint8Array?{async*[Symbol.asyncIterator](){yield e}}:e,Hr=(e,t)=>t===void 0?Wn(e):{async*[Symbol.asyncIterator](){let n=0,r=0;for await(let o of Wn(e)){if(r===t.length)return;if(n+o.byteLength<=t.offset){n+=o.byteLength;continue}let s=Math.max(0,t.offset-n),i=Math.min(o.byteLength-s,t.length-r);i>0&&(yield o.subarray(s,s+i),r+=i),n+=o.byteLength}}},Yr=e=>({async*[Symbol.asyncIterator](){let t=e.getReader(),n=!1;try{for(;;){let r=await t.read();if(r.done){n=!0;return}yield r.value}}finally{if(n===!1)try{await t.cancel()}catch{}t.releaseLock()}}}),ti=async(e,t)=>{let n=[],r=0;for await(let o of Wn(e)){let s=t-r;if(s<=0)break;let i=o.subarray(0,s);if(n.push(i),r+=i.byteLength,r===t)break}return og(n,r)},Xe=async(e,t)=>{let n=await ti(e,t+1);if(n.byteLength>t)throw new we;return n},ve=e=>new TextDecoder("utf-8",{fatal:!0}).decode(e),ln=e=>e.charCodeAt(0)===65279?e.slice(1):e;var Ef=e=>{for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n>=55296&&n<=56319){let r=e.charCodeAt(t+1);if(t+1>=e.length||r<56320||r>57343)throw new Error("JSON strings cannot contain lone Unicode surrogates");t+=1;continue}if(n>=56320&&n<=57343)throw new Error("JSON strings cannot contain lone Unicode surrogates")}},ni=(e,t)=>{if(e===null||typeof e=="boolean")return e;if(typeof e=="string")return Ef(e),e;if(typeof e=="number"){if(Number.isFinite(e)===!1)throw new Error("JSON cannot contain non-finite numbers");return e}if(Array.isArray(e)){if(Object.getOwnPropertySymbols(e).length>0)throw new Error("JSON arrays cannot contain symbol properties");if(t.has(e))throw new Error("JSON cannot contain circular references");t.add(e);try{let n=[];for(let r=0;r<e.length;r+=1){if(Object.hasOwn(e,r)===!1)throw new Error("JSON arrays cannot be sparse");let o=e[r];if(o===void 0)throw new Error("JSON arrays cannot contain undefined values");n.push(ni(o,t))}if(Object.keys(e).length!==e.length)throw new Error("JSON arrays cannot contain named properties");return n}finally{t.delete(e)}}if(typeof e=="object"){let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new Error("JSON can contain only plain objects");if(Object.getOwnPropertySymbols(e).length>0)throw new Error("JSON objects cannot contain symbol properties");if(t.has(e))throw new Error("JSON cannot contain circular references");t.add(e);let r={};try{for(let[o,s]of Object.entries(e))Ef(o),s!==void 0&&Object.defineProperty(r,o,{value:ni(s,t),enumerable:!0,configurable:!0,writable:!0})}finally{t.delete(e)}return r}throw new Error("Value cannot be represented as JSON")},vt=e=>ni(e,new Set),Re=e=>{let t=Vt(vt(e));if(t===void 0)throw new Error("Value cannot be represented as canonical JSON");return t},Kn=(e,t)=>e===void 0||t===void 0?e===t:Re(e)===Re(t),et=(e,t)=>e<t?-1:e>t?1:0,ri=async e=>{let t=typeof e=="string"?kt(e):e,n=await globalThis.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")},Af=async e=>`sha256:${await ri(e)}`;var kf=cn("type",[L({type:W("document")}),L({type:W("json"),path:H(D()).min(1)}),L({type:W("markdown-body")}),L({type:W("markdown-frontmatter")})]),oi=L({documentId:D().min(1),revision:D().min(1),representation:kf}),sg=e=>{let t=kf.parse(e);return t.type==="json"?Object.freeze({...t,path:Object.freeze([...t.path])}):Object.freeze(t)},vf=e=>{let t=oi.parse(e);return Object.freeze({...t,representation:sg(t.representation)})};var Hn=["json","markdown","mdx"],Rf=e=>typeof e=="string"&&Hn.includes(e),Df=e=>{let t=e.split(";",1)[0].trim().toLowerCase();if(t==="application/json")return"json";if(t==="text/markdown")return"markdown";if(t==="text/mdx")return"mdx"};var Xr=L({id:D().min(1),revision:D().min(1),contentRef:D().min(1),format:fe(Hn).optional()}),eo=L({sourceId:D().min(1),referenceId:D().min(1),reference:oi});var fn=e=>{let t=new Map;for(let n of e){let r=t.get(n.sourceId)??[];r.push(n),t.set(n.sourceId,r)}return t};var tt=class extends Error{code;documentIds;constructor({code:t,message:n,documentIds:r=[]}){super(n),this.name="DocumentGraphError",this.code=t,this.documentIds=Object.freeze([...r])}},ig=(e,t)=>et(e.sourceId,t.sourceId)||et(e.referenceId,t.referenceId),Yn=({nodes:e,edges:t})=>{let n=e.map(a=>Object.freeze(Xr.parse(a))).sort((a,c)=>et(a.id,c.id)),r=new Map,o=new Map;for(let a of n){if(r.has(a.id))throw new tt({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 tt({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=t.map(a=>{let c=eo.parse(a);return Object.freeze({...c,reference:vf(c.reference)})}).sort(ig),i=new Set;for(let a of s){if(r.get(a.sourceId)===void 0)throw new tt({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 tt({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 tt({code:"TARGET_REVISION_MISMATCH",message:`Document graph target ${u.id} revision does not match its reference`,documentIds:[a.sourceId,u.id]});let f=`${a.sourceId}\0${a.referenceId}`;if(i.has(f))throw new tt({code:"DUPLICATE_REFERENCE",message:`Document ${a.sourceId} contains duplicate reference ID ${a.referenceId}`,documentIds:[a.sourceId]});i.add(f)}return Object.freeze({nodes:Object.freeze(n),edges:Object.freeze(s)})},ag=e=>new Map(e.nodes.map(t=>[t.id,t]));var to=({graph:e,rootIds:t})=>{let n=ag(e),r=fn(e.edges),o=new Map,s=[],i=[],a=c=>{let u=n.get(c);if(u===void 0)throw new tt({code:"ROOT_NOT_FOUND",message:`Document graph root ${c} does not exist`,documentIds:[c]});let f=o.get(c);if(f!=="visited"){if(f==="visiting"){let l=s.indexOf(c),p=[...s.slice(l),c];throw new tt({code:"CYCLE",message:`Document graph contains a cycle: ${p.join(" -> ")}`,documentIds:p})}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(t)].sort(et))a(c);return Object.freeze(i)};var cg=D().regex(/^sha256:[a-f0-9]{64}$/),If=L({format:W("webstudio-document-graph"),version:W(1),nodes:H(Xr),edges:H(eo),integrity:L({algorithm:W("sha256"),checksum:cg})});var ug=D().min(1).refine(e=>e.startsWith("/")===!1,{error:"Asset path must be relative"}).refine(e=>e.includes("\\")===!1&&e.split("/").every(t=>t.length>0&&t!==".."&&t!=="."),{error:"Asset path must be normalized and must not contain dot segments"}),Nf=L({_id:D().min(1),_type:W("asset.file"),name:D().min(1),description:D().optional(),path:ug,key:D(),folderId:D().min(1).optional(),extension:D().regex(/^[a-z0-9]*$/),mimeType:D().min(1),size:U().int().nonnegative(),createdAt:D().datetime().optional(),revision:D().min(1),contentRef:D().min(1),properties:Ne(D(),At()),excerpt:D().optional(),metadataError:L({code:D().min(1),message:D().min(1),reason:D().min(1).optional(),line:U().int().positive().optional(),column:U().int().positive().optional()}).optional()}),ii=Nf.partial().required({_id:!0}),lg=fe(["null","boolean","number","string","object","array"]),fg=Et({format:W("webstudio-builder-asset-field-catalog"),version:W(1),canonicalRevision:D().regex(/^sha256:[a-f0-9]{64}$/),documentCount:U().int().nonnegative(),fields:Ne(D().min(1),Et({queryPath:H(D().min(1)).min(1).max(N.fieldPathDepth).optional(),types:H(lg).min(1),occurrences:U().int().positive(),optional:W(!0).optional(),mixed:W(!0).optional()}))}).superRefine((e,t)=>{for(let[n,r]of Object.entries(e.fields)){let o=[...new Set(r.types)].sort();JSON.stringify(r.types)!==JSON.stringify(o)&&t.addIssue({code:"custom",path:["fields",n,"types"],message:"Observed field types must be unique and sorted"}),r.occurrences>e.documentCount&&t.addIssue({code:"custom",path:["fields",n,"occurrences"],message:"Field occurrences cannot exceed the document count"});let s=r.occurrences<e.documentCount;r.optional===!0!==s&&t.addIssue({code:"custom",path:["fields",n,"optional"],message:"Field optionality must match its occurrence count"});let i=o.length>1;r.mixed===!0!==i&&t.addIssue({code:"custom",path:["fields",n,"mixed"],message:"Mixed status must match the observed types"})}}),no=D().regex(/^sha256:[a-f0-9]{64}$/),zf=L({fields:H(H(D().min(1)).min(1).max(N.fieldPathDepth)).min(1).max(N.outputFieldCount+1),rows:H(H(At())).max(N.resultCount),totalCount:U().int().nonnegative().max(N.candidateDocuments),hasMore:pt()}).superRefine(({fields:e,rows:t},n)=>{for(let[r,o]of t.entries())o.length!==e.length&&n.addIssue({code:"custom",path:["rows",r],message:"Materialized query rows must match the field count"})}),Cf=L({format:W("webstudio-content-database"),version:W(1),assetRevision:no,documents:H(ii),documentGraph:If.optional(),contents:Ne(D().min(1),D()).optional(),assetPaths:Ne(D().min(1),D().min(1)).optional(),assetReferences:Ne(D().min(1),H(L({start:U().int().nonnegative(),end:U().int().positive(),assetId:D().min(1),suffix:D().min(1).optional()}).refine(({start:e,end:t})=>t>e,{message:"Markdown asset reference range must not be empty"}))).optional(),assetValueReferences:Ne(D().min(1),H(L({path:H(D().min(1).or(U().int().nonnegative())).min(1),assetId:D().min(1),suffix:D().min(1).optional(),structured:W(!0).optional()}))).optional(),fieldCatalog:fg,queries:Ne(no,zf).optional(),database:L({maxBytes:U().int().positive(),unboundedBytes:U().int().nonnegative(),sourceDocumentCount:U().int().nonnegative(),includedDocumentCount:U().int().nonnegative().optional()}).optional(),integrity:L({algorithm:W("sha256"),checksum:no})}).superRefine((e,t)=>{e.documents.length>N.candidateDocuments&&t.addIssue({code:"custom",path:["documents"],message:"Asset index exceeds the document limit"}),(e.fieldCatalog.canonicalRevision!==e.assetRevision||e.fieldCatalog.documentCount!==e.documents.length)&&t.addIssue({code:"custom",path:["fieldCatalog"],message:"Asset index field catalog does not match its documents"}),e.database!==void 0&&e.database.sourceDocumentCount<e.documents.length&&t.addIssue({code:"custom",path:["database","sourceDocumentCount"],message:"Source document count cannot be smaller than the database"}),e.database?.includedDocumentCount!==void 0&&(e.database.includedDocumentCount<e.documents.length||e.database.includedDocumentCount>e.database.sourceDocumentCount)&&t.addIssue({code:"custom",path:["database","includedDocumentCount"],message:"Included document count must match the database bounds"});let n;for(let[o,s]of e.documents.entries())n!==void 0&&s._id<=n&&t.addIssue({code:"custom",path:["documents",o,"_id"],message:"Asset index documents must have unique sorted IDs"}),n=s._id;let r=new Set(e.documents.flatMap(({contentRef:o})=>o===void 0?[]:[o]));for(let o of e.documentGraph?.nodes??[])r.add(o.contentRef);for(let o of Object.keys(e.contents??{}))r.has(o)===!1&&t.addIssue({code:"custom",path:["contents",o],message:"Embedded content must belong to an indexed document"});for(let o of Object.keys(e.assetReferences??{}))r.has(o)===!1&&t.addIssue({code:"custom",path:["assetReferences",o],message:"Asset references must belong to an indexed document"})}),dg=cn("mode",[L({mode:W("none")}),L({mode:W("full"),maxBytes:U().int().positive().max(N.hydratedFileBytes).optional()}),L({mode:W("range"),offset:U().int().nonnegative(),length:U().int().positive().max(N.hydratedRangeBytes)}),L({mode:W("markdown-body-ref"),maxBytes:U().int().positive().max(N.hydratedFileBytes).optional()})]),ai={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"]},$f=Object.keys(ai),Lf=["url","width","height"],ro=e=>Lf.includes(e),Pf=$f.filter(e=>ro(e)===!1&&e!=="excerpt"),Ff=Pf.filter(e=>e!=="id"),Mf=e=>Pf.includes(e),pg=fe($f),Xn=H(D().min(1)).min(1).max(N.fieldPathDepth).superRefine((e,t)=>{if(e[0]==="properties"){e.length<2&&t.addIssue({code:"custom",message:"A properties field path must select a property"});return}(e.length!==1||pg.safeParse(e[0]).success===!1)&&t.addIssue({code:"custom",message:"Asset query field path is unsupported"})}),si=pt().default(!0),mg=cn("mode",[L({mode:W("all"),includeMetadata:si}),L({mode:W("base"),includeMetadata:si}),L({mode:W("fields"),includeMetadata:si,fields:H(Xn).max(N.outputFieldCount).refine(e=>new Set(e.map(_f)).size===e.length,{error:"Selected output fields must be unique"})})]),hg={mode:"fields",includeMetadata:!1,fields:Lf.map(e=>[e])},Bf=["eq","ne","contains","startsWith","endsWith","gt","gte","lt","lte"],hS=[...Bf,"in","exists","isEmpty"],gg=L({field:Xn,operator:fe(Bf),value:At()}),yg=L({field:Xn,operator:W("in"),value:H(At()).max(N.resultCount)}),bg=L({field:Xn,operator:fe(["exists","isEmpty"]),value:pt()}),wg=cn("operator",[gg,yg,bg]),xg=Sf(wg,{maximumChildren:N.filterCount,maximumConditions:N.filterCount,maximumDepth:N.filterDepth,maximumConditionsMessage:"Asset query exceeds the filter limit",maximumDepthMessage:"Asset query exceeds the filter nesting limit"});var _g=xg,qf=e=>{let t=new Set(["eq","ne","in","exists"]);return e.some(n=>n==="string"||n==="array")&&t.add("contains"),e.includes("string")&&(t.add("startsWith"),t.add("endsWith")),e.some(n=>n==="string"||n==="number")&&(t.add("gt"),t.add("gte"),t.add("lt"),t.add("lte")),e.some(n=>n==="string"||n==="array"||n==="object")&&t.add("isEmpty"),[...t]},Sg=L({field:Xn,direction:fe(["asc","desc"])}),Eg=fe(["many","one","first","last"]),Ag=({output:e,content:t})=>e.includeMetadata||e.mode==="all"||e.mode==="fields"&&e.fields.length>0||t.mode!=="none",Rt=L({result:Eg.default("many"),where:_g.default({all:[]}),sort:H(Sg).max(N.sortCount).default([]),limit:U().int().nonnegative().max(N.resultCount).default(N.defaultResultCount),offset:U().int().nonnegative().max(N.candidateDocuments).default(0),output:mg.default(hg),content:dg.default({mode:"none"})}).superRefine((e,t)=>{Ag(e)===!1&&t.addIssue({code:"custom",message:"Select at least one asset query output"}),(e.result==="first"||e.result==="last")&&e.sort.length===0&&t.addIssue({code:"custom",path:["sort"],message:"Add sorting to define which item is first."})}),Zf=L({query:Rt,indexRevision:D().min(1).max(255).optional()}),kg=Et({_id:D().min(1),revision:D().min(1),contentRef:D().min(1),encoding:W("utf-8"),text:D(),range:Et({offset:U().int().nonnegative(),length:U().int().nonnegative(),total:U().int().nonnegative()}).optional()}),vg=kg.omit({_id:!0,revision:!0,contentRef:!0}),Uf=Nf.omit({_id:!0,_type:!0,contentRef:!0}).partial().extend({id:D().min(1),url:D().min(1).optional(),width:U().positive().optional(),height:U().positive().optional(),content:vg.optional()}).refine(e=>e.width===void 0==(e.height===void 0),{error:"Asset dimensions must include both width and height"}),Rg=L({format:W("webstudio-content-database"),version:W(1),revision:no,usedBytes:U().int().nonnegative(),maxBytes:U().int().positive(),unboundedBytes:U().int().nonnegative(),includedDocumentCount:U().int().nonnegative(),omittedDocumentCount:U().int().nonnegative(),omissionReason:fe(["size","unavailable"]).optional(),truncated:pt()}),Tf=Rg.pick({usedBytes:!0,maxBytes:!0,unboundedBytes:!0,includedDocumentCount:!0,omittedDocumentCount:!0,omissionReason:!0,truncated:!0}),ci=L({items:H(Uf),totalCount:U().int().nonnegative(),hasMore:pt()}),Dg=L({item:Uf.nullable(),totalCount:U().int().nonnegative()}),jf=an([ci,Dg]),Of=L({line:U().int().positive(),column:U().int().positive(),offset:U().int().nonnegative().optional()}),Ig=L({severity:fe(["error","warning"]),scope:fe(["query","database"]),phase:fe(["metadata","reference","source"]),code:D().min(1),message:D().min(1),assetId:D().min(1),path:D().min(1),line:U().int().positive().optional(),column:U().int().positive().optional(),reference:D().min(1).optional(),nodeType:D().min(1).optional(),reason:D().min(1).optional(),sourceRange:L({start:Of,end:Of}).optional()}),Cg=L({severity:fe(["error","warning"]),code:D().min(1),path:H(D()),message:D().min(1)}),Tg=L({scope:W("query-preview"),queryIssues:H(Cg).optional(),queryWarnings:H(D().min(1)).optional(),query:Tf,database:Tf,artifacts:L({query:Cf,database:Cf}).optional(),unresolved:jf.optional(),issues:H(Ig).optional(),issueCount:U().int().nonnegative().optional(),issuesTruncated:pt().optional()}),gS=L({data:jf,__diagnostics__:Tg}),Og=fe(["INVALID_REQUEST","REQUEST_CANCELLED","UNAUTHORIZED","FORBIDDEN","STALE_INDEX","CONTENT_IDENTITY_REQUIRED","CONTENT_NOT_TEXT","CONTENT_DECODING_FAILED","CONTENT_LIMIT_EXCEEDED","MULTIPLE_RESULTS","INTERNAL_ERROR"]),Ng=Et({ok:W(!1),error:Et({code:Og,message:D().min(1),retryable:pt(),details:Ne(D(),At()).optional()}),meta:Et({queryHash:D().min(1).optional(),indexRevision:D().min(1).optional(),assetRevision:D().min(1).optional()}).optional()}),Vf=({code:e,message:t,retryable:n=!1,details:r})=>Ng.parse({ok:!1,error:{code:e,message:t,retryable:n,details:r}});var Qf=function*(e){if(e.length>0&&!e.startsWith("/")||/~(?![01])/.test(e))throw Error("Invalid JSON Pointer");let t=1,n=0;for(;n<e.length;){let r=e.indexOf("/",t);n=r===-1?e.length:r;let o=e.slice(t,n);t=n+1,yield $g(o)}};var ui=(e,t)=>t+"/"+zg(e),zg=e=>e.toString().replace(/~/g,"~0").replace(/\//g,"~1"),$g=e=>e.toString().replace(/~1/g,"/").replace(/~0/g,"~");var oo=async(e,t,n)=>{if(Number.isSafeInteger(t)===!1||t<=0)throw new Error("Concurrency must be a positive safe integer");let r=0,o=new Array(e.length),s=async()=>{for(;r<e.length;){let u=r;r+=1,o[u]=await n(e[u])}},i=Array.from({length:Math.min(t,e.length)},s),c=(await Promise.allSettled(i)).find(u=>u.status==="rejected");if(c!==void 0)throw c.reason;return o},li=e=>e.reason??new DOMException("The operation was aborted","AbortError"),Gf=e=>{if(e?.aborted)throw li(e)},dn=async(e,t)=>t===void 0?await e:await new Promise((n,r)=>{let o=()=>t.removeEventListener("abort",s),s=()=>{o(),r(li(t))};t.addEventListener("abort",s,{once:!0}),Promise.resolve(e).then(i=>{o(),n(i)},i=>{o(),r(i)}),t.aborted&&s()}),so=({concurrency:e,signal:t})=>{if(Number.isSafeInteger(e)===!1||e<=0)throw new TypeError("Concurrency must be a positive safe integer");let n=0,r=[],o=async()=>{if(Gf(t),n<e){n+=1;return}await new Promise((i,a)=>{let c,u=()=>{let f=r.indexOf(c);f!==-1&&r.splice(f,1),t!==void 0&&a(li(t))};c={start:()=>{t?.removeEventListener("abort",u),i()}},r.push(c),t?.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 Gf(t),await i()}finally{s()}}};var pn=e=>typeof e=="object"&&e!==null&&Array.isArray(e)===!1,io=e=>{if(pn(e)===!1)return;let t=Object.keys(e);if(!(t.length!==1||t[0]!=="$ref"))return e.$ref};var De=class extends Error{code;referenceId;constructor({code:t,message:n,referenceId:r,cause:o}){super(n,{cause:o}),this.name="JsonDocumentError",this.code=t,this.referenceId=r}},Lg=(e,t)=>{let n=io(e);if(n!==void 0){if(typeof n!="string")throw new De({code:"INVALID_REFERENCE_MARKER",message:`JSON reference marker ${t} must contain a string $ref`,referenceId:t});return n}},Pg=e=>`#${e}`;var Jf=async({source:e,maximumBytes:t=N.hydratedFileBytes})=>{let n;try{n=await Xe(e,t)}catch(o){throw o instanceof we?new De({code:"CONTENT_LIMIT_EXCEEDED",message:"JSON document exceeds the byte limit",cause:o}):o}let r;try{r=ln(ve(n))}catch(o){throw new De({code:"CONTENT_DECODING_FAILED",message:"JSON document is not valid UTF-8",cause:o})}try{return vt(JSON.parse(r))}catch(o){throw new De({code:"INVALID_DOCUMENT",message:"JSON document is invalid",cause:o})}};var Fg=(e,t)=>{let n=e;for(let r of t){if(Array.isArray(n)){let o=Number(r);if(Number.isSafeInteger(o)===!1||o<0||String(o)!==r||o>=n.length)return;n=n[o];continue}if(pn(n)&&Object.hasOwn(n,r)){n=n[r];continue}return}return n},Wf=({document:e,representation:t})=>{let n=vt(e);if(t.type==="document")return n;if(t.type!=="json")throw new De({code:"UNSUPPORTED_REPRESENTATION",message:`JSON documents do not support ${t.type}`});let r=Fg(n,t.path);if(r===void 0)throw new De({code:"JSON_PATH_NOT_FOUND",message:"JSON document path does not exist"});return r},Mg=(e,t,n)=>{Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})},ao=({document:e,references:t,allowUnresolvedReferences:n=!1})=>{let r=vt(e),o=new Set,s=(a,c)=>{let u=Pg(c);if(Lg(a,u)!==void 0){if(t.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 vt(t.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,p)=>s(l,ui(String(p),c)));if(pn(a)){let l={};for(let[p,d]of Object.entries(a))Mg(l,p,s(d,ui(p,c)));return l}return a},i=s(r,"");for(let a of[...t.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 co=Symbol.for("yaml.alias"),uo=Symbol.for("yaml.document"),Ue=Symbol.for("yaml.map"),fi=Symbol.for("yaml.pair"),Ie=Symbol.for("yaml.scalar"),mt=Symbol.for("yaml.seq"),xe=Symbol.for("yaml.node.type"),ze=e=>!!e&&typeof e=="object"&&e[xe]===co,nt=e=>!!e&&typeof e=="object"&&e[xe]===uo,$e=e=>!!e&&typeof e=="object"&&e[xe]===Ue,j=e=>!!e&&typeof e=="object"&&e[xe]===fi,B=e=>!!e&&typeof e=="object"&&e[xe]===Ie,Le=e=>!!e&&typeof e=="object"&&e[xe]===mt;function K(e){if(e&&typeof e=="object")switch(e[xe]){case Ue:case mt:return!0}return!1}function V(e){if(e&&typeof e=="object")switch(e[xe]){case co:case Ue:case Ie:case mt:return!0}return!1}var lo=e=>(B(e)||K(e))&&!!e.anchor;var Ae=Symbol("break visit"),Kf=Symbol("skip children"),rt=Symbol("remove node");function ot(e,t){let n=Hf(t);nt(e)?mn(null,e.contents,n,Object.freeze([e]))===rt&&(e.contents=null):mn(null,e,n,Object.freeze([]))}ot.BREAK=Ae;ot.SKIP=Kf;ot.REMOVE=rt;function mn(e,t,n,r){let o=Yf(e,t,n,r);if(V(o)||j(o))return Xf(e,r,o),mn(e,o,n,r);if(typeof o!="symbol"){if(K(t)){r=Object.freeze(r.concat(t));for(let s=0;s<t.items.length;++s){let i=mn(s,t.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===Ae)return Ae;i===rt&&(t.items.splice(s,1),s-=1)}}}else if(j(t)){r=Object.freeze(r.concat(t));let s=mn("key",t.key,n,r);if(s===Ae)return Ae;s===rt&&(t.key=null);let i=mn("value",t.value,n,r);if(i===Ae)return Ae;i===rt&&(t.value=null)}}return o}async function fo(e,t){let n=Hf(t);nt(e)?await hn(null,e.contents,n,Object.freeze([e]))===rt&&(e.contents=null):await hn(null,e,n,Object.freeze([]))}fo.BREAK=Ae;fo.SKIP=Kf;fo.REMOVE=rt;async function hn(e,t,n,r){let o=await Yf(e,t,n,r);if(V(o)||j(o))return Xf(e,r,o),hn(e,o,n,r);if(typeof o!="symbol"){if(K(t)){r=Object.freeze(r.concat(t));for(let s=0;s<t.items.length;++s){let i=await hn(s,t.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===Ae)return Ae;i===rt&&(t.items.splice(s,1),s-=1)}}}else if(j(t)){r=Object.freeze(r.concat(t));let s=await hn("key",t.key,n,r);if(s===Ae)return Ae;s===rt&&(t.key=null);let i=await hn("value",t.value,n,r);if(i===Ae)return Ae;i===rt&&(t.value=null)}}return o}function Hf(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Yf(e,t,n,r){if(typeof n=="function")return n(e,t,r);if($e(t))return n.Map?.(e,t,r);if(Le(t))return n.Seq?.(e,t,r);if(j(t))return n.Pair?.(e,t,r);if(B(t))return n.Scalar?.(e,t,r);if(ze(t))return n.Alias?.(e,t,r)}function Xf(e,t,n){let r=t[t.length-1];if(K(r))r.items[e]=n;else if(j(r))e==="key"?r.key=n:r.value=n;else if(nt(r))r.contents=n;else{let o=ze(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}var Bg={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},qg=e=>e.replace(/[!,[\]{}]/g,t=>Bg[t]),st=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),o=r.shift();switch(o){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[s,i]=r;return this.tags[s]=i,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=r;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let i=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,i),!1}}default:return n(0,`Unknown directive ${o}`,!0),!1}}tagName(t,n){if(t==="!")return"!";if(t[0]!=="!")return n(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let i=t.slice(2,-1);return i==="!"||i==="!!"?(n(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&n("Verbatim tags must end with a >"),i)}let[,r,o]=t.match(/^(.*!)([^!]*)$/s);o||n(`The ${t} tag has no suffix`);let s=this.tags[r];if(s)try{return s+decodeURIComponent(o)}catch(i){return n(String(i)),null}return r==="!"?t:(n(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[n,r]of Object.entries(this.tags))if(t.startsWith(r))return n+qg(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),o;if(t&&r.length>0&&V(t.contents)){let s={};ot(t.contents,(i,a)=>{V(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:"||(!t||o.some(a=>a.startsWith(i)))&&n.push(`%TAG ${s} ${i}`);return n.join(`+`)}};st.defaultYaml={explicit:!1,version:"1.2"};st.defaultTags={"!!":"tag:yaml.org,2002:"};function po(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(n)}return!0}function di(e){let t=new Set;return ot(e,{Value(n,r){r.anchor&&t.add(r.anchor)}}),t}function pi(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function ed(e,t){let n=[],r=new Map,o=null;return{onAnchor:s=>{n.push(s),o??(o=di(e));let i=pi(t,o);return o.add(i),i},setAnchors:()=>{for(let s of n){let i=r.get(s);if(typeof i=="object"&&i.anchor&&(B(i.node)||K(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 Dt(e,t,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let o=0,s=r.length;o<s;++o){let i=r[o],a=Dt(e,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=Dt(e,r,o,s);i===void 0?r.delete(o):i!==s&&r.set(o,i)}else if(r instanceof Set)for(let o of Array.from(r)){let s=Dt(e,r,o,o);s===void 0?r.delete(o):s!==o&&(r.delete(o),r.add(s))}else for(let[o,s]of Object.entries(r)){let i=Dt(e,r,o,s);i===void 0?delete r[o]:i!==s&&(r[o]=i)}return e.call(t,n,r)}function le(e,t,n){if(Array.isArray(e))return e.map((r,o)=>le(r,String(o),n));if(e&&typeof e.toJSON=="function"){if(!n||!lo(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=s=>{r.res=s,delete n.onCreate};let o=e.toJSON(t,n);return n.onCreate&&n.onCreate(o),o}return typeof e=="bigint"&&!n?.keep?Number(e):e}var It=class{constructor(t){Object.defineProperty(this,xe,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:n,maxAliasCount:r,onAnchor:o,reviver:s}={}){if(!nt(t))throw new TypeError("A document argument is required");let i={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=le(this,"",i);if(typeof o=="function")for(let{count:c,res:u}of i.anchors.values())o(u,c);return typeof s=="function"?Dt(s,{"":a},"",a):a}};var ht=class extends It{constructor(t){super(co),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],ot(t,{Node:(s,i)=>{(ze(i)||lo(i))&&r.push(i)}}),n&&(n.aliasResolveCache=r));let o;for(let s of r){if(s===this)break;s.anchor===this.source&&(o=s)}return o}toJSON(t,n){if(!n)return{source:this.source};let{anchors:r,doc:o,maxAliasCount:s}=n,i=this.resolve(o,n);if(!i){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=r.get(i);if(a||(le(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=mo(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(t,n,r){let o=`*${this.source}`;if(t){if(po(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(t.implicitKey)return`${o} `}return o}};function mo(e,t,n){if(ze(t)){let r=t.resolve(e),o=n&&r&&n.get(r);return o?o.count*o.aliasCount:0}else if(K(t)){let r=0;for(let o of t.items){let s=mo(e,o,n);s>r&&(r=s)}return r}else if(j(t)){let r=mo(e,t.key,n),o=mo(e,t.value,n);return Math.max(r,o)}return 1}var ho=e=>!e||typeof e!="function"&&typeof e!="object",T=class extends It{constructor(t){super(Ie),this.value=t}toJSON(t,n){return n?.keep?this.value:le(this.value,t,n)}toString(){return String(this.value)}};T.BLOCK_FOLDED="BLOCK_FOLDED";T.BLOCK_LITERAL="BLOCK_LITERAL";T.PLAIN="PLAIN";T.QUOTE_DOUBLE="QUOTE_DOUBLE";T.QUOTE_SINGLE="QUOTE_SINGLE";var Zg="tag:yaml.org,2002:";function Ug(e,t,n){if(t){let r=n.filter(s=>s.tag===t),o=r.find(s=>!s.format)??r[0];if(!o)throw new Error(`Tag ${t} not found`);return o}return n.find(r=>r.identify?.(e)&&!r.format)}function gt(e,t,n){if(nt(e)&&(e=e.contents),V(e))return e;if(j(e)){let l=n.schema[Ue].createNode?.(n.schema,null,n);return l.items.push(e),l}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:o,onTagObj:s,schema:i,sourceObjects:a}=n,c;if(r&&e&&typeof e=="object"){if(c=a.get(e),c)return c.anchor??(c.anchor=o(e)),new ht(c.anchor);c={anchor:null,node:null},a.set(e,c)}t?.startsWith("!!")&&(t=Zg+t.slice(2));let u=Ug(e,t,i.tags);if(!u){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let l=new T(e);return c&&(c.node=l),l}u=e instanceof Map?i[Ue]:Symbol.iterator in Object(e)?i[mt]:i[Ue]}s&&(s(u),delete n.onTagObj);let f=u?.createNode?u.createNode(n.schema,e,n):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(n.schema,e,n):new T(e);return t?f.tag=t:u.default||(f.tag=u.tag),c&&(c.node=f),f}function er(e,t,n){let r=n;for(let o=t.length-1;o>=0;--o){let s=t[o];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let i=[];i[s]=r,r=i}else r=new Map([[s,r]])}return gt(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var yn=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,gn=class extends It{constructor(t,n){super(t),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(t){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(n.schema=t),n.items=n.items.map(r=>V(r)||j(r)?r.clone(t):r),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(yn(t))this.add(n);else{let[r,...o]=t,s=this.get(r,!0);if(K(s))s.addIn(o,n);else if(s===void 0&&this.schema)this.set(r,er(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}deleteIn(t){let[n,...r]=t;if(r.length===0)return this.delete(n);let o=this.get(n,!0);if(K(o))return o.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(t,n){let[r,...o]=t,s=this.get(r,!0);return o.length===0?!n&&B(s)?s.value:s:K(s)?s.getIn(o,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!j(n))return!1;let r=n.value;return r==null||t&&B(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[n,...r]=t;if(r.length===0)return this.has(n);let o=this.get(n,!0);return K(o)?o.hasIn(r):!1}setIn(t,n){let[r,...o]=t;if(o.length===0)this.set(r,n);else{let s=this.get(r,!0);if(K(s))s.setIn(o,n);else if(s===void 0&&this.schema)this.set(r,er(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}};var td=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Pe(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var it=(e,t,n)=>e.endsWith(`+`)?Pe(n,t):n.includes(``)?`-`+we(n,e):(t.endsWith(" ")?"":" ")+n;var bs="flow",Cr="block",Rn="quoted";function kn(t,e,n="flow",{indentAtStart:r,lineWidth:o=80,minContentWidth:s=20,onFold:i,onOverflow:a}={}){if(!o||o<0)return t;o<s&&(s=0);let c=Math.max(1+s,1+o-e.length);if(t.length<=c)return t;let u=[],d={},l=o-e.length;typeof r=="number"&&(r>o-Math.max(2,s)?u.push(0):l=o-r);let f,p,g=!1,m=-1,h=-1,y=-1;n===Cr&&(m=Zl(t,m,e.length),m!==-1&&(l=m+c));for(let S;S=t[m+=1];){if(n===Rn&&S==="\\"){switch(h=m,t[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}y=m}if(S===`-`)n===Cr&&(m=Zl(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===Rn){for(;p===" "||p===" ";)p=S,S=t[m+=1],g=!0;let _=m>y+1?m-2:h-1;if(d[_])return t;u.push(_),d[_]=!0,l=_+c,f=void 0}else g=!0}p=S}if(g&&a&&a(),u.length===0)return t;i&&i();let x=t.slice(0,u[0]);for(let S=0;S<u.length;++S){let _=u[S],b=u[S+1]||t.length;_===0?x=`-${e}${t.slice(0,b)}`:(n===Rn&&d[_]&&(x+=`${t[_]}\\`),x+=`-${e}${t.slice(_+1,b)}`)}return x}function Zl(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 Nr=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),$r=t=>/^(%|---|\.\.\.)/m.test(t);function oh(t,e,n){if(!e||e<0)return!1;let r=e-n,o=t.length;if(o<=r)return!1;for(let s=0,i=0;s<o;++s)if(t[s]===`-`){if(s-i>r)return!0;if(i=s+1,o-i<=r)return!1}return!0}function In(t,e){let n=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=e,o=e.options.doubleQuotedMinMultiLineLength,s=e.indent||($r(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)+`+`+Pe(n,t):(e.endsWith(" ")?"":" ")+n;var mi="flow",go="block",tr="quoted";function nr(e,t,n="flow",{indentAtStart:r,lineWidth:o=80,minContentWidth:s=20,onFold:i,onOverflow:a}={}){if(!o||o<0)return e;o<s&&(s=0);let c=Math.max(1+s,1+o-t.length);if(e.length<=c)return e;let u=[],f={},l=o-t.length;typeof r=="number"&&(r>o-Math.max(2,s)?u.push(0):l=o-r);let p,d,w=!1,h=-1,y=-1,m=-1;n===go&&(h=nd(e,h,t.length),h!==-1&&(l=h+c));for(let S;S=e[h+=1];){if(n===tr&&S==="\\"){switch(y=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}m=h}if(S===`+`)n===go&&(h=nd(e,h,t.length)),l=h+t.length+c,p=void 0;else{if(S===" "&&d&&d!==" "&&d!==`+`&&d!==" "){let E=e[h+1];E&&E!==" "&&E!==`+`&&E!==" "&&(p=h)}if(h>=l)if(p)u.push(p),l=p+c,p=void 0;else if(n===tr){for(;d===" "||d===" ";)d=S,S=e[h+=1],w=!0;let E=h>m+1?h-2:y-1;if(f[E])return e;u.push(E),f[E]=!0,l=E+c,p=void 0}else w=!0}d=S}if(w&&a&&a(),u.length===0)return e;i&&i();let A=e.slice(0,u[0]);for(let S=0;S<u.length;++S){let E=u[S],_=u[S+1]||e.length;E===0?A=`+${t}${e.slice(0,_)}`:(n===tr&&f[E]&&(A+=`${e[E]}\\`),A+=`+${t}${e.slice(E+1,_)}`)}return A}function nd(e,t,n){let r=t,o=t+1,s=e[o];for(;s===" "||s===" ";)if(t<o+n)s=e[++t];else{do s=e[++t];while(s&&s!==`+`);r=t,o=t+1,s=e[o]}return r}var bo=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),wo=e=>/^(%|---|\.\.\.)/m.test(e);function jg(e,t,n){if(!t||t<0)return!1;let r=t-n,o=e.length;if(o<=r)return!1;for(let s=0,i=0;s<o;++s)if(e[s]===`+`){if(s-i>r)return!0;if(i=s+1,o-i<=r)return!1}return!0}function rr(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,o=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(wo(e)?" ":""),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 f=n.substr(c+2,4);switch(f){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:f.substr(0,2)==="00"?i+="\\x"+f.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:kn(i,s,Rn,Nr(e,!1))}function ws(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`-`)||/[ \t]\n|\n[ \t]/.test(t))return In(t,e);let n=e.indent||($r(t)?" ":""),r="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&-${n}`)+"'";return e.implicitKey?r:kn(r,n,bs,Nr(e,!1))}function Qt(t,e){let{singleQuote:n}=e.options,r;if(n===!1)r=In;else{let o=t.includes('"'),s=t.includes("'");o&&!s?r=ws:s&&!o?r=In:r=n?ws:In}return r(t,e)}var _s;try{_s=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:nr(i,s,tr,bo(t,!1))}function hi(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`+`)||/[ \t]\n|\n[ \t]/.test(e))return rr(e,t);let n=t.indent||(wo(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&+${n}`)+"'";return t.implicitKey?r:nr(r,n,mi,bo(t,!1))}function bn(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=rr;else{let o=e.includes('"'),s=e.includes("'");o&&!s?r=hi:s&&!o?r=rr:r=n?hi:rr}return r(e,t)}var gi;try{gi=new RegExp(`(^|(?<!))+(?!-|$)`,"g")}catch{_s=/\n+(?!\n|$)/g}function Tr({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 Qt(n,r);let u=r.indent||(r.forceBlockIndent||$r(n)?" ":""),d=i==="literal"?!0:i==="folded"||e===R.BLOCK_FOLDED?!1:e===R.BLOCK_LITERAL?!0:!oh(n,c,u.length);if(!n)return d?`|+|$)`,"g")}catch{gi=/\n+(?!\n|$)/g}function yo({comment:e,type:t,value:n},r,o,s){let{blockQuote:i,commentString:a,lineWidth:c}=r.options;if(!i||/\n[\t ]+$/.test(n))return bn(n,r);let u=r.indent||(r.forceBlockIndent||wo(n)?" ":""),f=i==="literal"?!0:i==="folded"||t===T.BLOCK_FOLDED?!1:t===T.BLOCK_LITERAL?!0:!jg(n,c,u.length);if(!n)return f?`|`:`>-`;let l,f;for(f=n.length;f>0;--f){let b=n[f-1];if(b!==`-`&&b!==" "&&b!==" ")break}let p=n.substring(f),g=p.indexOf(`-`);g===-1?l="-":n===p||g!==p.length-1?(l="+",s&&s()):l="",p&&(n=n.slice(0,-p.length),p[p.length-1]===`-`&&(p=p.slice(0,-1)),p=p.replace(_s,`$&${u}`));let m=!1,h,y=-1;for(h=0;h<n.length;++h){let b=n[h];if(b===" ")m=!0;else if(b===`-`)y=h;else break}let x=n.substring(0,y<h?y+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 b=n.replace(/\n+/g,`-$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`),A=!1,D=Nr(r,!0);i!=="folded"&&e!==R.BLOCK_FOLDED&&(D.onOverflow=()=>{A=!0});let E=kn(`${x}${b}${p}`,u,Cr,D);if(!A)return`>${_}-${u}${E}`}return n=n.replace(/\n+/g,`$&${u}`),`|${_}-${u}${x}${n}${p}`}function sh(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 Qt(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||d||!s.includes(`-`)?Qt(s,e):Tr(t,e,n,r);if(!a&&!d&&o!==R.PLAIN&&s.includes(`-`))return Tr(t,e,n,r);if($r(s)){if(c==="")return e.forceBlockIndent=!0,Tr(t,e,n,r);if(a&&c===u)return Qt(s,e)}let l=s.replace(/\n+/g,`$&-${c}`);if(i){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(l),{compat:p,tags:g}=e.doc.schema;if(g.some(f)||p?.some(f))return Qt(s,e)}return a?l:kn(l,c,bs,Nr(e,!1))}function xt(t,e,n,r){let{implicitKey:o,inFlow:s}=e,i=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==R.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(i.value)&&(a=R.QUOTE_DOUBLE);let c=d=>{switch(d){case R.BLOCK_FOLDED:case R.BLOCK_LITERAL:return o||s?Qt(i.value,e):Tr(i,e,n,r);case R.QUOTE_DOUBLE:return In(i.value,e);case R.QUOTE_SINGLE:return ws(i.value,e);case R.PLAIN:return sh(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 zr(t,e){let n=Object.assign({blockQuote:!0,commentString:Fl,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 ih(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 ah(t,e,{anchors:n,doc:r}){if(!r.directives)return"";let o=[],s=(T(t)||B(t))&&t.anchor;s&&kr(s)&&(n.add(s),o.push(`&${s}`));let i=t.tag??(e.default?null:e.tag);return i&&o.push(r.directives.tagString(i)),o.join(" ")}function Ye(t,e,n,r){if($(t))return t.toString(e,n,r);if(ye(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let o,s=z(t)?t:e.doc.createNode(t,{onTagObj:c=>o=c});o??(o=ih(e.doc.schema.tags,s));let i=ah(s,o,e);i.length>0&&(e.indentAtStart=(e.indentAtStart??0)+i.length+1);let a=typeof o.stringify=="function"?o.stringify(s,e,n,r):T(s)?xt(s,e,n,r):s.toString(e,n,r);return i?T(s)||a[0]==="{"||a[0]==="["?`${i} ${a}`:`${i}-${e.indent}${a}`:a}function Bl({key:t,value:e},n,r,o){let{allNullValues:s,doc:i,indent:a,indentStep:c,options:{commentString:u,indentSeq:d,simpleKeys:l}}=n,f=z(t)&&t.comment||null;if(l){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(B(t)||!z(t)&&typeof t=="object"){let D="With simple keys, collection cannot be used as a key value";throw new Error(D)}}let p=!l&&(!t||f&&e==null&&!n.inFlow||B(t)||(T(t)?t.type===R.BLOCK_FOLDED||t.type===R.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(l||!s),indent:a+c});let g=!1,m=!1,h=Ye(t,n,()=>g=!0,()=>m=!0);if(!p&&!n.inFlow&&h.length>1024){if(l)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(n.inFlow){if(s||e==null)return g&&r&&r(),h===""?"?":p?`? ${h}`:h}else if(s&&!l||e==null&&p)return h=`? ${h}`,f&&!g?h+=Be(h,n.indent,u(f)):m&&o&&o(),h;g&&(f=null),p?(f&&(h+=Be(h,n.indent,u(f))),h=`? ${h}-${a}:`):(h=`${h}:`,f&&(h+=Be(h,n.indent,u(f))));let y,x,S;z(e)?(y=!!e.spaceBefore,x=e.commentBefore,S=e.comment):(y=!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&&be(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let _=!1,b=Ye(e,n,()=>_=!0,()=>m=!0),A=" ";if(f||y||x){if(A=y?`-`:"",x){let D=u(x);A+=`-${we(D,n.indent)}`}b===""&&!n.inFlow?A===`-`&&S&&(A=`+`;let l,p;for(p=n.length;p>0;--p){let _=n[p-1];if(_!==`+`&&_!==" "&&_!==" ")break}let d=n.substring(p),w=d.indexOf(`+`);w===-1?l="-":n===d||w!==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(gi,`$&${u}`));let h=!1,y,m=-1;for(y=0;y<n.length;++y){let _=n[y];if(_===" ")h=!0;else if(_===`+`)m=y;else break}let A=n.substring(0,m<y?m+1:y);A&&(n=n.substring(A.length),A=A.replace(/\n+/g,`$&${u}`));let E=(h?u?"2":"1":"")+l;if(e&&(E+=" "+a(e.replace(/ ?[\r\n]+/g," ")),o&&o()),!f){let _=n.replace(/\n+/g,`+$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`),x=!1,R=bo(r,!0);i!=="folded"&&t!==T.BLOCK_FOLDED&&(R.onOverflow=()=>{x=!0});let v=nr(`${A}${_}${d}`,u,go,R);if(!x)return`>${E}+${u}${v}`}return n=n.replace(/\n+/g,`$&${u}`),`|${E}+${u}${A}${n}${d}`}function Vg(e,t,n,r){let{type:o,value:s}=e,{actualString:i,implicitKey:a,indent:c,indentStep:u,inFlow:f}=t;if(a&&s.includes(`+`)||f&&/[[\]{},]/.test(s))return bn(s,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||f||!s.includes(`+`)?bn(s,t):yo(e,t,n,r);if(!a&&!f&&o!==T.PLAIN&&s.includes(`+`))return yo(e,t,n,r);if(wo(s)){if(c==="")return t.forceBlockIndent=!0,yo(e,t,n,r);if(a&&c===u)return bn(s,t)}let l=s.replace(/\n+/g,`$&+${c}`);if(i){let p=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(l),{compat:d,tags:w}=t.doc.schema;if(w.some(p)||d?.some(p))return bn(s,t)}return a?l:nr(l,c,mi,bo(t,!1))}function Qt(e,t,n,r){let{implicitKey:o,inFlow:s}=t,i=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:a}=e;a!==T.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(i.value)&&(a=T.QUOTE_DOUBLE);let c=f=>{switch(f){case T.BLOCK_FOLDED:case T.BLOCK_LITERAL:return o||s?bn(i.value,t):yo(i,t,n,r);case T.QUOTE_DOUBLE:return rr(i.value,t);case T.QUOTE_SINGLE:return hi(i.value,t);case T.PLAIN:return Vg(i,t,n,r);default:return null}},u=c(a);if(u===null){let{defaultKeyType:f,defaultStringType:l}=t.options,p=o&&f||l;if(u=c(p),u===null)throw new Error(`Unsupported default string type ${p}`)}return u}function xo(e,t){let n=Object.assign({blockQuote:!0,commentString:td,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:r,options:n}}function Qg(e,t){if(t.tag){let o=e.filter(s=>s.tag===t.tag);if(o.length>0)return o.find(s=>s.format===t.format)??o[0]}let n,r;if(B(t)){r=t.value;let o=e.filter(s=>s.identify?.(r));if(o.length>1){let s=o.filter(i=>i.test);s.length>0&&(o=s)}n=o.find(s=>s.format===t.format)??o.find(s=>!s.format)}else r=t,n=e.find(o=>o.nodeClass&&r instanceof o.nodeClass);if(!n){let o=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${o} value`)}return n}function Gg(e,t,{anchors:n,doc:r}){if(!r.directives)return"";let o=[],s=(B(e)||K(e))&&e.anchor;s&&po(s)&&(n.add(s),o.push(`&${s}`));let i=e.tag??(t.default?null:t.tag);return i&&o.push(r.directives.tagString(i)),o.join(" ")}function yt(e,t,n,r){if(j(e))return e.toString(t,n,r);if(ze(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let o,s=V(e)?e:t.doc.createNode(e,{onTagObj:c=>o=c});o??(o=Qg(t.doc.schema.tags,s));let i=Gg(s,o,t);i.length>0&&(t.indentAtStart=(t.indentAtStart??0)+i.length+1);let a=typeof o.stringify=="function"?o.stringify(s,t,n,r):B(s)?Qt(s,t,n,r):s.toString(t,n,r);return i?B(s)||a[0]==="{"||a[0]==="["?`${i} ${a}`:`${i}+${t.indent}${a}`:a}function rd({key:e,value:t},n,r,o){let{allNullValues:s,doc:i,indent:a,indentStep:c,options:{commentString:u,indentSeq:f,simpleKeys:l}}=n,p=V(e)&&e.comment||null;if(l){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(K(e)||!V(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let d=!l&&(!e||p&&t==null&&!n.inFlow||K(e)||(B(e)?e.type===T.BLOCK_FOLDED||e.type===T.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!d&&(l||!s),indent:a+c});let w=!1,h=!1,y=yt(e,n,()=>w=!0,()=>h=!0);if(!d&&!n.inFlow&&y.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||t==null)return w&&r&&r(),y===""?"?":d?`? ${y}`:y}else if(s&&!l||t==null&&d)return y=`? ${y}`,p&&!w?y+=it(y,n.indent,u(p)):h&&o&&o(),y;w&&(p=null),d?(p&&(y+=it(y,n.indent,u(p))),y=`? ${y}+${a}:`):(y=`${y}:`,p&&(y+=it(y,n.indent,u(p))));let m,A,S;V(t)?(m=!!t.spaceBefore,A=t.commentBefore,S=t.comment):(m=!1,A=null,S=null,t&&typeof t=="object"&&(t=i.createNode(t))),n.implicitKey=!1,!d&&!p&&B(t)&&(n.indentAtStart=y.length+1),h=!1,!f&&c.length>=2&&!n.inFlow&&!d&&Le(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let E=!1,_=yt(t,n,()=>E=!0,()=>h=!0),x=" ";if(p||m||A){if(x=m?`+`:"",A){let R=u(A);x+=`+${Pe(R,n.indent)}`}_===""&&!n.inFlow?x===`+`&&S&&(x=`-`):A+=`-${n.indent}`}else if(!p&&B(e)){let D=b[0],E=b.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=b.indexOf(" ");D==="&"&&L!==-1&&L<E&&b[L+1]==="!"&&(L=b.indexOf(" ",L+1)),(L===-1||E<L)&&(G=!0)}G||(A=`-${n.indent}`)}}else(b===""||b[0]===`-`)&&(A="");return h+=A+b,n.inFlow?_&&r&&r():S&&!_?h+=Be(h,n.indent,u(S)):m&&o&&o(),h}function Es(t,e){(t==="debug"||t==="warn")&&console.warn(e)}var Pr="<<",De={identify:t=>t===Pr||typeof t=="symbol"&&t.description===Pr,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new R(Symbol(Pr)),{addToJSMap:Ss}),stringify:()=>Pr},jl=(t,e)=>(De.identify(e)||T(e)&&(!e.type||e.type===R.PLAIN)&&De.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===De.tag&&n.default);function Ss(t,e,n){let r=Ul(t,n);if(be(r))for(let o of r.items)xs(t,e,o);else if(Array.isArray(r))for(let o of r)xs(t,e,o);else xs(t,e,r)}function xs(t,e,n){let r=Ul(t,n);if(!ge(r))throw new Error("Merge sources must be maps or map aliases");let o=r.toJSON(null,t,Map);for(let[s,i]of o)e instanceof Map?e.has(s)||e.set(s,i):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:i,writable:!0,enumerable:!0,configurable:!0});return e}function Ul(t,e){return t&&ye(e)?e.resolve(t.doc,t):e}function Lr(t,e,{key:n,value:r}){if(z(n)&&n.addToJSMap)n.addToJSMap(t,e,r);else if(jl(t,n))Ss(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=ch(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 ch(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(z(t)&&n?.doc){let r=zr(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)+'..."'),Es(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 Vt(t,e,n){let r=We(t,void 0,n),o=We(e,void 0,n);return new K(r,o)}var K=class t{constructor(e,n=null){Object.defineProperty(this,ie,{value:hs}),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 Lr(n,r,this)}toString(e,n,r){return e?.doc?Bl(this,e,n,r):JSON.stringify(this)}};function Fr(t,e,n){return(e.inFlow??t.flow?lh:uh)(t,e,n)}function uh({comment:t,items:e},n,{blockItemPrefix:r,flowChars:o,itemIndent:s,onChompKeep:i,onComment:a}){let{indent:c,options:{commentString:u}}=n,d=Object.assign({},n,{indent:s,type:null}),l=!1,f=[];for(let g=0;g<e.length;++g){let m=e[g],h=null;if(z(m))!l&&m.spaceBefore&&f.push(""),Mr(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(""),Mr(n,f,x.commentBefore,l))}l=!1;let y=Ye(m,d,()=>h=null,()=>l=!0);h&&(y+=Be(y,s,u(h))),l&&h&&(l=!1),f.push(r+y)}let p;if(f.length===0)p=o.start+o.end;else{p=f[0];for(let g=1;g<f.length;++g){let m=f[g];p+=m?`-${c}${m}`:`-`}}return t?(p+=`-`+we(u(t),c),a&&a()):l&&i&&i(),p}function lh({items:t},e,{flowChars:n,itemIndent:r}){let{indent:o,indentStep:s,flowCollectionPadding:i,options:{commentString:a}}=e;r+=s;let c=Object.assign({},e,{indent:r,inFlow:!0,type:null}),u=!1,d=0,l=[];for(let g=0;g<t.length;++g){let m=t[g],h=null;if(z(m))m.spaceBefore&&l.push(""),Mr(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(""),Mr(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 y=Ye(m,c,()=>h=null);u||(u=l.length>d||y.includes(`-`)),g<t.length-1?y+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(u||(u=l.reduce((x,S)=>x+S.length+2,2)+(y.length+2)>e.options.lineWidth)),u&&(y+=",")),h&&(y+=Be(y,r,a(h))),l.push(y),d=l.length}let{start:f,end:p}=n;if(l.length===0)return f+p;if(!u){let g=l.reduce((m,h)=>m+h.length+2,2);u=e.options.lineWidth>0&&g>e.options.lineWidth}if(u){let g=f;for(let m of l)g+=m?`-${s}${o}${m}`:`-`;return`${g}-${o}${p}`}else return`${f}${i}${l.join(" ")}${i}${p}`}function Mr({indent:t,options:{commentString:e}},n,r,o){if(r&&o&&(r=r.replace(/^\n+/,"")),r){let s=we(e(r),t);n.push(s.trimStart())}}function ut(t,e){let n=T(e)?e.value:e;for(let r of t)if($(r)&&(r.key===e||r.key===n||T(r.key)&&r.key.value===n))return r}var W=class extends jt{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(ve,e),this.items=[]}static from(e,n,r){let{keepUndefined:o,replacer:s}=r,i=new this(e),a=(c,u)=>{if(typeof s=="function")u=s.call(n,c,u);else if(Array.isArray(s)&&!s.includes(c))return;(u!==void 0||o)&&i.items.push(Vt(c,u,r))};if(n instanceof Map)for(let[c,u]of n)a(c,u);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&i.items.sort(e.sortMapEntries),i}add(e,n){let r;$(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new K(e,e?.value):r=new K(e.key,e.value);let o=ut(this.items,r.key),s=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${r.key} already set`);T(o.value)&&Or(r.value)?o.value.value=r.value:o.value=r.value}else if(s){let i=this.items.findIndex(a=>s(r,a)<0);i===-1?this.items.push(r):this.items.splice(i,0,r)}else this.items.push(r)}delete(e){let n=ut(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let o=ut(this.items,e)?.value;return(!n&&T(o)?o.value:o)??void 0}has(e){return!!ut(this.items,e)}set(e,n){this.add(new K(e,n),!0)}toJSON(e,n,r){let o=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(o);for(let s of this.items)Lr(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})),Fr(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:n})}};var Re={collection:"map",default:!0,nodeClass:W,tag:"tag:yaml.org,2002:map",resolve(t,e){return ge(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>W.from(t,e,n)};var ne=class extends jt{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Je,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=Zr(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let r=Zr(e);if(typeof r!="number")return;let o=this.items[r];return!n&&T(o)?o.value:o}has(e){let n=Zr(e);return typeof n=="number"&&n<this.items.length}set(e,n){let r=Zr(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);let o=this.items[r];T(o)&&Or(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?Fr(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:r,onComment:n}):JSON.stringify(this)}static from(e,n,r){let{replacer:o}=r,s=new this(e);if(n&&Symbol.iterator in Object(n)){let i=0;for(let a of n){if(typeof o=="function"){let c=n instanceof Set?a:String(i++);a=o.call(n,c,a)}s.items.push(We(a,void 0,r))}}return s}};function Zr(t){let e=T(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}var ke={collection:"seq",default:!0,nodeClass:ne,tag:"tag:yaml.org,2002:seq",resolve(t,e){return be(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>ne.from(t,e,n)};var lt={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,r){return e=Object.assign({actualString:!0},e),xt(t,e,n,r)}};var St={identify:t=>t==null,createNode:()=>new R(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new R(null),stringify:({source:t},e)=>typeof t=="string"&&St.test.test(t)?t:e.options.nullStr};var On={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new R(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&On.test.test(t)){let r=t[0]==="t"||t[0]==="T";if(e===r)return t}return e?n.options.trueStr:n.options.falseStr}};function re({format:t,minFractionDigits:e,tag:n,value:r}){if(typeof r=="bigint")return String(r);let o=typeof r=="number"?r:Number(r);if(!isFinite(o))return isNaN(o)?".nan":o<0?"-.inf":".inf";let s=Object.is(r,-0)?"-0":JSON.stringify(r);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let i=s.indexOf(".");i<0&&(i=s.length,s+=".");let a=e-(s.length-i-1);for(;a-- >0;)s+="0"}return s}var Br={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},jr={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)}},Ur={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 Qr=t=>typeof t=="bigint"||Number.isInteger(t),As=(t,e,n,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),n);function Ql(t,e,n){let{value:r}=t;return Qr(r)&&r>=0?n+r.toString(e):re(t)}var Vr={identify:t=>Qr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>As(t,2,8,n),stringify:t=>Ql(t,8,"0o")},Gr={identify:Qr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>As(t,0,10,n),stringify:re},qr={identify:t=>Qr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>As(t,2,16,n),stringify:t=>Ql(t,16,"0x")};var Vl=[Re,ke,lt,St,On,Vr,Gr,qr,Br,jr,Ur];function Gl(t){return typeof t=="bigint"||Number.isInteger(t)}var Jr=({value:t})=>JSON.stringify(t),fh=[{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:Gl,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})=>Gl(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}],dh={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},ql=[Re,ke].concat(fh,dh);var Cn={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),r=new Uint8Array(n.length);for(let o=0;o<n.length;++o)r[o]=n.charCodeAt(o);return r}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:n},r,o,s){if(!n)return"";let i=n,a;if(typeof btoa=="function"){let c="";for(let u=0;u<i.length;++u)c+=String.fromCharCode(i[u]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=R.BLOCK_LITERAL),e!==R.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),u=Math.ceil(a.length/c),d=new Array(u);for(let l=0,f=0;l<u;++l,f+=c)d[l]=a.substr(f,c);a=d.join(e===R.BLOCK_LITERAL?`-`:" ")}return xt({comment:t,type:e,value:a},r,o,s)}};function vs(t,e){if(be(t))for(let n=0;n<t.items.length;++n){let r=t.items[n];if(!$(r)){if(ge(r)){r.items.length>1&&e("Each pair must have its own sequence indicator");let o=r.items[0]||new K(new R(null));if(r.commentBefore&&(o.key.commentBefore=o.key.commentBefore?`${r.commentBefore}+`):x+=`+${n.indent}`}else if(!d&&K(t)){let R=_[0],v=_.indexOf(`+`),I=v!==-1,P=n.inFlow??t.flow??t.items.length===0;if(I||!P){let Q=!1;if(I&&(R==="&"||R==="!")){let O=_.indexOf(" ");R==="&"&&O!==-1&&O<v&&_[O+1]==="!"&&(O=_.indexOf(" ",O+1)),(O===-1||v<O)&&(Q=!0)}Q||(x=`+${n.indent}`)}}else(_===""||_[0]===`+`)&&(x="");return y+=x+_,n.inFlow?E&&r&&r():S&&!E?y+=it(y,n.indent,u(S)):h&&o&&o(),y}function yi(e,t){(e==="debug"||e==="warn")&&console.warn(t)}var _o="<<",je={identify:e=>e===_o||typeof e=="symbol"&&e.description===_o,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new T(Symbol(_o)),{addToJSMap:wi}),stringify:()=>_o},od=(e,t)=>(je.identify(t)||B(t)&&(!t.type||t.type===T.PLAIN)&&je.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===je.tag&&n.default);function wi(e,t,n){let r=sd(e,n);if(Le(r))for(let o of r.items)bi(e,t,o);else if(Array.isArray(r))for(let o of r)bi(e,t,o);else bi(e,t,r)}function bi(e,t,n){let r=sd(e,n);if(!$e(r))throw new Error("Merge sources must be maps or map aliases");let o=r.toJSON(null,e,Map);for(let[s,i]of o)t instanceof Map?t.has(s)||t.set(s,i):t instanceof Set?t.add(s):Object.prototype.hasOwnProperty.call(t,s)||Object.defineProperty(t,s,{value:i,writable:!0,enumerable:!0,configurable:!0});return t}function sd(e,t){return e&&ze(t)?t.resolve(e.doc,e):t}function So(e,t,{key:n,value:r}){if(V(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(od(e,n))wi(e,t,r);else{let o=le(n,"",e);if(t instanceof Map)t.set(o,le(r,o,e));else if(t instanceof Set)t.add(o);else{let s=Jg(n,o,e),i=le(r,s,e);s in t?Object.defineProperty(t,s,{value:i,writable:!0,enumerable:!0,configurable:!0}):t[s]=i}}return t}function Jg(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(V(e)&&n?.doc){let r=xo(n.doc,{});r.anchors=new Set;for(let s of n.anchors.keys())r.anchors.add(s.anchor);r.inFlow=!0,r.inStringifyKey=!0;let o=e.toString(r);if(!n.mapKeyWarned){let s=JSON.stringify(o);s.length>40&&(s=s.substring(0,36)+'..."'),yi(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return o}return JSON.stringify(t)}function wn(e,t,n){let r=gt(e,void 0,n),o=gt(t,void 0,n);return new oe(r,o)}var oe=class e{constructor(t,n=null){Object.defineProperty(this,xe,{value:fi}),this.key=t,this.value=n}clone(t){let{key:n,value:r}=this;return V(n)&&(n=n.clone(t)),V(r)&&(r=r.clone(t)),new e(n,r)}toJSON(t,n){let r=n?.mapAsMap?new Map:{};return So(n,r,this)}toString(t,n,r){return t?.doc?rd(this,t,n,r):JSON.stringify(this)}};function Ao(e,t,n){return(t.inFlow??e.flow?Kg:Wg)(e,t,n)}function Wg({comment:e,items:t},n,{blockItemPrefix:r,flowChars:o,itemIndent:s,onChompKeep:i,onComment:a}){let{indent:c,options:{commentString:u}}=n,f=Object.assign({},n,{indent:s,type:null}),l=!1,p=[];for(let w=0;w<t.length;++w){let h=t[w],y=null;if(V(h))!l&&h.spaceBefore&&p.push(""),Eo(n,p,h.commentBefore,l),h.comment&&(y=h.comment);else if(j(h)){let A=V(h.key)?h.key:null;A&&(!l&&A.spaceBefore&&p.push(""),Eo(n,p,A.commentBefore,l))}l=!1;let m=yt(h,f,()=>y=null,()=>l=!0);y&&(m+=it(m,s,u(y))),l&&y&&(l=!1),p.push(r+m)}let d;if(p.length===0)d=o.start+o.end;else{d=p[0];for(let w=1;w<p.length;++w){let h=p[w];d+=h?`+${c}${h}`:`+`}}return e?(d+=`+`+Pe(u(e),c),a&&a()):l&&i&&i(),d}function Kg({items:e},t,{flowChars:n,itemIndent:r}){let{indent:o,indentStep:s,flowCollectionPadding:i,options:{commentString:a}}=t;r+=s;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),u=!1,f=0,l=[];for(let w=0;w<e.length;++w){let h=e[w],y=null;if(V(h))h.spaceBefore&&l.push(""),Eo(t,l,h.commentBefore,!1),h.comment&&(y=h.comment);else if(j(h)){let A=V(h.key)?h.key:null;A&&(A.spaceBefore&&l.push(""),Eo(t,l,A.commentBefore,!1),A.comment&&(u=!0));let S=V(h.value)?h.value:null;S?(S.comment&&(y=S.comment),S.commentBefore&&(u=!0)):h.value==null&&A?.comment&&(y=A.comment)}y&&(u=!0);let m=yt(h,c,()=>y=null);u||(u=l.length>f||m.includes(`+`)),w<e.length-1?m+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(u||(u=l.reduce((A,S)=>A+S.length+2,2)+(m.length+2)>t.options.lineWidth)),u&&(m+=",")),y&&(m+=it(m,r,a(y))),l.push(m),f=l.length}let{start:p,end:d}=n;if(l.length===0)return p+d;if(!u){let w=l.reduce((h,y)=>h+y.length+2,2);u=t.options.lineWidth>0&&w>t.options.lineWidth}if(u){let w=p;for(let h of l)w+=h?`+${s}${o}${h}`:`+`;return`${w}+${o}${d}`}else return`${p}${i}${l.join(" ")}${i}${d}`}function Eo({indent:e,options:{commentString:t}},n,r,o){if(r&&o&&(r=r.replace(/^\n+/,"")),r){let s=Pe(t(r),e);n.push(s.trimStart())}}function Ct(e,t){let n=B(t)?t.value:t;for(let r of e)if(j(r)&&(r.key===t||r.key===n||B(r.key)&&r.key.value===n))return r}var se=class extends gn{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Ue,t),this.items=[]}static from(t,n,r){let{keepUndefined:o,replacer:s}=r,i=new this(t),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(wn(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 t.sortMapEntries=="function"&&i.items.sort(t.sortMapEntries),i}add(t,n){let r;j(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new oe(t,t?.value):r=new oe(t.key,t.value);let o=Ct(this.items,r.key),s=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${r.key} already set`);B(o.value)&&ho(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(t){let n=Ct(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){let o=Ct(this.items,t)?.value;return(!n&&B(o)?o.value:o)??void 0}has(t){return!!Ct(this.items,t)}set(t,n){this.add(new oe(t,n),!0)}toJSON(t,n,r){let o=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(o);for(let s of this.items)So(n,o,s);return o}toString(t,n,r){if(!t)return JSON.stringify(this);for(let o of this.items)if(!j(o))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),Ao(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:n})}};var Ve={collection:"map",default:!0,nodeClass:se,tag:"tag:yaml.org,2002:map",resolve(e,t){return $e(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,n)=>se.from(e,t,n)};var me=class extends gn{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(mt,t),this.items=[]}add(t){this.items.push(t)}delete(t){let n=ko(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){let r=ko(t);if(typeof r!="number")return;let o=this.items[r];return!n&&B(o)?o.value:o}has(t){let n=ko(t);return typeof n=="number"&&n<this.items.length}set(t,n){let r=ko(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let o=this.items[r];B(o)&&ho(n)?o.value=n:this.items[r]=n}toJSON(t,n){let r=[];n?.onCreate&&n.onCreate(r);let o=0;for(let s of this.items)r.push(le(s,String(o++),n));return r}toString(t,n,r){return t?Ao(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:n}):JSON.stringify(this)}static from(t,n,r){let{replacer:o}=r,s=new this(t);if(n&&Symbol.iterator in Object(n)){let i=0;for(let a of n){if(typeof o=="function"){let c=n instanceof Set?a:String(i++);a=o.call(n,c,a)}s.items.push(gt(a,void 0,r))}}return s}};function ko(e){let t=B(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}var Qe={collection:"seq",default:!0,nodeClass:me,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Le(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,n)=>me.from(e,t,n)};var Tt={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),Qt(e,t,n,r)}};var Gt={identify:e=>e==null,createNode:()=>new T(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new T(null),stringify:({source:e},t)=>typeof e=="string"&&Gt.test.test(e)?e:t.options.nullStr};var or={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new T(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},n){if(e&&or.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?n.options.trueStr:n.options.falseStr}};function he({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r=="bigint")return String(r);let o=typeof r=="number"?r:Number(r);if(!isFinite(o))return isNaN(o)?".nan":o<0?"-.inf":".inf";let s=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let i=s.indexOf(".");i<0&&(i=s.length,s+=".");let a=t-(s.length-i-1);for(;a-- >0;)s+="0"}return s}var vo={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:he},Ro={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():he(e)}},Do={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new T(parseFloat(e)),n=e.indexOf(".");return n!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-n-1),t},stringify:he};var Io=e=>typeof e=="bigint"||Number.isInteger(e),xi=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function id(e,t,n){let{value:r}=e;return Io(r)&&r>=0?n+r.toString(t):he(e)}var Co={identify:e=>Io(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>xi(e,2,8,n),stringify:e=>id(e,8,"0o")},To={identify:Io,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>xi(e,0,10,n),stringify:he},Oo={identify:e=>Io(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>xi(e,2,16,n),stringify:e=>id(e,16,"0x")};var ad=[Ve,Qe,Tt,Gt,or,Co,To,Oo,vo,Ro,Do];function cd(e){return typeof e=="bigint"||Number.isInteger(e)}var No=({value:e})=>JSON.stringify(e),Hg=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:No},{identify:e=>e==null,createNode:()=>new T(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:No},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:No},{identify:cd,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>cd(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:No}],Yg={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},ud=[Ve,Qe].concat(Hg,Yg);var sr={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof atob=="function"){let n=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(n.length);for(let o=0;o<n.length;++o)r[o]=n.charCodeAt(o);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:n},r,o,s){if(!n)return"";let i=n,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(t??(t=T.BLOCK_LITERAL),t!==T.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),u=Math.ceil(a.length/c),f=new Array(u);for(let l=0,p=0;l<u;++l,p+=c)f[l]=a.substr(p,c);a=f.join(t===T.BLOCK_LITERAL?`+`:" ")}return Qt({comment:e,type:t,value:a},r,o,s)}};function _i(e,t){if(Le(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!j(r)){if($e(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let o=r.items[0]||new oe(new T(null));if(r.commentBefore&&(o.key.commentBefore=o.key.commentBefore?`${r.commentBefore}${o.key.commentBefore}`:r.commentBefore),r.comment){let s=o.value??o.key;s.comment=s.comment?`${r.comment}-${s.comment}`:r.comment}r=o}t.items[n]=$(r)?r:new K(r)}}else e("Expected a sequence for this tag");return t}function Ds(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(Vt(a,c,n))}return o}var Tn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:vs,createNode:Ds};var Gt=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=Ds(e,n,r),s=new this;return s.items=o.items,s}};Gt.tag="tag:yaml.org,2002:omap";var Nn={collection:"seq",identify:t=>t instanceof Map,nodeClass:Gt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=vs(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 Gt,n)},createNode:(t,e,n)=>Gt.from(t,e,n)};function Jl({value:t,source:e},n){return e&&(t?Rs:ks).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var Rs={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:Jl},ks={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:Jl};var Kl={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},Wl={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)}},Yl={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new R(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let r=t.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:re};var $n=t=>typeof t=="bigint"||Number.isInteger(t);function Kr(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 Is(t,e,n){let{value:r}=t;if($n(r)){let o=r.toString(e);return r<0?"-"+n+o.substr(1):n+o}return re(t)}var Xl={identify:$n,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>Kr(t,2,2,n),stringify:t=>Is(t,2,"0b")},Hl={identify:$n,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>Kr(t,1,8,n),stringify:t=>Is(t,8,"0")},ef={identify:$n,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>Kr(t,0,10,n),stringify:re},tf={identify:$n,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>Kr(t,2,16,n),stringify:t=>Is(t,16,"0x")};var qt=class t extends W{constructor(e){super(e),this.tag=t.tag}add(e){let n;$(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new K(e.key,null):n=new K(e,null),ut(this.items,n.key)||this.items.push(n)}get(e,n){let r=ut(this.items,e);return!n&&$(r)?T(r.key)?r.key.value:r.key:r}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=ut(this.items,e);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new K(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(e,n,r){let{replacer:o}=r,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let i of n)typeof o=="function"&&(i=o.call(n,i,i)),s.items.push(Vt(i,null,r));return s}};qt.tag="tag:yaml.org,2002:set";var zn={collection:"map",identify:t=>t instanceof Set,nodeClass:qt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>qt.from(t,e,n),resolve(t,e){if(ge(t)){if(t.hasAllNullValues(!0))return Object.assign(new qt,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};function Os(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 nf(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 Wr={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})=>Os(t,n),stringify:nf},Yr={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=>Os(t,!1),stringify:nf},Jt={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(Jt.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=Os(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 Cs=[Re,ke,lt,St,Rs,ks,Xl,Hl,ef,tf,Kl,Wl,Yl,Cn,De,Nn,Tn,zn,Wr,Yr,Jt];var rf=new Map([["core",Vl],["failsafe",[Re,ke,lt]],["json",ql],["yaml11",Cs],["yaml-1.1",Cs]]),of={binary:Cn,bool:On,float:Ur,floatExp:jr,floatNaN:Br,floatTime:Yr,int:Gr,intHex:qr,intOct:Vr,intTime:Wr,map:Re,merge:De,null:St,omap:Nn,pairs:Tn,seq:ke,set:zn,timestamp:Jt},sf={"tag:yaml.org,2002:binary":Cn,"tag:yaml.org,2002:merge":De,"tag:yaml.org,2002:omap":Nn,"tag:yaml.org,2002:pairs":Tn,"tag:yaml.org,2002:set":zn,"tag:yaml.org,2002:timestamp":Jt};function Xr(t,e,n){let r=rf.get(e);if(r&&!t)return n&&!r.includes(De)?r.concat(De):r.slice();let o=r;if(!o)if(Array.isArray(t))o=[];else{let s=Array.from(rf.keys()).filter(i=>i!=="yaml11").map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(t))for(let s of t)o=o.concat(s);else typeof t=="function"&&(o=t(o.slice()));return n&&(o=o.concat(De)),o.reduce((s,i)=>{let a=typeof i=="string"?of[i]:i;if(!a){let c=JSON.stringify(i),u=Object.keys(of).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 ph=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,Pn=class t{constructor({compat:e,customTags:n,merge:r,resolveKnownTags:o,schema:s,sortMapEntries:i,toStringDefaults:a}){this.compat=Array.isArray(e)?Xr(e,"compat"):e?Xr(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=o?sf:{},this.tags=Xr(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,ve,{value:Re}),Object.defineProperty(this,pe,{value:lt}),Object.defineProperty(this,Je,{value:ke}),this.sortMapEntries=typeof i=="function"?i:i===!0?ph:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function af(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=zr(t,e),{commentString:s}=o.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(we(c,""))}let i=!1,a=null;if(t.contents){if(z(t.contents)){if(t.contents.spaceBefore&&r&&n.push(""),t.contents.commentBefore){let d=s(t.contents.commentBefore);n.push(we(d,""))}o.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>i=!0,u=Ye(t.contents,o,()=>a=null,c);a&&(u+=Be(u,"",s(a))),(u[0]==="|"||u[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${u}`:n.push(u)}else n.push(Ye(t.contents,o));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(`-`)?(n.push("..."),n.push(we(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=t.comment;c&&i&&(c=c.replace(/^\n+/,"")),c&&((!i||a)&&n[n.length-1]!==""&&n.push(""),n.push(we(s(c),"")))}return n.join(`+${s.comment}`:r.comment}r=o}e.items[n]=j(r)?r:new oe(r)}}else t("Expected a sequence for this tag");return e}function Si(e,t,n){let{replacer:r}=n,o=new me(e);o.tag="tag:yaml.org,2002:pairs";let s=0;if(t&&Symbol.iterator in Object(t))for(let i of t){typeof r=="function"&&(i=r.call(t,String(s++),i));let 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(wn(a,c,n))}return o}var ir={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:_i,createNode:Si};var xn=class e extends me{constructor(){super(),this.add=se.prototype.add.bind(this),this.delete=se.prototype.delete.bind(this),this.get=se.prototype.get.bind(this),this.has=se.prototype.has.bind(this),this.set=se.prototype.set.bind(this),this.tag=e.tag}toJSON(t,n){if(!n)return super.toJSON(t);let r=new Map;n?.onCreate&&n.onCreate(r);for(let o of this.items){let s,i;if(j(o)?(s=le(o.key,"",n),i=le(o.value,s,n)):s=le(o,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,i)}return r}static from(t,n,r){let o=Si(t,n,r),s=new this;return s.items=o.items,s}};xn.tag="tag:yaml.org,2002:omap";var ar={collection:"seq",identify:e=>e instanceof Map,nodeClass:xn,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let n=_i(e,t),r=[];for(let{key:o}of n.items)B(o)&&(r.includes(o.value)?t(`Ordered maps must not include duplicate keys: ${o.value}`):r.push(o.value));return Object.assign(new xn,n)},createNode:(e,t,n)=>xn.from(e,t,n)};function ld({value:e,source:t},n){return t&&(e?Ei:Ai).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var Ei={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new T(!0),stringify:ld},Ai={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new T(!1),stringify:ld};var fd={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:he},dd={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():he(e)}},pd={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new T(parseFloat(e.replace(/_/g,""))),n=e.indexOf(".");if(n!==-1){let r=e.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:he};var cr=e=>typeof e=="bigint"||Number.isInteger(e);function zo(e,t,n,{intAsBigInt:r}){let o=e[0];if((o==="-"||o==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let i=BigInt(e);return o==="-"?BigInt(-1)*i:i}let s=parseInt(e,n);return o==="-"?-1*s:s}function ki(e,t,n){let{value:r}=e;if(cr(r)){let o=r.toString(t);return r<0?"-"+n+o.substr(1):n+o}return he(e)}var md={identify:cr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>zo(e,2,2,n),stringify:e=>ki(e,2,"0b")},hd={identify:cr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>zo(e,1,8,n),stringify:e=>ki(e,8,"0")},gd={identify:cr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>zo(e,0,10,n),stringify:he},yd={identify:cr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>zo(e,2,16,n),stringify:e=>ki(e,16,"0x")};var _n=class e extends se{constructor(t){super(t),this.tag=e.tag}add(t){let n;j(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new oe(t.key,null):n=new oe(t,null),Ct(this.items,n.key)||this.items.push(n)}get(t,n){let r=Ct(this.items,t);return!n&&j(r)?B(r.key)?r.key.value:r.key:r}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=Ct(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new oe(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(t,n,r){let{replacer:o}=r,s=new this(t);if(n&&Symbol.iterator in Object(n))for(let i of n)typeof o=="function"&&(i=o.call(n,i,i)),s.items.push(wn(i,null,r));return s}};_n.tag="tag:yaml.org,2002:set";var ur={collection:"map",identify:e=>e instanceof Set,nodeClass:_n,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>_n.from(e,t,n),resolve(e,t){if($e(e)){if(e.hasAllNullValues(!0))return Object.assign(new _n,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};function vi(e,t){let n=e[0],r=n==="-"||n==="+"?e.substring(1):e,o=i=>t?BigInt(i):Number(i),s=r.replace(/_/g,"").split(":").reduce((i,a)=>i*o(60)+o(a),o(0));return n==="-"?o(-1)*s:s}function bd(e){let{value:t}=e,n=i=>i;if(typeof t=="bigint")n=i=>BigInt(i);else if(isNaN(t)||!isFinite(t))return he(e);let r="";t<0&&(r="-",t*=n(-1));let o=n(60),s=[t%o];return t<60?s.unshift(0):(t=(t-s[0])/o,s.unshift(t%o),t>=60&&(t=(t-s[0])/o,s.unshift(t))),r+s.map(i=>String(i).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var $o={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>vi(e,n),stringify:bd},Lo={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>vi(e,!1),stringify:bd},Sn={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(Sn.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,o,s,i,a]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,u=Date.UTC(n,r-1,o,s||0,i||0,a||0,c),f=t[8];if(f&&f!=="Z"){let l=vi(f,!1);Math.abs(l)<30&&(l*=60),u-=6e4*l}return new Date(u)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};var Ri=[Ve,Qe,Tt,Gt,Ei,Ai,md,hd,gd,yd,fd,dd,pd,sr,je,ar,ir,ur,$o,Lo,Sn];var wd=new Map([["core",ad],["failsafe",[Ve,Qe,Tt]],["json",ud],["yaml11",Ri],["yaml-1.1",Ri]]),xd={binary:sr,bool:or,float:Do,floatExp:Ro,floatNaN:vo,floatTime:Lo,int:To,intHex:Oo,intOct:Co,intTime:$o,map:Ve,merge:je,null:Gt,omap:ar,pairs:ir,seq:Qe,set:ur,timestamp:Sn},_d={"tag:yaml.org,2002:binary":sr,"tag:yaml.org,2002:merge":je,"tag:yaml.org,2002:omap":ar,"tag:yaml.org,2002:pairs":ir,"tag:yaml.org,2002:set":ur,"tag:yaml.org,2002:timestamp":Sn};function Po(e,t,n){let r=wd.get(t);if(r&&!e)return n&&!r.includes(je)?r.concat(je):r.slice();let o=r;if(!o)if(Array.isArray(e))o=[];else{let s=Array.from(wd.keys()).filter(i=>i!=="yaml11").map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${s} or define customTags array`)}if(Array.isArray(e))for(let s of e)o=o.concat(s);else typeof e=="function"&&(o=e(o.slice()));return n&&(o=o.concat(je)),o.reduce((s,i)=>{let a=typeof i=="string"?xd[i]:i;if(!a){let c=JSON.stringify(i),u=Object.keys(xd).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${u}`)}return s.includes(a)||s.push(a),s},[])}var Xg=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,lr=class e{constructor({compat:t,customTags:n,merge:r,resolveKnownTags:o,schema:s,sortMapEntries:i,toStringDefaults:a}){this.compat=Array.isArray(t)?Po(t,"compat"):t?Po(null,t):null,this.name=typeof s=="string"&&s||"core",this.knownTags=o?_d:{},this.tags=Po(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,Ue,{value:Ve}),Object.defineProperty(this,Ie,{value:Tt}),Object.defineProperty(this,mt,{value:Qe}),this.sortMapEntries=typeof i=="function"?i:i===!0?Xg:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};function Sd(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(n.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&n.push("---");let o=xo(e,t),{commentString:s}=o.options;if(e.commentBefore){n.length!==1&&n.unshift("");let c=s(e.commentBefore);n.unshift(Pe(c,""))}let i=!1,a=null;if(e.contents){if(V(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){let f=s(e.contents.commentBefore);n.push(Pe(f,""))}o.forceBlockIndent=!!e.comment,a=e.contents.comment}let c=a?void 0:()=>i=!0,u=yt(e.contents,o,()=>a=null,c);a&&(u+=it(u,"",s(a))),(u[0]==="|"||u[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${u}`:n.push(u)}else n.push(yt(e.contents,o));if(e.directives?.docEnd)if(e.comment){let c=s(e.comment);c.includes(`+`)?(n.push("..."),n.push(Pe(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=e.comment;c&&i&&(c=c.replace(/^\n+/,"")),c&&((!i||a)&&n[n.length-1]!==""&&n.push(""),n.push(Pe(s(c),"")))}return n.join(``)+`-`}var ft=class t{constructor(e,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ie,{value:vr});let o=null;typeof n=="function"||Array.isArray(n)?o=n:r===void 0&&n&&(r=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=s;let{version:i}=s;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(i=this.directives.yaml.version)):this.directives=new Ze({version:i}),this.setSchema(i,r),this.contents=e===void 0?null:this.createNode(e,o,r)}clone(){let e=Object.create(t.prototype,{[ie]:{value:vr}});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){Kt(this.contents)&&this.contents.add(e)}addIn(e,n){Kt(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let r=ys(this);e.anchor=!n||r.has(n)?gs(n||"a",r):n}return new Ke(e.anchor)}createNode(e,n,r){let o;if(typeof n=="function")e=n.call({"":e},"",e),o=n;else if(Array.isArray(n)){let h=x=>typeof x=="number"||x instanceof String||x instanceof Number,y=n.filter(h).map(String);y.length>0&&(n=n.concat(y)),o=n}else r===void 0&&n&&(r=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:i,flow:a,keepUndefined:c,onTagObj:u,tag:d}=r??{},{onAnchor:l,setAnchors:f,sourceObjects:p}=Ml(this,i||"a"),g={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:l,onTagObj:u,replacer:o,schema:this.schema,sourceObjects:p},m=We(e,d,g);return a&&B(m)&&(m.flow=!0),f(),m}createPair(e,n,r={}){let o=this.createNode(e,null,r),s=this.createNode(n,null,r);return new K(o,s)}delete(e){return Kt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ut(e)?this.contents==null?!1:(this.contents=null,!0):Kt(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 Ut(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 Ut(e)?this.contents!==void 0:B(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=Dn(this.schema,[e],n):Kt(this.contents)&&this.contents.set(e,n)}setIn(e,n){Ut(e)?this.contents=n:this.contents==null?this.contents=Dn(this.schema,Array.from(e),n):Kt(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let r;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Ze({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Ze({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let o=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${o}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(r)this.schema=new Pn(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:r,maxAliasCount:o,onAnchor:s,reviver:i}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof o=="number"?o:100},c=H(this.contents,n??"",a);if(typeof s=="function")for(let{count:u,res:d}of a.anchors.values())s(d,u);return typeof i=="function"?at(i,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return af(this,e)}};function Kt(t){if(B(t))return!0;throw new Error("Expected a YAML collection as document contents")}var Ln=class extends Error{constructor(e,n,r,o){super(),this.name=e,this.code=r,this.message=o,this.pos=n}},Ie=class extends Ln{constructor(e,n,r){super("YAMLParseError",e,n,r)}},Mn=class extends Ln{constructor(e,n,r){super("YAMLWarning",e,n,r)}},Ts=(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 Ot=class e{constructor(t,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,xe,{value:uo});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 st({version:i}),this.setSchema(i,r),this.contents=t===void 0?null:this.createNode(t,o,r)}clone(){let t=Object.create(e.prototype,{[xe]:{value:uo}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=V(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){En(this.contents)&&this.contents.add(t)}addIn(t,n){En(this.contents)&&this.contents.addIn(t,n)}createAlias(t,n){if(!t.anchor){let r=di(this);t.anchor=!n||r.has(n)?pi(n||"a",r):n}return new ht(t.anchor)}createNode(t,n,r){let o;if(typeof n=="function")t=n.call({"":t},"",t),o=n;else if(Array.isArray(n)){let y=A=>typeof A=="number"||A instanceof String||A instanceof Number,m=n.filter(y).map(String);m.length>0&&(n=n.concat(m)),o=n}else r===void 0&&n&&(r=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:i,flow:a,keepUndefined:c,onTagObj:u,tag:f}=r??{},{onAnchor:l,setAnchors:p,sourceObjects:d}=ed(this,i||"a"),w={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:l,onTagObj:u,replacer:o,schema:this.schema,sourceObjects:d},h=gt(t,f,w);return a&&K(h)&&(h.flow=!0),p(),h}createPair(t,n,r={}){let o=this.createNode(t,null,r),s=this.createNode(n,null,r);return new oe(o,s)}delete(t){return En(this.contents)?this.contents.delete(t):!1}deleteIn(t){return yn(t)?this.contents==null?!1:(this.contents=null,!0):En(this.contents)?this.contents.deleteIn(t):!1}get(t,n){return K(this.contents)?this.contents.get(t,n):void 0}getIn(t,n){return yn(t)?!n&&B(this.contents)?this.contents.value:this.contents:K(this.contents)?this.contents.getIn(t,n):void 0}has(t){return K(this.contents)?this.contents.has(t):!1}hasIn(t){return yn(t)?this.contents!==void 0:K(this.contents)?this.contents.hasIn(t):!1}set(t,n){this.contents==null?this.contents=er(this.schema,[t],n):En(this.contents)&&this.contents.set(t,n)}setIn(t,n){yn(t)?this.contents=n:this.contents==null?this.contents=er(this.schema,Array.from(t),n):En(this.contents)&&this.contents.setIn(t,n)}setSchema(t,n={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new st({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new st({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let o=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${o}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(r)this.schema=new lr(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:n,mapAsMap:r,maxAliasCount:o,onAnchor:s,reviver:i}={}){let a={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof o=="number"?o:100},c=le(this.contents,n??"",a);if(typeof s=="function")for(let{count:u,res:f}of a.anchors.values())s(f,u);return typeof i=="function"?Dt(i,{"":c},"",c):c}toJSON(t,n){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:n})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let n=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return Sd(this,t)}};function En(e){if(K(e))return!0;throw new Error("Expected a YAML collection as document contents")}var fr=class extends Error{constructor(t,n,r,o){super(),this.name=t,this.code=r,this.message=o,this.pos=n}},Ge=class extends fr{constructor(t,n,r){super("YAMLParseError",t,n,r)}},dr=class extends fr{constructor(t,n,r){super("YAMLWarning",t,n,r)}},Di=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>t.linePos(a));let{line:r,col:o}=n.linePos[0];n.message+=` at line ${r}, column ${o}`;let s=o-1,i=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(s>=60&&i.length>80){let 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=e.substring(t.lineStarts[r-2],t.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 je(t,{flow:e,indicator:n,next:r,offset:o,onError:s,parentIndent:i,startOnNewline:a}){let c=!1,u=a,d=a,l="",f="",p=!1,g=!1,m=null,h=null,y=null,x=null,S=null,_=null,b=null;for(let E of t)switch(g&&(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"),g=!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||y)&&(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,b??(b=E.offset),u=!1,d=!1,g=!0;break;case"tag":{y&&s(E,"MULTIPLE_TAGS","A node can have at most one tag"),y=E,b??(b=E.offset),u=!1,d=!1,g=!0;break}case n:(h||y)&&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 g&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&s(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(u&&m.indent<=i||r?.type==="block-map"||r?.type==="block-seq")&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:S,found:_,spaceBefore:c,comment:l,hasNewline:p,anchor:h,tag:y,newlineAfterProp:x,end:D,start:b??D}}function dt(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`-`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(dt(e.key)||dt(e.value))return!0}return!1;default:return!0}}function Fn(t,e,n){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&dt(e)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function Hr(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 cf="All mapping items must start at the same column";function uf({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=s?.nodeClass??W,a=new i(n.schema);n.atRoot&&(n.atRoot=!1);let c=r.offset,u=null;for(let d of r.items){let{start:l,key:f,sep:p,value:g}=d,m=je(l,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:o,parentIndent:r.indent,startOnNewline:!0}),h=!m.found;if(h){if(f&&(f.type==="block-seq"?o(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&o(c,"BAD_INDENT",cf)),!m.anchor&&!m.tag&&!p){u=m.end,m.comment&&(a.comment?a.comment+=`-`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||dt(f))&&o(f??l[l.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==r.indent&&o(c,"BAD_INDENT",cf);n.atKey=!0;let y=m.end,x=f?t(n,f,m,o):e(n,y,l,null,m,o);n.schema.compat&&Fn(r.indent,f,o),n.atKey=!1,Hr(n,a.items,x)&&o(y,"DUPLICATE_KEY","Map keys must be unique");let S=je(p??[],{indicator:"map-value-ind",next:g,offset:x.range[2],onError:o,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=S.end,S.found){h&&(g?.type==="block-map"&&!S.hasNewline&&o(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&m.start<S.found.offset-1024&&o(x.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let _=g?t(n,g,S,o):e(n,c,p,null,S,o);n.schema.compat&&Fn(r.indent,g,o),c=_.range[2];let b=new K(x,_);n.options.keepSourceTokens&&(b.srcToken=d),a.items.push(b)}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 lf({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=s?.nodeClass??ne,a=new i(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=r.offset,u=null;for(let{start:d,value:l}of r.items){let f=je(d,{indicator:"seq-item-ind",next:l,offset:c,onError:o,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||l)l?.type==="block-seq"?o(f.end,"BAD_INDENT","All sequence items must start at the same column"):o(c,"MISSING_CHAR","Sequence item without - indicator");else{u=f.end,f.comment&&(a.comment=f.comment);continue}let p=l?t(n,l,f,o):e(n,f.end,d,null,f,o);n.schema.compat&&Fn(r.indent,l,o),c=p.range[2],a.items.push(p)}return a.range=[r.offset,c,u??c],a}function Ue(t,e,n,r){let o="";if(t){let s=!1,i="";for(let a of t){let{source:c,type:u}=a;switch(u){case"space":s=!0;break;case"comment":{n&&!s&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=c.substring(1)||" ";o?o+=i+d:o=d,i="";break}case"newline":o&&(i+=c),s=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=c.length}}return{comment:o,offset:e}}var Ns="Block collections are not allowed within flow collections",$s=t=>t&&(t.type==="block-map"||t.type==="block-seq");function ff({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=r.start.source==="{",a=i?"flow map":"flow sequence",c=s?.nodeClass??(i?W:ne),u=new c(n.schema);u.flow=!0;let d=n.atRoot;d&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let l=r.offset+r.start.source.length;for(let h=0;h<r.items.length;++h){let y=r.items[h],{start:x,key:S,sep:_,value:b}=y,A=je(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&&!_&&!b){h===0&&A.comma?o(A.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):h<r.items.length-1&&o(A.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),A.comment&&(u.comment?u.comment+=`-`+A.comment:u.comment=A.comment),l=A.end;continue}!i&&n.options.strict&&dt(S)&&o(S,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(h===0)A.comma&&o(A.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(A.comma||o(A.start,"MISSING_CHAR",`Missing , between ${a} items`),A.comment){let D="";e:for(let 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=b?t(n,b,A,o):e(n,A.end,_,null,A,o);u.items.push(D),l=D.range[2],$s(b)&&o(D.range,"BLOCK_IN_FLOW",Ns)}else{n.atKey=!0;let D=A.end,E=S?t(n,S,A,o):e(n,D,x,null,A,o);$s(S)&&o(E.range,"BLOCK_IN_FLOW",Ns),n.atKey=!1;let C=je(_??[],{flow:a,indicator:"map-value-ind",next:b,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 b&&("source"in b&&b.source?.[0]===":"?o(b,"MISSING_CHAR",`Missing space after : in ${a}`):o(C.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let P=b?t(n,b,C,o):C.found?e(n,C.end,_,null,C,o):null;P?$s(b)&&o(P.range,"BLOCK_IN_FLOW",Ns):C.comment&&(E.comment?E.comment+=`-`+C.comment:E.comment=C.comment);let G=new K(E,P);if(n.options.keepSourceTokens&&(G.srcToken=y),i){let L=u;Hr(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 bt=(P??E).range;L.range=[E.range[0],bt[1],bt[2]],u.items.push(L)}l=P?P.range[2]:C.end}}let f=i?"}":"]",[p,...g]=r.end,m=l;if(p?.source===f)m=p.offset+p.source.length;else{let h=a[0].toUpperCase()+a.substring(1),y=d?`${h} must end with a ${f}`:`${h} in block collection must be sufficiently indented and end with a ${f}`;o(l,d?"MISSING_CHAR":"BAD_INDENT",y),p&&p.source.length!==1&&g.unshift(p)}if(g.length>0){let h=Ue(g,m,n.options.strict,o);h.comment&&(u.comment?u.comment+=`-`+h.comment:u.comment=h.comment),u.range=[r.offset,m,h.offset]}else u.range=[r.offset,m,m];return u}function zs(t,e,n,r,o,s){let i=n.type==="block-map"?uf(t,e,n,r,s):n.type==="block-seq"?lf(t,e,n,r,s):ff(t,e,n,r,s),a=i.constructor;return o==="!"||o===a.tagName?(i.tag=a.tagName,i):(o&&(i.tag=o),i)}function df(t,e,n,r,o){let s=r.tag,i=s?e.directives.tagName(s.source,f=>o(s,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=r,g=f&&s?f.offset>s.offset?f:s:f??s;g&&(!p||p.offset<g.offset)&&o(g,"MISSING_CHAR","Missing newline after block sequence props")}let a=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!s||!i||i==="!"||i===W.tagName&&a==="map"||i===ne.tagName&&a==="seq")return zs(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),zs(t,e,n,o,i)}let u=zs(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 Ps(t,e,n){let r=e.offset,o=mh(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?hh(e.source):[],a=i.length;for(let m=i.length-1;m>=0;--m){let h=i[m][1];if(h===""||h==="\r")a=m;else break}if(a===0){let m=o.chomp==="+"&&i.length>0?`-`.repeat(Math.max(1,i.length-1)):"",h=r+o.length;return e.source&&(h+=e.source.length),{value:m,type:s,comment:o.comment,range:[r,h,h]}}let c=e.indent+o.indent,u=e.offset+o.length,d=0;for(let m=0;m<a;++m){let[h,y]=i[m];if(y===""||y==="\r")o.indent===0&&h.length>c&&(c=h.length);else{h.length<c&&n(u+h.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),o.indent===0&&(c=h.length),d=m,c===0&&!t.atRoot&&n(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=h.length+y.length+1}for(let m=i.length-1;m>=a;--m)i[m][0].length>c&&(a=m+1);let l="",f="",p=!1;for(let m=0;m<d;++m)l+=i[m][0].slice(c)+`-`;for(let m=d;m<a;++m){let[h,y]=i[m];u+=h.length+y.length+1;let x=y[y.length-1]==="\r";if(x&&(y=y.slice(0,-1)),y&&h.length<c){let _=`Block scalar lines must not be less indented than their ${o.indent?"explicit indentation indicator":"first line"}`;n(u-y.length-(x?2:1),"BAD_INDENT",_),h=""}s===R.BLOCK_LITERAL?(l+=f+h.slice(c)+y,f=`-`):h.length>c||y[0]===" "?(f===" "?f=`-`:!p&&f===`-`&&(f=`+`}};function at(e,{flow:t,indicator:n,next:r,offset:o,onError:s,parentIndent:i,startOnNewline:a}){let c=!1,u=a,f=a,l="",p="",d=!1,w=!1,h=null,y=null,m=null,A=null,S=null,E=null,_=null;for(let v of e)switch(w&&(v.type!=="space"&&v.type!=="newline"&&v.type!=="comma"&&s(v.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),h&&(u&&v.type!=="comment"&&v.type!=="newline"&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),v.type){case"space":!t&&(n!=="doc-start"||r?.type!=="flow-collection")&&v.source.includes(" ")&&(h=v),f=!0;break;case"comment":{f||s(v,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let I=v.source.substring(1)||" ";l?l+=p+I:l=I,p="",u=!1;break}case"newline":u?l?l+=v.source:(!E||n!=="seq-item-ind")&&(c=!0):p+=v.source,u=!0,d=!0,(y||m)&&(A=v),f=!0;break;case"anchor":y&&s(v,"MULTIPLE_ANCHORS","A node can have at most one anchor"),v.source.endsWith(":")&&s(v.offset+v.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=v,_??(_=v.offset),u=!1,f=!1,w=!0;break;case"tag":{m&&s(v,"MULTIPLE_TAGS","A node can have at most one tag"),m=v,_??(_=v.offset),u=!1,f=!1,w=!0;break}case n:(y||m)&&s(v,"BAD_PROP_ORDER",`Anchors and tags must be after the ${v.source} indicator`),E&&s(v,"UNEXPECTED_TOKEN",`Unexpected ${v.source} in ${t??"collection"}`),E=v,u=n==="seq-item-ind"||n==="explicit-key-ind",f=!1;break;case"comma":if(t){S&&s(v,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),S=v,u=!1,f=!1;break}default:s(v,"UNEXPECTED_TOKEN",`Unexpected ${v.type} token`),u=!1,f=!1}let x=e[e.length-1],R=x?x.offset+x.source.length:o;return w&&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"),h&&(u&&h.indent<=i||r?.type==="block-map"||r?.type==="block-seq")&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:S,found:E,spaceBefore:c,comment:l,hasNewline:d,anchor:y,tag:m,newlineAfterProp:A,end:R,start:_??R}}function Nt(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`+`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let n of t.start)if(n.type==="newline")return!0;if(t.sep){for(let n of t.sep)if(n.type==="newline")return!0}if(Nt(t.key)||Nt(t.value))return!0}return!1;default:return!0}}function pr(e,t,n){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&Nt(t)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function Fo(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let o=typeof r=="function"?r:(s,i)=>s===i||B(s)&&B(i)&&s.value===i.value;return t.some(s=>o(s.key,n))}var Ed="All mapping items must start at the same column";function Ad({composeNode:e,composeEmptyNode:t},n,r,o,s){let i=s?.nodeClass??se,a=new i(n.schema);n.atRoot&&(n.atRoot=!1);let c=r.offset,u=null;for(let f of r.items){let{start:l,key:p,sep:d,value:w}=f,h=at(l,{indicator:"explicit-key-ind",next:p??d?.[0],offset:c,onError:o,parentIndent:r.indent,startOnNewline:!0}),y=!h.found;if(y){if(p&&(p.type==="block-seq"?o(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in p&&p.indent!==r.indent&&o(c,"BAD_INDENT",Ed)),!h.anchor&&!h.tag&&!d){u=h.end,h.comment&&(a.comment?a.comment+=`+`+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||Nt(p))&&o(p??l[l.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&o(c,"BAD_INDENT",Ed);n.atKey=!0;let m=h.end,A=p?e(n,p,h,o):t(n,m,l,null,h,o);n.schema.compat&&pr(r.indent,p,o),n.atKey=!1,Fo(n,a.items,A)&&o(m,"DUPLICATE_KEY","Map keys must be unique");let S=at(d??[],{indicator:"map-value-ind",next:w,offset:A.range[2],onError:o,parentIndent:r.indent,startOnNewline:!p||p.type==="block-scalar"});if(c=S.end,S.found){y&&(w?.type==="block-map"&&!S.hasNewline&&o(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&h.start<S.found.offset-1024&&o(A.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let E=w?e(n,w,S,o):t(n,c,d,null,S,o);n.schema.compat&&pr(r.indent,w,o),c=E.range[2];let _=new oe(A,E);n.options.keepSourceTokens&&(_.srcToken=f),a.items.push(_)}else{y&&o(A.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),S.comment&&(A.comment?A.comment+=`+`+S.comment:A.comment=S.comment);let E=new oe(A);n.options.keepSourceTokens&&(E.srcToken=f),a.items.push(E)}}return u&&u<c&&o(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,c,u??c],a}function kd({composeNode:e,composeEmptyNode:t},n,r,o,s){let i=s?.nodeClass??me,a=new i(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=r.offset,u=null;for(let{start:f,value:l}of r.items){let p=at(f,{indicator:"seq-item-ind",next:l,offset:c,onError:o,parentIndent:r.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||l)l?.type==="block-seq"?o(p.end,"BAD_INDENT","All sequence items must start at the same column"):o(c,"MISSING_CHAR","Sequence item without - indicator");else{u=p.end,p.comment&&(a.comment=p.comment);continue}let d=l?e(n,l,p,o):t(n,p.end,f,null,p,o);n.schema.compat&&pr(r.indent,l,o),c=d.range[2],a.items.push(d)}return a.range=[r.offset,c,u??c],a}function ct(e,t,n,r){let o="";if(e){let s=!1,i="";for(let a of e){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 f=c.substring(1)||" ";o?o+=i+f:o=f,i="";break}case"newline":o&&(i+=c),s=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}t+=c.length}}return{comment:o,offset:t}}var Ii="Block collections are not allowed within flow collections",Ci=e=>e&&(e.type==="block-map"||e.type==="block-seq");function vd({composeNode:e,composeEmptyNode:t},n,r,o,s){let i=r.start.source==="{",a=i?"flow map":"flow sequence",c=s?.nodeClass??(i?se:me),u=new c(n.schema);u.flow=!0;let f=n.atRoot;f&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let l=r.offset+r.start.source.length;for(let y=0;y<r.items.length;++y){let m=r.items[y],{start:A,key:S,sep:E,value:_}=m,x=at(A,{flow:a,indicator:"explicit-key-ind",next:S??E?.[0],offset:l,onError:o,parentIndent:r.indent,startOnNewline:!1});if(!x.found){if(!x.anchor&&!x.tag&&!E&&!_){y===0&&x.comma?o(x.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<r.items.length-1&&o(x.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),x.comment&&(u.comment?u.comment+=`+`+x.comment:u.comment=x.comment),l=x.end;continue}!i&&n.options.strict&&Nt(S)&&o(S,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)x.comma&&o(x.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(x.comma||o(x.start,"MISSING_CHAR",`Missing , between ${a} items`),x.comment){let R="";e:for(let v of A)switch(v.type){case"comma":case"space":break;case"comment":R=v.source.substring(1);break e;default:break e}if(R){let v=u.items[u.items.length-1];j(v)&&(v=v.value??v.key),v.comment?v.comment+=`+`+R:v.comment=R,x.comment=x.comment.substring(R.length+1)}}if(!i&&!E&&!x.found){let R=_?e(n,_,x,o):t(n,x.end,E,null,x,o);u.items.push(R),l=R.range[2],Ci(_)&&o(R.range,"BLOCK_IN_FLOW",Ii)}else{n.atKey=!0;let R=x.end,v=S?e(n,S,x,o):t(n,R,A,null,x,o);Ci(S)&&o(v.range,"BLOCK_IN_FLOW",Ii),n.atKey=!1;let I=at(E??[],{flow:a,indicator:"map-value-ind",next:_,offset:v.range[2],onError:o,parentIndent:r.indent,startOnNewline:!1});if(I.found){if(!i&&!x.found&&n.options.strict){if(E)for(let O of E){if(O===I.found)break;if(O.type==="newline"){o(O,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}x.start<I.found.offset-1024&&o(I.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else _&&("source"in _&&_.source?.[0]===":"?o(_,"MISSING_CHAR",`Missing space after : in ${a}`):o(I.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let P=_?e(n,_,I,o):I.found?t(n,I.end,E,null,I,o):null;P?Ci(_)&&o(P.range,"BLOCK_IN_FLOW",Ii):I.comment&&(v.comment?v.comment+=`+`+I.comment:v.comment=I.comment);let Q=new oe(v,P);if(n.options.keepSourceTokens&&(Q.srcToken=m),i){let O=u;Fo(n,O.items,v)&&o(R,"DUPLICATE_KEY","Map keys must be unique"),O.items.push(Q)}else{let O=new se(n.schema);O.flow=!0,O.items.push(Q);let z=(P??v).range;O.range=[v.range[0],z[1],z[2]],u.items.push(O)}l=P?P.range[2]:I.end}}let p=i?"}":"]",[d,...w]=r.end,h=l;if(d?.source===p)h=d.offset+d.source.length;else{let y=a[0].toUpperCase()+a.substring(1),m=f?`${y} must end with a ${p}`:`${y} in block collection must be sufficiently indented and end with a ${p}`;o(l,f?"MISSING_CHAR":"BAD_INDENT",m),d&&d.source.length!==1&&w.unshift(d)}if(w.length>0){let y=ct(w,h,n.options.strict,o);y.comment&&(u.comment?u.comment+=`+`+y.comment:u.comment=y.comment),u.range=[r.offset,h,y.offset]}else u.range=[r.offset,h,h];return u}function Ti(e,t,n,r,o,s){let i=n.type==="block-map"?Ad(e,t,n,r,s):n.type==="block-seq"?kd(e,t,n,r,s):vd(e,t,n,r,s),a=i.constructor;return o==="!"||o===a.tagName?(i.tag=a.tagName,i):(o&&(i.tag=o),i)}function Rd(e,t,n,r,o){let s=r.tag,i=s?t.directives.tagName(s.source,p=>o(s,"TAG_RESOLVE_FAILED",p)):null;if(n.type==="block-seq"){let{anchor:p,newlineAfterProp:d}=r,w=p&&s?p.offset>s.offset?p:s:p??s;w&&(!d||d.offset<w.offset)&&o(w,"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===se.tagName&&a==="map"||i===me.tagName&&a==="seq")return Ti(e,t,n,o,i);let c=t.schema.tags.find(p=>p.tag===i&&p.collection===a);if(!c){let p=t.schema.knownTags[i];if(p?.collection===a)t.schema.tags.push(Object.assign({},p,{default:!1})),c=p;else return p?o(s,"BAD_COLLECTION_TYPE",`${p.tag} used for ${a} collection, but expects ${p.collection??"scalar"}`,!0):o(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,!0),Ti(e,t,n,o,i)}let u=Ti(e,t,n,o,i,c),f=c.resolve?.(u,p=>o(s,"TAG_RESOLVE_FAILED",p),t.options)??u,l=V(f)?f:new T(f);return l.range=u.range,l.tag=i,c?.format&&(l.format=c.format),l}function Oi(e,t,n){let r=t.offset,o=ey(t,e.options.strict,n);if(!o)return{value:"",type:null,comment:"",range:[r,r,r]};let s=o.mode===">"?T.BLOCK_FOLDED:T.BLOCK_LITERAL,i=t.source?ty(t.source):[],a=i.length;for(let h=i.length-1;h>=0;--h){let y=i[h][1];if(y===""||y==="\r")a=h;else break}if(a===0){let h=o.chomp==="+"&&i.length>0?`+`.repeat(Math.max(1,i.length-1)):"",y=r+o.length;return t.source&&(y+=t.source.length),{value:h,type:s,comment:o.comment,range:[r,y,y]}}let c=t.indent+o.indent,u=t.offset+o.length,f=0;for(let h=0;h<a;++h){let[y,m]=i[h];if(m===""||m==="\r")o.indent===0&&y.length>c&&(c=y.length);else{y.length<c&&n(u+y.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),o.indent===0&&(c=y.length),f=h,c===0&&!e.atRoot&&n(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=y.length+m.length+1}for(let h=i.length-1;h>=a;--h)i[h][0].length>c&&(a=h+1);let l="",p="",d=!1;for(let h=0;h<f;++h)l+=i[h][0].slice(c)+`+`;for(let h=f;h<a;++h){let[y,m]=i[h];u+=y.length+m.length+1;let A=m[m.length-1]==="\r";if(A&&(m=m.slice(0,-1)),m&&y.length<c){let E=`Block scalar lines must not be less indented than their ${o.indent?"explicit indentation indicator":"first line"}`;n(u-m.length-(A?2:1),"BAD_INDENT",E),y=""}s===T.BLOCK_LITERAL?(l+=p+y.slice(c)+m,p=`+`):y.length>c||m[0]===" "?(p===" "?p=`+`:!d&&p===`+`&&(p=`-`),l+=f+h.slice(c)+y,f=`-`,p=!0):y===""?f===`+`),l+=p+y.slice(c)+m,p=`+`,d=!0):m===""?p===``?l+=`-`:f=`-`:(l+=f+y,f=" ",p=!1)}switch(o.chomp){case"-":break;case"+":for(let m=a;m<i.length;++m)l+=`-`+i[m][0].slice(c);l[l.length-1]!==`+`:p=`+`:(l+=p+m,p=" ",d=!1)}switch(o.chomp){case"-":break;case"+":for(let h=a;h<i.length;++h)l+=`+`+i[h][0].slice(c);l[l.length-1]!==``&&(l+=``);break;default:l+=`-`}let g=r+o.length+e.source.length;return{value:l,type:s,comment:o.comment,range:[r,g,g]}}function mh({offset:t,props:e},n,r){if(e[0].type!=="block-scalar-header")return r(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:o}=e[0],s=o[0],i=0,a="",c=-1;for(let f=1;f<o.length;++f){let p=o[f];if(!a&&(p==="-"||p==="+"))a=p;else{let g=Number(p);!i&&g?i=g:c===-1&&(c=t+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${o}`);let u=!1,d="",l=o.length;for(let f=1;f<e.length;++f){let p=e[f];switch(p.type){case"space":u=!0;case"newline":l+=p.source.length;break;case"comment":n&&!u&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),l+=p.source.length,d=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),l+=p.source.length;break;default:{let g=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",g);let m=p.source;m&&typeof m=="string"&&(l+=m.length)}}}return{mode:s,indent:i,chomp:a,comment:d,length:l}}function hh(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 Ls(t,e,n){let{offset:r,type:o,source:s,end:i}=t,a,c,u=(f,p,g)=>n(r+f,p,g);switch(o){case"scalar":a=R.PLAIN,c=yh(s,u);break;case"single-quoted-scalar":a=R.QUOTE_SINGLE,c=gh(s,u);break;case"double-quoted-scalar":a=R.QUOTE_DOUBLE,c=bh(s,u);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${o}`),{value:"",type:null,comment:"",range:[r,r+s.length,r+s.length]}}let d=r+s.length,l=Ue(i,d,e,n);return{value:c,type:a,comment:l.comment,range:[r,d,l.offset]}}function yh(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}`),pf(t)}function gh(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),pf(t.slice(1,-1)).replace(/''/g,"'")}function pf(t){let e,n;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?+`}let w=r+o.length+t.source.length;return{value:l,type:s,comment:o.comment,range:[r,w,w]}}function ey({offset:e,props:t},n,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:o}=t[0],s=o[0],i=0,a="",c=-1;for(let p=1;p<o.length;++p){let d=o[p];if(!a&&(d==="-"||d==="+"))a=d;else{let w=Number(d);!i&&w?i=w:c===-1&&(c=e+p)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${o}`);let u=!1,f="",l=o.length;for(let p=1;p<t.length;++p){let d=t[p];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,f=d.source.substring(1);break;case"error":r(d,"UNEXPECTED_TOKEN",d.message),l+=d.source.length;break;default:{let w=`Unexpected token in block scalar header: ${d.type}`;r(d,"UNEXPECTED_TOKEN",w);let h=d.source;h&&typeof h=="string"&&(l+=h.length)}}}return{mode:s,indent:i,chomp:a,comment:f,length:l}}function ty(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),s=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let i=1;i<t.length;i+=2)s.push([t[i],t[i+1]]);return s}function Ni(e,t,n){let{offset:r,type:o,source:s,end:i}=e,a,c,u=(p,d,w)=>n(r+p,d,w);switch(o){case"scalar":a=T.PLAIN,c=ny(s,u);break;case"single-quoted-scalar":a=T.QUOTE_SINGLE,c=ry(s,u);break;case"double-quoted-scalar":a=T.QUOTE_DOUBLE,c=oy(s,u);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${o}`),{value:"",type:null,comment:"",range:[r,r+s.length,r+s.length]}}let f=r+s.length,l=ct(i,f,t,n);return{value:c,type:a,comment:l.comment,range:[r,f,l.offset]}}function ny(e,t){let n="";switch(e[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${e[0]}`;break}case"@":case"`":{n=`reserved character ${e[0]}`;break}}return n&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),Dd(e)}function ry(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Dd(e.slice(1,-1)).replace(/''/g,"'")}function Dd(e){let t,n;try{t=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===`+`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let o=r[1],s=" ",i=t.lastIndex;for(n.lastIndex=i;r=n.exec(e);)r[1]===""?s===``?o+=s:s=`-`:(o+=s+r[1],s=" "),i=n.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=i,r=a.exec(t),o+s+(r?.[1]??"")}function bh(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(e),o+s+(r?.[1]??"")}function oy(e,t){let n="";for(let r=1;r<e.length-1;++r){let o=e[r];if(!(o==="\r"&&e[r+1]===``))if(o===`-`){let{fold:s,offset:i}=wh(t,r);n+=s,r=i}else if(o==="\\"){let s=t[++r],i=_h[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+=Eh(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 wh(t,e){let n="",r=t[e+1];for(;(r===" "||r===" "||r===`-`||r==="\r")&&!(r==="\r"&&t[e+2]!==`+`){let{fold:s,offset:i}=sy(e,r);n+=s,r=i}else if(o==="\\"){let s=e[++r],i=iy[s];if(i)n+=i;else if(s===`+`)for(s=e[r+1];s===" "||s===" ";)s=e[++r+1];else if(s==="\r"&&e[r+1]===`+`)for(s=e[++r+1];s===" "||s===" ";)s=e[++r+1];else if(s==="x"||s==="u"||s==="U"){let a=s==="x"?2:s==="u"?4:8;n+=ay(e,r+1,a,t),r+=a}else{let a=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),n+=a}}else if(o===" "||o===" "){let s=r,i=e[r+1];for(;i===" "||i===" ";)i=e[++r+1];i!==`+`&&!(i==="\r"&&e[r+2]===`+`)&&(n+=r>s?e.slice(s,r+1):o)}else n+=o}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),n}function sy(e,t){let n="",r=e[t+1];for(;(r===" "||r===" "||r===`+`||r==="\r")&&!(r==="\r"&&e[t+2]!==``);)r===``&&(n+=`-`),e+=1,r=t[e+1];return n||(n=" "),{fold:n,offset:e}}var _h={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`-`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Eh(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 Ms(t,e,n,r){let{value:o,type:s,comment:i,range:a}=e.type==="block-scalar"?Ps(t,e,r):Ls(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=xh(t.schema,o,c,n,r):e.type==="scalar"?u=Sh(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 xh(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 Sh({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 mf(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 Ah={composeNode:Fs,composeEmptyNode:eo};function Fs(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=vh(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=Ms(t,e,c,r),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{u=df(Ah,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=eo(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 eo(t,e,n,r,{spaceBefore:o,comment:s,anchor:i,tag:a,end:c},u){let d={type:"scalar",offset:mf(e,n,r),indent:-1,source:""},l=Ms(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 vh({options:t},{offset:e,source:n,end:r},o){let s=new Ke(n.substring(1));s.source===""&&o(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&o(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let i=e+n.length,a=Ue(r,i,t.strict,o);return s.range=[e,i,a.offset],a.comment&&(s.comment=a.comment),s}function hf(t,e,{offset:n,start:r,value:o,end:s},i){let a=Object.assign({_directives:e},t),c=new ft(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=je(r,{indicator:"doc-start",next:o??s?.[0],offset:n,onError:i,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,o&&(o.type==="block-map"||o.type==="block-seq")&&!d.hasNewline&&i(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=o?Fs(u,o,d,i):eo(u,d.end,r,null,d,i);let l=c.contents.range[2],f=Ue(s,l,!1,i);return f.comment&&(c.comment=f.comment),c.range=[n,l,f.offset],c}function Zn(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function yf(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?`+`),t+=1,r=e[t+1];return n||(n=" "),{fold:n,offset:t}}var iy={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`+`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function ay(e,t,n,r){let o=e.substr(t,n),i=o.length===n&&/^[0-9a-fA-F]+$/.test(o)?parseInt(o,16):NaN;try{return String.fromCodePoint(i)}catch{let a=e.substr(t-2,n+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}function zi(e,t,n,r){let{value:o,type:s,comment:i,range:a}=t.type==="block-scalar"?Oi(e,t,r):Ni(t,e.options.strict,r),c=n?e.directives.tagName(n.source,l=>r(n,"TAG_RESOLVE_FAILED",l)):null,u;e.options.stringKeys&&e.atKey?u=e.schema[Ie]:c?u=cy(e.schema,o,c,n,r):t.type==="scalar"?u=uy(e,o,t,r):u=e.schema[Ie];let f;try{let l=u.resolve(o,p=>r(n??t,"TAG_RESOLVE_FAILED",p),e.options);f=B(l)?l:new T(l)}catch(l){let p=l instanceof Error?l.message:String(l);r(n??t,"TAG_RESOLVE_FAILED",p),f=new T(o)}return f.range=a,f.source=o,s&&(f.type=s),c&&(f.tag=c),u.format&&(f.format=u.format),i&&(f.comment=i),f}function cy(e,t,n,r,o){if(n==="!")return e[Ie];let s=[];for(let a of e.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(t))return a;let i=e.knownTags[n];return i&&!i.collection?(e.tags.push(Object.assign({},i,{default:!1,test:void 0})),i):(o(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),e[Ie])}function uy({atKey:e,directives:t,schema:n},r,o,s){let i=n.tags.find(a=>(a.default===!0||e&&a.default==="key")&&a.test?.test(r))||n[Ie];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(r))??n[Ie];if(i.tag!==a.tag){let c=t.tagString(i.tag),u=t.tagString(a.tag),f=`Value may be parsed as either ${c} or ${u}`;s(o,"TAG_RESOLVE_FAILED",f,!0)}}return i}function Id(e,t,n){if(t){n??(n=t.length);for(let r=n-1;r>=0;--r){let o=t[r];switch(o.type){case"space":case"comment":case"newline":e-=o.source.length;continue}for(o=t[++r];o?.type==="space";)e+=o.source.length,o=t[++r];break}}return e}var ly={composeNode:$i,composeEmptyNode:Mo};function $i(e,t,n,r){let o=e.atKey,{spaceBefore:s,comment:i,anchor:a,tag:c}=n,u,f=!0;switch(t.type){case"alias":u=fy(e,t,r),(a||c)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":u=zi(e,t,c,r),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{u=Rd(ly,e,t,n,r),a&&(u.anchor=a.source.substring(1))}catch(l){let p=l instanceof Error?l.message:String(l);r(t,"RESOURCE_EXHAUSTION",p)}break;default:{let l=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",l),f=!1}}return u??(u=Mo(e,t.offset,void 0,null,n,r)),a&&u.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),o&&e.options.stringKeys&&(!B(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(u.spaceBefore=!0),i&&(t.type==="scalar"&&t.source===""?u.comment=i:u.commentBefore=i),e.options.keepSourceTokens&&f&&(u.srcToken=t),u}function Mo(e,t,n,r,{spaceBefore:o,comment:s,anchor:i,tag:a,end:c},u){let f={type:"scalar",offset:Id(t,n,r),indent:-1,source:""},l=zi(e,f,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 fy({options:e},{offset:t,source:n,end:r},o){let s=new ht(n.substring(1));s.source===""&&o(t,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&o(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let i=t+n.length,a=ct(r,i,e.strict,o);return s.range=[t,i,a.offset],a.comment&&(s.comment=a.comment),s}function Cd(e,t,{offset:n,start:r,value:o,end:s},i){let a=Object.assign({_directives:t},e),c=new Ot(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=at(r,{indicator:"doc-start",next:o??s?.[0],offset:n,onError:i,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,o&&(o.type==="block-map"||o.type==="block-seq")&&!f.hasNewline&&i(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=o?$i(u,o,f,i):Mo(u,f.end,r,null,f,i);let l=c.contents.range[2],p=ct(s,l,!1,i);return p.comment&&(c.comment=p.comment),c.range=[n,l,p.offset],c}function mr(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n=="string"?n.length:1)]}function Td(e){let t="",n=!1,r=!1;for(let o=0;o<e.length;++o){let s=e[o];switch(s[0]){case"#":t+=(t===""?"":r?``:`-`)+(s.substring(1)||" "),n=!0,r=!1;break;case"%":t[o+1]?.[0]!=="#"&&(o+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:e,afterEmptyLine:r}}var Bn=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,o,s)=>{let i=Zn(n);s?this.warnings.push(new Mn(i,r,o)):this.errors.push(new Ie(i,r,o))},this.directives=new Ze({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:r,afterEmptyLine:o}=yf(this.prelude);if(r){let s=e.contents;if(n)e.comment=e.comment?`${e.comment}-${r}`:r;else if(o||e.directives.docStart||!s)e.commentBefore=r;else if(B(s)&&!s.flow&&s.items.length>0){let i=s.items[0];$(i)&&(i=i.key);let a=i.commentBefore;i.commentBefore=a?`${r}+`)+(s.substring(1)||" "),n=!0,r=!1;break;case"%":e[o+1]?.[0]!=="#"&&(o+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var hr=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,o,s)=>{let i=mr(n);s?this.warnings.push(new dr(i,r,o)):this.errors.push(new Ge(i,r,o))},this.directives=new st({version:t.version||"1.2"}),this.options=t}decorate(t,n){let{comment:r,afterEmptyLine:o}=Td(this.prelude);if(r){let s=t.contents;if(n)t.comment=t.comment?`${t.comment}+${r}`:r;else if(o||t.directives.docStart||!s)t.commentBefore=r;else if(K(s)&&!s.flow&&s.items.length>0){let i=s.items[0];j(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:yf(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,n=!1,r=-1){for(let o of e)yield*this.next(o);yield*this.end(n,r)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(n,r,o)=>{let s=Zn(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",r,o)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=hf(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,r=new Ie(Zn(e),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new Ie(Zn(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=Ue(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let r=this.doc.comment;this.doc.comment=r?`${r}-${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new Ie(Zn(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),o=new ft(void 0,r);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),o.range=[0,n,n],this.decorate(o,!1),yield o}}};var Zs=Symbol("break visit"),Dh=Symbol("skip children"),gf=Symbol("remove item");function At(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),bf(Object.freeze([]),t,e)}At.BREAK=Zs;At.SKIP=Dh;At.REMOVE=gf;At.itemAtPath=(t,e)=>{let n=t;for(let[r,o]of e){let s=n?.[r];if(s&&"items"in s)n=s.items[o];else return}return n};At.parentCollection=(t,e)=>{let n=At.itemAtPath(t,e.slice(0,-1)),r=e[e.length-1][0],o=n?.[r];if(o&&"items"in o)return o;throw new Error("Parent collection not found")};function bf(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=bf(Object.freeze(t.concat([[o,i]])),s.items[i],n);if(typeof a=="number")i=a-1;else{if(a===Zs)return Zs;a===gf&&(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 Bs="\uFEFF",js="",Us="",to="";function wf(t){switch(t){case Bs:return"byte-order-mark";case js:return"doc-mode";case Us:return"flow-error-end";case to: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)t.errors.push(this.errors[s]);for(let s=0;s<this.warnings.length;++s)t.warnings.push(this.warnings[s])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Td(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,n=!1,r=-1){for(let o of t)yield*this.next(o);yield*this.end(n,r)}*next(t){switch(t.type){case"directive":this.directives.add(t.source,(n,r,o)=>{let s=mr(t);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",r,o)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let n=Cd(this.options,this.directives,t,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let n=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new Ge(mr(t),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new Ge(mr(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=ct(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let r=this.doc.comment;this.doc.comment=r?`${r}+${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new Ge(mr(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),o=new Ot(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 Li=Symbol("break visit"),dy=Symbol("skip children"),Od=Symbol("remove item");function Jt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Nd(Object.freeze([]),e,t)}Jt.BREAK=Li;Jt.SKIP=dy;Jt.REMOVE=Od;Jt.itemAtPath=(e,t)=>{let n=e;for(let[r,o]of t){let s=n?.[r];if(s&&"items"in s)n=s.items[o];else return}return n};Jt.parentCollection=(e,t)=>{let n=Jt.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],o=n?.[r];if(o&&"items"in o)return o;throw new Error("Parent collection not found")};function Nd(e,t,n){let r=n(t,e);if(typeof r=="symbol")return r;for(let o of["key","value"]){let s=t[o];if(s&&"items"in s){for(let i=0;i<s.items.length;++i){let a=Nd(Object.freeze(e.concat([[o,i]])),s.items[i],n);if(typeof a=="number")i=a-1;else{if(a===Li)return Li;a===Od&&(s.items.splice(i,1),i-=1)}}typeof r=="function"&&o==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}var Pi="\uFEFF",Fi="",Mi="",Bo="";function zd(e){switch(e){case Pi:return"byte-order-mark";case Fi:return"doc-mode";case Mi:return"flow-error-end";case Bo: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 Oe(t){switch(t){case void 0:case" ":case`-`:case"\r":case" ":return!0;default:return!1}}var _f=new Set("0123456789ABCDEFabcdef"),kh=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),no=new Set(",[]{}"),Ih=new Set(` ,[]{}-\r `),Qs=t=>!t||Ih.has(t),jn=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===`-`?!0:n==="\r"?this.buffer[e+1]===`-`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let n=this.buffer[e];if(this.indentNext>0){let r=0;for(;n===" ";)n=this.buffer[++r+e];if(n==="\r"){let o=this.buffer[r+e+1];if(o===`-`||!o&&!this.atEnd)return e+r+1}return n===`-`||r>=this.indentNext||!n&&!this.atEnd?e+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(e,3);if((r==="---"||r==="...")&&Oe(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`-`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Bs&&(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 js,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let n=this.peek(3);if((n==="---"||n==="...")&&Oe(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,n==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Oe(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Oe(n)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(e[n]){case"#":yield*this.pushCount(e.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Qs),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,n,r=-1;do e=yield*this.pushNewline(),e>0?(n=yield*this.pushSpaces(!1),this.indentValue=r=n):n=0,n+=yield*this.pushSpaces(!0);while(e+n>0);let o=this.getLine();if(o===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&o[0]!=="#"||r===0&&(o.startsWith("---")||o.startsWith("..."))&&Oe(o[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(o[0]==="]"||o[0]==="}")))return this.flowLevel=0,yield Us,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(Qs),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let i=this.charAt(1);if(this.flowKey||Oe(i)||i===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),n=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;n!==-1&&this.buffer[n+1]==="'";)n=this.buffer.indexOf("'",n+2);else for(;n!==-1;){let s=0;for(;this.buffer[n-1-s]==="\\";)s+=1;if(s%2===0)break;n=this.buffer.indexOf('"',n+1)}let r=this.buffer.substring(0,n),o=r.indexOf(`+`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}function Je(e){switch(e){case void 0:case" ":case`+`:case"\r":case" ":return!0;default:return!1}}var $d=new Set("0123456789ABCDEFabcdef"),my=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),qo=new Set(",[]{}"),hy=new Set(` ,[]{}+\r `),Bi=e=>!e||hy.has(e),gr=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,n=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,n=this.buffer[t];for(;n===" "||n===" ";)n=this.buffer[++t];return!n||n==="#"||n===`+`?!0:n==="\r"?this.buffer[t+1]===`+`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let n=this.buffer[t];if(this.indentNext>0){let r=0;for(;n===" ";)n=this.buffer[++r+t];if(n==="\r"){let o=this.buffer[r+t+1];if(o===`+`||!o&&!this.atEnd)return t+r+1}return n===`+`||r>=this.indentNext||!n&&!this.atEnd?t+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&Je(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`+`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Pi&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let n=t.length,r=t.indexOf("#");for(;r!==-1;){let s=t[r-1];if(s===" "||s===" "){n=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let s=t[n-1];if(s===" "||s===" ")n-=1;else break}let o=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-o),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-n),yield*this.pushNewline(),"stream"}return yield Fi,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let n=this.peek(3);if((n==="---"||n==="...")&&Je(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&&!Je(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Je(n)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(t[n]){case"#":yield*this.pushCount(t.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Bi),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,n,r=-1;do t=yield*this.pushNewline(),t>0?(n=yield*this.pushSpaces(!1),this.indentValue=r=n):n=0,n+=yield*this.pushSpaces(!0);while(t+n>0);let o=this.getLine();if(o===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&o[0]!=="#"||r===0&&(o.startsWith("---")||o.startsWith("..."))&&Je(o[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(o[0]==="]"||o[0]==="}")))return this.flowLevel=0,yield Mi,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(Bi),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let i=this.charAt(1);if(this.flowKey||Je(i)||i===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),n=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;n!==-1&&this.buffer[n+1]==="'";)n=this.buffer.indexOf("'",n+2);else for(;n!==-1;){let s=0;for(;this.buffer[n-1-s]==="\\";)s+=1;if(s%2===0)break;n=this.buffer.indexOf('"',n+1)}let r=this.buffer.substring(0,n),o=r.indexOf(``,this.pos);if(o!==-1){for(;o!==-1;){let s=this.continueScalar(o+1);if(s===-1)break;o=r.indexOf(`-`,s)}o!==-1&&(n=o-(r[o-1]==="\r"?2:1))}if(n===-1){if(!this.atEnd)return this.setNext("quoted-scalar");n=this.buffer.length}return yield*this.pushToIndex(n+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let n=this.buffer[++e];if(n==="+")this.blockScalarKeep=!0;else if(n>"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>Oe(n)||n==="#")}*parseBlockScalar(){let e=this.pos-1,n=0,r;e:for(let s=this.pos;r=this.buffer[s];++s)switch(r){case" ":n+=1;break;case`-`:e=s,n=0;break;case"\r":{let i=this.buffer[s+1];if(!i&&!this.atEnd)return this.setNext("block-scalar");if(i===`-`)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=n:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let s=this.continueScalar(e+1);if(s===-1)break;e=this.buffer.indexOf(`-`,s)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let o=e+1;for(r=this.buffer[o];r===" ";)r=this.buffer[++o];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`-`;)r=this.buffer[++o];e=o-1}else if(!this.blockScalarKeep)do{let s=e-1,i=this.buffer[s];i==="\r"&&(i=this.buffer[--s]);let a=s;for(;i===" ";)i=this.buffer[--s];if(i===`-`&&s>=this.pos&&s+1+n>a)e=s;else break}while(!0);return yield to,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,n=this.pos-1,r=this.pos-1,o;for(;o=this.buffer[++r];)if(o===":"){let s=this.buffer[r+1];if(Oe(s)||e&&no.has(s))break;n=r}else if(Oe(o)){let s=this.buffer[r+1];if(o==="\r"&&(s===`+`,s)}o!==-1&&(n=o-(r[o-1]==="\r"?2:1))}if(n===-1){if(!this.atEnd)return this.setNext("quoted-scalar");n=this.buffer.length}return yield*this.pushToIndex(n+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let n=this.buffer[++t];if(n==="+")this.blockScalarKeep=!0;else if(n>"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>Je(n)||n==="#")}*parseBlockScalar(){let t=this.pos-1,n=0,r;e:for(let s=this.pos;r=this.buffer[s];++s)switch(r){case" ":n+=1;break;case`+`:t=s,n=0;break;case"\r":{let i=this.buffer[s+1];if(!i&&!this.atEnd)return this.setNext("block-scalar");if(i===`+`)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=n:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let s=this.continueScalar(t+1);if(s===-1)break;t=this.buffer.indexOf(`+`,s)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let o=t+1;for(r=this.buffer[o];r===" ";)r=this.buffer[++o];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`+`;)r=this.buffer[++o];t=o-1}else if(!this.blockScalarKeep)do{let s=t-1,i=this.buffer[s];i==="\r"&&(i=this.buffer[--s]);let a=s;for(;i===" ";)i=this.buffer[--s];if(i===`+`&&s>=this.pos&&s+1+n>a)t=s;else break}while(!0);return yield Bo,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,n=this.pos-1,r=this.pos-1,o;for(;o=this.buffer[++r];)if(o===":"){let s=this.buffer[r+1];if(Je(s)||t&&qo.has(s))break;n=r}else if(Je(o)){let s=this.buffer[r+1];if(o==="\r"&&(s===``?(r+=1,o=`-`,s=this.buffer[r+1]):n=r),s==="#"||e&&no.has(s))break;if(o===`-`){let i=this.continueScalar(r+1);if(i===-1)break;r=Math.max(r,i-2)}}else{if(e&&no.has(o))break;n=r}return!o&&!this.atEnd?this.setNext("plain-scalar"):(yield to,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(Qs),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(Oe(r)||n&&no.has(r)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!Oe(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(kh.has(n))n=this.buffer[++e];else if(n==="%"&&_f.has(this.buffer[e+1])&&_f.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 vt=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,r=this.lineStarts.length;for(;n<r;){let s=n+r>>1;this.lineStarts[s]<e?n=s+1:r=s}if(this.lineStarts[n]===e)return{line:n+1,col:1};if(n===0)return{line:0,col:e};let o=this.lineStarts[n-1];return{line:n,col:e-o+1}}}};function pt(t,e){for(let n=0;n<t.length;++n)if(t[n].type===e)return!0;return!1}function Ef(t){for(let e=0;e<t.length;++e)switch(t[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function Sf(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 ro(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 Wt(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 oo(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 xf(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!pt(e.start,"explicit-key-ind")&&!pt(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Sf(e.value)?e.value.end?oo(e.value.end,e.sep):e.value.end=e.sep:oo(e.start,e.sep),delete e.sep)}var Un=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new jn,this.onNewLine=e}*parse(e,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(e,n))yield*this.next(r);n||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let n=wf(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"&&xf(n),r.type){case"document":r.value=n;break;case"block-scalar":r.props.push(n);break;case"block-map":{let o=r.items[r.items.length-1];if(o.value){r.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(o.sep)o.value=n;else{Object.assign(o,{key:n,sep:[]}),this.onKeyLine=!o.explicitKey;return}break}case"block-seq":{let o=r.items[r.items.length-1];o.value?r.items.push({start:[],value:n}):o.value=n;break}case"flow-collection":{let o=r.items[r.items.length-1];!o||o.value?r.items.push({start:[],key:n,sep:[]}):o.sep?o.value=n:Object.assign(o,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let o=n.items[n.items.length-1];o&&!o.sep&&!o.value&&o.start.length>0&&Ef(o.start)===-1&&(n.indent===0||o.start.every(s=>s.type!=="comment"||s.indent<n.indent))&&(r.type==="document"?r.end=o.start:r.items.push({start:o.start}),n.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{Ef(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let n=ro(this.peek(2)),r=Wt(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(`+`,s=this.buffer[r+1]):n=r),s==="#"||t&&qo.has(s))break;if(o===`+`){let i=this.continueScalar(r+1);if(i===-1)break;r=Math.max(r,i-2)}}else{if(t&&qo.has(o))break;n=r}return!o&&!this.atEnd?this.setNext("plain-scalar"):(yield Bo,yield*this.pushToIndex(n+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,n){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(n&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Bi),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(Je(r)||n&&qo.has(r)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,n=this.buffer[t];for(;!Je(n)&&n!==">";)n=this.buffer[++t];return yield*this.pushToIndex(n===">"?t+1:t,!1)}else{let t=this.pos+1,n=this.buffer[t];for(;n;)if(my.has(n))n=this.buffer[++t];else if(n==="%"&&$d.has(this.buffer[t+1])&&$d.has(this.buffer[t+2]))n=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`+`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`+`?yield*this.pushCount(2):0}*pushSpaces(t){let n=this.pos-1,r;do r=this.buffer[++n];while(r===" "||t&&r===" ");let o=n-this.pos;return o>0&&(yield this.buffer.substr(this.pos,o),this.pos=n),o}*pushUntil(t){let n=this.pos,r=this.buffer[n];for(;!t(r);)r=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};var Wt=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let n=0,r=this.lineStarts.length;for(;n<r;){let s=n+r>>1;this.lineStarts[s]<t?n=s+1:r=s}if(this.lineStarts[n]===t)return{line:n+1,col:1};if(n===0)return{line:0,col:t};let o=this.lineStarts[n-1];return{line:n,col:t-o+1}}}};function zt(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Ld(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function Fd(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Zo(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function An(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Uo(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function Pd(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!zt(t.start,"explicit-key-ind")&&!zt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Fd(t.value)?t.value.end?Uo(t.value.end,t.sep):t.value.end=t.sep:Uo(t.start,t.sep),delete t.sep)}var yr=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new gr,this.onNewLine=t}*parse(t,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,n))yield*this.next(r);n||(yield*this.end())}*next(t){if(this.source=t,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let n=zd(t);if(n)if(n==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=n,yield*this.step(),n){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let n=t??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let r=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in r?r.indent:0:n.type==="flow-collection"&&r.type==="document"&&(n.indent=0),n.type==="flow-collection"&&Pd(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&&Ld(o.start)===-1&&(n.indent===0||o.start.every(s=>s.type!=="comment"||s.indent<n.indent))&&(r.type==="document"?r.end=o.start:r.items.push({start:o.start}),n.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{Ld(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let n=Zo(this.peek(2)),r=An(n),o;t.end?(o=t.end,o.push(this.sourceToken),delete t.end):o=[this.sourceToken];let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let n=this.source.indexOf(``)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`-`,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(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)){oo(o,n.start),o.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,o=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(o&&n.sep&&!n.value){let i=[];for(let a=0;a<n.sep.length;++a){let c=n.sep[a];switch(c.type){case"newline":i.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(i.length=0);break;default:i.length=0}}i.length>=2&&(s=n.sep.splice(i[1]))}switch(this.type){case"anchor":case"tag":o||n.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):o||n.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(pt(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(Sf(n.key)&&!pt(n.sep,"newline")){let i=Wt(n.start),a=n.key,c=n.sep;c.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:a,sep:c}]})}else s.length>0?n.sep=n.sep.concat(s,this.sourceToken):n.sep.push(this.sourceToken);else if(pt(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let i=Wt(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||o?e.items.push({start:s,key:null,sep:[this.sourceToken]}):pt(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);o||n.value?(e.items.push({start:s,key:i,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(i):(Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!0);return}default:{let i=this.startBlockValue(e);if(i){if(i.type==="block-seq"){if(!n.explicitKey&&n.sep&&!pt(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&e.items.push({start:s});this.stack.push(i);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){oo(o,n.start),o.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=e.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;n.value||pt(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?e.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);!n||n.value?e.items.push({start:[],key:o,sep:[]}):n.sep?this.stack.push(o):Object.assign(n,{key:o,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let o=ro(r),s=Wt(o);xf(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(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,t.indent)){let o=t.items[t.items.length-2]?.value?.end;if(Array.isArray(o)){Uo(o,n.start),o.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,o=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(o&&n.sep&&!n.value){let i=[];for(let 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>t.indent&&(i.length=0);break;default:i.length=0}}i.length>=2&&(s=n.sep.splice(i[1]))}switch(this.type){case"anchor":case"tag":o||n.value?(s.push(this.sourceToken),t.items.push({start:s}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):o||n.value?(s.push(this.sourceToken),t.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(zt(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(Fd(n.key)&&!zt(n.sep,"newline")){let i=An(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(zt(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let i=An(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||o?t.items.push({start:s,key:null,sep:[this.sourceToken]}):zt(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);o||n.value?(t.items.push({start:s,key:i,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(i):(Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!0);return}default:{let i=this.startBlockValue(t);if(i){if(i.type==="block-seq"){if(!n.explicitKey&&n.sep&&!zt(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:s});this.stack.push(i);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,t.indent)){let o=t.items[t.items.length-2]?.value?.end;if(Array.isArray(o)){Uo(o,n.start),o.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=t.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;n.value||zt(n.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let n=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?t.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);!n||n.value?t.items.push({start:[],key:o,sep:[]}):n.sep?this.stack.push(o):Object.assign(n,{key:o,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let o=Zo(r),s=An(o);Pd(t);let i=t.end.splice(1,t.end.length);i.push(this.sourceToken);let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:s,key:t,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let n=this.source.indexOf(``)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`-`,n)+1}return{type: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=ro(e),r=Wt(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=ro(e),r=Wt(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 Oh(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new vt||null,prettyErrors:e}}function Vs(t,e={}){let{lineCounter:n,prettyErrors:r}=Oh(e),o=new Un(n?.addNewLine),s=new Bn(e),i=null;for(let a of s.compose(o.parse(t),!0,t.length))if(!i)i=a;else if(i.options.logLevel!=="silent"){i.errors.push(new Ie(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(i.errors.forEach(Ts(t,n)),i.warnings.forEach(Ts(t,n))),i}var Ce=class extends Error{code;constructor(e){super(`Structured data failed validation: ${e}`),this.name="StructuredDataError",this.code=e}},vf=t=>Ne(JSON.stringify(t)),Af=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(Af(t)===!1)throw new Ce("INVALID");let n=0,r=(s,i)=>{if(i>e.depth)throw new Ce("DEPTH_EXCEEDED");if(typeof s=="string"){if(Ne(s)>e.stringBytes)throw new Ce("STRING_BYTES_EXCEEDED");return s}if(s===null||typeof s=="boolean"||typeof s=="number"&&Number.isFinite(s)&&(Number.isInteger(s)===!1||Number.isSafeInteger(s)))return s;if(Array.isArray(s))return s.map(a=>{if(n+=1,n>e.fields)throw new Ce("FIELDS_EXCEEDED");return r(a,i+1)});if(Af(s)){let a=Object.create(null);for(let[c,u]of Object.entries(s)){if(n+=1,n>e.fields)throw new Ce("FIELDS_EXCEEDED");a[c]=r(u,i+1)}return a}throw new Ce("INVALID")},o=r(t,1);if(vf(o)>e.serializedBytes)throw new Ce("SERIALIZED_BYTES_EXCEEDED");return o};var Y=class extends Error{code;line;column;constructor(e,n,r,o){super(n,{cause:o}),this.name="MarkdownMetadataError",this.code=e,this.line=r?.line,this.column=r?.column}};var Yt=new Uint8Array([239,187,191]),Rf=Yt.byteLength+10,Nh=(t,e,n=0)=>t.byteLength-n<e.byteLength?!1:e.every((r,o)=>t[n+o]===r),Qn=(t,e)=>{let n=0;if(Nh(t,Yt))n=Yt.byteLength;else if(t.byteLength<Yt.byteLength&&Yt.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 $h={bytes:k.frontmatterBytes,depth:k.frontmatterDepth,fields:k.frontmatterFields,stringBytes:k.frontmatterStringBytes,serializedBytes:k.indexedPropertiesBytes},kf=t=>{try{return le(t)}catch{throw new Y("FRONTMATTER_DECODING_FAILED","Markdown frontmatter is not valid UTF-8")}},zh=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"),If=(t,e)=>{let n=new vt,r=Vs(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 Df(o,e)}catch(s){throw s instanceof Ce?zh(s):s}};var Of=async(t,e={})=>{let n={...$h,...e},r=n.bytes+Rf,o=new Uint8Array(r),s=0;for await(let c of En(t)){let u=0;for(;u<c.byteLength;){let d=r-s;if(d<=0)break;let l=Math.max(0,6-s),f=Math.min(c.byteLength-u,l);if(l===0){let m=c.subarray(u,Math.min(c.byteLength,u+d)),h=m.indexOf(10);f=h===-1?m.byteLength:h+1}o.set(c.subarray(u,u+f),s),s+=f,u+=f;let p=o.subarray(0,s),g=Qn(p,!1);if(g===null)return{properties:{},frontmatterBytes:0,consumedBytes:p.length};if(g!==void 0){let m=g.yamlEnd-g.yamlStart;if(m>n.bytes)throw new Y("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter exceeds the byte limit");let h=kf(p.subarray(g.yamlStart,g.yamlEnd));return{properties:If(h,n),frontmatterBytes:m,consumedBytes:g.blockEnd}}}if(s>=r)break}let i=o.subarray(0,s),a=Qn(i,!0);if(a===null)return{properties:{},frontmatterBytes:0,consumedBytes:i.length};if(a!==void 0){let c=a.yamlEnd-a.yamlStart;if(c<=n.bytes){let u=kf(i.subarray(a.yamlStart,a.yamlEnd));return{properties:If(u,n),frontmatterBytes:c,consumedBytes:a.blockEnd}}}throw new Y("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter is not closed within the byte limit")};var so=async(t,e=k.hydratedFileBytes)=>{if(Number.isInteger(e)===!1||e<=0||e>k.hydratedFileBytes)throw new Y("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown body byte limit is outside the supported range");let n;try{n=await $e(t,e)}catch(a){throw a instanceof se?new Y("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown content exceeds the byte limit"):a}let r;try{r=le(n)}catch{throw new Y("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}let s=Qn(n,!0)?.blockEnd??0,i;try{i=s===0?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:Ne(i),sourceBytes:n.byteLength}};var mt=class extends Error{code;referenceId;constructor({code:e,message:n,referenceId:r,cause:o}){super(n,{cause:o}),this.name="MarkdownDocumentError",this.code=e,this.referenceId=r}},Ph=O({source:v(),body:v(),frontmatter:Ae(v(),rt())}),ao=t=>{let e;try{e=Ph.parse(t)}catch(n){throw new mt({code:"INVALID_DOCUMENT",message:"Markdown document is invalid",cause:n})}return Object.freeze({source:e.source,body:e.body,frontmatter:st(e.frontmatter)})},io="#frontmatter",Lh=t=>`${io}${t.slice(1)}`,Mh=t=>{if(t!==io&&t.startsWith(`${io}/`)===!1)throw new mt({code:"UNUSED_REFERENCE",message:`Resolved Markdown reference ${t} is outside frontmatter`,referenceId:t});return`#${t.slice(io.length)}`},Fh=t=>{let e=t.referenceId===void 0?void 0:Lh(t.referenceId),n="INVALID_DOCUMENT";throw(t.code==="INVALID_REFERENCE_MARKER"||t.code==="INVALID_REFERENCE"||t.code==="REFERENCE_NOT_FOUND"||t.code==="INVALID_RESOLVED_VALUE"||t.code==="UNUSED_REFERENCE")&&(n=t.code),new mt({code:n,message:t.message,referenceId:e,cause:t})},Cf=async({source:t,maximumBytes:e=k.hydratedFileBytes})=>{let n;try{n=await $e(t,e)}catch(i){throw i instanceof se?new mt({code:"CONTENT_LIMIT_EXCEEDED",message:"Markdown document exceeds the byte limit",cause:i}):i}let r;try{r=Pt(le(n))}catch(i){throw new mt({code:"CONTENT_DECODING_FAILED",message:"Markdown document is not valid UTF-8",cause:i})}let[o,s]=await Promise.all([so(n,e),Of(n).catch(i=>{if(i instanceof Y)return{properties:{},frontmatterBytes:0,consumedBytes:0};throw i})]);return ao({source:r,body:o.body,frontmatter:s.properties})};var Tf=({document:t,references:e,allowUnresolvedReferences:n=!1})=>{let r=ao(t),o=new Map;for(let[i,a]of e)o.set(Mh(i),a);let s;try{s=Sr({document:r.frontmatter,references:o,allowUnresolvedReferences:n})}catch(i){throw i instanceof de&&Fh(i),i}return ao({...r,frontmatter:s})},Nf=({document:t,representation:e})=>{let n=ao(t);if(e.type==="document")return n.source;if(e.type==="markdown-body")return n.body;if(e.type==="markdown-frontmatter")return n.frontmatter;throw new mt({code:"UNSUPPORTED_REPRESENTATION",message:`Markdown documents do not support ${e.type}`})};var $f=t=>{let e=encodeURIComponent(t);return e==="."?"%2E":e===".."?"%2E%2E":e};var zf=t=>t.split("/").map(e=>{try{return $f(decodeURIComponent(e))}catch{return $f(e)}}).join("/");var Pf=t=>Object.fromEntries(Object.entries(t??{}).map(([e,n])=>[e,n.url]));var co=(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}`},Gs=({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]=Gs({value:t[r],path:o,replacement:n}),s}return typeof r!="string"?t:{...t,[r]:Gs({value:t[r],path:o,replacement:n})}},Zh=({reference:t,runtimeAsset:e})=>{let{url:n,contentRef:r,...o}=e;return{...o,id:t.assetId,src:co(n,t.suffix)}},ht=({value:t,references:e,runtimeAssets:n={},assetUrls:r})=>{let o=t;for(let s of e??[]){let i=r?.[s.assetId],a=n[s.assetId]??(i===void 0?void 0:{url:i});a!==void 0&&(o=Gs({value:o,path:s.path,replacement:s.structured===!0?Zh({reference:s,runtimeAsset:a}):co(a.url,s.suffix)}))}return o};var lo=t=>{let e=t.format==="json"?t.value:t.value.frontmatter;return Ft(e)?e:void 0},qs=({document:t,references:e,runtimeAssets:n})=>{let r=lo(t);if(r===void 0||e===void 0)return t;let o=ht({value:{properties:r},references:e,runtimeAssets:n}).properties;return t.format==="json"?Object.freeze({...t,value:o}):Object.freeze({...t,value:Object.freeze({...t.value,frontmatter:o})})},uo=t=>Object.freeze(t),Lf=async({format:t,source:e,maximumBytes:n=k.hydratedFileBytes})=>uo(t==="json"?{format:t,value:await Tl({source:e,maximumBytes:n})}:{format:t,value:await Cf({source:e,maximumBytes:n})});var Mf=({document:t,references:e,allowUnresolvedReferences:n})=>t.format==="json"?uo({format:t.format,value:Sr({document:t.value,references:e,allowUnresolvedReferences:n})}):uo({format:t.format,value:Tf({document:t.value,references:e,allowUnresolvedReferences:n})}),Ff=({document:t,representation:e})=>t.format==="json"?Nl({document:t.value,representation:e}):Nf({document:t.value,representation:e});var fo=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}},Xt=({node:t,source:e})=>{if(e.revision!==t.revision)throw new fo({code:"REVISION_MISMATCH",documentId:t.id,expectedRevision:t.revision,actualRevision:e.revision});if(t.format!==void 0&&e.format!==t.format)throw new fo({code:"FORMAT_MISMATCH",documentId:t.id,expectedFormat:t.format,actualFormat:e.format});return e};var Ht=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{}},Zf=({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:Ht(s)}),s}};var Bh=O({format:ee(Sn),revision:v().min(1)}),en=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}},Bf=({fetch:t,getRequest:e,getMetadata:n,onEvent:r})=>Zf({load:async(s,{signal:i})=>{let a;try{a=await t(e(s),{signal:i})}catch(d){throw new en({code:"REQUEST_FAILED",message:`Document ${s.id} request failed`,documentId:s.id,cause:d})}if(a.ok===!1)throw new en({code:"HTTP_STATUS",message:`Document ${s.id} request returned status ${a.status}`,documentId:s.id,status:a.status});let c;try{c=Bh.parse(n({node:s,response:a}))}catch(d){throw new en({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 en({code:"BODY_MISSING",message:`Document ${s.id} response body is unavailable`,documentId:s.id});return Object.freeze({...c,source:mr(u)})},onEvent:r});var tn=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Uf=new Set,Js=typeof process=="object"&&process?process:{},Qf=(t,e,n,r)=>{typeof Js.emitWarning=="function"?Js.emitWarning(t,e,n,r):console.error(`[${n}] ${e}: ${t}`)},po=globalThis.AbortController,jf=globalThis.AbortSignal;if(typeof po>"u"){jf=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},po=class{constructor(){e()}signal=new jf;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=Js.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,Qf("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 jh=t=>!Uf.has(t),Zv=Symbol("type"),yt=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Vf=t=>yt(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?nn:null:null,nn=class extends Array{constructor(e){super(e),this.fill(0)}},Ks=class t{heap;length;static#c=!1;static create(e){let n=Vf(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]}},rn=class t{#c;#f;#h;#y;#O;#C;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#g;#r;#n;#e;#u;#d;#a;#s;#b;#i;#w;#_;#p;#E;#D;#l;static unsafeExposeInternals(e){return{starts:e.#_,ttls:e.#p,sizes:e.#w,keyMap:e.#r,keyList:e.#n,valList:e.#e,next:e.#u,prev:e.#d,get head(){return e.#a},get tail(){return e.#s},free:e.#b,isBackgroundFetch:n=>e.#t(n),backgroundFetch:(n,r,o,s)=>e.#$(n,r,o,s),moveToTail:n=>e.#I(n),indexes:n=>e.#x(n),rindexes:n=>e.#S(n),isStale:n=>e.#m(n)}}get max(){return this.#c}get maxSize(){return this.#f}get calculatedSize(){return this.#g}get size(){return this.#o}get fetchMethod(){return this.#O}get memoMethod(){return this.#C}get dispose(){return this.#h}get disposeAfter(){return this.#y}constructor(e){let{max:n=0,ttl:r,ttlResolution:o=1,ttlAutopurge:s,updateAgeOnGet:i,updateAgeOnHas:a,allowStale:c,dispose:u,disposeAfter:d,noDisposeOnSet:l,noUpdateTTL:f,maxSize:p=0,maxEntrySize:g=0,sizeCalculation:m,fetchMethod:h,memoMethod:y,noDeleteOnFetchRejection:x,noDeleteOnStaleGet:S,allowStaleOnFetchRejection:_,allowStaleOnFetchAbort:b,ignoreFetchAbort:A}=e;if(n!==0&&!yt(n))throw new TypeError("max option must be a nonnegative integer");let D=n?Vf(n):Array;if(!D)throw new Error("invalid max value: "+n);if(this.#c=n,this.#f=p,this.maxEntrySize=g||this.#f,this.sizeCalculation=m,this.sizeCalculation){if(!this.#f&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(y!==void 0&&typeof y!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#C=y,h!==void 0&&typeof h!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=h,this.#D=!!h,this.#r=new Map,this.#n=new Array(n).fill(void 0),this.#e=new Array(n).fill(void 0),this.#u=new D(n),this.#d=new D(n),this.#a=0,this.#s=0,this.#b=Ks.create(n),this.#o=0,this.#g=0,typeof u=="function"&&(this.#h=u),typeof d=="function"?(this.#y=d,this.#i=[]):(this.#y=void 0,this.#i=void 0),this.#E=!!this.#h,this.#l=!!this.#y,this.noDisposeOnSet=!!l,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!x,this.allowStaleOnFetchRejection=!!_,this.allowStaleOnFetchAbort=!!b,this.ignoreFetchAbort=!!A,this.maxEntrySize!==0){if(this.#f!==0&&!yt(this.#f))throw new TypeError("maxSize must be a positive integer if specified");if(!yt(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#B()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!S,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!a,this.ttlResolution=yt(o)||o===0?o:1,this.ttlAutopurge=!!s,this.ttl=r||0,this.ttl){if(!yt(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#z()}if(this.#c===0&&this.ttl===0&&this.#f===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#c&&!this.#f){let E="LRU_CACHE_UNBOUNDED";jh(E)&&(Uf.add(E),Qf("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 nn(this.#c),n=new nn(this.#c);this.#p=e,this.#_=n,this.#P=(s,i,a=tn.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?tn.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=tn.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 nn(this.#c);this.#g=0,this.#w=e,this.#k=n=>{this.#g-=e[n],e[n]=0},this.#L=(n,r,o,s)=>{if(this.#t(r))return 0;if(!yt(o))if(s){if(typeof s!="function")throw new TypeError("sizeCalculation must be a function");if(o=s(r,n),!yt(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#T=(n,r,o)=>{if(e[n]=r,this.#f){let s=this.#f-e[n];for(;this.#g>s;)this.#N(!0)}this.#g+=e[n],o&&(o.entrySize=r,o.totalCalculatedSize=this.#g)}}#k=e=>{};#T=(e,n,r)=>{};#L=(e,n,r,o)=>{if(r||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#x({allowStale:e=this.allowStale}={}){if(this.#o)for(let n=this.#s;!(!this.#M(n)||((e||!this.#m(n))&&(yield n),n===this.#a));)n=this.#d[n]}*#S({allowStale:e=this.allowStale}={}){if(this.#o)for(let n=this.#a;!(!this.#M(n)||((e||!this.#m(n))&&(yield n),n===this.#s));)n=this.#u[n]}#M(e){return e!==void 0&&this.#r.get(this.#n[e])===e}*entries(){for(let e of this.#x())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*rentries(){for(let e of this.#S())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*keys(){for(let e of this.#x()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*rkeys(){for(let e of this.#S()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*values(){for(let e of this.#x())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#S())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,n={}){for(let r of this.#x()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;if(s!==void 0&&e(s,this.#n[r],this))return this.get(this.#n[r],n)}}forEach(e,n=this){for(let r of this.#x()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;s!==void 0&&e.call(n,s,this.#n[r],this)}}rforEach(e,n=this){for(let r of this.#S()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;s!==void 0&&e.call(n,s,this.#n[r],this)}}purgeStale(){let e=!1;for(let n of this.#S({allowStale:!0}))this.#m(n)&&(this.#A(this.#n[n],"expire"),e=!0);return e}info(e){let n=this.#r.get(e);if(n===void 0)return;let r=this.#e[n],o=this.#t(r)?r.__staleWhileFetching:r;if(o===void 0)return;let s={value:o};if(this.#p&&this.#_){let i=this.#p[n],a=this.#_[n];if(i&&a){let c=i-(tn.now()-a);s.ttl=c,s.start=Date.now()}}return this.#w&&(s.size=this.#w[n]),s}dump(){let e=[];for(let n of this.#x({allowStale:!0})){let r=this.#n[n],o=this.#e[n],s=this.#t(o)?o.__staleWhileFetching:o;if(s===void 0||r===void 0)continue;let i={value:s};if(this.#p&&this.#_){i.ttl=this.#p[n];let a=tn.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=tn.now()-o}this.set(n,r.value,r)}}set(e,n,r={}){if(n===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:s,noDisposeOnSet:i=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=r,{noUpdateTTL:u=this.noUpdateTTL}=r,d=this.#L(e,n,r.size||0,a);if(this.maxEntrySize&&d>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#A(e,"set"),this;let l=this.#o===0?void 0:this.#r.get(e);if(l===void 0)l=this.#o===0?this.#s:this.#b.length!==0?this.#b.pop():this.#o===this.#c?this.#N(!1):this.#o,this.#n[l]=e,this.#e[l]=n,this.#r.set(e,l),this.#u[this.#s]=l,this.#d[l]=this.#s,this.#s=l,this.#o++,this.#T(l,d,c),c&&(c.set="add"),u=!1;else{this.#I(l);let f=this.#e[l];if(n!==f){if(this.#D&&this.#t(f)){f.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:p}=f;p!==void 0&&!i&&(this.#E&&this.#h?.(p,e,"set"),this.#l&&this.#i?.push([p,e,"set"]))}else i||(this.#E&&this.#h?.(f,e,"set"),this.#l&&this.#i?.push([f,e,"set"]));if(this.#k(l),this.#T(l,d,c),this.#e[l]=n,c){c.set="replace";let p=f&&this.#t(f)?f.__staleWhileFetching:f;p!==void 0&&(c.oldValue=p)}}else c&&(c.set="update")}if(o!==0&&!this.#p&&this.#z(),this.#p&&(u||this.#P(l,o,s),c&&this.#v(c,l)),!i&&this.#l&&this.#i){let f=this.#i,p;for(;p=f?.shift();)this.#y?.(...p)}return this}pop(){try{for(;this.#o;){let e=this.#e[this.#a];if(this.#N(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#l&&this.#i){let e=this.#i,n;for(;n=e?.shift();)this.#y?.(...n)}}}#N(e){let n=this.#a,r=this.#n[n],o=this.#e[n];return this.#D&&this.#t(o)?o.__abortController.abort(new Error("evicted")):(this.#E||this.#l)&&(this.#E&&this.#h?.(o,r,"evict"),this.#l&&this.#i?.push([o,r,"evict"])),this.#k(n),e&&(this.#n[n]=void 0,this.#e[n]=void 0,this.#b.push(n)),this.#o===1?(this.#a=this.#s=0,this.#b.length=0):this.#a=this.#u[n],this.#r.delete(r),this.#o--,n}has(e,n={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:o}=n,s=this.#r.get(e);if(s!==void 0){let i=this.#e[s];if(this.#t(i)&&i.__staleWhileFetching===void 0)return!1;if(this.#m(s))o&&(o.has="stale",this.#v(o,s));else return r&&this.#R(s),o&&(o.has="hit",this.#v(o,s)),!0}else o&&(o.has="miss");return!1}peek(e,n={}){let{allowStale:r=this.allowStale}=n,o=this.#r.get(e);if(o===void 0||!r&&this.#m(o))return;let s=this.#e[o];return this.#t(s)?s.__staleWhileFetching:s}#$(e,n,r,o){let s=n===void 0?void 0:this.#e[n];if(this.#t(s))return s;let i=new po,{signal:a}=r;a?.addEventListener("abort",()=>i.abort(a.reason),{signal:i.signal});let c={signal:i.signal,options:r,context:o},u=(m,h=!1)=>{let{aborted:y}=i.signal,x=r.ignoreFetchAbort&&m!==void 0;if(r.status&&(y&&!h?(r.status.fetchAborted=!0,r.status.fetchError=i.signal.reason,x&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),y&&!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,y=h&&r.allowStaleOnFetchAbort,x=y||r.allowStaleOnFetchRejection,S=x||r.noDeleteOnFetchRejection,_=p;if(this.#e[n]===p&&(!S||_.__staleWhileFetching===void 0?this.#A(e,"fetch"):y||(this.#e[n]=_.__staleWhileFetching)),x)return r.status&&_.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),_.__staleWhileFetching;if(_.__returned===_)throw m},f=(m,h)=>{let y=this.#O?.(e,s,c);y&&y instanceof Promise&&y.then(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),g=Object.assign(p,{__abortController:i,__staleWhileFetching:s,__returned:void 0});return n===void 0?(this.set(e,g,{...c.options,status:void 0}),n=this.#r.get(e)):this.#e[n]=g,g}#t(e){if(!this.#D)return!1;let n=e;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof po}async fetch(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:l=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:g=this.allowStaleOnFetchAbort,context:m,forceRefresh:h=!1,status:y,signal:x}=n;if(!this.#D)return y&&(y.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,status:y});let S={allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,ttl:i,noDisposeOnSet:a,size:c,sizeCalculation:u,noUpdateTTL:d,noDeleteOnFetchRejection:l,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:g,ignoreFetchAbort:p,status:y,signal:x},_=this.#r.get(e);if(_===void 0){y&&(y.fetch="miss");let b=this.#$(e,_,S,m);return b.__returned=b}else{let b=this.#e[_];if(this.#t(b)){let P=r&&b.__staleWhileFetching!==void 0;return y&&(y.fetch="inflight",P&&(y.returnedStale=!0)),P?b.__staleWhileFetching:b.__returned=b}let A=this.#m(_);if(!h&&!A)return y&&(y.fetch="hit"),this.#I(_),o&&this.#R(_),y&&this.#v(y,_),b;let D=this.#$(e,_,S,m),C=D.__staleWhileFetching!==void 0&&r;return y&&(y.fetch=A?"stale":"refresh",C&&A&&(y.returnedStale=!0)),C?D.__staleWhileFetching:D.__returned=D}}async forceFetch(e,n={}){let r=await this.fetch(e,n);if(r===void 0)throw new Error("fetch() returned undefined");return r}memo(e,n={}){let r=this.#C;if(!r)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:s,...i}=n,a=this.get(e,i);if(!s&&a!==void 0)return a;let c=r(e,a,{options:i,context:o});return this.set(e,c,i),c}get(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,status:i}=n,a=this.#r.get(e);if(a!==void 0){let c=this.#e[a],u=this.#t(c);return i&&this.#v(i,a),this.#m(a)?(i&&(i.get="stale"),u?(i&&r&&c.__staleWhileFetching!==void 0&&(i.returnedStale=!0),r?c.__staleWhileFetching:void 0):(s||this.#A(e,"expire"),i&&r&&(i.returnedStale=!0),r?c:void 0)):(i&&(i.get="hit"),u?c.__staleWhileFetching:(this.#I(a),o&&this.#R(a),c))}else i&&(i.get="miss")}#F(e,n){this.#d[n]=e,this.#u[e]=n}#I(e){e!==this.#s&&(e===this.#a?this.#a=this.#u[e]:this.#F(this.#d[e],this.#u[e]),this.#F(this.#s,e),this.#s=e)}delete(e){return this.#A(e,"delete")}#A(e,n){let r=!1;if(this.#o!==0){let o=this.#r.get(e);if(o!==void 0)if(r=!0,this.#o===1)this.#Z(n);else{this.#k(o);let s=this.#e[o];if(this.#t(s)?s.__abortController.abort(new Error("deleted")):(this.#E||this.#l)&&(this.#E&&this.#h?.(s,e,n),this.#l&&this.#i?.push([s,e,n])),this.#r.delete(e),this.#n[o]=void 0,this.#e[o]=void 0,o===this.#s)this.#s=this.#d[o];else if(o===this.#a)this.#a=this.#u[o];else{let i=this.#d[o];this.#u[i]=this.#u[o];let a=this.#u[o];this.#d[a]=this.#d[o]}this.#o--,this.#b.push(o)}}if(this.#l&&this.#i?.length){let o=this.#i,s;for(;s=o?.shift();)this.#y?.(...s)}return r}clear(){return this.#Z("delete")}#Z(e){for(let n of this.#S({allowStale:!0})){let r=this.#e[n];if(this.#t(r))r.__abortController.abort(new Error("deleted"));else{let o=this.#n[n];this.#E&&this.#h?.(r,o,e),this.#l&&this.#i?.push([r,o,e])}}if(this.#r.clear(),this.#e.fill(void 0),this.#n.fill(void 0),this.#p&&this.#_&&(this.#p.fill(0),this.#_.fill(0)),this.#w&&this.#w.fill(0),this.#a=0,this.#s=0,this.#b.length=0,this.#g=0,this.#o=0,this.#l&&this.#i){let n=this.#i,r;for(;r=n?.shift();)this.#y?.(...r)}}};var Ws=({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 rn({maxSize:t,sizeCalculation:e=>Math.max(1,e.bytes.byteLength)})},Vn=class extends Error{code="CONTENT_LIMIT_EXCEEDED";documentId;contentByteLimit;constructor({message:e,documentId:n,contentByteLimit:r,cause:o}){super(e,{cause:o}),this.name="CachedDocumentLoaderError",this.documentId=n,this.contentByteLimit=r}},mo=({contentRef:t,revision:e,format:n})=>fe([t,e,n??null]),Uh=t=>{if(typeof t!="object"||t===null)return!1;let e=t;return fl(e.format)&&typeof e.revision=="string"&&e.revision.length>0&&e.bytes instanceof Uint8Array},Gf=t=>Object.freeze({format:t.format,revision:t.revision,source:t.bytes}),qf=({load:t,cache:e,maximumBytes:n=k.hydratedFileBytes,onEvent:r})=>{let o=new Map;return async(s,i)=>{let a=mo(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:Ht(m)})}if(Uh(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}),Gf(l);ae(r,{type:"document-cache-miss",documentId:s.id,revision:s.revision});let f=Xt({node:s,source:await t(s,i)}),p;try{p=await $e(f.source,n)}catch(m){throw m instanceof se?new Vn({message:`Document ${s.id} exceeds the cache byte limit`,documentId:s.id,contentByteLimit:n,cause:m}):m}let g=Object.freeze({format:f.format,revision:f.revision,bytes:p});try{await e.set(a,g),ae(r,{type:"document-cache-stored",documentId:s.id,revision:s.revision})}catch(m){ae(r,{type:"document-cache-write-failed",documentId:s.id,revision:s.revision,errorCode:Ht(m)})}return Gf(g)})();c.set(i.signal,d);try{return await d}finally{c.delete(i.signal),c.size===0&&o.delete(a)}}};var me=class extends Error{code;resourceIds;constructor({code:e,message:n,resourceIds:r=[],cause:o}){super(n,{cause:o}),this.name="ResourceResolutionError",this.code=e,this.resourceIds=Object.freeze([...r])}},Gn=t=>{if(t?.aborted)throw new me({code:"REQUEST_CANCELLED",message:"Resource resolution was cancelled",cause:t.reason})},Qh=({resourcesById:t,rootIds:e})=>{let n=new Map,r=[],o=[],s=(i,a)=>{let c=t.get(i);if(c===void 0)throw new me({code:a===void 0?"ROOT_NOT_FOUND":"DEPENDENCY_NOT_FOUND",message:a===void 0?`Resource graph root ${i} does not exist`:`Resource ${a} dependency ${i} does not exist`,resourceIds:a===void 0?[i]:[a,i]});let u=n.get(i);if(u!=="visited"){if(u==="visiting"){let d=r.indexOf(i),l=[...r.slice(d),i];throw new me({code:"CYCLE",message:`Resource graph contains a cycle: ${l.join(" -> ")}`,resourceIds:l})}n.set(i,"visiting"),r.push(i);for(let d of c.dependencies)s(d,c.id);r.pop(),n.set(i,"visited"),o.push(c)}};for(let i of new Set(e))s(i);return o},Jf=async({resources:t,rootIds:e,concurrency:n,signal:r})=>{if(Number.isSafeInteger(n)===!1||n<=0)throw new TypeError("Resource resolution concurrency must be positive");Gn(r);let o=new Map;for(let l of t){if(o.has(l.id))throw new me({code:"DUPLICATE_RESOURCE",message:`Resource graph contains duplicate resource ${l.id}`,resourceIds:[l.id]});o.set(l.id,l)}let s=Qh({resourcesById:o,rootIds:e}),i=Er({concurrency:n,signal:r}),a=new Map,c=new Map,u=l=>{let f=c.get(l);if(f!==void 0)return f;let p=o.get(l),g=(async()=>{let m=new Map,h;try{h=await Promise.all(p.dependencies.map(u))}catch(y){throw y instanceof me&&y.code==="RESOLUTION_FAILED"?new me({code:y.code,message:`Resource dependency path ${[p.id,...y.resourceIds].join(" -> ")} could not be resolved`,resourceIds:[p.id,...y.resourceIds],cause:y.cause}):y}for(let[y,x]of p.dependencies.entries())m.set(x,h[y]);Gn(r);try{return await i(async()=>{Gn(r);let y=await Mt(p.resolve({documents:m,signal:r}),r);return Gn(r),y})}catch(y){throw r?.aborted&&Gn(r),y instanceof me?y:new me({code:"RESOLUTION_FAILED",message:`Resource ${p.id} could not be resolved`,resourceIds:[p.id],cause:y})}})();return c.set(l,g),g},d=await Promise.all(e.map(u));for(let l of s){let f=await c.get(l.id);a.set(l.id,f)}return Object.freeze({roots:Object.freeze(d),documents:a})};var _e=class extends Error{code;documentId;referenceId;constructor({code:e,message:n,documentId:r,referenceId:o,cause:s}){super(n,{cause:s}),this.name="DocumentGraphResolutionError",this.code=e,this.documentId=r,this.referenceId=o}},ho=t=>{if(t?.aborted)throw new _e({code:"REQUEST_CANCELLED",message:"Document graph resolution was cancelled",cause:t.reason})},Kf=async({graph:t,rootIds:e,concurrency:n,signal:r,load:o,select:s,assemble:i})=>{ho(r);let a=gr({graph:t,rootIds:e}),c=new Map(a.map(p=>[p.id,p])),u=new Map,d=new Map;for(let p of a){let g=d.get(p.contentRef);g===void 0?d.set(p.contentRef,{representative:p,nodes:[p]}):g.nodes.push(p)}await _r([...d.values()],n,async p=>{ho(r);let g=p.representative;try{let m=await Mt(o(g,{signal:r}),r);for(let h of p.nodes)u.set(h.id,m)}catch(m){throw r?.aborted&&ho(r),new _e({code:"DOCUMENT_LOAD_FAILED",message:`Document ${g.id} could not be loaded`,documentId:g.id,cause:m})}});let l=Lt(t.edges),f=a.map(p=>({id:p.id,dependencies:(l.get(p.id)??[]).map(g=>g.reference.documentId),resolve:async({documents:g})=>{ho(r);let m=new Map;for(let y of l.get(p.id)??[]){let x=c.get(y.reference.documentId);if(x===void 0||g.has(y.reference.documentId)===!1)throw new _e({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${p.id} dependency ${y.reference.documentId} is unavailable`,documentId:p.id,referenceId:y.referenceId});let S=g.get(y.reference.documentId),_;if(s===void 0){if(y.reference.representation.type!=="document")throw new _e({code:"REPRESENTATION_SELECTOR_REQUIRED",message:`Document ${p.id} reference ${y.referenceId} requires a representation selector`,documentId:p.id,referenceId:y.referenceId});_=S}else try{_=await s({reference:y.reference,value:S,sourceNode:p,targetNode:x})}catch(b){throw new _e({code:"DOCUMENT_SELECTION_FAILED",message:`Document ${p.id} reference ${y.referenceId} could not be selected`,documentId:p.id,referenceId:y.referenceId,cause:b})}m.set(y.referenceId,_)}if(u.has(p.id)===!1)throw new _e({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${p.id} source is unavailable`,documentId:p.id});let h=u.get(p.id);try{return await i({node:p,source:h,references:m})}catch(y){throw y instanceof _e?y:new _e({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${p.id} could not be assembled`,documentId:p.id,cause:y})}}}));try{let p=await Jf({resources:f,rootIds:e,concurrency:1,signal:r});return Object.freeze({roots:p.roots,values:p.documents})}catch(p){throw p instanceof me&&p.cause instanceof _e?p.cause:p instanceof me&&p.code==="REQUEST_CANCELLED"?new _e({code:"REQUEST_CANCELLED",message:"Document graph resolution was cancelled",cause:p.cause}):p}};var Dt=class extends Error{code;documentId;documentCount;documentLimit;contentByteLimit;totalBytes;totalByteLimit;constructor({code:e,message:n,documentId:r,documentCount:o,documentLimit:s,contentByteLimit:i,totalBytes:a,totalByteLimit:c,cause:u}){super(n,{cause:u}),this.name="DocumentResolutionLimitError",this.code=e,this.documentId=r,this.documentCount=o,this.documentLimit=s,this.contentByteLimit=i,this.totalBytes=a,this.totalByteLimit=c}},Vh=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=gr({graph:t,rootIds:e}).length,f={rootCount:e.length,documentCount:l};ae(a,{type:"resolution-started",...f});try{if(l>s)throw new Dt({code:"DOCUMENT_COUNT_EXCEEDED",message:"Document graph resolution exceeds the document limit",documentCount:l,documentLimit:s});let p=0,g=Promise.resolve(),m=await Kf({graph:t,rootIds:e,concurrency:n,signal:i,load:async(h,y)=>{let x=g,S=()=>{};g=new Promise(b=>{S=b});let _;try{_={status:"fulfilled",value:await d(h,y)}}catch(b){_={status:"rejected",reason:b}}await x;try{if(_.status==="rejected")throw _.reason;if(_.value.byteLength>r)throw new Dt({code:"CONTENT_LIMIT_EXCEEDED",message:`Document ${h.id} exceeds the byte limit`,documentId:h.id,contentByteLimit:r,cause:new se});let b=p+_.value.byteLength;if(b>o)throw new Dt({code:"TOTAL_BYTES_EXCEEDED",message:"Document graph resolution exceeds the total byte limit",documentId:h.id,totalBytes:b,totalByteLimit:o});return p=b,await _.value.parse()}finally{S()}},select:({reference:h,value:y})=>Ff({document:y,representation:h.representation}),assemble:({node:h,source:y,references:x})=>{let S=Mf({document:y,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:Ht(p)}),p}},Wf=({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 rn({maxSize:o,sizeCalculation:({byteLength:f})=>Math.max(1,f)}),i=new Map,a=Er({concurrency:e,signal:n}),c=f=>{if(f!==void 0&&f!==n)throw new TypeError("Document resolution session signal does not match");n?.throwIfAborted()},u=async f=>(c(),await Mt(f,n)),d=async(f,p)=>{c(p.signal);let g=mo(f),m=s.get(g);if(m!==void 0)return m;let h=i.get(g);if(h!==void 0)return await u(h);let y=a(async()=>{c(p.signal);let x=Xt({node:f,source:await t(f,{signal:n})});c(p.signal);let S=await ss(x.source,r+1);c(p.signal);let _,b=Object.freeze({format:x.format,revision:x.revision,bytes:S,byteLength:S.byteLength,parse:()=>(_??=Lf({format:x.format,source:S,maximumBytes:r}),_)});return b.byteLength<=o&&s.set(g,b),b});i.set(g,y);try{return await u(y)}finally{i.delete(g)}};return Object.freeze({getCached:f=>{c();let p=s.get(mo(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 Vh({...f,concurrency:e,maximumBytes:r,signal:n,load:d})})};var Yf=t=>{if(t.output.mode==="all")return"all";let e=[];for(let{field:n}of dr(t.where))n[0]==="properties"&&e.push(n);for(let{field:n}of t.sort)n[0]==="properties"&&e.push(n);if(t.output.mode==="fields")for(let n of t.output.fields)n[0]==="properties"&&e.push(n);return e},Xf=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",...Ol(e)]}catch{return}},Hf=(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},ed=({queryPaths:t,referenceId:e})=>{let n=Xf(e);return n!==void 0&&(t==="all"||t.some(r=>Hf(r,n)))},td=({graph:t,sourceId:e,field:n})=>n[0]!=="properties"?!1:t.edges.some(r=>{if(r.sourceId!==e)return!1;let o=Xf(r.referenceId);return o!==void 0&&Hf(n,o)}),nd=({graph:t,query:e})=>{let n=Yf(e),r=new Set;for(let o of t.edges)ed({queryPaths:n,referenceId:o.referenceId})&&r.add(o.sourceId);return[...r]},rd=({graph:t,query:e,rootIds:n})=>{let r=Yf(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)&&ed({queryPaths:r,referenceId:l.referenceId})&&(c.add(l),d(l.reference.documentId));return An({nodes:[...a].map(l=>{let f=s.get(l);if(f===void 0)throw new Error(`Document graph query root ${l} does not exist`);return f}),edges:[...c]})};var od=({artifact:t})=>{if(t.documentGraph===void 0)return;let e=new Map(t.documents.map(s=>[s._id,s])),n=new Map(t.documentGraph.nodes.map(s=>[s.id,s])),r=new Map;for(let{sourceId:s}of t.documentGraph.edges){if(n.has(s))continue;let i=e.get(s);if(i?.properties===void 0)throw new Error(`Runtime document graph source ${s} is unavailable`);r.set(s,i),n.set(s,{id:s,revision:s,contentRef:s,format:"json"})}return{graph:An({nodes:[...n.values()],edges:t.documentGraph.edges.map(({sourceId:s,referenceId:i,documentId:a,representation:c})=>{let u=n.get(a);if(u===void 0)throw new Error(`Runtime document graph target ${a} is unavailable`);return{sourceId:s,referenceId:i,reference:{documentId:a,revision:u.revision,representation:c}}})}),inlineDocuments:r}};var sd=({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=co(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}},Gh=t=>{if(t===null)return[];let e=Array.isArray(t)?t:[t],n=new Map;for(let r of e){if(typeof r!="object"||r===null||!("_id"in r)||typeof r._id!="string"||!("revision"in r)||typeof r.revision!="string"||!("contentRef"in r)||typeof r.contentRef!="string")throw new X({code:"CONTENT_IDENTITY_REQUIRED",message:"Hydrated query results must retain _id, revision, and contentRef"});let o=n.get(r._id);if(o!==void 0&&(o.revision!==r.revision||o.contentRef!==r.contentRef))throw new X({code:"CONTENT_IDENTITY_REQUIRED",message:"A selected asset ID has conflicting content identity",details:{assetId:r._id}});n.set(r._id,{_id:r._id,revision:r.revision,contentRef:r.contentRef})}return Array.from(n.values())},qh=t=>typeof t.mimeType=="string"&&(t.mimeType.startsWith("text/")||["application/json","application/javascript","application/xml","image/svg+xml"].includes(t.mimeType)),Jh=async({read:t,contentRef:e,range:n,maximumBytes:r})=>{if(r===0)return new Uint8Array;let o=await t(e,n);try{return await $e(o.data,r)}catch(s){throw s instanceof se?new X({code:"CONTENT_LIMIT_EXCEEDED",message:"Asset storage returned more content than requested"}):s}},Kh=t=>{try{return le(t)}catch{throw new X({code:"CONTENT_DECODING_FAILED",message:"Selected asset content is not valid UTF-8"})}},Wh=(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},id=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}})},ad=async({result:t,documents:e,options:n,read:r,assetReferences:o,assetUrls:s})=>{if(n.mode==="none")return{content:{},hydratedFileCount:0,hydratedBytes:0};let i=Gh(t);if(i.length>k.hydratedFileCount)throw new X({code:"CONTENT_LIMIT_EXCEEDED",message:"Too many selected assets requested content hydration",details:{fileCount:i.length,fileCountLimit:k.hydratedFileCount}});let a=new Map(e.map(m=>[m._id,m])),c=i.map(m=>{let h=a.get(m._id);try{if(h===void 0||h.revision!==m.revision||h.contentRef!==m.contentRef||typeof h.size!="number"||typeof h.mimeType!="string")throw new X({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset content identity is stale or unavailable",details:{assetId:m._id}});let y={...h,size:h.size,mimeType:h.mimeType};if(qh(y)===!1)throw new X({code:"CONTENT_NOT_TEXT",message:"Selected binary asset cannot be embedded as text",details:{assetId:m._id,mimeType:y.mimeType}});return{status:"fulfilled",value:{identity:m,document:y,readLength:Wh(y,n)}}}catch(y){return{status:"rejected",reason:y,document:h??{_id:m._id}}}}),u=c.flatMap(m=>m.status==="rejected"?[m]:[]);u.length>0&&id(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 _r(d,k.concurrentContentReads,async m=>{try{let h=n.mode==="range"?{offset:n.offset,length:m.readLength}:m.readLength===0?void 0:{offset:0,length:m.readLength},y=await Jh({read:r,contentRef:m.identity.contentRef,range:h,maximumBytes:m.readLength});if(y.byteLength!==m.readLength)throw new X({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset bytes do not match canonical metadata",details:{assetId:m.identity._id}});let x;if(n.mode==="markdown-body-ref")try{x=(await so(y,m.readLength||1)).body;let _=o?.[m.identity.contentRef];_!==void 0&&s!==void 0&&(x=sd({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=Kh(y);let S=Ne(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:y.byteLength,total:m.document.size}}:{}}}}}catch(h){return{status:"rejected",reason:h,document:m.document}}}),p=f.flatMap(m=>m.status==="rejected"?[m]:[]);p.length>0&&id(p);let g=f.flatMap(m=>m.status==="fulfilled"?[m.value]:[]);return{content:Object.fromEntries(g.map(({id:m,content:h})=>[m,h])),hydratedFileCount:d.length,hydratedBytes:g.reduce((m,{returnedBytes:h})=>m+h,0)}};var OD=v().datetime({offset:!0}).transform(t=>new Date(t).toISOString());var Yh=/^[A-Za-z_][A-Za-z0-9_]*$/,cd=(t,e)=>Yh.test(e)?`${t}.${e}`:`${t}[${JSON.stringify(e)}]`;var ud=({document:t,includes:e})=>{let n={};for(let r of xl){let o=t[r];o!==void 0&&e(r)&&(n[r]=o)}return n},gt=Symbol("missing property selection"),Ys=(t,e)=>{if(e.some(r=>r.length===0)||typeof xr(t)=="string")return t;if(Array.isArray(t)){let r=e.filter(([s])=>s==="*").map(s=>s.slice(1));if(r.length===0)return gt;let o=t.map(s=>Ys(s,r));return o.some(s=>s!==gt)?o.map(s=>s===gt?null:s):gt}if(typeof t!="object"||t===null)return gt;let n={};for(let[r,o]of Object.entries(t)){let s=e.filter(([a])=>a===r).map(a=>a.slice(1));if(s.length===0)continue;let i=Ys(o,s);i!==gt&&(n[r]=i)}return Object.keys(n).length===0?gt:n},ld=({properties:t,fields:e})=>{let n=e.filter(([o])=>o==="properties").map(o=>o.slice(1)),r=Ys(t,n);return r===gt?{}:r};var Ee=class extends Error{code;issues;details;constructor(e,n){super(e,n),this.name="AssetQueryExecutionError",this.code=n?.code??"INVALID_REQUEST",this.issues=n?.issues,this.details=n?.details}},qn=class extends Ee{code="MULTIPLE_RESULTS";matchedCount;constructor(e){super(`Expected at most one asset, but the query matched ${e}.`),this.matchedCount=e,this.name="AssetQueryMultipleResultsError"}},sn=class extends Error{constructor(){super("The requested asset index revision is stale"),this.name="AssetIndexRevisionError"}},Xs=t=>{if(t[0]!=="properties")return t[0];let e="properties";for(let n of t.slice(1))e=cd(e,n);return e},fd=({filter:t,fieldTypes:e})=>vl(e).includes(t.operator),dd=(t,e)=>t!==void 0&&Object.hasOwn(t.fields,e)?t.fields[e]:void 0,Xh=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"},Hh=({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}},pd=({filter:t,fieldTypes:e,path:n})=>{let r=Hh({operator:t.operator,fieldTypes:e});return r===void 0?[]:(t.operator==="in"?t.value:[t.value]).flatMap((s,i)=>r.some(a=>a===Xh(s))?[]:[t.operator==="in"?[...n,"value",String(i)]:[...n,"value"]])},ei=(t,e=["query","where"])=>"field"in t?[{filter:t,path:e}]:"all"in t?t.all.flatMap((n,r)=>ei(n,[...e,"all",String(r)])):t.any.flatMap((n,r)=>ei(n,[...e,"any",String(r)])),ey=({query:t,catalog:e})=>{let n=it.safeParse(t);if(n.success===!1)return{success:!1,issues:n.error.issues.map(u=>({severity:"error",code:u.code,path:["query",...u.path.map(String)],message:u.message}))};let r=n.data,o=new Map,s=[],i=[],a=(u,d,l)=>{s.push(l),i.push({severity:"warning",code:u,path:d,message:l})};for(let{filter:u,path:d}of ei(r.where)){let l=Xs(u.field);if(o.set(l,u.field),u.field[0]==="properties"){let f=dd(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&&fd({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 pd({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=fs[u.field[0]];if(fd({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 pd({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=Xs(d.field);if(o.set(l,d.field),d.field[0]==="properties"){let f=dd(e,l);e!==void 0&&f===void 0?a("UNOBSERVED_FIELD",["query","sort",String(u),"field"],`Asset field ${l} is not currently observed`):f!==void 0&&f.types.some(p=>p==="object"||p==="array")&&a("STRUCTURED_SORT_ORDER",["query","sort",String(u),"field"],`Asset field ${l} currently includes structured values that use deterministic JSON sort order`)}}if(r.output.mode==="fields")for(let u of r.output.fields){let d=Xs(u);o.set(d,u)}let c=[...new Map(i.map(u=>[JSON.stringify([u.code,u.path,u.message]),u])).values()];return{success:c.some(({severity:u})=>u==="error")===!1,query:r,referencedFieldPaths:[...o.values()],warnings:[...new Set(s)],issues:c}},ty=({query:t,catalog:e})=>{let n=ey({query:t,catalog:e});if(n.success===!1){let r=n.issues.filter(({severity:o})=>o==="error");throw new Ee(r.length===1?r[0].message:`${r.length} invalid query operations found`,{issues:n.issues})}return{query:n.query,referencedFieldPaths:n.referencedFieldPaths,warnings:n.warnings,warningIssues:n.issues}},ti=(t,e,n)=>{let r=e[0]==="id"?t._id:wr(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},ny=t=>typeof t=="string"||Array.isArray(t)?t.length===0:typeof t=="object"&&t!==null&&Object.keys(t).length===0,ry=(t,e)=>{if(typeof t=="number"&&typeof e=="number")return t-e;if(typeof t=="string"&&typeof e=="string")return ze(t,e)},md=(t,e)=>{if(t.field.length!==1||t.field[0]!=="path"||typeof e!="string")return[e];let n=zf(e);return n===e?[e]:[e,n]},ni=(t,e,n)=>{let r=ti(t,e.field,n);if(e.operator==="exists")return r!=null===e.value;if(e.operator==="isEmpty")return ny(r)===e.value;let o=md(e,e.value);if(e.operator==="eq")return o.some(i=>xn(r,i));if(e.operator==="ne")return o.every(i=>xn(r,i)===!1);if(e.operator==="in")return e.value.some(i=>md(e,i).some(a=>xn(r,a)));if(e.operator==="contains")return typeof r=="string"?o.some(i=>typeof i=="string"&&r.includes(i)):Array.isArray(r)&&r.some(i=>xn(i,e.value));if(e.operator==="startsWith")return typeof r=="string"&&o.some(i=>typeof i=="string"&&r.startsWith(i));if(e.operator==="endsWith")return typeof r=="string"&&o.some(i=>typeof i=="string"&&r.endsWith(i));let s=ry(r,o[o.length-1]);return s===void 0?!1:e.operator==="gt"?s>0:e.operator==="gte"?s>=0:e.operator==="lt"?s<0:s<=0},oy=({document:t,where:e,runtimeAsset:n,filterKeys:r,filterResults:o})=>zt(e,s=>{let i=r.get(s)??fe(s),a=o.get(i);if(a!==void 0)return a;let c=ni(t,s,n);return o.set(i,c),c})===!0,sy=({document:t,content:e})=>{if(e.mode!=="markdown-body-ref")return!0;let n=t.mimeType===void 0?void 0:dl(t.mimeType);return n==="markdown"||n==="mdx"?!0:t.extension==="md"||t.extension==="mdx"},iy=(t,e)=>{let n=t==null,r=e==null;return n||r?n===r?0:n?1:-1:typeof t=="number"&&typeof e=="number"?t-e:(typeof t=="string"||typeof t=="boolean")&&(typeof e=="string"||typeof e=="boolean")?ze(String(t),String(e)):ze(fe(t),fe(e))},ay=({left:t,right:e,sort:n,runtimeAssets:r})=>{for(let o of n){let s=iy(ti(t,o.field,r?.[t._id]),ti(e,o.field,r?.[e._id]));if(s!==0)return o.direction==="asc"?s:-s}return ze(t._id,e._id)};var cy=(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=ld({properties:t.properties,fields:e.fields});return Object.keys(n).length===0?void 0:n},on=(t,e)=>t.includeMetadata&&Sl(e)||t.mode==="fields"&&t.fields.some(n=>n.length===1&&n[0]===e),uy=t=>t.mode==="all"||t.mode==="fields"&&t.fields.some(e=>e.length===1&&e[0]==="excerpt"),ly=(t,e,n)=>{if(on(e,"url")&&n===void 0)throw new Ee(`Asset URL is unavailable for ${t._id}`,{details:{assetId:t._id}});let r=cy(t,e),o=n?.width!==void 0&&n.height!==void 0;return{...n!==void 0&&on(e,"url")?{url:n.url}:{},...o&&on(e,"width")?{width:n.width}:{},...o&&on(e,"height")?{height:n.height}:{},...ud({document:t,includes:s=>on(e,s)}),...r===void 0?{}:{properties:r},...t.excerpt===void 0||uy(e)===!1?{}:{excerpt:t.excerpt},...t.metadataError===void 0||e.includeMetadata===!1?{}:{metadataError:t.metadataError}}},ri=t=>{let e=Ne(fe(t));if(e>k.resultBytes)throw new Ee("Asset query result exceeds the byte limit",{code:"CONTENT_LIMIT_EXCEEDED",details:{resultBytes:e,resultByteLimit:k.resultBytes}})},yo=(t,e,n)=>{t[e]={status:"rejected",reason:n}},fy=({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=ty({query:a,catalog:e}).query}catch(l){yo(n,i,l);continue}for(let l of dr(c.where))o.set(l,fe(l));let u=fe(c.sort),d=r.get(u);d===void 0&&(d={sort:c.sort,documents:new Set,sorted:[]},r.set(u,d)),s.push({index:i,query:c,matches:new Map,sortGroup:d})}return{filterKeys:o,preparedQueries:s,sortGroups:r}},hd=({preparedQueries:t,results:e,createReason:n})=>{for(let{index:r}of t)yo(e,r,n())},Hs=t=>t.map(e=>{if(e===void 0)throw new Error("Asset query result was not settled");return e}),dy=({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(sy({document:i,content:d.content})===!1||oy({document:i,where:d.where,runtimeAsset:a,filterKeys:n,filterResults:c})===!1)continue;let l=ly(i,d.output,a);if(d.content.mode==="none"&&Object.keys(l).length===0&&d.output.mode!=="all"&&on(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){yo(o,u.index,l)}}}for(let i of r.values())i.sorted=[...i.documents].sort((a,c)=>ay({left:a,right:c,sort:i.sort,runtimeAssets:s}))},py=async({preparedQueries:t,results:e,read:n,assetReferences:r,assetUrls:o})=>{await Promise.all(t.map(async s=>{if(e[s.index]!==void 0)return;let{query:i}=s;try{let a=s.sortGroup.sorted.flatMap(p=>{let g=s.matches.get(p);return g===void 0?[]:[g]}),c=i.result??"many";if(c==="one"&&a.length>1)throw new qn(a.length);let u=c==="many"?a.slice(i.offset,i.offset+i.limit):c==="last"?a.slice(-1):a.slice(0,1),d=u.map(({document:p})=>p),l=u.map(({item:p})=>p);if(i.content.mode!=="none"){let p=i.content;if(n===void 0)throw new Ee("Asset content reader is unavailable");let g=await ad({result:d,documents:d,options:p,read:n,assetReferences:r,assetUrls:r===void 0?void 0:o});l=d.map((m,h)=>{let y=g.content[m._id];if(y===void 0)throw new Ee("Selected asset content could not be read");return{...l[h],content:{encoding:y.encoding,text:y.text,...y.range===void 0?{}:{range:y.range}}}})}let f=c==="many"?{items:l,totalCount:a.length,hasMore:i.offset+u.length<a.length}:{item:l[0]??null,totalCount:a.length};ri(f),e[s.index]={status:"fulfilled",value:f}}catch(a){yo(e,s.index,a)}}))},yd=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}=fy({inputs:t,catalog:e,results:a});if(n.length>k.candidateDocuments)return hd({preparedQueries:u,results:a,createReason:()=>new Ee("Asset query document limit was exceeded",{code:"CONTENT_LIMIT_EXCEEDED",details:{documentCount:n.length,documentLimit:k.candidateDocuments}})}),Hs(a);let l;try{l=n.map(p=>ht({value:p,references:i?.[p._id],runtimeAssets:o??{}}))}catch(p){return hd({preparedQueries:u,results:a,createReason:()=>p}),Hs(a)}dy({preparedQueries:u,documents:l,filterKeys:c,sortGroups:d,results:a,runtimeAssets:o});let f=Pf(o);return await py({preparedQueries:u,results:a,read:r,assetReferences:s,assetUrls:f}),Hs(a)};var my=async t=>await cl(fe(it.parse(t)));var hy=({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}},yy=t=>ds.parse({items:t.rows.map(e=>{let n={};for(let[r,o]of t.fields.entries())hy({item:n,field:o,value:e[r]});return n}),totalCount:t.totalCount,hasMore:t.hasMore}),gd=async({queries:t,query:e,assetValueReferences:n,runtimeAssets:r={}})=>{if(t===void 0)return;let o=t[await my(it.parse(e))];if(o===void 0)return;let s=yy(o),i={...s,items:s.items.map(a=>ht({value:a,references:n?.[a.id],runtimeAssets:r}))};return ri(i),i};var gy=({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=Xt({node:c,source:n(c)??await e(c,{signal:o})});return{data:pr(u.source,a),...a===void 0?{}:{contentLength:a.length}}}},by=({artifact:t,revision:e,catalog:n,documentGraph:r,inlineDocuments:o,readContent:s})=>{let i=new Map(t.documents.map(b=>[b._id,b])),a=b=>{if(b.indexRevision!==void 0&&b.indexRevision!==e)throw new sn},c=b=>async(A,D)=>{let E=t.contents?.[A];if(E===void 0){let G=b??s;if(G===void 0)throw new Error("Content is not embedded in this database");return await G(A,D)}let C=ot(E),P=D===void 0?C:C.slice(D.offset,D.offset+D.length);return{data:async function*(){yield P}(),contentLength:P.byteLength}},u=b=>{if(b.status==="rejected")throw b.reason;return b.value},d=async({requests:b,queryContentReader:A,runtimeAssets:D,documents:E=t.documents})=>await yd({queries:b.map(({query:C})=>C),catalog:n,documents:E,read:c(A),runtimeAssets:D,assetReferences:t.assetReferences,assetValueReferences:t.assetValueReferences}),l=async({request:b,...A})=>u((await d({...A,requests:[b]}))[0]),f=async({requests:b,queryContentReader:A,runtimeAssets:D})=>{let E=Array.from({length:b.length}),C=[];for(let[P,G]of b.entries()){try{a(G);let L=await gd({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=>b[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(b,A,D)=>u((await f({requests:[b],queryContentReader:A,runtimeAssets:D}))[0]),g=async(...b)=>await p(...b),m=b=>async(A,D)=>{let E=o?.get(A.id);return E!==void 0?{format:"json",revision:A.revision,source:JSON.stringify(E.properties)}:await b(A,D)},h=({graph:b,query:A,runtimeAssets:D})=>nd({graph:b,query:A}).filter(E=>{let C=i.get(E),P=C===void 0?void 0:ht({value:C,references:t.assetValueReferences?.[E],runtimeAssets:D??{}});return P===void 0?!1:zt(A.where,G=>{if(!td({graph:b,sourceId:E,field:G.field}))return ni(P,G,D?.[E])})!==!1}),y=({rootIds:b,roots:A})=>{let D=new Map(b.flatMap((E,C)=>{let P=lo(A[C]);return P===void 0?[]:[[E,P]]}));return t.documents.map(E=>{let C=D.get(E._id);return C===void 0?E:ls.parse({...E,properties:C})})},x=async({request:b,graph:A,resolutionSession:D,contentReader:E,runtimeAssets:C,onEvent:P})=>{a(b);let G=it.parse(b.query),L=h({graph:A,query:G,runtimeAssets:C});if(L.length===0)return await p(b,E,C);let bt=rd({graph:A,query:G,rootIds:L});ae(P,{type:"roots-selected",rootCount:L.length});let bo=await D.resolve({graph:bt,rootIds:L,onEvent:P,allowUnresolvedReferences:!0,transformDocument:({node:vd,document:Dd})=>qs({document:Dd,references:t.assetValueReferences?.[vd.id],runtimeAssets:C})}),wo=y({rootIds:L,roots:bo.roots});return await l({request:b,queryContentReader:E,runtimeAssets:C,documents:wo})},S=async({requests:b,load:A,resolutionSession:D,readContent:E,runtimeAssets:C,signal:P,onEvent:G})=>{if(r===void 0)return await f({requests:b,queryContentReader:E,runtimeAssets:C});let L=m(A),bt=D??Wf({load:L,concurrency:k.concurrentContentReads,signal:P}),bo=gy({graph:r,load:L,getCached:bt.getCached,readFallback:E??s,signal:P});return await Promise.allSettled(b.map(wo=>x({request:wo,graph:r,resolutionSession:bt,contentReader:bo,runtimeAssets:C,onEvent:G})))};return{query:g,queryManyWithDocumentGraph:S,queryWithDocumentGraph:async({request:b,...A})=>u((await S({...A,requests:[b]}))[0])}};var oi=({artifact:t,readContent:e})=>{let n=od({artifact:t});return by({artifact:t,revision:t.revision,documentGraph:n?.graph,inlineDocuments:n?.inlineDocuments,readContent:e})};var an=class extends Error{constructor(e,n){super(e,n),this.name="AssetQueryRequestError"}},Jn=class extends Error{},wy=async(t,e)=>{if(Number.isSafeInteger(e)===!1||e<0)throw new TypeError("Request byte limit must be a non-negative integer");let n=Number(t.headers.get("content-length"));if(Number.isFinite(n)&&n>e)throw new Jn("Request exceeds the byte limit");let r=t.body?.getReader(),o=[],s=0;if(r!==void 0)for(;;){let{done:c,value:u}=await r.read();if(c)break;if(s+=u.byteLength,s>e){try{await r.cancel()}catch{}throw new Jn("Request exceeds the byte limit")}o.push(u)}let i=new Uint8Array(s),a=0;for(let c of o)i.set(c,a),a+=c.byteLength;return i},bd=async t=>{let e;try{e=await wy(t,k.requestBytes)}catch(n){throw n instanceof Jn?new an("Asset query request exceeds the byte limit",{cause:n}):n}try{return Dl.parse(JSON.parse(le(e)))}catch(n){throw new an("Asset query request is invalid",{cause:n})}};var wd=t=>{if(!(t instanceof an))return;let e=t.message,n=new Set,r=t.cause;for(;r instanceof Error&&n.has(r)===!1;){if(r instanceof Ou)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}},_d=t=>{if(t instanceof sn)return{code:"STALE_INDEX",message:t.message,retryable:!1,status:409};if(t instanceof qn)return{code:t.code,message:t.message,retryable:!1,details:{matchedCount:t.matchedCount},status:409};if(t instanceof Ee){let r={...t.details,...t.issues===void 0?{}:{issues:t.issues.map(o=>({...o,path:[...o.path]}))}};return{code:t.code,message:t.message,retryable:!1,...Object.keys(r).length===0?{}:{details:r},status:400}}if(t instanceof X)return{code:t.code,message:t.message,retryable:!1,details:t.details,status:400};let e=new Set,n=t;for(;n!==void 0&&e.has(n)===!1;){if(n instanceof Dt){let r={};for(let[o,s]of Object.entries({assetId:n.documentId,documentCount:n.documentCount,documentLimit:n.documentLimit,contentByteLimit:n.contentByteLimit,totalBytes:n.totalBytes,totalByteLimit:n.totalByteLimit}))s!==void 0&&(r[o]=s);return{code:"CONTENT_LIMIT_EXCEEDED",message:n.message,retryable:!1,details:r,status:400}}if(n instanceof Vn)return{code:"CONTENT_LIMIT_EXCEEDED",message:n.message,retryable:!1,details:{assetId:n.documentId,contentByteLimit:n.contentByteLimit},status:400};e.add(n),n=n instanceof Error?n.cause:void 0}};var _y="/$resources/assets",Ey="WEBSTUDIO_AUTOMATION_TOKEN",go=t=>typeof t=="object"&&t!==null?t:void 0,xy=t=>{let e=go(t),n=go(e?.cloudflare),r=[e,go(e?.env),go(n?.env)];for(let o of r){let s=o?.[Ey];if(typeof s=="string"&&s.length>0)return s}},Ed=(t,e=200)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json; charset=utf-8"}}),cn=({code:t,message:e,status:n,retryable:r=!1,details:o})=>Ed(Il({code:t,message:e,retryable:r,details:o}),n),Sy=(t,e,n)=>typeof t=="string"||t instanceof URL?new Request(new URL(t,e),n):new Request(t,n),Ay=async({deploymentId:t,artifact:e,request:n})=>{let r=await n.clone().text(),o=n.headers.get("cache-control"),s=await as(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"})},RR=({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,automationToken:s,fetchDocument:i=globalThis.fetch,onDocumentGraphEvent:a})=>{Sd({artifact:e,runtimeAssets:n});let c=Ws();return Ad({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,automationToken:s,database:oi({artifact:e}),fetchDocument:i,documentCache:c,onDocumentGraphEvent:a})},xd=({assetId:t,baseUrl:e,runtimeAssets:n,automationToken:r,authorization:o})=>{let s=n[t];if(s===void 0)throw new Error(`Published document URL is unavailable for ${t}`);let i=new Request(new URL(s.url,e));return i.headers.delete("referer"),r!==void 0&&i.headers.set("x-webstudio-automation",r),o!==void 0&&/^Basic\s/i.test(o)&&new URL(i.url).origin===new URL(e).origin?(i.headers.set("authorization",o),new Request(i,{redirect:"manual"})):i},vy=({baseUrl:t,runtimeAssets:e,embeddedContents:n,automationToken:r,authorization:o,fetchDocument:s,cache:i,onEvent:a})=>{let c=Bf({fetch:s,getRequest:u=>xd({assetId:u.id,baseUrl:t,runtimeAssets:e,automationToken:r,authorization:o}),getMetadata:({node:u})=>({format:u.format,revision:u.revision}),onEvent:a});return qf({cache:i,onEvent:a,load:async(u,d)=>{let l=u.format,f=l===void 0?void 0:n?.[u.contentRef];return f!==void 0&&l!==void 0?{format:l,revision:u.revision,source:ot(f)}:await c(u,d)}})},Sd=({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}`)},Ad=({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,automationToken:s,authorization:i,database:a,fetchDocument:c,documentCache:u,onDocumentGraphEvent:d})=>{let l=new URL(o).origin,f=new Map(e.documents.map(g=>[g.contentRef,g])),p=vy({baseUrl:o,runtimeAssets:n,embeddedContents:e.contents,automationToken:s,authorization:i,fetchDocument:c,cache:u,onEvent:d});return async(g,m)=>{let h=Sy(g,o,m),y=new URL(h.url);if(y.origin!==l||y.pathname!==_y||h.method.toUpperCase()!=="POST")return;let x;try{x=await bd(h.clone())}catch(_){let b=wd(_);return cn(b!==void 0?b:{code:"INVALID_REQUEST",message:"Asset resource request is invalid",status:400})}let S=r===void 0||h.headers.has("cache-control")===!1?void 0:await Ay({deploymentId:t,artifact:e,request:h});if(S!==void 0&&r!==void 0){let _=await r.match(S).catch(()=>{});if(_!==void 0)return new Response(_.body,_)}try{if(h.signal.aborted)return cn({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let _=Ed(await a.queryWithDocumentGraph({request:x,load:p,readContent:async(b,A)=>{let D=f.get(b);if(D===void 0)throw new Error(`Published content reference is unavailable: ${b}`);let E=await c(xd({assetId:D._id,baseUrl:o,runtimeAssets:n,automationToken:s,authorization:i}),{signal:h.signal});if(!E.ok||E.body===null)throw new Error(`Document ${D._id} request returned status ${E.status} or no body`);return{data:pr(mr(E.body),A)}},runtimeAssets:n,signal:h.signal,onEvent:d}));return S!==void 0&&r!==void 0&&h.signal.aborted===!1&&(_.headers.set("cache-control",h.headers.get("cache-control")),await r.put(S,_.clone()).catch(()=>{})),_}catch(_){if(h.signal.aborted)return cn({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let b=_d(_);return cn(b!==void 0?b:{code:"INTERNAL_ERROR",message:"Published asset query failed",status:500,retryable:!0})}}},kR=({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)};Sd({artifact:e,runtimeAssets:n});let c=oi({artifact:e}),u=Ws();return async({request:d,context:l,fallback:f})=>{let p=new URL(d.url).origin,g=Ad({deploymentId:t,artifact:e,runtimeAssets:n,cache:a,baseUrl:p,automationToken:xy(l),authorization:d.headers.get("authorization")??void 0,database:c,fetchDocument:f,documentCache:u,onDocumentGraphEvent:r});return async(m,h)=>await g(m,h)??f(m,h)}};export{kR as createGeneratedAssetResourceRuntime,RR as createPublishedAssetResourceFetch};+`,n)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Zo(t),r=An(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=Zo(t),r=An(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,n){return this.type!=="comment"||this.indent<=n?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};function gy(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Wt||null,prettyErrors:t}}function qi(e,t={}){let{lineCounter:n,prettyErrors:r}=gy(t),o=new yr(n?.addNewLine),s=new hr(t),i=null;for(let a of s.compose(o.parse(e),!0,e.length))if(!i)i=a;else if(i.options.logLevel!=="silent"){i.errors.push(new Ge(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(i.errors.forEach(Di(e,n)),i.warnings.forEach(Di(e,n))),i}var We=class extends Error{code;constructor(t){super(`Structured data failed validation: ${t}`),this.name="StructuredDataError",this.code=t}},Bd=e=>Ye(JSON.stringify(e)),Md=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},qd=(e,t)=>{if(Md(e)===!1)throw new We("INVALID");let n=0,r=(s,i)=>{if(i>t.depth)throw new We("DEPTH_EXCEEDED");if(typeof s=="string"){if(Ye(s)>t.stringBytes)throw new We("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>t.fields)throw new We("FIELDS_EXCEEDED");return r(a,i+1)});if(Md(s)){let a=Object.create(null);for(let[c,u]of Object.entries(s)){if(n+=1,n>t.fields)throw new We("FIELDS_EXCEEDED");a[c]=r(u,i+1)}return a}throw new We("INVALID")},o=r(e,1);if(Bd(o)>t.serializedBytes)throw new We("SERIALIZED_BYTES_EXCEEDED");return o};var ae=class extends Error{code;line;column;constructor(t,n,r,o){super(n,{cause:o}),this.name="MarkdownMetadataError",this.code=t,this.line=r?.line,this.column=r?.column}};var kn=new Uint8Array([239,187,191]),Zd=kn.byteLength+10,wy=(e,t,n=0)=>e.byteLength-n<t.byteLength?!1:t.every((r,o)=>e[n+o]===r),br=(e,t)=>{let n=0;if(wy(e,kn))n=kn.byteLength;else if(e.byteLength<kn.byteLength&&kn.slice(0,e.byteLength).every((s,i)=>s===e[i]))return t?null:void 0;if(e.byteLength<n+4)return t?null:void 0;if(e[n]!==45||e[n+1]!==45||e[n+2]!==45)return null;let r=n+3;if(e[r]===10)r+=1;else if(e[r]===13){if(e.byteLength===r+1)return t?null:void 0;if(e[r+1]!==10)return null;r+=2}else return null;let o=r;for(let s=r;s<=e.byteLength;s+=1){let i=s===e.byteLength;if(i===!1&&e[s]!==10)continue;if(i&&t===!1)return;let a=s;if(a>o&&e[a-1]===13&&(a-=1),a-o===3&&(e[o]===45&&e[o+1]===45&&e[o+2]===45||e[o]===46&&e[o+1]===46&&e[o+2]===46))return{yamlStart:r,yamlEnd:o,blockEnd:i?s:s+1};o=s+1}};var xy={bytes:N.frontmatterBytes,depth:N.frontmatterDepth,fields:N.frontmatterFields,stringBytes:N.frontmatterStringBytes,serializedBytes:N.indexedPropertiesBytes},Ud=e=>{try{return ve(e)}catch{throw new ae("FRONTMATTER_DECODING_FAILED","Markdown frontmatter is not valid UTF-8")}},_y=e=>e.code==="DEPTH_EXCEEDED"?new ae("FRONTMATTER_DEPTH_EXCEEDED","Markdown frontmatter exceeds the nesting limit"):e.code==="FIELDS_EXCEEDED"?new ae("FRONTMATTER_FIELDS_EXCEEDED","Markdown frontmatter exceeds the field limit"):e.code==="STRING_BYTES_EXCEEDED"?new ae("FRONTMATTER_STRING_BYTES_EXCEEDED","Markdown frontmatter contains a string that exceeds the byte limit"):e.code==="SERIALIZED_BYTES_EXCEEDED"?new ae("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter properties exceed the indexed byte limit"):new ae("FRONTMATTER_INVALID","Markdown frontmatter must contain a JSON-compatible object"),jd=(e,t)=>{let n=new Wt,r=qi(e,{schema:"core",uniqueKeys:!0,lineCounter:n});if(r.errors.length>0){let s=r.errors[0],i=n.linePos(s.pos[0]);throw new ae("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 ae("FRONTMATTER_INVALID","Markdown frontmatter contains unsupported YAML aliases")}if(o===null)return{};try{return qd(o,t)}catch(s){throw s instanceof We?_y(s):s}};var Vd=async(e,t={})=>{let n={...xy,...t},r=n.bytes+Zd,o=new Uint8Array(r),s=0;for await(let c of Wn(e)){let u=0;for(;u<c.byteLength;){let f=r-s;if(f<=0)break;let l=Math.max(0,6-s),p=Math.min(c.byteLength-u,l);if(l===0){let h=c.subarray(u,Math.min(c.byteLength,u+f)),y=h.indexOf(10);p=y===-1?h.byteLength:y+1}o.set(c.subarray(u,u+p),s),s+=p,u+=p;let d=o.subarray(0,s),w=br(d,!1);if(w===null)return{properties:{},frontmatterBytes:0,consumedBytes:d.length};if(w!==void 0){let h=w.yamlEnd-w.yamlStart;if(h>n.bytes)throw new ae("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter exceeds the byte limit");let y=Ud(d.subarray(w.yamlStart,w.yamlEnd));return{properties:jd(y,n),frontmatterBytes:h,consumedBytes:w.blockEnd}}}if(s>=r)break}let i=o.subarray(0,s),a=br(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=Ud(i.subarray(a.yamlStart,a.yamlEnd));return{properties:jd(u,n),frontmatterBytes:c,consumedBytes:a.blockEnd}}}throw new ae("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter is not closed within the byte limit")};var jo=async(e,t=N.hydratedFileBytes)=>{if(Number.isInteger(t)===!1||t<=0||t>N.hydratedFileBytes)throw new ae("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown body byte limit is outside the supported range");let n;try{n=await Xe(e,t)}catch(a){throw a instanceof we?new ae("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown content exceeds the byte limit"):a}let r;try{r=ve(n)}catch{throw new ae("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}let s=br(n,!0)?.blockEnd??0,i;try{i=s===0?ln(r):ve(n.subarray(s))}catch{throw new ae("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}return{body:i,bodyBytes:Ye(i),sourceBytes:n.byteLength}};var $t=class extends Error{code;referenceId;constructor({code:t,message:n,referenceId:r,cause:o}){super(n,{cause:o}),this.name="MarkdownDocumentError",this.code=t,this.referenceId=r}},Sy=L({source:D(),body:D(),frontmatter:Ne(D(),At())}),Qo=e=>{let t;try{t=Sy.parse(e)}catch(n){throw new $t({code:"INVALID_DOCUMENT",message:"Markdown document is invalid",cause:n})}return Object.freeze({source:t.source,body:t.body,frontmatter:vt(t.frontmatter)})},Vo="#frontmatter",Ey=e=>`${Vo}${e.slice(1)}`,Ay=e=>{if(e!==Vo&&e.startsWith(`${Vo}/`)===!1)throw new $t({code:"UNUSED_REFERENCE",message:`Resolved Markdown reference ${e} is outside frontmatter`,referenceId:e});return`#${e.slice(Vo.length)}`},ky=e=>{let t=e.referenceId===void 0?void 0:Ey(e.referenceId),n="INVALID_DOCUMENT";throw(e.code==="INVALID_REFERENCE_MARKER"||e.code==="INVALID_REFERENCE"||e.code==="REFERENCE_NOT_FOUND"||e.code==="INVALID_RESOLVED_VALUE"||e.code==="UNUSED_REFERENCE")&&(n=e.code),new $t({code:n,message:e.message,referenceId:t,cause:e})},Qd=async({source:e,maximumBytes:t=N.hydratedFileBytes})=>{let n;try{n=await Xe(e,t)}catch(i){throw i instanceof we?new $t({code:"CONTENT_LIMIT_EXCEEDED",message:"Markdown document exceeds the byte limit",cause:i}):i}let r;try{r=ln(ve(n))}catch(i){throw new $t({code:"CONTENT_DECODING_FAILED",message:"Markdown document is not valid UTF-8",cause:i})}let[o,s]=await Promise.all([jo(n,t),Vd(n).catch(i=>{if(i instanceof ae)return{properties:{},frontmatterBytes:0,consumedBytes:0};throw i})]);return Qo({source:r,body:o.body,frontmatter:s.properties})};var Gd=({document:e,references:t,allowUnresolvedReferences:n=!1})=>{let r=Qo(e),o=new Map;for(let[i,a]of t)o.set(Ay(i),a);let s;try{s=ao({document:r.frontmatter,references:o,allowUnresolvedReferences:n})}catch(i){throw i instanceof De&&ky(i),i}return Qo({...r,frontmatter:s})},Jd=({document:e,representation:t})=>{let n=Qo(e);if(t.type==="document")return n.source;if(t.type==="markdown-body")return n.body;if(t.type==="markdown-frontmatter")return n.frontmatter;throw new $t({code:"UNSUPPORTED_REPRESENTATION",message:`Markdown documents do not support ${t.type}`})};var Go=e=>{let t=encodeURIComponent(e);return t==="."?"%2E":t===".."?"%2E%2E":t};var Wd=e=>e.split("/").map(t=>{try{return Go(decodeURIComponent(t))}catch{return Go(t)}}).join("/");var Jo=e=>{let t=new Set,n=new Map;for(let{id:r,path:o}of e){if(n.has(o)){t.add(o),n.delete(o);continue}t.has(o)===!1&&n.set(o,r)}return n},Kd=({sourcePath:e,url:t,allowRootRelative:n=!1})=>{if(t.length===0||t.startsWith("#")||t.startsWith("?")||n===!1&&t.startsWith("/"))return;let r="https://content.webstudio.invalid",o="__webstudio_asset_source_";for(;e.includes(o)||t.includes(o);)o=`_${o}`;let s=e.split("/"),i=new Map(s.map((f,l)=>[`${o}${l}__`,f])),a=Array.from(i.keys()).join("/"),c;try{c=new URL(t,new URL(a,`${r}/`))}catch{return}if(c.origin!==r)return;let u=[];for(let f of c.pathname.slice(1).split("/")){let l;try{l=decodeURIComponent(f)}catch{return}if(l==="")continue;let p=i.get(l);if(p!==void 0){u.push(p);continue}if(l.includes("/"))return;u.push(Go(l))}return u.join("/")},vy=e=>{let n=Kd({sourcePath:"document",url:e,allowRootRelative:!0})?.split("/");if(!(n?.length!==2||n[0]!=="assets"))return n[1]},Hd=(e,t)=>{let n=new Set(e.values()),r=Jo(Array.from(e,([o,s])=>({id:s,path:o.slice(o.lastIndexOf("/")+1)})));return o=>{let s=Kd({sourcePath:t,url:o});return(s===void 0?void 0:e.get(s))??r.get(vy(o)??"")??(n.has(o)?o:void 0)}};var Ry=e=>{let t;try{t=new URL(e,"https://content.webstudio.invalid/")}catch{return}let n=`${t.search}${t.hash}`;return n===""?void 0:n},Yd=({sourcePath:e,assetIdsByPath:t})=>{let n=Hd(t,e);return r=>{let o=n(r);if(o===void 0)return;let s=Ry(r);return{assetId:o,...s===void 0?{}:{suffix:s}}}};var Xd=e=>Object.fromEntries(Object.entries(e??{}).map(([t,n])=>[t,n.url]));var Wo=(e,t)=>{if(t===void 0||t.length===0)return e;let n=new URL("https://content.webstudio.invalid/__assets__/"),r=new URL(e,n),o=new URL(t,n);for(let[a,c]of o.searchParams)r.searchParams.append(a,c);if(o.hash!==""&&(r.hash=o.hash),e.startsWith("//"))return`//${r.host}${r.pathname}${r.search}${r.hash}`;if(e.startsWith("/"))return`${r.pathname}${r.search}${r.hash}`;let s=!1;try{new URL(e),s=!0}catch{}return s?r.href:`${r.pathname.startsWith(n.pathname)?r.pathname.slice(n.pathname.length):r.pathname}${r.search}${r.hash}`},Zi=({value:e,path:t,replacement:n})=>{let[r,...o]=t;if(r===void 0)return n;if(typeof e!="object"||e===null||Object.hasOwn(e,r)===!1)return e;if(Array.isArray(e)){if(typeof r!="number")return e;let s=[...e];return s[r]=Zi({value:e[r],path:o,replacement:n}),s}return typeof r!="string"?e:{...e,[r]:Zi({value:e[r],path:o,replacement:n})}},Dy=({reference:e,runtimeAsset:t})=>{let{url:n,contentRef:r,...o}=t;return{...o,id:e.assetId,src:Wo(n,e.suffix)}},Lt=({value:e,references:t,runtimeAssets:n={},assetUrls:r})=>{let o=e;for(let s of t??[]){let i=r?.[s.assetId],a=n[s.assetId]??(i===void 0?void 0:{url:i});a!==void 0&&(o=Zi({value:o,path:s.path,replacement:s.structured===!0?Dy({reference:s,runtimeAsset:a}):Wo(a.url,s.suffix)}))}return o};var Ho=e=>{let t=e.format==="json"?e.value:e.value.frontmatter;return pn(t)?t:void 0},Ui=({document:e,references:t,runtimeAssets:n})=>{let r=Ho(e);if(r===void 0||t===void 0)return e;let o=Lt({value:{properties:r},references:t,runtimeAssets:n}).properties;return e.format==="json"?Object.freeze({...e,value:o}):Object.freeze({...e,value:Object.freeze({...e.value,frontmatter:o})})},Ko=e=>Object.freeze(e),ep=async({format:e,source:t,maximumBytes:n=N.hydratedFileBytes})=>Ko(e==="json"?{format:e,value:await Jf({source:t,maximumBytes:n})}:{format:e,value:await Qd({source:t,maximumBytes:n})});var tp=({document:e,references:t,allowUnresolvedReferences:n})=>e.format==="json"?Ko({format:e.format,value:ao({document:e.value,references:t,allowUnresolvedReferences:n})}):Ko({format:e.format,value:Gd({document:e.value,references:t,allowUnresolvedReferences:n})}),np=({document:e,representation:t})=>e.format==="json"?Wf({document:e.value,representation:t}):Jd({document:e.value,representation:t});var Yo=class extends Error{code;documentId;expectedRevision;actualRevision;expectedFormat;actualFormat;constructor({code:t,documentId:n,expectedRevision:r,actualRevision:o,expectedFormat:s,actualFormat:i}){super(`Document ${n} source ${t==="REVISION_MISMATCH"?"revision":"format"} does not match its graph`),this.name="DocumentSourceError",this.code=t,this.documentId=n,this.expectedRevision=r,this.actualRevision=o,this.expectedFormat=s,this.actualFormat=i}},vn=({node:e,source:t})=>{if(t.revision!==e.revision)throw new Yo({code:"REVISION_MISMATCH",documentId:e.id,expectedRevision:e.revision,actualRevision:t.revision});if(e.format!==void 0&&t.format!==e.format)throw new Yo({code:"FORMAT_MISMATCH",documentId:e.id,expectedFormat:e.format,actualFormat:t.format});return t};var Rn=e=>{if(typeof e=="object"&&e!==null){let t=Reflect.get(e,"code");if(typeof t=="string"&&t.length>0)return t;let n=Reflect.get(e,"name");if(typeof n=="string"&&n.length>0)return n}return"UNKNOWN"},_e=(e,t)=>{try{e?.(t)}catch{}},rp=({load:e,onEvent:t})=>async(n,r)=>{let o={documentId:n.id,revision:n.revision};_e(t,{type:"document-fetch-started",...o});try{let s=await e(n,r);return _e(t,{type:"document-fetch-completed",...o}),s}catch(s){throw _e(t,{type:"document-fetch-failed",...o,errorCode:Rn(s)}),s}};var Iy=L({format:fe(Hn),revision:D().min(1)}),Dn=class extends Error{code;documentId;status;constructor({code:t,message:n,documentId:r,status:o,cause:s}){super(n,{cause:s}),this.name="HttpDocumentLoaderError",this.code=t,this.documentId=r,this.status=o}},op=({fetch:e,getRequest:t,getMetadata:n,onEvent:r})=>rp({load:async(s,{signal:i})=>{let a;try{a=await e(t(s),{signal:i})}catch(f){throw new Dn({code:"REQUEST_FAILED",message:`Document ${s.id} request failed`,documentId:s.id,cause:f})}if(a.ok===!1)throw new Dn({code:"HTTP_STATUS",message:`Document ${s.id} request returned status ${a.status}`,documentId:s.id,status:a.status});let c;try{c=Iy.parse(n({node:s,response:a}))}catch(f){throw new Dn({code:"INVALID_METADATA",message:`Document ${s.id} response metadata is invalid`,documentId:s.id,cause:f})}let u=a.body;if(u===null)throw new Dn({code:"BODY_MISSING",message:`Document ${s.id} response body is unavailable`,documentId:s.id});return Object.freeze({...c,source:Yr(u)})},onEvent:r});var In=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,ip=new Set,ji=typeof process=="object"&&process?process:{},ap=(e,t,n,r)=>{typeof ji.emitWarning=="function"?ji.emitWarning(e,t,n,r):console.error(`[${n}] ${t}: ${e}`)},Xo=globalThis.AbortController,sp=globalThis.AbortSignal;if(typeof Xo>"u"){sp=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},Xo=class{constructor(){t()}signal=new sp;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 e=ji.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{e&&(e=!1,ap("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",t))}}var Cy=e=>!ip.has(e),rI=Symbol("type"),Pt=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),cp=e=>Pt(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?Cn:null:null,Cn=class extends Array{constructor(t){super(t),this.fill(0)}},Vi=class e{heap;length;static#c=!1;static create(t){let n=cp(t);if(!n)return[];e.#c=!0;let r=new e(t,n);return e.#c=!1,r}constructor(t,n){if(!e.#c)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new n(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},Tn=class e{#c;#f;#h;#g;#C;#T;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#y;#r;#n;#e;#u;#d;#a;#s;#b;#i;#w;#x;#p;#_;#v;#l;static unsafeExposeInternals(t){return{starts:t.#x,ttls:t.#p,sizes:t.#w,keyMap:t.#r,keyList:t.#n,valList:t.#e,next:t.#u,prev:t.#d,get head(){return t.#a},get tail(){return t.#s},free:t.#b,isBackgroundFetch:n=>t.#t(n),backgroundFetch:(n,r,o,s)=>t.#z(n,r,o,s),moveToTail:n=>t.#I(n),indexes:n=>t.#S(n),rindexes:n=>t.#E(n),isStale:n=>t.#m(n)}}get max(){return this.#c}get maxSize(){return this.#f}get calculatedSize(){return this.#y}get size(){return this.#o}get fetchMethod(){return this.#C}get memoMethod(){return this.#T}get dispose(){return this.#h}get disposeAfter(){return this.#g}constructor(t){let{max:n=0,ttl:r,ttlResolution:o=1,ttlAutopurge:s,updateAgeOnGet:i,updateAgeOnHas:a,allowStale:c,dispose:u,disposeAfter:f,noDisposeOnSet:l,noUpdateTTL:p,maxSize:d=0,maxEntrySize:w=0,sizeCalculation:h,fetchMethod:y,memoMethod:m,noDeleteOnFetchRejection:A,noDeleteOnStaleGet:S,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:_,ignoreFetchAbort:x}=t;if(n!==0&&!Pt(n))throw new TypeError("max option must be a nonnegative integer");let R=n?cp(n):Array;if(!R)throw new Error("invalid max value: "+n);if(this.#c=n,this.#f=d,this.maxEntrySize=w||this.#f,this.sizeCalculation=h,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(m!==void 0&&typeof m!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#T=m,y!==void 0&&typeof y!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#C=y,this.#v=!!y,this.#r=new Map,this.#n=new Array(n).fill(void 0),this.#e=new Array(n).fill(void 0),this.#u=new R(n),this.#d=new R(n),this.#a=0,this.#s=0,this.#b=Vi.create(n),this.#o=0,this.#y=0,typeof u=="function"&&(this.#h=u),typeof f=="function"?(this.#g=f,this.#i=[]):(this.#g=void 0,this.#i=void 0),this.#_=!!this.#h,this.#l=!!this.#g,this.noDisposeOnSet=!!l,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!A,this.allowStaleOnFetchRejection=!!E,this.allowStaleOnFetchAbort=!!_,this.ignoreFetchAbort=!!x,this.maxEntrySize!==0){if(this.#f!==0&&!Pt(this.#f))throw new TypeError("maxSize must be a positive integer if specified");if(!Pt(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#q()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!S,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!a,this.ttlResolution=Pt(o)||o===0?o:1,this.ttlAutopurge=!!s,this.ttl=r||0,this.ttl){if(!Pt(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#$()}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 v="LRU_CACHE_UNBOUNDED";Cy(v)&&(ip.add(v),ap("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",v,e))}}getRemainingTTL(t){return this.#r.has(t)?1/0:0}#$(){let t=new Cn(this.#c),n=new Cn(this.#c);this.#p=t,this.#x=n,this.#L=(s,i,a=In.now())=>{if(n[s]=i!==0?a:0,t[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]=t[s]!==0?In.now():0},this.#k=(s,i)=>{if(t[i]){let a=t[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=In.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=t[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=t[s];return!!a&&!!i&&(r||o())-i>a}}#R=()=>{};#k=()=>{};#L=()=>{};#m=()=>!1;#q(){let t=new Cn(this.#c);this.#y=0,this.#w=t,this.#D=n=>{this.#y-=t[n],t[n]=0},this.#P=(n,r,o,s)=>{if(this.#t(r))return 0;if(!Pt(o))if(s){if(typeof s!="function")throw new TypeError("sizeCalculation must be a function");if(o=s(r,n),!Pt(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#O=(n,r,o)=>{if(t[n]=r,this.#f){let s=this.#f-t[n];for(;this.#y>s;)this.#N(!0)}this.#y+=t[n],o&&(o.entrySize=r,o.totalCalculatedSize=this.#y)}}#D=t=>{};#O=(t,n,r)=>{};#P=(t,n,r,o)=>{if(r||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#S({allowStale:t=this.allowStale}={}){if(this.#o)for(let n=this.#s;!(!this.#F(n)||((t||!this.#m(n))&&(yield n),n===this.#a));)n=this.#d[n]}*#E({allowStale:t=this.allowStale}={}){if(this.#o)for(let n=this.#a;!(!this.#F(n)||((t||!this.#m(n))&&(yield n),n===this.#s));)n=this.#u[n]}#F(t){return t!==void 0&&this.#r.get(this.#n[t])===t}*entries(){for(let t of this.#S())this.#e[t]!==void 0&&this.#n[t]!==void 0&&!this.#t(this.#e[t])&&(yield[this.#n[t],this.#e[t]])}*rentries(){for(let t of this.#E())this.#e[t]!==void 0&&this.#n[t]!==void 0&&!this.#t(this.#e[t])&&(yield[this.#n[t],this.#e[t]])}*keys(){for(let t of this.#S()){let n=this.#n[t];n!==void 0&&!this.#t(this.#e[t])&&(yield n)}}*rkeys(){for(let t of this.#E()){let n=this.#n[t];n!==void 0&&!this.#t(this.#e[t])&&(yield n)}}*values(){for(let t of this.#S())this.#e[t]!==void 0&&!this.#t(this.#e[t])&&(yield this.#e[t])}*rvalues(){for(let t of this.#E())this.#e[t]!==void 0&&!this.#t(this.#e[t])&&(yield this.#e[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,n={}){for(let r of this.#S()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;if(s!==void 0&&t(s,this.#n[r],this))return this.get(this.#n[r],n)}}forEach(t,n=this){for(let r of this.#S()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;s!==void 0&&t.call(n,s,this.#n[r],this)}}rforEach(t,n=this){for(let r of this.#E()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;s!==void 0&&t.call(n,s,this.#n[r],this)}}purgeStale(){let t=!1;for(let n of this.#E({allowStale:!0}))this.#m(n)&&(this.#A(this.#n[n],"expire"),t=!0);return t}info(t){let n=this.#r.get(t);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.#x){let i=this.#p[n],a=this.#x[n];if(i&&a){let c=i-(In.now()-a);s.ttl=c,s.start=Date.now()}}return this.#w&&(s.size=this.#w[n]),s}dump(){let t=[];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.#x){i.ttl=this.#p[n];let a=In.now()-this.#x[n];i.start=Math.floor(Date.now()-a)}this.#w&&(i.size=this.#w[n]),t.unshift([r,i])}return t}load(t){this.clear();for(let[n,r]of t){if(r.start){let o=Date.now()-r.start;r.start=In.now()-o}this.set(n,r.value,r)}}set(t,n,r={}){if(n===void 0)return this.delete(t),this;let{ttl:o=this.ttl,start:s,noDisposeOnSet:i=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=r,{noUpdateTTL:u=this.noUpdateTTL}=r,f=this.#P(t,n,r.size||0,a);if(this.maxEntrySize&&f>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#A(t,"set"),this;let l=this.#o===0?void 0:this.#r.get(t);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]=t,this.#e[l]=n,this.#r.set(t,l),this.#u[this.#s]=l,this.#d[l]=this.#s,this.#s=l,this.#o++,this.#O(l,f,c),c&&(c.set="add"),u=!1;else{this.#I(l);let p=this.#e[l];if(n!==p){if(this.#v&&this.#t(p)){p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:d}=p;d!==void 0&&!i&&(this.#_&&this.#h?.(d,t,"set"),this.#l&&this.#i?.push([d,t,"set"]))}else i||(this.#_&&this.#h?.(p,t,"set"),this.#l&&this.#i?.push([p,t,"set"]));if(this.#D(l),this.#O(l,f,c),this.#e[l]=n,c){c.set="replace";let d=p&&this.#t(p)?p.__staleWhileFetching:p;d!==void 0&&(c.oldValue=d)}}else c&&(c.set="update")}if(o!==0&&!this.#p&&this.#$(),this.#p&&(u||this.#L(l,o,s),c&&this.#k(c,l)),!i&&this.#l&&this.#i){let p=this.#i,d;for(;d=p?.shift();)this.#g?.(...d)}return this}pop(){try{for(;this.#o;){let t=this.#e[this.#a];if(this.#N(!0),this.#t(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#l&&this.#i){let t=this.#i,n;for(;n=t?.shift();)this.#g?.(...n)}}}#N(t){let n=this.#a,r=this.#n[n],o=this.#e[n];return this.#v&&this.#t(o)?o.__abortController.abort(new Error("evicted")):(this.#_||this.#l)&&(this.#_&&this.#h?.(o,r,"evict"),this.#l&&this.#i?.push([o,r,"evict"])),this.#D(n),t&&(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(t,n={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:o}=n,s=this.#r.get(t);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.#k(o,s));else return r&&this.#R(s),o&&(o.has="hit",this.#k(o,s)),!0}else o&&(o.has="miss");return!1}peek(t,n={}){let{allowStale:r=this.allowStale}=n,o=this.#r.get(t);if(o===void 0||!r&&this.#m(o))return;let s=this.#e[o];return this.#t(s)?s.__staleWhileFetching:s}#z(t,n,r,o){let s=n===void 0?void 0:this.#e[n];if(this.#t(s))return s;let i=new Xo,{signal:a}=r;a?.addEventListener("abort",()=>i.abort(a.reason),{signal:i.signal});let c={signal:i.signal,options:r,context:o},u=(h,y=!1)=>{let{aborted:m}=i.signal,A=r.ignoreFetchAbort&&h!==void 0;if(r.status&&(m&&!y?(r.status.fetchAborted=!0,r.status.fetchError=i.signal.reason,A&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),m&&!A&&!y)return l(i.signal.reason);let S=d;return this.#e[n]===d&&(h===void 0?S.__staleWhileFetching?this.#e[n]=S.__staleWhileFetching:this.#A(t,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(t,h,c.options))),h},f=h=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=h),l(h)),l=h=>{let{aborted:y}=i.signal,m=y&&r.allowStaleOnFetchAbort,A=m||r.allowStaleOnFetchRejection,S=A||r.noDeleteOnFetchRejection,E=d;if(this.#e[n]===d&&(!S||E.__staleWhileFetching===void 0?this.#A(t,"fetch"):m||(this.#e[n]=E.__staleWhileFetching)),A)return r.status&&E.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),E.__staleWhileFetching;if(E.__returned===E)throw h},p=(h,y)=>{let m=this.#C?.(t,s,c);m&&m instanceof Promise&&m.then(A=>h(A===void 0?void 0:A),y),i.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(h(void 0),r.allowStaleOnFetchAbort&&(h=A=>u(A,!0)))})};r.status&&(r.status.fetchDispatched=!0);let d=new Promise(p).then(u,f),w=Object.assign(d,{__abortController:i,__staleWhileFetching:s,__returned:void 0});return n===void 0?(this.set(t,w,{...c.options,status:void 0}),n=this.#r.get(t)):this.#e[n]=w,w}#t(t){if(!this.#v)return!1;let n=t;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof Xo}async fetch(t,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:f=this.noUpdateTTL,noDeleteOnFetchRejection:l=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:d=this.ignoreFetchAbort,allowStaleOnFetchAbort:w=this.allowStaleOnFetchAbort,context:h,forceRefresh:y=!1,status:m,signal:A}=n;if(!this.#v)return m&&(m.fetch="get"),this.get(t,{allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,status:m});let S={allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,ttl:i,noDisposeOnSet:a,size:c,sizeCalculation:u,noUpdateTTL:f,noDeleteOnFetchRejection:l,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:w,ignoreFetchAbort:d,status:m,signal:A},E=this.#r.get(t);if(E===void 0){m&&(m.fetch="miss");let _=this.#z(t,E,S,h);return _.__returned=_}else{let _=this.#e[E];if(this.#t(_)){let P=r&&_.__staleWhileFetching!==void 0;return m&&(m.fetch="inflight",P&&(m.returnedStale=!0)),P?_.__staleWhileFetching:_.__returned=_}let x=this.#m(E);if(!y&&!x)return m&&(m.fetch="hit"),this.#I(E),o&&this.#R(E),m&&this.#k(m,E),_;let R=this.#z(t,E,S,h),I=R.__staleWhileFetching!==void 0&&r;return m&&(m.fetch=x?"stale":"refresh",I&&x&&(m.returnedStale=!0)),I?R.__staleWhileFetching:R.__returned=R}}async forceFetch(t,n={}){let r=await this.fetch(t,n);if(r===void 0)throw new Error("fetch() returned undefined");return r}memo(t,n={}){let r=this.#T;if(!r)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:s,...i}=n,a=this.get(t,i);if(!s&&a!==void 0)return a;let c=r(t,a,{options:i,context:o});return this.set(t,c,i),c}get(t,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,status:i}=n,a=this.#r.get(t);if(a!==void 0){let c=this.#e[a],u=this.#t(c);return i&&this.#k(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(t,"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")}#M(t,n){this.#d[n]=t,this.#u[t]=n}#I(t){t!==this.#s&&(t===this.#a?this.#a=this.#u[t]:this.#M(this.#d[t],this.#u[t]),this.#M(this.#s,t),this.#s=t)}delete(t){return this.#A(t,"delete")}#A(t,n){let r=!1;if(this.#o!==0){let o=this.#r.get(t);if(o!==void 0)if(r=!0,this.#o===1)this.#B(n);else{this.#D(o);let s=this.#e[o];if(this.#t(s)?s.__abortController.abort(new Error("deleted")):(this.#_||this.#l)&&(this.#_&&this.#h?.(s,t,n),this.#l&&this.#i?.push([s,t,n])),this.#r.delete(t),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.#g?.(...s)}return r}clear(){return this.#B("delete")}#B(t){for(let n of this.#E({allowStale:!0})){let r=this.#e[n];if(this.#t(r))r.__abortController.abort(new Error("deleted"));else{let o=this.#n[n];this.#_&&this.#h?.(r,o,t),this.#l&&this.#i?.push([r,o,t])}}if(this.#r.clear(),this.#e.fill(void 0),this.#n.fill(void 0),this.#p&&this.#x&&(this.#p.fill(0),this.#x.fill(0)),this.#w&&this.#w.fill(0),this.#a=0,this.#s=0,this.#b.length=0,this.#y=0,this.#o=0,this.#l&&this.#i){let n=this.#i,r;for(;r=n?.shift();)this.#g?.(...r)}}};var Qi=({maximumBytes:e=N.hydratedTotalBytes*4}={})=>{if(Number.isSafeInteger(e)===!1||e<=0)throw new TypeError("Document source cache byte limit must be positive");return new Tn({maxSize:e,sizeCalculation:t=>Math.max(1,t.bytes.byteLength)})},wr=class extends Error{code="CONTENT_LIMIT_EXCEEDED";documentId;contentByteLimit;constructor({message:t,documentId:n,contentByteLimit:r,cause:o}){super(t,{cause:o}),this.name="CachedDocumentLoaderError",this.documentId=n,this.contentByteLimit=r}},es=({contentRef:e,revision:t,format:n})=>Re([e,t,n??null]),Ty=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return Rf(t.format)&&typeof t.revision=="string"&&t.revision.length>0&&t.bytes instanceof Uint8Array},up=e=>Object.freeze({format:e.format,revision:e.revision,source:e.bytes}),lp=({load:e,cache:t,maximumBytes:n=N.hydratedFileBytes,onEvent:r})=>{let o=new Map;return async(s,i)=>{let a=es(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 f=(async()=>{let l;try{l=await t.get(a)}catch(h){_e(r,{type:"document-cache-read-failed",documentId:s.id,revision:s.revision,errorCode:Rn(h)})}if(Ty(l)&&l.revision===s.revision&&l.bytes.byteLength<=n&&(s.format===void 0||l.format===s.format))return _e(r,{type:"document-cache-hit",documentId:s.id,revision:s.revision}),up(l);_e(r,{type:"document-cache-miss",documentId:s.id,revision:s.revision});let p=vn({node:s,source:await e(s,i)}),d;try{d=await Xe(p.source,n)}catch(h){throw h instanceof we?new wr({message:`Document ${s.id} exceeds the cache byte limit`,documentId:s.id,contentByteLimit:n,cause:h}):h}let w=Object.freeze({format:p.format,revision:p.revision,bytes:d});try{await t.set(a,w),_e(r,{type:"document-cache-stored",documentId:s.id,revision:s.revision})}catch(h){_e(r,{type:"document-cache-write-failed",documentId:s.id,revision:s.revision,errorCode:Rn(h)})}return up(w)})();c.set(i.signal,f);try{return await f}finally{c.delete(i.signal),c.size===0&&o.delete(a)}}};var Ce=class extends Error{code;resourceIds;constructor({code:t,message:n,resourceIds:r=[],cause:o}){super(n,{cause:o}),this.name="ResourceResolutionError",this.code=t,this.resourceIds=Object.freeze([...r])}},xr=e=>{if(e?.aborted)throw new Ce({code:"REQUEST_CANCELLED",message:"Resource resolution was cancelled",cause:e.reason})},Oy=({resourcesById:e,rootIds:t})=>{let n=new Map,r=[],o=[],s=(i,a)=>{let c=e.get(i);if(c===void 0)throw new Ce({code:a===void 0?"ROOT_NOT_FOUND":"DEPENDENCY_NOT_FOUND",message:a===void 0?`Resource graph root ${i} does not exist`:`Resource ${a} dependency ${i} does not exist`,resourceIds:a===void 0?[i]:[a,i]});let u=n.get(i);if(u!=="visited"){if(u==="visiting"){let f=r.indexOf(i),l=[...r.slice(f),i];throw new Ce({code:"CYCLE",message:`Resource graph contains a cycle: ${l.join(" -> ")}`,resourceIds:l})}n.set(i,"visiting"),r.push(i);for(let f of c.dependencies)s(f,c.id);r.pop(),n.set(i,"visited"),o.push(c)}};for(let i of new Set(t))s(i);return o},fp=async({resources:e,rootIds:t,concurrency:n,signal:r})=>{if(Number.isSafeInteger(n)===!1||n<=0)throw new TypeError("Resource resolution concurrency must be positive");xr(r);let o=new Map;for(let l of e){if(o.has(l.id))throw new Ce({code:"DUPLICATE_RESOURCE",message:`Resource graph contains duplicate resource ${l.id}`,resourceIds:[l.id]});o.set(l.id,l)}let s=Oy({resourcesById:o,rootIds:t}),i=so({concurrency:n,signal:r}),a=new Map,c=new Map,u=l=>{let p=c.get(l);if(p!==void 0)return p;let d=o.get(l),w=(async()=>{let h=new Map,y;try{y=await Promise.all(d.dependencies.map(u))}catch(m){throw m instanceof Ce&&m.code==="RESOLUTION_FAILED"?new Ce({code:m.code,message:`Resource dependency path ${[d.id,...m.resourceIds].join(" -> ")} could not be resolved`,resourceIds:[d.id,...m.resourceIds],cause:m.cause}):m}for(let[m,A]of d.dependencies.entries())h.set(A,y[m]);xr(r);try{return await i(async()=>{xr(r);let m=await dn(d.resolve({documents:h,signal:r}),r);return xr(r),m})}catch(m){throw r?.aborted&&xr(r),m instanceof Ce?m:new Ce({code:"RESOLUTION_FAILED",message:`Resource ${d.id} could not be resolved`,resourceIds:[d.id],cause:m})}})();return c.set(l,w),w},f=await Promise.all(t.map(u));for(let l of s){let p=await c.get(l.id);a.set(l.id,p)}return Object.freeze({roots:Object.freeze(f),documents:a})};var Fe=class extends Error{code;documentId;referenceId;constructor({code:t,message:n,documentId:r,referenceId:o,cause:s}){super(n,{cause:s}),this.name="DocumentGraphResolutionError",this.code=t,this.documentId=r,this.referenceId=o}},ts=e=>{if(e?.aborted)throw new Fe({code:"REQUEST_CANCELLED",message:"Document graph resolution was cancelled",cause:e.reason})},dp=async({graph:e,rootIds:t,concurrency:n,signal:r,load:o,select:s,assemble:i})=>{ts(r);let a=to({graph:e,rootIds:t}),c=new Map(a.map(d=>[d.id,d])),u=new Map,f=new Map;for(let d of a){let w=f.get(d.contentRef);w===void 0?f.set(d.contentRef,{representative:d,nodes:[d]}):w.nodes.push(d)}await oo([...f.values()],n,async d=>{ts(r);let w=d.representative;try{let h=await dn(o(w,{signal:r}),r);for(let y of d.nodes)u.set(y.id,h)}catch(h){throw r?.aborted&&ts(r),new Fe({code:"DOCUMENT_LOAD_FAILED",message:`Document ${w.id} could not be loaded`,documentId:w.id,cause:h})}});let l=fn(e.edges),p=a.map(d=>({id:d.id,dependencies:(l.get(d.id)??[]).map(w=>w.reference.documentId),resolve:async({documents:w})=>{ts(r);let h=new Map;for(let m of l.get(d.id)??[]){let A=c.get(m.reference.documentId);if(A===void 0||w.has(m.reference.documentId)===!1)throw new Fe({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${d.id} dependency ${m.reference.documentId} is unavailable`,documentId:d.id,referenceId:m.referenceId});let S=w.get(m.reference.documentId),E;if(s===void 0){if(m.reference.representation.type!=="document")throw new Fe({code:"REPRESENTATION_SELECTOR_REQUIRED",message:`Document ${d.id} reference ${m.referenceId} requires a representation selector`,documentId:d.id,referenceId:m.referenceId});E=S}else try{E=await s({reference:m.reference,value:S,sourceNode:d,targetNode:A})}catch(_){throw new Fe({code:"DOCUMENT_SELECTION_FAILED",message:`Document ${d.id} reference ${m.referenceId} could not be selected`,documentId:d.id,referenceId:m.referenceId,cause:_})}h.set(m.referenceId,E)}if(u.has(d.id)===!1)throw new Fe({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${d.id} source is unavailable`,documentId:d.id});let y=u.get(d.id);try{return await i({node:d,source:y,references:h})}catch(m){throw m instanceof Fe?m:new Fe({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${d.id} could not be assembled`,documentId:d.id,cause:m})}}}));try{let d=await fp({resources:p,rootIds:t,concurrency:1,signal:r});return Object.freeze({roots:d.roots,values:d.documents})}catch(d){throw d instanceof Ce&&d.cause instanceof Fe?d.cause:d instanceof Ce&&d.code==="REQUEST_CANCELLED"?new Fe({code:"REQUEST_CANCELLED",message:"Document graph resolution was cancelled",cause:d.cause}):d}};var Kt=class extends Error{code;documentId;documentCount;documentLimit;contentByteLimit;totalBytes;totalByteLimit;constructor({code:t,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=t,this.documentId=r,this.documentCount=o,this.documentLimit=s,this.contentByteLimit=i,this.totalBytes=a,this.totalByteLimit=c}},Ny=async({graph:e,rootIds:t,concurrency:n,maximumBytes:r,maximumTotalBytes:o=N.hydratedTotalBytes,maximumDocuments:s=N.hydratedFileCount,signal:i,onEvent:a,allowUnresolvedReferences:c=!1,transformDocument:u,load:f})=>{let l=to({graph:e,rootIds:t}).length,p={rootCount:t.length,documentCount:l};_e(a,{type:"resolution-started",...p});try{if(l>s)throw new Kt({code:"DOCUMENT_COUNT_EXCEEDED",message:"Document graph resolution exceeds the document limit",documentCount:l,documentLimit:s});let d=0,w=Promise.resolve(),h=await dp({graph:e,rootIds:t,concurrency:n,signal:i,load:async(y,m)=>{let A=w,S=()=>{};w=new Promise(_=>{S=_});let E;try{E={status:"fulfilled",value:await f(y,m)}}catch(_){E={status:"rejected",reason:_}}await A;try{if(E.status==="rejected")throw E.reason;if(E.value.byteLength>r)throw new Kt({code:"CONTENT_LIMIT_EXCEEDED",message:`Document ${y.id} exceeds the byte limit`,documentId:y.id,contentByteLimit:r,cause:new we});let _=d+E.value.byteLength;if(_>o)throw new Kt({code:"TOTAL_BYTES_EXCEEDED",message:"Document graph resolution exceeds the total byte limit",documentId:y.id,totalBytes:_,totalByteLimit:o});return d=_,await E.value.parse()}finally{S()}},select:({reference:y,value:m})=>np({document:m,representation:y.representation}),assemble:({node:y,source:m,references:A})=>{let S=tp({document:m,references:A,allowUnresolvedReferences:c});return u?.({node:y,document:S})??S}});return _e(a,{type:"resolution-completed",...p}),h}catch(d){throw _e(a,{type:"resolution-failed",...p,errorCode:Rn(d)}),d}},pp=({load:e,concurrency:t,signal:n,maximumDocumentBytes:r=N.hydratedFileBytes,maximumCacheBytes:o=N.hydratedTotalBytes*4})=>{if(Number.isSafeInteger(t)===!1||t<=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:p})=>Math.max(1,p)}),i=new Map,a=so({concurrency:t,signal:n}),c=p=>{if(p!==void 0&&p!==n)throw new TypeError("Document resolution session signal does not match");n?.throwIfAborted()},u=async p=>(c(),await dn(p,n)),f=async(p,d)=>{c(d.signal);let w=es(p),h=s.get(w);if(h!==void 0)return h;let y=i.get(w);if(y!==void 0)return await u(y);let m=a(async()=>{c(d.signal);let A=vn({node:p,source:await e(p,{signal:n})});c(d.signal);let S=await ti(A.source,r+1);c(d.signal);let E,_=Object.freeze({format:A.format,revision:A.revision,bytes:S,byteLength:S.byteLength,parse:()=>(E??=ep({format:A.format,source:S,maximumBytes:r}),E)});return _.byteLength<=o&&s.set(w,_),_});i.set(w,m);try{return await u(m)}finally{i.delete(w)}};return Object.freeze({getCached:p=>{c();let d=s.get(es(p));if(!(d===void 0||d.byteLength>r))return Object.freeze({format:d.format,revision:d.revision,source:d.bytes.slice()})},resolve:async p=>await Ny({...p,concurrency:t,maximumBytes:r,signal:n,load:f})})};var mp=e=>{if(e.output.mode==="all")return"all";let t=[];for(let{field:n}of Kr(e.where))n[0]==="properties"&&t.push(n);for(let{field:n}of e.sort)n[0]==="properties"&&t.push(n);if(e.output.mode==="fields")for(let n of e.output.fields)n[0]==="properties"&&t.push(n);return t},hp=e=>{let t;if(e==="#frontmatter")t="";else if(e.startsWith("#frontmatter/"))t=e.slice(12);else if(e==="#")t="";else if(e.startsWith("#/"))t=e.slice(1);else return;try{return["properties",...Qf(t)]}catch{return}},gp=(e,t)=>{let n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1)if(e[r]!==t[r])return!1;return!0},yp=({queryPaths:e,referenceId:t})=>{let n=hp(t);return n!==void 0&&(e==="all"||e.some(r=>gp(r,n)))},bp=({graph:e,sourceId:t,field:n})=>n[0]!=="properties"?!1:e.edges.some(r=>{if(r.sourceId!==t)return!1;let o=hp(r.referenceId);return o!==void 0&&gp(n,o)}),wp=({graph:e,query:t})=>{let n=mp(t),r=new Set;for(let o of e.edges)yp({queryPaths:n,referenceId:o.referenceId})&&r.add(o.sourceId);return[...r]},xp=({graph:e,query:t,rootIds:n})=>{let r=mp(t),o=new Set(n),s=new Map(e.nodes.map(l=>[l.id,l])),i=fn(e.edges),a=new Set(n),c=new Set,u=new Set,f=l=>{if(a.add(l),!u.has(l)){u.add(l);for(let p of i.get(l)??[])c.add(p),f(p.reference.documentId)}};for(let l of e.edges)o.has(l.sourceId)&&yp({queryPaths:r,referenceId:l.referenceId})&&(c.add(l),f(l.reference.documentId));return Yn({nodes:[...a].map(l=>{let p=s.get(l);if(p===void 0)throw new Error(`Document graph query root ${l} does not exist`);return p}),edges:[...c]})};var _p=({artifact:e})=>{if(e.documentGraph===void 0)return;let t=new Map(e.documents.map(s=>[s._id,s])),n=new Map(e.documentGraph.nodes.map(s=>[s.id,s])),r=new Map;for(let{sourceId:s}of e.documentGraph.edges){if(n.has(s))continue;let i=t.get(s);if(i?.properties===void 0)throw new Error(`Runtime document graph source ${s} is unavailable`);r.set(s,i),n.set(s,{id:s,revision:s,contentRef:s,format:"json"})}return{graph:Yn({nodes:[...n.values()],edges:e.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 Gi={AElig:"\xC6",AMP:"&",Aacute:"\xC1",Abreve:"\u0102",Acirc:"\xC2",Acy:"\u0410",Afr:"\u{1D504}",Agrave:"\xC0",Alpha:"\u0391",Amacr:"\u0100",And:"\u2A53",Aogon:"\u0104",Aopf:"\u{1D538}",ApplyFunction:"\u2061",Aring:"\xC5",Ascr:"\u{1D49C}",Assign:"\u2254",Atilde:"\xC3",Auml:"\xC4",Backslash:"\u2216",Barv:"\u2AE7",Barwed:"\u2306",Bcy:"\u0411",Because:"\u2235",Bernoullis:"\u212C",Beta:"\u0392",Bfr:"\u{1D505}",Bopf:"\u{1D539}",Breve:"\u02D8",Bscr:"\u212C",Bumpeq:"\u224E",CHcy:"\u0427",COPY:"\xA9",Cacute:"\u0106",Cap:"\u22D2",CapitalDifferentialD:"\u2145",Cayleys:"\u212D",Ccaron:"\u010C",Ccedil:"\xC7",Ccirc:"\u0108",Cconint:"\u2230",Cdot:"\u010A",Cedilla:"\xB8",CenterDot:"\xB7",Cfr:"\u212D",Chi:"\u03A7",CircleDot:"\u2299",CircleMinus:"\u2296",CirclePlus:"\u2295",CircleTimes:"\u2297",ClockwiseContourIntegral:"\u2232",CloseCurlyDoubleQuote:"\u201D",CloseCurlyQuote:"\u2019",Colon:"\u2237",Colone:"\u2A74",Congruent:"\u2261",Conint:"\u222F",ContourIntegral:"\u222E",Copf:"\u2102",Coproduct:"\u2210",CounterClockwiseContourIntegral:"\u2233",Cross:"\u2A2F",Cscr:"\u{1D49E}",Cup:"\u22D3",CupCap:"\u224D",DD:"\u2145",DDotrahd:"\u2911",DJcy:"\u0402",DScy:"\u0405",DZcy:"\u040F",Dagger:"\u2021",Darr:"\u21A1",Dashv:"\u2AE4",Dcaron:"\u010E",Dcy:"\u0414",Del:"\u2207",Delta:"\u0394",Dfr:"\u{1D507}",DiacriticalAcute:"\xB4",DiacriticalDot:"\u02D9",DiacriticalDoubleAcute:"\u02DD",DiacriticalGrave:"`",DiacriticalTilde:"\u02DC",Diamond:"\u22C4",DifferentialD:"\u2146",Dopf:"\u{1D53B}",Dot:"\xA8",DotDot:"\u20DC",DotEqual:"\u2250",DoubleContourIntegral:"\u222F",DoubleDot:"\xA8",DoubleDownArrow:"\u21D3",DoubleLeftArrow:"\u21D0",DoubleLeftRightArrow:"\u21D4",DoubleLeftTee:"\u2AE4",DoubleLongLeftArrow:"\u27F8",DoubleLongLeftRightArrow:"\u27FA",DoubleLongRightArrow:"\u27F9",DoubleRightArrow:"\u21D2",DoubleRightTee:"\u22A8",DoubleUpArrow:"\u21D1",DoubleUpDownArrow:"\u21D5",DoubleVerticalBar:"\u2225",DownArrow:"\u2193",DownArrowBar:"\u2913",DownArrowUpArrow:"\u21F5",DownBreve:"\u0311",DownLeftRightVector:"\u2950",DownLeftTeeVector:"\u295E",DownLeftVector:"\u21BD",DownLeftVectorBar:"\u2956",DownRightTeeVector:"\u295F",DownRightVector:"\u21C1",DownRightVectorBar:"\u2957",DownTee:"\u22A4",DownTeeArrow:"\u21A7",Downarrow:"\u21D3",Dscr:"\u{1D49F}",Dstrok:"\u0110",ENG:"\u014A",ETH:"\xD0",Eacute:"\xC9",Ecaron:"\u011A",Ecirc:"\xCA",Ecy:"\u042D",Edot:"\u0116",Efr:"\u{1D508}",Egrave:"\xC8",Element:"\u2208",Emacr:"\u0112",EmptySmallSquare:"\u25FB",EmptyVerySmallSquare:"\u25AB",Eogon:"\u0118",Eopf:"\u{1D53C}",Epsilon:"\u0395",Equal:"\u2A75",EqualTilde:"\u2242",Equilibrium:"\u21CC",Escr:"\u2130",Esim:"\u2A73",Eta:"\u0397",Euml:"\xCB",Exists:"\u2203",ExponentialE:"\u2147",Fcy:"\u0424",Ffr:"\u{1D509}",FilledSmallSquare:"\u25FC",FilledVerySmallSquare:"\u25AA",Fopf:"\u{1D53D}",ForAll:"\u2200",Fouriertrf:"\u2131",Fscr:"\u2131",GJcy:"\u0403",GT:">",Gamma:"\u0393",Gammad:"\u03DC",Gbreve:"\u011E",Gcedil:"\u0122",Gcirc:"\u011C",Gcy:"\u0413",Gdot:"\u0120",Gfr:"\u{1D50A}",Gg:"\u22D9",Gopf:"\u{1D53E}",GreaterEqual:"\u2265",GreaterEqualLess:"\u22DB",GreaterFullEqual:"\u2267",GreaterGreater:"\u2AA2",GreaterLess:"\u2277",GreaterSlantEqual:"\u2A7E",GreaterTilde:"\u2273",Gscr:"\u{1D4A2}",Gt:"\u226B",HARDcy:"\u042A",Hacek:"\u02C7",Hat:"^",Hcirc:"\u0124",Hfr:"\u210C",HilbertSpace:"\u210B",Hopf:"\u210D",HorizontalLine:"\u2500",Hscr:"\u210B",Hstrok:"\u0126",HumpDownHump:"\u224E",HumpEqual:"\u224F",IEcy:"\u0415",IJlig:"\u0132",IOcy:"\u0401",Iacute:"\xCD",Icirc:"\xCE",Icy:"\u0418",Idot:"\u0130",Ifr:"\u2111",Igrave:"\xCC",Im:"\u2111",Imacr:"\u012A",ImaginaryI:"\u2148",Implies:"\u21D2",Int:"\u222C",Integral:"\u222B",Intersection:"\u22C2",InvisibleComma:"\u2063",InvisibleTimes:"\u2062",Iogon:"\u012E",Iopf:"\u{1D540}",Iota:"\u0399",Iscr:"\u2110",Itilde:"\u0128",Iukcy:"\u0406",Iuml:"\xCF",Jcirc:"\u0134",Jcy:"\u0419",Jfr:"\u{1D50D}",Jopf:"\u{1D541}",Jscr:"\u{1D4A5}",Jsercy:"\u0408",Jukcy:"\u0404",KHcy:"\u0425",KJcy:"\u040C",Kappa:"\u039A",Kcedil:"\u0136",Kcy:"\u041A",Kfr:"\u{1D50E}",Kopf:"\u{1D542}",Kscr:"\u{1D4A6}",LJcy:"\u0409",LT:"<",Lacute:"\u0139",Lambda:"\u039B",Lang:"\u27EA",Laplacetrf:"\u2112",Larr:"\u219E",Lcaron:"\u013D",Lcedil:"\u013B",Lcy:"\u041B",LeftAngleBracket:"\u27E8",LeftArrow:"\u2190",LeftArrowBar:"\u21E4",LeftArrowRightArrow:"\u21C6",LeftCeiling:"\u2308",LeftDoubleBracket:"\u27E6",LeftDownTeeVector:"\u2961",LeftDownVector:"\u21C3",LeftDownVectorBar:"\u2959",LeftFloor:"\u230A",LeftRightArrow:"\u2194",LeftRightVector:"\u294E",LeftTee:"\u22A3",LeftTeeArrow:"\u21A4",LeftTeeVector:"\u295A",LeftTriangle:"\u22B2",LeftTriangleBar:"\u29CF",LeftTriangleEqual:"\u22B4",LeftUpDownVector:"\u2951",LeftUpTeeVector:"\u2960",LeftUpVector:"\u21BF",LeftUpVectorBar:"\u2958",LeftVector:"\u21BC",LeftVectorBar:"\u2952",Leftarrow:"\u21D0",Leftrightarrow:"\u21D4",LessEqualGreater:"\u22DA",LessFullEqual:"\u2266",LessGreater:"\u2276",LessLess:"\u2AA1",LessSlantEqual:"\u2A7D",LessTilde:"\u2272",Lfr:"\u{1D50F}",Ll:"\u22D8",Lleftarrow:"\u21DA",Lmidot:"\u013F",LongLeftArrow:"\u27F5",LongLeftRightArrow:"\u27F7",LongRightArrow:"\u27F6",Longleftarrow:"\u27F8",Longleftrightarrow:"\u27FA",Longrightarrow:"\u27F9",Lopf:"\u{1D543}",LowerLeftArrow:"\u2199",LowerRightArrow:"\u2198",Lscr:"\u2112",Lsh:"\u21B0",Lstrok:"\u0141",Lt:"\u226A",Map:"\u2905",Mcy:"\u041C",MediumSpace:"\u205F",Mellintrf:"\u2133",Mfr:"\u{1D510}",MinusPlus:"\u2213",Mopf:"\u{1D544}",Mscr:"\u2133",Mu:"\u039C",NJcy:"\u040A",Nacute:"\u0143",Ncaron:"\u0147",Ncedil:"\u0145",Ncy:"\u041D",NegativeMediumSpace:"\u200B",NegativeThickSpace:"\u200B",NegativeThinSpace:"\u200B",NegativeVeryThinSpace:"\u200B",NestedGreaterGreater:"\u226B",NestedLessLess:"\u226A",NewLine:`+`,Nfr:"\u{1D511}",NoBreak:"\u2060",NonBreakingSpace:"\xA0",Nopf:"\u2115",Not:"\u2AEC",NotCongruent:"\u2262",NotCupCap:"\u226D",NotDoubleVerticalBar:"\u2226",NotElement:"\u2209",NotEqual:"\u2260",NotEqualTilde:"\u2242\u0338",NotExists:"\u2204",NotGreater:"\u226F",NotGreaterEqual:"\u2271",NotGreaterFullEqual:"\u2267\u0338",NotGreaterGreater:"\u226B\u0338",NotGreaterLess:"\u2279",NotGreaterSlantEqual:"\u2A7E\u0338",NotGreaterTilde:"\u2275",NotHumpDownHump:"\u224E\u0338",NotHumpEqual:"\u224F\u0338",NotLeftTriangle:"\u22EA",NotLeftTriangleBar:"\u29CF\u0338",NotLeftTriangleEqual:"\u22EC",NotLess:"\u226E",NotLessEqual:"\u2270",NotLessGreater:"\u2278",NotLessLess:"\u226A\u0338",NotLessSlantEqual:"\u2A7D\u0338",NotLessTilde:"\u2274",NotNestedGreaterGreater:"\u2AA2\u0338",NotNestedLessLess:"\u2AA1\u0338",NotPrecedes:"\u2280",NotPrecedesEqual:"\u2AAF\u0338",NotPrecedesSlantEqual:"\u22E0",NotReverseElement:"\u220C",NotRightTriangle:"\u22EB",NotRightTriangleBar:"\u29D0\u0338",NotRightTriangleEqual:"\u22ED",NotSquareSubset:"\u228F\u0338",NotSquareSubsetEqual:"\u22E2",NotSquareSuperset:"\u2290\u0338",NotSquareSupersetEqual:"\u22E3",NotSubset:"\u2282\u20D2",NotSubsetEqual:"\u2288",NotSucceeds:"\u2281",NotSucceedsEqual:"\u2AB0\u0338",NotSucceedsSlantEqual:"\u22E1",NotSucceedsTilde:"\u227F\u0338",NotSuperset:"\u2283\u20D2",NotSupersetEqual:"\u2289",NotTilde:"\u2241",NotTildeEqual:"\u2244",NotTildeFullEqual:"\u2247",NotTildeTilde:"\u2249",NotVerticalBar:"\u2224",Nscr:"\u{1D4A9}",Ntilde:"\xD1",Nu:"\u039D",OElig:"\u0152",Oacute:"\xD3",Ocirc:"\xD4",Ocy:"\u041E",Odblac:"\u0150",Ofr:"\u{1D512}",Ograve:"\xD2",Omacr:"\u014C",Omega:"\u03A9",Omicron:"\u039F",Oopf:"\u{1D546}",OpenCurlyDoubleQuote:"\u201C",OpenCurlyQuote:"\u2018",Or:"\u2A54",Oscr:"\u{1D4AA}",Oslash:"\xD8",Otilde:"\xD5",Otimes:"\u2A37",Ouml:"\xD6",OverBar:"\u203E",OverBrace:"\u23DE",OverBracket:"\u23B4",OverParenthesis:"\u23DC",PartialD:"\u2202",Pcy:"\u041F",Pfr:"\u{1D513}",Phi:"\u03A6",Pi:"\u03A0",PlusMinus:"\xB1",Poincareplane:"\u210C",Popf:"\u2119",Pr:"\u2ABB",Precedes:"\u227A",PrecedesEqual:"\u2AAF",PrecedesSlantEqual:"\u227C",PrecedesTilde:"\u227E",Prime:"\u2033",Product:"\u220F",Proportion:"\u2237",Proportional:"\u221D",Pscr:"\u{1D4AB}",Psi:"\u03A8",QUOT:'"',Qfr:"\u{1D514}",Qopf:"\u211A",Qscr:"\u{1D4AC}",RBarr:"\u2910",REG:"\xAE",Racute:"\u0154",Rang:"\u27EB",Rarr:"\u21A0",Rarrtl:"\u2916",Rcaron:"\u0158",Rcedil:"\u0156",Rcy:"\u0420",Re:"\u211C",ReverseElement:"\u220B",ReverseEquilibrium:"\u21CB",ReverseUpEquilibrium:"\u296F",Rfr:"\u211C",Rho:"\u03A1",RightAngleBracket:"\u27E9",RightArrow:"\u2192",RightArrowBar:"\u21E5",RightArrowLeftArrow:"\u21C4",RightCeiling:"\u2309",RightDoubleBracket:"\u27E7",RightDownTeeVector:"\u295D",RightDownVector:"\u21C2",RightDownVectorBar:"\u2955",RightFloor:"\u230B",RightTee:"\u22A2",RightTeeArrow:"\u21A6",RightTeeVector:"\u295B",RightTriangle:"\u22B3",RightTriangleBar:"\u29D0",RightTriangleEqual:"\u22B5",RightUpDownVector:"\u294F",RightUpTeeVector:"\u295C",RightUpVector:"\u21BE",RightUpVectorBar:"\u2954",RightVector:"\u21C0",RightVectorBar:"\u2953",Rightarrow:"\u21D2",Ropf:"\u211D",RoundImplies:"\u2970",Rrightarrow:"\u21DB",Rscr:"\u211B",Rsh:"\u21B1",RuleDelayed:"\u29F4",SHCHcy:"\u0429",SHcy:"\u0428",SOFTcy:"\u042C",Sacute:"\u015A",Sc:"\u2ABC",Scaron:"\u0160",Scedil:"\u015E",Scirc:"\u015C",Scy:"\u0421",Sfr:"\u{1D516}",ShortDownArrow:"\u2193",ShortLeftArrow:"\u2190",ShortRightArrow:"\u2192",ShortUpArrow:"\u2191",Sigma:"\u03A3",SmallCircle:"\u2218",Sopf:"\u{1D54A}",Sqrt:"\u221A",Square:"\u25A1",SquareIntersection:"\u2293",SquareSubset:"\u228F",SquareSubsetEqual:"\u2291",SquareSuperset:"\u2290",SquareSupersetEqual:"\u2292",SquareUnion:"\u2294",Sscr:"\u{1D4AE}",Star:"\u22C6",Sub:"\u22D0",Subset:"\u22D0",SubsetEqual:"\u2286",Succeeds:"\u227B",SucceedsEqual:"\u2AB0",SucceedsSlantEqual:"\u227D",SucceedsTilde:"\u227F",SuchThat:"\u220B",Sum:"\u2211",Sup:"\u22D1",Superset:"\u2283",SupersetEqual:"\u2287",Supset:"\u22D1",THORN:"\xDE",TRADE:"\u2122",TSHcy:"\u040B",TScy:"\u0426",Tab:" ",Tau:"\u03A4",Tcaron:"\u0164",Tcedil:"\u0162",Tcy:"\u0422",Tfr:"\u{1D517}",Therefore:"\u2234",Theta:"\u0398",ThickSpace:"\u205F\u200A",ThinSpace:"\u2009",Tilde:"\u223C",TildeEqual:"\u2243",TildeFullEqual:"\u2245",TildeTilde:"\u2248",Topf:"\u{1D54B}",TripleDot:"\u20DB",Tscr:"\u{1D4AF}",Tstrok:"\u0166",Uacute:"\xDA",Uarr:"\u219F",Uarrocir:"\u2949",Ubrcy:"\u040E",Ubreve:"\u016C",Ucirc:"\xDB",Ucy:"\u0423",Udblac:"\u0170",Ufr:"\u{1D518}",Ugrave:"\xD9",Umacr:"\u016A",UnderBar:"_",UnderBrace:"\u23DF",UnderBracket:"\u23B5",UnderParenthesis:"\u23DD",Union:"\u22C3",UnionPlus:"\u228E",Uogon:"\u0172",Uopf:"\u{1D54C}",UpArrow:"\u2191",UpArrowBar:"\u2912",UpArrowDownArrow:"\u21C5",UpDownArrow:"\u2195",UpEquilibrium:"\u296E",UpTee:"\u22A5",UpTeeArrow:"\u21A5",Uparrow:"\u21D1",Updownarrow:"\u21D5",UpperLeftArrow:"\u2196",UpperRightArrow:"\u2197",Upsi:"\u03D2",Upsilon:"\u03A5",Uring:"\u016E",Uscr:"\u{1D4B0}",Utilde:"\u0168",Uuml:"\xDC",VDash:"\u22AB",Vbar:"\u2AEB",Vcy:"\u0412",Vdash:"\u22A9",Vdashl:"\u2AE6",Vee:"\u22C1",Verbar:"\u2016",Vert:"\u2016",VerticalBar:"\u2223",VerticalLine:"|",VerticalSeparator:"\u2758",VerticalTilde:"\u2240",VeryThinSpace:"\u200A",Vfr:"\u{1D519}",Vopf:"\u{1D54D}",Vscr:"\u{1D4B1}",Vvdash:"\u22AA",Wcirc:"\u0174",Wedge:"\u22C0",Wfr:"\u{1D51A}",Wopf:"\u{1D54E}",Wscr:"\u{1D4B2}",Xfr:"\u{1D51B}",Xi:"\u039E",Xopf:"\u{1D54F}",Xscr:"\u{1D4B3}",YAcy:"\u042F",YIcy:"\u0407",YUcy:"\u042E",Yacute:"\xDD",Ycirc:"\u0176",Ycy:"\u042B",Yfr:"\u{1D51C}",Yopf:"\u{1D550}",Yscr:"\u{1D4B4}",Yuml:"\u0178",ZHcy:"\u0416",Zacute:"\u0179",Zcaron:"\u017D",Zcy:"\u0417",Zdot:"\u017B",ZeroWidthSpace:"\u200B",Zeta:"\u0396",Zfr:"\u2128",Zopf:"\u2124",Zscr:"\u{1D4B5}",aacute:"\xE1",abreve:"\u0103",ac:"\u223E",acE:"\u223E\u0333",acd:"\u223F",acirc:"\xE2",acute:"\xB4",acy:"\u0430",aelig:"\xE6",af:"\u2061",afr:"\u{1D51E}",agrave:"\xE0",alefsym:"\u2135",aleph:"\u2135",alpha:"\u03B1",amacr:"\u0101",amalg:"\u2A3F",amp:"&",and:"\u2227",andand:"\u2A55",andd:"\u2A5C",andslope:"\u2A58",andv:"\u2A5A",ang:"\u2220",ange:"\u29A4",angle:"\u2220",angmsd:"\u2221",angmsdaa:"\u29A8",angmsdab:"\u29A9",angmsdac:"\u29AA",angmsdad:"\u29AB",angmsdae:"\u29AC",angmsdaf:"\u29AD",angmsdag:"\u29AE",angmsdah:"\u29AF",angrt:"\u221F",angrtvb:"\u22BE",angrtvbd:"\u299D",angsph:"\u2222",angst:"\xC5",angzarr:"\u237C",aogon:"\u0105",aopf:"\u{1D552}",ap:"\u2248",apE:"\u2A70",apacir:"\u2A6F",ape:"\u224A",apid:"\u224B",apos:"'",approx:"\u2248",approxeq:"\u224A",aring:"\xE5",ascr:"\u{1D4B6}",ast:"*",asymp:"\u2248",asympeq:"\u224D",atilde:"\xE3",auml:"\xE4",awconint:"\u2233",awint:"\u2A11",bNot:"\u2AED",backcong:"\u224C",backepsilon:"\u03F6",backprime:"\u2035",backsim:"\u223D",backsimeq:"\u22CD",barvee:"\u22BD",barwed:"\u2305",barwedge:"\u2305",bbrk:"\u23B5",bbrktbrk:"\u23B6",bcong:"\u224C",bcy:"\u0431",bdquo:"\u201E",becaus:"\u2235",because:"\u2235",bemptyv:"\u29B0",bepsi:"\u03F6",bernou:"\u212C",beta:"\u03B2",beth:"\u2136",between:"\u226C",bfr:"\u{1D51F}",bigcap:"\u22C2",bigcirc:"\u25EF",bigcup:"\u22C3",bigodot:"\u2A00",bigoplus:"\u2A01",bigotimes:"\u2A02",bigsqcup:"\u2A06",bigstar:"\u2605",bigtriangledown:"\u25BD",bigtriangleup:"\u25B3",biguplus:"\u2A04",bigvee:"\u22C1",bigwedge:"\u22C0",bkarow:"\u290D",blacklozenge:"\u29EB",blacksquare:"\u25AA",blacktriangle:"\u25B4",blacktriangledown:"\u25BE",blacktriangleleft:"\u25C2",blacktriangleright:"\u25B8",blank:"\u2423",blk12:"\u2592",blk14:"\u2591",blk34:"\u2593",block:"\u2588",bne:"=\u20E5",bnequiv:"\u2261\u20E5",bnot:"\u2310",bopf:"\u{1D553}",bot:"\u22A5",bottom:"\u22A5",bowtie:"\u22C8",boxDL:"\u2557",boxDR:"\u2554",boxDl:"\u2556",boxDr:"\u2553",boxH:"\u2550",boxHD:"\u2566",boxHU:"\u2569",boxHd:"\u2564",boxHu:"\u2567",boxUL:"\u255D",boxUR:"\u255A",boxUl:"\u255C",boxUr:"\u2559",boxV:"\u2551",boxVH:"\u256C",boxVL:"\u2563",boxVR:"\u2560",boxVh:"\u256B",boxVl:"\u2562",boxVr:"\u255F",boxbox:"\u29C9",boxdL:"\u2555",boxdR:"\u2552",boxdl:"\u2510",boxdr:"\u250C",boxh:"\u2500",boxhD:"\u2565",boxhU:"\u2568",boxhd:"\u252C",boxhu:"\u2534",boxminus:"\u229F",boxplus:"\u229E",boxtimes:"\u22A0",boxuL:"\u255B",boxuR:"\u2558",boxul:"\u2518",boxur:"\u2514",boxv:"\u2502",boxvH:"\u256A",boxvL:"\u2561",boxvR:"\u255E",boxvh:"\u253C",boxvl:"\u2524",boxvr:"\u251C",bprime:"\u2035",breve:"\u02D8",brvbar:"\xA6",bscr:"\u{1D4B7}",bsemi:"\u204F",bsim:"\u223D",bsime:"\u22CD",bsol:"\\",bsolb:"\u29C5",bsolhsub:"\u27C8",bull:"\u2022",bullet:"\u2022",bump:"\u224E",bumpE:"\u2AAE",bumpe:"\u224F",bumpeq:"\u224F",cacute:"\u0107",cap:"\u2229",capand:"\u2A44",capbrcup:"\u2A49",capcap:"\u2A4B",capcup:"\u2A47",capdot:"\u2A40",caps:"\u2229\uFE00",caret:"\u2041",caron:"\u02C7",ccaps:"\u2A4D",ccaron:"\u010D",ccedil:"\xE7",ccirc:"\u0109",ccups:"\u2A4C",ccupssm:"\u2A50",cdot:"\u010B",cedil:"\xB8",cemptyv:"\u29B2",cent:"\xA2",centerdot:"\xB7",cfr:"\u{1D520}",chcy:"\u0447",check:"\u2713",checkmark:"\u2713",chi:"\u03C7",cir:"\u25CB",cirE:"\u29C3",circ:"\u02C6",circeq:"\u2257",circlearrowleft:"\u21BA",circlearrowright:"\u21BB",circledR:"\xAE",circledS:"\u24C8",circledast:"\u229B",circledcirc:"\u229A",circleddash:"\u229D",cire:"\u2257",cirfnint:"\u2A10",cirmid:"\u2AEF",cirscir:"\u29C2",clubs:"\u2663",clubsuit:"\u2663",colon:":",colone:"\u2254",coloneq:"\u2254",comma:",",commat:"@",comp:"\u2201",compfn:"\u2218",complement:"\u2201",complexes:"\u2102",cong:"\u2245",congdot:"\u2A6D",conint:"\u222E",copf:"\u{1D554}",coprod:"\u2210",copy:"\xA9",copysr:"\u2117",crarr:"\u21B5",cross:"\u2717",cscr:"\u{1D4B8}",csub:"\u2ACF",csube:"\u2AD1",csup:"\u2AD0",csupe:"\u2AD2",ctdot:"\u22EF",cudarrl:"\u2938",cudarrr:"\u2935",cuepr:"\u22DE",cuesc:"\u22DF",cularr:"\u21B6",cularrp:"\u293D",cup:"\u222A",cupbrcap:"\u2A48",cupcap:"\u2A46",cupcup:"\u2A4A",cupdot:"\u228D",cupor:"\u2A45",cups:"\u222A\uFE00",curarr:"\u21B7",curarrm:"\u293C",curlyeqprec:"\u22DE",curlyeqsucc:"\u22DF",curlyvee:"\u22CE",curlywedge:"\u22CF",curren:"\xA4",curvearrowleft:"\u21B6",curvearrowright:"\u21B7",cuvee:"\u22CE",cuwed:"\u22CF",cwconint:"\u2232",cwint:"\u2231",cylcty:"\u232D",dArr:"\u21D3",dHar:"\u2965",dagger:"\u2020",daleth:"\u2138",darr:"\u2193",dash:"\u2010",dashv:"\u22A3",dbkarow:"\u290F",dblac:"\u02DD",dcaron:"\u010F",dcy:"\u0434",dd:"\u2146",ddagger:"\u2021",ddarr:"\u21CA",ddotseq:"\u2A77",deg:"\xB0",delta:"\u03B4",demptyv:"\u29B1",dfisht:"\u297F",dfr:"\u{1D521}",dharl:"\u21C3",dharr:"\u21C2",diam:"\u22C4",diamond:"\u22C4",diamondsuit:"\u2666",diams:"\u2666",die:"\xA8",digamma:"\u03DD",disin:"\u22F2",div:"\xF7",divide:"\xF7",divideontimes:"\u22C7",divonx:"\u22C7",djcy:"\u0452",dlcorn:"\u231E",dlcrop:"\u230D",dollar:"$",dopf:"\u{1D555}",dot:"\u02D9",doteq:"\u2250",doteqdot:"\u2251",dotminus:"\u2238",dotplus:"\u2214",dotsquare:"\u22A1",doublebarwedge:"\u2306",downarrow:"\u2193",downdownarrows:"\u21CA",downharpoonleft:"\u21C3",downharpoonright:"\u21C2",drbkarow:"\u2910",drcorn:"\u231F",drcrop:"\u230C",dscr:"\u{1D4B9}",dscy:"\u0455",dsol:"\u29F6",dstrok:"\u0111",dtdot:"\u22F1",dtri:"\u25BF",dtrif:"\u25BE",duarr:"\u21F5",duhar:"\u296F",dwangle:"\u29A6",dzcy:"\u045F",dzigrarr:"\u27FF",eDDot:"\u2A77",eDot:"\u2251",eacute:"\xE9",easter:"\u2A6E",ecaron:"\u011B",ecir:"\u2256",ecirc:"\xEA",ecolon:"\u2255",ecy:"\u044D",edot:"\u0117",ee:"\u2147",efDot:"\u2252",efr:"\u{1D522}",eg:"\u2A9A",egrave:"\xE8",egs:"\u2A96",egsdot:"\u2A98",el:"\u2A99",elinters:"\u23E7",ell:"\u2113",els:"\u2A95",elsdot:"\u2A97",emacr:"\u0113",empty:"\u2205",emptyset:"\u2205",emptyv:"\u2205",emsp13:"\u2004",emsp14:"\u2005",emsp:"\u2003",eng:"\u014B",ensp:"\u2002",eogon:"\u0119",eopf:"\u{1D556}",epar:"\u22D5",eparsl:"\u29E3",eplus:"\u2A71",epsi:"\u03B5",epsilon:"\u03B5",epsiv:"\u03F5",eqcirc:"\u2256",eqcolon:"\u2255",eqsim:"\u2242",eqslantgtr:"\u2A96",eqslantless:"\u2A95",equals:"=",equest:"\u225F",equiv:"\u2261",equivDD:"\u2A78",eqvparsl:"\u29E5",erDot:"\u2253",erarr:"\u2971",escr:"\u212F",esdot:"\u2250",esim:"\u2242",eta:"\u03B7",eth:"\xF0",euml:"\xEB",euro:"\u20AC",excl:"!",exist:"\u2203",expectation:"\u2130",exponentiale:"\u2147",fallingdotseq:"\u2252",fcy:"\u0444",female:"\u2640",ffilig:"\uFB03",fflig:"\uFB00",ffllig:"\uFB04",ffr:"\u{1D523}",filig:"\uFB01",fjlig:"fj",flat:"\u266D",fllig:"\uFB02",fltns:"\u25B1",fnof:"\u0192",fopf:"\u{1D557}",forall:"\u2200",fork:"\u22D4",forkv:"\u2AD9",fpartint:"\u2A0D",frac12:"\xBD",frac13:"\u2153",frac14:"\xBC",frac15:"\u2155",frac16:"\u2159",frac18:"\u215B",frac23:"\u2154",frac25:"\u2156",frac34:"\xBE",frac35:"\u2157",frac38:"\u215C",frac45:"\u2158",frac56:"\u215A",frac58:"\u215D",frac78:"\u215E",frasl:"\u2044",frown:"\u2322",fscr:"\u{1D4BB}",gE:"\u2267",gEl:"\u2A8C",gacute:"\u01F5",gamma:"\u03B3",gammad:"\u03DD",gap:"\u2A86",gbreve:"\u011F",gcirc:"\u011D",gcy:"\u0433",gdot:"\u0121",ge:"\u2265",gel:"\u22DB",geq:"\u2265",geqq:"\u2267",geqslant:"\u2A7E",ges:"\u2A7E",gescc:"\u2AA9",gesdot:"\u2A80",gesdoto:"\u2A82",gesdotol:"\u2A84",gesl:"\u22DB\uFE00",gesles:"\u2A94",gfr:"\u{1D524}",gg:"\u226B",ggg:"\u22D9",gimel:"\u2137",gjcy:"\u0453",gl:"\u2277",glE:"\u2A92",gla:"\u2AA5",glj:"\u2AA4",gnE:"\u2269",gnap:"\u2A8A",gnapprox:"\u2A8A",gne:"\u2A88",gneq:"\u2A88",gneqq:"\u2269",gnsim:"\u22E7",gopf:"\u{1D558}",grave:"`",gscr:"\u210A",gsim:"\u2273",gsime:"\u2A8E",gsiml:"\u2A90",gt:">",gtcc:"\u2AA7",gtcir:"\u2A7A",gtdot:"\u22D7",gtlPar:"\u2995",gtquest:"\u2A7C",gtrapprox:"\u2A86",gtrarr:"\u2978",gtrdot:"\u22D7",gtreqless:"\u22DB",gtreqqless:"\u2A8C",gtrless:"\u2277",gtrsim:"\u2273",gvertneqq:"\u2269\uFE00",gvnE:"\u2269\uFE00",hArr:"\u21D4",hairsp:"\u200A",half:"\xBD",hamilt:"\u210B",hardcy:"\u044A",harr:"\u2194",harrcir:"\u2948",harrw:"\u21AD",hbar:"\u210F",hcirc:"\u0125",hearts:"\u2665",heartsuit:"\u2665",hellip:"\u2026",hercon:"\u22B9",hfr:"\u{1D525}",hksearow:"\u2925",hkswarow:"\u2926",hoarr:"\u21FF",homtht:"\u223B",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",hopf:"\u{1D559}",horbar:"\u2015",hscr:"\u{1D4BD}",hslash:"\u210F",hstrok:"\u0127",hybull:"\u2043",hyphen:"\u2010",iacute:"\xED",ic:"\u2063",icirc:"\xEE",icy:"\u0438",iecy:"\u0435",iexcl:"\xA1",iff:"\u21D4",ifr:"\u{1D526}",igrave:"\xEC",ii:"\u2148",iiiint:"\u2A0C",iiint:"\u222D",iinfin:"\u29DC",iiota:"\u2129",ijlig:"\u0133",imacr:"\u012B",image:"\u2111",imagline:"\u2110",imagpart:"\u2111",imath:"\u0131",imof:"\u22B7",imped:"\u01B5",in:"\u2208",incare:"\u2105",infin:"\u221E",infintie:"\u29DD",inodot:"\u0131",int:"\u222B",intcal:"\u22BA",integers:"\u2124",intercal:"\u22BA",intlarhk:"\u2A17",intprod:"\u2A3C",iocy:"\u0451",iogon:"\u012F",iopf:"\u{1D55A}",iota:"\u03B9",iprod:"\u2A3C",iquest:"\xBF",iscr:"\u{1D4BE}",isin:"\u2208",isinE:"\u22F9",isindot:"\u22F5",isins:"\u22F4",isinsv:"\u22F3",isinv:"\u2208",it:"\u2062",itilde:"\u0129",iukcy:"\u0456",iuml:"\xEF",jcirc:"\u0135",jcy:"\u0439",jfr:"\u{1D527}",jmath:"\u0237",jopf:"\u{1D55B}",jscr:"\u{1D4BF}",jsercy:"\u0458",jukcy:"\u0454",kappa:"\u03BA",kappav:"\u03F0",kcedil:"\u0137",kcy:"\u043A",kfr:"\u{1D528}",kgreen:"\u0138",khcy:"\u0445",kjcy:"\u045C",kopf:"\u{1D55C}",kscr:"\u{1D4C0}",lAarr:"\u21DA",lArr:"\u21D0",lAtail:"\u291B",lBarr:"\u290E",lE:"\u2266",lEg:"\u2A8B",lHar:"\u2962",lacute:"\u013A",laemptyv:"\u29B4",lagran:"\u2112",lambda:"\u03BB",lang:"\u27E8",langd:"\u2991",langle:"\u27E8",lap:"\u2A85",laquo:"\xAB",larr:"\u2190",larrb:"\u21E4",larrbfs:"\u291F",larrfs:"\u291D",larrhk:"\u21A9",larrlp:"\u21AB",larrpl:"\u2939",larrsim:"\u2973",larrtl:"\u21A2",lat:"\u2AAB",latail:"\u2919",late:"\u2AAD",lates:"\u2AAD\uFE00",lbarr:"\u290C",lbbrk:"\u2772",lbrace:"{",lbrack:"[",lbrke:"\u298B",lbrksld:"\u298F",lbrkslu:"\u298D",lcaron:"\u013E",lcedil:"\u013C",lceil:"\u2308",lcub:"{",lcy:"\u043B",ldca:"\u2936",ldquo:"\u201C",ldquor:"\u201E",ldrdhar:"\u2967",ldrushar:"\u294B",ldsh:"\u21B2",le:"\u2264",leftarrow:"\u2190",leftarrowtail:"\u21A2",leftharpoondown:"\u21BD",leftharpoonup:"\u21BC",leftleftarrows:"\u21C7",leftrightarrow:"\u2194",leftrightarrows:"\u21C6",leftrightharpoons:"\u21CB",leftrightsquigarrow:"\u21AD",leftthreetimes:"\u22CB",leg:"\u22DA",leq:"\u2264",leqq:"\u2266",leqslant:"\u2A7D",les:"\u2A7D",lescc:"\u2AA8",lesdot:"\u2A7F",lesdoto:"\u2A81",lesdotor:"\u2A83",lesg:"\u22DA\uFE00",lesges:"\u2A93",lessapprox:"\u2A85",lessdot:"\u22D6",lesseqgtr:"\u22DA",lesseqqgtr:"\u2A8B",lessgtr:"\u2276",lesssim:"\u2272",lfisht:"\u297C",lfloor:"\u230A",lfr:"\u{1D529}",lg:"\u2276",lgE:"\u2A91",lhard:"\u21BD",lharu:"\u21BC",lharul:"\u296A",lhblk:"\u2584",ljcy:"\u0459",ll:"\u226A",llarr:"\u21C7",llcorner:"\u231E",llhard:"\u296B",lltri:"\u25FA",lmidot:"\u0140",lmoust:"\u23B0",lmoustache:"\u23B0",lnE:"\u2268",lnap:"\u2A89",lnapprox:"\u2A89",lne:"\u2A87",lneq:"\u2A87",lneqq:"\u2268",lnsim:"\u22E6",loang:"\u27EC",loarr:"\u21FD",lobrk:"\u27E6",longleftarrow:"\u27F5",longleftrightarrow:"\u27F7",longmapsto:"\u27FC",longrightarrow:"\u27F6",looparrowleft:"\u21AB",looparrowright:"\u21AC",lopar:"\u2985",lopf:"\u{1D55D}",loplus:"\u2A2D",lotimes:"\u2A34",lowast:"\u2217",lowbar:"_",loz:"\u25CA",lozenge:"\u25CA",lozf:"\u29EB",lpar:"(",lparlt:"\u2993",lrarr:"\u21C6",lrcorner:"\u231F",lrhar:"\u21CB",lrhard:"\u296D",lrm:"\u200E",lrtri:"\u22BF",lsaquo:"\u2039",lscr:"\u{1D4C1}",lsh:"\u21B0",lsim:"\u2272",lsime:"\u2A8D",lsimg:"\u2A8F",lsqb:"[",lsquo:"\u2018",lsquor:"\u201A",lstrok:"\u0142",lt:"<",ltcc:"\u2AA6",ltcir:"\u2A79",ltdot:"\u22D6",lthree:"\u22CB",ltimes:"\u22C9",ltlarr:"\u2976",ltquest:"\u2A7B",ltrPar:"\u2996",ltri:"\u25C3",ltrie:"\u22B4",ltrif:"\u25C2",lurdshar:"\u294A",luruhar:"\u2966",lvertneqq:"\u2268\uFE00",lvnE:"\u2268\uFE00",mDDot:"\u223A",macr:"\xAF",male:"\u2642",malt:"\u2720",maltese:"\u2720",map:"\u21A6",mapsto:"\u21A6",mapstodown:"\u21A7",mapstoleft:"\u21A4",mapstoup:"\u21A5",marker:"\u25AE",mcomma:"\u2A29",mcy:"\u043C",mdash:"\u2014",measuredangle:"\u2221",mfr:"\u{1D52A}",mho:"\u2127",micro:"\xB5",mid:"\u2223",midast:"*",midcir:"\u2AF0",middot:"\xB7",minus:"\u2212",minusb:"\u229F",minusd:"\u2238",minusdu:"\u2A2A",mlcp:"\u2ADB",mldr:"\u2026",mnplus:"\u2213",models:"\u22A7",mopf:"\u{1D55E}",mp:"\u2213",mscr:"\u{1D4C2}",mstpos:"\u223E",mu:"\u03BC",multimap:"\u22B8",mumap:"\u22B8",nGg:"\u22D9\u0338",nGt:"\u226B\u20D2",nGtv:"\u226B\u0338",nLeftarrow:"\u21CD",nLeftrightarrow:"\u21CE",nLl:"\u22D8\u0338",nLt:"\u226A\u20D2",nLtv:"\u226A\u0338",nRightarrow:"\u21CF",nVDash:"\u22AF",nVdash:"\u22AE",nabla:"\u2207",nacute:"\u0144",nang:"\u2220\u20D2",nap:"\u2249",napE:"\u2A70\u0338",napid:"\u224B\u0338",napos:"\u0149",napprox:"\u2249",natur:"\u266E",natural:"\u266E",naturals:"\u2115",nbsp:"\xA0",nbump:"\u224E\u0338",nbumpe:"\u224F\u0338",ncap:"\u2A43",ncaron:"\u0148",ncedil:"\u0146",ncong:"\u2247",ncongdot:"\u2A6D\u0338",ncup:"\u2A42",ncy:"\u043D",ndash:"\u2013",ne:"\u2260",neArr:"\u21D7",nearhk:"\u2924",nearr:"\u2197",nearrow:"\u2197",nedot:"\u2250\u0338",nequiv:"\u2262",nesear:"\u2928",nesim:"\u2242\u0338",nexist:"\u2204",nexists:"\u2204",nfr:"\u{1D52B}",ngE:"\u2267\u0338",nge:"\u2271",ngeq:"\u2271",ngeqq:"\u2267\u0338",ngeqslant:"\u2A7E\u0338",nges:"\u2A7E\u0338",ngsim:"\u2275",ngt:"\u226F",ngtr:"\u226F",nhArr:"\u21CE",nharr:"\u21AE",nhpar:"\u2AF2",ni:"\u220B",nis:"\u22FC",nisd:"\u22FA",niv:"\u220B",njcy:"\u045A",nlArr:"\u21CD",nlE:"\u2266\u0338",nlarr:"\u219A",nldr:"\u2025",nle:"\u2270",nleftarrow:"\u219A",nleftrightarrow:"\u21AE",nleq:"\u2270",nleqq:"\u2266\u0338",nleqslant:"\u2A7D\u0338",nles:"\u2A7D\u0338",nless:"\u226E",nlsim:"\u2274",nlt:"\u226E",nltri:"\u22EA",nltrie:"\u22EC",nmid:"\u2224",nopf:"\u{1D55F}",not:"\xAC",notin:"\u2209",notinE:"\u22F9\u0338",notindot:"\u22F5\u0338",notinva:"\u2209",notinvb:"\u22F7",notinvc:"\u22F6",notni:"\u220C",notniva:"\u220C",notnivb:"\u22FE",notnivc:"\u22FD",npar:"\u2226",nparallel:"\u2226",nparsl:"\u2AFD\u20E5",npart:"\u2202\u0338",npolint:"\u2A14",npr:"\u2280",nprcue:"\u22E0",npre:"\u2AAF\u0338",nprec:"\u2280",npreceq:"\u2AAF\u0338",nrArr:"\u21CF",nrarr:"\u219B",nrarrc:"\u2933\u0338",nrarrw:"\u219D\u0338",nrightarrow:"\u219B",nrtri:"\u22EB",nrtrie:"\u22ED",nsc:"\u2281",nsccue:"\u22E1",nsce:"\u2AB0\u0338",nscr:"\u{1D4C3}",nshortmid:"\u2224",nshortparallel:"\u2226",nsim:"\u2241",nsime:"\u2244",nsimeq:"\u2244",nsmid:"\u2224",nspar:"\u2226",nsqsube:"\u22E2",nsqsupe:"\u22E3",nsub:"\u2284",nsubE:"\u2AC5\u0338",nsube:"\u2288",nsubset:"\u2282\u20D2",nsubseteq:"\u2288",nsubseteqq:"\u2AC5\u0338",nsucc:"\u2281",nsucceq:"\u2AB0\u0338",nsup:"\u2285",nsupE:"\u2AC6\u0338",nsupe:"\u2289",nsupset:"\u2283\u20D2",nsupseteq:"\u2289",nsupseteqq:"\u2AC6\u0338",ntgl:"\u2279",ntilde:"\xF1",ntlg:"\u2278",ntriangleleft:"\u22EA",ntrianglelefteq:"\u22EC",ntriangleright:"\u22EB",ntrianglerighteq:"\u22ED",nu:"\u03BD",num:"#",numero:"\u2116",numsp:"\u2007",nvDash:"\u22AD",nvHarr:"\u2904",nvap:"\u224D\u20D2",nvdash:"\u22AC",nvge:"\u2265\u20D2",nvgt:">\u20D2",nvinfin:"\u29DE",nvlArr:"\u2902",nvle:"\u2264\u20D2",nvlt:"<\u20D2",nvltrie:"\u22B4\u20D2",nvrArr:"\u2903",nvrtrie:"\u22B5\u20D2",nvsim:"\u223C\u20D2",nwArr:"\u21D6",nwarhk:"\u2923",nwarr:"\u2196",nwarrow:"\u2196",nwnear:"\u2927",oS:"\u24C8",oacute:"\xF3",oast:"\u229B",ocir:"\u229A",ocirc:"\xF4",ocy:"\u043E",odash:"\u229D",odblac:"\u0151",odiv:"\u2A38",odot:"\u2299",odsold:"\u29BC",oelig:"\u0153",ofcir:"\u29BF",ofr:"\u{1D52C}",ogon:"\u02DB",ograve:"\xF2",ogt:"\u29C1",ohbar:"\u29B5",ohm:"\u03A9",oint:"\u222E",olarr:"\u21BA",olcir:"\u29BE",olcross:"\u29BB",oline:"\u203E",olt:"\u29C0",omacr:"\u014D",omega:"\u03C9",omicron:"\u03BF",omid:"\u29B6",ominus:"\u2296",oopf:"\u{1D560}",opar:"\u29B7",operp:"\u29B9",oplus:"\u2295",or:"\u2228",orarr:"\u21BB",ord:"\u2A5D",order:"\u2134",orderof:"\u2134",ordf:"\xAA",ordm:"\xBA",origof:"\u22B6",oror:"\u2A56",orslope:"\u2A57",orv:"\u2A5B",oscr:"\u2134",oslash:"\xF8",osol:"\u2298",otilde:"\xF5",otimes:"\u2297",otimesas:"\u2A36",ouml:"\xF6",ovbar:"\u233D",par:"\u2225",para:"\xB6",parallel:"\u2225",parsim:"\u2AF3",parsl:"\u2AFD",part:"\u2202",pcy:"\u043F",percnt:"%",period:".",permil:"\u2030",perp:"\u22A5",pertenk:"\u2031",pfr:"\u{1D52D}",phi:"\u03C6",phiv:"\u03D5",phmmat:"\u2133",phone:"\u260E",pi:"\u03C0",pitchfork:"\u22D4",piv:"\u03D6",planck:"\u210F",planckh:"\u210E",plankv:"\u210F",plus:"+",plusacir:"\u2A23",plusb:"\u229E",pluscir:"\u2A22",plusdo:"\u2214",plusdu:"\u2A25",pluse:"\u2A72",plusmn:"\xB1",plussim:"\u2A26",plustwo:"\u2A27",pm:"\xB1",pointint:"\u2A15",popf:"\u{1D561}",pound:"\xA3",pr:"\u227A",prE:"\u2AB3",prap:"\u2AB7",prcue:"\u227C",pre:"\u2AAF",prec:"\u227A",precapprox:"\u2AB7",preccurlyeq:"\u227C",preceq:"\u2AAF",precnapprox:"\u2AB9",precneqq:"\u2AB5",precnsim:"\u22E8",precsim:"\u227E",prime:"\u2032",primes:"\u2119",prnE:"\u2AB5",prnap:"\u2AB9",prnsim:"\u22E8",prod:"\u220F",profalar:"\u232E",profline:"\u2312",profsurf:"\u2313",prop:"\u221D",propto:"\u221D",prsim:"\u227E",prurel:"\u22B0",pscr:"\u{1D4C5}",psi:"\u03C8",puncsp:"\u2008",qfr:"\u{1D52E}",qint:"\u2A0C",qopf:"\u{1D562}",qprime:"\u2057",qscr:"\u{1D4C6}",quaternions:"\u210D",quatint:"\u2A16",quest:"?",questeq:"\u225F",quot:'"',rAarr:"\u21DB",rArr:"\u21D2",rAtail:"\u291C",rBarr:"\u290F",rHar:"\u2964",race:"\u223D\u0331",racute:"\u0155",radic:"\u221A",raemptyv:"\u29B3",rang:"\u27E9",rangd:"\u2992",range:"\u29A5",rangle:"\u27E9",raquo:"\xBB",rarr:"\u2192",rarrap:"\u2975",rarrb:"\u21E5",rarrbfs:"\u2920",rarrc:"\u2933",rarrfs:"\u291E",rarrhk:"\u21AA",rarrlp:"\u21AC",rarrpl:"\u2945",rarrsim:"\u2974",rarrtl:"\u21A3",rarrw:"\u219D",ratail:"\u291A",ratio:"\u2236",rationals:"\u211A",rbarr:"\u290D",rbbrk:"\u2773",rbrace:"}",rbrack:"]",rbrke:"\u298C",rbrksld:"\u298E",rbrkslu:"\u2990",rcaron:"\u0159",rcedil:"\u0157",rceil:"\u2309",rcub:"}",rcy:"\u0440",rdca:"\u2937",rdldhar:"\u2969",rdquo:"\u201D",rdquor:"\u201D",rdsh:"\u21B3",real:"\u211C",realine:"\u211B",realpart:"\u211C",reals:"\u211D",rect:"\u25AD",reg:"\xAE",rfisht:"\u297D",rfloor:"\u230B",rfr:"\u{1D52F}",rhard:"\u21C1",rharu:"\u21C0",rharul:"\u296C",rho:"\u03C1",rhov:"\u03F1",rightarrow:"\u2192",rightarrowtail:"\u21A3",rightharpoondown:"\u21C1",rightharpoonup:"\u21C0",rightleftarrows:"\u21C4",rightleftharpoons:"\u21CC",rightrightarrows:"\u21C9",rightsquigarrow:"\u219D",rightthreetimes:"\u22CC",ring:"\u02DA",risingdotseq:"\u2253",rlarr:"\u21C4",rlhar:"\u21CC",rlm:"\u200F",rmoust:"\u23B1",rmoustache:"\u23B1",rnmid:"\u2AEE",roang:"\u27ED",roarr:"\u21FE",robrk:"\u27E7",ropar:"\u2986",ropf:"\u{1D563}",roplus:"\u2A2E",rotimes:"\u2A35",rpar:")",rpargt:"\u2994",rppolint:"\u2A12",rrarr:"\u21C9",rsaquo:"\u203A",rscr:"\u{1D4C7}",rsh:"\u21B1",rsqb:"]",rsquo:"\u2019",rsquor:"\u2019",rthree:"\u22CC",rtimes:"\u22CA",rtri:"\u25B9",rtrie:"\u22B5",rtrif:"\u25B8",rtriltri:"\u29CE",ruluhar:"\u2968",rx:"\u211E",sacute:"\u015B",sbquo:"\u201A",sc:"\u227B",scE:"\u2AB4",scap:"\u2AB8",scaron:"\u0161",sccue:"\u227D",sce:"\u2AB0",scedil:"\u015F",scirc:"\u015D",scnE:"\u2AB6",scnap:"\u2ABA",scnsim:"\u22E9",scpolint:"\u2A13",scsim:"\u227F",scy:"\u0441",sdot:"\u22C5",sdotb:"\u22A1",sdote:"\u2A66",seArr:"\u21D8",searhk:"\u2925",searr:"\u2198",searrow:"\u2198",sect:"\xA7",semi:";",seswar:"\u2929",setminus:"\u2216",setmn:"\u2216",sext:"\u2736",sfr:"\u{1D530}",sfrown:"\u2322",sharp:"\u266F",shchcy:"\u0449",shcy:"\u0448",shortmid:"\u2223",shortparallel:"\u2225",shy:"\xAD",sigma:"\u03C3",sigmaf:"\u03C2",sigmav:"\u03C2",sim:"\u223C",simdot:"\u2A6A",sime:"\u2243",simeq:"\u2243",simg:"\u2A9E",simgE:"\u2AA0",siml:"\u2A9D",simlE:"\u2A9F",simne:"\u2246",simplus:"\u2A24",simrarr:"\u2972",slarr:"\u2190",smallsetminus:"\u2216",smashp:"\u2A33",smeparsl:"\u29E4",smid:"\u2223",smile:"\u2323",smt:"\u2AAA",smte:"\u2AAC",smtes:"\u2AAC\uFE00",softcy:"\u044C",sol:"/",solb:"\u29C4",solbar:"\u233F",sopf:"\u{1D564}",spades:"\u2660",spadesuit:"\u2660",spar:"\u2225",sqcap:"\u2293",sqcaps:"\u2293\uFE00",sqcup:"\u2294",sqcups:"\u2294\uFE00",sqsub:"\u228F",sqsube:"\u2291",sqsubset:"\u228F",sqsubseteq:"\u2291",sqsup:"\u2290",sqsupe:"\u2292",sqsupset:"\u2290",sqsupseteq:"\u2292",squ:"\u25A1",square:"\u25A1",squarf:"\u25AA",squf:"\u25AA",srarr:"\u2192",sscr:"\u{1D4C8}",ssetmn:"\u2216",ssmile:"\u2323",sstarf:"\u22C6",star:"\u2606",starf:"\u2605",straightepsilon:"\u03F5",straightphi:"\u03D5",strns:"\xAF",sub:"\u2282",subE:"\u2AC5",subdot:"\u2ABD",sube:"\u2286",subedot:"\u2AC3",submult:"\u2AC1",subnE:"\u2ACB",subne:"\u228A",subplus:"\u2ABF",subrarr:"\u2979",subset:"\u2282",subseteq:"\u2286",subseteqq:"\u2AC5",subsetneq:"\u228A",subsetneqq:"\u2ACB",subsim:"\u2AC7",subsub:"\u2AD5",subsup:"\u2AD3",succ:"\u227B",succapprox:"\u2AB8",succcurlyeq:"\u227D",succeq:"\u2AB0",succnapprox:"\u2ABA",succneqq:"\u2AB6",succnsim:"\u22E9",succsim:"\u227F",sum:"\u2211",sung:"\u266A",sup1:"\xB9",sup2:"\xB2",sup3:"\xB3",sup:"\u2283",supE:"\u2AC6",supdot:"\u2ABE",supdsub:"\u2AD8",supe:"\u2287",supedot:"\u2AC4",suphsol:"\u27C9",suphsub:"\u2AD7",suplarr:"\u297B",supmult:"\u2AC2",supnE:"\u2ACC",supne:"\u228B",supplus:"\u2AC0",supset:"\u2283",supseteq:"\u2287",supseteqq:"\u2AC6",supsetneq:"\u228B",supsetneqq:"\u2ACC",supsim:"\u2AC8",supsub:"\u2AD4",supsup:"\u2AD6",swArr:"\u21D9",swarhk:"\u2926",swarr:"\u2199",swarrow:"\u2199",swnwar:"\u292A",szlig:"\xDF",target:"\u2316",tau:"\u03C4",tbrk:"\u23B4",tcaron:"\u0165",tcedil:"\u0163",tcy:"\u0442",tdot:"\u20DB",telrec:"\u2315",tfr:"\u{1D531}",there4:"\u2234",therefore:"\u2234",theta:"\u03B8",thetasym:"\u03D1",thetav:"\u03D1",thickapprox:"\u2248",thicksim:"\u223C",thinsp:"\u2009",thkap:"\u2248",thksim:"\u223C",thorn:"\xFE",tilde:"\u02DC",times:"\xD7",timesb:"\u22A0",timesbar:"\u2A31",timesd:"\u2A30",tint:"\u222D",toea:"\u2928",top:"\u22A4",topbot:"\u2336",topcir:"\u2AF1",topf:"\u{1D565}",topfork:"\u2ADA",tosa:"\u2929",tprime:"\u2034",trade:"\u2122",triangle:"\u25B5",triangledown:"\u25BF",triangleleft:"\u25C3",trianglelefteq:"\u22B4",triangleq:"\u225C",triangleright:"\u25B9",trianglerighteq:"\u22B5",tridot:"\u25EC",trie:"\u225C",triminus:"\u2A3A",triplus:"\u2A39",trisb:"\u29CD",tritime:"\u2A3B",trpezium:"\u23E2",tscr:"\u{1D4C9}",tscy:"\u0446",tshcy:"\u045B",tstrok:"\u0167",twixt:"\u226C",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",uArr:"\u21D1",uHar:"\u2963",uacute:"\xFA",uarr:"\u2191",ubrcy:"\u045E",ubreve:"\u016D",ucirc:"\xFB",ucy:"\u0443",udarr:"\u21C5",udblac:"\u0171",udhar:"\u296E",ufisht:"\u297E",ufr:"\u{1D532}",ugrave:"\xF9",uharl:"\u21BF",uharr:"\u21BE",uhblk:"\u2580",ulcorn:"\u231C",ulcorner:"\u231C",ulcrop:"\u230F",ultri:"\u25F8",umacr:"\u016B",uml:"\xA8",uogon:"\u0173",uopf:"\u{1D566}",uparrow:"\u2191",updownarrow:"\u2195",upharpoonleft:"\u21BF",upharpoonright:"\u21BE",uplus:"\u228E",upsi:"\u03C5",upsih:"\u03D2",upsilon:"\u03C5",upuparrows:"\u21C8",urcorn:"\u231D",urcorner:"\u231D",urcrop:"\u230E",uring:"\u016F",urtri:"\u25F9",uscr:"\u{1D4CA}",utdot:"\u22F0",utilde:"\u0169",utri:"\u25B5",utrif:"\u25B4",uuarr:"\u21C8",uuml:"\xFC",uwangle:"\u29A7",vArr:"\u21D5",vBar:"\u2AE8",vBarv:"\u2AE9",vDash:"\u22A8",vangrt:"\u299C",varepsilon:"\u03F5",varkappa:"\u03F0",varnothing:"\u2205",varphi:"\u03D5",varpi:"\u03D6",varpropto:"\u221D",varr:"\u2195",varrho:"\u03F1",varsigma:"\u03C2",varsubsetneq:"\u228A\uFE00",varsubsetneqq:"\u2ACB\uFE00",varsupsetneq:"\u228B\uFE00",varsupsetneqq:"\u2ACC\uFE00",vartheta:"\u03D1",vartriangleleft:"\u22B2",vartriangleright:"\u22B3",vcy:"\u0432",vdash:"\u22A2",vee:"\u2228",veebar:"\u22BB",veeeq:"\u225A",vellip:"\u22EE",verbar:"|",vert:"|",vfr:"\u{1D533}",vltri:"\u22B2",vnsub:"\u2282\u20D2",vnsup:"\u2283\u20D2",vopf:"\u{1D567}",vprop:"\u221D",vrtri:"\u22B3",vscr:"\u{1D4CB}",vsubnE:"\u2ACB\uFE00",vsubne:"\u228A\uFE00",vsupnE:"\u2ACC\uFE00",vsupne:"\u228B\uFE00",vzigzag:"\u299A",wcirc:"\u0175",wedbar:"\u2A5F",wedge:"\u2227",wedgeq:"\u2259",weierp:"\u2118",wfr:"\u{1D534}",wopf:"\u{1D568}",wp:"\u2118",wr:"\u2240",wreath:"\u2240",wscr:"\u{1D4CC}",xcap:"\u22C2",xcirc:"\u25EF",xcup:"\u22C3",xdtri:"\u25BD",xfr:"\u{1D535}",xhArr:"\u27FA",xharr:"\u27F7",xi:"\u03BE",xlArr:"\u27F8",xlarr:"\u27F5",xmap:"\u27FC",xnis:"\u22FB",xodot:"\u2A00",xopf:"\u{1D569}",xoplus:"\u2A01",xotime:"\u2A02",xrArr:"\u27F9",xrarr:"\u27F6",xscr:"\u{1D4CD}",xsqcup:"\u2A06",xuplus:"\u2A04",xutri:"\u25B3",xvee:"\u22C1",xwedge:"\u22C0",yacute:"\xFD",yacy:"\u044F",ycirc:"\u0177",ycy:"\u044B",yen:"\xA5",yfr:"\u{1D536}",yicy:"\u0457",yopf:"\u{1D56A}",yscr:"\u{1D4CE}",yucy:"\u044E",yuml:"\xFF",zacute:"\u017A",zcaron:"\u017E",zcy:"\u0437",zdot:"\u017C",zeetrf:"\u2128",zeta:"\u03B6",zfr:"\u{1D537}",zhcy:"\u0436",zigrarr:"\u21DD",zopf:"\u{1D56B}",zscr:"\u{1D4CF}",zwj:"\u200D",zwnj:"\u200C"};var zy={}.hasOwnProperty;function ns(e){return zy.call(Gi,e)?Gi[e]:!1}function pe(e,t,n,r){let o=e.length,s=0,i;if(t<0?t=-t>o?0:o+t:t=t>o?o:t,n=n>0?n:0,r.length<1e4)i=Array.from(r),i.unshift(t,n),e.splice(...i);else for(n&&e.splice(t,n);s<r.length;)i=r.slice(s,s+1e4),i.unshift(t,0),e.splice(...i),s+=1e4,t+=1e4}function Se(e,t){return e.length>0?(pe(e,e.length,0,t),e):t}var Sp={}.hasOwnProperty;function Ep(e){let t={},n=-1;for(;++n<e.length;)$y(t,e[n]);return t}function $y(e,t){let n;for(n in t){let o=(Sp.call(e,n)?e[n]:void 0)||(e[n]={}),s=t[n],i;if(s)for(i in s){Sp.call(o,i)||(o[i]=[]);let a=s[i];Ly(o[i],Array.isArray(a)?a:a?[a]:[])}}}function Ly(e,t){let n=-1,r=[];for(;++n<t.length;)(t[n].add==="after"?e:r).push(t[n]);pe(e,0,0,r)}function Ap(e,t){let n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"\uFFFD":String.fromCodePoint(n)}function _r(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}var Te=Ft(/[A-Za-z]/),Ee=Ft(/[\dA-Za-z]/),kp=Ft(/[#-'*+\--9=?A-Z^-~]/);function Sr(e){return e!==null&&(e<32||e===127)}var Er=Ft(/\d/),vp=Ft(/[\dA-Fa-f]/),Rp=Ft(/[!-/:-@[-`{-~]/);function C(e){return e!==null&&e<-2}function ie(e){return e!==null&&(e<0||e===32)}function F(e){return e===-2||e===-1||e===32}var Dp=Ft(/\p{P}|\p{S}/u),Ip=Ft(/\s/);function Ft(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function M(e,t,n,r){let o=r?r-1:Number.POSITIVE_INFINITY,s=0;return i;function i(c){return F(c)?(e.enter(n),a(c)):t(c)}function a(c){return F(c)&&s++<o?(e.consume(c),a):(e.exit(n),t(c))}}var Cp={tokenize:Py};function Py(e){let t=e.attempt(this.parser.constructs.contentInitial,r,o),n;return t;function r(a){if(a===null){e.consume(a);return}return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),M(e,t,"linePrefix")}function o(a){return e.enter("paragraph"),s(a)}function s(a){let c=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=c),n=c,i(a)}function i(a){if(a===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(a);return}return C(a)?(e.consume(a),e.exit("chunkText"),s):(e.consume(a),i)}}var Op={tokenize:Fy},Tp={tokenize:My};function Fy(e){let t=this,n=[],r=0,o,s,i;return a;function a(S){if(r<n.length){let E=n[r];return t.containerState=E[1],e.attempt(E[0].continuation,c,u)(S)}return u(S)}function c(S){if(r++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,o&&A();let E=t.events.length,_=E,x;for(;_--;)if(t.events[_][0]==="exit"&&t.events[_][1].type==="chunkFlow"){x=t.events[_][1].end;break}m(r);let R=E;for(;R<t.events.length;)t.events[R][1].end={...x},R++;return pe(t.events,_+1,0,t.events.slice(E)),t.events.length=R,u(S)}return a(S)}function u(S){if(r===n.length){if(!o)return p(S);if(o.currentConstruct&&o.currentConstruct.concrete)return w(S);t.interrupt=!!(o.currentConstruct&&!o._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(Tp,f,l)(S)}function f(S){return o&&A(),m(r),p(S)}function l(S){return t.parser.lazy[t.now().line]=r!==n.length,i=t.now().offset,w(S)}function p(S){return t.containerState={},e.attempt(Tp,d,w)(S)}function d(S){return r++,n.push([t.currentConstruct,t.containerState]),p(S)}function w(S){if(S===null){o&&A(),m(0),e.consume(S);return}return o=o||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:o,contentType:"flow",previous:s}),h(S)}function h(S){if(S===null){y(e.exit("chunkFlow"),!0),m(0),e.consume(S);return}return C(S)?(e.consume(S),y(e.exit("chunkFlow")),r=0,t.interrupt=void 0,a):(e.consume(S),h)}function y(S,E){let _=t.sliceStream(S);if(E&&_.push(null),S.previous=s,s&&(s.next=S),s=S,o.defineSkip(S.start),o.write(_),t.parser.lazy[S.start.line]){let x=o.events.length;for(;x--;)if(o.events[x][1].start.offset<i&&(!o.events[x][1].end||o.events[x][1].end.offset>i))return;let R=t.events.length,v=R,I,P;for(;v--;)if(t.events[v][0]==="exit"&&t.events[v][1].type==="chunkFlow"){if(I){P=t.events[v][1].end;break}I=!0}for(m(r),x=R;x<t.events.length;)t.events[x][1].end={...P},x++;pe(t.events,v+1,0,t.events.slice(R)),t.events.length=x}}function m(S){let E=n.length;for(;E-- >S;){let _=n[E];t.containerState=_[1],_[0].exit.call(t,e)}n.length=S}function A(){o.write([null]),s=void 0,o=void 0,t.containerState._closeFlow=void 0}}function My(e,t,n){return M(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Ji(e){if(e===null||ie(e)||Ip(e))return 1;if(Dp(e))return 2}function On(e,t,n){let r=[],o=-1;for(;++o<e.length;){let s=e[o].resolveAll;s&&!r.includes(s)&&(t=s(t,n),r.push(s))}return t}var Ar={name:"attention",resolveAll:By,tokenize:qy};function By(e,t){let n=-1,r,o,s,i,a,c,u,f;for(;++n<e.length;)if(e[n][0]==="enter"&&e[n][1].type==="attentionSequence"&&e[n][1]._close){for(r=n;r--;)if(e[r][0]==="exit"&&e[r][1].type==="attentionSequence"&&e[r][1]._open&&t.sliceSerialize(e[r][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[r][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[r][1].end.offset-e[r][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;c=e[r][1].end.offset-e[r][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;let l={...e[r][1].end},p={...e[n][1].start};Np(l,-c),Np(p,c),i={type:c>1?"strongSequence":"emphasisSequence",start:l,end:{...e[r][1].end}},a={type:c>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:p},s={type:c>1?"strongText":"emphasisText",start:{...e[r][1].end},end:{...e[n][1].start}},o={type:c>1?"strong":"emphasis",start:{...i.start},end:{...a.end}},e[r][1].end={...i.start},e[n][1].start={...a.end},u=[],e[r][1].end.offset-e[r][1].start.offset&&(u=Se(u,[["enter",e[r][1],t],["exit",e[r][1],t]])),u=Se(u,[["enter",o,t],["enter",i,t],["exit",i,t],["enter",s,t]]),u=Se(u,On(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),u=Se(u,[["exit",s,t],["enter",a,t],["exit",a,t],["exit",o,t]]),e[n][1].end.offset-e[n][1].start.offset?(f=2,u=Se(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):f=0,pe(e,r-1,n-r+3,u),n=r+u.length-f-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function qy(e,t){let n=this.parser.constructs.attentionMarkers.null,r=this.previous,o=Ji(r),s;return i;function i(c){return s=c,e.enter("attentionSequence"),a(c)}function a(c){if(c===s)return e.consume(c),a;let u=e.exit("attentionSequence"),f=Ji(c),l=!f||f===2&&o||n.includes(c),p=!o||o===2&&f||n.includes(r);return u._open=!!(s===42?l:l&&(o||!p)),u._close=!!(s===42?p:p&&(f||!l)),t(c)}}function Np(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}var Wi={name:"autolink",tokenize:Zy};function Zy(e,t,n){let r=0;return o;function o(d){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(d),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),s}function s(d){return Te(d)?(e.consume(d),i):d===64?n(d):u(d)}function i(d){return d===43||d===45||d===46||Ee(d)?(r=1,a(d)):u(d)}function a(d){return d===58?(e.consume(d),r=0,c):(d===43||d===45||d===46||Ee(d))&&r++<32?(e.consume(d),a):(r=0,u(d))}function c(d){return d===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(d),e.exit("autolinkMarker"),e.exit("autolink"),t):d===null||d===32||d===60||Sr(d)?n(d):(e.consume(d),c)}function u(d){return d===64?(e.consume(d),f):kp(d)?(e.consume(d),u):n(d)}function f(d){return Ee(d)?l(d):n(d)}function l(d){return d===46?(e.consume(d),r=0,f):d===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(d),e.exit("autolinkMarker"),e.exit("autolink"),t):p(d)}function p(d){if((d===45||Ee(d))&&r++<63){let w=d===45?p:l;return e.consume(d),w}return n(d)}}var Mt={partial:!0,tokenize:Uy};function Uy(e,t,n){return r;function r(s){return F(s)?M(e,o,"linePrefix")(s):o(s)}function o(s){return s===null||C(s)?t(s):n(s)}}var rs={continuation:{tokenize:Vy},exit:Qy,name:"blockQuote",tokenize:jy};function jy(e,t,n){let r=this;return o;function o(i){if(i===62){let a=r.containerState;return a.open||(e.enter("blockQuote",{_container:!0}),a.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(i),e.exit("blockQuoteMarker"),s}return n(i)}function s(i){return F(i)?(e.enter("blockQuotePrefixWhitespace"),e.consume(i),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(i))}}function Vy(e,t,n){let r=this;return o;function o(i){return F(i)?M(e,s,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(i):s(i)}function s(i){return e.attempt(rs,t,n)(i)}}function Qy(e){e.exit("blockQuote")}var os={name:"characterEscape",tokenize:Gy};function Gy(e,t,n){return r;function r(s){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(s),e.exit("escapeMarker"),o}function o(s){return Rp(s)?(e.enter("characterEscapeValue"),e.consume(s),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(s)}}var ss={name:"characterReference",tokenize:Jy};function Jy(e,t,n){let r=this,o=0,s,i;return a;function a(l){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(l),e.exit("characterReferenceMarker"),c}function c(l){return l===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(l),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),s=31,i=Ee,f(l))}function u(l){return l===88||l===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(l),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),s=6,i=vp,f):(e.enter("characterReferenceValue"),s=7,i=Er,f(l))}function f(l){if(l===59&&o){let p=e.exit("characterReferenceValue");return i===Ee&&!ns(r.sliceSerialize(p))?n(l):(e.enter("characterReferenceMarker"),e.consume(l),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return i(l)&&o++<s?(e.consume(l),f):n(l)}}var zp={partial:!0,tokenize:Ky},is={concrete:!0,name:"codeFenced",tokenize:Wy};function Wy(e,t,n){let r=this,o={partial:!0,tokenize:_},s=0,i=0,a;return c;function c(x){return u(x)}function u(x){let R=r.events[r.events.length-1];return s=R&&R[1].type==="linePrefix"?R[2].sliceSerialize(R[1],!0).length:0,a=x,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),f(x)}function f(x){return x===a?(i++,e.consume(x),f):i<3?n(x):(e.exit("codeFencedFenceSequence"),F(x)?M(e,l,"whitespace")(x):l(x))}function l(x){return x===null||C(x)?(e.exit("codeFencedFence"),r.interrupt?t(x):e.check(zp,h,E)(x)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),p(x))}function p(x){return x===null||C(x)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),l(x)):F(x)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),M(e,d,"whitespace")(x)):x===96&&x===a?n(x):(e.consume(x),p)}function d(x){return x===null||C(x)?l(x):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),w(x))}function w(x){return x===null||C(x)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),l(x)):x===96&&x===a?n(x):(e.consume(x),w)}function h(x){return e.attempt(o,E,y)(x)}function y(x){return e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),m}function m(x){return s>0&&F(x)?M(e,A,"linePrefix",s+1)(x):A(x)}function A(x){return x===null||C(x)?e.check(zp,h,E)(x):(e.enter("codeFlowValue"),S(x))}function S(x){return x===null||C(x)?(e.exit("codeFlowValue"),A(x)):(e.consume(x),S)}function E(x){return e.exit("codeFenced"),t(x)}function _(x,R,v){let I=0;return P;function P(q){return x.enter("lineEnding"),x.consume(q),x.exit("lineEnding"),Q}function Q(q){return x.enter("codeFencedFence"),F(q)?M(x,O,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(q):O(q)}function O(q){return q===a?(x.enter("codeFencedFenceSequence"),z(q)):v(q)}function z(q){return q===a?(I++,x.consume(q),z):I>=i?(x.exit("codeFencedFenceSequence"),F(q)?M(x,Z,"whitespace")(q):Z(q)):v(q)}function Z(q){return q===null||C(q)?(x.exit("codeFencedFence"),R(q)):v(q)}}}function Ky(e,t,n){let r=this;return o;function o(i){return i===null?n(i):(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),s)}function s(i){return r.parser.lazy[r.now().line]?n(i):t(i)}}var kr={name:"codeIndented",tokenize:Yy},Hy={partial:!0,tokenize:Xy};function Yy(e,t,n){let r=this;return o;function o(u){return e.enter("codeIndented"),M(e,s,"linePrefix",5)(u)}function s(u){let f=r.events[r.events.length-1];return f&&f[1].type==="linePrefix"&&f[2].sliceSerialize(f[1],!0).length>=4?i(u):n(u)}function i(u){return u===null?c(u):C(u)?e.attempt(Hy,i,c)(u):(e.enter("codeFlowValue"),a(u))}function a(u){return u===null||C(u)?(e.exit("codeFlowValue"),i(u)):(e.consume(u),a)}function c(u){return e.exit("codeIndented"),t(u)}}function Xy(e,t,n){let r=this;return o;function o(i){return r.parser.lazy[r.now().line]?n(i):C(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),o):M(e,s,"linePrefix",5)(i)}function s(i){let a=r.events[r.events.length-1];return a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?t(i):C(i)?o(i):n(i)}}var Ki={name:"codeText",previous:tb,resolve:eb,tokenize:nb};function eb(e){let t=e.length-4,n=3,r,o;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r<t;)if(e[r][1].type==="codeTextData"){e[n][1].type="codeTextPadding",e[t][1].type="codeTextPadding",n+=2,t-=2;break}}for(r=n-1,t++;++r<=t;)o===void 0?r!==t&&e[r][1].type!=="lineEnding"&&(o=r):(r===t||e[r][1].type==="lineEnding")&&(e[o][1].type="codeTextData",r!==o+2&&(e[o][1].end=e[r-1][1].end,e.splice(o+2,r-o-2),t-=r-o-2,r=o+2),o=void 0);return e}function tb(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function nb(e,t,n){let r=this,o=0,s,i;return a;function a(p){return e.enter("codeText"),e.enter("codeTextSequence"),c(p)}function c(p){return p===96?(e.consume(p),o++,c):(e.exit("codeTextSequence"),u(p))}function u(p){return p===null?n(p):p===32?(e.enter("space"),e.consume(p),e.exit("space"),u):p===96?(i=e.enter("codeTextSequence"),s=0,l(p)):C(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),u):(e.enter("codeTextData"),f(p))}function f(p){return p===null||p===32||p===96||C(p)?(e.exit("codeTextData"),u(p)):(e.consume(p),f)}function l(p){return p===96?(e.consume(p),s++,l):s===o?(e.exit("codeTextSequence"),e.exit("codeText"),t(p)):(i.type="codeTextData",f(p))}}var as=class{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,n){let r=n??Number.POSITIVE_INFINITY;return r<this.left.length?this.left.slice(t,r):t>this.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){let o=n||0;this.setCursor(Math.trunc(t));let s=this.right.splice(this.right.length-o,Number.POSITIVE_INFINITY);return r&&vr(this.left,r),s.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),vr(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),vr(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){let n=this.left.splice(t,Number.POSITIVE_INFINITY);vr(this.right,n.reverse())}else{let n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);vr(this.left,n.reverse())}}};function vr(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function cs(e){let t={},n=-1,r,o,s,i,a,c,u,f=new as(e);for(;++n<f.length;){for(;n in t;)n=t[n];if(r=f.get(n),n&&r[1].type==="chunkFlow"&&f.get(n-1)[1].type==="listItemPrefix"&&(c=r[1]._tokenizer.events,s=0,s<c.length&&c[s][1].type==="lineEndingBlank"&&(s+=2),s<c.length&&c[s][1].type==="content"))for(;++s<c.length&&c[s][1].type!=="content";)c[s][1].type==="chunkText"&&(c[s][1]._isInFirstContentOfListItem=!0,s++);if(r[0]==="enter")r[1].contentType&&(Object.assign(t,rb(f,n)),n=t[n],u=!0);else if(r[1]._container){for(s=n,o=void 0;s--;)if(i=f.get(s),i[1].type==="lineEnding"||i[1].type==="lineEndingBlank")i[0]==="enter"&&(o&&(f.get(o)[1].type="lineEndingBlank"),i[1].type="lineEnding",o=s);else if(!(i[1].type==="linePrefix"||i[1].type==="listItemIndent"))break;o&&(r[1].end={...f.get(o)[1].start},a=f.slice(o,n),a.unshift(r),f.splice(o,n-o+1,a))}}return pe(e,0,Number.POSITIVE_INFINITY,f.slice(0)),!u}function rb(e,t){let n=e.get(t)[1],r=e.get(t)[2],o=t-1,s=[],i=n._tokenizer;i||(i=r.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(i._contentTypeTextTrailing=!0));let a=i.events,c=[],u={},f,l,p=-1,d=n,w=0,h=0,y=[h];for(;d;){for(;e.get(++o)[1]!==d;);s.push(o),d._tokenizer||(f=r.sliceStream(d),d.next||f.push(null),l&&i.defineSkip(d.start),d._isInFirstContentOfListItem&&(i._gfmTasklistFirstContentOfListItem=!0),i.write(f),d._isInFirstContentOfListItem&&(i._gfmTasklistFirstContentOfListItem=void 0)),l=d,d=d.next}for(d=n;++p<a.length;)a[p][0]==="exit"&&a[p-1][0]==="enter"&&a[p][1].type===a[p-1][1].type&&a[p][1].start.line!==a[p][1].end.line&&(h=p+1,y.push(h),d._tokenizer=void 0,d.previous=void 0,d=d.next);for(i.events=[],d?(d._tokenizer=void 0,d.previous=void 0):y.pop(),p=y.length;p--;){let m=a.slice(y[p],y[p+1]),A=s.pop();c.push([A,A+m.length-1]),e.splice(A,2,m)}for(c.reverse(),p=-1;++p<c.length;)u[w+c[p][0]]=w+c[p][1],w+=c[p][1]-c[p][0]-1;return u}var Hi={resolve:sb,tokenize:ib},ob={partial:!0,tokenize:ab};function sb(e){return cs(e),e}function ib(e,t){let n;return r;function r(a){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),o(a)}function o(a){return a===null?s(a):C(a)?e.check(ob,i,s)(a):(e.consume(a),o)}function s(a){return e.exit("chunkContent"),e.exit("content"),t(a)}function i(a){return e.consume(a),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,o}}function ab(e,t,n){let r=this;return o;function o(i){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),M(e,s,"linePrefix")}function s(i){if(i===null||C(i))return n(i);let a=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes("codeIndented")&&a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?t(i):e.interrupt(r.parser.constructs.flow,n,t)(i)}}function us(e,t,n,r,o,s,i,a,c){let u=c||Number.POSITIVE_INFINITY,f=0;return l;function l(m){return m===60?(e.enter(r),e.enter(o),e.enter(s),e.consume(m),e.exit(s),p):m===null||m===32||m===41||Sr(m)?n(m):(e.enter(r),e.enter(i),e.enter(a),e.enter("chunkString",{contentType:"string"}),h(m))}function p(m){return m===62?(e.enter(s),e.consume(m),e.exit(s),e.exit(o),e.exit(r),t):(e.enter(a),e.enter("chunkString",{contentType:"string"}),d(m))}function d(m){return m===62?(e.exit("chunkString"),e.exit(a),p(m)):m===null||m===60||C(m)?n(m):(e.consume(m),m===92?w:d)}function w(m){return m===60||m===62||m===92?(e.consume(m),d):d(m)}function h(m){return!f&&(m===null||m===41||ie(m))?(e.exit("chunkString"),e.exit(a),e.exit(i),e.exit(r),t(m)):f<u&&m===40?(e.consume(m),f++,h):m===41?(e.consume(m),f--,h):m===null||m===32||m===40||Sr(m)?n(m):(e.consume(m),m===92?y:h)}function y(m){return m===40||m===41||m===92?(e.consume(m),h):h(m)}}function ls(e,t,n,r,o,s){let i=this,a=0,c;return u;function u(d){return e.enter(r),e.enter(o),e.consume(d),e.exit(o),e.enter(s),f}function f(d){return a>999||d===null||d===91||d===93&&!c||d===94&&!a&&"_hiddenFootnoteSupport"in i.parser.constructs?n(d):d===93?(e.exit(s),e.enter(o),e.consume(d),e.exit(o),e.exit(r),t):C(d)?(e.enter("lineEnding"),e.consume(d),e.exit("lineEnding"),f):(e.enter("chunkString",{contentType:"string"}),l(d))}function l(d){return d===null||d===91||d===93||C(d)||a++>999?(e.exit("chunkString"),f(d)):(e.consume(d),c||(c=!F(d)),d===92?p:l)}function p(d){return d===91||d===92||d===93?(e.consume(d),a++,l):l(d)}}function fs(e,t,n,r,o,s){let i;return a;function a(p){return p===34||p===39||p===40?(e.enter(r),e.enter(o),e.consume(p),e.exit(o),i=p===40?41:p,c):n(p)}function c(p){return p===i?(e.enter(o),e.consume(p),e.exit(o),e.exit(r),t):(e.enter(s),u(p))}function u(p){return p===i?(e.exit(s),c(i)):p===null?n(p):C(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),M(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),f(p))}function f(p){return p===i||p===null||C(p)?(e.exit("chunkString"),u(p)):(e.consume(p),p===92?l:f)}function l(p){return p===i||p===92?(e.consume(p),f):f(p)}}function Ht(e,t){let n;return r;function r(o){return C(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),n=!0,r):F(o)?M(e,r,n?"linePrefix":"lineSuffix")(o):t(o)}}var Yi={name:"definition",tokenize:ub},cb={partial:!0,tokenize:lb};function ub(e,t,n){let r=this,o;return s;function s(d){return e.enter("definition"),i(d)}function i(d){return ls.call(r,e,a,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(d)}function a(d){return o=_r(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),d===58?(e.enter("definitionMarker"),e.consume(d),e.exit("definitionMarker"),c):n(d)}function c(d){return ie(d)?Ht(e,u)(d):u(d)}function u(d){return us(e,f,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(d)}function f(d){return e.attempt(cb,l,l)(d)}function l(d){return F(d)?M(e,p,"whitespace")(d):p(d)}function p(d){return d===null||C(d)?(e.exit("definition"),r.parser.defined.push(o),t(d)):n(d)}}function lb(e,t,n){return r;function r(a){return ie(a)?Ht(e,o)(a):n(a)}function o(a){return fs(e,s,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(a)}function s(a){return F(a)?M(e,i,"whitespace")(a):i(a)}function i(a){return a===null||C(a)?t(a):n(a)}}var Xi={name:"hardBreakEscape",tokenize:fb};function fb(e,t,n){return r;function r(s){return e.enter("hardBreakEscape"),e.consume(s),o}function o(s){return C(s)?(e.exit("hardBreakEscape"),t(s)):n(s)}}var ea={name:"headingAtx",resolve:db,tokenize:pb};function db(e,t){let n=e.length-2,r=3,o,s;return e[r][1].type==="whitespace"&&(r+=2),n-2>r&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&e[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(o={type:"atxHeadingText",start:e[r][1].start,end:e[n][1].end},s={type:"chunkText",start:e[r][1].start,end:e[n][1].end,contentType:"text"},pe(e,r,n-r+1,[["enter",o,t],["enter",s,t],["exit",s,t],["exit",o,t]])),e}function pb(e,t,n){let r=0;return o;function o(f){return e.enter("atxHeading"),s(f)}function s(f){return e.enter("atxHeadingSequence"),i(f)}function i(f){return f===35&&r++<6?(e.consume(f),i):f===null||ie(f)?(e.exit("atxHeadingSequence"),a(f)):n(f)}function a(f){return f===35?(e.enter("atxHeadingSequence"),c(f)):f===null||C(f)?(e.exit("atxHeading"),t(f)):F(f)?M(e,a,"whitespace")(f):(e.enter("atxHeadingText"),u(f))}function c(f){return f===35?(e.consume(f),c):(e.exit("atxHeadingSequence"),a(f))}function u(f){return f===null||f===35||ie(f)?(e.exit("atxHeadingText"),a(f)):(e.consume(f),u)}}var $p=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],ta=["pre","script","style","textarea"];var na={concrete:!0,name:"htmlFlow",resolveTo:gb,tokenize:yb},mb={partial:!0,tokenize:wb},hb={partial:!0,tokenize:bb};function gb(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function yb(e,t,n){let r=this,o,s,i,a,c;return u;function u(b){return f(b)}function f(b){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(b),l}function l(b){return b===33?(e.consume(b),p):b===47?(e.consume(b),s=!0,h):b===63?(e.consume(b),o=3,r.interrupt?t:g):Te(b)?(e.consume(b),i=String.fromCharCode(b),y):n(b)}function p(b){return b===45?(e.consume(b),o=2,d):b===91?(e.consume(b),o=5,a=0,w):Te(b)?(e.consume(b),o=4,r.interrupt?t:g):n(b)}function d(b){return b===45?(e.consume(b),r.interrupt?t:g):n(b)}function w(b){let Be="CDATA[";return b===Be.charCodeAt(a++)?(e.consume(b),a===Be.length?r.interrupt?t:O:w):n(b)}function h(b){return Te(b)?(e.consume(b),i=String.fromCharCode(b),y):n(b)}function y(b){if(b===null||b===47||b===62||ie(b)){let Be=b===47,Cr=i.toLowerCase();return!Be&&!s&&ta.includes(Cr)?(o=1,r.interrupt?t(b):O(b)):$p.includes(i.toLowerCase())?(o=6,Be?(e.consume(b),m):r.interrupt?t(b):O(b)):(o=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(b):s?A(b):S(b))}return b===45||Ee(b)?(e.consume(b),i+=String.fromCharCode(b),y):n(b)}function m(b){return b===62?(e.consume(b),r.interrupt?t:O):n(b)}function A(b){return F(b)?(e.consume(b),A):P(b)}function S(b){return b===47?(e.consume(b),P):b===58||b===95||Te(b)?(e.consume(b),E):F(b)?(e.consume(b),S):P(b)}function E(b){return b===45||b===46||b===58||b===95||Ee(b)?(e.consume(b),E):_(b)}function _(b){return b===61?(e.consume(b),x):F(b)?(e.consume(b),_):S(b)}function x(b){return b===null||b===60||b===61||b===62||b===96?n(b):b===34||b===39?(e.consume(b),c=b,R):F(b)?(e.consume(b),x):v(b)}function R(b){return b===c?(e.consume(b),c=null,I):b===null||C(b)?n(b):(e.consume(b),R)}function v(b){return b===null||b===34||b===39||b===47||b===60||b===61||b===62||b===96||ie(b)?_(b):(e.consume(b),v)}function I(b){return b===47||b===62||F(b)?S(b):n(b)}function P(b){return b===62?(e.consume(b),Q):n(b)}function Q(b){return b===null||C(b)?O(b):F(b)?(e.consume(b),Q):n(b)}function O(b){return b===45&&o===2?(e.consume(b),ne):b===60&&o===1?(e.consume(b),ue):b===62&&o===4?(e.consume(b),Ke):b===63&&o===3?(e.consume(b),g):b===93&&o===5?(e.consume(b),bt):C(b)&&(o===6||o===7)?(e.exit("htmlFlowData"),e.check(mb,qt,z)(b)):b===null||C(b)?(e.exit("htmlFlowData"),z(b)):(e.consume(b),O)}function z(b){return e.check(hb,Z,qt)(b)}function Z(b){return e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),q}function q(b){return b===null||C(b)?z(b):(e.enter("htmlFlowData"),O(b))}function ne(b){return b===45?(e.consume(b),g):O(b)}function ue(b){return b===47?(e.consume(b),i="",ut):O(b)}function ut(b){if(b===62){let Be=i.toLowerCase();return ta.includes(Be)?(e.consume(b),Ke):O(b)}return Te(b)&&i.length<8?(e.consume(b),i+=String.fromCharCode(b),ut):O(b)}function bt(b){return b===93?(e.consume(b),g):O(b)}function g(b){return b===62?(e.consume(b),Ke):b===45&&o===2?(e.consume(b),g):O(b)}function Ke(b){return b===null||C(b)?(e.exit("htmlFlowData"),qt(b)):(e.consume(b),Ke)}function qt(b){return e.exit("htmlFlow"),t(b)}}function bb(e,t,n){let r=this;return o;function o(i){return C(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),s):n(i)}function s(i){return r.parser.lazy[r.now().line]?n(i):t(i)}}function wb(e,t,n){return r;function r(o){return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),e.attempt(Mt,t,n)}}var ra={name:"htmlText",tokenize:xb};function xb(e,t,n){let r=this,o,s,i;return a;function a(g){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(g),c}function c(g){return g===33?(e.consume(g),u):g===47?(e.consume(g),_):g===63?(e.consume(g),S):Te(g)?(e.consume(g),v):n(g)}function u(g){return g===45?(e.consume(g),f):g===91?(e.consume(g),s=0,w):Te(g)?(e.consume(g),A):n(g)}function f(g){return g===45?(e.consume(g),d):n(g)}function l(g){return g===null?n(g):g===45?(e.consume(g),p):C(g)?(i=l,ue(g)):(e.consume(g),l)}function p(g){return g===45?(e.consume(g),d):l(g)}function d(g){return g===62?ne(g):g===45?p(g):l(g)}function w(g){let Ke="CDATA[";return g===Ke.charCodeAt(s++)?(e.consume(g),s===Ke.length?h:w):n(g)}function h(g){return g===null?n(g):g===93?(e.consume(g),y):C(g)?(i=h,ue(g)):(e.consume(g),h)}function y(g){return g===93?(e.consume(g),m):h(g)}function m(g){return g===62?ne(g):g===93?(e.consume(g),m):h(g)}function A(g){return g===null||g===62?ne(g):C(g)?(i=A,ue(g)):(e.consume(g),A)}function S(g){return g===null?n(g):g===63?(e.consume(g),E):C(g)?(i=S,ue(g)):(e.consume(g),S)}function E(g){return g===62?ne(g):S(g)}function _(g){return Te(g)?(e.consume(g),x):n(g)}function x(g){return g===45||Ee(g)?(e.consume(g),x):R(g)}function R(g){return C(g)?(i=R,ue(g)):F(g)?(e.consume(g),R):ne(g)}function v(g){return g===45||Ee(g)?(e.consume(g),v):g===47||g===62||ie(g)?I(g):n(g)}function I(g){return g===47?(e.consume(g),ne):g===58||g===95||Te(g)?(e.consume(g),P):C(g)?(i=I,ue(g)):F(g)?(e.consume(g),I):ne(g)}function P(g){return g===45||g===46||g===58||g===95||Ee(g)?(e.consume(g),P):Q(g)}function Q(g){return g===61?(e.consume(g),O):C(g)?(i=Q,ue(g)):F(g)?(e.consume(g),Q):I(g)}function O(g){return g===null||g===60||g===61||g===62||g===96?n(g):g===34||g===39?(e.consume(g),o=g,z):C(g)?(i=O,ue(g)):F(g)?(e.consume(g),O):(e.consume(g),Z)}function z(g){return g===o?(e.consume(g),o=void 0,q):g===null?n(g):C(g)?(i=z,ue(g)):(e.consume(g),z)}function Z(g){return g===null||g===34||g===39||g===60||g===61||g===96?n(g):g===47||g===62||ie(g)?I(g):(e.consume(g),Z)}function q(g){return g===47||g===62||ie(g)?I(g):n(g)}function ne(g){return g===62?(e.consume(g),e.exit("htmlTextData"),e.exit("htmlText"),t):n(g)}function ue(g){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),ut}function ut(g){return F(g)?M(e,bt,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(g):bt(g)}function bt(g){return e.enter("htmlTextData"),i(g)}}var Yt={name:"labelEnd",resolveAll:Ab,resolveTo:kb,tokenize:vb},_b={tokenize:Rb},Sb={tokenize:Db},Eb={tokenize:Ib};function Ab(e){let t=-1,n=[];for(;++t<e.length;){let r=e[t][1];if(n.push(e[t]),r.type==="labelImage"||r.type==="labelLink"||r.type==="labelEnd"){let o=r.type==="labelImage"?4:2;r.type="data",t+=o}}return e.length!==n.length&&pe(e,0,e.length,n),e}function kb(e,t){let n=e.length,r=0,o,s,i,a;for(;n--;)if(o=e[n][1],s){if(o.type==="link"||o.type==="labelLink"&&o._inactive)break;e[n][0]==="enter"&&o.type==="labelLink"&&(o._inactive=!0)}else if(i){if(e[n][0]==="enter"&&(o.type==="labelImage"||o.type==="labelLink")&&!o._balanced&&(s=n,o.type!=="labelLink")){r=2;break}}else o.type==="labelEnd"&&(i=n);let c={type:e[s][1].type==="labelLink"?"link":"image",start:{...e[s][1].start},end:{...e[e.length-1][1].end}},u={type:"label",start:{...e[s][1].start},end:{...e[i][1].end}},f={type:"labelText",start:{...e[s+r+2][1].end},end:{...e[i-2][1].start}};return a=[["enter",c,t],["enter",u,t]],a=Se(a,e.slice(s+1,s+r+3)),a=Se(a,[["enter",f,t]]),a=Se(a,On(t.parser.constructs.insideSpan.null,e.slice(s+r+4,i-3),t)),a=Se(a,[["exit",f,t],e[i-2],e[i-1],["exit",u,t]]),a=Se(a,e.slice(i+1)),a=Se(a,[["exit",c,t]]),pe(e,s,e.length,a),e}function vb(e,t,n){let r=this,o=r.events.length,s,i;for(;o--;)if((r.events[o][1].type==="labelImage"||r.events[o][1].type==="labelLink")&&!r.events[o][1]._balanced){s=r.events[o][1];break}return a;function a(p){return s?s._inactive?l(p):(i=r.parser.defined.includes(_r(r.sliceSerialize({start:s.end,end:r.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(p),e.exit("labelMarker"),e.exit("labelEnd"),c):n(p)}function c(p){return p===40?e.attempt(_b,f,i?f:l)(p):p===91?e.attempt(Sb,f,i?u:l)(p):i?f(p):l(p)}function u(p){return e.attempt(Eb,f,l)(p)}function f(p){return t(p)}function l(p){return s._balanced=!0,n(p)}}function Rb(e,t,n){return r;function r(l){return e.enter("resource"),e.enter("resourceMarker"),e.consume(l),e.exit("resourceMarker"),o}function o(l){return ie(l)?Ht(e,s)(l):s(l)}function s(l){return l===41?f(l):us(e,i,a,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(l)}function i(l){return ie(l)?Ht(e,c)(l):f(l)}function a(l){return n(l)}function c(l){return l===34||l===39||l===40?fs(e,u,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(l):f(l)}function u(l){return ie(l)?Ht(e,f)(l):f(l)}function f(l){return l===41?(e.enter("resourceMarker"),e.consume(l),e.exit("resourceMarker"),e.exit("resource"),t):n(l)}}function Db(e,t,n){let r=this;return o;function o(a){return ls.call(r,e,s,i,"reference","referenceMarker","referenceString")(a)}function s(a){return r.parser.defined.includes(_r(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(a):n(a)}function i(a){return n(a)}}function Ib(e,t,n){return r;function r(s){return e.enter("reference"),e.enter("referenceMarker"),e.consume(s),e.exit("referenceMarker"),o}function o(s){return s===93?(e.enter("referenceMarker"),e.consume(s),e.exit("referenceMarker"),e.exit("reference"),t):n(s)}}var oa={name:"labelStartImage",resolveAll:Yt.resolveAll,tokenize:Cb};function Cb(e,t,n){let r=this;return o;function o(a){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(a),e.exit("labelImageMarker"),s}function s(a){return a===91?(e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelImage"),i):n(a)}function i(a){return a===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(a):t(a)}}var sa={name:"labelStartLink",resolveAll:Yt.resolveAll,tokenize:Tb};function Tb(e,t,n){let r=this;return o;function o(i){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(i),e.exit("labelMarker"),e.exit("labelLink"),s}function s(i){return i===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(i):t(i)}}var Rr={name:"lineEnding",tokenize:Ob};function Ob(e,t){return n;function n(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),M(e,t,"linePrefix")}}var Xt={name:"thematicBreak",tokenize:Nb};function Nb(e,t,n){let r=0,o;return s;function s(u){return e.enter("thematicBreak"),i(u)}function i(u){return o=u,a(u)}function a(u){return u===o?(e.enter("thematicBreakSequence"),c(u)):r>=3&&(u===null||C(u))?(e.exit("thematicBreak"),t(u)):n(u)}function c(u){return u===o?(e.consume(u),r++,c):(e.exit("thematicBreakSequence"),F(u)?M(e,a,"whitespace")(u):a(u))}}var ge={continuation:{tokenize:Pb},exit:Mb,name:"list",tokenize:Lb},zb={partial:!0,tokenize:Bb},$b={partial:!0,tokenize:Fb};function Lb(e,t,n){let r=this,o=r.events[r.events.length-1],s=o&&o[1].type==="linePrefix"?o[2].sliceSerialize(o[1],!0).length:0,i=0;return a;function a(d){let w=r.containerState.type||(d===42||d===43||d===45?"listUnordered":"listOrdered");if(w==="listUnordered"?!r.containerState.marker||d===r.containerState.marker:Er(d)){if(r.containerState.type||(r.containerState.type=w,e.enter(w,{_container:!0})),w==="listUnordered")return e.enter("listItemPrefix"),d===42||d===45?e.check(Xt,n,u)(d):u(d);if(!r.interrupt||d===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(d)}return n(d)}function c(d){return Er(d)&&++i<10?(e.consume(d),c):(!r.interrupt||i<2)&&(r.containerState.marker?d===r.containerState.marker:d===41||d===46)?(e.exit("listItemValue"),u(d)):n(d)}function u(d){return e.enter("listItemMarker"),e.consume(d),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||d,e.check(Mt,r.interrupt?n:f,e.attempt(zb,p,l))}function f(d){return r.containerState.initialBlankLine=!0,s++,p(d)}function l(d){return F(d)?(e.enter("listItemPrefixWhitespace"),e.consume(d),e.exit("listItemPrefixWhitespace"),p):n(d)}function p(d){return r.containerState.size=s+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(d)}}function Pb(e,t,n){let r=this;return r.containerState._closeFlow=void 0,e.check(Mt,o,s);function o(a){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,M(e,t,"listItemIndent",r.containerState.size+1)(a)}function s(a){return r.containerState.furtherBlankLines||!F(a)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,i(a)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt($b,t,i)(a))}function i(a){return r.containerState._closeFlow=!0,r.interrupt=void 0,M(e,e.attempt(ge,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a)}}function Fb(e,t,n){let r=this;return M(e,o,"listItemIndent",r.containerState.size+1);function o(s){let i=r.events[r.events.length-1];return i&&i[1].type==="listItemIndent"&&i[2].sliceSerialize(i[1],!0).length===r.containerState.size?t(s):n(s)}}function Mb(e){e.exit(this.containerState.type)}function Bb(e,t,n){let r=this;return M(e,o,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function o(s){let i=r.events[r.events.length-1];return!F(s)&&i&&i[1].type==="listItemPrefixWhitespace"?t(s):n(s)}}var ds={name:"setextUnderline",resolveTo:qb,tokenize:Zb};function qb(e,t){let n=e.length,r,o,s;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){r=n;break}e[n][1].type==="paragraph"&&(o=n)}else e[n][1].type==="content"&&e.splice(n,1),!s&&e[n][1].type==="definition"&&(s=n);let i={type:"setextHeading",start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[o][1].type="setextHeadingText",s?(e.splice(o,0,["enter",i,t]),e.splice(s+1,0,["exit",e[r][1],t]),e[r][1].end={...e[s][1].end}):e[r][1]=i,e.push(["exit",i,t]),e}function Zb(e,t,n){let r=this,o;return s;function s(u){let f=r.events.length,l;for(;f--;)if(r.events[f][1].type!=="lineEnding"&&r.events[f][1].type!=="linePrefix"&&r.events[f][1].type!=="content"){l=r.events[f][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||l)?(e.enter("setextHeadingLine"),o=u,i(u)):n(u)}function i(u){return e.enter("setextHeadingLineSequence"),a(u)}function a(u){return u===o?(e.consume(u),a):(e.exit("setextHeadingLineSequence"),F(u)?M(e,c,"lineSuffix")(u):c(u))}function c(u){return u===null||C(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}var Lp={tokenize:Ub};function Ub(e){let t=this,n=e.attempt(Mt,r,e.attempt(this.parser.constructs.flowInitial,o,M(e,e.attempt(this.parser.constructs.flow,o,e.attempt(Hi,o)),"linePrefix")));return n;function r(s){if(s===null){e.consume(s);return}return e.enter("lineEndingBlank"),e.consume(s),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function o(s){if(s===null){e.consume(s);return}return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),t.currentConstruct=void 0,n}}var Pp={resolveAll:qp()},Fp=Bp("string"),Mp=Bp("text");function Bp(e){return{resolveAll:qp(e==="text"?jb:void 0),tokenize:t};function t(n){let r=this,o=this.parser.constructs[e],s=n.attempt(o,i,a);return i;function i(f){return u(f)?s(f):a(f)}function a(f){if(f===null){n.consume(f);return}return n.enter("data"),n.consume(f),c}function c(f){return u(f)?(n.exit("data"),s(f)):(n.consume(f),c)}function u(f){if(f===null)return!0;let l=o[f],p=-1;if(l)for(;++p<l.length;){let d=l[p];if(!d.previous||d.previous.call(r,r.previous))return!0}return!1}}}function qp(e){return t;function t(n,r){let o=-1,s;for(;++o<=n.length;)s===void 0?n[o]&&n[o][1].type==="data"&&(s=o,o++):(!n[o]||n[o][1].type!=="data")&&(o!==s+2&&(n[s][1].end=n[o-1][1].end,n.splice(s+2,o-s-2),o=s+2),s=void 0);return e?e(n,r):n}}function jb(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type==="lineEnding")&&e[n-1][1].type==="data"){let r=e[n-1][1],o=t.sliceStream(r),s=o.length,i=-1,a=0,c;for(;s--;){let u=o[s];if(typeof u=="string"){for(i=u.length;u.charCodeAt(i-1)===32;)a++,i--;if(i)break;i=-1}else if(u===-2)c=!0,a++;else if(u!==-1){s++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(a=0),a){let u={type:n===e.length||c||a<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:s?i:r.start._bufferIndex+i,_index:r.start._index+s,line:r.end.line,column:r.end.column-a,offset:r.end.offset-a},end:{...r.end}};r.end={...u.start},r.start.offset===r.end.offset?Object.assign(r,u):(e.splice(n,0,["enter",u,t],["exit",u,t]),n+=2)}n++}return e}var ia={};wa(ia,{attentionMarkers:()=>Yb,contentInitial:()=>Qb,disable:()=>Xb,document:()=>Vb,flow:()=>Jb,flowInitial:()=>Gb,insideSpan:()=>Hb,string:()=>Wb,text:()=>Kb});var Vb={42:ge,43:ge,45:ge,48:ge,49:ge,50:ge,51:ge,52:ge,53:ge,54:ge,55:ge,56:ge,57:ge,62:rs},Qb={91:Yi},Gb={[-2]:kr,[-1]:kr,32:kr},Jb={35:ea,42:Xt,45:[ds,Xt],60:na,61:ds,95:Xt,96:is,126:is},Wb={38:ss,92:os},Kb={[-5]:Rr,[-4]:Rr,[-3]:Rr,33:oa,38:ss,42:Ar,60:[Wi,ra],91:sa,92:[Xi,os],93:Yt,95:Ar,96:Ki},Hb={null:[Ar,Pp]},Yb={null:[42,95]},Xb={null:[]};function Zp(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0},o={},s=[],i=[],a=[],c=!0,u={attempt:I(R),check:I(v),consume:E,enter:_,exit:x,interrupt:I(v,{interrupt:!0})},f={code:null,containerState:{},defineSkip:m,events:[],now:y,parser:e,previous:null,sliceSerialize:w,sliceStream:h,write:d},l=t.tokenize.call(f,u),p;return t.resolveAll&&s.push(t),f;function d(z){return i=Se(i,z),A(),i[i.length-1]!==null?[]:(P(t,0),f.events=On(s,f.events,f),f.events)}function w(z,Z){return tw(h(z),Z)}function h(z){return ew(i,z)}function y(){let{_bufferIndex:z,_index:Z,line:q,column:ne,offset:ue}=r;return{_bufferIndex:z,_index:Z,line:q,column:ne,offset:ue}}function m(z){o[z.line]=z.column,O()}function A(){let z;for(;r._index<i.length;){let Z=i[r._index];if(typeof Z=="string")for(z=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===z&&r._bufferIndex<Z.length;)S(Z.charCodeAt(r._bufferIndex));else S(Z)}}function S(z){c=void 0,p=z,l=l(z)}function E(z){C(z)?(r.line++,r.column=1,r.offset+=z===-3?2:1,O()):z!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===i[r._index].length&&(r._bufferIndex=-1,r._index++)),f.previous=z,c=!0}function _(z,Z){let q=Z||{};return q.type=z,q.start=y(),f.events.push(["enter",q,f]),a.push(q),q}function x(z){let Z=a.pop();return Z.end=y(),f.events.push(["exit",Z,f]),Z}function R(z,Z){P(z,Z.from)}function v(z,Z){Z.restore()}function I(z,Z){return q;function q(ne,ue,ut){let bt,g,Ke,qt;return Array.isArray(ne)?Be(ne):"tokenize"in ne?Be([ne]):b(ne);function b(ye){return hs;function hs(Zt){let Tr=Zt!==null&&ye[Zt],Or=Zt!==null&&ye.null,pm=[...Array.isArray(Tr)?Tr:Tr?[Tr]:[],...Array.isArray(Or)?Or:Or?[Or]:[]];return Be(pm)(Zt)}}function Be(ye){return bt=ye,g=0,ye.length===0?ut:Cr(ye[g])}function Cr(ye){return hs;function hs(Zt){return qt=Q(),Ke=ye,ye.partial||(f.currentConstruct=ye),ye.name&&f.parser.constructs.disable.null.includes(ye.name)?ba(Zt):ye.tokenize.call(Z?Object.assign(Object.create(f),Z):f,u,dm,ba)(Zt)}}function dm(ye){return c=!0,z(Ke,qt),ue}function ba(ye){return c=!0,qt.restore(),++g<bt.length?Cr(bt[g]):ut}}}function P(z,Z){z.resolveAll&&!s.includes(z)&&s.push(z),z.resolve&&pe(f.events,Z,f.events.length-Z,z.resolve(f.events.slice(Z),f)),z.resolveTo&&(f.events=z.resolveTo(f.events,f))}function Q(){let z=y(),Z=f.previous,q=f.currentConstruct,ne=f.events.length,ue=Array.from(a);return{from:ne,restore:ut};function ut(){r=z,f.previous=Z,f.currentConstruct=q,f.events.length=ne,a=ue,O()}}function O(){r.line in o&&r.column<2&&(r.column=o[r.line],r.offset+=o[r.line]-1)}}function ew(e,t){let n=t.start._index,r=t.start._bufferIndex,o=t.end._index,s=t.end._bufferIndex,i;if(n===o)i=[e[n].slice(r,s)];else{if(i=e.slice(n,o),r>-1){let a=i[0];typeof a=="string"?i[0]=a.slice(r):i.shift()}s>0&&i.push(e[o].slice(0,s))}return i}function tw(e,t){let n=-1,r=[],o;for(;++n<e.length;){let s=e[n],i;if(typeof s=="string")i=s;else switch(s){case-5:{i="\r";break}case-4:{i=`+`;break}case-3:{i=`\r+`;break}case-2:{i=t?" ":" ";break}case-1:{if(!t&&o)continue;i=" ";break}default:i=String.fromCharCode(s)}o=s===-2,r.push(i)}return r.join("")}function aa(e){let r={constructs:Ep([ia,...(e||{}).extensions||[]]),content:o(Cp),defined:[],document:o(Op),flow:o(Lp),lazy:{},string:o(Fp),text:o(Mp)};return r;function o(s){return i;function i(a){return Zp(r,s,a)}}}function ca(e){for(;!cs(e););return e}var Up=/[\0\t\n\r]/g;function ua(){let e=1,t="",n=!0,r;return o;function o(s,i,a){let c=[],u,f,l,p,d;for(s=t+(typeof s=="string"?s.toString():new TextDecoder(i||void 0).decode(s)),l=0,t="",n&&(s.charCodeAt(0)===65279&&l++,n=void 0);l<s.length;){if(Up.lastIndex=l,u=Up.exec(s),p=u&&u.index!==void 0?u.index:s.length,d=s.charCodeAt(p),!u){t=s.slice(l);break}if(d===10&&l===p&&r)c.push(-3),r=void 0;else switch(r&&(c.push(-5),r=void 0),l<p&&(c.push(s.slice(l,p)),e+=p-l),d){case 0:{c.push(65533),e++;break}case 9:{for(f=Math.ceil(e/4)*4,c.push(-2);e++<f;)c.push(-1);break}case 10:{c.push(-4),e=1;break}default:r=!0,e=1}l=p+1}return a&&(r&&c.push(-5),t&&c.push(t),c.push(null)),c}}var nw=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function jp(e){return e.replace(nw,rw)}function rw(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){let o=n.charCodeAt(1),s=o===120||o===88;return Ap(n.slice(s?2:1),s?16:10)}return ns(n)||e}var Vp=({markdown:e,references:t,assetUrls:n})=>{let r=e.length,o=e;for(let s of[...t].sort((i,a)=>a.start-i.start)){if(s.start<0||s.end<=s.start||s.end>e.length||s.end>r)throw new Error("Markdown asset reference range is invalid");r=s.start;let i=n[s.assetId];if(i===void 0)continue;let a=Wo(i,s.suffix);o=`${o.slice(0,s.start)}${a}${o.slice(s.end)}`}return o};var ow=e=>{let t=ca(aa().document().write(ua()(e,void 0,!0))),n=[];for(let[r,o]of t){if(r!=="enter"||o.type!=="resourceDestinationString"&&o.type!=="definitionDestinationString")continue;let s=e.slice(o.start.offset,o.end.offset);n.push({start:o.start.offset,end:o.end.offset,url:jp(s)})}return n},Qp=({markdown:e,sourcePath:t,assetIdsByPath:n})=>{let r=Yd({assetIdsByPath:n,sourcePath:t});return ow(e).flatMap(({start:o,end:s,url:i})=>{let a=r(i);return a===void 0?[]:[{start:o,end:s,...a}]})};var ce=class extends Error{code;details;constructor({code:t,message:n,details:r}){super(n),this.name="AssetResourceHydrationError",this.code=t,this.details=r}},sw=e=>{if(e===null)return[];let t=Array.isArray(e)?e:[e],n=new Map;for(let r of t){if(typeof r!="object"||r===null||!("_id"in r)||typeof r._id!="string"||!("revision"in r)||typeof r.revision!="string"||!("contentRef"in r)||typeof r.contentRef!="string")throw new ce({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 ce({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())},iw=e=>typeof e.mimeType=="string"&&(e.mimeType.startsWith("text/")||["application/json","application/javascript","application/xml","image/svg+xml"].includes(e.mimeType)),aw=async({read:e,contentRef:t,range:n,maximumBytes:r})=>{if(r===0)return new Uint8Array;let o=await e(t,n);try{return await Xe(o.data,r)}catch(s){throw s instanceof we?new ce({code:"CONTENT_LIMIT_EXCEEDED",message:"Asset storage returned more content than requested"}):s}},cw=e=>{try{return ve(e)}catch{throw new ce({code:"CONTENT_DECODING_FAILED",message:"Selected asset content is not valid UTF-8"})}},uw=(e,t)=>{if(t.mode==="range")return Math.max(0,Math.min(t.length,e.size-t.offset));let n=t.maxBytes??N.hydratedFileBytes;if(e.size>n)throw new ce({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected asset exceeds the per-file content limit",details:{assetId:e._id,assetBytes:e.size,fileByteLimit:n}});return e.size},Gp=e=>{let t=e.flatMap(({reason:s,document:i})=>{if(typeof i.path!="string")return[];let a=s instanceof ce?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(t.length!==e.length)throw e[0].reason;if(e.length===1){let s=e[0].reason,i=t[0];throw i===void 0?s:new ce({code:s instanceof ce?s.code:"INVALID_REQUEST",message:i.message,details:{...s instanceof ce?s.details:{},diagnostics:t}})}let n=new Set(t.map(({code:s})=>s)),r=t[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 ce({code:o,message:`${t.length} selected asset content errors found`,details:{diagnostics:t}})},Jp=async({result:e,documents:t,options:n,read:r,assetReferences:o,assetUrls:s,assetPaths:i})=>{if(n.mode==="none")return{content:{},hydratedFileCount:0,hydratedBytes:0};let a=sw(e);if(a.length>N.hydratedFileCount)throw new ce({code:"CONTENT_LIMIT_EXCEEDED",message:"Too many selected assets requested content hydration",details:{fileCount:a.length,fileCountLimit:N.hydratedFileCount}});let c=new Map(t.map(m=>[m._id,m])),u=a.map(m=>{let A=c.get(m._id);try{if(A===void 0||A.revision!==m.revision||A.contentRef!==m.contentRef||typeof A.size!="number"||typeof A.mimeType!="string")throw new ce({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset content identity is stale or unavailable",details:{assetId:m._id}});let S={...A,size:A.size,mimeType:A.mimeType};if(iw(S)===!1)throw new ce({code:"CONTENT_NOT_TEXT",message:"Selected binary asset cannot be embedded as text",details:{assetId:m._id,mimeType:S.mimeType}});return{status:"fulfilled",value:{identity:m,document:S,readLength:uw(S,n)}}}catch(S){return{status:"rejected",reason:S,document:A??{_id:m._id}}}}),f=u.flatMap(m=>m.status==="rejected"?[m]:[]);f.length>0&&Gp(f);let l=u.flatMap(m=>m.status==="fulfilled"?[m.value]:[]),p=l.reduce((m,A)=>m+A.readLength,0);if(p>N.hydratedTotalBytes)throw new ce({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected assets exceed the total hydrated-content limit",details:{totalReadBytes:p,totalByteLimit:N.hydratedTotalBytes}});let d=i===void 0?void 0:Jo(Object.entries(i).map(([m,A])=>({id:m,path:A}))),w=await oo(l,N.concurrentContentReads,async m=>{try{let A=n.mode==="range"?{offset:n.offset,length:m.readLength}:m.readLength===0?void 0:{offset:0,length:m.readLength},S=await aw({read:r,contentRef:m.identity.contentRef,range:A,maximumBytes:m.readLength});if(S.byteLength!==m.readLength)throw new ce({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset bytes do not match canonical metadata",details:{assetId:m.identity._id}});let E;if(n.mode==="markdown-body-ref")try{E=(await jo(S,m.readLength||1)).body;let x=d===void 0||m.document.path===void 0?o?.[m.identity.contentRef]:Qp({markdown:E,sourcePath:m.document.path,assetIdsByPath:d});x!==void 0&&s!==void 0&&(E=Vp({markdown:E,references:x,assetUrls:s}))}catch{throw new ce({code:"CONTENT_DECODING_FAILED",message:"Selected Markdown body could not be decoded",details:{assetId:m.identity._id}})}else E=cw(S);let _=Ye(E);return{status:"fulfilled",value:{id:m.identity._id,returnedBytes:_,content:{...m.identity,encoding:"utf-8",text:E,...n.mode==="range"?{range:{offset:n.offset,length:S.byteLength,total:m.document.size}}:{}}}}}catch(A){return{status:"rejected",reason:A,document:m.document}}}),h=w.flatMap(m=>m.status==="rejected"?[m]:[]);h.length>0&&Gp(h);let y=w.flatMap(m=>m.status==="fulfilled"?[m.value]:[]);return{content:Object.fromEntries(y.map(({id:m,content:A})=>[m,A])),hydratedFileCount:l.length,hydratedBytes:y.reduce((m,{returnedBytes:A})=>m+A,0)}};var tO=D().datetime({offset:!0}).transform(e=>new Date(e).toISOString());var lw=/^[A-Za-z_][A-Za-z0-9_]*$/,Wp=(e,t)=>lw.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`;var Kp=({document:e,includes:t})=>{let n={};for(let r of Ff){let o=e[r];o!==void 0&&t(r)&&(n[r]=o)}return n},Bt=Symbol("missing property selection"),la=(e,t)=>{if(t.some(r=>r.length===0)||typeof io(e)=="string")return e;if(Array.isArray(e)){let r=t.filter(([s])=>s==="*").map(s=>s.slice(1));if(r.length===0)return Bt;let o=e.map(s=>la(s,r));return o.some(s=>s!==Bt)?o.map(s=>s===Bt?null:s):Bt}if(typeof e!="object"||e===null)return Bt;let n={};for(let[r,o]of Object.entries(e)){let s=t.filter(([a])=>a===r).map(a=>a.slice(1));if(s.length===0)continue;let i=la(o,s);i!==Bt&&(n[r]=i)}return Object.keys(n).length===0?Bt:n},Hp=({properties:e,fields:t})=>{let n=t.filter(([o])=>o==="properties").map(o=>o.slice(1)),r=la(e,n);return r===Bt?{}:r};var Me=class extends Error{code;issues;details;constructor(t,n){super(t,n),this.name="AssetQueryExecutionError",this.code=n?.code??"INVALID_REQUEST",this.issues=n?.issues,this.details=n?.details}},Dr=class extends Me{code="MULTIPLE_RESULTS";matchedCount;constructor(t){super(`Expected at most one asset, but the query matched ${t}.`),this.matchedCount=t,this.name="AssetQueryMultipleResultsError"}},zn=class extends Error{constructor(){super("The requested asset index revision is stale"),this.name="AssetIndexRevisionError"}},fa=e=>{if(e[0]!=="properties")return e[0];let t="properties";for(let n of e.slice(1))t=Wp(t,n);return t},Yp=({filter:e,fieldTypes:t})=>qf(t).includes(e.operator),Xp=(e,t)=>e!==void 0&&Object.hasOwn(e.fields,t)?e.fields[t]:void 0,fw=e=>{if(e===null)return"null";if(Array.isArray(e))return"array";if(typeof e=="object")return"object";if(typeof e=="boolean")return"boolean";if(typeof e=="number")return"number";if(typeof e=="string")return"string"},dw=({operator:e,fieldTypes:t})=>{if(!(e==="contains"&&t.includes("array"))){if(e==="startsWith"||e==="endsWith"||e==="contains")return["string"];if(e==="gt"||e==="gte"||e==="lt"||e==="lte")return t.filter(n=>n==="string"||n==="number");if(e==="eq"||e==="ne"||e==="in")return t}},em=({filter:e,fieldTypes:t,path:n})=>{let r=dw({operator:e.operator,fieldTypes:t});return r===void 0?[]:(e.operator==="in"?e.value:[e.value]).flatMap((s,i)=>r.some(a=>a===fw(s))?[]:[e.operator==="in"?[...n,"value",String(i)]:[...n,"value"]])},pa=(e,t=["query","where"])=>"field"in e?[{filter:e,path:t}]:"all"in e?e.all.flatMap((n,r)=>pa(n,[...t,"all",String(r)])):e.any.flatMap((n,r)=>pa(n,[...t,"any",String(r)])),pw=({query:e,catalog:t})=>{let n=Rt.safeParse(e);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,f,l)=>{s.push(l),i.push({severity:"warning",code:u,path:f,message:l})};for(let{filter:u,path:f}of pa(r.where)){let l=fa(u.field);if(o.set(l,u.field),u.field[0]==="properties"){let p=Xp(t,l);if(t!==void 0&&p===void 0)a("UNOBSERVED_FIELD",[...f,"field"],`Asset field ${l} is not currently observed`);else if(p!==void 0&&Yp({filter:u,fieldTypes:p.types})===!1)a("INCOMPATIBLE_OBSERVED_TYPES",[...f,"operator"],`Operator ${u.operator} is not compatible with the currently observed types of ${l}`);else if(p!==void 0)for(let d of em({filter:u,fieldTypes:p.types,path:f}))a("INCOMPATIBLE_OBSERVED_VALUE",d,`Filter value is not compatible with the currently observed types of ${l}`)}else{let p=ai[u.field[0]];if(Yp({filter:u,fieldTypes:p})===!1)i.push({severity:"error",code:"INCOMPATIBLE_OPERATOR",path:[...f,"operator"],message:`Operator ${u.operator} is incompatible with ${l}`});else for(let d of em({filter:u,fieldTypes:p,path:f}))i.push({severity:"error",code:"INCOMPATIBLE_VALUE",path:d,message:`Filter value is incompatible with ${l}`})}}for(let[u,f]of r.sort.entries()){let l=fa(f.field);if(o.set(l,f.field),f.field[0]==="properties"){let p=Xp(t,l);t!==void 0&&p===void 0?a("UNOBSERVED_FIELD",["query","sort",String(u),"field"],`Asset field ${l} is not currently observed`):p!==void 0&&p.types.some(d=>d==="object"||d==="array")&&a("STRUCTURED_SORT_ORDER",["query","sort",String(u),"field"],`Asset field ${l} currently includes structured values that use deterministic JSON sort order`)}}if(r.output.mode==="fields")for(let u of r.output.fields){let f=fa(u);o.set(f,u)}let c=[...new Map(i.map(u=>[JSON.stringify([u.code,u.path,u.message]),u])).values()];return{success:c.some(({severity:u})=>u==="error")===!1,query:r,referencedFieldPaths:[...o.values()],warnings:[...new Set(s)],issues:c}},mw=({query:e,catalog:t})=>{let n=pw({query:e,catalog:t});if(n.success===!1){let r=n.issues.filter(({severity:o})=>o==="error");throw new Me(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}},ma=(e,t,n)=>{let r=t[0]==="id"?e._id:ro(t[0])?n?.[t[0]]:e[t[0]];for(let o of t.slice(1)){if(typeof r!="object"||r===null||Object.hasOwn(r,o)===!1)return;r=r[o]}return r},hw=e=>typeof e=="string"||Array.isArray(e)?e.length===0:typeof e=="object"&&e!==null&&Object.keys(e).length===0,gw=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e-t;if(typeof e=="string"&&typeof t=="string")return et(e,t)},tm=(e,t)=>{if(e.field.length!==1||e.field[0]!=="path"||typeof t!="string")return[t];let n=Wd(t);return n===t?[t]:[t,n]},ha=(e,t,n)=>{let r=ma(e,t.field,n);if(t.operator==="exists")return r!=null===t.value;if(t.operator==="isEmpty")return hw(r)===t.value;let o=tm(t,t.value);if(t.operator==="eq")return o.some(i=>Kn(r,i));if(t.operator==="ne")return o.every(i=>Kn(r,i)===!1);if(t.operator==="in")return t.value.some(i=>tm(t,i).some(a=>Kn(r,a)));if(t.operator==="contains")return typeof r=="string"?o.some(i=>typeof i=="string"&&r.includes(i)):Array.isArray(r)&&r.some(i=>Kn(i,t.value));if(t.operator==="startsWith")return typeof r=="string"&&o.some(i=>typeof i=="string"&&r.startsWith(i));if(t.operator==="endsWith")return typeof r=="string"&&o.some(i=>typeof i=="string"&&r.endsWith(i));let s=gw(r,o[o.length-1]);return s===void 0?!1:t.operator==="gt"?s>0:t.operator==="gte"?s>=0:t.operator==="lt"?s<0:s<=0},yw=({document:e,where:t,runtimeAsset:n,filterKeys:r,filterResults:o})=>un(t,s=>{let i=r.get(s)??Re(s),a=o.get(i);if(a!==void 0)return a;let c=ha(e,s,n);return o.set(i,c),c})===!0,bw=({document:e,content:t})=>{if(t.mode!=="markdown-body-ref")return!0;let n=e.mimeType===void 0?void 0:Df(e.mimeType);return n==="markdown"||n==="mdx"?!0:e.extension==="md"||e.extension==="mdx"},ww=(e,t)=>{let n=e==null,r=t==null;return n||r?n===r?0:n?1:-1:typeof e=="number"&&typeof t=="number"?e-t:(typeof e=="string"||typeof e=="boolean")&&(typeof t=="string"||typeof t=="boolean")?et(String(e),String(t)):et(Re(e),Re(t))},xw=({left:e,right:t,sort:n,runtimeAssets:r})=>{for(let o of n){let s=ww(ma(e,o.field,r?.[e._id]),ma(t,o.field,r?.[t._id]));if(s!==0)return o.direction==="asc"?s:-s}return et(e._id,t._id)};var _w=(e,t)=>{if(e.properties===void 0)return;if(t.mode==="all")return Object.keys(e.properties).length===0?void 0:e.properties;if(t.mode!=="fields"||t.fields.some(r=>r[0]==="properties")===!1)return;let n=Hp({properties:e.properties,fields:t.fields});return Object.keys(n).length===0?void 0:n},Nn=(e,t)=>e.includeMetadata&&Mf(t)||e.mode==="fields"&&e.fields.some(n=>n.length===1&&n[0]===t),Sw=e=>e.mode==="all"||e.mode==="fields"&&e.fields.some(t=>t.length===1&&t[0]==="excerpt"),Ew=(e,t,n)=>{if(Nn(t,"url")&&n===void 0)throw new Me(`Asset URL is unavailable for ${e._id}`,{details:{assetId:e._id}});let r=_w(e,t),o=n?.width!==void 0&&n.height!==void 0;return{...n!==void 0&&Nn(t,"url")?{url:n.url}:{},...o&&Nn(t,"width")?{width:n.width}:{},...o&&Nn(t,"height")?{height:n.height}:{},...Kp({document:e,includes:s=>Nn(t,s)}),...r===void 0?{}:{properties:r},...e.excerpt===void 0||Sw(t)===!1?{}:{excerpt:e.excerpt},...e.metadataError===void 0||t.includeMetadata===!1?{}:{metadataError:e.metadataError}}},ga=e=>{let t=Ye(Re(e));if(t>N.resultBytes)throw new Me("Asset query result exceeds the byte limit",{code:"CONTENT_LIMIT_EXCEEDED",details:{resultBytes:t,resultByteLimit:N.resultBytes}})},ps=(e,t,n)=>{e[t]={status:"rejected",reason:n}},Aw=({inputs:e,catalog:t,results:n})=>{let r=new Map,o=new Map,s=[];for(let[i,a]of e.entries()){let c;try{c=mw({query:a,catalog:t}).query}catch(l){ps(n,i,l);continue}for(let l of Kr(c.where))o.set(l,Re(l));let u=Re(c.sort),f=r.get(u);f===void 0&&(f={sort:c.sort,documents:new Set,sorted:[]},r.set(u,f)),s.push({index:i,query:c,matches:new Map,sortGroup:f})}return{filterKeys:o,preparedQueries:s,sortGroups:r}},nm=({preparedQueries:e,results:t,createReason:n})=>{for(let{index:r}of e)ps(t,r,n())},da=e=>e.map(t=>{if(t===void 0)throw new Error("Asset query result was not settled");return t}),kw=({preparedQueries:e,documents:t,filterKeys:n,sortGroups:r,results:o,runtimeAssets:s})=>{for(let i of t){let a=s?.[i._id],c=new Map;for(let u of e){if(o[u.index]!==void 0)continue;let{query:f}=u;try{if(bw({document:i,content:f.content})===!1||yw({document:i,where:f.where,runtimeAsset:a,filterKeys:n,filterResults:c})===!1)continue;let l=Ew(i,f.output,a);if(f.content.mode==="none"&&Object.keys(l).length===0&&f.output.mode!=="all"&&Nn(f.output,"id")===!1)continue;let p={document:i,item:{id:i._id,...l}};u.matches.set(i,p),u.sortGroup.documents.add(i)}catch(l){ps(o,u.index,l)}}}for(let i of r.values())i.sorted=[...i.documents].sort((a,c)=>xw({left:a,right:c,sort:i.sort,runtimeAssets:s}))},vw=async({preparedQueries:e,results:t,read:n,assetReferences:r,assetUrls:o,assetPaths:s})=>{await Promise.all(e.map(async i=>{if(t[i.index]!==void 0)return;let{query:a}=i;try{let c=i.sortGroup.sorted.flatMap(w=>{let h=i.matches.get(w);return h===void 0?[]:[h]}),u=a.result??"many";if(u==="one"&&c.length>1)throw new Dr(c.length);let f=u==="many"?c.slice(a.offset,a.offset+a.limit):u==="last"?c.slice(-1):c.slice(0,1),l=f.map(({document:w})=>w),p=f.map(({item:w})=>w);if(a.content.mode!=="none"){let w=a.content;if(n===void 0)throw new Me("Asset content reader is unavailable");let h=await Jp({result:l,documents:l,options:w,read:n,assetReferences:r,assetUrls:o,assetPaths:s});p=l.map((y,m)=>{let A=h.content[y._id];if(A===void 0)throw new Me("Selected asset content could not be read");return{...p[m],content:{encoding:A.encoding,text:A.text,...A.range===void 0?{}:{range:A.range}}}})}let d=u==="many"?{items:p,totalCount:c.length,hasMore:a.offset+f.length<c.length}:{item:p[0]??null,totalCount:c.length};ga(d),t[i.index]={status:"fulfilled",value:d}}catch(c){ps(t,i.index,c)}}))},rm=async({queries:e,catalog:t,documents:n,read:r,runtimeAssets:o,assetReferences:s,assetValueReferences:i,assetPaths:a})=>{let c=Array.from({length:e.length}),{filterKeys:u,preparedQueries:f,sortGroups:l}=Aw({inputs:e,catalog:t,results:c});if(n.length>N.candidateDocuments)return nm({preparedQueries:f,results:c,createReason:()=>new Me("Asset query document limit was exceeded",{code:"CONTENT_LIMIT_EXCEEDED",details:{documentCount:n.length,documentLimit:N.candidateDocuments}})}),da(c);let p;try{p=n.map(w=>Lt({value:w,references:i?.[w._id],runtimeAssets:o??{}}))}catch(w){return nm({preparedQueries:f,results:c,createReason:()=>w}),da(c)}kw({preparedQueries:f,documents:p,filterKeys:u,sortGroups:l,results:c,runtimeAssets:o});let d=Xd(o);return await vw({preparedQueries:f,results:c,read:r,assetReferences:s,assetUrls:d,assetPaths:a}),da(c)};var Rw=async e=>await Af(Re(Rt.parse(e)));var Dw=({item:e,field:t,value:n})=>{let r=e;for(let[o,s]of t.entries()){if(o===t.length-1){Object.defineProperty(r,s,{value:n,enumerable:!0,configurable:!0,writable:!0});return}let i=Object.hasOwn(r,s)?r[s]:void 0;if(typeof i=="object"&&i!==null){r=i;continue}let a={};Object.defineProperty(r,s,{value:a,enumerable:!0,configurable:!0,writable:!0}),r=a}},Iw=e=>ci.parse({items:e.rows.map(t=>{let n={};for(let[r,o]of e.fields.entries())Dw({item:n,field:o,value:t[r]});return n}),totalCount:e.totalCount,hasMore:e.hasMore}),om=async({queries:e,query:t,assetValueReferences:n,runtimeAssets:r={}})=>{if(e===void 0)return;let o=e[await Rw(Rt.parse(t))];if(o===void 0)return;let s=Iw(o),i={...s,items:s.items.map(a=>Lt({value:a,references:n?.[a.id],runtimeAssets:r}))};return ga(i),i};var Cw=({graph:e,load:t,getCached:n,readFallback:r,signal:o})=>{let s=new Map(e.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=vn({node:c,source:n(c)??await t(c,{signal:o})});return{data:Hr(u.source,a),...a===void 0?{}:{contentLength:a.length}}}},Tw=({artifact:e,revision:t,catalog:n,documentGraph:r,inlineDocuments:o,readContent:s})=>{let i=new Map(e.documents.map(_=>[_._id,_])),a=_=>{if(_.indexRevision!==void 0&&_.indexRevision!==t)throw new zn},c=_=>async(x,R)=>{let v=e.contents?.[x];if(v===void 0){let Q=_??s;if(Q===void 0)throw new Error("Content is not embedded in this database");return await Q(x,R)}let I=kt(v),P=R===void 0?I:I.slice(R.offset,R.offset+R.length);return{data:async function*(){yield P}(),contentLength:P.byteLength}},u=_=>{if(_.status==="rejected")throw _.reason;return _.value},f=async({requests:_,queryContentReader:x,runtimeAssets:R,documents:v=e.documents})=>await rm({queries:_.map(({query:I})=>I),catalog:n,documents:v,read:c(x),runtimeAssets:R,assetReferences:e.assetReferences,assetPaths:e.assetPaths,assetValueReferences:e.assetValueReferences}),l=async({request:_,...x})=>u((await f({...x,requests:[_]}))[0]),p=async({requests:_,queryContentReader:x,runtimeAssets:R})=>{let v=Array.from({length:_.length}),I=[];for(let[P,Q]of _.entries()){try{a(Q);let O=await om({queries:e.queries,query:Q.query,assetValueReferences:e.assetValueReferences,runtimeAssets:R});if(O!==void 0){v[P]={status:"fulfilled",value:O};continue}}catch(O){v[P]={status:"rejected",reason:O};continue}I.push(P)}if(I.length>0){let P=await f({requests:I.map(Q=>_[Q]),queryContentReader:x,runtimeAssets:R});for(let[Q,O]of I.entries())v[O]=P[Q]}return v.map(P=>{if(P===void 0)throw new Error("Content database query was not settled");return P})},d=async(_,x,R)=>u((await p({requests:[_],queryContentReader:x,runtimeAssets:R}))[0]),w=async(..._)=>await d(..._),h=_=>async(x,R)=>{let v=o?.get(x.id);return v!==void 0?{format:"json",revision:x.revision,source:JSON.stringify(v.properties)}:await _(x,R)},y=({graph:_,query:x,runtimeAssets:R})=>wp({graph:_,query:x}).filter(v=>{let I=i.get(v),P=I===void 0?void 0:Lt({value:I,references:e.assetValueReferences?.[v],runtimeAssets:R??{}});return P===void 0?!1:un(x.where,Q=>{if(!bp({graph:_,sourceId:v,field:Q.field}))return ha(P,Q,R?.[v])})!==!1}),m=({rootIds:_,roots:x})=>{let R=new Map(_.flatMap((v,I)=>{let P=Ho(x[I]);return P===void 0?[]:[[v,P]]}));return e.documents.map(v=>{let I=R.get(v._id);return I===void 0?v:ii.parse({...v,properties:I})})},A=async({request:_,graph:x,resolutionSession:R,contentReader:v,runtimeAssets:I,onEvent:P})=>{a(_);let Q=Rt.parse(_.query),O=y({graph:x,query:Q,runtimeAssets:I});if(O.length===0)return await d(_,v,I);let z=xp({graph:x,query:Q,rootIds:O});_e(P,{type:"roots-selected",rootCount:O.length});let Z=await R.resolve({graph:z,rootIds:O,onEvent:P,allowUnresolvedReferences:!0,transformDocument:({node:ne,document:ue})=>Ui({document:ue,references:e.assetValueReferences?.[ne.id],runtimeAssets:I})}),q=m({rootIds:O,roots:Z.roots});return await l({request:_,queryContentReader:v,runtimeAssets:I,documents:q})},S=async({requests:_,load:x,resolutionSession:R,readContent:v,runtimeAssets:I,signal:P,onEvent:Q})=>{if(r===void 0)return await p({requests:_,queryContentReader:v,runtimeAssets:I});let O=h(x),z=R??pp({load:O,concurrency:N.concurrentContentReads,signal:P}),Z=Cw({graph:r,load:O,getCached:z.getCached,readFallback:v??s,signal:P});return await Promise.allSettled(_.map(q=>A({request:q,graph:r,resolutionSession:z,contentReader:Z,runtimeAssets:I,onEvent:Q})))};return{query:w,queryManyWithDocumentGraph:S,queryWithDocumentGraph:async({request:_,...x})=>u((await S({...x,requests:[_]}))[0])}};var ya=({artifact:e,readContent:t})=>{let n=_p({artifact:e});return Tw({artifact:e,revision:e.revision,documentGraph:n?.graph,inlineDocuments:n?.inlineDocuments,readContent:t})};var $n=class extends Error{constructor(t,n){super(t,n),this.name="AssetQueryRequestError"}},Ir=class extends Error{},Ow=async(e,t)=>{if(Number.isSafeInteger(t)===!1||t<0)throw new TypeError("Request byte limit must be a non-negative integer");let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>t)throw new Ir("Request exceeds the byte limit");let r=e.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>t){try{await r.cancel()}catch{}throw new Ir("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},sm=async e=>{let t;try{t=await Ow(e,N.requestBytes)}catch(n){throw n instanceof Ir?new $n("Asset query request exceeds the byte limit",{cause:n}):n}try{return Zf.parse(JSON.parse(ve(t)))}catch(n){throw new $n("Asset query request is invalid",{cause:n})}};var im=e=>{if(!(e instanceof $n))return;let t=e.message,n=new Set,r=e.cause;for(;r instanceof Error&&n.has(r)===!1;){if(r instanceof Vl)return{code:"INVALID_REQUEST",message:e.message,retryable:!1,status:400,details:{issues:r.issues.map(o=>({code:o.code,path:o.path.map(String),message:o.message}))}};t=r.message,n.add(r),r=r.cause}return{code:"INVALID_REQUEST",message:t,retryable:!1,status:400}},am=e=>{if(e instanceof zn)return{code:"STALE_INDEX",message:e.message,retryable:!1,status:409};if(e instanceof Dr)return{code:e.code,message:e.message,retryable:!1,details:{matchedCount:e.matchedCount},status:409};if(e instanceof Me){let r={...e.details,...e.issues===void 0?{}:{issues:e.issues.map(o=>({...o,path:[...o.path]}))}};return{code:e.code,message:e.message,retryable:!1,...Object.keys(r).length===0?{}:{details:r},status:400}}if(e instanceof ce)return{code:e.code,message:e.message,retryable:!1,details:e.details,status:400};let t=new Set,n=e;for(;n!==void 0&&t.has(n)===!1;){if(n instanceof Kt){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 wr)return{code:"CONTENT_LIMIT_EXCEEDED",message:n.message,retryable:!1,details:{assetId:n.documentId,contentByteLimit:n.contentByteLimit},status:400};t.add(n),n=n instanceof Error?n.cause:void 0}};var Nw="/$resources/assets",zw="WEBSTUDIO_AUTOMATION_TOKEN",ms=e=>typeof e=="object"&&e!==null?e:void 0,$w=e=>{let t=ms(e),n=ms(t?.cloudflare),r=[t,ms(t?.env),ms(n?.env)];for(let o of r){let s=o?.[zw];if(typeof s=="string"&&s.length>0)return s}},cm=(e,t=200)=>new Response(JSON.stringify(e),{status:t,headers:{"content-type":"application/json; charset=utf-8"}}),Ln=({code:e,message:t,status:n,retryable:r=!1,details:o})=>cm(Vf({code:e,message:t,retryable:r,details:o}),n),Lw=(e,t,n)=>typeof e=="string"||e instanceof URL?new Request(new URL(e,t),n):new Request(e,n),Pw=async({deploymentId:e,artifact:t,request:n})=>{let r=await n.clone().text(),o=n.headers.get("cache-control"),s=await ri(JSON.stringify([e,t.revision,r,o])),i=new URL(n.url);return i.searchParams.set("ws-asset-resource",s),new Request(i,{method:"GET"})},YO=({deploymentId:e,artifact:t,runtimeAssets:n,cache:r,baseUrl:o,automationToken:s,fetchDocument:i=globalThis.fetch,onDocumentGraphEvent:a})=>{lm({artifact:t,runtimeAssets:n});let c=Qi();return fm({deploymentId:e,artifact:t,runtimeAssets:n,cache:r,baseUrl:o,automationToken:s,database:ya({artifact:t}),fetchDocument:i,documentCache:c,onDocumentGraphEvent:a})},um=({assetId:e,baseUrl:t,runtimeAssets:n,automationToken:r,authorization:o})=>{let s=n[e];if(s===void 0)throw new Error(`Published document URL is unavailable for ${e}`);let i=new Request(new URL(s.url,t));return i.headers.delete("referer"),r!==void 0&&i.headers.set("x-webstudio-automation",r),o!==void 0&&/^Basic\s/i.test(o)&&new URL(i.url).origin===new URL(t).origin?(i.headers.set("authorization",o),new Request(i,{redirect:"manual"})):i},Fw=({baseUrl:e,runtimeAssets:t,embeddedContents:n,automationToken:r,authorization:o,fetchDocument:s,cache:i,onEvent:a})=>{let c=op({fetch:s,getRequest:u=>um({assetId:u.id,baseUrl:e,runtimeAssets:t,automationToken:r,authorization:o}),getMetadata:({node:u})=>({format:u.format,revision:u.revision}),onEvent:a});return lp({cache:i,onEvent:a,load:async(u,f)=>{let l=u.format,p=l===void 0?void 0:n?.[u.contentRef];return p!==void 0&&l!==void 0?{format:l,revision:u.revision,source:kt(p)}:await c(u,f)}})},lm=({artifact:e,runtimeAssets:t})=>{let n=[e.assetReferences,e.assetValueReferences].flatMap(s=>Object.values(s??{}).flat()).map(({assetId:s})=>s).find(s=>t[s]===void 0);if(n!==void 0)throw new Error(`Published referenced asset URL is unavailable for ${n}`);let r=e.documentGraph?.nodes.find(({id:s})=>t[s]===void 0)?.id;if(r!==void 0)throw new Error(`Published document URL is unavailable for ${r}`);let o=e.documentGraph?.nodes.find(({id:s,contentRef:i})=>t[s]?.contentRef!==i)?.id;if(o!==void 0)throw new Error(`Published document identity does not match graph node ${o}`)},fm=({deploymentId:e,artifact:t,runtimeAssets:n,cache:r,baseUrl:o,automationToken:s,authorization:i,database:a,fetchDocument:c,documentCache:u,onDocumentGraphEvent:f})=>{let l=new URL(o).origin,p=new Map(t.documents.map(w=>[w.contentRef,w])),d=Fw({baseUrl:o,runtimeAssets:n,embeddedContents:t.contents,automationToken:s,authorization:i,fetchDocument:c,cache:u,onEvent:f});return async(w,h)=>{let y=Lw(w,o,h),m=new URL(y.url);if(m.origin!==l||m.pathname!==Nw||y.method.toUpperCase()!=="POST")return;let A;try{A=await sm(y.clone())}catch(E){let _=im(E);return Ln(_!==void 0?_:{code:"INVALID_REQUEST",message:"Asset resource request is invalid",status:400})}let S=r===void 0||y.headers.has("cache-control")===!1?void 0:await Pw({deploymentId:e,artifact:t,request:y});if(S!==void 0&&r!==void 0){let E=await r.match(S).catch(()=>{});if(E!==void 0)return new Response(E.body,E)}try{if(y.signal.aborted)return Ln({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let E=cm(await a.queryWithDocumentGraph({request:A,load:d,readContent:async(_,x)=>{let R=p.get(_);if(R===void 0)throw new Error(`Published content reference is unavailable: ${_}`);let v=await c(um({assetId:R._id,baseUrl:o,runtimeAssets:n,automationToken:s,authorization:i}),{signal:y.signal});if(!v.ok||v.body===null)throw new Error(`Document ${R._id} request returned status ${v.status} or no body`);return{data:Hr(Yr(v.body),x)}},runtimeAssets:n,signal:y.signal,onEvent:f}));return S!==void 0&&r!==void 0&&y.signal.aborted===!1&&(E.headers.set("cache-control",y.headers.get("cache-control")),await r.put(S,E.clone()).catch(()=>{})),E}catch(E){if(y.signal.aborted)return Ln({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let _=am(E);return Ln(_!==void 0?_:{code:"INTERNAL_ERROR",message:"Published asset query failed",status:500,retryable:!0})}}},XO=({deploymentId:e,artifact:t,runtimeAssets:n,onDocumentGraphEvent:r=void 0})=>{let o=globalThis.caches,s,i=()=>(s??=o.open(`webstudio-assets-${e}`),s),a=o===void 0?void 0:{match:async f=>(await i()).match(f),put:async(f,l)=>(await i()).put(f,l)};lm({artifact:t,runtimeAssets:n});let c=ya({artifact:t}),u=Qi();return async({request:f,context:l,fallback:p})=>{let d=new URL(f.url).origin,w=fm({deploymentId:e,artifact:t,runtimeAssets:n,cache:a,baseUrl:d,automationToken:$w(l),authorization:f.headers.get("authorization")??void 0,database:c,fetchDocument:p,documentCache:u,onDocumentGraphEvent:r});return async(h,y)=>await w(h,y)??p(h,y)}};export{XO as createGeneratedAssetResourceRuntime,YO as createPublishedAssetResourceFetch};diff --git a/fixtures/webstudio-features/app/__generated__/$resources.headers.server.ts b/fixtures/webstudio-features/app/__generated__/$resources.headers.server.tsnew file mode 100644index 0000000000..a1c2be60fc--- /dev/null+++ b/fixtures/webstudio-features/app/__generated__/$resources.headers.server.ts@@ -0,0 +1,2 @@+// Generated response header configuration for hosting adapters.+export const customHeaders: Array<{ route?: string; name: string; value: string }> = [];diff --git a/packages/asset-uploader/src/asset-repository.test.ts b/packages/asset-uploader/src/asset-repository.test.tsindex 7b671e866f..e4bb1e9302 100644--- a/packages/asset-uploader/src/asset-repository.test.ts+++ b/packages/asset-uploader/src/asset-repository.test.ts@@ -172,6 +172,124 @@ const prepareAssetContentUpdate = (});describe("PostgresAssetRepository", () => {+ test.each(+ [false, true].flatMap((cache) =>+ [false, true].map((recover) => ({ cache, recover }))+ )+ )(+ "uses prepared frontmatter for body-reference publication (cache: $cache, recover: $recover)",+ async ({ cache, recover }) => {+ const dependencies = createDependencies();+ const source = "---\ntitle: Post\n---\n\n";+ const entry: CanonicalAssetFileEntry = {+ projectId: "project-1",+ assetId: "post",+ revision: "post-r1",+ metadataRequirements: { structuredProperties: true, excerpt: false },+ document: {+ _id: "post",+ _type: "asset.file",+ name: "post.md",+ path: "blog/post.md",+ key: "post",+ extension: "md",+ mimeType: "text/markdown",+ size: new TextEncoder().encode(source).byteLength,+ revision: "post-r1",+ contentRef: "storage:post",+ properties: { title: "Post" },+ },+ };+ const image: CanonicalAssetFileEntry = {+ ...entry,+ assetId: "cover",+ revision: "cover-r1",+ document: {+ ...entry.document,+ _id: "cover",+ name: "cover.svg",+ path: "blog/cover.svg",+ key: "cover",+ extension: "svg",+ mimeType: "image/svg+xml",+ revision: "cover-r1",+ contentRef: "storage:cover",+ properties: {},+ },+ };+ const baseEntry = {+ ...entry,+ metadataRequirements: { structuredProperties: false, excerpt: false },+ document: { ...entry.document, properties: {} },+ };+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([+ baseEntry,+ image,+ ]);+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue([entry]);+ if (recover) {+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValueOnce([+ baseEntry,+ ]);+ }+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);+ const assetStore = createSourceAssetClient({ "storage:post": source });+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore,+ dependencies,+ compilationCache: cache ? createContentCompilationCache() : false,+ });+ const plan = createCompilationPlan({+ output: { mode: "base", includeMetadata: false },+ content: { mode: "markdown-body-ref" },+ });+ const artifact = await repository.prepareIndex(plan);+ expect(assetStore.readFile).not.toHaveBeenCalled();+ if (recover) {+ expect(+ dependencies.synchronizeCanonicalAssets+ ).toHaveBeenCalledExactlyOnceWith({+ client: context.postgrest.client,+ assetClient: assetStore,+ projectId: "project-1",+ assetIds: ["post"],+ requirements: { structuredProperties: true, excerpt: false },+ });+ } else {+ expect(dependencies.synchronizeCanonicalAssets).not.toHaveBeenCalled();+ }+ expect(artifact.contents).toBeUndefined();+ const fetchDocument = vi.fn(async () => new Response(source));+ const runtimeFetch = createPublishedAssetResourceFetch({+ baseUrl: "https://site.example",+ deploymentId: "publication",+ artifact: createContentRuntimeArtifact(artifact),+ runtimeAssets: {+ post: { url: "/assets/post.md", contentRef: "storage:post" },+ cover: { url: "/assets/cover.svg" },+ },+ fetchDocument,+ });+ const response = await runtimeFetch("/$resources/assets", {+ method: "POST",+ body: JSON.stringify({+ query: {+ output: { mode: "base", includeMetadata: false },+ content: { mode: "markdown-body-ref" },+ },+ }),+ });+ await expect(response?.json()).resolves.toMatchObject({+ items: [+ { id: "post", content: { text: "\n" } },+ ],+ });+ expect(fetchDocument).toHaveBeenCalledOnce();+ }+ );+test("publication keeps entries with invalid fields but rejects broken configuration", async () => {const sources = {"collection.json": createDefaultCollectionConfig(),@@ -3261,56 +3379,64 @@ describe("PostgresAssetRepository", () => {expect(dependencies.synchronizeCanonicalAssets).toHaveBeenCalledOnce();});- test("creates a base-only index without synchronizing or reading content", async () => {- const dependencies = createDependencies();- const entries = [- {- projectId: "project-1",- assetId: "asset-1",- revision: "revision-1",- document: {- _id: "asset-1",- _type: "asset.file" as const,- name: "post.md",- path: "post.md",- key: "post",- extension: "md",- mimeType: "text/markdown",- size: 10,+ test.each([+ { mode: "none", limit: 10 },+ { mode: "markdown-body-ref", limit: 0 },+ ] as const)(+ "creates a base-only index without synchronizing or reading content: $mode / $limit",+ async ({ mode, limit }) => {+ const dependencies = createDependencies();+ const entries = [+ {+ projectId: "project-1",+ assetId: "asset-1",revision: "revision-1",- contentRef: "post.md",- properties: {},+ document: {+ _id: "asset-1",+ _type: "asset.file" as const,+ name: "post.md",+ path: "post.md",+ key: "post",+ extension: "md",+ mimeType: "text/markdown",+ size: 10,+ revision: "revision-1",+ contentRef: "post.md",+ properties: {},+ },},- },- ];- const index = { integrity: { checksum: `sha256:${"b".repeat(64)}` } };- dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue(entries);- dependencies.createAssetIndex.mockResolvedValue(index as never);- const readFile = vi.fn();- const repository = new PostgresAssetRepository({- projectId: "project-1",- context,- assetStore: { readFile, uploadFile: vi.fn() },- dependencies,- });-- await expect(- repository.prepareIndex(- createCompilationPlan({- where: { all: [] },- output: { mode: "base", includeMetadata: true },- })- )- ).resolves.toBe(index);+ ];+ const index = { integrity: { checksum: `sha256:${"b".repeat(64)}` } };+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue(entries);+ dependencies.createAssetIndex.mockResolvedValue(index as never);+ const readFile = vi.fn();+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: { readFile, uploadFile: vi.fn() },+ dependencies,+ });- expect(dependencies.synchronizeCanonicalAssets).not.toHaveBeenCalled();- expect(dependencies.loadCanonicalAssetFileEntries).not.toHaveBeenCalled();- expect(dependencies.loadCanonicalAssetBaseEntries).toHaveBeenCalledWith({- client: context.postgrest.client,- projectId: "project-1",- });- expect(readFile).not.toHaveBeenCalled();- });+ await expect(+ repository.prepareIndex(+ createCompilationPlan({+ where: { all: [] },+ output: { mode: "base", includeMetadata: true },+ limit,+ content: { mode },+ })+ )+ ).resolves.toBe(index);++ expect(dependencies.synchronizeCanonicalAssets).not.toHaveBeenCalled();+ expect(dependencies.loadCanonicalAssetFileEntries).not.toHaveBeenCalled();+ expect(dependencies.loadCanonicalAssetBaseEntries).toHaveBeenCalledWith({+ client: context.postgrest.client,+ projectId: "project-1",+ });+ expect(readFile).not.toHaveBeenCalled();+ }+ );test("keeps collection configuration and templates out of query indexes", async () => {const dependencies = createDependencies();diff --git a/packages/asset-uploader/src/asset-repository.ts b/packages/asset-uploader/src/asset-repository.tsindex a3bf2d12e0..ac1c90767f 100644--- a/packages/asset-uploader/src/asset-repository.ts+++ b/packages/asset-uploader/src/asset-repository.ts@@ -20,7 +20,7 @@ import {inspectContentCollection,prepareContentCompilerEntries,requiresRuntimeDocumentData,- requiresStructuredProperties,+ getContentCompilationMetadataRequirements,validateAssetQueryAgainstCatalog,collectionConfigFilename,ContentCollectionError,@@ -47,7 +47,6 @@ import {createContentSourceFile,computeCanonicalAssetRevision,decodeUtf8,- fullCanonicalAssetMetadataRequirements,materializeContentSource,materializeContentSnapshot,mapBounded,@@ -131,7 +130,10 @@ 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 {+ createTextAssetSourceValidator,+ validateTextAssetSourceBytes,+} from "@webstudio-is/content-engine/mdx";import { removeMetadataIssuesDuplicatedBySource } from "./diagnostic-utils";import {getCollectionFolderIds,@@ -274,6 +276,7 @@ const parseCollectionTemplate = async (source: string) => {};class RequestContentBytesCache {+ readonly validateSource = createTextAssetSourceValidator();private values = new Map<string, Uint8Array>();private byteLength = 0;@@ -2133,10 +2136,8 @@ export class PostgresAssetRepository implements AssetRepository {...(requirements === undefined? {}: {- requirements: {- structuredProperties: requiresStructuredProperties(requirements),- excerpt: requirements.excerpt,- },+ requirements:+ getContentCompilationMetadataRequirements(requirements),}),});}@@ -2224,22 +2225,15 @@ export class PostgresAssetRepository implements AssetRepository {contentBytesCache,preparationIssues);- const compile = async (- entries: Parameters<typeof createAssetIndex>[0]["entries"],- assetReferences: Parameters<- typeof createAssetIndex- >[0]["assetReferences"],- assetValueReferences: Parameters<- typeof createAssetIndex- >[0]["assetValueReferences"],- documentGraph: Parameters<typeof createAssetIndex>[0]["documentGraph"],- assetReferenceIssues: Awaited<- ReturnType<typeof materializeContentSource>- >["assetReferenceIssues"],- sourceIssues: Awaited<- ReturnType<typeof materializeContentSource>- >["sourceIssues"]- ) => {+ const compile = async ({+ entries,+ assetReferences,+ assetPaths,+ assetValueReferences,+ documentGraph,+ assetReferenceIssues,+ sourceIssues,+ }: Awaited<ReturnType<typeof materializeContentSource>>) => {const artifact = await this.measurePerformance("artifact-compilation",async () =>@@ -2247,6 +2241,7 @@ export class PostgresAssetRepository implements AssetRepository {projectId: this.projectId,entries,assetReferences,+ assetPaths,...(assetValueReferences === undefined ||Object.keys(assetValueReferences).length === 0? {}@@ -2278,30 +2273,17 @@ export class PostgresAssetRepository implements AssetRepository {type: "compilation-cache",status: "disabled",});- const {- entries,- assetReferences,- assetValueReferences,- documentGraph,- assetReferenceIssues,- sourceIssues,- } = await preservePreparationIssues(() =>+ const materialized = await preservePreparationIssues(() =>materializeContentSource({source,+ validateSource: contentBytesCache.validateSource,plan: requirements,maximumContentBytes: this.contentDatabaseMaxBytes,onPerformanceEvent: this.onPerformanceEvent,performanceNow: this.dependencies.performanceNow,}));- return await compile(- entries,- assetReferences,- assetValueReferences,- documentGraph,- assetReferenceIssues,- sourceIssues- );+ return await compile(materialized);}for (let attempt = 0; attempt < 2; attempt += 1) {const snapshot = await this.measurePerformance(@@ -2319,30 +2301,17 @@ export class PostgresAssetRepository implements AssetRepository {const cached = this.compilationCache.getOrCreateWithStatus(key,async () => {- const {- entries,- assetReferences,- assetValueReferences,- documentGraph,- assetReferenceIssues,- sourceIssues,- } = await preservePreparationIssues(() =>+ const materialized = await preservePreparationIssues(() =>materializeContentSnapshot({snapshot,+ validateSource: contentBytesCache.validateSource,plan: requirements,maximumContentBytes: this.contentDatabaseMaxBytes,onPerformanceEvent: this.onPerformanceEvent,performanceNow: this.dependencies.performanceNow,}));- return await compile(- entries,- assetReferences,- assetValueReferences,- documentGraph,- assetReferenceIssues,- sourceIssues- );+ return await compile(materialized);});emitAssetQueryPerformanceEvent(this.onPerformanceEvent, {@@ -2554,22 +2523,15 @@ export class PostgresAssetRepository implements AssetRepository {? undefined: candidateBaseEntries.map(({ assetId }) => assetId);let entries = candidateBaseEntries;+ const metadataRequirements =+ getContentCompilationMetadataRequirements(requirements);if (- requirements === undefined ||- requiresStructuredProperties(requirements) ||- requirements.excerpt+ metadataRequirements.structuredProperties ||+ metadataRequirements.excerpt) {entries = await this.measurePerformance("canonical-metadata",async () => {- const metadataRequirements =- requirements === undefined- ? fullCanonicalAssetMetadataRequirements- : {- structuredProperties:- requiresStructuredProperties(requirements),- excerpt: requirements.excerpt,- };const current =await this.dependencies.loadCanonicalAssetFileEntriesForRecovery({client: this.context.postgrest.client,@@ -2689,6 +2651,7 @@ export class PostgresAssetRepository implements AssetRepository {const validation = await validateTextAssetSourceBytes({source: bytes,format: documentFormat === "markdown" ? "md" : "mdx",+ validateSource: contentBytesCache.validateSource,});byteSourceDiagnostics.push(...validation.diagnostics.map((diagnostic) => ({diff --git a/packages/asset-uploader/src/publication.ts b/packages/asset-uploader/src/publication.tsindex 403cf08c6b..369be6d641 100644--- a/packages/asset-uploader/src/publication.ts+++ b/packages/asset-uploader/src/publication.ts@@ -3,7 +3,10 @@ import {type ContentCompilationPlan,type ContentArtifactV1,} from "@webstudio-is/content-engine";-import { serializeJsonDeterministically } from "@webstudio-is/content-engine/compiler";+import {+ compileContentUntilPlanIsStable,+ serializeJsonDeterministically,+} from "@webstudio-is/content-engine/compiler";import type { Asset } from "@webstudio-is/sdk";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";import { PostgresAssetRepository } from "./asset-repository";@@ -155,37 +158,13 @@ export const preparePublishedAssetData = async (await repository.withIndexPreparationSession(async (prepareIndex) => {// Keep hydrated bytes local to one stability attempt. Dependency// convergence can reuse them, while a retry starts from a clean cache.- let artifact = await prepareIndex(plan);- if (resolvePlan !== undefined) {- let resolvedPlan = await resolvePlan(artifact);- if (- serializeJsonDeterministically(plan) ===- serializeJsonDeterministically(resolvedPlan)- ) {- return artifact;- }- for (- let dependencyPass = 0;- dependencyPass < 20;- dependencyPass += 1- ) {- artifact = await prepareIndex(resolvedPlan);- const validatedPlan = await resolvePlan(artifact);- if (- serializeJsonDeterministically(resolvedPlan) ===- serializeJsonDeterministically(validatedPlan)- ) {- break;- }- if (dependencyPass === 19) {- throw new Error(- "Dynamic MDX dependency closure exceeds the safe publication depth"- );- }- resolvedPlan = validatedPlan;- }- }- return artifact;+ return resolvePlan === undefined+ ? await prepareIndex(plan)+ : await compileContentUntilPlanIsStable({+ plan,+ compile: prepareIndex,+ resolvePlan,+ });}),dependencies,}diff --git a/packages/cli/src/asset-files.test.ts b/packages/cli/src/asset-files.test.tsindex ba17b2defa..3ba1584090 100644--- a/packages/cli/src/asset-files.test.ts+++ b/packages/cli/src/asset-files.test.ts@@ -13,6 +13,7 @@ import type { Asset } from "@webstudio-is/sdk";import {createLocalAssetDataReader,createLocalUpdateAssetContentInput,+ downloadAssetFiles,getLocalAssetPath,materializeAssetFile,} from "./asset-files";@@ -143,6 +144,40 @@ test("downloads asset files when they are missing from the synced asset cache",);});+test("downloads no more than 10 asset files concurrently", async () => {+ let active = 0;+ let peak = 0;+ const releases: Array<() => void> = [];+ const fetch = vi.fn(async () => {+ active += 1;+ peak = Math.max(peak, active);+ await new Promise<void>((resolve) => releases.push(resolve));+ active -= 1;+ return new Response("article");+ });+ globalThis.fetch = fetch;+ const assets = Array.from({ length: 20 }, (_, index) => ({+ ...asset,+ id: `article-${index}`,+ name: `article-${index}.mdx`,+ type: "file" as const,+ format: "mdx",+ meta: {},+ }));++ const downloading = downloadAssetFiles({+ assets,+ origin: "https://example.com",+ });+ await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(10));+ expect(peak).toBe(10);+ releases.splice(0).forEach((release) => release());+ await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(20));+ expect(peak).toBe(10);+ releases.splice(0).forEach((release) => release());+ await downloading;+});+test("retries asset download once after a server error", async () => {const fetch = vi.fn()diff --git a/packages/cli/src/commands/sync.test.ts b/packages/cli/src/commands/sync.test.tsindex 961eab4ae5..3e1f6cca8c 100644--- a/packages/cli/src/commands/sync.test.ts+++ b/packages/cli/src/commands/sync.test.ts@@ -1,5 +1,12 @@import { afterEach, beforeEach, expect, test, vi } from "vitest";-import { access, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import {+ access,+ mkdir,+ mkdtemp,+ readFile,+ rm,+ writeFile,+} from "node:fs/promises";import { join } from "node:path";import { tmpdir } from "node:os";import { createServer } from "node:http";@@ -13,6 +20,7 @@ import { resolveApiConnection } from "../api-connection";import { sync, defaultSyncDependencies } from "./sync";import { apiCompatibilityHeaders } from "./api";import { materializeManagedAgents } from "../managed-agents";+import { prebuild } from "../prebuild";const originalCwd = process.cwd();let tempDir: string;@@ -206,6 +214,133 @@ test("downloads project bundle asset files into local project bundle", async ()expect(indicator.message).toHaveBeenCalledWith("Downloading 1 asset files");});+test.each([+ {+ name: "hosted",+ deployment: { destination: "saas" as const, domains: [] },+ compilesArticles: false,+ },+ {+ name: "SSG",+ deployment: {+ destination: "static" as const,+ name: "site.zip",+ assetsDomain: "https://assets.example.com",+ templates: ["ssg" as const],+ },+ compilesArticles: true,+ },+])(+ "$name publish sync $compilesArticles articles only for SSG",+ async ({ deployment, compilesArticles }) => {+ const source = "# Published from the runner";+ const article = {+ ...createImageAssetFixture(),+ id: "article",+ name: "article.mdx",+ type: "file" as const,+ format: "mdx",+ size: new TextEncoder().encode(source).byteLength,+ meta: {},+ };+ const image = createImageAssetFixture();+ loadProjectBundleByBuildId.mockResolvedValue(+ createProjectBundle({+ assets: [article, image],+ build: {+ deployment,+ instances: [+ [+ "root",+ {+ type: "instance",+ id: "root",+ component: "Box",+ children: [{ type: "id", value: "content" }],+ },+ ],+ [+ "content",+ {+ type: "instance",+ id: "content",+ component: "ws:block",+ children: [{ type: "id", value: "templates" }],+ },+ ],+ [+ "templates",+ {+ type: "instance",+ id: "templates",+ component: "ws:block-template",+ children: [],+ },+ ],+ ],+ props: [+ [+ "article-source",+ {+ id: "article-source",+ instanceId: "content",+ name: "src",+ type: "asset",+ value: article.id,+ },+ ],+ ],+ },+ })+ );+ downloadAssetFiles.mockImplementation(async ({ assets }) => {+ await mkdir(".webstudio/assets", { recursive: true });+ await Promise.all(+ assets.map((asset: { id: string; name: string }) =>+ writeFile(+ `.webstudio/assets/${asset.name}`,+ asset.id === article.id ? source : "image"+ )+ )+ );+ });++ await sync(+ {+ authToken: "token-1",+ buildId: "build-1",+ origin: "https://example.com",+ },+ dependencies+ );++ const data = JSON.parse(await readFile(".webstudio/data.json", "utf8"));+ if (compilesArticles) {+ expect(downloadAssetFiles).toHaveBeenCalledWith({+ assets: [article, image],+ origin: "https://example.com",+ });+ expect(data.assetIndex.documents).toContainEqual(+ expect.objectContaining({ _id: article.id, extension: "mdx" })+ );+ expect(Object.values(data.assetIndex.contents)).toContain(source);++ await prebuild({ assets: false, template: ["ssg"] });+ const generatedPage = await readFile(+ "app/__generated__/_index.tsx",+ "utf8"+ );+ expect(generatedPage).toContain("Published from the runner");+ } else {+ expect(downloadAssetFiles).toHaveBeenCalledWith({+ assets: [image],+ origin: "https://example.com",+ });+ expect(data.assetIndex).toBeUndefined();+ }+ }+);+test("sends linked share token when synchronizing by build id", async () => {const resolveApiConnection = vi.fn(async () => ({authToken: "share-token",@@ -228,6 +363,7 @@ test("sends linked share token when synchronizing by build id", async () => {authToken: "share-token",origin: "https://example.com",headers: apiCompatibilityHeaders,+ contentIndex: "client",});});diff --git a/packages/cli/src/commands/sync.ts b/packages/cli/src/commands/sync.tsindex 3e6fa30a47..3964949ab8 100644--- a/packages/cli/src/commands/sync.ts+++ b/packages/cli/src/commands/sync.ts@@ -30,12 +30,23 @@ import {createSerializedBuilderBuildDataFromState,} from "@webstudio-is/project-build/state";import { migratePages } from "@webstudio-is/project-migrations/pages";+import {+ createBuildContentCompilationPlan,+ createPublishedBuildContentCompilationPlan,+ createPublishedMdxDependencyClosureResolver,+ getDynamicPublishedMdxSourceBlockIds,+ getPublishedMdxContentDatabaseMaxBytes,+ resolvePublishedMdxAssetCandidates,+} from "@webstudio-is/project-build";import {createReachableAssetContentCompilationPlan,getHomePage,} from "@webstudio-is/sdk";-import { compileContentSource } from "@webstudio-is/content-engine/compiler";import { parseContentDatabaseMaxBytes } from "@webstudio-is/content-engine";+import {+ compileContentSource,+ compileContentUntilPlanIsStable,+} from "@webstudio-is/content-engine/compiler";import { createFileSystemContentSource } from "../filesystem-content-source";import { z } from "zod";import {@@ -178,6 +189,7 @@ export const sync = async (serviceToken: options.authToken,origin: options.origin,headers: apiCompatibilityHeaders,+ contentIndex: "client",});project.origin = options.origin;} catch (error) {@@ -211,6 +223,7 @@ export const sync = async (authToken,origin,headers: apiCompatibilityHeaders,+ contentIndex: "client",}): await dependencies.loadCurrentProjectBundle({projectId,@@ -229,15 +242,31 @@ export const sync = async (throw new HandledCliError();}- if (project.assets.length > 0) {- syncing.message(`Downloading ${project.assets.length} asset files`);+ const createContentSource = () =>+ createFileSystemContentSource({+ projectId: project.build.projectId,+ assets: project.assets,+ folders: new Map(+ (project.assetFolders ?? []).map((folder) => [folder.id, folder])+ ),+ });++ const isStaticBuild = project.build.deployment?.destination === "static";+ const assetsToDownload =+ options.buildId !== undefined && isStaticBuild === false+ ? project.assets.filter(+ (asset) => asset.format !== "md" && asset.format !== "mdx"+ )+ : project.assets;+ if (assetsToDownload.length > 0) {+ syncing.message(`Downloading ${assetsToDownload.length} asset files`);if (project.origin === undefined) {syncing.stop("Asset origin is missing from project bundle", 2);throw new HandledCliError();}try {await dependencies.downloadAssetFiles({- assets: project.assets,+ assets: assetsToDownload,origin: project.origin,});} catch (error) {@@ -251,7 +280,65 @@ export const sync = async (}}- if (options.buildId === undefined) {+ if (+ options.buildId !== undefined &&+ isStaticBuild &&+ project.assetIndex === undefined+ ) {+ const publicationBuild = {+ ...project.build,+ pages: migratePages(project.build.pages),+ };+ const projectCandidates = resolvePublishedMdxAssetCandidates({+ build: publicationBuild,+ allowUnresolved: true,+ });+ const needsCandidateDiscovery = getDynamicPublishedMdxSourceBlockIds(+ publicationBuild+ ).some((blockId) => projectCandidates.has(blockId) === false);+ const candidateDiscoveryPlan = needsCandidateDiscovery+ ? createBuildContentCompilationPlan(publicationBuild)+ : undefined;+ let plan =+ candidateDiscoveryPlan ??+ createPublishedBuildContentCompilationPlan(+ publicationBuild,+ projectCandidates+ );+ if (plan !== undefined) {+ syncing.message("Preparing local content index");+ const source = createContentSource();+ const maxBytes = getPublishedMdxContentDatabaseMaxBytes({+ baseBytes: parseContentDatabaseMaxBytes(+ process.env.CONTENT_DATABASE_MAX_BYTES+ ),+ assets: project.assets,+ });+ const compile = async (compilationPlan: typeof plan) =>+ (+ await compileContentSource({+ source,+ projectId: project.build.projectId,+ plan: compilationPlan,+ maxBytes,+ })+ ).artifact;+ if (+ candidateDiscoveryPlan !== undefined ||+ plan.queries.some(({ id }) => id.startsWith("__content-block-mdx__:"))+ ) {+ const resolvePlan = createPublishedMdxDependencyClosureResolver();+ project.assetIndex = await compileContentUntilPlanIsStable({+ plan,+ compile,+ resolvePlan: async (artifact) =>+ await resolvePlan({ build: publicationBuild, artifact }),+ });+ } else {+ project.assetIndex = await compile(plan);+ }+ }+ } else if (options.buildId === undefined) {const plan = createReachableAssetContentCompilationPlan({props: project.build.props.map(([, value]) => value),dataSources: project.build.dataSources.map(([, value]) => value),@@ -260,13 +347,7 @@ export const sync = async (if (plan !== undefined) {syncing.message("Preparing local content index");const { artifact } = await compileContentSource({- source: createFileSystemContentSource({- projectId: project.build.projectId,- assets: project.assets,- folders: new Map(- (project.assetFolders ?? []).map((folder) => [folder.id, folder])- ),- }),+ source: createContentSource(),projectId: project.build.projectId,plan,maxBytes: parseContentDatabaseMaxBytes(diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.tsindex 1e8779f1d7..169d0d1b8a 100644--- a/packages/cli/src/docs.generated.ts+++ b/packages/cli/src/docs.generated.ts@@ -2,13 +2,13 @@// Edit markdown files in src/docs instead.export const cliDocs = {"api-use-cases":- '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get-more-tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get-more-tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search values and ids across every Builder namespace without sending full project data to the model.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nested asset folders and upload, inspect, move, duplicate, download, replace, delete, and inspect usage for assets.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Enter this workflow only when the user explicitly requests visual verification or opts in after being asked. Do not start preview, screenshots, diffs, OCR, or rendered audits automatically after a mutation.\n- `preview.status` reports whether generated output is `stale`. When no preview is running, `url`, `pid`, and `mode` are omitted. When present, `renderedProjectVersion` is the last project version materialized into the preview.\n- MCP preview and path-based screenshot tools select an available loopback port and return the preview URL. Do not pass `host` or `port`.\n- A managed `screenshot` or another `preview.start` refreshes stale generated output before capture.\n\n- After opt-in, use this so a vision-capable AI can see the generated site from the current MCP session. Use `path`; never pass a Webstudio Builder/share URL or capture Builder chrome.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- Iterative mode is the default: after MCP mutations, path screenshots ensure generated project files are current, wait for the exact session version, and perform an ordinary page reload without Vite HMR. The preview server and browser stay alive. Use `{"mode":"production"}` only for release-like verification; rendered audit does this automatically.\n- Calling `preview.start` after a committed mutation restarts a stale iterative server so external browsers and HTTP clients receive the newly generated project.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- The screenshot timeout bounds browser capture after the preview is ready. A timeout returns `SCREENSHOT_TIMEOUT`, resets the reusable browser session, and releases the shared preview lifecycle for cleanup.\n- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- When launcher metadata is available, Preview reuses a supported npm or pnpm launcher. Without launcher metadata, it uses npm when available and otherwise falls back to pnpm.\n- Unless `npm_config_cache` is already configured, npm uses the writable `.webstudio/preview/.npm-cache` directory.\n- For npm cache permission errors, unset `npm_config_cache` to use the preview-local cache, then retry. No cache deletion is required.\n- If dependency installation fails, check the reported package-manager path and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"\\"Pricing\\"","meta":{"description":"\\"Plans for teams\\""}}\n\nNotes:\n\n- `name` and `path` are plain values. Page `title` and metadata text fields contain expression source; quote fixed text as a JavaScript string literal inside the JSON string.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`. An unquoted word is a variable reference.\n- CLI flags such as `--title` treat values as fixed text. Add `--expressions` to `webstudio create-page` when passing expression source through these flags; quote any fixed text in the same call as a JavaScript string expression.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"\\"Pricing\\"","meta":{"description":"\\"Plans\\"","status":200}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- For fixed page `title` and metadata text, quote the text as a JavaScript string literal inside the JSON string.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`. An unquoted word is a variable reference.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599 or a JavaScript expression string for a dynamic status.\n- For `webstudio update-page`, add `--expressions` when page title or metadata flags contain expression source. Without it, those flags are fixed text.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## Submit marketplace product\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"marketplace-thumbnail.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"<uploadedAssetId>","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: publish {"target":"production"}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nNotes:\n\n- Wait for the production publish to complete before submitting the product for review.\n- Submission requires complete, valid marketplace metadata.\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}\n- webstudio duplicate-page --page <pageId> --name Paris --path /paris --substitutions \'{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}\' --json\n\nNotes:\n\n- Text substitutions replace exact fixed text only in the duplicated page\'s text children, string props, title, and metadata.\n- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.\n- Existing expressions and cloned variable/resource references keep their remapped ids.\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"\\"Landing\\""}\n\nCLI `create-page-template` and `update-page-template` use fixed text flags by default. Add `--expressions` when passing expression source through title or metadata flags.\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {}\n- MCP tool: list-pages {}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<section ws:style={css`padding: 32px;`}><h2>Product OS</h2><Switch><SwitchThumb /></Switch></section>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- Use lowercase HTML JSX such as `<div>` and `<form>`. The internal `ws:` namespace is not HTML-tag shorthand.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use ``ws:style={css`...`}`` for Webstudio-native CSS, or use React-style object syntax such as `style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<Switch><SwitchThumb /></Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside exactly one direct `ws:block-template` child. A missing or second template container makes the Content Block invalid. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before implementation, inventory every editor-owned field and its intended control and write destination, whether or not the block uses MDX. Check that templates contain the required styling, but do not treat containment or a successful text edit as proof that the whole block is editable. Test every field through Content mode, inspect its saved project data or source file, reload, and restore the original value. Report passed, failed, or not tested for each field; missing or read-only required controls are unfinished requirements.\n- Use controls that match the content: a calendar for dates and an image picker for image replacement. Keep fixed punctuation and units out of directly bound value elements. Preserve stored types and wording: when reading time is already a complete string such as `4 min read`, bind that string directly rather than assuming it is a number.\n- For MDX-backed blocks, containment alone is not enough: the MDX body is editable through its source mapping, but the designed shell needs writable document-frontmatter bindings. Follow the binding recipe below rather than binding editable article fields to query results.\n\n## Store Content Block content in MDX\n\nCommands:\n\n- MCP tool: list-assets {"type":"file"}\n- MCP tool: upload-asset {"asset":{"name":"article.mdx","type":"file","format":"mdx","meta":{}},"assetsDir":".webstudio/assets"}\n- MCP tool: connect-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":{"type":"asset","assetId":"<mdxAssetId>"}}\n- MCP tool: switch-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":{"type":"asset","assetId":"<otherMdxAssetId>"}}\n- MCP tool: inspect-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\n- MCP tool: edit-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":"# Article title\\n\\nArticle body."}\n- MCP tool: update-content-block-frontmatter {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","properties":{"title":"Article title","draft":false}}\n- MCP tool: reload-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\n- MCP tool: migrate-content-block-template-references {"assetIds":["<mdxAssetId>"],"migration":{"type":"rename","from":"Old template name","to":"New template name"}}\n- MCP tool: disconnect-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\n\nNotes:\n\n- Create the local `.mdx` file under `.webstudio/assets` before calling `upload-asset`. Use the returned Asset ID when connecting it.\n- Use the Content Block source operations for connecting, switching, inspecting, editing, reloading, and disconnecting. Do not create or delete the `src` prop with generic prop tools; the source operations preserve the Body outlet and Content Block lifecycle.\n- `renderScope` accepts any non-empty stable key for one rendered occurrence. Use a page-based key for a direct Content Block and a distinct key for each repeated Collection occurrence. It does not load a page, route parameters, or resource results. Supply the concrete scoped values needed to resolve an expression through `variables`.\n- For a result-one Assets resource, preview the concrete query, then connect its persisted expression with the previewed item supplied as `variables`, for example `source:{"type":"expression","value":"post.data.id"}` and `variables:{"post":{"data":{"id":"<mdxAssetId>"}}}`.\n- Connecting replaces existing Body content. If the result returns `requiresConfirmation:true`, report that replacement to the user and repeat the same call with `confirmReplacement:true` only after approval.\n- Prefer Markdown for standard document content; it automatically uses a unique matching semantic template when one exists. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG with authored properties that Markdown cannot express.\n- Verify that the Content Block has exactly one direct Templates container before connecting or editing MDX. Zero or multiple containers block materialization and publication.\n- Read the Content Block\'s Templates children before writing a custom reference. Use capitalized JSX such as `<PromotionCard />` for its stable **Name**, which is independent from the display label. A matching template wins over a built-in MDX adapter. Other registered components are unavailable until added to this Content Block\'s Templates. JSX attributes accept quoted static values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported.\n- When explicit JSX children match the designed template structure, their text and supported props overlay the cloned descendants and retain template styles. A mismatched child structure replaces the root defaults, while each authored child still resolves through a matching template when possible. An explicit empty pair clears defaults, and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live, so adding a matching semantic or named template later updates existing MDX. Preserve unresolved names and report their diagnostics instead of deleting them.\n- When a template is renamed or deleted, use `migrate-content-block-template-references` to update a selected set of affected MDX files. The first call returns a plan. Report its changed-file, update, omission, and diagnostic counts, then repeat the exact request with its `confirmationToken` only after approval. Renames and removals update named JSX and legacy `ws:name` references, including names such as `Image` and `CodeText` when they identify templates. Rename targets must be valid PascalCase JSX identifiers. Removing a paired reference unwraps and preserves its authored children; removing a self-closing reference removes the node because it has no authored children. Invalid files remain unchanged and are reported in diagnostics.\n- `edit-content-block-source` replaces the complete MDX source. Preserve frontmatter and unrelated source when making a bounded edit.\n- `update-content-block-frontmatter` replaces the complete frontmatter mapping. Inspect the current source first and include every property that must remain.\n- Store frontmatter images as exact `$ref` objects. Bind an editable Image source to the resolved `.src` with explicit `binding.mode:"readwrite"`; use `mode:"read"` for its alt binding to `.description`. Omitting the source mode leaves the image visible but not replaceable in Content mode.\n- Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document\'s frontmatter. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings.\n- Inspect every returned diagnostic. Invalid MDX is saved rather than silently repaired; preserve the source, report the source range, and fix only the requested or invalid part.\n- If an edit in a long-lived MCP session reports a conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly.\n\n## Make an MDX article header editable\n\nUse the resource only to select the connected source, for example `post.data.id`.\nBind article values inside the Content Block to its document parameter instead\nof `post.data.properties.*`. Inspect the block\'s variables first; `document` is\nthe default name, not a name to assume.\n\nThese commands target persistent designed instances inside the connected block.\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<headingInstanceId>","childIndex":0,"text":"document.frontmatter.title","mode":"expression","expressionBindingMode":"readwrite"}\n- MCP tool: update-text {"instanceId":"<readingTimeValueInstanceId>","childIndex":0,"text":"document.frontmatter.readingTime","mode":"expression","expressionBindingMode":"readwrite"}\n- MCP tool: bind-props {"bindings":[{"instanceId":"<dateInstanceId>","name":"datetime","binding":{"type":"expression","value":"document.frontmatter.publishedAt","mode":"readwrite"}}]}\n\nNotes:\n\n- Create writable bindings explicitly; the default is read-only. Merely moving a heading or Link inside the Content Block does not make its query-bound text editable.\n- The MDX body uses its source mapping. Static designed content outside that body remains protected unless its text or supported props bind to writable frontmatter fields. Do not apply these generic instance tools to MDX-generated instances.\n- Use direct static paths. Property access is already safe. Fallbacks and formatted expressions, such as `document.frontmatter.title ?? "Untitled"`, remain read-only.\n- Keep every intended editable value in its own text element with a single direct read-write binding. For reading time, use three inline siblings: static `— `, the bound reading-time value, and static ` min read`. Preserve whitespace and the stored field type. Do not combine them into a template literal or concatenate strings, and do not put literal siblings inside the value element itself. Keep fixed wording protected in the designed shell.\n- Prefer component formatting controls, such as Date Time formatting with a directly bound date prop, over transforming the expression. Do not silently sacrifice editability for formatting or a fallback; explain unsupported cases and ask before making an intended editable field read-only.\n- A direct writable binding such as `document.frontmatter.author.name` can edit a shared author loaded through `../authors/oleg.md#frontmatter`. The edit saves to the author file and affects every article using it; preserve the article\'s `$ref` marker.\n- Before handoff, inventory every article-owned field, including header text, author details, dates, reading time, categories, hero and inline image sources, alternative text, captions, links, and custom-component content. For each field, inspect its binding and source, edit it through the Content-mode UI, verify the saved MDX or referenced file, reload, and restore the test value. Record passed, failed, or not tested for each field. A correct preview, a successful MCP write, and one representative text edit do not prove the whole article is editable. Do not claim completion while required fields fail or remain untested.\n- Bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. Content mode\'s **Choose source** replaces the article\'s frontmatter image `$ref`; the resolved URL stays read-only. Verify selection, the saved reference, and reload instead of treating a missing write mode as a platform limitation. For alternative text bound to `.description`, use **Choose source → asset actions → Settings → Description** to edit shared Asset metadata. This affects every use of the Asset and is separate from replacing an article\'s image.\n\n## Make an article image replaceable in Content mode\n\nUse this for a persistent designed Image inside a connected Content Block,\nwith `featureImage: { $ref: "./images/hero.png" }` in its MDX frontmatter.\nRead the instance ID and document variable name before adapting the example.\n\nCommands:\n\n- MCP tool: bind-props {"bindings":[{"instanceId":"<imageInstanceId>","name":"src","binding":{"type":"expression","value":"document.frontmatter.featureImage.src","mode":"readwrite"}},{"instanceId":"<imageInstanceId>","name":"alt","binding":{"type":"expression","value":"document.frontmatter.featureImage.description","mode":"read"}}]}\n\nNotes:\n\n- The source mode must be explicit: the default `read` mode displays the image but prevents Content-mode replacement. Do not bind to query-result properties or add a fallback expression.\n- **Choose source** replaces the article\'s `featureImage.$ref`; the disabled resolved-URL input is expected. Do not store a resolved URL string or replace the shared Asset itself.\n- Shared alternative text is a separate action: **Choose source → asset actions → Settings → Description**. Its read-only binding does not require the image source binding to be read-only.\n- If the picker is missing or disabled, inspect the source mode, document scope, loaded reference, and permissions before claiming a product limitation.\n- Verify through Content mode with an approved temporary replacement. Check the saved `$ref`, unchanged unrelated MDX and original shared Asset, reload persistence, and restoration. If that test is not authorized, report it as not tested, not passed.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: bind-props {"bindings":[{"instanceId":"<jsonLdInstanceId>","name":"code","binding":{"type":"expression","value":"({ \'@context\': \'https://schema.org\', \'@type\': \'Article\', headline: post.title })"}}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- For fixed structured data, store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- For structured data containing runtime values, use `bind-props` with an expression that evaluates directly to an object or array. Do not call `JSON.stringify` or assemble JSON with string concatenation. Webstudio stores the expression as source text, evaluates it at runtime, and the `JsonLd` component validates and serializes the resulting value.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"verbose":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `verbose:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":{"--color-primary":"#2d3748","--color-accent":"#e53e3e","--space-card":"1.5rem"},"overwrite":true}\n\nNotes:\n\n- Define or overwrite multiple CSS variables atomically by including every name and value in one `vars` object.\n- Pass colors as CSS strings. Structured `hex` color components use normalized values from `0` to `1`, not `0` to `255`.\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":["--color-primary","--color-accent","--space-card"],"force":true}\n\nNotes:\n\n- Delete multiple CSS variables atomically by including every name in one `names` array. Destructive MCP calls still require the returned confirmation token before they commit.\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays and objects.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\'https://api.example.com/posts?tag=\' + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\'Bearer \' + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \'query Post($slug: String!) { post(slug: $slug) { title } }\', variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\n## Query Markdown assets\n\nCommands:\n\n- MCP tool: get-asset-field-catalog {}\n- MCP tool: validate-asset-query {"query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","draft"],"operator":"ne","value":true}]},"limit":20}}\n- MCP tool: create-assets-resource {"name":"All assets","scopeInstanceId":"<instanceId>","dataSourceName":"assets"}\n- MCP tool: create-assets-resource {"name":"Published posts","scopeInstanceId":"<instanceId>","dataSourceName":"posts","query":{"result":"many","where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","draft"],"operator":"ne","value":{"type":"literal","value":true}}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"}],"limit":{"type":"literal","value":20},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["properties","excerpt"]]},"content":{"mode":"none"}}}\n- MCP tool: create-assets-resource {"name":"Post by slug or ID","scopeInstanceId":"<instanceId>","dataSourceName":"post","query":{"result":"one","where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"}]},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","publishedAt"]]},"content":{"mode":"markdown-body-ref"}}}\n- MCP tool: list-assets-resources {}\n- MCP tool: get-assets-resource {"resourceId":"<resourceId>"}\n- MCP tool: update-assets-resource {"resourceId":"<resourceId>","values":{"query":null}}\n- MCP tool: preview-asset-query {"query":{"result":"one","where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","slug"],"operator":"eq","value":"hello-world"}]},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"]]},"content":{"mode":"markdown-body-ref"}}}\n\nNotes:\n\n- Read the field catalog before authoring unfamiliar queries. It includes dynamic schema-less frontmatter paths such as `properties.author.name`, observed types, optionality, and mixed-type state without downloading the source files.\n- Minimize the deployed content database by using `output.mode:"fields"` and selecting only fields the rendered page needs. Keep `includeMetadata:false` unless the rendered value needs file metadata such as name, path, MIME type, or creation date, and avoid `output.mode:"all"` as a convenience default. Query diagnostics are returned separately and do not require metadata output. Filters and sorting may still require their referenced fields in the database.\n- Every reachable Assets data source contributes to the shared published database. Keep one final resource per rendered query. Update an existing scoped resource rather than creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicates.\n- Keep bounded overview filters, limits, and offsets literal and add a deterministic ID tie-breaker to the sort. With `content.mode:"none"`, compilation can materialize the small overview result instead of retaining its output fields across every candidate document. Use runtime expressions only for genuinely dynamic values such as the detail slug.\n- Combine filters with `where.all` (AND) and `where.any` (OR), including nested groups. Filter values, limit, and offset on a saved resource may be Webstudio expressions evaluated at render time. Preview queries use concrete JSON values.\n- Query Markdown or MDX files directly and use `content.mode:"markdown-body-ref"` when rendering their bodies. The published database retains metadata and a document reference, then fetches only the selected files from Asset storage at runtime; it does not embed their bodies. Filter and paginate before content is loaded.\n- `full` and bounded `range` continue to request embedded file bytes. Use them only when the caller requires the complete source or a byte range.\n- In Markdown or MDX, reference sibling Assets with conventional relative URLs such as `../images/hero.png`. Deferred `markdown-body-ref` content resolves matching files against the document\'s folder and emits the correct Builder or published Asset URL. Keep external URLs absolute.\n- Markdown Embed renders sanitized authored HTML for figures, captions, audio, video, and iframes. Scripts, inline event handlers, `srcdoc`, and unsafe URL protocols are removed. It does not render Webstudio MDX elements; connect the `.mdx` file to a Content Block for that workflow.\n- Preview each query with concrete values before saving it. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes must not be summed and are not separate allowances. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A completed Markdown blog should include every source document without truncation, contain no embedded Markdown bodies, and retain only its intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files.\n- Use `result:"many"` for listings. It returns the ID-keyed map at `<dataSourceName>.data`, with `totalCount` and `hasMore` at `<dataSourceName>.meta`, and remains the default for existing queries. Bind a listing Collection to `posts.data`.\n- Use `result:"one"` for a unique detail route. It returns the selected item or `null` directly at `post.data`, always includes its `id`, and omits pagination. Bind components and page settings directly with expressions such as `post.data.properties.title`, `post.data.content.text`, and `post.data ? 200 : 404`. `result:"first"` and `result:"last"` also return a direct item or `null` but require explicit sorting.\n- Assets always executes a structured query. Omit `query` to use the default many-result query, which selects URL and optional image dimensions. Set `values.query:null` to restore it.\n- `create-assets-resource` and `update-assets-resource` are the semantic authoring path. Do not construct the internal query URL, headers, or body expression manually.\n- The shared metadata index is maintained automatically and is emitted only when a configured Assets resource is reachable.\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: list-assets {"verbose":true}\n\nNotes:\n\n- Compact results include each asset\'s folder id. Use `verbose:true` to include complete records for a page of assets, or `get-asset` to read one complete record including description, folder, creation time, and image/font metadata.\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Get asset\n\nCommands:\n\n- MCP tool: get-asset {"assetId":"<assetId>"}\n\n## List asset folders\n\nCommands:\n\n- MCP tool: list-asset-folders {}\n\n## Create asset folder\n\nCommands:\n\n- MCP tool: create-asset-folder {"name":"Marketing"}\n- MCP tool: create-asset-folder {"name":"Photos","parentId":"<parentFolderId>"}\n\n## Update asset folder\n\nCommands:\n\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"name":"Brand"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":"<parentFolderId>"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":null}}\n\nNotes:\n\n- Updating `parentId` is the folder equivalent of cut and paste. Use `null` to move a folder to Root.\n\n## Duplicate asset folder\n\nCommands:\n\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>"}\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>","parentId":"<targetFolderId>"}\n\nNotes:\n\n- Duplication recursively copies descendant folders and assets. This is the folder equivalent of copy and paste.\n\n## Delete asset folder\n\nCommands:\n\n- MCP tool: delete-asset-folder {"folderId":"<folderId>"}\n\nNotes:\n\n- Deleting a folder recursively deletes its descendant folders and assets.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n- MCP tool: update-asset {"assetId":"<fontAssetId>","values":{"meta":{"family":"Rajdhani","style":"normal","weight":600}}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n- Font metadata updates merge with the detected metadata and are validated before committing; use this to correct a family, style, or weight after upload.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","folderId":"<folderId>","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\nNotes:\n\n- Multi-file uploads return `uploaded`, `failed`, and `ambiguous` lists with the\n original input index. Retry only `failed` files. A forced upload in\n `ambiguous` may already be committed; inspect the Assets list before deciding\n whether to upload it again. Successful uploads remain committed.\n\n## Duplicate asset\n\nCommands:\n\n- MCP tool: duplicate-asset {"assetId":"<assetId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":"<targetFolderId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":null}\n\nNotes:\n\n- Duplication is the asset equivalent of copy and paste. Updating `folderId` is the equivalent of cut and paste; use `null` for Root.\n\n## Download asset\n\nCommands:\n\n- MCP tool: download-asset {"assetId":"<assetId>"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- webstudio search-project \'{"query":"pricing"}\'\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","namespaces":["resources"]}\n- MCP tool: search-project {"query":"Brand","namespaces":["styles","styleSources","styleSourceSelections"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- `search-project` is a standalone local-session command over every Builder namespace. It returns matching values with stable match ids, namespace paths, owning entities, references, and affected pages.\n- Use it when a value or id is known. Use list/get tools when the project structure or target is not known.\n- The command synchronizes its required Builder namespaces, then searches locally and returns only matches. Namespace filters limit values matched; related namespaces may still supply route and reference context, and synchronization is unchanged. This reduces data passed to the model, not the initial project-data synchronization.\n- Asset records and file metadata are searchable. Asset binary or document contents are not Builder namespace data and are not searched.\n- Values in recognized credential fields are excluded and counted in `excludedSensitiveValueCount`.\n- Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility --scopes seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- webstudio audit --rendered --page-path /pricing --json\n- webstudio audit --rendered --route-example post=/blog/hello --json\n- webstudio audit --rendered --image-domain images.example.com --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"scopes":["craft"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`\n (or MCP `routeExamples`) supplies a concrete path. The path must not contain\n unresolved `:` or `*` parameters.\n- Plans above 120 captures return a short-lived confirmation token. Review the\n unchanged plan, then rerun with `--confirm-large-run` and\n `--confirmation-token`.\n- Detailed rendered evidence is stored in a versioned manifest under\n `.webstudio/audits`; compact output includes its path and screenshot count.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Verify dynamic bindings\n\nCommands:\n\n- webstudio verify-bindings --json\n- MCP tool: verify-bindings {"pagePath":"/pricing"}\n- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}\n\nNotes:\n\n- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.\n- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.\n- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.\n- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"\\"Pricing\\"","meta":{"description":"\\"Plans\\""}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"\\"Pricing\\"","meta":{"description":"\\"Plans\\""}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \'query Post($slug: String!) { post(slug: $slug) { title } }\', variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Render an array or object as repeated content\n\nCommands:\n\n- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<article><h2>{expression`collectionItem.title`}</h2></article>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\n\nNotes:\n\n- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.\n- Pass `insert-collection` the complete array or object. Do not pass the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result\'s `data` field or deeper.\n- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\n- Wrap multiple repeated sibling instances in one Element inside Collection.\n- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.\n- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.\n- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.\n- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.\n- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page","taskScope":"structural-project-change","workflow":"authenticated-page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Inspect and reuse the project\'s existing auth convention before authoring. Do\n not add a second provider or session model implicitly.\n- Model signed-out, loading, signed-in, and failed-auth states explicitly.\n- Never store credentials, service-role keys, refresh tokens, private session\n values, or authenticated response bodies in project data, command output,\n screenshots, agent instructions, or error reports. Privileged provider calls\n and authorization enforcement belong server-side.\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still\n uses the existing resource, variable, prop, binding, and embed tools; there is\n no provider-specific installer.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page","taskScope":"visual-change","workflow":"design-input"}\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<section><p>Section copy</p></section>"}\n- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpoint":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {}\n- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after the agent can inspect the supplied design. There is no direct\n Figma, screenshot, Inception, or `design.md` import command.\n- Inspect and reuse existing variables, tokens, styles, components, assets, and\n page patterns before authoring. Build semantic editable structure rather than\n flattening the design into an image or absolute-positioned approximation.\n- Ask whether the user wants visual verification unless they explicitly requested\n it. If they decline, stop after focused reads and a static audit. If they opt\n in, verify one familiar viewport inside every distinct Builder breakpoint\n range, then run rendered audit and inspect the screenshots before completion.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio mcp run .temp/projects.json\n- webstudio mcp run .temp/projects.json --dry-run\n- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2\n\nNotes:\n\n- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.\n- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.\n- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCall `meta.guide` with `workflow:"authenticated-page"`, then create the\npage, resources, variables, props, bindings, and embeds with existing semantic\ntools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nCall `meta.guide` with `workflow:"design-input"`, let the agent inspect the supplied\ndesign, then use semantic page, token, asset, fragment, style, preview,\nscreenshot, and audit tools. Use `apply-patch` only when no semantic operation\nfits.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',+ '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get-more-tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get-more-tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search values and ids across every Builder namespace without sending full project data to the model.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nested asset folders and upload, inspect, move, duplicate, download, replace, delete, and inspect usage for assets.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Enter this workflow only when the user explicitly requests visual verification or opts in after being asked. Do not start preview, screenshots, diffs, OCR, or rendered audits automatically after a mutation.\n- `preview.status` reports whether generated output is `stale`. When no preview is running, `url`, `pid`, and `mode` are omitted. When present, `renderedProjectVersion` is the last project version materialized into the preview.\n- MCP preview and path-based screenshot tools select an available loopback port and return the preview URL. Do not pass `host` or `port`.\n- A managed `screenshot` or another `preview.start` refreshes stale generated output before capture.\n\n- After opt-in, use this so a vision-capable AI can see the generated site from the current MCP session. Use `path`; never pass a Webstudio Builder/share URL or capture Builder chrome.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- Iterative mode is the default: after MCP mutations, path screenshots ensure generated project files are current, wait for the exact session version, and perform an ordinary page reload without Vite HMR. The preview server and browser stay alive. Use `{"mode":"production"}` only for release-like verification; rendered audit does this automatically.\n- Calling `preview.start` after a committed mutation restarts a stale iterative server so external browsers and HTTP clients receive the newly generated project.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- The screenshot timeout bounds browser capture after the preview is ready. A timeout returns `SCREENSHOT_TIMEOUT`, resets the reusable browser session, and releases the shared preview lifecycle for cleanup.\n- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- When launcher metadata is available, Preview reuses a supported npm or pnpm launcher. Without launcher metadata, it uses npm when available and otherwise falls back to pnpm.\n- Unless `npm_config_cache` is already configured, npm uses the writable `.webstudio/preview/.npm-cache` directory.\n- For npm cache permission errors, unset `npm_config_cache` to use the preview-local cache, then retry. No cache deletion is required.\n- If dependency installation fails, check the reported package-manager path and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"\\"Pricing\\"","meta":{"description":"\\"Plans for teams\\""}}\n\nNotes:\n\n- `name` and `path` are plain values. Page `title` and metadata text fields contain expression source; quote fixed text as a JavaScript string literal inside the JSON string.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`. An unquoted word is a variable reference.\n- CLI flags such as `--title` treat values as fixed text. Add `--expressions` to `webstudio create-page` when passing expression source through these flags; quote any fixed text in the same call as a JavaScript string expression.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"\\"Pricing\\"","meta":{"description":"\\"Plans\\"","status":200}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- For fixed page `title` and metadata text, quote the text as a JavaScript string literal inside the JSON string.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`. An unquoted word is a variable reference.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599 or a JavaScript expression string for a dynamic status.\n- For `webstudio update-page`, add `--expressions` when page title or metadata flags contain expression source. Without it, those flags are fixed text.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## Submit marketplace product\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"marketplace-thumbnail.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"<uploadedAssetId>","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: publish {"target":"production"}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nNotes:\n\n- Wait for the production publish to complete before submitting the product for review.\n- Submission requires complete, valid marketplace metadata.\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}\n- webstudio duplicate-page --page <pageId> --name Paris --path /paris --substitutions \'{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}\' --json\n\nNotes:\n\n- Text substitutions replace exact fixed text only in the duplicated page\'s text children, string props, title, and metadata.\n- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.\n- Existing expressions and cloned variable/resource references keep their remapped ids.\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"\\"Landing\\""}\n\nCLI `create-page-template` and `update-page-template` use fixed text flags by default. Add `--expressions` when passing expression source through title or metadata flags.\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {}\n- MCP tool: list-pages {}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<section ws:style={css`padding: 32px;`}><h2>Product OS</h2><Switch><SwitchThumb /></Switch></section>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- Use lowercase HTML JSX such as `<div>` and `<form>`. The internal `ws:` namespace is not HTML-tag shorthand.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use ``ws:style={css`...`}`` for Webstudio-native CSS, or use React-style object syntax such as `style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<Switch><SwitchThumb /></Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside exactly one direct `ws:block-template` child. A missing or second template container makes the Content Block invalid. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before implementation, inventory every editor-owned field and its intended control and write destination, whether or not the block uses MDX. Check that templates contain the required styling, but do not treat containment or a successful text edit as proof that the whole block is editable. Test every field through Content mode, inspect its saved project data or source file, reload, and restore the original value. Report passed, failed, or not tested for each field; missing or read-only required controls are unfinished requirements.\n- Use controls that match the content: a calendar for dates and an image picker for image replacement. Keep fixed punctuation and units out of directly bound value elements. Preserve stored types and wording: when reading time is already a complete string such as `4 min read`, bind that string directly rather than assuming it is a number.\n- For MDX-backed blocks, containment alone is not enough: the MDX body is editable through its source mapping, but the designed shell needs writable document-frontmatter bindings. Follow the binding recipe below rather than binding editable article fields to query results.\n\n## Store Content Block content in MDX\n\nCommands:\n\n- MCP tool: list-assets {"type":"file"}\n- MCP tool: upload-asset {"asset":{"name":"article.mdx","type":"file","format":"mdx","meta":{}},"assetsDir":".webstudio/assets"}\n- MCP tool: connect-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":{"type":"asset","assetId":"<mdxAssetId>"}}\n- MCP tool: switch-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":{"type":"asset","assetId":"<otherMdxAssetId>"}}\n- MCP tool: inspect-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\n- MCP tool: edit-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":"# Article title\\n\\nArticle body."}\n- MCP tool: update-content-block-frontmatter {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","properties":{"title":"Article title","draft":false}}\n- MCP tool: reload-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\n- MCP tool: migrate-content-block-template-references {"assetIds":["<mdxAssetId>"],"migration":{"type":"rename","from":"Old template name","to":"New template name"}}\n- MCP tool: disconnect-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\n\nNotes:\n\n- Create the local `.mdx` file under `.webstudio/assets` before calling `upload-asset`. Use the returned Asset ID when connecting it.\n- Use the Content Block source operations for connecting, switching, inspecting, editing, reloading, and disconnecting. Do not create or delete the `src` prop with generic prop tools; the source operations preserve the Body outlet and Content Block lifecycle.\n- `renderScope` accepts any non-empty stable key for one rendered occurrence. Use a page-based key for a direct Content Block and a distinct key for each repeated Collection occurrence. It does not load a page, route parameters, or resource results. Supply the concrete scoped values needed to resolve an expression through `variables`.\n- For a result-one Assets resource, preview the concrete query, then connect its persisted expression with the previewed item supplied as `variables`, for example `source:{"type":"expression","value":"post.data.id"}` and `variables:{"post":{"data":{"id":"<mdxAssetId>"}}}`.\n- Connecting replaces existing Body content. If the result returns `requiresConfirmation:true`, report that replacement to the user and repeat the same call with `confirmReplacement:true` only after approval.\n- Prefer Markdown for standard document content; it automatically uses a unique matching semantic template when one exists. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG with authored properties that Markdown cannot express.\n- Verify that the Content Block has exactly one direct Templates container before connecting or editing MDX. Zero or multiple containers block materialization and publication.\n- Read the Content Block\'s Templates children before writing a custom reference. Use capitalized JSX such as `<PromotionCard />` for its stable **Name**, which is independent from the display label. A matching template wins over a built-in MDX adapter. Other registered components are unavailable until added to this Content Block\'s Templates. JSX attributes accept quoted static values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported.\n- When explicit JSX children match the designed template structure, their text and supported props overlay the cloned descendants and retain template styles. A mismatched child structure replaces the root defaults, while each authored child still resolves through a matching template when possible. An explicit empty pair clears defaults, and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live, so adding a matching semantic or named template later updates existing MDX. Preserve unresolved names and report their diagnostics instead of deleting them.\n- When a template is renamed or deleted, use `migrate-content-block-template-references` to update a selected set of affected MDX files. The first call returns a plan. Report its changed-file, update, omission, and diagnostic counts, then repeat the exact request with its `confirmationToken` only after approval. Renames and removals update named JSX and legacy `ws:name` references, including names such as `Image` and `CodeText` when they identify templates. Rename targets must be valid PascalCase JSX identifiers. Removing a paired reference unwraps and preserves its authored children; removing a self-closing reference removes the node because it has no authored children. Invalid files remain unchanged and are reported in diagnostics.\n- `edit-content-block-source` replaces the complete MDX source. Preserve frontmatter and unrelated source when making a bounded edit.\n- `update-content-block-frontmatter` replaces the complete frontmatter mapping. Inspect the current source first and include every property that must remain.\n- Store frontmatter images as exact `$ref` objects. Bind an editable Image source to the resolved `.src` with explicit `binding.mode:"readwrite"`; use `mode:"read"` for its alt binding to `.description`. Omitting the source mode leaves the image visible but not replaceable in Content mode.\n- Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document\'s frontmatter. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings.\n- Inspect every returned diagnostic. Invalid MDX is saved rather than silently repaired; preserve the source, report the source range, and fix only the requested or invalid part.\n- If an edit in a long-lived MCP session reports a conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly.\n\n## Make an MDX article header editable\n\nUse the resource only to select the connected source, for example `post.data.id`.\nBind article values inside the Content Block to its document parameter instead\nof `post.data.properties.*`. Inspect the block\'s variables first; `document` is\nthe default name, not a name to assume.\n\nThese commands target persistent designed instances inside the connected block.\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<headingInstanceId>","childIndex":0,"text":"document.frontmatter.title","mode":"expression","expressionBindingMode":"readwrite"}\n- MCP tool: update-text {"instanceId":"<readingTimeValueInstanceId>","childIndex":0,"text":"document.frontmatter.readingTime","mode":"expression","expressionBindingMode":"readwrite"}\n- MCP tool: bind-props {"bindings":[{"instanceId":"<dateInstanceId>","name":"datetime","binding":{"type":"expression","value":"document.frontmatter.publishedAt","mode":"readwrite"}}]}\n\nNotes:\n\n- Create writable bindings explicitly; the default is read-only. Merely moving a heading or Link inside the Content Block does not make its query-bound text editable.\n- The MDX body uses its source mapping. Static designed content outside that body remains protected unless its text or supported props bind to writable frontmatter fields. Do not apply these generic instance tools to MDX-generated instances.\n- Use direct static paths. Property access is already safe. Fallbacks and formatted expressions, such as `document.frontmatter.title ?? "Untitled"`, remain read-only.\n- Keep every intended editable value in its own text element with a single direct read-write binding. For reading time, use three inline siblings: static `— `, the bound reading-time value, and static ` min read`. Preserve whitespace and the stored field type. Do not combine them into a template literal or concatenate strings, and do not put literal siblings inside the value element itself. Keep fixed wording protected in the designed shell.\n- Prefer component formatting controls, such as Date Time formatting with a directly bound date prop, over transforming the expression. Do not silently sacrifice editability for formatting or a fallback; explain unsupported cases and ask before making an intended editable field read-only.\n- A direct writable binding such as `document.frontmatter.author.name` can edit a shared author loaded through `../authors/oleg.md#frontmatter`. The edit saves to the author file and affects every article using it; preserve the article\'s `$ref` marker.\n- Before handoff, inventory every article-owned field, including header text, author details, dates, reading time, categories, hero and inline image sources, alternative text, captions, links, and custom-component content. For each field, inspect its binding and source, edit it through the Content-mode UI, verify the saved MDX or referenced file, reload, and restore the test value. Record passed, failed, or not tested for each field. A correct preview, a successful MCP write, and one representative text edit do not prove the whole article is editable. Do not claim completion while required fields fail or remain untested.\n- Bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. Content mode\'s **Choose source** replaces the article\'s frontmatter image `$ref`; the resolved URL stays read-only. Verify selection, the saved reference, and reload instead of treating a missing write mode as a platform limitation. For alternative text bound to `.description`, use **Choose source → asset actions → Settings → Description** to edit shared Asset metadata. This affects every use of the Asset and is separate from replacing an article\'s image.\n\n## Make an article image replaceable in Content mode\n\nUse this for a persistent designed Image inside a connected Content Block,\nwith `featureImage: { $ref: "./images/hero.png" }` in its MDX frontmatter.\nRead the instance ID and document variable name before adapting the example.\n\nCommands:\n\n- MCP tool: bind-props {"bindings":[{"instanceId":"<imageInstanceId>","name":"src","binding":{"type":"expression","value":"document.frontmatter.featureImage.src","mode":"readwrite"}},{"instanceId":"<imageInstanceId>","name":"alt","binding":{"type":"expression","value":"document.frontmatter.featureImage.description","mode":"read"}}]}\n\nNotes:\n\n- The source mode must be explicit: the default `read` mode displays the image but prevents Content-mode replacement. Do not bind to query-result properties or add a fallback expression.\n- **Choose source** replaces the article\'s `featureImage.$ref`; the disabled resolved-URL input is expected. Do not store a resolved URL string or replace the shared Asset itself.\n- Shared alternative text is a separate action: **Choose source → asset actions → Settings → Description**. Its read-only binding does not require the image source binding to be read-only.\n- If the picker is missing or disabled, inspect the source mode, document scope, loaded reference, and permissions before claiming a product limitation.\n- Verify through Content mode with an approved temporary replacement. Check the saved `$ref`, unchanged unrelated MDX and original shared Asset, reload persistence, and restoration. If that test is not authorized, report it as not tested, not passed.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: bind-props {"bindings":[{"instanceId":"<jsonLdInstanceId>","name":"code","binding":{"type":"expression","value":"({ \'@context\': \'https://schema.org\', \'@type\': \'Article\', headline: post.title })"}}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- For fixed structured data, store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- For structured data containing runtime values, use `bind-props` with an expression that evaluates directly to an object or array. Do not call `JSON.stringify` or assemble JSON with string concatenation. Webstudio stores the expression as source text, evaluates it at runtime, and the `JsonLd` component validates and serializes the resulting value.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"verbose":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `verbose:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":{"--color-primary":"#2d3748","--color-accent":"#e53e3e","--space-card":"1.5rem"},"overwrite":true}\n\nNotes:\n\n- Define or overwrite multiple CSS variables atomically by including every name and value in one `vars` object.\n- Pass colors as CSS strings. Structured `hex` color components use normalized values from `0` to `1`, not `0` to `255`.\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":["--color-primary","--color-accent","--space-card"],"force":true}\n\nNotes:\n\n- Delete multiple CSS variables atomically by including every name in one `names` array. Destructive MCP calls still require the returned confirmation token before they commit.\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays and objects.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\'https://api.example.com/posts?tag=\' + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\'Bearer \' + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \'query Post($slug: String!) { post(slug: $slug) { title } }\', variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\n## Query Markdown assets\n\nCommands:\n\n- MCP tool: get-asset-field-catalog {}\n- MCP tool: validate-asset-query {"query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","draft"],"operator":"ne","value":true}]},"limit":20}}\n- MCP tool: create-assets-resource {"name":"All assets","scopeInstanceId":"<instanceId>","dataSourceName":"assets"}\n- MCP tool: create-assets-resource {"name":"Published posts","scopeInstanceId":"<instanceId>","dataSourceName":"posts","query":{"result":"many","where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","draft"],"operator":"ne","value":{"type":"literal","value":true}}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"}],"limit":{"type":"literal","value":20},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["properties","excerpt"]]},"content":{"mode":"none"}}}\n- MCP tool: create-assets-resource {"name":"Post by slug or ID","scopeInstanceId":"<instanceId>","dataSourceName":"post","query":{"result":"one","where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"}]},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","publishedAt"]]},"content":{"mode":"markdown-body-ref"}}}\n- MCP tool: list-assets-resources {}\n- MCP tool: get-assets-resource {"resourceId":"<resourceId>"}\n- MCP tool: update-assets-resource {"resourceId":"<resourceId>","values":{"query":null}}\n- MCP tool: preview-asset-query {"query":{"result":"one","where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","slug"],"operator":"eq","value":"hello-world"}]},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"]]},"content":{"mode":"markdown-body-ref"}}}\n\nNotes:\n\n- Choose `.mdx` connected to a Content Block when editors must edit article bodies visually in Content mode. Publishing downloads and compiles every reachable MDX article, so more articles can slow publishing. Choose `.md` with Markdown Embed when editing the source in Assets is enough; Content mode editors can still edit the Markdown file there, but not its body on the canvas. `.md` needs no per-article MDX compilation, though the publish runner still synchronizes Asset files for both formats and static generation may read Markdown bodies.\n- Read the field catalog before authoring unfamiliar queries. It includes dynamic schema-less frontmatter paths such as `properties.author.name`, observed types, optionality, and mixed-type state without downloading the source files.\n- Minimize the deployed content database by using `output.mode:"fields"` and selecting only fields the rendered page needs. Keep `includeMetadata:false` unless the rendered value needs file metadata such as name, path, MIME type, or creation date, and avoid `output.mode:"all"` as a convenience default. Query diagnostics are returned separately and do not require metadata output. Filters and sorting may still require their referenced fields in the database.\n- Every reachable Assets data source contributes to the shared published database. Keep one final resource per rendered query. Update an existing scoped resource rather than creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicates.\n- Keep bounded overview filters, limits, and offsets literal and add a deterministic ID tie-breaker to the sort. With `content.mode:"none"`, compilation can materialize the small overview result instead of retaining its output fields across every candidate document. Use runtime expressions only for genuinely dynamic values such as the detail slug.\n- Combine filters with `where.all` (AND) and `where.any` (OR), including nested groups. Filter values, limit, and offset on a saved resource may be Webstudio expressions evaluated at render time. Preview queries use concrete JSON values.\n- Query Markdown or MDX files directly and use `content.mode:"markdown-body-ref"` when rendering their bodies. The published database retains metadata and a document reference, then fetches only the selected files from Asset storage at runtime; it does not embed their bodies. Filter and paginate before content is loaded.\n- `full` and bounded `range` continue to request embedded file bytes. Use them only when the caller requires the complete source or a byte range.\n- In Markdown or MDX, reference sibling Assets with conventional relative URLs such as `../images/hero.png`. Deferred `markdown-body-ref` content resolves matching files against the document\'s folder and emits the correct Builder or published Asset URL. Keep external URLs absolute.\n- Markdown Embed renders sanitized authored HTML for figures, captions, audio, video, and iframes. Scripts, inline event handlers, `srcdoc`, and unsafe URL protocols are removed. It does not render Webstudio MDX elements; connect the `.mdx` file to a Content Block for that workflow.\n- Preview each query with concrete values before saving it. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes must not be summed and are not separate allowances. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A completed Markdown blog should include every source document without truncation, contain no embedded Markdown bodies, and retain only its intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files.\n- Use `result:"many"` for listings. It returns the ID-keyed map at `<dataSourceName>.data`, with `totalCount` and `hasMore` at `<dataSourceName>.meta`, and remains the default for existing queries. Bind a listing Collection to `posts.data`.\n- Use `result:"one"` for a unique detail route. It returns the selected item or `null` directly at `post.data`, always includes its `id`, and omits pagination. Bind components and page settings directly with expressions such as `post.data.properties.title`, `post.data.content.text`, and `post.data ? 200 : 404`. `result:"first"` and `result:"last"` also return a direct item or `null` but require explicit sorting.\n- Assets always executes a structured query. Omit `query` to use the default many-result query, which selects URL and optional image dimensions. Set `values.query:null` to restore it.\n- `create-assets-resource` and `update-assets-resource` are the semantic authoring path. Do not construct the internal query URL, headers, or body expression manually.\n- The shared metadata index is maintained automatically and is emitted only when a configured Assets resource is reachable.\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: list-assets {"verbose":true}\n\nNotes:\n\n- Compact results include each asset\'s folder id. Use `verbose:true` to include complete records for a page of assets, or `get-asset` to read one complete record including description, folder, creation time, and image/font metadata.\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Get asset\n\nCommands:\n\n- MCP tool: get-asset {"assetId":"<assetId>"}\n\n## List asset folders\n\nCommands:\n\n- MCP tool: list-asset-folders {}\n\n## Create asset folder\n\nCommands:\n\n- MCP tool: create-asset-folder {"name":"Marketing"}\n- MCP tool: create-asset-folder {"name":"Photos","parentId":"<parentFolderId>"}\n\n## Update asset folder\n\nCommands:\n\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"name":"Brand"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":"<parentFolderId>"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":null}}\n\nNotes:\n\n- Updating `parentId` is the folder equivalent of cut and paste. Use `null` to move a folder to Root.\n\n## Duplicate asset folder\n\nCommands:\n\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>"}\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>","parentId":"<targetFolderId>"}\n\nNotes:\n\n- Duplication recursively copies descendant folders and assets. This is the folder equivalent of copy and paste.\n\n## Delete asset folder\n\nCommands:\n\n- MCP tool: delete-asset-folder {"folderId":"<folderId>"}\n\nNotes:\n\n- Deleting a folder recursively deletes its descendant folders and assets.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n- MCP tool: update-asset {"assetId":"<fontAssetId>","values":{"meta":{"family":"Rajdhani","style":"normal","weight":600}}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n- Font metadata updates merge with the detected metadata and are validated before committing; use this to correct a family, style, or weight after upload.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","folderId":"<folderId>","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\nNotes:\n\n- Multi-file uploads return `uploaded`, `failed`, and `ambiguous` lists with the\n original input index. Retry only `failed` files. A forced upload in\n `ambiguous` may already be committed; inspect the Assets list before deciding\n whether to upload it again. Successful uploads remain committed.\n\n## Duplicate asset\n\nCommands:\n\n- MCP tool: duplicate-asset {"assetId":"<assetId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":"<targetFolderId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":null}\n\nNotes:\n\n- Duplication is the asset equivalent of copy and paste. Updating `folderId` is the equivalent of cut and paste; use `null` for Root.\n\n## Download asset\n\nCommands:\n\n- MCP tool: download-asset {"assetId":"<assetId>"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- webstudio search-project \'{"query":"pricing"}\'\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","namespaces":["resources"]}\n- MCP tool: search-project {"query":"Brand","namespaces":["styles","styleSources","styleSourceSelections"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- `search-project` is a standalone local-session command over every Builder namespace. It returns matching values with stable match ids, namespace paths, owning entities, references, and affected pages.\n- Use it when a value or id is known. Use list/get tools when the project structure or target is not known.\n- The command synchronizes its required Builder namespaces, then searches locally and returns only matches. Namespace filters limit values matched; related namespaces may still supply route and reference context, and synchronization is unchanged. This reduces data passed to the model, not the initial project-data synchronization.\n- Asset records and file metadata are searchable. Asset binary or document contents are not Builder namespace data and are not searched.\n- Values in recognized credential fields are excluded and counted in `excludedSensitiveValueCount`.\n- Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility --scopes seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- webstudio audit --rendered --page-path /pricing --json\n- webstudio audit --rendered --route-example post=/blog/hello --json\n- webstudio audit --rendered --image-domain images.example.com --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"scopes":["craft"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`\n (or MCP `routeExamples`) supplies a concrete path. The path must not contain\n unresolved `:` or `*` parameters.\n- Plans above 120 captures return a short-lived confirmation token. Review the\n unchanged plan, then rerun with `--confirm-large-run` and\n `--confirmation-token`.\n- Detailed rendered evidence is stored in a versioned manifest under\n `.webstudio/audits`; compact output includes its path and screenshot count.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Verify dynamic bindings\n\nCommands:\n\n- webstudio verify-bindings --json\n- MCP tool: verify-bindings {"pagePath":"/pricing"}\n- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}\n\nNotes:\n\n- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.\n- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.\n- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.\n- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"\\"Pricing\\"","meta":{"description":"\\"Plans\\""}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"\\"Pricing\\"","meta":{"description":"\\"Plans\\""}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \'query Post($slug: String!) { post(slug: $slug) { title } }\', variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Render an array or object as repeated content\n\nCommands:\n\n- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<article><h2>{expression`collectionItem.title`}</h2></article>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\n\nNotes:\n\n- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.\n- Pass `insert-collection` the complete array or object. Do not pass the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result\'s `data` field or deeper.\n- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\n- Wrap multiple repeated sibling instances in one Element inside Collection.\n- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.\n- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.\n- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.\n- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.\n- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page","taskScope":"structural-project-change","workflow":"authenticated-page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Inspect and reuse the project\'s existing auth convention before authoring. Do\n not add a second provider or session model implicitly.\n- Model signed-out, loading, signed-in, and failed-auth states explicitly.\n- Never store credentials, service-role keys, refresh tokens, private session\n values, or authenticated response bodies in project data, command output,\n screenshots, agent instructions, or error reports. Privileged provider calls\n and authorization enforcement belong server-side.\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still\n uses the existing resource, variable, prop, binding, and embed tools; there is\n no provider-specific installer.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page","taskScope":"visual-change","workflow":"design-input"}\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<section><p>Section copy</p></section>"}\n- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpoint":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {}\n- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after the agent can inspect the supplied design. There is no direct\n Figma, screenshot, Inception, or `design.md` import command.\n- Inspect and reuse existing variables, tokens, styles, components, assets, and\n page patterns before authoring. Build semantic editable structure rather than\n flattening the design into an image or absolute-positioned approximation.\n- Ask whether the user wants visual verification unless they explicitly requested\n it. If they decline, stop after focused reads and a static audit. If they opt\n in, verify one familiar viewport inside every distinct Builder breakpoint\n range, then run rendered audit and inspect the screenshots before completion.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio mcp run .temp/projects.json\n- webstudio mcp run .temp/projects.json --dry-run\n- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2\n\nNotes:\n\n- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.\n- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.\n- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCall `meta.guide` with `workflow:"authenticated-page"`, then create the\npage, resources, variables, props, bindings, and embeds with existing semantic\ntools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nCall `meta.guide` with `workflow:"design-input"`, let the agent inspect the supplied\ndesign, then use semantic page, token, asset, fragment, style, preview,\nscreenshot, and audit tools. Use `apply-patch` only when no semantic operation\nfits.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',"manual-api":'# Webstudio API CLI Manual\n\nThe API commands operate on the single project configured by:\n\n- .webstudio/config.json: projectId\n- global Webstudio config: origin and token\n\n- Pass --json to API/discovery commands that support it. Do not add --json to top-level commands unless their help/schema documents it.\n- Never pass a project id. Commands use configured project only.\n- Read ids before writing. Do not invent ids for existing records.\n- stdout is one JSON object. stderr is diagnostics.\n- Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.\n\n## Start\n\n{{start}}\n\n## Read First\n\n{{readFirst}}\n\n## Project Session Cache\n\n- CLI commands use one local ProjectSession snapshot for the configured project.\n- Local-capable reads use cached namespaces when compatible and fetch only missing or stale namespaces.\n- Local-capable mutations build patches from the local snapshot, then commit with the cached build version.\n- Successful mutation commits update the local snapshot only after the remote commit succeeds.\n- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.\n- Use --refresh on local-capable commands to refresh required namespaces before running.\n- Successful JSON responses include compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.\n\n## Search project data\n\nRun `webstudio search-project \'{"query":"known value"}\'` to search all Builder\nnamespaces in the local project session. Narrow it with\n`{"query":"Brand","namespaces":["styleSources","styles"]}` when only specific\nnamespaces are relevant. Results contain the current value, stable match id,\nnamespace path, owning entity, resolved references, and affected pages.\n\nValues in recognized credential fields are excluded and reported in\n`excludedSensitiveValueCount`.\n\nThe command synchronizes its required Builder namespaces, then searches locally\nand returns only matches. Namespace filters limit values matched; related\nnamespaces may still supply route and reference context, and synchronization is\nunchanged. This reduces data sent to the model, not project synchronization. It\nsearches asset metadata, not asset binaries or document contents.\n\n## CLI Capability Inventory\n\nFor a short end-consumer summary of what MCP can do, see\n`manual mcp` / `webstudio man mcp`. The MCP inventory describes the same\nproject, page, element, style, data, asset, publish, domain, and visual\nverification capabilities without internal command names.\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP Tool Operations\n\nThese are MCP tools. From a shell, call them with the shortcut form `webstudio <tool> \'<json>\'` or with the explicit form `webstudio mcp single-op-call <tool> \'<json>\'`:\n\n{{mcpOnlyCommandIndex}}\n\n## Task Recipes\n\n{{taskRecipeIndex}}\n\n## Use Case Index\n\n{{useCaseIndex}}\n\n## Known CLI Gaps\n\n{{knownCliGapIndex}}\n\n## Input File Shapes\n\n{{inputFileShapeIndex}}\n\n## Raw Patch Fallback\n\napply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.\n\nEach transaction has:\n\n{\n"id": "patch-transaction-label",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\n\nThe transaction id is a patch label used for optimistic synchronization. It is\nnot a Builder record id. Do not invent ids for pages, instances, props,\nbreakpoints, resources, variables, folders, assets, or other project records.\n\nPatch paths are JSON-patch-like paths into Builder store data. Map-like namespaces use ids as the first path item.\n\nSupported namespaces:\n\n- pages: redirects, page records, and folders\n- projectSettings: project-wide metadata and compiler settings\n- instances: element instances and children, including text/expression children\n- props: element props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and reusable design tokens\n- styleSourceSelections: instance-to-style-source connections\n- dataSources: data variables, parameters, and resource data sources\n- resources: data resource definitions\n- assets: project asset records handled by the existing asset patch path\n- breakpoints: responsive breakpoints\n- marketplaceProduct: marketplace metadata\n\n## Data Sources\n\n`dataSources` is the internal Builder namespace for variables. Public API, CLI,\nand MCP tools expose it through two user-facing groups:\n\n- data variables: `list-variables`, `create-variable`, `update-variable`, and\n `delete-variable`\n- data resources: `list-resources`, `create-resource`, `update-resource`, and\n `delete-resource`\n\nFor raw `snapshot`, request the public `variables` namespace rather than the\ninternal `dataSources` name. Raw patch payloads still use `dataSources` when\napplying direct changes.\n\nVariables can be scoped to an instance. Expressions under that instance can use\nthe variable by name; nested variables with the same name mask outer variables.\nVariable values support `string`, `number`, `boolean`, and `json`. Use `json`\nfor all arrays and objects, including tags, selected categories, and nested API\nfilter state.\nParameters are internal scoped runtime values provided by pages, collections,\nor components. They are not a public authoring surface: do not create, update,\nor delete parameter records. Public tools should preserve existing parameter\nrecords and may reference documented context values such as `system` in\nexpressions where they are already in scope.\n\nResource `url` accepts plain fixed URLs and paths, for example\n`https://api.example.com/posts` or `/$resources/current-date`. Dynamic URLs can\ncombine strings and variables, for example\n`"https://api.example.com/posts?tag=" + filters.tag`. Prefer `searchParams` for\nquery parameters that should be encoded separately:\n`[{ "name": "tag", "value": "filters.tag" }]`. Header values, search parameter\nvalues, and bodies are expressions for dynamic content. For fixed text, use\n`{ "type": "literal", "value": "application/json" }`; Webstudio stores the\nrequired string expression. Headers can still read variables such as\n`"Bearer " + auth.token`, and GraphQL bodies can return objects such as\n`{ query: "...", variables: { slug: system.params.slug } }`.\n\nCreate a GET resource with `scopeInstanceId` when the fetched resource result\nshould be available as a read data variable. Scoped GET resources default to\n`exposeAsDataSource: true`, are generated into the page resource `data` map,\nand may be loaded during page rendering. Use `dataSourceName` to choose the\nvariable name.\n\nFor submit/write/action resources, create the resource without\n`scopeInstanceId`, then bind a component prop such as a Form `action` to the\nresource with `bind-props` and `binding.type: "resource"`. Prop-bound resources\nare generated into the page resource `action` map instead of the read `data`\nmap. Use this shape for POST, PUT, DELETE, webhook, and other resources that\nshould run only from an explicit form/action flow, not merely because the page\nrendered.\n\nPOST, PUT, and DELETE resources default to `exposeAsDataSource: false` even\nwhen a scope is supplied. Set `exposeAsDataSource: true` only when a write-method\nresource intentionally provides render-time data, such as a read-only GraphQL\nPOST query. A scope is required, and the result includes a warning because the\nrequest may execute during page rendering. Set `exposeAsDataSource: false` on\n`update-resource` to detach an existing render-time data source.\n\nResource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read\ndata. Use POST for creates, GraphQL requests, webhooks, and form submissions.\nUse PUT for full updates/replacements. Use DELETE for deletion actions.\nOptional `control` values are `graphql` and `system`: `graphql` marks a\nGraphQL-style resource, usually POST with a query body; `system` marks a\nresource intended to use the built-in `system` parameter or one of the built-in\nlocal resource URLs: `"/$resources/sitemap.xml"`,\n`"/$resources/current-date"`, and `"/$resources/assets"`. The system parameter\nfields are `system.origin`, `system.pathname`, `system.params`, and\n`system.search`.\n\nUse prop bindings for dynamic values that read variables or resources; use\ndirect props for static values.\n\nCommit raw patch:\n\nMCP tool: apply-patch\n\n## Raw Patch Examples\n\nRename the site:\n\n[\n{\n"id": "patch-site-name",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "add", "path": ["meta", "siteName"], "value": "Acme Studio" }\n]\n}\n]\n}\n]\n\nUpdate page title metadata:\n\n[\n{\n"id": "patch-page-title",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["pages", "page-id", "meta", "title"], "value": "Pricing" }\n]\n}\n]\n}\n]\n\nUpdate a text child on an element:\n\n[\n{\n"id": "patch-text",\n"payload": [\n{\n"namespace": "instances",\n"patches": [\n{ "op": "replace", "path": ["instance-id", "children", 0, "value"], "value": "Launch faster" }\n]\n}\n]\n}\n]\n\nCreate records with semantic operations such as create-variable,\ncreate-resource, create-design-token, create-page, create-folder,\nand create-breakpoint. Raw patch rejects generated record\ncreation, collection replacement, record replacement with a different `id`, and\nrecord id field mutations in id-keyed namespaces because Webstudio must generate\nand preserve record ids.\n\n## Safety Rules\n\n- For MCP apply-patch, read the latest version with MCP snapshot before writing.\n- Reuse ids from MCP snapshot output when updating existing records.\n- Do not create generated records, replace generated record collections, replace records with different ids, or mutate record id fields with raw patch. Use semantic create operations so Webstudio generates ids.\n- If apply-patch reports a version conflict, read the latest build and regenerate the patch.\n- Prefer semantic MCP read tools for discovery, then use MCP snapshot for exact patch paths.\n\n## Command Index\n\n{{commandIndex}}\n',"manual-llm":- '# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Use MCP locally or optionally connect a client\n\nDo not install, register, or connect an MCP server merely because the user asks\nyou to edit a Webstudio project. If Webstudio MCP tools are already available,\nuse them. If you have shell access, use the local CLI shortcuts such as\n`webstudio meta.index` and `webstudio list-pages`; they expose the same project\noperations without changing client configuration or restarting the app.\n\nOnly when the user explicitly asks for persistent native MCP integration, run\nthe command for their client:\n\n- Claude Code: `webstudio connect claude`\n- Codex: `webstudio connect codex`\n- Cursor: `webstudio connect cursor`\n- VS Code or GitHub Copilot: `webstudio connect vscode`\n\nRun project operations from the linked project root. If the folder is not\nlinked, ask for an editable Builder share link and run\n`webstudio init --link <share-link> --json`. You can then use local CLI\nshortcuts immediately. Do not run `webstudio sync`, `webstudio connect`, or\nrestart the app unless the user specifically wants native MCP registration:\nMCP reads and edits the latest editable Builder build directly, including for\nprojects that have never been published. Treat the share link as a credential\nand do not include it in committed files, logs, screenshots, or issue reports.\n\nThe optional `connect` command verifies project access before changing client configuration. For\nClaude Code, Cursor, and VS Code it safely merges the `webstudio` server into\nthe client\'s project configuration. For Codex it runs both `codex mcp add` and\n`codex mcp get webstudio`; do not repeat those commands separately. Follow the\nreload, restart, or approval instruction printed by `connect`, then verify the\nloaded MCP connection by asking the client to use Webstudio MCP and list the\nproject pages. Use `--print` only to inspect the generated setup without\nchanging configuration or requiring project access.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a compact MCP tool overview. Add `--verbose` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get-more-tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nSave the readable payload in `.temp/insert-fragment.json`:\n\n```json\n{\n "parentInstanceId": "parent-id",\n "fragment": "<section ws:style={css`padding: 32px; display: grid; gap: 12px;`}><h2>Launch Kit</h2><p>A focused section created with Webstudio JSX.</p><button>Get started</button></section>"\n}\n```\n\nSingle quotes inside the JSX keep the JSON valid without backslash-escaped attributes. The same local shortcut form is shorter and preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nFor this simple path, do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only to get the target `parentInstanceId`.\n\nWhen authoring JSX for `insert-fragment`, use Webstudio component helpers and Webstudio style syntax. Use `ws:style={css\\`...\\`}`for Webstudio-native CSS. For simpler cases, use React-style object syntax such as`style={{ padding: 24 }}`. Both forms create editable Webstudio style data.\n\nWhen the task says another user will edit a page in Content mode, use a Content Block (`ws:block`) around every editable region. Content-mode users can edit text and supported props only in descendants of that block; content outside it is read-only. Put reusable insertable options in exactly one direct `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes editable Content Block body content. A missing or second template container makes the block invalid. Verify this structure before handoff.\n\nWhen MDX files belong to a content collection, connect the collection to its dynamic entry page explicitly. Read the page ID after finding or creating the page, verify that its path has exactly one URL parameter, and store the ID at `x-webstudio.entryPageId` in `collection.json`. Do not assume Webstudio infers the page from its path, Assets query, or Content Block source. Preserve the rest of `collection.json`, and verify **Open on canvas** from both an entry asset menu and **Entry settings** before handoff. If no compatible page exists, leave the field unset and report that entry navigation still needs configuration.\n\nWhen the Content Block body must be stored in an `.mdx` Asset, use the dedicated `connect-content-block-source`, `switch-content-block-source`, `inspect-content-block-source`, `edit-content-block-source`, `update-content-block-frontmatter`, `reload-content-block-source`, and `disconnect-content-block-source` tools. Do not manipulate its `src` with generic prop tools. Connecting replaces existing Body content, so report `requiresConfirmation:true` and retry with `confirmReplacement:true` only after user approval. Prefer Markdown for standard document content; it automatically uses unique matching semantic templates. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG that Markdown cannot express. Capitalized JSX resolves a unique stable template **Name** or a built-in MDX adapter. Add custom components to this Content Block\'s Templates before referencing them in MDX. The display label is independent. JSX attributes accept quoted values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use direct component identifiers. Matching explicit children overlay designed descendants and keep their template styles. A mismatched child structure replaces defaults, while an explicit empty pair clears defaults and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live, including when a matching template is added after the MDX element. Preserve invalid MDX and unresolved template names, inspect all source-located diagnostics, and resolve revision conflicts by reloading before reapplying the change. After a template rename or deletion, use `migrate-content-block-template-references` to preview and confirm custom-template JSX and legacy updates across selected MDX files. A confirmed removal unwraps paired references and preserves their authored children; a self-closing reference disappears because it has none.\n\nFrontmatter is part of the same MDX source. `update-content-block-frontmatter` receives the complete replacement property map, so inspect and preserve properties the user did not ask to remove. Store frontmatter images as exact `$ref` objects. Bind editable Image sources to their resolved `.src` with explicit `binding.mode:"readwrite"`; omitting the mode leaves the image visible but not replaceable in Content mode. Bind alt properties to their Asset `.description` with `mode:"read"`. Use `update-content-block-frontmatter` for MCP frontmatter edits; MDX-rendered elements are not persistent targets for generic prop or text mutations. Preserve existing `mode:"readwrite"` bindings, which are valid only for exact direct frontmatter paths. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. For an expression-bound source inside a Collection, pass the occurrence\'s scoped values and a distinct stable `renderScope`; for example, resolve `post.assetId` with `variables:{"post":{"assetId":"<mdxAssetId>"}}`.\n\nFor an editable MDX article, use the resource to select the Content Block\'s source Asset (`post.data.id`), then bind article fields inside the block to its document parameter (`document.frontmatter.title`), not query-result properties. Inspect the actual document variable name first. Create writable bindings explicitly: `update-text` uses `expressionBindingMode:"readwrite"`; `bind-props` uses `binding.mode:"readwrite"`. These generic tools target persistent designed instances, such as a header outside the MDX body, not MDX-generated instances. The MDX body is editable through its source mapping; merely placing static or query-bound content inside the block does not make it editable. Use exact direct paths; property access is already safe. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. Follow the complete article editability checklist below before handoff.\n\n### Content Block completion checklist\n\nFor every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.\n\n### Complete article editability is required\n\nWhen the user asks for the whole article to be editable in Content mode, this includes every article-owned value: title, excerpt, author details and links, dates, reading time, categories, hero and inline image sources, alternative text, captions, body text, links, and custom-component content and media. Exclude only designer-owned layout, styling, templates, and shared navigation/footer unless the user asks otherwise. A correct preview, a successful MCP write, or an editable body does not prove this requirement is met.\n\nBefore handoff:\n\n1. Inventory every article field, its UI control, binding, and source file/field. Header fields outside **MDX content** are still part of the article and must be editable through the Content Block\'s document bindings.\n2. In Content mode, edit every inventoried field through the UI, including choosing a different hero image and editing link destinations and custom-component props. Do not substitute a raw MDX/YAML edit or an MCP write for this check.\n3. Read the saved source after each edit. Confirm the intended MDX body/frontmatter or referenced author file changed, unrelated content stayed intact, and the edit survives reload. Restore test values and verify restoration.\n4. Mark each field passed, failed, or not tested. Do not claim the article is fully editable while any required field is failed or untested.\n\n**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.\n\nKeep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.\n\nDo not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.\n\nUse Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/Webstudio names. Do not use React-only aliases such as `className` or `htmlFor`; the runtime rejects them with the Webstudio prop name to use.\n\nUse Webstudio actions for event/action props. Do not pass JavaScript functions such as `onClick={() => ...}`; the runtime rejects them because functions cannot be persisted as Webstudio project data.\n\n```tsx\n<button onClick={new ActionValue(["event"], expression`console.log(event)`)}>\n Open\n</button>\n```\n\nPlain JSX prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n\nIf a component has a registered template with required parts, JSX must include those parts explicitly under the same parent structure as the template, for example `<Switch><SwitchThumb /></Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.\n\n## Animation Components\n\nBefore creating animation examples, inspect the exact components with focused discovery:\n\n```sh\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateChildren"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateText"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:StaggerAnimation"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:VideoAnimation"}\'\n```\n\nUse Animation Group (`AnimateChildren`) as the controller. Put normal instances directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it. Text, Stagger, and Video are helper components with `contentModel.category: "none"` and should not be used as standalone section roots.\n\nDefine timing and CSS changes on the Animation Group `action` prop. Use `type:"view"` for viewport entry/exit progress and `type:"scroll"` for scroll-progress timelines. For in animations, keep the canvas styles as the final state and use `fill:"backwards"` with keyframes that describe the starting state. For out animations, use `fill:"forwards"` with keyframes that describe the ending state.\n\nText Animation settings: `slidingWindow` defaults to `5`, `easing` defaults to `linear`, and `splitBy` defaults to `char`. Use `splitBy:"space"` for word-by-word animation. The parent Animation Group keyframes provide the actual opacity, translate, scale, or other styles.\n\nStagger Animation settings: `slidingWindow` defaults to `1` and `easing` defaults to `linear`. It applies parent Animation Group progress across its direct children. Use `slidingWindow:0` for instant sequential steps, `1` for one child at a time, and values above `1` for overlapping waves.\n\nVideo Animation settings: `timeline` is a boolean. Prefer `insert-component` for Video Animation so the Video child template is inserted, then configure the Video child asset/source. Use short, seek-friendly videos for smooth scroll-linked playback.\n\nUse JSX fragments for authored animation structures when you need styled, editable examples. Put the final visual state in `ws:style` and put the starting or ending animated state in the Animation Group `action` keyframes. Include an explicit `offset` on every keyframe: use `offset: 0` for starting-state keyframes with `fill:"backwards"` and `offset: 1` for ending-state keyframes with `fill:"forwards"`.\n\n```tsx\n<AnimateChildren\n action={{\n type: "view",\n axis: "block",\n animations: [\n {\n name: "Fade up on entry",\n timing: {\n fill: "backwards",\n rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 24, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n ],\n }}\n>\n <section\n ws:style={css`\n display: grid;\n gap: 16px;\n padding: 48px;\n border-radius: 24px;\n background: #111827;\n color: white;\n `}\n >\n <h2>Launch metrics</h2>\n <p>A polished card that fades up as it enters the viewport.</p>\n </section>\n</AnimateChildren>\n```\n\nFor Text Animation, keep `AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Parallax In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 100, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Opacity In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n {\n name: "Scale In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Parallax Out",\n timing: {\n fill: "forwards",\n rangeStart: ["cover", { type: "unit", value: 50, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 1,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: -100, unit: "px" },\n ],\n },\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n insetStart: { type: "unit", value: 5, unit: "%" },\n insetEnd: { type: "unit", value: 5, unit: "%" },\n isPinned: true,\n }}\n>\n <AnimateText splitBy="space" slidingWindow={5} easing="easeOutQuart">\n <h2>Animate words with controlled rhythm</h2>\n </AnimateText>\n</AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `StaggerAnimation`:\n\n```tsx\n<AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n timing: {\n fill: "backwards",\n rangeStart: ["contain", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["contain", { type: "unit", value: 30, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n }}\n>\n <StaggerAnimation>\n <article\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </article>\n <article\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </article>\n <article\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </article>\n </StaggerAnimation>\n</AnimateChildren>\n```\n\nFor Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:\n\n```tsx\n<AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Video progress",\n timing: {\n fill: "both",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [{ offset: 0, styles: {} }],\n },\n ],\n }}\n>\n <VideoAnimation timeline={true}>\n <Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </VideoAnimation>\n</AnimateChildren>\n```\n\n## Command Surface Boundary\n\n- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, registry inspection, man, and starting MCP.\n- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.\n- From a shell, call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio insert-fragment \'<json>\' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.\n- For experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- Read `meta.session.commitStatus` before interpreting durability. Read-only results report `not-applicable` and retain `committed:false` for compatibility; dry-run plans report `planned`; failed mutations report `failed`; no-op mutations report `unchanged`; durable mutations report `committed` with `meta.session.committed:true`.\n- For bounded multi-step shell work, run inline JSON with `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For large batches, write `{ "calls": [{ "tool": "..." }] }` to a normal JSON file and run `webstudio mcp run .temp/mcp-calls.json`.\n- Use JSON strings for `brief` fields. Never pass boolean flags such as `{"brief":true}`.\n- Treat `webstudio mcp single-op-call` and `webstudio mcp run` stderr lines as progress checkpoints; stdout remains JSON on both success and failure. On failure, parse stdout for `{ "ok": false, "error": { "code": "...", "message": "..." } }` before deciding what to fix.\n- If a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in Discord `#help` at https://wstd.us/community. Give them a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n- Run one-shot `webstudio mcp single-op-call` commands sequentially against a linked `.webstudio` folder. If a command returns `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- In delegated or non-streaming agent environments, do not batch many MCP calls silently and do not wrap many shortcut or `webstudio mcp single-op-call` commands in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report that command/result, then wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with `workflow.next {"goal":"design-system-page","phase":"presentation-pass"}`. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world examples, not raw unstyled component dumps.\n- For design-system or “use every component” tasks, start with compact `webstudio components.coverage-plan`, checkpoint, then request component coverage details with `webstudio components.coverage-plan \'{"detail":"roots","offset":20}\'` or `{"detail":"parts"}` only when needed. Do not pass `detail` to `list-pages`; use `list-pages {}` or `get-page-by-path` for page lookup.\n- MCP tool shortcuts are only for MCP tools. If a shortcut is ambiguous with a real top-level command, the real top-level command wins; use `webstudio mcp single-op-call <tool> \'<json>\'` to force the MCP path.\n\n## LLM Implementation Process\n\nUse this process for user requests that change Webstudio content, layout, styles, assets, pages, redirects, resources, or publishing state:\n\n1. Discover capabilities with `webstudio man --json`, `webstudio schema api`, `webstudio schema mcp`, MCP `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.coverage-plan`, `components.search`, `components.get`, `templates.list`, and `templates.get`. From a shell, prefer shortcut calls such as `webstudio meta.index` and `webstudio components.search \'{"brief":"button"}\'` for these focused tool calls; use `webstudio mcp single-op-call` when you need the explicit MCP form. Read full resources such as `webstudio://project/tools` and `webstudio://project/components` only when needed. Do not write scripts to parse full MCP discovery JSON for normal lookup.\n2. When a value or id is known, call `search-project` once instead of passing broad snapshots or several lists to the model. Use semantic list/get reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, and `list-breakpoints` when the structure or target is not known. Use `snapshot` only when exact raw patch paths are needed. Before changing a project, read `get-project-settings` and follow any non-empty `meta.agentInstructions`. These are shared project instructions, not a place for secrets.\n For a Builder link from **Copy link to instance**, parse the URL with `URL`/`URLSearchParams`. The decoded `instance` query parameter is a comma-separated selector ordered from the target instance to the page root. Pass its first entry to `inspect-instance`, for example `?pageId=page-id&instance=heading-id%2Cslot-id%2Cbody-id` becomes `{"instanceId":"heading-id","include":["props","styles","children","ancestors"]}`. Use `pageId` and the remaining selector entries to check the page and shared Slot occurrence before changing it. Shared Slot descendants are shared records; editing one changes all occurrences. Verify that the configured MCP project matches the linked project before editing; stop if they differ. The URL does not authorize switching projects. If the instance is missing, ask for an updated link instead of guessing another target. Never send a Builder link to screenshot tools or echo its `authToken`.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.\n4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.\n5. For visual/design work, ask whether the user wants visual verification unless they explicitly requested it. Only after they opt in, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate.\n6. Report what changed and what verification ran.\n\n## Visual Design Workflow\n\nFor requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:\n\n1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.\n2. Do not use generated route/component files as the source of truth for editable content.\n3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.\n4. Ask whether the user wants visual verification unless they explicitly requested screenshots, visual verification, or a rendered audit. Do not start preview, screenshots, screenshot diffs, OCR installation, or rendered audits until they opt in.\n5. After they opt in, keep generated project files current, start preview, and capture the changed page with `screenshot`.\n6. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n7. If the user declines or vision tooling is unavailable, use focused non-visual assertions and state that vision was not run.\n\n## Responsive Verification Workflow\n\nFor responsive page work, use Builder breakpoints as the source of truth:\n\n1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.\n2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.\n3. Ask whether the user wants visual verification unless they explicitly requested it. Do not capture responsive screenshots until they opt in.\n4. Pick screenshot viewport widths from the project breakpoints: include a desktop width, each defined max-width or min-width edge, and a narrow mobile width.\n5. Capture each viewport with `screenshot`, for example `{"path":"/","output":"home-375.png","viewport":{"width":375,"height":812}}` and `{"path":"/","output":"home-1440.png","viewport":{"width":1440,"height":900}}`.\n6. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n7. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.\n\n## Generated Files Guardrails\n\n- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.\n- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.\n- Generated files are build artifacts and may be overwritten by `webstudio build`.\n- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.\n\n## Values vs Bindings\n\nBefore authoring unfamiliar expressions, read `webstudio://project/expressions` with MCP `resources/read` or `webstudio mcp read-resource webstudio://project/expressions`. It documents the supported expression subset, method allowlist, scope, Collection context, and validation limits.\n\n- Use direct value tools for fixed content. For one visible text child, use `update-text` with plain `text`. For a bounded multi-instance literal replacement, use `replace-text` with `find`, `replace`, `pagePath` or `pageId`, and `limit`; it does not change expression children. Use `replace-prop-text` for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop\'s direct type/value.\n- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.\n- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.\n- Expression binding example: `{"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}`.\n- Page metadata fields contain JavaScript expression source. For fixed text, pass a quoted string expression such as `"Pricing | Acme"`; for computed values, pass code such as `pageTitle ?? "Pricing | Acme"`. An unquoted word is a variable reference, not fixed text.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599, for example `302`. For a dynamic status, pass JavaScript expression code such as `system.status`.\n- Page metadata update example: use `update-page` with `{"pageId":"page-id","values":{"title":"\\"Pricing | Acme\\"","meta":{"description":"\\"Plans for teams\\""}}}`.\n- Draft a page with `update-page` and `{"pageId":"page-id","values":{"isDraft":true}}`. It remains editable and previewable but is omitted from every publish target, including staging, and from sitemap output.\n- Stage a draft page for a future publish with `{"pageId":"page-id","values":{"isDraft":false}}`. This clears draft state but does not deploy the site. The home page and `/*` catch-all page cannot be drafts.\n- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.\n- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.\n- Assets is one system resource that always executes a structured query. `result:"many"` returns the existing ID-keyed collection shape and is the backward-compatible default. `result:"one"`, `result:"first"`, and `result:"last"` return one direct item or `null`; first and last require explicit sorting. `create-assets-resource` without `query` uses the default URL and optional image-dimensions output.\n- For a Markdown-backed blog, create exactly two Builder page definitions: a fixed `/blog` overview and one `/blog/:slug` detail page. Both pages load content through Assets resources. Never create one Builder page per post or duplicate Markdown content into static page structures. Read `get-asset-field-catalog`, validate each structured query with `validate-asset-query`, then call `create-assets-resource` or `update-assets-resource`. Set `values.query:null` to restore the default query.\n- Optimize every explicit Assets query for the deployed content-database size. Use `output.mode:"fields"` and select only fields that are actually rendered or otherwise required by the query. Keep `includeMetadata:false` unless the rendered value needs file metadata; diagnostics are returned separately. Do not use `output.mode:"all"` as a convenience default.\n- Every reachable Assets data source contributes to the shared database. Keep one final resource per rendered query. Update an existing scoped resource instead of creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicate resources and data sources.\n- Make a bounded overview fully static: use literal values for its filters, limit, and offset, add a deterministic ID tie-breaker to its sort, and use `content.mode:"none"`. This lets compilation materialize the small overview result instead of retaining overview-only fields across every candidate article. Reserve runtime expressions for values that are truly dynamic, such as `system.params.slug` on the detail route.\n- Query Markdown or MDX files directly and use `content.mode:"markdown-body-ref"` when rendering their bodies. The published database keeps only metadata and document references, filters and paginates first, and fetches the selected files from Asset storage at runtime. Do not create companion JSON descriptors merely to avoid embedding the document.\n- `full` and bounded `range` request embedded file bytes. Use them only when the caller explicitly requires the complete source or a byte range.\n- Deferred Markdown or MDX bodies exclude frontmatter and resolve conventional relative links and images such as `../images/hero.png` to matching Assets. Markdown Embed permits sanitized figures, audio, video, and iframes, but removes scripts, inline event handlers, and unsafe URLs. It does not render Webstudio MDX elements; connect the `.mdx` file to a Content Block for that workflow.\n- For `result:"many"`, Assets expose an ID-keyed map at `<dataSourceName>.data` and `totalCount`/`hasMore` at `<dataSourceName>.meta`; bind a listing Collection to `posts.data`. Single-result modes expose the selected item or `null` directly at `<dataSourceName>.data`, always include its `id`, and expose `totalCount` in meta. Bind detail components and page settings directly from expressions such as `post.data.properties.title`, `post.data.content.text`, and `post.data ? 200 : 404` without a Collection.\n- Use `preview-asset-query` with concrete values before binding expressions in the saved resource. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes are not separate allowances and must not be summed. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A finished Markdown blog must include every source document without truncation, contain no embedded Markdown bodies, and retain only the intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files. Inspect saved mode and configuration with `list-assets-resources` or `get-assets-resource`; shared index maintenance is automatic.\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays, objects, filters, and nested data.\n- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.\n- Use scoped resources for read data. A GET resource created with `scopeInstanceId`/`dataSourceName` defaults to `exposeAsDataSource:true`, becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Read the loaded resource result from its wrapper, usually `.data`.\n- Use prop-bound resources for actions. A resource created without `scopeInstanceId` and bound to a component prop such as Form `action` with `bind-props` and `binding.type: "resource"` becomes an action resource in the page resource `action` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.\n- POST, PUT, and DELETE resources default to `exposeAsDataSource:false`, even with a scope. Set `exposeAsDataSource:true` only for an intentional render-time read such as a GraphQL POST query; provide `scopeInstanceId` and inspect the returned warning. Set it to `false` during `update-resource` to detach existing render-time exposure.\n- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Use `{"type":"literal","value":"website"}` for fixed request text. Header values can use an expression such as `"Bearer " + auth.token`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.\n- Resource methods are `get`, `post`, `put`, and `delete`. Optional resource controls are `graphql` and `system`. Use `control:"graphql"` for GraphQL POST resources with query bodies. Use `control:"system"` for built-in local resource URLs such as `"/$resources/current-date"` and for resources reading the built-in `system` parameter. The built-in system fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`; do not use `system.path`.\n- Whenever an array or object from a resource or data variable should render repeated UI, call `insert-collection` with the complete iterable and one repeated-item JSX root. The command creates the Collection, private item parameters, iterable binding, and descendant item bindings atomically. Use `collectionItem` and `collectionItemKey` expressions in the item JSX. Wrap multiple repeated siblings in one Element, and give repeated Radix items stable unique `value` bindings.\n- Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, `new`, `this`, `await`, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Property and index access are made safe automatically, so write direct access. Use nullish coalescing when a fallback is required.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- Never run visual verification automatically. Ask first unless the user explicitly requested screenshots, visual verification, or a rendered audit; if they do not opt in, use focused non-visual assertions.\n- Do not edit generated files for normal Webstudio content/design requests.\n- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.\n- Use expression source for page metadata. Quote fixed text as a JavaScript string literal within the JSON string.\n- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n',+ '# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Use MCP locally or optionally connect a client\n\nDo not install, register, or connect an MCP server merely because the user asks\nyou to edit a Webstudio project. If Webstudio MCP tools are already available,\nuse them. If you have shell access, use the local CLI shortcuts such as\n`webstudio meta.index` and `webstudio list-pages`; they expose the same project\noperations without changing client configuration or restarting the app.\n\nOnly when the user explicitly asks for persistent native MCP integration, run\nthe command for their client:\n\n- Claude Code: `webstudio connect claude`\n- Codex: `webstudio connect codex`\n- Cursor: `webstudio connect cursor`\n- VS Code or GitHub Copilot: `webstudio connect vscode`\n\nRun project operations from the linked project root. If the folder is not\nlinked, ask for an editable Builder share link and run\n`webstudio init --link <share-link> --json`. You can then use local CLI\nshortcuts immediately. Do not run `webstudio sync`, `webstudio connect`, or\nrestart the app unless the user specifically wants native MCP registration:\nMCP reads and edits the latest editable Builder build directly, including for\nprojects that have never been published. Treat the share link as a credential\nand do not include it in committed files, logs, screenshots, or issue reports.\n\nThe optional `connect` command verifies project access before changing client configuration. For\nClaude Code, Cursor, and VS Code it safely merges the `webstudio` server into\nthe client\'s project configuration. For Codex it runs both `codex mcp add` and\n`codex mcp get webstudio`; do not repeat those commands separately. Follow the\nreload, restart, or approval instruction printed by `connect`, then verify the\nloaded MCP connection by asking the client to use Webstudio MCP and list the\nproject pages. Use `--print` only to inspect the generated setup without\nchanging configuration or requiring project access.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a compact MCP tool overview. Add `--verbose` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get-more-tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nSave the readable payload in `.temp/insert-fragment.json`:\n\n```json\n{\n "parentInstanceId": "parent-id",\n "fragment": "<section ws:style={css`padding: 32px; display: grid; gap: 12px;`}><h2>Launch Kit</h2><p>A focused section created with Webstudio JSX.</p><button>Get started</button></section>"\n}\n```\n\nSingle quotes inside the JSX keep the JSON valid without backslash-escaped attributes. The same local shortcut form is shorter and preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nFor this simple path, do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only to get the target `parentInstanceId`.\n\nWhen authoring JSX for `insert-fragment`, use Webstudio component helpers and Webstudio style syntax. Use `ws:style={css\\`...\\`}`for Webstudio-native CSS. For simpler cases, use React-style object syntax such as`style={{ padding: 24 }}`. Both forms create editable Webstudio style data.\n\nWhen the task says another user will edit a page in Content mode, use a Content Block (`ws:block`) around every editable region. Content-mode users can edit text and supported props only in descendants of that block; content outside it is read-only. Put reusable insertable options in exactly one direct `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes editable Content Block body content. A missing or second template container makes the block invalid. Verify this structure before handoff.\n\nWhen MDX files belong to a content collection, connect the collection to its dynamic entry page explicitly. Read the page ID after finding or creating the page, verify that its path has exactly one URL parameter, and store the ID at `x-webstudio.entryPageId` in `collection.json`. Do not assume Webstudio infers the page from its path, Assets query, or Content Block source. Preserve the rest of `collection.json`, and verify **Open on canvas** from both an entry asset menu and **Entry settings** before handoff. If no compatible page exists, leave the field unset and report that entry navigation still needs configuration.\n\nWhen the Content Block body must be stored in an `.mdx` Asset, use the dedicated `connect-content-block-source`, `switch-content-block-source`, `inspect-content-block-source`, `edit-content-block-source`, `update-content-block-frontmatter`, `reload-content-block-source`, and `disconnect-content-block-source` tools. Do not manipulate its `src` with generic prop tools. Connecting replaces existing Body content, so report `requiresConfirmation:true` and retry with `confirmReplacement:true` only after user approval. Prefer Markdown for standard document content; it automatically uses unique matching semantic templates. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG that Markdown cannot express. Capitalized JSX resolves a unique stable template **Name** or a built-in MDX adapter. Add custom components to this Content Block\'s Templates before referencing them in MDX. The display label is independent. JSX attributes accept quoted values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use direct component identifiers. Matching explicit children overlay designed descendants and keep their template styles. A mismatched child structure replaces defaults, while an explicit empty pair clears defaults and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live, including when a matching template is added after the MDX element. Preserve invalid MDX and unresolved template names, inspect all source-located diagnostics, and resolve revision conflicts by reloading before reapplying the change. After a template rename or deletion, use `migrate-content-block-template-references` to preview and confirm custom-template JSX and legacy updates across selected MDX files. A confirmed removal unwraps paired references and preserves their authored children; a self-closing reference disappears because it has none.\n\nFrontmatter is part of the same MDX source. `update-content-block-frontmatter` receives the complete replacement property map, so inspect and preserve properties the user did not ask to remove. Store frontmatter images as exact `$ref` objects. Bind editable Image sources to their resolved `.src` with explicit `binding.mode:"readwrite"`; omitting the mode leaves the image visible but not replaceable in Content mode. Bind alt properties to their Asset `.description` with `mode:"read"`. Use `update-content-block-frontmatter` for MCP frontmatter edits; MDX-rendered elements are not persistent targets for generic prop or text mutations. Preserve existing `mode:"readwrite"` bindings, which are valid only for exact direct frontmatter paths. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. For an expression-bound source inside a Collection, pass the occurrence\'s scoped values and a distinct stable `renderScope`; for example, resolve `post.assetId` with `variables:{"post":{"assetId":"<mdxAssetId>"}}`.\n\nFor an editable MDX article, use the resource to select the Content Block\'s source Asset (`post.data.id`), then bind article fields inside the block to its document parameter (`document.frontmatter.title`), not query-result properties. Inspect the actual document variable name first. Create writable bindings explicitly: `update-text` uses `expressionBindingMode:"readwrite"`; `bind-props` uses `binding.mode:"readwrite"`. These generic tools target persistent designed instances, such as a header outside the MDX body, not MDX-generated instances. The MDX body is editable through its source mapping; merely placing static or query-bound content inside the block does not make it editable. Use exact direct paths; property access is already safe. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. Follow the complete article editability checklist below before handoff.\n\n### Content Block completion checklist\n\nFor every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.\n\n### Complete article editability is required\n\nWhen the user asks for the whole article to be editable in Content mode, this includes every article-owned value: title, excerpt, author details and links, dates, reading time, categories, hero and inline image sources, alternative text, captions, body text, links, and custom-component content and media. Exclude only designer-owned layout, styling, templates, and shared navigation/footer unless the user asks otherwise. A correct preview, a successful MCP write, or an editable body does not prove this requirement is met.\n\nBefore handoff:\n\n1. Inventory every article field, its UI control, binding, and source file/field. Header fields outside **MDX content** are still part of the article and must be editable through the Content Block\'s document bindings.\n2. In Content mode, edit every inventoried field through the UI, including choosing a different hero image and editing link destinations and custom-component props. Do not substitute a raw MDX/YAML edit or an MCP write for this check.\n3. Read the saved source after each edit. Confirm the intended MDX body/frontmatter or referenced author file changed, unrelated content stayed intact, and the edit survives reload. Restore test values and verify restoration.\n4. Mark each field passed, failed, or not tested. Do not claim the article is fully editable while any required field is failed or untested.\n\n**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.\n\nKeep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.\n\nDo not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.\n\nUse Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/Webstudio names. Do not use React-only aliases such as `className` or `htmlFor`; the runtime rejects them with the Webstudio prop name to use.\n\nUse Webstudio actions for event/action props. Do not pass JavaScript functions such as `onClick={() => ...}`; the runtime rejects them because functions cannot be persisted as Webstudio project data.\n\n```tsx\n<button onClick={new ActionValue(["event"], expression`console.log(event)`)}>\n Open\n</button>\n```\n\nPlain JSX prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n\nIf a component has a registered template with required parts, JSX must include those parts explicitly under the same parent structure as the template, for example `<Switch><SwitchThumb /></Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.\n\n## Animation Components\n\nBefore creating animation examples, inspect the exact components with focused discovery:\n\n```sh\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateChildren"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateText"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:StaggerAnimation"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:VideoAnimation"}\'\n```\n\nUse Animation Group (`AnimateChildren`) as the controller. Put normal instances directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it. Text, Stagger, and Video are helper components with `contentModel.category: "none"` and should not be used as standalone section roots.\n\nDefine timing and CSS changes on the Animation Group `action` prop. Use `type:"view"` for viewport entry/exit progress and `type:"scroll"` for scroll-progress timelines. For in animations, keep the canvas styles as the final state and use `fill:"backwards"` with keyframes that describe the starting state. For out animations, use `fill:"forwards"` with keyframes that describe the ending state.\n\nText Animation settings: `slidingWindow` defaults to `5`, `easing` defaults to `linear`, and `splitBy` defaults to `char`. Use `splitBy:"space"` for word-by-word animation. The parent Animation Group keyframes provide the actual opacity, translate, scale, or other styles.\n\nStagger Animation settings: `slidingWindow` defaults to `1` and `easing` defaults to `linear`. It applies parent Animation Group progress across its direct children. Use `slidingWindow:0` for instant sequential steps, `1` for one child at a time, and values above `1` for overlapping waves.\n\nVideo Animation settings: `timeline` is a boolean. Prefer `insert-component` for Video Animation so the Video child template is inserted, then configure the Video child asset/source. Use short, seek-friendly videos for smooth scroll-linked playback.\n\nUse JSX fragments for authored animation structures when you need styled, editable examples. Put the final visual state in `ws:style` and put the starting or ending animated state in the Animation Group `action` keyframes. Include an explicit `offset` on every keyframe: use `offset: 0` for starting-state keyframes with `fill:"backwards"` and `offset: 1` for ending-state keyframes with `fill:"forwards"`.\n\n```tsx\n<AnimateChildren\n action={{\n type: "view",\n axis: "block",\n animations: [\n {\n name: "Fade up on entry",\n timing: {\n fill: "backwards",\n rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 24, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n ],\n }}\n>\n <section\n ws:style={css`\n display: grid;\n gap: 16px;\n padding: 48px;\n border-radius: 24px;\n background: #111827;\n color: white;\n `}\n >\n <h2>Launch metrics</h2>\n <p>A polished card that fades up as it enters the viewport.</p>\n </section>\n</AnimateChildren>\n```\n\nFor Text Animation, keep `AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Parallax In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 100, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Opacity In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n {\n name: "Scale In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Parallax Out",\n timing: {\n fill: "forwards",\n rangeStart: ["cover", { type: "unit", value: 50, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 1,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: -100, unit: "px" },\n ],\n },\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n insetStart: { type: "unit", value: 5, unit: "%" },\n insetEnd: { type: "unit", value: 5, unit: "%" },\n isPinned: true,\n }}\n>\n <AnimateText splitBy="space" slidingWindow={5} easing="easeOutQuart">\n <h2>Animate words with controlled rhythm</h2>\n </AnimateText>\n</AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `StaggerAnimation`:\n\n```tsx\n<AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n timing: {\n fill: "backwards",\n rangeStart: ["contain", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["contain", { type: "unit", value: 30, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n }}\n>\n <StaggerAnimation>\n <article\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </article>\n <article\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </article>\n <article\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </article>\n </StaggerAnimation>\n</AnimateChildren>\n```\n\nFor Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:\n\n```tsx\n<AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Video progress",\n timing: {\n fill: "both",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [{ offset: 0, styles: {} }],\n },\n ],\n }}\n>\n <VideoAnimation timeline={true}>\n <Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </VideoAnimation>\n</AnimateChildren>\n```\n\n## Command Surface Boundary\n\n- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, registry inspection, man, and starting MCP.\n- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.\n- From a shell, call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio insert-fragment \'<json>\' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.\n- For experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- Read `meta.session.commitStatus` before interpreting durability. Read-only results report `not-applicable` and retain `committed:false` for compatibility; dry-run plans report `planned`; failed mutations report `failed`; no-op mutations report `unchanged`; durable mutations report `committed` with `meta.session.committed:true`.\n- For bounded multi-step shell work, run inline JSON with `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For large batches, write `{ "calls": [{ "tool": "..." }] }` to a normal JSON file and run `webstudio mcp run .temp/mcp-calls.json`.\n- Use JSON strings for `brief` fields. Never pass boolean flags such as `{"brief":true}`.\n- Treat `webstudio mcp single-op-call` and `webstudio mcp run` stderr lines as progress checkpoints; stdout remains JSON on both success and failure. On failure, parse stdout for `{ "ok": false, "error": { "code": "...", "message": "..." } }` before deciding what to fix.\n- If a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in Discord `#help` at https://wstd.us/community. Give them a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n- Run one-shot `webstudio mcp single-op-call` commands sequentially against a linked `.webstudio` folder. If a command returns `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- In delegated or non-streaming agent environments, do not batch many MCP calls silently and do not wrap many shortcut or `webstudio mcp single-op-call` commands in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report that command/result, then wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with `workflow.next {"goal":"design-system-page","phase":"presentation-pass"}`. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world examples, not raw unstyled component dumps.\n- For design-system or “use every component” tasks, start with compact `webstudio components.coverage-plan`, checkpoint, then request component coverage details with `webstudio components.coverage-plan \'{"detail":"roots","offset":20}\'` or `{"detail":"parts"}` only when needed. Do not pass `detail` to `list-pages`; use `list-pages {}` or `get-page-by-path` for page lookup.\n- MCP tool shortcuts are only for MCP tools. If a shortcut is ambiguous with a real top-level command, the real top-level command wins; use `webstudio mcp single-op-call <tool> \'<json>\'` to force the MCP path.\n\n## LLM Implementation Process\n\nUse this process for user requests that change Webstudio content, layout, styles, assets, pages, redirects, resources, or publishing state:\n\n1. Discover capabilities with `webstudio man --json`, `webstudio schema api`, `webstudio schema mcp`, MCP `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.coverage-plan`, `components.search`, `components.get`, `templates.list`, and `templates.get`. From a shell, prefer shortcut calls such as `webstudio meta.index` and `webstudio components.search \'{"brief":"button"}\'` for these focused tool calls; use `webstudio mcp single-op-call` when you need the explicit MCP form. Read full resources such as `webstudio://project/tools` and `webstudio://project/components` only when needed. Do not write scripts to parse full MCP discovery JSON for normal lookup.\n2. When a value or id is known, call `search-project` once instead of passing broad snapshots or several lists to the model. Use semantic list/get reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, and `list-breakpoints` when the structure or target is not known. Use `snapshot` only when exact raw patch paths are needed. Before changing a project, read `get-project-settings` and follow any non-empty `meta.agentInstructions`. These are shared project instructions, not a place for secrets.\n For a Builder link from **Copy link to instance**, parse the URL with `URL`/`URLSearchParams`. The decoded `instance` query parameter is a comma-separated selector ordered from the target instance to the page root. Pass its first entry to `inspect-instance`, for example `?pageId=page-id&instance=heading-id%2Cslot-id%2Cbody-id` becomes `{"instanceId":"heading-id","include":["props","styles","children","ancestors"]}`. Use `pageId` and the remaining selector entries to check the page and shared Slot occurrence before changing it. Shared Slot descendants are shared records; editing one changes all occurrences. Verify that the configured MCP project matches the linked project before editing; stop if they differ. The URL does not authorize switching projects. If the instance is missing, ask for an updated link instead of guessing another target. Never send a Builder link to screenshot tools or echo its `authToken`.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.\n4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.\n5. For visual/design work, ask whether the user wants visual verification unless they explicitly requested it. Only after they opt in, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate.\n6. Report what changed and what verification ran.\n\n## Visual Design Workflow\n\nFor requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:\n\n1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.\n2. Do not use generated route/component files as the source of truth for editable content.\n3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.\n4. Ask whether the user wants visual verification unless they explicitly requested screenshots, visual verification, or a rendered audit. Do not start preview, screenshots, screenshot diffs, OCR installation, or rendered audits until they opt in.\n5. After they opt in, keep generated project files current, start preview, and capture the changed page with `screenshot`.\n6. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n7. If the user declines or vision tooling is unavailable, use focused non-visual assertions and state that vision was not run.\n\n## Responsive Verification Workflow\n\nFor responsive page work, use Builder breakpoints as the source of truth:\n\n1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.\n2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.\n3. Ask whether the user wants visual verification unless they explicitly requested it. Do not capture responsive screenshots until they opt in.\n4. Pick screenshot viewport widths from the project breakpoints: include a desktop width, each defined max-width or min-width edge, and a narrow mobile width.\n5. Capture each viewport with `screenshot`, for example `{"path":"/","output":"home-375.png","viewport":{"width":375,"height":812}}` and `{"path":"/","output":"home-1440.png","viewport":{"width":1440,"height":900}}`.\n6. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n7. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.\n\n## Generated Files Guardrails\n\n- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.\n- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.\n- Generated files are build artifacts and may be overwritten by `webstudio build`.\n- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.\n\n## Values vs Bindings\n\nBefore authoring unfamiliar expressions, read `webstudio://project/expressions` with MCP `resources/read` or `webstudio mcp read-resource webstudio://project/expressions`. It documents the supported expression subset, method allowlist, scope, Collection context, and validation limits.\n\n- Use direct value tools for fixed content. For one visible text child, use `update-text` with plain `text`. For a bounded multi-instance literal replacement, use `replace-text` with `find`, `replace`, `pagePath` or `pageId`, and `limit`; it does not change expression children. Use `replace-prop-text` for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop\'s direct type/value.\n- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.\n- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.\n- Expression binding example: `{"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}`.\n- Page metadata fields contain JavaScript expression source. For fixed text, pass a quoted string expression such as `"Pricing | Acme"`; for computed values, pass code such as `pageTitle ?? "Pricing | Acme"`. An unquoted word is a variable reference, not fixed text.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599, for example `302`. For a dynamic status, pass JavaScript expression code such as `system.status`.\n- Page metadata update example: use `update-page` with `{"pageId":"page-id","values":{"title":"\\"Pricing | Acme\\"","meta":{"description":"\\"Plans for teams\\""}}}`.\n- Draft a page with `update-page` and `{"pageId":"page-id","values":{"isDraft":true}}`. It remains editable and previewable but is omitted from every publish target, including staging, and from sitemap output.\n- Stage a draft page for a future publish with `{"pageId":"page-id","values":{"isDraft":false}}`. This clears draft state but does not deploy the site. The home page and `/*` catch-all page cannot be drafts.\n- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.\n- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.\n- Assets is one system resource that always executes a structured query. `result:"many"` returns the existing ID-keyed collection shape and is the backward-compatible default. `result:"one"`, `result:"first"`, and `result:"last"` return one direct item or `null`; first and last require explicit sorting. `create-assets-resource` without `query` uses the default URL and optional image-dimensions output.\n- Choose the article format before building a blog. Use `.mdx` with a Content Block for Notion-style visual body editing in Content mode; publishing downloads and compiles each reachable MDX article, which can slow publishing as the blog grows. Use `.md` with Markdown Embed when editors can work in the Markdown file editor in Assets instead; they can edit the source in Content mode but not the body visually on the canvas. `.md` needs no per-article MDX compilation, but the current publish sync still downloads Asset files for both formats, and static generation may read Markdown bodies.\n- For a Markdown-backed blog, create exactly two Builder page definitions: a fixed `/blog` overview and one `/blog/:slug` detail page. Both pages load content through Assets resources. Never create one Builder page per post or duplicate Markdown content into static page structures. Read `get-asset-field-catalog`, validate each structured query with `validate-asset-query`, then call `create-assets-resource` or `update-assets-resource`. Set `values.query:null` to restore the default query.\n- Optimize every explicit Assets query for the deployed content-database size. Use `output.mode:"fields"` and select only fields that are actually rendered or otherwise required by the query. Keep `includeMetadata:false` unless the rendered value needs file metadata; diagnostics are returned separately. Do not use `output.mode:"all"` as a convenience default.\n- Every reachable Assets data source contributes to the shared database. Keep one final resource per rendered query. Update an existing scoped resource instead of creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicate resources and data sources.\n- Make a bounded overview fully static: use literal values for its filters, limit, and offset, add a deterministic ID tie-breaker to its sort, and use `content.mode:"none"`. This lets compilation materialize the small overview result instead of retaining overview-only fields across every candidate article. Reserve runtime expressions for values that are truly dynamic, such as `system.params.slug` on the detail route.\n- Query Markdown or MDX files directly and use `content.mode:"markdown-body-ref"` when rendering their bodies. The published database keeps only metadata and document references, filters and paginates first, and fetches the selected files from Asset storage at runtime. Do not create companion JSON descriptors merely to avoid embedding the document.\n- `full` and bounded `range` request embedded file bytes. Use them only when the caller explicitly requires the complete source or a byte range.\n- Deferred Markdown or MDX bodies exclude frontmatter and resolve conventional relative links and images such as `../images/hero.png` to matching Assets. Markdown Embed permits sanitized figures, audio, video, and iframes, but removes scripts, inline event handlers, and unsafe URLs. It does not render Webstudio MDX elements; connect the `.mdx` file to a Content Block for that workflow.\n- For `result:"many"`, Assets expose an ID-keyed map at `<dataSourceName>.data` and `totalCount`/`hasMore` at `<dataSourceName>.meta`; bind a listing Collection to `posts.data`. Single-result modes expose the selected item or `null` directly at `<dataSourceName>.data`, always include its `id`, and expose `totalCount` in meta. Bind detail components and page settings directly from expressions such as `post.data.properties.title`, `post.data.content.text`, and `post.data ? 200 : 404` without a Collection.\n- Use `preview-asset-query` with concrete values before binding expressions in the saved resource. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes are not separate allowances and must not be summed. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A finished Markdown blog must include every source document without truncation, contain no embedded Markdown bodies, and retain only the intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files. Inspect saved mode and configuration with `list-assets-resources` or `get-assets-resource`; shared index maintenance is automatic.\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays, objects, filters, and nested data.\n- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.\n- Use scoped resources for read data. A GET resource created with `scopeInstanceId`/`dataSourceName` defaults to `exposeAsDataSource:true`, becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Read the loaded resource result from its wrapper, usually `.data`.\n- Use prop-bound resources for actions. A resource created without `scopeInstanceId` and bound to a component prop such as Form `action` with `bind-props` and `binding.type: "resource"` becomes an action resource in the page resource `action` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.\n- POST, PUT, and DELETE resources default to `exposeAsDataSource:false`, even with a scope. Set `exposeAsDataSource:true` only for an intentional render-time read such as a GraphQL POST query; provide `scopeInstanceId` and inspect the returned warning. Set it to `false` during `update-resource` to detach existing render-time exposure.\n- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Use `{"type":"literal","value":"website"}` for fixed request text. Header values can use an expression such as `"Bearer " + auth.token`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.\n- Resource methods are `get`, `post`, `put`, and `delete`. Optional resource controls are `graphql` and `system`. Use `control:"graphql"` for GraphQL POST resources with query bodies. Use `control:"system"` for built-in local resource URLs such as `"/$resources/current-date"` and for resources reading the built-in `system` parameter. The built-in system fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`; do not use `system.path`.\n- Whenever an array or object from a resource or data variable should render repeated UI, call `insert-collection` with the complete iterable and one repeated-item JSX root. The command creates the Collection, private item parameters, iterable binding, and descendant item bindings atomically. Use `collectionItem` and `collectionItemKey` expressions in the item JSX. Wrap multiple repeated siblings in one Element, and give repeated Radix items stable unique `value` bindings.\n- Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, `new`, `this`, `await`, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Property and index access are made safe automatically, so write direct access. Use nullish coalescing when a fallback is required.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- Never run visual verification automatically. Ask first unless the user explicitly requested screenshots, visual verification, or a rendered audit; if they do not opt in, use focused non-visual assertions.\n- Do not edit generated files for normal Webstudio content/design requests.\n- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.\n- Use expression source for page metadata. Quote fixed text as a JavaScript string literal within the JSON string.\n- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n',"manual-mcp":- '# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\nIf you are already working with a shell-capable agent, it can use the local CLI\ndirectly. Native MCP client registration is optional. Give the editable Builder\nshare link only when the trusted agent asks for it. Treat the share link as a\ncredential: do not include it in committed files, screenshots, logs, or issue\nreports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nDo not run `webstudio sync`, install an MCP server, change client configuration,\nor restart the app for this local CLI workflow.\n\nWhen the user explicitly wants persistent native MCP integration, run\n`webstudio connect claude`, `webstudio connect codex`, `webstudio connect\ncursor`, or `webstudio connect vscode`. This optional command changes client\nconfiguration, so follow its client-specific reload or restart instruction.\nUse `--print` to inspect the generated setup without changing configuration or\nrequiring project access. For Codex, `connect` registers and verifies the server\nthrough the Codex CLI. Before changing client configuration, `connect` verifies\nthat the saved project endpoint is reachable and its credential is accepted.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\n### Tool name convention\n\nMCP tool names are opaque strings, not JavaScript property access. A dot separates a namespace from its tool name, and every segment uses lowercase kebab-case. For example, `components.coverage-insert-next` is the `coverage-insert-next` tool in the `components` namespace. Pass the complete name as one CLI argument: `webstudio components.coverage-insert-next`. Batch `mcp run` calls also accept the underscore form advertised by MCP protocol discovery, such as `components_coverage_insert_next`. Unknown names return near matches and direct you to `meta.index`.\n\n### Readable fragment inputs\n\nPrefer `--input-file` for JSX so JSON and shell quoting do not obscure the fragment. For example, save this as `.temp/insert-fragment.json`:\n\n```json\n{\n "parentInstanceId": "root-id",\n "fragment": "<section ws:style={css`padding: 32px; display: grid; gap: 16px;`}><h2>Northstar Product OS</h2><p>Reusable patterns for teams.</p></section>"\n}\n```\n\nThen run `webstudio insert-fragment --input-file .temp/insert-fragment.json`. Single quotes inside the JSX keep the JSON valid and readable without backslash-escaped attributes.\n\nWrite and review larger fragments as JSX before placing them in the `fragment` field. Common patterns:\n\n```tsx\n<section style={{ padding: 32, borderRadius: 16 }}>\n <h2>Operations Console</h2>\n <p>\n React-style object styles become editable Webstudio styles.\n </p>\n</section>\n\n<section ws:tokens={[token("accent", css`color: #0f766e;`)]}>\n <button\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n >\n Track launch\n </button>\n</section>\n\n<section ws:tokens={[token("accent")]}>Reuse an existing accent token</section>\n\n<section>\n <Switch>\n <SwitchThumb />\n </Switch>\n</section>\n```\n\nUse the two-argument `token` form with a `css` template to define styles in the\nfragment. Use `token("name")` to attach an existing project token; an unknown\nname is an error.\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\n- In `insert-fragment` JSX, use ``ws:style={css`...`}`` for Webstudio-native CSS, or use React-style object syntax such as `style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- `css` templates accept declarations and `@media` rules. Do not put selectors or unsupported at-rules such as `@keyframes` inside them. Use direct animation component identifiers such as `<AnimateChildren>`; `animation` is accepted only as legacy input and is not a callable CSS keyframes helper.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<Switch><SwitchThumb /></Switch>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build version. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- To work with another previously linked project without changing the directory\'s default link, start MCP or a shell call with `--project <projectId>`, for example `webstudio mcp --project <projectId>` or `webstudio mcp single-op-call list-pages --project <projectId>`. Selected projects use isolated local session and checkpoint files.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## MDX-backed Content Blocks\n\nUse a connected `.mdx` Asset when editors should change a Content Block body visually while the document remains stored as a file.\n\n### Connect a collection to its entry page\n\nWhen MDX files belong to a content collection, connect the collection to its dynamic entry page explicitly. Read the page ID after finding or creating the page, verify that its path has exactly one URL parameter, and store the ID at `x-webstudio.entryPageId` in `collection.json`. Do not assume Webstudio infers the page from its path, Assets query, or Content Block source. Preserve the rest of `collection.json`, and verify **Open on canvas** from both an entry asset menu and **Entry settings** before handoff. If no compatible page exists, leave the field unset and report that entry navigation still needs configuration.\n\n```json\n{\n "x-webstudio": {\n "template": "template.mdx",\n "entries": ["*.mdx"],\n "entryPageId": "<dynamic-entry-page-id>"\n }\n}\n```\n\n1. Create the `.mdx` file under `.webstudio/assets`, then upload it and keep the returned Asset ID.\n2. Inspect the Content Block and verify that it has exactly one direct Templates container. Every custom template referenced from MDX needs a unique top-level instance name. A missing or second Templates container blocks connected MDX materialization and publication.\n3. Connect the Asset with `connect-content-block-source`. Use a stable page-based `renderScope` for a direct occurrence.\n4. If the result returns `requiresConfirmation:true`, tell the user that connecting will replace the existing Body content. Repeat the same call with `confirmReplacement:true` only after approval.\n5. Edit the complete source with `edit-content-block-source`, or replace the complete frontmatter map with `update-content-block-frontmatter`.\n6. Inspect every returned diagnostic. Invalid MDX is preserved, not silently repaired.\n\n```sh\nwebstudio upload-asset \'{"asset":{"name":"article.mdx","type":"file","format":"mdx","meta":{}},"assetsDir":".webstudio/assets"}\'\nwebstudio connect-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":{"type":"asset","assetId":"<mdxAssetId>"}}\'\nwebstudio inspect-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\'\nwebstudio edit-content-block-source --input-file .temp/edit-content-block-source.json\nwebstudio reload-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\'\nwebstudio migrate-content-block-template-references \'{"assetIds":["<mdxAssetId>"],"migration":{"type":"rename","from":"Old template name","to":"New template name"}}\'\n```\n\nPrefer Markdown for standard document content. Markdown nodes automatically use a unique matching semantic template when one exists and keep their normal semantic fallback otherwise. Use lowercase JSX such as `<section>` or `<svg>` for a standard HTML or SVG element with authored properties Markdown cannot express.\n\nReference a uniquely named top-level custom template with capitalized JSX such as `<PromotionCard tone="featured">Content</PromotionCard>`. The template\'s stable **Name** must be a valid JSX component identifier and is independent from its display label. A template name wins over a built-in MDX adapter. Other registered components are unavailable until added to this Content Block\'s Templates. Attributes accept quoted static values and bare booleans. Expressions such as `{false}` are unsupported, as are imports, spreads, functions, and executable JavaScript. Legacy `ws.element` and `ws:name` forms are read for compatibility but are not emitted or recommended. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use the direct component identifier.\n\nWhen explicit JSX children match the designed template structure, their text and supported props overlay the cloned descendants so template styles stay intact. A mismatched child structure replaces the root defaults, and each authored child still resolves through a matching template when possible. An explicit empty pair such as `<PromotionCard></PromotionCard>` clears the defaults. A self-closing reference such as `<PromotionCard />` keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live: adding a missing semantic or named template later also updates existing MDX without rewriting it. Preserve unresolved template names and report their diagnostics.\n\nWhen a template is renamed or deleted, use `migrate-content-block-template-references` to update the affected MDX files. Its first call returns a plan with changed-file, update, omission, and diagnostic counts. Report the plan and repeat the exact request with its `confirmationToken` only after approval. Renames and removals update named JSX and legacy `ws:name` references, including names such as `Image` and `CodeText` when they identify templates. Rename targets must be valid PascalCase JSX identifiers. Removing a paired reference unwraps and preserves its explicit authored children; removing a self-closing reference removes that node because it has no authored children. Invalid files remain unchanged and are reported in diagnostics.\n\nUse the dedicated connect, switch, inspect, edit, update-frontmatter, reload, and disconnect operations instead of creating or deleting the Content Block\'s `src` with generic prop tools. An expression-bound source inside a Collection also needs the occurrence\'s scoped values and a distinct stable `renderScope`. For example, use `source:{"type":"expression","value":"post.assetId"}` with `variables:{"post":{"assetId":"<mdxAssetId>"}}`.\n\n`renderScope` is any non-empty stable identity for one rendered occurrence, such as `page:/articles/example`. It does not load that page, its route parameters, or its resource results. To connect a result-one Assets resource, run `preview-asset-query` with concrete values, keep the saved source expression such as `post.data.id`, and supply the previewed item for this occurrence with `variables:{"post":{"data":{"id":"<mdxAssetId>"}}}`. The operation validates that concrete Asset while persisting the dynamic expression.\n\nA source edit replaces the complete MDX document. A frontmatter update replaces the complete frontmatter property map. Inspect the current source first and preserve everything the user did not ask to change. Store frontmatter images as exact `$ref` objects. Bind editable Image sources to their resolved `.src` with explicit `binding.mode:"readwrite"`; omitting the mode leaves the image visible but not replaceable in Content mode. Bind alt properties to their Asset `.description` with `mode:"read"`. Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document\'s frontmatter. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings.\n\nFor an editable MDX article, use the resource to select the Content Block\'s source Asset (`post.data.id`), then bind article fields inside the block to its document parameter (`document.frontmatter.title`), not query-result properties. Inspect the actual document variable name first. Create writable bindings explicitly: `update-text` uses `expressionBindingMode:"readwrite"`; `bind-props` uses `binding.mode:"readwrite"`. These generic tools target persistent designed instances, such as a header outside the MDX body, not MDX-generated instances. The MDX body is editable through its source mapping; merely placing static or query-bound content inside the block does not make it editable. Use exact direct paths; property access is already safe. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. Follow the complete article editability checklist below before handoff.\n\n### Content Block completion checklist\n\nFor every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.\n\n### Complete article editability is required\n\nWhen the user asks for the whole article to be editable in Content mode, this includes every article-owned value: title, excerpt, author details and links, dates, reading time, categories, hero and inline image sources, alternative text, captions, body text, links, and custom-component content and media. Exclude only designer-owned layout, styling, templates, and shared navigation/footer unless the user asks otherwise. A correct preview, a successful MCP write, or an editable body does not prove this requirement is met.\n\nBefore handoff:\n\n1. Inventory every article field, its UI control, binding, and source file/field. Header fields outside **MDX content** are still part of the article and must be editable through the Content Block\'s document bindings.\n2. In Content mode, edit every inventoried field through the UI, including choosing a different hero image and editing link destinations and custom-component props. Do not substitute a raw MDX/YAML edit or an MCP write for this check.\n3. Read the saved source after each edit. Confirm the intended MDX body/frontmatter or referenced author file changed, unrelated content stayed intact, and the edit survives reload. Restore test values and verify restoration.\n4. Mark each field passed, failed, or not tested. Do not claim the article is fully editable while any required field is failed or untested.\n\n**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.\n\nKeep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.\n\nIf an edit in a long-lived MCP session reports a revision conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly. Use `disconnect-content-block-source` to remove the connection while leaving the Asset unchanged.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get-more-tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details\n- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: compact metadata for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n- `search-project`: find a known value or id with `webstudio search-project \'{"query":"pricing"}\'` or MCP `search-project {"query":"pricing"}`; use focused list/get tools when the target structure is unknown\n\n`meta.guide` returns structured `routing` with the selected workflow and any broad context bundle it recommends. Authentication and design context bundles appear only when their specialized workflow is selected. Set `authoredFragment` when using an authored fragment and `reuseDesignSystem` when its recommendations should retain design-system discovery tools.\n\nSet `taskScope` and `workflow` explicitly; `meta.guide` does not infer them or the authored-fragment flags from the brief. Specialized workflows are `markdown-blog`, `json-ld`, `collection`, `expression`, `authenticated-page`, `font-assets`, `design-input`, `content-block-source`, and `craft`; otherwise use `general`. Use `content-block-source` to connect or edit a Markdown/MDX-backed Content Block, including writable bindings for its designed header. For work that must not change project or local state, pass `{"brief":"Inventory custom code","taskScope":"read-only-audit","workflow":"general"}`. The resulting `read-only-discovery` workflow excludes mutation and side-effecting session tools and uses focused search, list, get, inspect, and snapshot tools.\n\n`search-project` follows normal ProjectSession synchronization, then searches in the CLI process. Namespace filters limit values matched; related namespaces may still supply route and reference context, and synchronization is unchanged. Only paged matches enter model context. Recognized credential fields and asset binary or document bodies are excluded.\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Search all Builder namespaces for a known value or id without putting complete namespace data in model context.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, and JSON variables. Arrays use JSON.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List and inspect complete asset metadata; upload, download, update, move, duplicate, find usage for, replace, and delete assets.\n- List, create, rename, move, recursively duplicate, and recursively delete nested asset folders.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- Read `meta.session.commitStatus` before interpreting durability. Read-only results report `not-applicable` and retain `committed:false` for compatibility; dry-run plans report `planned`; failed mutations report `failed`; no-op mutations report `unchanged`; durable mutations report `committed` with `meta.session.committed:true`.\n- Never run visual verification automatically. Ask first unless the user explicitly requested screenshots, visual verification, or a rendered audit; if they do not opt in, use focused non-visual assertions.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP argument examples\n\nExamples below show meaningful argument combinations. Tool schemas are the\nsource of truth. For tools with no required arguments, pass `{}`.\n\n{{mcpArgumentExampleIndex}}\n\n{{contentEngineReferenceMarkdown}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',+ '# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\nIf you are already working with a shell-capable agent, it can use the local CLI\ndirectly. Native MCP client registration is optional. Give the editable Builder\nshare link only when the trusted agent asks for it. Treat the share link as a\ncredential: do not include it in committed files, screenshots, logs, or issue\nreports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nDo not run `webstudio sync`, install an MCP server, change client configuration,\nor restart the app for this local CLI workflow.\n\nWhen the user explicitly wants persistent native MCP integration, run\n`webstudio connect claude`, `webstudio connect codex`, `webstudio connect\ncursor`, or `webstudio connect vscode`. This optional command changes client\nconfiguration, so follow its client-specific reload or restart instruction.\nUse `--print` to inspect the generated setup without changing configuration or\nrequiring project access. For Codex, `connect` registers and verifies the server\nthrough the Codex CLI. Before changing client configuration, `connect` verifies\nthat the saved project endpoint is reachable and its credential is accepted.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\n### Tool name convention\n\nMCP tool names are opaque strings, not JavaScript property access. A dot separates a namespace from its tool name, and every segment uses lowercase kebab-case. For example, `components.coverage-insert-next` is the `coverage-insert-next` tool in the `components` namespace. Pass the complete name as one CLI argument: `webstudio components.coverage-insert-next`. Batch `mcp run` calls also accept the underscore form advertised by MCP protocol discovery, such as `components_coverage_insert_next`. Unknown names return near matches and direct you to `meta.index`.\n\n### Readable fragment inputs\n\nPrefer `--input-file` for JSX so JSON and shell quoting do not obscure the fragment. For example, save this as `.temp/insert-fragment.json`:\n\n```json\n{\n "parentInstanceId": "root-id",\n "fragment": "<section ws:style={css`padding: 32px; display: grid; gap: 16px;`}><h2>Northstar Product OS</h2><p>Reusable patterns for teams.</p></section>"\n}\n```\n\nThen run `webstudio insert-fragment --input-file .temp/insert-fragment.json`. Single quotes inside the JSX keep the JSON valid and readable without backslash-escaped attributes.\n\nWrite and review larger fragments as JSX before placing them in the `fragment` field. Common patterns:\n\n```tsx\n<section style={{ padding: 32, borderRadius: 16 }}>\n <h2>Operations Console</h2>\n <p>\n React-style object styles become editable Webstudio styles.\n </p>\n</section>\n\n<section ws:tokens={[token("accent", css`color: #0f766e;`)]}>\n <button\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n >\n Track launch\n </button>\n</section>\n\n<section ws:tokens={[token("accent")]}>Reuse an existing accent token</section>\n\n<section>\n <Switch>\n <SwitchThumb />\n </Switch>\n</section>\n```\n\nUse the two-argument `token` form with a `css` template to define styles in the\nfragment. Use `token("name")` to attach an existing project token; an unknown\nname is an error.\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\n- In `insert-fragment` JSX, use ``ws:style={css`...`}`` for Webstudio-native CSS, or use React-style object syntax such as `style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- `css` templates accept declarations and `@media` rules. Do not put selectors or unsupported at-rules such as `@keyframes` inside them. Use direct animation component identifiers such as `<AnimateChildren>`; `animation` is accepted only as legacy input and is not a callable CSS keyframes helper.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<Switch><SwitchThumb /></Switch>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build version. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- To work with another previously linked project without changing the directory\'s default link, start MCP or a shell call with `--project <projectId>`, for example `webstudio mcp --project <projectId>` or `webstudio mcp single-op-call list-pages --project <projectId>`. Selected projects use isolated local session and checkpoint files.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## MDX-backed Content Blocks\n\nUse a connected `.mdx` Asset when editors should change a Content Block body visually while the document remains stored as a file.\n\nChoose this format before building a blog: each reachable connected MDX article is downloaded and compiled when publishing, so publishing can take longer as the blog grows. If editors only need to edit Markdown source in Assets, use `.md` with Markdown Embed instead. Content mode editors can edit those files in the Markdown file editor, but cannot edit the article body visually on the canvas. `.md` does not need per-article MDX compilation; the current publish sync still transfers Asset files for either format, and static generation may read Markdown bodies.\n\n### Connect a collection to its entry page\n\nWhen MDX files belong to a content collection, connect the collection to its dynamic entry page explicitly. Read the page ID after finding or creating the page, verify that its path has exactly one URL parameter, and store the ID at `x-webstudio.entryPageId` in `collection.json`. Do not assume Webstudio infers the page from its path, Assets query, or Content Block source. Preserve the rest of `collection.json`, and verify **Open on canvas** from both an entry asset menu and **Entry settings** before handoff. If no compatible page exists, leave the field unset and report that entry navigation still needs configuration.\n\n```json\n{\n "x-webstudio": {\n "template": "template.mdx",\n "entries": ["*.mdx"],\n "entryPageId": "<dynamic-entry-page-id>"\n }\n}\n```\n\n1. Create the `.mdx` file under `.webstudio/assets`, then upload it and keep the returned Asset ID.\n2. Inspect the Content Block and verify that it has exactly one direct Templates container. Every custom template referenced from MDX needs a unique top-level instance name. A missing or second Templates container blocks connected MDX materialization and publication.\n3. Connect the Asset with `connect-content-block-source`. Use a stable page-based `renderScope` for a direct occurrence.\n4. If the result returns `requiresConfirmation:true`, tell the user that connecting will replace the existing Body content. Repeat the same call with `confirmReplacement:true` only after approval.\n5. Edit the complete source with `edit-content-block-source`, or replace the complete frontmatter map with `update-content-block-frontmatter`.\n6. Inspect every returned diagnostic. Invalid MDX is preserved, not silently repaired.\n\n```sh\nwebstudio upload-asset \'{"asset":{"name":"article.mdx","type":"file","format":"mdx","meta":{}},"assetsDir":".webstudio/assets"}\'\nwebstudio connect-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":{"type":"asset","assetId":"<mdxAssetId>"}}\'\nwebstudio inspect-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\'\nwebstudio edit-content-block-source --input-file .temp/edit-content-block-source.json\nwebstudio reload-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\'\nwebstudio migrate-content-block-template-references \'{"assetIds":["<mdxAssetId>"],"migration":{"type":"rename","from":"Old template name","to":"New template name"}}\'\n```\n\nPrefer Markdown for standard document content. Markdown nodes automatically use a unique matching semantic template when one exists and keep their normal semantic fallback otherwise. Use lowercase JSX such as `<section>` or `<svg>` for a standard HTML or SVG element with authored properties Markdown cannot express.\n\nReference a uniquely named top-level custom template with capitalized JSX such as `<PromotionCard tone="featured">Content</PromotionCard>`. The template\'s stable **Name** must be a valid JSX component identifier and is independent from its display label. A template name wins over a built-in MDX adapter. Other registered components are unavailable until added to this Content Block\'s Templates. Attributes accept quoted static values and bare booleans. Expressions such as `{false}` are unsupported, as are imports, spreads, functions, and executable JavaScript. Legacy `ws.element` and `ws:name` forms are read for compatibility but are not emitted or recommended. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use the direct component identifier.\n\nWhen explicit JSX children match the designed template structure, their text and supported props overlay the cloned descendants so template styles stay intact. A mismatched child structure replaces the root defaults, and each authored child still resolves through a matching template when possible. An explicit empty pair such as `<PromotionCard></PromotionCard>` clears the defaults. A self-closing reference such as `<PromotionCard />` keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live: adding a missing semantic or named template later also updates existing MDX without rewriting it. Preserve unresolved template names and report their diagnostics.\n\nWhen a template is renamed or deleted, use `migrate-content-block-template-references` to update the affected MDX files. Its first call returns a plan with changed-file, update, omission, and diagnostic counts. Report the plan and repeat the exact request with its `confirmationToken` only after approval. Renames and removals update named JSX and legacy `ws:name` references, including names such as `Image` and `CodeText` when they identify templates. Rename targets must be valid PascalCase JSX identifiers. Removing a paired reference unwraps and preserves its explicit authored children; removing a self-closing reference removes that node because it has no authored children. Invalid files remain unchanged and are reported in diagnostics.\n\nUse the dedicated connect, switch, inspect, edit, update-frontmatter, reload, and disconnect operations instead of creating or deleting the Content Block\'s `src` with generic prop tools. An expression-bound source inside a Collection also needs the occurrence\'s scoped values and a distinct stable `renderScope`. For example, use `source:{"type":"expression","value":"post.assetId"}` with `variables:{"post":{"assetId":"<mdxAssetId>"}}`.\n\n`renderScope` is any non-empty stable identity for one rendered occurrence, such as `page:/articles/example`. It does not load that page, its route parameters, or its resource results. To connect a result-one Assets resource, run `preview-asset-query` with concrete values, keep the saved source expression such as `post.data.id`, and supply the previewed item for this occurrence with `variables:{"post":{"data":{"id":"<mdxAssetId>"}}}`. The operation validates that concrete Asset while persisting the dynamic expression.\n\nA source edit replaces the complete MDX document. A frontmatter update replaces the complete frontmatter property map. Inspect the current source first and preserve everything the user did not ask to change. Store frontmatter images as exact `$ref` objects. Bind editable Image sources to their resolved `.src` with explicit `binding.mode:"readwrite"`; omitting the mode leaves the image visible but not replaceable in Content mode. Bind alt properties to their Asset `.description` with `mode:"read"`. Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document\'s frontmatter. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings.\n\nFor an editable MDX article, use the resource to select the Content Block\'s source Asset (`post.data.id`), then bind article fields inside the block to its document parameter (`document.frontmatter.title`), not query-result properties. Inspect the actual document variable name first. Create writable bindings explicitly: `update-text` uses `expressionBindingMode:"readwrite"`; `bind-props` uses `binding.mode:"readwrite"`. These generic tools target persistent designed instances, such as a header outside the MDX body, not MDX-generated instances. The MDX body is editable through its source mapping; merely placing static or query-bound content inside the block does not make it editable. Use exact direct paths; property access is already safe. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. Follow the complete article editability checklist below before handoff.\n\n### Content Block completion checklist\n\nFor every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.\n\n### Complete article editability is required\n\nWhen the user asks for the whole article to be editable in Content mode, this includes every article-owned value: title, excerpt, author details and links, dates, reading time, categories, hero and inline image sources, alternative text, captions, body text, links, and custom-component content and media. Exclude only designer-owned layout, styling, templates, and shared navigation/footer unless the user asks otherwise. A correct preview, a successful MCP write, or an editable body does not prove this requirement is met.\n\nBefore handoff:\n\n1. Inventory every article field, its UI control, binding, and source file/field. Header fields outside **MDX content** are still part of the article and must be editable through the Content Block\'s document bindings.\n2. In Content mode, edit every inventoried field through the UI, including choosing a different hero image and editing link destinations and custom-component props. Do not substitute a raw MDX/YAML edit or an MCP write for this check.\n3. Read the saved source after each edit. Confirm the intended MDX body/frontmatter or referenced author file changed, unrelated content stayed intact, and the edit survives reload. Restore test values and verify restoration.\n4. Mark each field passed, failed, or not tested. Do not claim the article is fully editable while any required field is failed or untested.\n\n**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.\n\nKeep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.\n\nIf an edit in a long-lived MCP session reports a revision conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly. Use `disconnect-content-block-source` to remove the connection while leaving the Asset unchanged.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get-more-tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details\n- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: compact metadata for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n- `search-project`: find a known value or id with `webstudio search-project \'{"query":"pricing"}\'` or MCP `search-project {"query":"pricing"}`; use focused list/get tools when the target structure is unknown\n\n`meta.guide` returns structured `routing` with the selected workflow and any broad context bundle it recommends. Authentication and design context bundles appear only when their specialized workflow is selected. Set `authoredFragment` when using an authored fragment and `reuseDesignSystem` when its recommendations should retain design-system discovery tools.\n\nSet `taskScope` and `workflow` explicitly; `meta.guide` does not infer them or the authored-fragment flags from the brief. Specialized workflows are `markdown-blog`, `json-ld`, `collection`, `expression`, `authenticated-page`, `font-assets`, `design-input`, `content-block-source`, and `craft`; otherwise use `general`. Use `content-block-source` to connect or edit a Markdown/MDX-backed Content Block, including writable bindings for its designed header. For work that must not change project or local state, pass `{"brief":"Inventory custom code","taskScope":"read-only-audit","workflow":"general"}`. The resulting `read-only-discovery` workflow excludes mutation and side-effecting session tools and uses focused search, list, get, inspect, and snapshot tools.\n\n`search-project` follows normal ProjectSession synchronization, then searches in the CLI process. Namespace filters limit values matched; related namespaces may still supply route and reference context, and synchronization is unchanged. Only paged matches enter model context. Recognized credential fields and asset binary or document bodies are excluded.\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Search all Builder namespaces for a known value or id without putting complete namespace data in model context.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, and JSON variables. Arrays use JSON.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List and inspect complete asset metadata; upload, download, update, move, duplicate, find usage for, replace, and delete assets.\n- List, create, rename, move, recursively duplicate, and recursively delete nested asset folders.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- Read `meta.session.commitStatus` before interpreting durability. Read-only results report `not-applicable` and retain `committed:false` for compatibility; dry-run plans report `planned`; failed mutations report `failed`; no-op mutations report `unchanged`; durable mutations report `committed` with `meta.session.committed:true`.\n- Never run visual verification automatically. Ask first unless the user explicitly requested screenshots, visual verification, or a rendered audit; if they do not opt in, use focused non-visual assertions.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP argument examples\n\nExamples below show meaningful argument combinations. Tool schemas are the\nsource of truth. For tools with no required arguments, pass `{}`.\n\n{{mcpArgumentExampleIndex}}\n\n{{contentEngineReferenceMarkdown}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',"mcp-startup-epilogue":'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output.\n\nPlain `webstudio mcp` starts the stdio MCP server for real MCP clients. Do not manually type or pipe raw JSON-RPC frames into it from an interactive shell or PTY. From a shell, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for one bounded tool call. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for small multi-call batches in one shared CLI session. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nPut each local CLI call in its own shell command; do not chain helper commands with `&&`, `;`, command substitution, or shell wrappers around the CLI when reporting a CLI step. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`; those can resolve an older binary. For example:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nSave the input as `.temp/insert-fragment.json`; use single quotes for JSX attributes so the JSON needs no backslash escaping:\n\n```json\n{\n "parentInstanceId": "parent-id",\n "fragment": "<section ws:style={css`padding: 32px; display: grid; gap: 12px;`}><h2>Launch Kit</h2><p>A focused section created with Webstudio JSX.</p><button>Get started</button></section>"\n}\n```\n\nThe shorter local shortcut form is preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nFor simple authored/styled sections, run the three commands above. Do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only when you still need the target `parentInstanceId`.\n\nWhen building for a Content-mode editor, use a Content Block (`ws:block`) around every region that editor must change. Content-mode text and supported props are editable only in Content Block descendants; content outside is read-only. Keep reusable insertable source options in exactly one direct `ws:block-template` child. A missing or second template container makes the block invalid. Templates themselves are protected; an editor\'s inserted copy becomes editable Content Block body content. Verify this structure before handoff.\n\nFor an MDX-backed Content Block, use the dedicated content-source tools instead of generic prop mutations: connect, switch, inspect, edit, update frontmatter, reload, or disconnect the source. Confirm before replacing existing Body content. Prefer Markdown for standard document content; it automatically uses unique matching semantic templates. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG that Markdown cannot express. Capitalized JSX resolves a unique stable template **Name** or a built-in MDX adapter. Add custom components to this Content Block\'s Templates before referencing them in MDX. The display label is independent. JSX attributes accept quoted values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use direct component identifiers. Matching explicit children overlay designed descendants and keep template styles. A mismatched child structure replaces defaults, an explicit empty pair clears defaults, and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live when matching templates are added later. Preserve invalid source and unresolved names, inspect all diagnostics, and reload before retrying a revision conflict. A frontmatter update replaces the complete property map; preserve fields the user did not ask to remove. Store frontmatter images as exact `$ref` objects; bind editable Image sources to `.src` with explicit `binding.mode:"readwrite"` and alt properties to the Asset `.description` with `mode:"read"`. Omitting the source mode leaves the image visible but not replaceable in Content mode. Only exact direct frontmatter bindings may use `mode:"readwrite"`. After a template rename or deletion, use `migrate-content-block-template-references` to preview and confirm custom-template JSX and legacy changes across selected MDX files. A confirmed removal unwraps paired references and preserves their authored children; a self-closing reference disappears because it has none.\n\nFor an editable MDX article, use the resource to select the Content Block\'s source Asset (`post.data.id`), then bind article fields inside the block to its document parameter (`document.frontmatter.title`), not query-result properties. Inspect the actual document variable name first. Create writable bindings explicitly: `update-text` uses `expressionBindingMode:"readwrite"`; `bind-props` uses `binding.mode:"readwrite"`. These generic tools target persistent designed instances, such as a header outside the MDX body, not MDX-generated instances. The MDX body is editable through its source mapping; merely placing static or query-bound content inside the block does not make it editable. Use exact direct paths; property access is already safe. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. Follow the complete article editability checklist below before handoff.\n\n### Content Block completion checklist\n\nFor every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.\n\n### Complete article editability is required\n\nWhen the user asks for the whole article to be editable in Content mode, this includes every article-owned value: title, excerpt, author details and links, dates, reading time, categories, hero and inline image sources, alternative text, captions, body text, links, and custom-component content and media. Exclude only designer-owned layout, styling, templates, and shared navigation/footer unless the user asks otherwise. A correct preview, a successful MCP write, or an editable body does not prove this requirement is met.\n\nBefore handoff:\n\n1. Inventory every article field, its UI control, binding, and source file/field. Header fields outside **MDX content** are still part of the article and must be editable through the Content Block\'s document bindings.\n2. In Content mode, edit every inventoried field through the UI, including choosing a different hero image and editing link destinations and custom-component props. Do not substitute a raw MDX/YAML edit or an MCP write for this check.\n3. Read the saved source after each edit. Confirm the intended MDX body/frontmatter or referenced author file changed, unrelated content stayed intact, and the edit survives reload. Restore test values and verify restoration.\n4. Mark each field passed, failed, or not tested. Do not claim the article is fully editable while any required field is failed or untested.\n\n**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.\n\nKeep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.\n\nRun it from the linked Webstudio project root. The startup status line prints that absolute root; use it for local files such as `<project root>/.temp/script.mjs`, screenshots, and generated artifacts.\n\nFor experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n\nStartup marks cached ProjectSession data stale so MCP tools read the current Builder dev build.\n\nAfter startup, use focused discovery tools with concrete JSON. For delegated design-system or “use every component” tasks, start with exactly one command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`; report the returned checkpoint to the parent/user and stop until continued. For other tasks, read `meta.index` first. From a shell, `webstudio mcp list-tools` is a concise alias for the initial tool catalog. Then call shortcuts such as `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio workflow.next \'{"goal":"design-system-page"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.summary`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`. Use `webstudio mcp single-op-call` when you need the explicit MCP form. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. In JSX, use `ws:style={css\\`...\\`}`for styles,`class`/`for`instead of`className`/`htmlFor`, `ActionValue`for actions instead of JavaScript functions such as`onClick={() => ...}`, only JSON-compatible plain prop values, and no host globals or dynamic code APIs. For bounded multi-step shell work, run inline JSON like `webstudio mcp run \'[{"tool":"meta.index"},{"tool":"components.search","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For larger batches, write `{ "calls": [{ "tool": "..." }] }`to`.temp/mcp-calls.json`and run`webstudio mcp run .temp/mcp-calls.json`. If any call returns `checkpoint.required`, `mcp run`stops immediately before later calls; report the checkpoint and call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`before continuing. For design-system or “use every component” tasks, call`workflow.next {"goal":"design-system-page"}`for the next bounded phase, report its checkpoint, wait until the parent/user continues, call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, then run only that phase. Start coverage phases with compact`webstudio components.coverage-plan`, checkpoint, then request component coverage details with `components.coverage-plan {"detail":"roots"}`or`components.coverage-plan {"detail":"parts"}`. Do not pass `detail`to`list-pages`; use `list-pages {}`or`get-page-by-path`for page lookup. Read MCP overview resources`webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview`when useful. Read full resources`webstudio://project/tools`and`webstudio://project/components` only when focused tools are insufficient; do not dump or parse full discovery JSON for common lookup.\n\nAfter startup, MCP clients discover capabilities with `tools/list`, `resources/list`, `meta.index`, `meta.guide`, and `meta.get-more-tools`.\n\nstdout is reserved for MCP JSON-RPC messages while the server is running.\n\nThe server advertises MCP `logging` capability and sends sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`. It also writes the same sparse lifecycle status lines to stderr, prefixed with `[webstudio mcp]`, including a final ready line. Treat the process as healthy and long-running after either ready signal; surface tool lifecycle logs as progress checkpoints and interact through MCP JSON-RPC on stdin/stdout.\n\n`webstudio mcp single-op-call` also writes sparse lifecycle lines to stderr for each one-shot call. Use those stderr lines as progress checkpoints and parse stdout as JSON on both success and failure. Failed one-shot calls print `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` to stdout and exit nonzero. If a one-shot call returns checkpoint.required, read-only discovery remains available, while later mutations fail with `CHECKPOINT_REQUIRED` until you report the checkpoint and call `webstudio mcp single-op-call checkpoint.ack \'{"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}\'`.\n\n`webstudio mcp run` also writes sparse lifecycle lines to stderr and prints one JSON result on success or failure. It stops at the first failed call or checkpoint requirement, including `CHECKPOINT_REQUIRED`, and preserves partial results so delegated agents can report exactly where they stopped.\n\nWhen `report-issue` is available, use it when the user explicitly asks to report a problem. Also use it automatically after a Webstudio-controlled tool crash, hang, malformed result, misleading success, repeated failure of the same documented operation, failed documented recovery, or required undocumented workaround. Do not automatically report expected confirmation/checkpoint flow, a clearly explained invalid input, missing permissions, `PROJECT_SESSION_BUSY`, a recovered version conflict, rate limiting, cancellation, or an offline environment. Write a complete technical report with the generalized user story, attempted workflow, expected behavior, actual result, recovery attempts, impact, technical context, acceptance criteria, exact model identifier, and reasoning effort. The CLI attaches the project ID and recognized entity IDs from the failed tool input; do not copy additional IDs into the authored text. Never include names, usernames, emails, phone numbers, organizations, domains, URLs, IP addresses, local paths, credentials, tokens, customer content, other exact unique values, or raw contextual tool data.\n\nIf a mutation returns an unclear transport or response error, make one read-only check to see whether it committed and include that outcome in the report. For browser startup failures, include the selected browser family, whether fallback was attempted, and any shown exit signal or code, but never an executable path. The CLI adds bounded failure diagnostics automatically; do not paraphrase missing values as facts.\n\nIf you are running as a delegated or non-streaming agent whose parent cannot see live stderr/stdout, do not batch many MCP calls silently and do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, return a concise checkpoint with that command/result, and wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase.\n',"mcp-vision":@@ -86,6 +86,7 @@ export const cliDocSections = {'Resource url accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as "https://api.example.com/items?tag=" + filters.tag. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use { "type": "literal", "value": "application/json" }.','Resource update example: use update-resource with {"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}.','Assets is one system resource that always executes a structured query. result:"many" returns the existing ID-keyed collection shape and is the backward-compatible default. result:"one", result:"first", and result:"last" return one direct item or null; first and last require explicit sorting. create-assets-resource without query uses the default URL and optional image-dimensions output.',+ "Choose the article format before building a blog. Use .mdx with a Content Block for Notion-style visual body editing in Content mode; publishing downloads and compiles each reachable MDX article, which can slow publishing as the blog grows. Use .md with Markdown Embed when editors can work in the Markdown file editor in Assets instead; they can edit the source in Content mode but not the body visually on the canvas. .md needs no per-article MDX compilation, but the current publish sync still downloads Asset files for both formats, and static generation may read Markdown bodies.","For a Markdown-backed blog, create exactly two Builder page definitions: a fixed /blog overview and one /blog/:slug detail page. Both pages load content through Assets resources. Never create one Builder page per post or duplicate Markdown content into static page structures. Read get-asset-field-catalog, validate each structured query with validate-asset-query, then call create-assets-resource or update-assets-resource. Set values.query:null to restore the default query.",'Optimize every explicit Assets query for the deployed content-database size. Use output.mode:"fields" and select only fields that are actually rendered or otherwise required by the query. Keep includeMetadata:false unless the rendered value needs file metadata; diagnostics are returned separately. Do not use output.mode:"all" as a convenience default.',"Every reachable Assets data source contributes to the shared database. Keep one final resource per rendered query. Update an existing scoped resource instead of creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicate resources and data sources.",diff --git a/packages/cli/src/docs/api-use-cases.md b/packages/cli/src/docs/api-use-cases.mdindex bf44056eec..7a3c194990 100644--- a/packages/cli/src/docs/api-use-cases.md+++ b/packages/cli/src/docs/api-use-cases.md@@ -849,6 +849,7 @@ Commands:Notes:+- Choose `.mdx` connected to a Content Block when editors must edit article bodies visually in Content mode. Publishing downloads and compiles every reachable MDX article, so more articles can slow publishing. Choose `.md` with Markdown Embed when editing the source in Assets is enough; Content mode editors can still edit the Markdown file there, but not its body on the canvas. `.md` needs no per-article MDX compilation, though the publish runner still synchronizes Asset files for both formats and static generation may read Markdown bodies.- Read the field catalog before authoring unfamiliar queries. It includes dynamic schema-less frontmatter paths such as `properties.author.name`, observed types, optionality, and mixed-type state without downloading the source files.- Minimize the deployed content database by using `output.mode:"fields"` and selecting only fields the rendered page needs. Keep `includeMetadata:false` unless the rendered value needs file metadata such as name, path, MIME type, or creation date, and avoid `output.mode:"all"` as a convenience default. Query diagnostics are returned separately and do not require metadata output. Filters and sorting may still require their referenced fields in the database.- Every reachable Assets data source contributes to the shared published database. Keep one final resource per rendered query. Update an existing scoped resource rather than creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicates.diff --git a/packages/cli/src/docs/manual-llm.md b/packages/cli/src/docs/manual-llm.mdindex 94494b247d..6cb8e674d7 100644--- a/packages/cli/src/docs/manual-llm.md+++ b/packages/cli/src/docs/manual-llm.md@@ -487,6 +487,7 @@ Before authoring unfamiliar expressions, read `webstudio://project/expressions`- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.- Assets is one system resource that always executes a structured query. `result:"many"` returns the existing ID-keyed collection shape and is the backward-compatible default. `result:"one"`, `result:"first"`, and `result:"last"` return one direct item or `null`; first and last require explicit sorting. `create-assets-resource` without `query` uses the default URL and optional image-dimensions output.+- Choose the article format before building a blog. Use `.mdx` with a Content Block for Notion-style visual body editing in Content mode; publishing downloads and compiles each reachable MDX article, which can slow publishing as the blog grows. Use `.md` with Markdown Embed when editors can work in the Markdown file editor in Assets instead; they can edit the source in Content mode but not the body visually on the canvas. `.md` needs no per-article MDX compilation, but the current publish sync still downloads Asset files for both formats, and static generation may read Markdown bodies.- For a Markdown-backed blog, create exactly two Builder page definitions: a fixed `/blog` overview and one `/blog/:slug` detail page. Both pages load content through Assets resources. Never create one Builder page per post or duplicate Markdown content into static page structures. Read `get-asset-field-catalog`, validate each structured query with `validate-asset-query`, then call `create-assets-resource` or `update-assets-resource`. Set `values.query:null` to restore the default query.- Optimize every explicit Assets query for the deployed content-database size. Use `output.mode:"fields"` and select only fields that are actually rendered or otherwise required by the query. Keep `includeMetadata:false` unless the rendered value needs file metadata; diagnostics are returned separately. Do not use `output.mode:"all"` as a convenience default.- Every reachable Assets data source contributes to the shared database. Keep one final resource per rendered query. Update an existing scoped resource instead of creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicate resources and data sources.diff --git a/packages/cli/src/docs/manual-mcp.md b/packages/cli/src/docs/manual-mcp.mdindex 93f68b6577..8be8ac91cc 100644--- a/packages/cli/src/docs/manual-mcp.md+++ b/packages/cli/src/docs/manual-mcp.md@@ -140,6 +140,8 @@ Rules:Use a connected `.mdx` Asset when editors should change a Content Block body visually while the document remains stored as a file.+Choose this format before building a blog: each reachable connected MDX article is downloaded and compiled when publishing, so publishing can take longer as the blog grows. If editors only need to edit Markdown source in Assets, use `.md` with Markdown Embed instead. Content mode editors can edit those files in the Markdown file editor, but cannot edit the article body visually on the canvas. `.md` does not need per-article MDX compilation; the current publish sync still transfers Asset files for either format, and static generation may read Markdown bodies.+### Connect a collection to its entry pageWhen MDX files belong to a content collection, connect the collection to its dynamic entry page explicitly. Read the page ID after finding or creating the page, verify that its path has exactly one URL parameter, and store the ID at `x-webstudio.entryPageId` in `collection.json`. Do not assume Webstudio infers the page from its path, Assets query, or Content Block source. Preserve the rest of `collection.json`, and verify **Open on canvas** from both an entry asset menu and **Entry settings** before handoff. If no compatible page exists, leave the field unset and report that entry navigation still needs configuration.diff --git a/packages/cli/src/filesystem-content-source.test.ts b/packages/cli/src/filesystem-content-source.test.tsindex 141cd1e67f..62f250b87c 100644--- a/packages/cli/src/filesystem-content-source.test.ts+++ b/packages/cli/src/filesystem-content-source.test.ts@@ -5,9 +5,12 @@ import {createContentCompilationPlan,createLiteralContentCompilationQuery,} from "@webstudio-is/content-engine";-import { readBoundedBytes } from "@webstudio-is/content-engine/compiler";+import {+ compileContentSource,+ readBoundedBytes,+} from "@webstudio-is/content-engine/compiler";import type { Asset, AssetFolders } from "@webstudio-is/sdk";-import { afterEach, describe, expect, test } from "vitest";+import { afterEach, describe, expect, test, vi } from "vitest";import { createFileSystemContentSource } from "./filesystem-content-source";const temporaryDirectories: string[] = [];@@ -114,6 +117,59 @@ describe("filesystem content source", () => {await expect(snapshot.isCurrent()).resolves.toBe(true);});+ test("reuses prepared local frontmatter when compiling deferred article queries", async () => {+ const directory = await createTemporaryDirectory();+ const name = "hello_hash.md";+ await writeFile(join(directory, name), "---\ntitle: Hello\n---\n# Body\n");+ const snapshot = await createFileSystemContentSource({+ projectId: "project",+ assets: [createAsset(name)],+ folders,+ assetsDirectory: directory,+ }).openSnapshot();+ const deferredPlan = createContentCompilationPlan([+ createLiteralContentCompilationQuery({+ id: "post",+ query: {+ where: { all: [] },+ sort: [],+ limit: 1,+ offset: 0,+ output: { mode: "base", includeMetadata: false },+ content: { mode: "markdown-body-ref" },+ },+ }),+ ]);+ const readGraphSource = vi.fn(() => {+ throw new Error(+ "Prepared frontmatter must not require a second source read"+ );+ });+ const { artifact } = await compileContentSource({+ projectId: "project",+ plan: deferredPlan,+ source: {+ async openSnapshot() {+ return {+ ...snapshot,+ async loadDocumentSources() {+ return [+ {+ id: "post",+ source: { [Symbol.asyncIterator]: readGraphSource },+ },+ ];+ },+ };+ },+ },+ });++ expect(readGraphSource).not.toHaveBeenCalled();+ expect(artifact.documents).toHaveLength(1);+ expect(artifact.contents).toBeUndefined();+ });+test("invalidates a snapshot when a local file is replaced", async () => {const directory = await createTemporaryDirectory();const name = "hello_hash.md";diff --git a/packages/cli/src/filesystem-content-source.ts b/packages/cli/src/filesystem-content-source.tsindex 9adb48e6d4..157423f8a4 100644--- a/packages/cli/src/filesystem-content-source.ts+++ b/packages/cli/src/filesystem-content-source.ts@@ -5,7 +5,6 @@ import {createCanonicalAssetFileEntry,createContentSourceFile,decodeUtf8,- fullCanonicalAssetMetadataRequirements,normalizeAssetFileDocument,prepareCanonicalContentMetadata,type ContentSource,@@ -14,7 +13,7 @@ import {getDocumentFormatByContentType,isContentDocumentCandidate,prepareContentCompilerEntries,- requiresStructuredProperties,+ getContentCompilationMetadataRequirements,type ContentCompilationPlan,} from "@webstudio-is/content-engine";import {@@ -252,13 +251,7 @@ export const createFileSystemContentSource = ({available: "base",}));- const requirements =- plan === undefined- ? fullCanonicalAssetMetadataRequirements- : {- structuredProperties: requiresStructuredProperties(plan),- excerpt: plan.excerpt,- };+ const requirements = getContentCompilationMetadataRequirements(plan);const prepared = await Promise.all(candidates.map(({ entry, filePath, identity }) =>requirements.structuredProperties === false &&diff --git a/packages/content-engine/src/asset-index.ts b/packages/content-engine/src/asset-index.tsindex 15fc50b380..74103cd313 100644--- a/packages/content-engine/src/asset-index.ts+++ b/packages/content-engine/src/asset-index.ts@@ -39,7 +39,7 @@ import {import { getQueryConditions } from "@webstudio-is/query-builder/runtime";import type { AssetValueReferences } from "./asset-value-references";-export const contentCompilationGeneration = 1;+export const contentCompilationGeneration = 2;export type ContentCompilerDiagnostics = {maxBytes: number;@@ -136,31 +136,12 @@ const isDocumentEvaluationAffectedByAssetValues = ({);export type ContentCompilerInput = CanonicalAssetFileEntry & {+ /** Complete source frontmatter before output-field projection. */+ sourceFrontmatter?: Readonly<Record<string, unknown>>;content?: string;contentRequired?: true;};-const selectMarkdownBodyReferenceIds = ({- entries,- plan,-}: {- entries: readonly ContentCompilerInput[];- plan?: ContentCompilationPlan;-}) => {- if (plan === undefined) {- return new Set<string>();- }- return selectContentHydrationCandidates({- documents: entries.map(({ document }) => document),- plan: {- ...plan,- queries: plan.queries.filter(- ({ content }) => content.mode === "markdown-body-ref"- ),- },- });-};-const excludeReferencedMarkdownBodies = ({entries,documentGraph,@@ -175,15 +156,10 @@ const excludeReferencedMarkdownBodies = ({if (plan === undefined) {return entries;}- const embeddedQueryPlan = {- ...plan,- queries: plan.queries.filter(- ({ content }) => content.mode !== "markdown-body-ref"- ),- };const embeddedIds = selectContentHydrationCandidates({documents: entries.map(({ document }) => document),- plan: embeddedQueryPlan,+ plan,+ mode: "embedded",});const graphNodeIds = new Set(documentGraph.nodes.map(({ id }) => id));const missingNodeIds = [...referencedIds].filter(@@ -294,6 +270,7 @@ const buildAssetIndex = async ({documentContents,plan,finalize = true,+ assetPaths,}: {entries: readonly ContentCompilerInput[];sourceDocumentCount: number;@@ -305,6 +282,7 @@ const buildAssetIndex = async ({documentContents?: Readonly<Record<string, string>>;plan?: ContentCompilationPlan;finalize?: boolean;+ assetPaths?: Readonly<Record<string, string>>;}) => {const sourceDocuments = entries.map(({ document }) => document);const sourceCatalog = await createAssetFieldCatalog(entries);@@ -458,6 +436,7 @@ const buildAssetIndex = async ({format: "webstudio-content-database",version: 1,assetRevision,+ ...(assetPaths === undefined ? {} : { assetPaths }),documents,...(documentGraph === undefined ? {} : { documentGraph }),...(Object.keys(contents).length === 0 ? {} : { contents }),@@ -505,6 +484,7 @@ export const compileContentArtifact = async ({documentGraph,documentContents,plan,+ assetPaths,}: {projectId: string;entries: readonly ContentCompilerInput[];@@ -514,6 +494,7 @@ export const compileContentArtifact = async ({documentGraph?: DocumentGraph;documentContents?: Readonly<Record<string, string>>;plan?: ContentCompilationPlan;+ assetPaths?: Readonly<Record<string, string>>;}): Promise<{artifact: ContentArtifactV1;diagnostics: ContentCompilerDiagnostics;@@ -521,10 +502,14 @@ export const compileContentArtifact = async ({if (Number.isSafeInteger(maxBytes) === false || maxBytes <= 0) {throw new Error("Content database byte limit must be a positive integer");}- const referencedMarkdownBodyIds = selectMarkdownBodyReferenceIds({- entries,- plan,- });+ const referencedMarkdownBodyIds =+ plan === undefined+ ? new Set<string>()+ : selectContentHydrationCandidates({+ documents: entries.map(({ document }) => document),+ plan,+ mode: "deferred",+ });if (referencedMarkdownBodyIds.size > 0 && documentGraph === undefined) {throw new Error("Markdown body reference queries require a document graph");}@@ -565,6 +550,7 @@ export const compileContentArtifact = async ({for (let attempt = 0; ; attempt += 1) {unbounded = await buildAssetIndex({entries: available,+ assetPaths,sourceDocumentCount,maxBytes,unboundedBytes,@@ -594,6 +580,7 @@ export const compileContentArtifact = async ({let selectedContentRefs = new Set<string>();const emptyArtifact = await buildAssetIndex({entries: selected,+ assetPaths,sourceDocumentCount,maxBytes,unboundedBytes,@@ -628,6 +615,7 @@ export const compileContentArtifact = async ({) {const trial = await buildAssetIndex({entries: [...selected, ...candidates],+ assetPaths,sourceDocumentCount,maxBytes,unboundedBytes,@@ -663,6 +651,7 @@ export const compileContentArtifact = async ({}const artifact = await buildAssetIndex({entries: selected,+ assetPaths,sourceDocumentCount,maxBytes,unboundedBytes,@@ -715,14 +704,6 @@ export const compileContentArtifact = async ({};};-export const createAssetIndex = async (input: {- projectId: string;- entries: readonly ContentCompilerInput[];- maxBytes?: number;- assetReferences?: MarkdownAssetReferences;- assetValueReferences?: AssetValueReferences;- documentGraph?: DocumentGraph;- documentContents?: Readonly<Record<string, string>>;- plan?: ContentCompilationPlan;-}): Promise<ContentArtifactV1> =>- (await compileContentArtifact(input)).artifact;+export const createAssetIndex = async (+ input: Parameters<typeof compileContentArtifact>[0]+): Promise<ContentArtifactV1> => (await compileContentArtifact(input)).artifact;diff --git a/packages/content-engine/src/compilation-plan.test.ts b/packages/content-engine/src/compilation-plan.test.tsindex 171527eb39..c557b4fc44 100644--- a/packages/content-engine/src/compilation-plan.test.ts+++ b/packages/content-engine/src/compilation-plan.test.ts@@ -128,6 +128,31 @@ const document: AssetFileDocument = {};describe("content compilation plan", () => {+ test("preserves complete frontmatter separately from projected properties", async () => {+ const properties = { title: "Post", author: { $ref: "author.json" } };+ const entry = createCanonicalAssetFileEntry({+ projectId: "project",+ document: { ...document, properties },+ });+ const plan = createContentCompilationPlan([+ compilationQuery(+ "title",+ assetQuery.parse({+ output: { mode: "fields", fields: [["properties", "title"]] },+ })+ ),+ ]);+ const [prepared] = await prepareContentCompilerEntries({+ entries: [entry],+ plan,+ loadContent: async () => {+ throw new Error("No body requested");+ },+ });+ expect(prepared.document.properties).toEqual({ title: "Post" });+ expect(prepared.sourceFrontmatter).toEqual(properties);+ });+test("keeps base-only queries free of parser and hydration work", () => {const plan = createContentCompilationPlan([compilationQuery("base")]);expect(plan).toEqual({@@ -499,13 +524,9 @@ describe("content compilation plan", () => {loadContent,});- expect(loadContent).toHaveBeenCalledOnce();- expect(loadContent).toHaveBeenCalledWith(- expect.objectContaining({ assetId: "post" })- );- expect(prepared).toEqual([- expect.objectContaining({ assetId: "post", contentRequired: true }),- ]);+ expect(loadContent).not.toHaveBeenCalled();+ expect(prepared).toEqual([expect.objectContaining({ assetId: "post" })]);+ expect(prepared[0].content).toBeUndefined();});test("reports dynamic filter and window values", () => {diff --git a/packages/content-engine/src/compilation-plan.ts b/packages/content-engine/src/compilation-plan.tsindex 9c397f0294..2d903aa300 100644--- a/packages/content-engine/src/compilation-plan.ts+++ b/packages/content-engine/src/compilation-plan.ts@@ -23,7 +23,14 @@ import {} from "./structured-query";import { contentEngineLimits } from "./limits";import { selectAssetDocumentFields, selectAssetProperties } from "./projection";-import type { CanonicalAssetFileEntry } from "./canonical";+import {+ fullCanonicalAssetMetadataRequirements,+ getCanonicalAssetMetadataRequirements,+ type CanonicalAssetFileEntry,+ type CanonicalAssetMetadataRequirements,+} from "./canonical";+import { getDocumentFormatByContentType } from "./document-graph/document-format";+import type { ContentCompilerInput } from "./asset-index";import {areJsonValuesEqual,compareStrings,@@ -98,6 +105,29 @@ export const requiresStructuredProperties = (plan: ContentCompilationPlan) =>plan.structuredPropertyPaths === "all" ||plan.structuredPropertyPaths.length > 0;+export const isContentCompilationWindowEmpty = ({+ limit,+}: Pick<ContentCompilationQuery, "limit">) =>+ limit.type === "literal" &&+ typeof limit.value === "number" &&+ limit.value <= 0;++export const getContentCompilationMetadataRequirements = (+ plan?: ContentCompilationPlan+): CanonicalAssetMetadataRequirements =>+ plan === undefined+ ? fullCanonicalAssetMetadataRequirements+ : {+ structuredProperties:+ requiresStructuredProperties(plan) ||+ plan.queries.some(+ (query) =>+ query.content.mode === "markdown-body-ref" &&+ isContentCompilationWindowEmpty(query) === false+ ),+ excerpt: plan.excerpt,+ };+export const requiresHydratedContent = (plan: ContentCompilationPlan) =>plan.queries.some(({ content }) => content.mode !== "none");@@ -279,13 +309,20 @@ const usesRuntimeWhere = (where: ContentCompilationWhere) =>export const selectContentHydrationCandidates = ({documents,plan,+ mode = "all",}: {documents: readonly ContentDatabaseDocument[];plan: ContentCompilationPlan;+ mode?: "all" | "embedded" | "deferred";}) => {const selected = new Set<string>();for (const query of plan.queries) {- if (query.content.mode === "none") {+ if (+ query.content.mode === "none" ||+ isContentCompilationWindowEmpty(query) ||+ (mode === "embedded" && query.content.mode === "markdown-body-ref") ||+ (mode === "deferred" && query.content.mode !== "markdown-body-ref")+ ) {continue;}const matched = documents.filter(@@ -328,7 +365,7 @@ export const prepareContentCompilerEntries = async ({plan?: ContentCompilationPlan;loadContent: (entry: CanonicalAssetFileEntry) => Promise<string | undefined>;maximumContentBytes?: number;-}) => {+}): Promise<readonly ContentCompilerInput[]> => {if (Number.isSafeInteger(maximumContentBytes) === false ||maximumContentBytes <= 0@@ -338,10 +375,16 @@ export const prepareContentCompilerEntries = async ({if (plan === undefined) {return entries;}- const projected = entries.map((entry) => {+ const projected: ContentCompilerInput[] = entries.map((entry) => {const { excerpt, ...document } = entry.document;+ const format = getDocumentFormatByContentType(document.mimeType);return {...entry,+ ...((format === "markdown" || format === "mdx") &&+ getCanonicalAssetMetadataRequirements(entry).structuredProperties &&+ document.metadataError === undefined+ ? { sourceFrontmatter: document.properties }+ : {}),document: {...document,properties:@@ -358,6 +401,7 @@ export const prepareContentCompilerEntries = async ({const hydrationIds = selectContentHydrationCandidates({documents: projected.map(({ document }) => document),plan,+ mode: "embedded",});const candidates = projected.filter(({ document }) =>isContentDocumentCandidate({ document, plan, available: "all" })diff --git a/packages/content-engine/src/content-artifact.ts b/packages/content-engine/src/content-artifact.tsindex 8e4a909a4a..d195807c71 100644--- a/packages/content-engine/src/content-artifact.ts+++ b/packages/content-engine/src/content-artifact.ts@@ -13,17 +13,21 @@ export const serializeContentArtifact = (value: unknown) =>serializeJsonDeterministically(contentArtifactV1.parse(value));export const getContentArtifactReferencedAssetIds = (- artifact: Pick<ContentArtifactV1, "assetReferences" | "assetValueReferences">+ artifact: Pick<+ ContentArtifactV1,+ "assetReferences" | "assetValueReferences" | "assetPaths"+ >) =>[- ...new Set(- [artifact.assetReferences, artifact.assetValueReferences].flatMap(+ ...new Set([+ ...Object.keys(artifact.assetPaths ?? {}),+ ...[artifact.assetReferences, artifact.assetValueReferences].flatMap((references) =>Object.values(references ?? {}).flat().map(({ assetId }) => assetId)- )- ),+ ),+ ]),].sort();export const getContentArtifactRuntimeAssetIds = ({@@ -33,7 +37,7 @@ export const getContentArtifactRuntimeAssetIds = ({}: {artifact: Pick<ContentArtifactV1,- "assetReferences" | "assetValueReferences"+ "assetReferences" | "assetValueReferences" | "assetPaths"> & {documents: readonly { _id: string }[];documentGraph?: { readonly nodes: readonly { id: string }[] };diff --git a/packages/content-engine/src/content-database.ts b/packages/content-engine/src/content-database.tsindex 4919ec25ac..fead402916 100644--- a/packages/content-engine/src/content-database.ts+++ b/packages/content-engine/src/content-database.ts@@ -133,6 +133,7 @@ const createQueryableContentDatabase = ({| "documents"| "contents"| "assetReferences"+ | "assetPaths"| "assetValueReferences"| "queries">;@@ -204,6 +205,7 @@ const createQueryableContentDatabase = ({read: createContentReader(queryContentReader),runtimeAssets,assetReferences: artifact.assetReferences,+ assetPaths: artifact.assetPaths,assetValueReferences: artifact.assetValueReferences,});const executeDynamicQuery = async ({diff --git a/packages/content-engine/src/content-runtime-artifact.ts b/packages/content-engine/src/content-runtime-artifact.tsindex 474017a27f..7e85dab509 100644--- a/packages/content-engine/src/content-runtime-artifact.ts+++ b/packages/content-engine/src/content-runtime-artifact.ts@@ -28,6 +28,7 @@ export type ContentRuntimeArtifact = Readonly<{edges: readonly RuntimeDocumentGraphEdge[];}>;contents?: Readonly<Record<string, string>>;+ assetPaths?: Readonly<Record<string, string>>;assetReferences?: MarkdownAssetReferences;assetValueReferences?: AssetValueReferences;queries?: Readonly<Record<string, MaterializedAssetQuery>>;@@ -78,6 +79,9 @@ export const createContentRuntimeArtifact = (return {revision: artifact.integrity.checksum,documents: artifact.documents,+ ...(artifact.assetPaths === undefined+ ? {}+ : { assetPaths: artifact.assetPaths }),...(documentGraph === undefined ? {} : { documentGraph }),...(includeContents && artifact.contents !== undefined? { contents: artifact.contents }@@ -111,6 +115,9 @@ export const getContentRuntimeArtifactRuntimeAssetIds = ({.map(({ assetId }) => assetId)));+ for (const id of Object.keys(artifact.assetPaths ?? {})) {+ ids.add(id);+ }if (includeDocuments) {for (const { _id } of artifact.documents) {ids.add(_id);diff --git a/packages/content-engine/src/content-source.test.ts b/packages/content-engine/src/content-source.test.tsindex 21f3489577..130d1b1933 100644--- a/packages/content-engine/src/content-source.test.ts+++ b/packages/content-engine/src/content-source.test.ts@@ -1,17 +1,118 @@-import { describe, expect, test } from "vitest";+import { describe, expect, test, vi } from "vitest";+import {+ createTextAssetSourceValidator,+ validateTextAssetSource,+ validateTextAssetSourceBytes,+} from "./mdx";import { createCanonicalAssetFileEntry } from "./canonical";-import { getContentArtifactReferencedAssetIds } from "./content-artifact";+import {+ getContentArtifactReferencedAssetIds,+ getContentArtifactRuntimeAssetIds,+} from "./content-artifact";import { createContentDatabase } from "./content-database";+import {+ createContentRuntimeArtifact,+ getContentRuntimeArtifactRuntimeAssetIds,+} from "./content-runtime-artifact";+import { createPublishedAssetResourceFetch } from "./published-runtime";+import {+ createContentCompilationPlan,+ prepareContentCompilerEntries,+ type ContentCompilationPlan,+} from "./compilation-plan";import {compileContentSource,+ compileContentUntilPlanIsStable,ContentSourceChangedError,createContentSourceFile,+ materializeContentSource,type ContentSource,type ContentSourceFile,} from "./content-source";const projectId = "project";+describe("compileContentUntilPlanIsStable", () => {+ const initialPlan: ContentCompilationPlan = {+ standardFields: "all",+ structuredPropertyPaths: "all",+ excerpt: false,+ metadataError: false,+ queries: [],+ };++ test("keeps the initial artifact when the resolved plan is unchanged", async () => {+ const equivalentPlan: ContentCompilationPlan = {+ queries: [],+ metadataError: false,+ excerpt: false,+ structuredPropertyPaths: "all",+ standardFields: "all",+ };+ const artifact = {};+ const compile = vi.fn(async () => artifact);+ const resolvePlan = vi.fn(async () => equivalentPlan);++ await expect(+ compileContentUntilPlanIsStable({+ plan: initialPlan,+ compile,+ resolvePlan,+ })+ ).resolves.toBe(artifact);++ expect(compile).toHaveBeenCalledOnce();+ expect(resolvePlan).toHaveBeenCalledOnce();+ });++ test("recompiles when dependency discovery expands the plan", async () => {+ const expandedPlan: ContentCompilationPlan = {+ ...initialPlan,+ excerpt: true,+ };+ const compile = vi+ .fn()+ .mockResolvedValueOnce({ pass: 0 })+ .mockResolvedValueOnce({ pass: 1 });+ const resolvePlan = vi+ .fn()+ .mockResolvedValueOnce(expandedPlan)+ .mockResolvedValueOnce(expandedPlan);++ const artifact = await compileContentUntilPlanIsStable({+ plan: initialPlan,+ compile,+ resolvePlan,+ });++ expect(artifact).toEqual({ pass: 1 });+ expect(compile.mock.calls).toEqual([[initialPlan], [expandedPlan]]);+ expect(resolvePlan).toHaveBeenCalledTimes(2);+ });++ test("rejects dependency discovery that never stabilizes", async () => {+ const compile = vi.fn(async (_plan: ContentCompilationPlan) => ({+ pass: compile.mock.calls.length,+ }));+ const resolvePlan = vi.fn(async ({ pass }: { pass: number }) => ({+ ...initialPlan,+ excerpt: pass % 2 === 1,+ }));++ await expect(+ compileContentUntilPlanIsStable({+ plan: initialPlan,+ compile,+ resolvePlan,+ })+ ).rejects.toThrow(+ "Dynamic MDX dependency closure exceeds the safe publication depth"+ );+ expect(compile).toHaveBeenCalledTimes(21);+ expect(resolvePlan).toHaveBeenCalledTimes(21);+ });+});+const createFile = (values: Partial<ContentSourceFile> & Pick<ContentSourceFile, "id">): ContentSourceFile => ({@@ -121,6 +222,391 @@ const createDocumentSource = ({});describe("content source snapshots", () => {+ test.each([+ "zero limit",+ "no match",+ "zero limit with dynamic filter",+ "zero limit with dynamic offset",+ ])(+ "omits the asset-path map when no article body can be selected: %s",+ async (selection) => {+ const article = createFile({ id: "article" });+ const files = [+ article,+ ...Array.from({ length: 100 }, (_, index) =>+ createFile({+ id: `image-${index}`,+ path: `images/${"long-name-".repeat(12)}${index}.svg`,+ contentType: "image/svg+xml",+ })+ ),+ ];+ const plan = createContentCompilationPlan([+ {+ id: "empty",+ where: {+ field: ["id"],+ operator: "eq",+ value:+ selection === "zero limit with dynamic filter"+ ? { type: "dynamic" }+ : {+ type: "literal",+ value: selection === "no match" ? "missing" : "article",+ },+ },+ sort: [],+ limit: { type: "literal", value: selection === "no match" ? 1 : 0 },+ offset:+ selection === "zero limit with dynamic offset"+ ? { type: "dynamic" }+ : { type: "literal", value: 0 },+ output: { mode: "base", includeMetadata: false },+ content: { mode: "markdown-body-ref" },+ },+ ]);+ const read = vi.fn(async () => "");+ const { artifact } = await compileContentSource({+ projectId,+ plan,+ maxBytes: 4096,+ source: {+ async openSnapshot() {+ return {+ revision: "snapshot",+ files,+ loadEntries: () =>+ prepareContentCompilerEntries({+ entries: files.map(createEntry),+ plan,+ loadContent: read,+ }),+ async loadDocumentSources() {+ return [+ {+ id: article.id,+ source: {+ async *[Symbol.asyncIterator]() {+ yield new TextEncoder().encode(await read());+ },+ },+ },+ ];+ },+ async isCurrent() {+ return true;+ },+ };+ },+ },+ });+ expect(artifact.assetPaths).toBeUndefined();+ expect(read).not.toHaveBeenCalled();+ }+ );++ test.each(["md", "mdx"])(+ "compiles a query over 300 referenced %s articles without reading bodies and loads only the requested article",+ async (extension) => {+ const body =+ "---\ntitle: Article\n---\nArticle body\n\n";+ const articles = Array.from({ length: 300 }, (_, index) =>+ createFile({+ id: `article-${index}`,+ path: `blog/article-${index}.${extension}`,+ contentType: extension === "md" ? "text/markdown" : "text/mdx",+ size: new TextEncoder().encode(body).byteLength,+ })+ );+ const files = [+ ...articles,+ createFile({+ id: "cover",+ path: "blog/cover.svg",+ contentType: "image/svg+xml",+ }),+ ];+ const plan = createContentCompilationPlan([+ {+ id: "article",+ result: "one",+ where: {+ field: ["id"],+ operator: "eq",+ value: { type: "dynamic" },+ },+ sort: [],+ limit: { type: "literal", value: 1 },+ offset: { type: "literal", value: 0 },+ output: { mode: "base", includeMetadata: false },+ content: { mode: "markdown-body-ref" },+ },+ ]);+ const readAtPublish = vi.fn(async () => body);+ const source: ContentSource = {+ async openSnapshot() {+ return {+ revision: "snapshot",+ files,+ loadEntries: () =>+ prepareContentCompilerEntries({+ entries: files.map((file) => ({+ ...createEntry(file),+ metadataRequirements: {+ structuredProperties: true,+ excerpt: false,+ },+ })),+ plan,+ loadContent: readAtPublish,+ }),+ async loadDocumentSources() {+ return articles.map(({ id }) => ({+ id,+ source: {+ async *[Symbol.asyncIterator]() {+ yield new TextEncoder().encode(await readAtPublish());+ },+ },+ }));+ },+ async isCurrent() {+ return true;+ },+ };+ },+ };+ const { artifact, diagnostics } = await compileContentSource({+ projectId,+ source,+ plan,+ });+ expect(readAtPublish.mock.calls.length).toBe(0);+ expect(artifact.contents).toBeUndefined();+ expect(artifact.documents).toHaveLength(300);+ expect(diagnostics.omittedDocumentCount).toBe(0);++ const fetchDocument = vi.fn(async () => new Response(body));+ const runtimeArtifact = createContentRuntimeArtifact(artifact);+ const publishedAssetIds = new Set(+ getContentArtifactRuntimeAssetIds({+ artifact,+ includeDocuments: true,+ })+ );+ const runtimeAssetIds = new Set(+ getContentRuntimeArtifactRuntimeAssetIds({+ artifact: runtimeArtifact,+ includeDocuments: true,+ })+ );+ const runtimeFetch = createPublishedAssetResourceFetch({+ baseUrl: "https://site.example",+ deploymentId: `articles-${extension}`,+ artifact: runtimeArtifact,+ runtimeAssets: Object.fromEntries(+ files+ .filter(+ ({ id }) => publishedAssetIds.has(id) && runtimeAssetIds.has(id)+ )+ .map((file) => [+ file.id,+ { url: `/assets/${file.id}`, contentRef: file.contentRef },+ ])+ ),+ fetchDocument,+ });+ const response = await runtimeFetch("/$resources/assets", {+ method: "POST",+ body: JSON.stringify({+ query: {+ result: "one",+ where: { field: ["id"], operator: "eq", value: "article-175" },+ output: { mode: "base", includeMetadata: false },+ content: { mode: "markdown-body-ref" },+ },+ }),+ });+ await expect(response?.json()).resolves.toMatchObject({+ item: {+ id: "article-175",+ content: { text: "Article body\n\n" },+ },+ totalCount: 1,+ });+ expect(response?.status).toBe(200);+ expect(fetchDocument).toHaveBeenCalledOnce();+ }+ );++ test.each(+ ["md", "mdx"].flatMap((extension) =>+ (["none", "full", "markdown-body-ref"] as const).flatMap((mode) =>+ (["current", "missing", "invalid"] as const).map((metadata) => ({+ extension,+ mode,+ metadata,+ }))+ )+ )+ )(+ "reads $extension bodies only when needed: $mode / $metadata metadata",+ async ({ extension, mode, metadata }) => {+ const file = createFile({+ id: "article",+ path: `article.${extension}`,+ contentType: extension === "md" ? "text/markdown" : "text/mdx",+ });+ const plan = createContentCompilationPlan([+ {+ id: "titles",+ where: { all: [] },+ sort: [],+ limit: { type: "literal", value: 10 },+ offset: { type: "literal", value: 0 },+ output: {+ mode: "fields",+ fields: [["properties", "title"]],+ includeMetadata: false,+ },+ content: { mode },+ },+ ]);+ const read = vi.fn(async () => "---\ntitle: article\n---\nBody");+ const entry = createEntry(file);+ const source: ContentSource = {+ async openSnapshot() {+ return {+ revision: "snapshot",+ files: [file],+ loadEntries: () =>+ prepareContentCompilerEntries({+ entries: [+ {+ ...entry,+ metadataRequirements: {+ structuredProperties: metadata !== "missing",+ excerpt: false,+ },+ document: {+ ...entry.document,+ ...(metadata === "invalid"+ ? {+ metadataError: {+ code: "MARKDOWN_INVALID_FRONTMATTER",+ message: "Invalid frontmatter",+ },+ }+ : {}),+ },+ },+ ],+ plan,+ loadContent: read,+ }),+ async loadDocumentSources() {+ return [+ {+ id: file.id,+ source: {+ async *[Symbol.asyncIterator]() {+ yield new TextEncoder().encode(await read());+ },+ },+ },+ ];+ },+ async isCurrent() {+ return true;+ },+ };+ },+ };+ const result = await materializeContentSource({ source, plan });+ expect(result.entries[0].document.properties).toEqual({+ title: "article",+ });+ if (mode !== "full" && metadata === "current") {+ expect(result.documentContents).toBeUndefined();+ if (mode === "none") {+ expect(result.documentGraph).toBeUndefined();+ }+ expect(read).not.toHaveBeenCalled();+ } else {+ expect(read).toHaveBeenCalled();+ }+ if (mode === "full") {+ expect(result.entries[0].content).toContain("Body");+ } else {+ expect(result.entries[0].content).toBeUndefined();+ }+ }+ );++ test("reuses source validation across byte loading and compilation passes without losing per-file diagnostics", async () => {+ const validate = vi.fn(validateTextAssetSource);+ const validateSource = createTextAssetSourceValidator(+ {},+ { validateTextAssetSource: validate }+ );+ const files = [+ createFile({ id: "one", path: "one.mdx", contentType: "text/mdx" }),+ createFile({ id: "two", path: "two.mdx", contentType: "text/mdx" }),+ ];+ let content = "{unsafe()}";+ const source: ContentSource = {+ async openSnapshot() {+ return {+ revision: "snapshot",+ files,+ async loadEntries() {+ const validated = await validateTextAssetSourceBytes({+ source: new TextEncoder().encode(content),+ format: "mdx",+ validateSource,+ });+ return files.map((file) => ({+ ...createEntry(file),+ content: validated.source,+ }));+ },+ async isCurrent() {+ return true;+ },+ };+ },+ };+ const first = await materializeContentSource({ source, validateSource });+ expect(first.sourceIssues).toMatchObject([+ {+ assetId: "one",+ path: "one.mdx",+ severity: "warning",+ code: "unsafe-mdx",+ },+ {+ assetId: "two",+ path: "two.mdx",+ severity: "warning",+ code: "unsafe-mdx",+ },+ ]);+ expect(await materializeContentSource({ source, validateSource })).toEqual(+ first+ );+ expect(validate).toHaveBeenCalledOnce();+ content = "<ws.element";+ await expect(+ materializeContentSource({ source, validateSource })+ ).rejects.toMatchObject({+ diagnostics: [+ { assetId: "one", severity: "error" },+ { assetId: "two", severity: "error" },+ ],+ });+ expect(validate).toHaveBeenCalledTimes(2);+ });+test("reports all fatal MDX errors from selected files", async () => {const files = [createFile({ id: "one", path: "blog/one.mdx", contentType: "text/mdx" }),diff --git a/packages/content-engine/src/content-source.ts b/packages/content-engine/src/content-source.tsindex 225d4e7c3d..80293c8924 100644--- a/packages/content-engine/src/content-source.ts+++ b/packages/content-engine/src/content-source.ts@@ -1,5 +1,6 @@import {createContentCompilationPlan,+ isContentCompilationWindowEmpty,requiresStructuredProperties,selectContentHydrationCandidates,type ContentCompilationPlan,@@ -17,7 +18,7 @@ import {discoverAssetValueReferences,type AssetValueReferences,} from "./asset-value-references";-import { compareStrings } from "./canonical-json";+import { areJsonValuesEqual, compareStrings } from "./canonical-json";import {decodeUtf8,encodeUtf8,@@ -35,6 +36,7 @@ import {compileDocumentSourceGraph,createDocumentSourceUrl,getDocumentFormatByContentType,+ getDocumentGraphClosure,type SourceReferenceOccurrence,type DocumentGraph,} from "./document-graph";@@ -83,6 +85,40 @@ export type ContentSourcePerformanceObserver = (event: {durationMs: number;}) => void;+const maxContentCompilationPlanUpdates = 20;++export const compileContentUntilPlanIsStable = async <Artifact>({+ plan: initialPlan,+ compile,+ resolvePlan,+}: {+ plan: ContentCompilationPlan;+ compile: (plan: ContentCompilationPlan) => Promise<Artifact>;+ resolvePlan: (+ artifact: Artifact+ ) =>+ | ContentCompilationPlan+ | undefined+ | Promise<ContentCompilationPlan | undefined>;+}) => {+ let plan = initialPlan;+ let artifact = await compile(plan);++ for (let depth = 0; ; depth += 1) {+ const nextPlan = await resolvePlan(artifact);+ if (nextPlan === undefined || areJsonValuesEqual(plan, nextPlan)) {+ return artifact;+ }+ if (depth === maxContentCompilationPlanUpdates) {+ throw new Error(+ "Dynamic MDX dependency closure exceeds the safe publication depth"+ );+ }+ plan = nextPlan;+ artifact = await compile(plan);+ }+};+const measureContentSourcePerformance = async <Value>({phase,operation,@@ -216,19 +252,15 @@ const discoverSnapshotAssetReferences = async ({snapshot: ContentSourceSnapshot;entries: readonly ContentCompilerInput[];plan?: ContentCompilationPlan;-}): Promise<MarkdownAssetReferences> => {+}) => {const assetIdsByPath = createUniqueAssetIdsByPath(snapshot.files);const selectedAssetIds =plan === undefined? undefined: selectContentHydrationCandidates({documents: entries.map(({ document }) => document),- plan: {- ...plan,- queries: plan.queries.filter(- ({ content }) => content.mode === "markdown-body-ref"- ),- },+ plan,+ mode: "deferred",});const references: Record<string, MarkdownAssetReferences[string]> = {};for (const entry of [...entries].sort((left, right) =>@@ -255,11 +287,18 @@ const discoverSnapshotAssetReferences = async ({references[entry.document.contentRef] = discovered;}}- return references;+ return {+ assetReferences: references,+ assetPaths:+ selectedAssetIds !== undefined && selectedAssetIds.size > 0+ ? Object.fromEntries(snapshot.files.map(({ id, path }) => [id, path]))+ : undefined,+ };};const validateSnapshotDocumentSources = async (- entries: readonly ContentCompilerInput[]+ entries: readonly ContentCompilerInput[],+ validateSource: typeof validateTextAssetSource): Promise<{sourceIssues: readonly SourceIssue[];mdxDocuments: ReadonlyMap<string, MdxDocument>;@@ -287,7 +326,7 @@ const validateSnapshotDocumentSources = async () {continue;}- const validation = await validateTextAssetSource({+ const validation = await validateSource({source: entry.content,format: format === "markdown" ? "md" : "mdx",});@@ -412,11 +451,7 @@ const discoverSnapshotAssetValueReferences = async ({const queryNeedsDocumentGraph = (query: ContentCompilationPlan["queries"][number]) => {- if (- query.limit.type === "literal" &&- typeof query.limit.value === "number" &&- query.limit.value <= 0- ) {+ if (isContentCompilationWindowEmpty(query)) {return false;}if (query.content.mode === "markdown-body-ref") {@@ -481,6 +516,7 @@ const discoverSnapshotDocumentGraph = async (}const sourceDocuments = await snapshot.loadDocumentSources();const filesById = new Map(snapshot.files.map((file) => [file.id, file]));+ const entriesById = new Map(entries.map((entry) => [entry.assetId, entry]));const sourcesById = new Map<string, ByteSource>();for (const document of sourceDocuments) {if (sourcesById.has(document.id)) {@@ -535,6 +571,7 @@ const discoverSnapshotDocumentGraph = async (revision: file.revision,contentRef: file.contentRef,format,+ frontmatter: entriesById.get(file.id)?.sourceFrontmatter,source: {async *[Symbol.asyncIterator]() {yield await getBytes(file.id);@@ -576,15 +613,26 @@ const discoverSnapshotDocumentGraph = async (? undefined: { assetReferenceIssues };}+ const embeddedNodes = getDocumentGraphClosure({+ graph,+ rootIds: entries+ .filter(({ content }) => content !== undefined)+ .map(({ assetId }) => assetId)+ .filter((id) => sourcesById.has(id)),+ });const contents = Object.fromEntries(await Promise.all(- graph.nodes.map(async (node) => [+ embeddedNodes.map(async (node) => [node.contentRef,decodeUtf8(await getBytes(node.id)),])));- return { graph, contents, assetReferenceIssues };+ return {+ graph,+ contents: embeddedNodes.length === 0 ? undefined : contents,+ assetReferenceIssues,+ };};export const materializeContentSnapshot = async ({@@ -593,12 +641,14 @@ export const materializeContentSnapshot = async ({maximumContentBytes = contentEngineLimits.databaseBytes,onPerformanceEvent,performanceNow = () => performance.now(),+ validateSource = validateTextAssetSource,}: {snapshot: ContentSourceSnapshot;plan?: ContentCompilationPlan;maximumContentBytes?: number;onPerformanceEvent?: ContentSourcePerformanceObserver;performanceNow?: () => number;+ validateSource?: typeof validateTextAssetSource;}) => {validateSnapshot(snapshot);try {@@ -608,7 +658,10 @@ export const materializeContentSnapshot = async ({string,Readonly<Record<string, unknown>>>();- const validation = await validateSnapshotDocumentSources(entries);+ const validation = await validateSnapshotDocumentSources(+ entries,+ validateSource+ );const documentGraphResult = await measureContentSourcePerformance({phase: "document-graph",observer: onPerformanceEvent,@@ -622,13 +675,14 @@ export const materializeContentSnapshot = async ({),});const documentGraph = documentGraphResult?.graph;- const assetReferences = await measureContentSourcePerformance({- phase: "asset-references",- observer: onPerformanceEvent,- now: performanceNow,- operation: () =>- discoverSnapshotAssetReferences({ snapshot, entries, plan }),- });+ const { assetReferences, assetPaths } =+ await measureContentSourcePerformance({+ phase: "asset-references",+ observer: onPerformanceEvent,+ now: performanceNow,+ operation: () =>+ discoverSnapshotAssetReferences({ snapshot, entries, plan }),+ });const assetValueReferenceResult =await discoverSnapshotAssetValueReferences({snapshot,@@ -648,6 +702,7 @@ export const materializeContentSnapshot = async ({sourceRevision: snapshot.revision,entries,assetReferences,+ assetPaths,assetValueReferences: assetValueReferenceResult.references,sourceIssues: assetValueReferenceResult.sourceIssues,documentGraph,@@ -694,6 +749,7 @@ export const compileContentSource = async ({sourceRevision,entries,assetReferences,+ assetPaths,assetValueReferences,sourceIssues,documentGraph,@@ -710,6 +766,7 @@ export const compileContentSource = async ({projectId,entries,assetReferences,+ assetPaths,assetValueReferences,documentGraph,documentContents,@@ -734,16 +791,19 @@ export const materializeContentSource = async ({maximumContentBytes,onPerformanceEvent,performanceNow,+ validateSource,}: {source: ContentSource;plan?: ContentCompilationPlan;maximumContentBytes?: number;onPerformanceEvent?: ContentSourcePerformanceObserver;performanceNow?: () => number;+ validateSource?: typeof validateTextAssetSource;}): Promise<{sourceRevision: string;entries: readonly ContentCompilerInput[];assetReferences: MarkdownAssetReferences;+ assetPaths?: Readonly<Record<string, string>>;assetValueReferences: AssetValueReferences;documentGraph?: DocumentGraph;documentContents?: Readonly<Record<string, string>>;@@ -759,6 +819,7 @@ export const materializeContentSource = async ({maximumContentBytes,onPerformanceEvent,performanceNow,+ validateSource,});} catch (error) {if (error instanceof ContentSourceChangedError === false) {diff --git a/packages/content-engine/src/document-graph/markdown-document.ts b/packages/content-engine/src/document-graph/markdown-document.tsindex 2e998ba554..819347723c 100644--- a/packages/content-engine/src/document-graph/markdown-document.ts+++ b/packages/content-engine/src/document-graph/markdown-document.ts@@ -173,28 +173,20 @@ export const parseMarkdownDocumentSource = async ({});};-/** Reads one bounded Markdown source and discovers references in frontmatter. */-export const analyzeMarkdownDocument = async ({- source,+/** Discovers references from complete, revision-matched frontmatter. */+export const analyzeMarkdownFrontmatter = ({+ frontmatter,sourceDocumentId,documentUrl,- maximumBytes = contentEngineLimits.hydratedFileBytes,}: {- source: ByteSource;+ frontmatter: Readonly<Record<string, unknown>>;sourceDocumentId: string;documentUrl: string | URL;- maximumBytes?: number;-}): Promise<- Readonly<{- document: MarkdownDocument;- references: readonly SourceReferenceOccurrence[];- }>-> => {- const parsed = await parseMarkdownDocumentSource({ source, maximumBytes });+}) => {let analyzedFrontmatter;try {analyzedFrontmatter = analyzeJsonDocument({- value: parsed.frontmatter,+ value: frontmatter,sourceDocumentId,documentUrl,});@@ -204,13 +196,8 @@ export const analyzeMarkdownDocument = async ({}throw cause;}- const document = normalizeMarkdownDocument({- source: parsed.source,- body: parsed.body,- frontmatter: analyzedFrontmatter.document,- });return Object.freeze({- document,+ properties: analyzedFrontmatter.document as MarkdownDocument["frontmatter"],references: Object.freeze(analyzedFrontmatter.references.map((occurrence) =>Object.freeze({@@ -222,6 +209,35 @@ export const analyzeMarkdownDocument = async ({});};+/** Reads one bounded Markdown source and discovers references in frontmatter. */+export const analyzeMarkdownDocument = async ({+ source,+ sourceDocumentId,+ documentUrl,+ maximumBytes = contentEngineLimits.hydratedFileBytes,+}: {+ source: ByteSource;+ sourceDocumentId: string;+ documentUrl: string | URL;+ maximumBytes?: number;+}): Promise<+ Readonly<{+ document: MarkdownDocument;+ references: readonly SourceReferenceOccurrence[];+ }>+> => {+ const parsed = await parseMarkdownDocumentSource({ source, maximumBytes });+ const { properties, references } = analyzeMarkdownFrontmatter({+ frontmatter: parsed.frontmatter,+ sourceDocumentId,+ documentUrl,+ });+ return Object.freeze({+ document: normalizeMarkdownDocument({ ...parsed, frontmatter: properties }),+ references,+ });+};+/** Assembles frontmatter references while preserving the original source and body. */export const assembleMarkdownDocument = ({document: input,diff --git a/packages/content-engine/src/document-graph/source-compiler.test.ts b/packages/content-engine/src/document-graph/source-compiler.test.tsindex 1ab4a7893f..6c0f70b440 100644--- a/packages/content-engine/src/document-graph/source-compiler.test.ts+++ b/packages/content-engine/src/document-graph/source-compiler.test.ts@@ -35,6 +35,61 @@ const documents = [];describe("document source graph compiler", () => {+ test("rejects invalid reference markers in supplied frontmatter", async () => {+ await expect(+ compileDocumentSourceGraph({+ documents: [+ {+ ...documents[1],+ source: "---\nname: Ada\n---\nBody",+ frontmatter: { avatar: { $ref: 42 } },+ },+ ],+ })+ ).rejects.toMatchObject({+ code: "DOCUMENT_ANALYSIS_FAILED",+ documentId: "author",+ cause: {+ code: "INVALID_REFERENCE_MARKER",+ referenceId: "#frontmatter/avatar",+ },+ });+ });++ test.each(["markdown", "mdx"] as const)(+ "discovers %s references from supplied frontmatter without reading its body",+ async (format) => {+ const expected = await compileDocumentSourceGraph({ documents });+ const graph = await compileDocumentSourceGraph({+ documents: documents.map((document) =>+ document.id === "author"+ ? {+ ...document,+ format,+ frontmatter: {+ name: "Ada",+ avatar: { $ref: "../media/ada.json#/url" },+ },+ source: {+ async *[Symbol.asyncIterator]() {+ yield await Promise.reject<Uint8Array>(+ new Error("Markdown body must not be downloaded")+ );+ },+ },+ }+ : document+ ),+ });+ expect(graph.edges).toEqual(expected.edges);+ expect(graph.nodes).toEqual(+ expected.nodes.map((node) =>+ node.id === "author" ? { ...node, format } : node+ )+ );+ }+ );+test("encodes every Asset path segment as document URL data", () => {expect(createDocumentSourceUrl("authors/Ada #1/プロフィール.md")).toBe("https://content.webstudio.local/authors/Ada%20%231/%E3%83%97%E3%83%AD%E3%83%95%E3%82%A3%E3%83%BC%E3%83%AB.md"diff --git a/packages/content-engine/src/document-graph/source-compiler.ts b/packages/content-engine/src/document-graph/source-compiler.tsindex 36eca4415c..b5253bdd46 100644--- a/packages/content-engine/src/document-graph/source-compiler.ts+++ b/packages/content-engine/src/document-graph/source-compiler.ts@@ -14,11 +14,14 @@ import {import type { DocumentFormat } from "./document-format";import type { DocumentGraph } from "./graph";import type { SourceReferenceOccurrence } from "./reference-codec";+import { analyzeMarkdownFrontmatter } from "./markdown-document";export type DocumentSourceDescriptor = DocumentDescriptor &Readonly<{format: DocumentFormat;source: ByteSource;+ /** Complete frontmatter for this revision, never an output-field projection. */+ frontmatter?: Readonly<Record<string, unknown>>;}>;export const createDocumentSourceUrl = (path: string) =>@@ -212,6 +215,22 @@ export const compileDocumentSourceGraph = async ({});}assertActive(signal);+ if (+ document.format !== "json" &&+ document.frontmatter !== undefined+ ) {+ return {+ status: "fulfilled" as const,+ value: {+ document,+ ...analyzeMarkdownFrontmatter({+ frontmatter: document.frontmatter,+ sourceDocumentId: document.id,+ documentUrl: document.documentUrl,+ }),+ },+ };+ }const result = await analyzeDocumentSource({format: document.format,source: document.source,@@ -221,7 +240,11 @@ export const compileDocumentSourceGraph = async ({});return {status: "fulfilled" as const,- value: { document, analyzedDocument: result },+ value: {+ document,+ properties: getAdaptedDocumentProperties(result),+ references: result.references,+ },};} catch (cause) {assertActive(signal);@@ -254,15 +277,14 @@ export const compileDocumentSourceGraph = async ({compilationErrors.push(settlement.reason);return [];});- for (const { document, analyzedDocument } of analyzed) {+ for (const { document, properties } of analyzed) {analyzedIds.add(document.id);- const properties = getAdaptedDocumentProperties(analyzedDocument);if (properties !== undefined) {onDocumentProperties?.({ id: document.id, properties });}}for (const result of analyzed) {- for (const occurrence of result.analyzedDocument.references) {+ for (const occurrence of result.references) {if (ignoredReferenceUrls?.has(occurrence.reference.documentUrl) ||ignoreReference?.(occurrence) === truediff --git a/packages/content-engine/src/hydration.test.ts b/packages/content-engine/src/hydration.test.tsindex 2a346910c6..6edb05eaa4 100644--- a/packages/content-engine/src/hydration.test.ts+++ b/packages/content-engine/src/hydration.test.ts@@ -1,6 +1,7 @@import { describe, expect, test, vi } from "vitest";import type { AssetFileDocument } from "./schema";import { contentEngineLimits } from "./limits";+import { discoverMarkdownAssetReferenceRanges } from "./markdown-assets";import {hydrateAssetResourceResult,type AssetResourceContentReader,@@ -142,6 +143,44 @@ describe("selected asset content hydration", () => {expect(result.content[document._id]?.text).toBe("# Body\n");});+ test("resolves relative images per article path when articles share stored bytes", async () => {+ const body = "\n";+ const documents = ["first", "second"].map((id) =>+ createDocument(id, body, {+ path: `${id}/post.md`,+ contentRef: "shared-content",+ })+ );+ const assetPaths = {+ "first-cover": "first/cover.svg",+ "second-cover": "second/cover.svg",+ };+ const assetUrls = {+ "first-cover": "/assets/first.svg",+ "second-cover": "/assets/second.svg",+ };+ // A mixed full/body query can include a reference map keyed by shared bytes.+ const references = discoverMarkdownAssetReferenceRanges({+ markdown: body,+ sourcePath: documents[0].path,+ assetIdsByPath: new Map(+ Object.entries(assetPaths).map(([id, path]) => [path, id])+ ),+ });+ const result = await hydrateAssetResourceResult({+ result: documents.map(identity),+ documents,+ options: { mode: "markdown-body-ref" },+ read: createReader({ "shared-content": body }),+ assetReferences: { "shared-content": references },+ assetPaths,+ assetUrls,+ });++ expect(result.content.first.text).toBe("\n");+ expect(result.content.second.text).toBe("\n");+ });+test("requires selected projections to retain stable content identity", async () => {const document = createDocument("post", "Post");const read = createReader({ [document.contentRef]: "Post" });diff --git a/packages/content-engine/src/hydration.ts b/packages/content-engine/src/hydration.tsindex ffa671c570..63ac185fb9 100644--- a/packages/content-engine/src/hydration.ts+++ b/packages/content-engine/src/hydration.ts@@ -7,6 +7,8 @@ import type {} from "./schema";import { contentEngineLimits } from "./limits";import { extractMarkdownBody } from "./markdown-body";+import { discoverMarkdownAssetReferenceRanges } from "./markdown-assets";+import { createUniqueAssetIdsByPath } from "./asset-path-resolution";import {ByteLimitExceededError,decodeUtf8,@@ -256,6 +258,7 @@ export const hydrateAssetResourceResult = async ({read,assetReferences,assetUrls,+ assetPaths,}: {result: unknown;documents: readonly ContentDatabaseDocument[];@@ -263,6 +266,7 @@ export const hydrateAssetResourceResult = async ({read: AssetResourceContentReader;assetReferences?: MarkdownAssetReferences;assetUrls?: Readonly<Record<string, string>>;+ assetPaths?: Readonly<Record<string, string>>;}) => {if (options.mode === "none") {return { content: {}, hydratedFileCount: 0, hydratedBytes: 0 };@@ -356,6 +360,12 @@ export const hydrateAssetResourceResult = async ({});}+ const assetIdsByPath =+ assetPaths === undefined+ ? undefined+ : createUniqueAssetIdsByPath(+ Object.entries(assetPaths).map(([id, path]) => ({ id, path }))+ );const settlements = await mapBounded(selected,contentEngineLimits.concurrentContentReads,@@ -385,7 +395,14 @@ export const hydrateAssetResourceResult = async ({try {text = (await extractMarkdownBody(bytes, item.readLength || 1)).body;- const references = assetReferences?.[item.identity.contentRef];+ const references =+ assetIdsByPath === undefined || item.document.path === undefined+ ? assetReferences?.[item.identity.contentRef]+ : discoverMarkdownAssetReferenceRanges({+ markdown: text,+ sourcePath: item.document.path,+ assetIdsByPath,+ });if (references !== undefined && assetUrls !== undefined) {text = rewriteMarkdownAssetReferenceRanges({markdown: text,diff --git a/packages/content-engine/src/mdx.test.ts b/packages/content-engine/src/mdx.test.tsindex 9f99f22846..33406911a1 100644--- a/packages/content-engine/src/mdx.test.ts+++ b/packages/content-engine/src/mdx.test.ts@@ -1,9 +1,10 @@-import { describe, expect, test } from "vitest";+import { describe, expect, test, vi } from "vitest";import { resolveAssetValueReferences } from "./asset-value-references";import { parseMarkdownAst } from "./markdown-ast";import {createMdxCodeBlock,createMdxSourceDiagnostics,+ createTextAssetSourceValidator,discoverMdxAssetReferences,isMdxTemplateComponentName,MdxDocumentError,@@ -22,6 +23,113 @@ import {} from "./mdx";import { contentEngineLimits } from "./limits";+describe("compilation-scoped text validation", () => {+ test.each(["# Article", "<ws.element", "{unsafe()}"])(+ "shares byte and text validation, including diagnostics: %s",+ async (source) => {+ const validate = vi.fn(validateTextAssetSource);+ const validateSource = createTextAssetSourceValidator(+ {},+ { validateTextAssetSource: validate }+ );+ const input = { source, format: "mdx" as const };+ const first = validateSource(input);+ expect(validateSource(input)).toBe(first);+ const expected = await validateTextAssetSource(input);+ expect(await first).toEqual(expected);+ expect(+ await validateTextAssetSourceBytes({+ source: new TextEncoder().encode(source),+ format: "mdx",+ validateSource,+ })+ ).toEqual({ ...expected, source });+ expect(validate).toHaveBeenCalledOnce();+ }+ );++ test("does not reuse validation for different content, formats, or sessions", async () => {+ const validate = vi.fn(validateTextAssetSource);+ const dependencies = { validateTextAssetSource: validate };+ const validateSource = createTextAssetSourceValidator({}, dependencies);+ const source = "<ws.element";+ expect(+ (await validateSource({ source, format: "md" })).diagnostics+ ).toEqual([]);+ expect(+ (await validateSource({ source, format: "mdx" })).diagnostics[0].severity+ ).toBe("error");+ expect(+ (await validateSource({ source: "# Fixed", format: "mdx" })).diagnostics+ ).toEqual([]);+ await createTextAssetSourceValidator(+ {},+ dependencies+ )({ source, format: "mdx" });+ expect(validate).toHaveBeenCalledTimes(4);+ });++ test("bounds retained source bytes, including multibyte input", async () => {+ const validate = vi.fn(validateTextAssetSource);+ const validateSource = createTextAssetSourceValidator(+ { maximumBytes: 8 },+ { validateTextAssetSource: validate }+ );+ const first = { source: "éé", format: "mdx" as const };+ await validateSource(first);+ await validateSource(first);+ expect(validate).toHaveBeenCalledOnce();+ await validateSource({ source: "abc", format: "mdx" });+ await validateSource(first);+ expect(validate).toHaveBeenCalledTimes(3);+ await validateSource({ source: "ééé", format: "mdx" });+ await validateSource({ source: "ééé", format: "mdx" });+ expect(validate).toHaveBeenCalledTimes(5);+ });++ test("does not retain a failed validation attempt", async () => {+ const failure = new Error("Parser failed");+ const validate = vi+ .fn(validateTextAssetSource)+ .mockRejectedValueOnce(failure);+ const validateSource = createTextAssetSourceValidator(+ {},+ { validateTextAssetSource: validate }+ );+ const input = { source: "# Article", format: "mdx" as const };+ await expect(validateSource(input)).rejects.toBe(failure);+ expect((await validateSource(input)).diagnostics).toEqual([]);+ expect(validate).toHaveBeenCalledTimes(2);+ });++ test("rejects invalid byte input before consulting the source cache", async () => {+ const validateSource = vi.fn(validateTextAssetSource);+ await expect(+ validateTextAssetSourceBytes({+ source: new Uint8Array([0xc3, 0x28]),+ format: "md",+ validateSource,+ })+ ).resolves.toMatchObject({+ diagnostics: [+ { code: "MARKDOWN_BODY_DECODING_FAILED", severity: "error" },+ ],+ });+ await expect(+ validateTextAssetSourceBytes({+ source: new Uint8Array(contentEngineLimits.hydratedFileBytes + 1),+ format: "md",+ validateSource,+ })+ ).resolves.toMatchObject({+ diagnostics: [+ { code: "MARKDOWN_BODY_BYTES_EXCEEDED", severity: "error" },+ ],+ });+ expect(validateSource).not.toHaveBeenCalled();+ });+});+test("validates template names as PascalCase JavaScript identifiers", () => {expect(isMdxTemplateComponentName("PromotionCard")).toBe(true);expect(isMdxTemplateComponentName("ÉditionCard")).toBe(true);diff --git a/packages/content-engine/src/mdx.ts b/packages/content-engine/src/mdx.tsindex 96201d28a2..a08544b46a 100644--- a/packages/content-engine/src/mdx.ts+++ b/packages/content-engine/src/mdx.ts@@ -10,6 +10,7 @@ import {} from "mdast-util-to-hast";import { parse, postprocess, preprocess } from "micromark";import { mdxjs } from "micromark-extension-mdxjs";+import { LRUCache } from "lru-cache";import {discoverAssetValueReferences,rewriteAssetValueReferences,@@ -1724,6 +1725,38 @@ export const validateTextAssetSource = async ({return { format, ...validation };};+/** Reuses validation only within a caller-owned compilation session. */+export const createTextAssetSourceValidator = (+ {+ maximumBytes = contentEngineLimits.hydratedTotalBytes,+ }: {+ maximumBytes?: number;+ } = {},+ dependencies = { validateTextAssetSource }+): typeof validateTextAssetSource => {+ const cache = new LRUCache<string, Promise<TextAssetSourceValidation>>({+ maxSize: maximumBytes,+ sizeCalculation: (_value, key) => getUtf8ByteLength(key),+ });+ return (input) => {+ const key = `${input.format}:${input.source}`;+ const cached = cache.get(key);+ if (cached !== undefined) {+ return cached;+ }+ const result = dependencies+ .validateTextAssetSource(input)+ .catch((error) => {+ if (cache.peek(key) === result) {+ cache.delete(key);+ }+ throw error;+ });+ cache.set(key, result);+ return result;+ };+};+/*** Fatal-decodes one complete byte source before running the shared source* validator. This is the byte-input entry point for query and MCP callers.@@ -1731,9 +1764,11 @@ export const validateTextAssetSource = async ({export const validateTextAssetSourceBytes = async ({source: bytes,format,+ validateSource = validateTextAssetSource,}: {source: Uint8Array;format: "md" | "mdx";+ validateSource?: typeof validateTextAssetSource;}): Promise<TextAssetByteSourceValidation> => {if (bytes.byteLength > contentEngineLimits.hydratedFileBytes) {if (format === "md") {@@ -1785,7 +1820,7 @@ export const validateTextAssetSourceBytes = async ({recovery: { status: "unrecoverable", diagnostics: [error] },};}- return { ...(await validateTextAssetSource({ source, format })), source };+ return { ...(await validateSource({ source, format })), source };};const withMarkdownSyntax = (node: MdxAuthoredNode): MdxAuthoredNode => {diff --git a/packages/content-engine/src/schema.ts b/packages/content-engine/src/schema.tsindex 5a56a02f1c..28dace6096 100644--- a/packages/content-engine/src/schema.ts+++ b/packages/content-engine/src/schema.ts@@ -183,6 +183,7 @@ export const contentArtifactV1 = strictObject({documents: array(contentDatabaseDocument),documentGraph: documentGraphArtifactV1.optional(),contents: record(string().min(1), string()).optional(),+ assetPaths: record(string().min(1), string().min(1)).optional(),assetReferences: record(string().min(1),array(diff --git a/packages/content-engine/src/structured-query.ts b/packages/content-engine/src/structured-query.tsindex 8ea993a206..75a037ed24 100644--- a/packages/content-engine/src/structured-query.ts+++ b/packages/content-engine/src/structured-query.ts@@ -906,12 +906,14 @@ const finalizeAssetQueries = async ({read,assetReferences,assetUrls,+ assetPaths,}: {preparedQueries: readonly PreparedAssetQuery[];results: AssetQuerySettlements;read?: AssetResourceContentReader;assetReferences?: MarkdownAssetReferences;assetUrls: Readonly<Record<string, string>>;+ assetPaths?: Readonly<Record<string, string>>;}) => {await Promise.all(preparedQueries.map(async (state) => {@@ -949,7 +951,8 @@ const finalizeAssetQueries = async ({options: contentOptions,read,assetReferences,- assetUrls: assetReferences === undefined ? undefined : assetUrls,+ assetUrls,+ assetPaths,});items = selectedDocuments.map((document, index) => {const content = hydrated.content[document._id];@@ -998,6 +1001,7 @@ export const executeAssetQueries = async ({runtimeAssets,assetReferences,assetValueReferences,+ assetPaths,}: {queries: readonly AssetQueryInput[];catalog?: BuilderAssetFieldCatalog;@@ -1006,6 +1010,7 @@ export const executeAssetQueries = async ({runtimeAssets?: Readonly<Record<string, AssetRuntimeData>>;assetReferences?: MarkdownAssetReferences;assetValueReferences?: AssetValueReferences;+ assetPaths?: Readonly<Record<string, string>>;}): Promise<PromiseSettledResult<AssetQueryExecutionResult>[]> => {const results: AssetQuerySettlements = Array.from({ length: inputs.length });const { filterKeys, preparedQueries, sortGroups } = prepareAssetQueries({@@ -1066,6 +1071,7 @@ export const executeAssetQueries = async ({read,assetReferences,assetUrls,+ assetPaths,});return requireSettledAssetQueryResults(results);};@@ -1077,6 +1083,7 @@ type ExecuteAssetQueryInput = {read?: AssetResourceContentReader;runtimeAssets?: Readonly<Record<string, AssetRuntimeData>>;assetReferences?: MarkdownAssetReferences;+ assetPaths?: Readonly<Record<string, string>>;assetValueReferences?: AssetValueReferences;};diff --git a/packages/http-client/src/index.test.ts b/packages/http-client/src/index.test.tsindex e5d9e88ec6..83972b5aab 100644--- a/packages/http-client/src/index.test.ts+++ b/packages/http-client/src/index.test.ts@@ -232,6 +232,7 @@ test("sends the bundle contract when loading by project id", async () => {expect(decodeURIComponent(String(url))).toContain(`"bundleVersion":"${bundleVersion}"`);+ expect(decodeURIComponent(String(url))).not.toContain("contentIndex");});test("creates api client compatibility headers", () => {@@ -1301,6 +1302,26 @@ test("loads project bundle by build id without auth headers", async () => {);});+test("requests local content preparation for the publish runner", async () => {+ const project = createPublishedProjectBundleFixture();+ const fetch = vi.fn().mockResolvedValue(+ new Response(JSON.stringify([{ result: { data: project } }]), {+ headers: { "content-type": "application/json" },+ })+ );+ vi.stubGlobal("fetch", fetch);++ await loadProjectBundleByBuildId({+ buildId: project.build.id,+ origin: "https://example.com",+ contentIndex: "client",+ });++ expect(decodeURIComponent(String(fetch.mock.calls[0]?.[0]))).toContain(+ '"contentIndex":"client"'+ );+});+test("reports asset upload errors", async () => {vi.stubGlobal("fetch",diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.tsindex e4b8987d6d..bb8bbda11f 100644--- a/packages/http-client/src/index.ts+++ b/packages/http-client/src/index.ts@@ -1213,6 +1213,7 @@ export const loadProjectBundleByBuildId = async (buildId: string;origin: string;headers?: RequestHeaders;+ contentIndex?: "client";} & (| {serviceToken: string;@@ -1235,6 +1236,7 @@ export const loadProjectBundleByBuildId = async (const data = await client.query("build.loadProjectBundleByBuildId", {buildId: params.buildId,bundleVersion: currentBundleVersion,+ contentIndex: params.contentIndex,});return publishedProjectBundle.parse(data);};diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.tsindex f040ba6e12..f8a0770c52 100644--- a/packages/project-build/src/mcp.test.ts+++ b/packages/project-build/src/mcp.test.ts@@ -4824,6 +4824,20 @@ describe("project session mcp adapter", () => {expect(markdownBlogGuide.structuredContent.data).toEqual(expect.objectContaining({recipe: expect.objectContaining({+ articleFormat: {+ extension: "md",+ editSurface: "asset-source-editor",+ publishCompilation: false,+ assetSyncDownloadsFiles: true,+ visualAlternative: {+ extension: "mdx",+ editSurface: "content-block-canvas",+ publishCompilation: true,+ assetSyncDownloadsFiles: true,+ workflow: "general",+ tool: "connect-content-block-source",+ },+ },executionOrder: [{ tool: "create-asset-folder", calls: 1 },{ tool: "upload-assets", calls: 1 },diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.tsindex 180576182b..5f305eb74b 100644--- a/packages/project-build/src/mcp.ts+++ b/packages/project-build/src/mcp.ts@@ -6272,6 +6272,7 @@ const metaGoalGuides = ["verify-page-responsive",],workflow: [+ "Use .md for Markdown-only editing; use .mdx when visual Content mode is needed. MDX compiles during publishing, and Asset sync downloads both formats.","Follow recipe.executionOrder in order. Resolve documented placeholders from earlier results, and do not add calls outside that sequence.",'Create one asset folder named exactly "Blog", then call upload-assets exactly once with all Markdown files and assetsDir ".webstudio/assets". Put slug, title, author, publishedAt, excerpt, and draft in frontmatter. Each asset uses {"name":"<filename>.md","type":"file","format":"md","folderId":"<blog-folder-id>","meta":{}}; do not create companion files.','Create exactly two pages once using the recipe pages payloads exactly: call create-page with {"path":"/blog","name":"Blog"} and {"path":"/blog/:slug","name":"Blog article"}. Use each returned pageId and rootInstanceId in later recipe placeholders. Do not omit name, dry-run page creation, create one page per post, or copy Markdown into static page content.',@@ -6283,6 +6284,20 @@ const metaGoalGuides = ['After both insertions succeed, ask whether the user wants visual verification unless they explicitly requested it. If they decline, use focused reads and a static audit. If they opt in, call verify-page-responsive once for "/blog" and once for one concrete detail path with desktop and mobile viewports. Confirm Assets-backed content and empty/not-found behavior. Stop on an error instead of retrying.',],recipe: {+ articleFormat: {+ extension: "md",+ editSurface: "asset-source-editor",+ publishCompilation: false,+ assetSyncDownloadsFiles: true,+ visualAlternative: {+ extension: "mdx",+ editSurface: "content-block-canvas",+ publishCompilation: true,+ assetSyncDownloadsFiles: true,+ workflow: "general",+ tool: "connect-content-block-source",+ },+ },executionOrder: [{ tool: "create-asset-folder", calls: 1 },{ tool: "upload-assets", calls: 1 },