Skip to content

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

feat: Add single-result modes to Assets queries (#6040)

Oleg Isonen2ec78c183d0b
diff --git a/.github/workflows/fixtures-test.yml b/.github/workflows/fixtures-test.yml
index 08738b288a..87d3f29b84 100644
--- a/.github/workflows/fixtures-test.yml
+++ b/.github/workflows/fixtures-test.yml
@@ -65,11 +65,8 @@ jobs:
exit "$sync_status"
fi
- - name: Build CLI content runtime
- run: mkdir -p packages/cli/lib && pnpm --filter webstudio build:content-runtime
-
- - name: Testing cli build command
- run: pnpm --filter='./fixtures/*' run --parallel fixtures:build
+ - name: Testing fixture build command
+ run: pnpm -r fixtures:build
- name: Prepare for diffing
shell: bash
diff --git a/apps/builder/app/builder/features/settings-panel/asset-query-form.test.tsx b/apps/builder/app/builder/features/settings-panel/asset-query-form.test.tsx
index de6a52c790..bad6247736 100644
--- a/apps/builder/app/builder/features/settings-panel/asset-query-form.test.tsx
+++ b/apps/builder/app/builder/features/settings-panel/asset-query-form.test.tsx
@@ -7,7 +7,7 @@ import {
} from "@webstudio-is/protocol/asset-resource-api";
import { AssetQueryForm, __testing__ } from "./asset-query-form";
-const { loadAssetQueryDefinition } = __testing__;
+const { configureAssetQueryDefinition, loadAssetQueryDefinition } = __testing__;
(
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
@@ -74,4 +74,25 @@ test("loads the external query schema declared by OpenAPI", async () => {
expect(definition.fields).toContainEqual(
expect.objectContaining({ path: ["properties", "title"] })
);
+ const manyControls = configureAssetQueryDefinition({
+ definition,
+ paths: [],
+ result: "many",
+ }).source.controls;
+ const oneControls = configureAssetQueryDefinition({
+ definition,
+ paths: [],
+ result: "one",
+ }).source.controls;
+
+ expect(manyControls.slice(-2).map(({ key }) => key)).toEqual([
+ "output",
+ "result",
+ ]);
+ expect(manyControls.map(({ key }) => key)).toEqual(
+ expect.arrayContaining(["limit", "offset"])
+ );
+ expect(oneControls.map(({ key }) => key)).not.toEqual(
+ expect.arrayContaining(["limit", "offset"])
+ );
});
diff --git a/apps/builder/app/builder/features/settings-panel/asset-query-form.tsx b/apps/builder/app/builder/features/settings-panel/asset-query-form.tsx
index 578e1c6bf2..c9b86315a3 100644
--- a/apps/builder/app/builder/features/settings-panel/asset-query-form.tsx
+++ b/apps/builder/app/builder/features/settings-panel/asset-query-form.tsx
@@ -33,10 +33,16 @@ type AssetQueryDefinition = QueryDefinition<
const defaultConfiguration: StructuredAssetQueryResourceConfiguration =
createDefaultStructuredAssetQueryResourceConfiguration();
+const controlOrder = new Map([
+ ["output", 1],
+ ["result", 2],
+]);
+
const normalizeConfiguration = (
value: StructuredAssetQueryResourceConfiguration
): StructuredAssetQueryResourceConfiguration => ({
...value,
+ result: value.result ?? "many",
where: "field" in value.where ? { all: [value.where] } : value.where,
});
@@ -68,6 +74,38 @@ const loadAssetQueryDefinition = async (
return definition as AssetQueryDefinition;
};
+const configureAssetQueryDefinition = ({
+ definition,
+ paths,
+ result,
+}: {
+ definition: AssetQueryDefinition;
+ paths: string[][];
+ result: StructuredAssetQueryResourceConfiguration["result"];
+}) => {
+ const configured = addConfiguredQueryFields({
+ definition,
+ paths,
+ fallbackType: "string",
+ });
+ return {
+ ...configured,
+ source: {
+ ...configured.source,
+ controls: configured.source.controls
+ .filter(
+ ({ key }) =>
+ result === "many" || (key !== "limit" && key !== "offset")
+ )
+ .toSorted(
+ (left, right) =>
+ (controlOrder.get(left.key) ?? 0) -
+ (controlOrder.get(right.key) ?? 0)
+ ),
+ },
+ };
+};
+
export const AssetQueryForm = ({
resource,
scope,
@@ -109,21 +147,26 @@ export const AssetQueryForm = ({
),
[configuration]
);
- const definition = useMemo(
- () =>
- baseDefinition === undefined
- ? undefined
- : addConfiguredQueryFields({
- definition: baseDefinition,
- paths: configuredPaths,
- fallbackType: "string",
- }),
- [baseDefinition, configuredPaths]
- );
+ const definition = useMemo(() => {
+ if (baseDefinition === undefined) {
+ return;
+ }
+ return configureAssetQueryDefinition({
+ definition: baseDefinition,
+ paths: configuredPaths,
+ result: configuration.result,
+ });
+ }, [baseDefinition, configuration.result, configuredPaths]);
const configurationError = useMemo(() => {
if (definition === undefined) {
return;
}
+ if (
+ (configuration.result === "first" || configuration.result === "last") &&
+ configuration.sort.length === 0
+ ) {
+ return "Add sorting to define which item is first.";
+ }
try {
createQuerySourceCodec<
string,
@@ -192,7 +235,15 @@ export const AssetQueryForm = ({
sourceContainer={sourceContainer}
sectionPaddingInline={theme.panel.paddingInline}
onChange={(value) => {
- setConfiguration(value);
+ setConfiguration(
+ configuration.result === "many" && value.result !== "many"
+ ? {
+ ...value,
+ limit: defaultConfiguration.limit,
+ offset: defaultConfiguration.offset,
+ }
+ : value
+ );
}}
/>
) : (
@@ -207,4 +258,7 @@ export const AssetQueryForm = ({
);
};
-export const __testing__ = { loadAssetQueryDefinition };
+export const __testing__ = {
+ configureAssetQueryDefinition,
+ loadAssetQueryDefinition,
+};
diff --git a/fixtures/webstudio-features/.webstudio/data.json b/fixtures/webstudio-features/.webstudio/data.json
index 5ef601b25e..c9c055ef49 100644
--- a/fixtures/webstudio-features/.webstudio/data.json
+++ b/fixtures/webstudio-features/.webstudio/data.json
@@ -6882,7 +6882,7 @@
"value": "\"application/json\""
}
],
- "body": "{\n query: ({\n output: {\n mode: \"fields\",\n includeMetadata: false,\n fields: [[\"url\"], [\"width\"], [\"height\"]],\n },\n content: {\n mode: \"none\",\n },\n where: {\n all: [],\n },\n sort: [],\n limit: 1000,\n offset: 0,\n }),\n}"
+ "body": "{\n query: ({\n output: {\n mode: \"fields\",\n includeMetadata: false,\n fields: [[\"url\"], [\"width\"], [\"height\"]],\n },\n content: {\n mode: \"none\",\n },\n result: \"many\",\n where: {\n all: [],\n },\n sort: [],\n limit: 1000,\n offset: 0,\n }),\n}"
}
]
],
diff --git a/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js
index f3148317d8..774f7dfb91 100644
--- a/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js
+++ b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js
@@ -1,45 +1,45 @@
-var Jf=Object.defineProperty;var Kf=(t,e)=>{for(var n in e)Jf(t,n,{get:e[n],enumerable:!0})};var Bs;function g(t,e,n){function r(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=i.prototype,d=Object.keys(u);for(let l=0;l<d.length;l++){let f=d[l];f in a||(a[f]=u[f].bind(a))}}let o=n?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=n?.Parent?new s:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Uh=Symbol("zod_brand"),Ce=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},St=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Bs=globalThis).__zod_globalConfig??(Bs.__zod_globalConfig={});var At=globalThis.__zod_globalConfig;function be(t){return t&&Object.assign(At,t),At}var L={};Kf(L,{BIGINT_FORMAT_RANGES:()=>qs,Class:()=>uo,NUMBER_FORMAT_RANGES:()=>yo,aborted:()=>et,allowsEval:()=>po,assert:()=>ed,assertEqual:()=>Wf,assertIs:()=>Hf,assertNever:()=>Xf,assertNotEqual:()=>Yf,assignProp:()=>He,base64ToUint8Array:()=>Ks,base64urlToUint8Array:()=>wd,cached:()=>vt,captureStackTrace:()=>Qn,cleanEnum:()=>bd,cleanRegex:()=>on,clone:()=>we,cloneDef:()=>rd,createTransparentProxy:()=>ud,defineLazy:()=>z,esc:()=>Un,escapeRegex:()=>Ge,explicitlyAborted:()=>go,extend:()=>dd,finalizeIssue:()=>he,floatSafeRemainder:()=>lo,getElementAtPath:()=>od,getEnumValues:()=>nn,getLengthableOrigin:()=>sn,getParsedType:()=>cd,getSizableOrigin:()=>Js,hexToUint8Array:()=>xd,isObject:()=>ht,isPlainObject:()=>Xe,issue:()=>kt,joinValues:()=>td,jsonStringifyReplacer:()=>Et,merge:()=>md,mergeDefs:()=>Qe,normalizeParams:()=>O,nullish:()=>rn,numKeys:()=>ad,objectClone:()=>nd,omit:()=>fd,optionalKeys:()=>ho,parsedType:()=>gd,partial:()=>hd,pick:()=>ld,prefixIssues:()=>Ve,primitiveTypes:()=>Gs,promiseAllObject:()=>sd,propertyKeyTypes:()=>mo,randomString:()=>id,required:()=>yd,safeExtend:()=>pd,shallowClone:()=>Qs,slugify:()=>fo,stringifyPrimitive:()=>Vs,uint8ArrayToBase64:()=>Ws,uint8ArrayToBase64url:()=>_d,uint8ArrayToHex:()=>Sd,unwrapMessage:()=>tn});function Wf(t){return t}function Yf(t){return t}function Hf(t){}function Xf(t){throw new Error("Unexpected value in exhaustive check")}function ed(t){}function nn(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 td(t,e="|"){return t.map(n=>Vs(n)).join(e)}function Et(t,e){return typeof e=="bigint"?e.toString():e}function vt(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function rn(t){return t==null}function on(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function lo(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 Us=Symbol("evaluating");function z(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==Us)return r===void 0&&(r=Us,r=n()),r},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function nd(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function He(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 rd(t){return Qe(t._zod.def)}function od(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function sd(t){let e=Object.keys(t),n=e.map(r=>t[r]);return Promise.all(n).then(r=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=r[s];return o})}function id(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<t;r++)n+=e[Math.floor(Math.random()*e.length)];return n}function Un(t){return JSON.stringify(t)}function fo(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Qn="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function ht(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var po=vt(()=>{if(At.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Xe(t){if(ht(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let n=e.prototype;return!(ht(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Qs(t){return Xe(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function ad(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}var cd=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},mo=new Set(["string","number","symbol"]),Gs=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ge(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function we(t,e,n){let r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function O(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 ud(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 Vs(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function ho(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var yo={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]},qs={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function ld(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 He(this,"shape",i),i},checks:[]});return we(t,s)}function fd(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 He(this,"shape",i),i},checks:[]});return we(t,s)}function dd(t,e){if(!Xe(e))throw new Error("Invalid input to extend: expected a plain object");let n=t._zod.def.checks;if(n&&n.length>0){let s=t._zod.def.shape;for(let i in e)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Qe(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return He(this,"shape",s),s}});return we(t,o)}function pd(t,e){if(!Xe(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 He(this,"shape",r),r}});return we(t,n)}function md(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 He(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return we(t,n)}function hd(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 He(this,"shape",c),c},checks:[]});return we(e,i)}function yd(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 He(this,"shape",s),s}});return we(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 go(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue===!1)return!0;return!1}function Ve(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function tn(t){return typeof t=="string"?t:t?.message}function he(t,e,n){let r=t.message?t.message:tn(t.inst?._zod.def?.error?.(t))??tn(e?.error?.(t))??tn(n.customError?.(t))??tn(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 Js(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function sn(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function gd(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let n=t;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return e}function kt(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function bd(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function Ks(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 Ws(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}function wd(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-e.length%4)%4);return Ks(e+n)}function _d(t){return Ws(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function xd(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 Sd(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var uo=class{constructor(...e){}};var Ys=(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,Et,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Gn=g("$ZodError",Ys),bo=g("$ZodError",Ys,{Parent:Error});function Hs(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 Xs(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 Vn=t=>(e,n,r,o)=>{let s=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new Ce;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>he(c,s,be())));throw Qn(a,o?.callee),a}return i.value};var qn=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,be())));throw Qn(a,o?.callee),a}return i.value};var an=t=>(e,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Ce;return s.issues.length?{success:!1,error:new(t??Gn)(s.issues.map(i=>he(i,o,be())))}:{success:!0,data:s.value}},ei=an(bo),cn=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,be())))}:{success:!0,data:s.value}},ti=cn(bo),ni=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Vn(t)(e,n,o)};var ri=t=>(e,n,r)=>Vn(t)(e,n,r);var oi=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return qn(t)(e,n,o)};var si=t=>async(e,n,r)=>qn(t)(e,n,r);var ii=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return an(t)(e,n,o)};var ai=t=>(e,n,r)=>an(t)(e,n,r);var ci=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return cn(t)(e,n,o)};var ui=t=>async(e,n,r)=>cn(t)(e,n,r);var li=/^[cC][0-9a-z]{6,}$/,fi=/^[0-9a-z]+$/,di=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,pi=/^[0-9a-vA-V]{20}$/,mi=/^[A-Za-z0-9]{27}$/,hi=/^[a-zA-Z0-9_-]{21}$/,yi=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var gi=/^([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})$/,wo=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 bi=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Ed="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function wi(){return new RegExp(Ed,"u")}var _i=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,xi=/^(([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 Si=/^((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])$/,Ai=/^(([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])$/,Ei=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,_o=/^[A-Za-z0-9_-]*$/;var vi=/^https?$/,ki=/^\+[1-9]\d{6,14}$/,Di="(?:(?:\\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])))",Ri=new RegExp(`^${Di}$`);function Oi(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 Ii(t){return new RegExp(`^${Oi(t)}$`)}function Ci(t){let e=Oi({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(`^${Di}T(?:${r})$`)}var Ni=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var $i=/^-?\d+$/,xo=/^-?\d+(?:\.\d+)?$/,Ti=/^(?:true|false)$/i,zi=/^null$/i;var Pi=/^[^A-Z]*$/,Li=/^[^a-z]*$/;var X=g("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Mi={number:"number",bigint:"bigint",object:"date"},So=g("$ZodCheckLessThan",(t,e)=>{X.init(t,e);let n=Mi[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})}}),Ao=g("$ZodCheckGreaterThan",(t,e)=>{X.init(t,e);let n=Mi[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})}}),Fi=g("$ZodCheckMultipleOf",(t,e)=>{X.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):lo(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})}}),Zi=g("$ZodCheckNumberFormat",(t,e)=>{X.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,s]=yo[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=$i)}),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 ji=g("$ZodCheckMaxLength",(t,e)=>{var n;X.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!rn(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=sn(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Bi=g("$ZodCheckMinLength",(t,e)=>{var n;X.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!rn(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=sn(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Ui=g("$ZodCheckLengthEquals",(t,e)=>{var n;X.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!rn(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=sn(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})}}),un=g("$ZodCheckStringFormat",(t,e)=>{var n,r;X.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),Qi=g("$ZodCheckRegex",(t,e)=>{un.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})}}),Gi=g("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Pi),un.init(t,e)}),Vi=g("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Li),un.init(t,e)}),qi=g("$ZodCheckIncludes",(t,e)=>{X.init(t,e);let n=Ge(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})}}),Ji=g("$ZodCheckStartsWith",(t,e)=>{X.init(t,e);let n=new RegExp(`^${Ge(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})}}),Ki=g("$ZodCheckEndsWith",(t,e)=>{X.init(t,e);let n=new RegExp(`.*${Ge(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 Wi=g("$ZodCheckOverwrite",(t,e)=>{X.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});var Kn=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
+var Yf=Object.defineProperty;var Hf=(t,e)=>{for(var n in e)Yf(t,n,{get:e[n],enumerable:!0})};var Us;function g(t,e,n){function r(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=i.prototype,d=Object.keys(u);for(let l=0;l<d.length;l++){let f=d[l];f in a||(a[f]=u[f].bind(a))}}let o=n?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=n?.Parent?new s:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var qh=Symbol("zod_brand"),Ne=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},St=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Us=globalThis).__zod_globalConfig??(Us.__zod_globalConfig={});var At=globalThis.__zod_globalConfig;function be(t){return t&&Object.assign(At,t),At}var L={};Hf(L,{BIGINT_FORMAT_RANGES:()=>Js,Class:()=>uo,NUMBER_FORMAT_RANGES:()=>yo,aborted:()=>et,allowsEval:()=>po,assert:()=>rd,assertEqual:()=>Xf,assertIs:()=>td,assertNever:()=>nd,assertNotEqual:()=>ed,assignProp:()=>He,base64ToUint8Array:()=>Ws,base64urlToUint8Array:()=>Sd,cached:()=>vt,captureStackTrace:()=>Vn,cleanEnum:()=>xd,cleanRegex:()=>sn,clone:()=>we,cloneDef:()=>id,createTransparentProxy:()=>dd,defineLazy:()=>z,esc:()=>Gn,escapeRegex:()=>Ge,explicitlyAborted:()=>go,extend:()=>hd,finalizeIssue:()=>he,floatSafeRemainder:()=>lo,getElementAtPath:()=>ad,getEnumValues:()=>rn,getLengthableOrigin:()=>an,getParsedType:()=>fd,getSizableOrigin:()=>Ks,hexToUint8Array:()=>Ed,isObject:()=>ht,isPlainObject:()=>Xe,issue:()=>kt,joinValues:()=>od,jsonStringifyReplacer:()=>Et,merge:()=>gd,mergeDefs:()=>Qe,normalizeParams:()=>I,nullish:()=>on,numKeys:()=>ld,objectClone:()=>sd,omit:()=>md,optionalKeys:()=>ho,parsedType:()=>_d,partial:()=>bd,pick:()=>pd,prefixIssues:()=>Ve,primitiveTypes:()=>Vs,promiseAllObject:()=>cd,propertyKeyTypes:()=>mo,randomString:()=>ud,required:()=>wd,safeExtend:()=>yd,shallowClone:()=>Gs,slugify:()=>fo,stringifyPrimitive:()=>qs,uint8ArrayToBase64:()=>Ys,uint8ArrayToBase64url:()=>Ad,uint8ArrayToHex:()=>vd,unwrapMessage:()=>nn});function Xf(t){return t}function ed(t){return t}function td(t){}function nd(t){throw new Error("Unexpected value in exhaustive check")}function rd(t){}function rn(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 od(t,e="|"){return t.map(n=>qs(n)).join(e)}function Et(t,e){return typeof e=="bigint"?e.toString():e}function vt(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function on(t){return t==null}function sn(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function lo(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 Qs=Symbol("evaluating");function z(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==Qs)return r===void 0&&(r=Qs,r=n()),r},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function sd(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function He(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 id(t){return Qe(t._zod.def)}function ad(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function cd(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 ud(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<t;r++)n+=e[Math.floor(Math.random()*e.length)];return n}function Gn(t){return JSON.stringify(t)}function fo(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Vn="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function ht(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var po=vt(()=>{if(At.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Xe(t){if(ht(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let n=e.prototype;return!(ht(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Gs(t){return Xe(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function ld(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}var fd=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}`)}},mo=new Set(["string","number","symbol"]),Vs=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ge(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function we(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 dd(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 qs(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function ho(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var yo={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]},Js={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function pd(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 He(this,"shape",i),i},checks:[]});return we(t,s)}function md(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 He(this,"shape",i),i},checks:[]});return we(t,s)}function hd(t,e){if(!Xe(e))throw new Error("Invalid input to extend: expected a plain object");let n=t._zod.def.checks;if(n&&n.length>0){let s=t._zod.def.shape;for(let i in e)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Qe(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return He(this,"shape",s),s}});return we(t,o)}function yd(t,e){if(!Xe(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 He(this,"shape",r),r}});return we(t,n)}function gd(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 He(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return we(t,n)}function bd(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 He(this,"shape",c),c},checks:[]});return we(e,i)}function wd(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 He(this,"shape",s),s}});return we(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 go(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue===!1)return!0;return!1}function Ve(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function nn(t){return typeof t=="string"?t:t?.message}function he(t,e,n){let r=t.message?t.message:nn(t.inst?._zod.def?.error?.(t))??nn(e?.error?.(t))??nn(n.customError?.(t))??nn(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 Ks(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function an(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function _d(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let n=t;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return e}function kt(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function xd(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function Ws(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 Ys(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}function Sd(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-e.length%4)%4);return Ws(e+n)}function Ad(t){return Ys(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ed(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let n=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)n[r/2]=Number.parseInt(e.slice(r,r+2),16);return n}function vd(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var uo=class{constructor(...e){}};var Hs=(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,Et,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},qn=g("$ZodError",Hs),bo=g("$ZodError",Hs,{Parent:Error});function Xs(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 ei(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 Jn=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 Ne;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>he(c,s,be())));throw Vn(a,o?.callee),a}return i.value};var Kn=t=>async(e,n,r,o)=>{let s=r?{...r,async:!0}:{async:!0},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>he(c,s,be())));throw Vn(a,o?.callee),a}return i.value};var cn=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 Ne;return s.issues.length?{success:!1,error:new(t??qn)(s.issues.map(i=>he(i,o,be())))}:{success:!0,data:s.value}},ti=cn(bo),un=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,be())))}:{success:!0,data:s.value}},ni=un(bo),ri=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Jn(t)(e,n,o)};var oi=t=>(e,n,r)=>Jn(t)(e,n,r);var si=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Kn(t)(e,n,o)};var ii=t=>async(e,n,r)=>Kn(t)(e,n,r);var ai=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return cn(t)(e,n,o)};var ci=t=>(e,n,r)=>cn(t)(e,n,r);var ui=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return un(t)(e,n,o)};var li=t=>async(e,n,r)=>un(t)(e,n,r);var fi=/^[cC][0-9a-z]{6,}$/,di=/^[0-9a-z]+$/,pi=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,mi=/^[0-9a-vA-V]{20}$/,hi=/^[A-Za-z0-9]{27}$/,yi=/^[a-zA-Z0-9_-]{21}$/,gi=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var bi=/^([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})$/,wo=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 wi=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Dd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function _i(){return new RegExp(Dd,"u")}var xi=/^(?:(?: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])$/,Si=/^(([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 Ai=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Ei=/^(([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])$/,vi=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,_o=/^[A-Za-z0-9_-]*$/;var ki=/^https?$/,Di=/^\+[1-9]\d{6,14}$/,Ri="(?:(?:\\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])))",Ii=new RegExp(`^${Ri}$`);function Oi(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 Ci(t){return new RegExp(`^${Oi(t)}$`)}function Ni(t){let e=Oi({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(`^${Ri}T(?:${r})$`)}var $i=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Ti=/^-?\d+$/,xo=/^-?\d+(?:\.\d+)?$/,zi=/^(?:true|false)$/i,Pi=/^null$/i;var Li=/^[^A-Z]*$/,Mi=/^[^a-z]*$/;var X=g("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Fi={number:"number",bigint:"bigint",object:"date"},So=g("$ZodCheckLessThan",(t,e)=>{X.init(t,e);let n=Fi[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})}}),Ao=g("$ZodCheckGreaterThan",(t,e)=>{X.init(t,e);let n=Fi[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})}}),Zi=g("$ZodCheckMultipleOf",(t,e)=>{X.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):lo(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),ji=g("$ZodCheckNumberFormat",(t,e)=>{X.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,s]=yo[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=Ti)}),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 Bi=g("$ZodCheckMaxLength",(t,e)=>{var n;X.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!on(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=an(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Ui=g("$ZodCheckMinLength",(t,e)=>{var n;X.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!on(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=an(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Qi=g("$ZodCheckLengthEquals",(t,e)=>{var n;X.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!on(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=an(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})}}),ln=g("$ZodCheckStringFormat",(t,e)=>{var n,r;X.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),Gi=g("$ZodCheckRegex",(t,e)=>{ln.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})}}),Vi=g("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Li),ln.init(t,e)}),qi=g("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Mi),ln.init(t,e)}),Ji=g("$ZodCheckIncludes",(t,e)=>{X.init(t,e);let n=Ge(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})}}),Ki=g("$ZodCheckStartsWith",(t,e)=>{X.init(t,e);let n=new RegExp(`^${Ge(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})}}),Wi=g("$ZodCheckEndsWith",(t,e)=>{X.init(t,e);let n=new RegExp(`.*${Ge(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 Yi=g("$ZodCheckOverwrite",(t,e)=>{X.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});var Yn=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
`).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 Hi={major:4,minor:4,patch:3};var U=g("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Hi;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(go(i)||!l._zod.def.when(i))continue}else if(u)continue;let f=i.issues.length,p=l._zod.check(i);if(p instanceof Promise&&c?.async===!1)throw new Ce;if(d||p instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await p,i.issues.length!==f&&(u||(u=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 Ce;return u.then(d=>t._zod.parse(d,c))}return t._zod.parse(u,c)};t._zod.run=(i,a)=>{if(a.skipChecks)return t._zod.parse(i,a);if(a.direction==="backward"){let u=t._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(d=>s(d,i,a)):s(u,i,a)}let c=t._zod.parse(i,a);if(c instanceof Promise){if(a.async===!1)throw new Ce;return c.then(u=>o(u,r,a))}return o(c,r,a)}}z(t,"~standard",()=>({validate:o=>{try{let s=ei(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return ti(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),Hn=g("$ZodString",(t,e)=>{U.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Ni(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=g("$ZodStringFormat",(t,e)=>{un.init(t,e),Hn.init(t,e)}),aa=g("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=gi),Q.init(t,e)}),ca=g("$ZodUUID",(t,e)=>{if(e.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=wo(r))}else e.pattern??(e.pattern=wo());Q.init(t,e)}),ua=g("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=bi),Q.init(t,e)}),la=g("$ZodURL",(t,e)=>{Q.init(t,e),t._zod.check=n=>{try{let r=n.value.trim();if(!e.normalize&&e.protocol?.source===vi.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})}}}),fa=g("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=wi()),Q.init(t,e)}),da=g("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=hi),Q.init(t,e)}),pa=g("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=li),Q.init(t,e)}),ma=g("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=fi),Q.init(t,e)}),ha=g("$ZodULID",(t,e)=>{e.pattern??(e.pattern=di),Q.init(t,e)}),ya=g("$ZodXID",(t,e)=>{e.pattern??(e.pattern=pi),Q.init(t,e)}),ga=g("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=mi),Q.init(t,e)}),ba=g("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Ci(e)),Q.init(t,e)}),wa=g("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Ri),Q.init(t,e)}),_a=g("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Ii(e)),Q.init(t,e)}),xa=g("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=yi),Q.init(t,e)}),Sa=g("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=_i),Q.init(t,e),t._zod.bag.format="ipv4"}),Aa=g("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=xi),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 Ea=g("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Si),Q.init(t,e)}),va=g("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Ai),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 ka(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Da=g("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Ei),Q.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{ka(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function vd(t){if(!_o.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return ka(n)}var Ra=g("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=_o),Q.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{vd(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Oa=g("$ZodE164",(t,e)=>{e.pattern??(e.pattern=ki),Q.init(t,e)});function kd(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var Ia=g("$ZodJWT",(t,e)=>{Q.init(t,e),t._zod.check=n=>{kd(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}});var vo=g("$ZodNumber",(t,e)=>{U.init(t,e),t._zod.pattern=t._zod.bag.pattern??xo,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}}),Ca=g("$ZodNumberFormat",(t,e)=>{Zi.init(t,e),vo.init(t,e)}),Na=g("$ZodBoolean",(t,e)=>{U.init(t,e),t._zod.pattern=Ti,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 $a=g("$ZodNull",(t,e)=>{U.init(t,e),t._zod.pattern=zi,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 Ta=g("$ZodUnknown",(t,e)=>{U.init(t,e),t._zod.parse=n=>n}),za=g("$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 Xi(t,e,n){t.issues.length&&e.issues.push(...Ve(n,t.issues)),e.value[n]=t.value}var Pa=g("$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=>Xi(u,n,i))):Xi(c,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function Yn(t,e,n,r,o,s){let i=n in r;if(t.issues.length){if(o&&s&&!i)return;e.issues.push(...Ve(n,t.issues))}if(!i&&!o){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}t.value===void 0?i&&(e.value[n]=void 0):e.value[n]=t.value}function La(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=ho(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Ma(t,e,n,r,o,s){let i=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,d=c.optin==="optional",l=c.optout==="optional";for(let f in e){if(f==="__proto__"||a.has(f))continue;if(u==="never"){i.push(f);continue}let p=c.run({value:e[f],issues:[]},r);p instanceof Promise?t.push(p.then(y=>Yn(y,n,f,e,d,l))):Yn(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 Dd=g("$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=vt(()=>La(e));z(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=ht,s=e.catchall,i;t._zod.parse=(a,c)=>{i??(i=r.value);let u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let d=[],l=i.shape;for(let f of i.keys){let p=l[f],y=p._zod.optin==="optional",m=p._zod.optout==="optional",h=p._zod.run({value:u[f],issues:[]},c);h instanceof Promise?d.push(h.then(w=>Yn(w,a,f,u,y,m))):Yn(h,a,f,u,y,m)}return s?Ma(d,u,a,c,r.value,t):d.length?Promise.all(d).then(()=>a):a}}),Fa=g("$ZodObjectJIT",(t,e)=>{Dd.init(t,e);let n=t._zod.parse,r=vt(()=>La(e)),o=f=>{let p=new Kn(["shape","payload","ctx"]),y=r.value,m=A=>{let _=Un(A);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),w=0;for(let A of y.keys)h[A]=`key_${w++}`;p.write("const newResult = {};");for(let A of y.keys){let _=h[A],b=Un(A),E=f[A],k=E?._zod?.optin==="optional",x=E?._zod?.optout==="optional";p.write(`const ${_} = ${m(A)};`),k&&x?p.write(`
+`))}};var Xi={major:4,minor:4,patch:3};var U=g("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Xi;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(go(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 Ne;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 Ne;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 Ne;return c.then(u=>o(u,r,a))}return o(c,r,a)}}z(t,"~standard",()=>({validate:o=>{try{let s=ti(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return ni(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),er=g("$ZodString",(t,e)=>{U.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??$i(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=g("$ZodStringFormat",(t,e)=>{ln.init(t,e),er.init(t,e)}),ca=g("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=bi),Q.init(t,e)}),ua=g("$ZodUUID",(t,e)=>{if(e.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=wo(r))}else e.pattern??(e.pattern=wo());Q.init(t,e)}),la=g("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=wi),Q.init(t,e)}),fa=g("$ZodURL",(t,e)=>{Q.init(t,e),t._zod.check=n=>{try{let r=n.value.trim();if(!e.normalize&&e.protocol?.source===ki.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})}}}),da=g("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=_i()),Q.init(t,e)}),pa=g("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=yi),Q.init(t,e)}),ma=g("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=fi),Q.init(t,e)}),ha=g("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=di),Q.init(t,e)}),ya=g("$ZodULID",(t,e)=>{e.pattern??(e.pattern=pi),Q.init(t,e)}),ga=g("$ZodXID",(t,e)=>{e.pattern??(e.pattern=mi),Q.init(t,e)}),ba=g("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=hi),Q.init(t,e)}),wa=g("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Ni(e)),Q.init(t,e)}),_a=g("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Ii),Q.init(t,e)}),xa=g("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Ci(e)),Q.init(t,e)}),Sa=g("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=gi),Q.init(t,e)}),Aa=g("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=xi),Q.init(t,e),t._zod.bag.format="ipv4"}),Ea=g("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Si),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 va=g("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Ai),Q.init(t,e)}),ka=g("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Ei),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 Da(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Ra=g("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=vi),Q.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{Da(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function Rd(t){if(!_o.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Da(n)}var Ia=g("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=_o),Q.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{Rd(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Oa=g("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Di),Q.init(t,e)});function Id(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 Ca=g("$ZodJWT",(t,e)=>{Q.init(t,e),t._zod.check=n=>{Id(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}});var vo=g("$ZodNumber",(t,e)=>{U.init(t,e),t._zod.pattern=t._zod.bag.pattern??xo,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}}),Na=g("$ZodNumberFormat",(t,e)=>{ji.init(t,e),vo.init(t,e)}),$a=g("$ZodBoolean",(t,e)=>{U.init(t,e),t._zod.pattern=zi,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 Ta=g("$ZodNull",(t,e)=>{U.init(t,e),t._zod.pattern=Pi,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 za=g("$ZodUnknown",(t,e)=>{U.init(t,e),t._zod.parse=n=>n}),Pa=g("$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 ea(t,e,n){t.issues.length&&e.issues.push(...Ve(n,t.issues)),e.value[n]=t.value}var La=g("$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=>ea(u,n,i))):ea(c,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function Xn(t,e,n,r,o,s){let i=n in r;if(t.issues.length){if(o&&s&&!i)return;e.issues.push(...Ve(n,t.issues))}if(!i&&!o){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}t.value===void 0?i&&(e.value[n]=void 0):e.value[n]=t.value}function Ma(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=ho(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Fa(t,e,n,r,o,s){let i=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,d=c.optin==="optional",l=c.optout==="optional";for(let f in e){if(f==="__proto__"||a.has(f))continue;if(u==="never"){i.push(f);continue}let p=c.run({value:e[f],issues:[]},r);p instanceof Promise?t.push(p.then(y=>Xn(y,n,f,e,d,l))):Xn(p,n,f,e,d,l)}return i.length&&n.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:s}),t.length?Promise.all(t).then(()=>n):n}var Od=g("$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=vt(()=>Ma(e));z(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=ht,s=e.catchall,i;t._zod.parse=(a,c)=>{i??(i=r.value);let u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let d=[],l=i.shape;for(let f of i.keys){let p=l[f],y=p._zod.optin==="optional",m=p._zod.optout==="optional",h=p._zod.run({value:u[f],issues:[]},c);h instanceof Promise?d.push(h.then(b=>Xn(b,a,f,u,y,m))):Xn(h,a,f,u,y,m)}return s?Fa(d,u,a,c,r.value,t):d.length?Promise.all(d).then(()=>a):a}}),Za=g("$ZodObjectJIT",(t,e)=>{Od.init(t,e);let n=t._zod.parse,r=vt(()=>Ma(e)),o=f=>{let p=new Yn(["shape","payload","ctx"]),y=r.value,m=A=>{let _=Gn(A);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),b=0;for(let A of y.keys)h[A]=`key_${b++}`;p.write("const newResult = {};");for(let A of y.keys){let _=h[A],w=Gn(A),E=f[A],k=E?._zod?.optin==="optional",x=E?._zod?.optout==="optional";p.write(`const ${_} = ${m(A)};`),k&&x?p.write(`
if (${_}.issues.length) {
- if (${b} in input) {
+ if (${w} in input) {
payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
...iss,
- path: iss.path ? [${b}, ...iss.path] : [${b}]
+ path: iss.path ? [${w}, ...iss.path] : [${w}]
})));
}
}
if (${_}.value === undefined) {
- if (${b} in input) {
- newResult[${b}] = undefined;
+ if (${w} in input) {
+ newResult[${w}] = undefined;
}
} else {
- newResult[${b}] = ${_}.value;
+ newResult[${w}] = ${_}.value;
}
`):k?p.write(`
if (${_}.issues.length) {
payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
...iss,
- path: iss.path ? [${b}, ...iss.path] : [${b}]
+ path: iss.path ? [${w}, ...iss.path] : [${w}]
})));
}
if (${_}.value === undefined) {
- if (${b} in input) {
- newResult[${b}] = undefined;
+ if (${w} in input) {
+ newResult[${w}] = undefined;
}
} else {
- newResult[${b}] = ${_}.value;
+ newResult[${w}] = ${_}.value;
}
`):p.write(`
- const ${_}_present = ${b} in input;
+ const ${_}_present = ${w} in input;
if (${_}.issues.length) {
payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
...iss,
- path: iss.path ? [${b}, ...iss.path] : [${b}]
+ path: iss.path ? [${w}, ...iss.path] : [${w}]
})));
}
if (!${_}_present && !${_}.issues.length) {
@@ -47,148 +47,148 @@ var Jf=Object.defineProperty;var Kf=(t,e)=>{for(var n in e)Jf(t,n,{get:e[n],enum
code: "invalid_type",
expected: "nonoptional",
input: undefined,
- path: [${b}]
+ path: [${w}]
});
}
if (${_}_present) {
if (${_}.value === undefined) {
- newResult[${b}] = undefined;
+ newResult[${w}] = undefined;
} else {
- newResult[${b}] = ${_}.value;
+ newResult[${w}] = ${_}.value;
}
}
- `)}p.write("payload.value = newResult;"),p.write("return payload;");let S=p.compile();return(A,_)=>S(f,A,_)},s,i=ht,a=!At.jitless,u=a&&po.value,d=e.catchall,l;t._zod.parse=(f,p)=>{l??(l=r.value);let y=f.value;return i(y)?a&&u&&p?.async===!1&&p.jitless!==!0?(s||(s=o(e.shape)),f=s(f,p),d?Ma([],y,f,p,l,t):f):n(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:y,inst:t}),f)}});function ea(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,be())))}),e)}var ko=g("$ZodUnion",(t,e)=>{U.init(t,e),z(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),z(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),z(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),z(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=>on(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=>ea(a,r,t,o)):ea(i,r,t,o)}});var Za=g("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,ko.init(t,e);let n=t._zod.parse;z(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=vt(()=>{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(!ht(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)}}),ja=g("$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])=>ta(n,c,u)):ta(n,s,i)}});function Eo(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Xe(t)&&Xe(e)){let n=Object.keys(e),r=Object.keys(t).filter(s=>n.indexOf(s)!==-1),o={...t,...e};for(let s of r){let i=Eo(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=Eo(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 ta(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=Eo(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 Ba=g("$ZodRecord",(t,e)=>{U.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Xe(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let s=[],i=e.keyType._zod.values;if(i){n.value={};let a=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let d=e.keyType._zod.run({value:u,issues:[]},r);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(d.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(p=>he(p,r,be())),input:u,path:[u],inst:t});continue}let l=d.value,f=e.valueType._zod.run({value:o[u],issues:[]},r);f instanceof Promise?s.push(f.then(p=>{p.issues.length&&n.issues.push(...Ve(u,p.issues)),n.value[l]=p.value})):(f.issues.length&&n.issues.push(...Ve(u,f.issues)),n.value[l]=f.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{n.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},r);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&xo.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,be())),input:a,path:[a],inst:t});continue}let d=e.valueType._zod.run({value:o[a],issues:[]},r);d instanceof Promise?s.push(d.then(l=>{l.issues.length&&n.issues.push(...Ve(a,l.issues)),n.value[c.value]=l.value})):(d.issues.length&&n.issues.push(...Ve(a,d.issues)),n.value[c.value]=d.value)}}return s.length?Promise.all(s).then(()=>n):n}});var Ua=g("$ZodEnum",(t,e)=>{U.init(t,e);let n=nn(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(o=>mo.has(typeof o)).map(o=>typeof o=="string"?Ge(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}}),Qa=g("$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"?Ge(r):r?Ge(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 Ga=g("$ZodTransform",(t,e)=>{U.init(t,e),t._zod.optin="optional",t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new St(t.constructor.name);let o=e.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n.fallback=!0,n));if(o instanceof Promise)throw new Ce;return n.value=o,n.fallback=!0,n}});function na(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var Do=g("$ZodOptional",(t,e)=>{U.init(t,e),t._zod.optin="optional",t._zod.optout="optional",z(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),z(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${on(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=>na(i,o)):na(s,o)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),Va=g("$ZodExactOptional",(t,e)=>{Do.init(t,e),z(t._zod,"values",()=>e.innerType._zod.values),z(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(n,r)=>e.innerType._zod.run(n,r)}),qa=g("$ZodNullable",(t,e)=>{U.init(t,e),z(t._zod,"optin",()=>e.innerType._zod.optin),z(t._zod,"optout",()=>e.innerType._zod.optout),z(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${on(n.source)}|null)$`):void 0}),z(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)}),Ja=g("$ZodDefault",(t,e)=>{U.init(t,e),t._zod.optin="optional",z(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=>ra(s,e)):ra(o,e)}});function ra(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Ka=g("$ZodPrefault",(t,e)=>{U.init(t,e),t._zod.optin="optional",z(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))}),Wa=g("$ZodNonOptional",(t,e)=>{U.init(t,e),z(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=>oa(s,t)):oa(o,t)}});function oa(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 Ya=g("$ZodCatch",(t,e)=>{U.init(t,e),t._zod.optin="optional",z(t._zod,"optout",()=>e.innerType._zod.optout),z(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,be()))},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,be()))},input:n.value}),n.issues=[],n.fallback=!0),n)}});var Ha=g("$ZodPipe",(t,e)=>{U.init(t,e),z(t._zod,"values",()=>e.in._zod.values),z(t._zod,"optin",()=>e.in._zod.optin),z(t._zod,"optout",()=>e.out._zod.optout),z(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=>Wn(i,e.in,r)):Wn(s,e.in,r)}let o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Wn(s,e.out,r)):Wn(o,e.out,r)}});function Wn(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 Xa=g("$ZodReadonly",(t,e)=>{U.init(t,e),z(t._zod,"propValues",()=>e.innerType._zod.propValues),z(t._zod,"values",()=>e.innerType._zod.values),z(t._zod,"optin",()=>e.innerType?._zod?.optin),z(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(sa):sa(o)}});function sa(t){return t.value=Object.freeze(t.value),t}var ec=g("$ZodLazy",(t,e)=>{U.init(t,e),z(t._zod,"innerType",()=>{let n=e;return n._cachedInner||(n._cachedInner=e.getter()),n._cachedInner}),z(t._zod,"pattern",()=>t._zod.innerType?._zod?.pattern),z(t._zod,"propValues",()=>t._zod.innerType?._zod?.propValues),z(t._zod,"optin",()=>t._zod.innerType?._zod?.optin??void 0),z(t._zod,"optout",()=>t._zod.innerType?._zod?.optout??void 0),t._zod.parse=(n,r)=>t._zod.innerType._zod.run(n,r)}),tc=g("$ZodCustom",(t,e)=>{X.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=>ia(s,n,r,t));ia(o,n,r,t)}});function ia(t,e,n,r){if(!t){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),e.issues.push(kt(o))}}var nc,iy=Symbol("ZodOutput"),ay=Symbol("ZodInput"),Ro=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 Rd(){return new Ro}(nc=globalThis).__zod_globalRegistry??(nc.__zod_globalRegistry=Rd());var yt=globalThis.__zod_globalRegistry;function rc(t,e){return new t({type:"string",...O(e)})}function oc(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...O(e)})}function Oo(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...O(e)})}function sc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...O(e)})}function ic(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...O(e)})}function ac(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...O(e)})}function cc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...O(e)})}function uc(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...O(e)})}function lc(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...O(e)})}function fc(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...O(e)})}function dc(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...O(e)})}function pc(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...O(e)})}function mc(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...O(e)})}function hc(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...O(e)})}function yc(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...O(e)})}function gc(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...O(e)})}function bc(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...O(e)})}function wc(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...O(e)})}function _c(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...O(e)})}function xc(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...O(e)})}function Sc(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...O(e)})}function Ac(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...O(e)})}function Ec(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...O(e)})}function vc(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...O(e)})}function kc(t,e){return new t({type:"string",format:"date",check:"string_format",...O(e)})}function Dc(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...O(e)})}function Rc(t,e){return new t({type:"string",format:"duration",check:"string_format",...O(e)})}function Oc(t,e){return new t({type:"number",checks:[],...O(e)})}function Ic(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...O(e)})}function Cc(t,e){return new t({type:"boolean",...O(e)})}function Nc(t,e){return new t({type:"null",...O(e)})}function $c(t){return new t({type:"unknown"})}function Tc(t,e){return new t({type:"never",...O(e)})}function Xn(t,e){return new So({check:"less_than",...O(e),value:t,inclusive:!1})}function ln(t,e){return new So({check:"less_than",...O(e),value:t,inclusive:!0})}function er(t,e){return new Ao({check:"greater_than",...O(e),value:t,inclusive:!1})}function fn(t,e){return new Ao({check:"greater_than",...O(e),value:t,inclusive:!0})}function tr(t,e){return new Fi({check:"multiple_of",...O(e),value:t})}function nr(t,e){return new ji({check:"max_length",...O(e),maximum:t})}function Dt(t,e){return new Bi({check:"min_length",...O(e),minimum:t})}function rr(t,e){return new Ui({check:"length_equals",...O(e),length:t})}function Io(t,e){return new Qi({check:"string_format",format:"regex",...O(e),pattern:t})}function Co(t){return new Gi({check:"string_format",format:"lowercase",...O(t)})}function No(t){return new Vi({check:"string_format",format:"uppercase",...O(t)})}function $o(t,e){return new qi({check:"string_format",format:"includes",...O(e),includes:t})}function To(t,e){return new Ji({check:"string_format",format:"starts_with",...O(e),prefix:t})}function zo(t,e){return new Ki({check:"string_format",format:"ends_with",...O(e),suffix:t})}function tt(t){return new Wi({check:"overwrite",tx:t})}function Po(t){return tt(e=>e.normalize(t))}function Lo(){return tt(t=>t.trim())}function Mo(){return tt(t=>t.toLowerCase())}function Fo(){return tt(t=>t.toUpperCase())}function Zo(){return tt(t=>fo(t))}function zc(t,e,n){return new t({type:"array",element:e,...O(n)})}function Pc(t,e,n){return new t({type:"custom",check:"custom",fn:e,...O(n)})}function Lc(t,e){let n=Od(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(kt(o,r.value,n._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),r.issues.push(kt(s))}},t(r.value,r)),e);return n}function Od(t,e){let n=new X({check:"custom",...O(e)});return n._zod.check=t,n}function jo(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??yt,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"&&ne(t)&&(delete i.schema.examples,delete i.schema.default),e.io==="input"&&"_prefault"in i.schema&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,e.seen.get(t).schema}function Bo(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=new Map;for(let i of t.seen.entries()){let a=t.metadataRegistry.get(i[0])?.id;if(a){let c=r.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,i[0])}}let o=i=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let l=t.external.registry.get(i[0])?.id,f=t.external.uri??(y=>y);if(l)return{ref:f(l)};let p=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=p,{defId:p,ref:`${f("__shared")}#/${a}/${p}`}}if(i[1]===n)return{ref:"#"};let u=`#/${a}/`,d=i[1].schema.id??`__schema${t.counter++}`;return{defId:d,ref:u+d}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=o(i);a.def={...a.schema},u&&(a.defId=u);let d=a.schema;for(let l in d)delete d[l];d.$ref=c};if(t.cycles==="throw")for(let i of t.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
+ `)}p.write("payload.value = newResult;"),p.write("return payload;");let S=p.compile();return(A,_)=>S(f,A,_)},s,i=ht,a=!At.jitless,u=a&&po.value,d=e.catchall,l;t._zod.parse=(f,p)=>{l??(l=r.value);let y=f.value;return i(y)?a&&u&&p?.async===!1&&p.jitless!==!0?(s||(s=o(e.shape)),f=s(f,p),d?Fa([],y,f,p,l,t):f):n(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:y,inst:t}),f)}});function ta(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,be())))}),e)}var ko=g("$ZodUnion",(t,e)=>{U.init(t,e),z(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),z(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),z(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),z(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=>sn(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=>ta(a,r,t,o)):ta(i,r,t,o)}});var ja=g("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,ko.init(t,e);let n=t._zod.parse;z(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=vt(()=>{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(!ht(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)}}),Ba=g("$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])=>na(n,c,u)):na(n,s,i)}});function Eo(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Xe(t)&&Xe(e)){let n=Object.keys(e),r=Object.keys(t).filter(s=>n.indexOf(s)!==-1),o={...t,...e};for(let s of r){let i=Eo(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=Eo(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 na(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=Eo(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 Ua=g("$ZodRecord",(t,e)=>{U.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Xe(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let s=[],i=e.keyType._zod.values;if(i){n.value={};let a=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let d=e.keyType._zod.run({value:u,issues:[]},r);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(d.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(p=>he(p,r,be())),input:u,path:[u],inst:t});continue}let l=d.value,f=e.valueType._zod.run({value:o[u],issues:[]},r);f instanceof Promise?s.push(f.then(p=>{p.issues.length&&n.issues.push(...Ve(u,p.issues)),n.value[l]=p.value})):(f.issues.length&&n.issues.push(...Ve(u,f.issues)),n.value[l]=f.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{n.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},r);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&xo.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,be())),input:a,path:[a],inst:t});continue}let d=e.valueType._zod.run({value:o[a],issues:[]},r);d instanceof Promise?s.push(d.then(l=>{l.issues.length&&n.issues.push(...Ve(a,l.issues)),n.value[c.value]=l.value})):(d.issues.length&&n.issues.push(...Ve(a,d.issues)),n.value[c.value]=d.value)}}return s.length?Promise.all(s).then(()=>n):n}});var Qa=g("$ZodEnum",(t,e)=>{U.init(t,e);let n=rn(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(o=>mo.has(typeof o)).map(o=>typeof o=="string"?Ge(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}}),Ga=g("$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"?Ge(r):r?Ge(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 Va=g("$ZodTransform",(t,e)=>{U.init(t,e),t._zod.optin="optional",t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new St(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 Ne;return n.value=o,n.fallback=!0,n}});function ra(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var Do=g("$ZodOptional",(t,e)=>{U.init(t,e),t._zod.optin="optional",t._zod.optout="optional",z(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),z(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${sn(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=>ra(i,o)):ra(s,o)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),qa=g("$ZodExactOptional",(t,e)=>{Do.init(t,e),z(t._zod,"values",()=>e.innerType._zod.values),z(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(n,r)=>e.innerType._zod.run(n,r)}),Ja=g("$ZodNullable",(t,e)=>{U.init(t,e),z(t._zod,"optin",()=>e.innerType._zod.optin),z(t._zod,"optout",()=>e.innerType._zod.optout),z(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${sn(n.source)}|null)$`):void 0}),z(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)}),Ka=g("$ZodDefault",(t,e)=>{U.init(t,e),t._zod.optin="optional",z(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=>oa(s,e)):oa(o,e)}});function oa(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Wa=g("$ZodPrefault",(t,e)=>{U.init(t,e),t._zod.optin="optional",z(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))}),Ya=g("$ZodNonOptional",(t,e)=>{U.init(t,e),z(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=>sa(s,t)):sa(o,t)}});function sa(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 Ha=g("$ZodCatch",(t,e)=>{U.init(t,e),t._zod.optin="optional",z(t._zod,"optout",()=>e.innerType._zod.optout),z(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,be()))},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,be()))},input:n.value}),n.issues=[],n.fallback=!0),n)}});var Xa=g("$ZodPipe",(t,e)=>{U.init(t,e),z(t._zod,"values",()=>e.in._zod.values),z(t._zod,"optin",()=>e.in._zod.optin),z(t._zod,"optout",()=>e.out._zod.optout),z(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,r)=>{if(r.direction==="backward"){let s=e.out._zod.run(n,r);return s instanceof Promise?s.then(i=>Hn(i,e.in,r)):Hn(s,e.in,r)}let o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Hn(s,e.out,r)):Hn(o,e.out,r)}});function Hn(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},n)}var ec=g("$ZodReadonly",(t,e)=>{U.init(t,e),z(t._zod,"propValues",()=>e.innerType._zod.propValues),z(t._zod,"values",()=>e.innerType._zod.values),z(t._zod,"optin",()=>e.innerType?._zod?.optin),z(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(ia):ia(o)}});function ia(t){return t.value=Object.freeze(t.value),t}var tc=g("$ZodLazy",(t,e)=>{U.init(t,e),z(t._zod,"innerType",()=>{let n=e;return n._cachedInner||(n._cachedInner=e.getter()),n._cachedInner}),z(t._zod,"pattern",()=>t._zod.innerType?._zod?.pattern),z(t._zod,"propValues",()=>t._zod.innerType?._zod?.propValues),z(t._zod,"optin",()=>t._zod.innerType?._zod?.optin??void 0),z(t._zod,"optout",()=>t._zod.innerType?._zod?.optout??void 0),t._zod.parse=(n,r)=>t._zod.innerType._zod.run(n,r)}),nc=g("$ZodCustom",(t,e)=>{X.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=>aa(s,n,r,t));aa(o,n,r,t)}});function aa(t,e,n,r){if(!t){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),e.issues.push(kt(o))}}var rc,ly=Symbol("ZodOutput"),fy=Symbol("ZodInput"),Ro=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 Cd(){return new Ro}(rc=globalThis).__zod_globalRegistry??(rc.__zod_globalRegistry=Cd());var yt=globalThis.__zod_globalRegistry;function oc(t,e){return new t({type:"string",...I(e)})}function sc(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...I(e)})}function Io(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...I(e)})}function ic(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...I(e)})}function ac(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(e)})}function cc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(e)})}function uc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(e)})}function lc(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...I(e)})}function fc(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...I(e)})}function dc(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(e)})}function pc(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...I(e)})}function mc(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(e)})}function hc(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...I(e)})}function yc(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...I(e)})}function gc(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(e)})}function bc(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(e)})}function wc(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(e)})}function _c(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(e)})}function xc(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(e)})}function Sc(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...I(e)})}function Ac(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...I(e)})}function Ec(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...I(e)})}function vc(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...I(e)})}function kc(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(e)})}function Dc(t,e){return new t({type:"string",format:"date",check:"string_format",...I(e)})}function Rc(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...I(e)})}function Ic(t,e){return new t({type:"string",format:"duration",check:"string_format",...I(e)})}function Oc(t,e){return new t({type:"number",checks:[],...I(e)})}function Cc(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...I(e)})}function Nc(t,e){return new t({type:"boolean",...I(e)})}function $c(t,e){return new t({type:"null",...I(e)})}function Tc(t){return new t({type:"unknown"})}function zc(t,e){return new t({type:"never",...I(e)})}function tr(t,e){return new So({check:"less_than",...I(e),value:t,inclusive:!1})}function fn(t,e){return new So({check:"less_than",...I(e),value:t,inclusive:!0})}function nr(t,e){return new Ao({check:"greater_than",...I(e),value:t,inclusive:!1})}function dn(t,e){return new Ao({check:"greater_than",...I(e),value:t,inclusive:!0})}function rr(t,e){return new Zi({check:"multiple_of",...I(e),value:t})}function or(t,e){return new Bi({check:"max_length",...I(e),maximum:t})}function Dt(t,e){return new Ui({check:"min_length",...I(e),minimum:t})}function sr(t,e){return new Qi({check:"length_equals",...I(e),length:t})}function Oo(t,e){return new Gi({check:"string_format",format:"regex",...I(e),pattern:t})}function Co(t){return new Vi({check:"string_format",format:"lowercase",...I(t)})}function No(t){return new qi({check:"string_format",format:"uppercase",...I(t)})}function $o(t,e){return new Ji({check:"string_format",format:"includes",...I(e),includes:t})}function To(t,e){return new Ki({check:"string_format",format:"starts_with",...I(e),prefix:t})}function zo(t,e){return new Wi({check:"string_format",format:"ends_with",...I(e),suffix:t})}function tt(t){return new Yi({check:"overwrite",tx:t})}function Po(t){return tt(e=>e.normalize(t))}function Lo(){return tt(t=>t.trim())}function Mo(){return tt(t=>t.toLowerCase())}function Fo(){return tt(t=>t.toUpperCase())}function Zo(){return tt(t=>fo(t))}function Pc(t,e,n){return new t({type:"array",element:e,...I(n)})}function Lc(t,e,n){return new t({type:"custom",check:"custom",fn:e,...I(n)})}function Mc(t,e){let n=Nd(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(kt(o,r.value,n._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),r.issues.push(kt(s))}},t(r.value,r)),e);return n}function Nd(t,e){let n=new X({check:"custom",...I(e)});return n._zod.check=t,n}function jo(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??yt,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"&&ne(t)&&(delete i.schema.examples,delete i.schema.default),e.io==="input"&&"_prefault"in i.schema&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,e.seen.get(t).schema}function Bo(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=new Map;for(let i of t.seen.entries()){let a=t.metadataRegistry.get(i[0])?.id;if(a){let c=r.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,i[0])}}let o=i=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let l=t.external.registry.get(i[0])?.id,f=t.external.uri??(y=>y);if(l)return{ref:f(l)};let p=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=p,{defId:p,ref:`${f("__shared")}#/${a}/${p}`}}if(i[1]===n)return{ref:"#"};let u=`#/${a}/`,d=i[1].schema.id??`__schema${t.counter++}`;return{defId:d,ref:u+d}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=o(i);a.def={...a.schema},u&&(a.defId=u);let d=a.schema;for(let l in d)delete d[l];d.$ref=c};if(t.cycles==="throw")for(let i of t.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
-Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of t.seen.entries()){let a=i[1];if(e===i[0]){s(i);continue}if(t.external){let u=t.external.registry.get(i[0])?.id;if(e!==i[0]&&u){s(i);continue}}if(t.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&t.reused==="ref"){s(i);continue}}}function Uo(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,d={...u},l=c.ref;if(c.ref=null,l){r(l);let p=t.seen.get(l),y=p.schema;if(y.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(y)):Object.assign(u,y),Object.assign(u,d),a._zod.parent===l)for(let h in u)h==="$ref"||h==="allOf"||h in d||delete u[h];if(y.$ref&&p.def)for(let h in u)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(u[h])===JSON.stringify(p.def[h])&&delete u[h]}let f=a._zod.parent;if(f&&f!==l){r(f);let p=t.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let y in u)y==="$ref"||y==="allOf"||y in p.def&&JSON.stringify(u[y])===JSON.stringify(p.def[y])&&delete u[y]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())r(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,n.def??n.schema);let s=t.metadataRegistry.get(e)?.id;s!==void 0&&o.id===s&&delete o.id;let i=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:dn(e,"input",t.processors),output:dn(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function ne(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let r=t._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return ne(r.element,n);if(r.type==="set")return ne(r.valueType,n);if(r.type==="lazy")return ne(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return ne(r.innerType,n);if(r.type==="intersection")return ne(r.left,n)||ne(r.right,n);if(r.type==="record"||r.type==="map")return ne(r.keyType,n)||ne(r.valueType,n);if(r.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:ne(r.in,n)||ne(r.out,n);if(r.type==="object"){for(let o in r.shape)if(ne(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(ne(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(ne(o,n))return!0;return!!(r.rest&&ne(r.rest,n))}return!1}var Mc=(t,e={})=>n=>{let r=jo({...n,processors:e});return J(t,r),Bo(r,t),Uo(r,t)},dn=(t,e,n={})=>r=>{let{libraryOptions:o,target:s}=r??{},i=jo({...o??{},target:s,io:e,processors:n});return J(t,i),Bo(i,t),Uo(i,t)};var Id={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Fc=(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=Id[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}))])}},Zc=(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)},jc=(t,e,n,r)=>{n.type="boolean"};var Bc=(t,e,n,r)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"};var Uc=(t,e,n,r)=>{n.not={}};var Qc=(t,e,n,r)=>{};var Gc=(t,e,n,r)=>{let o=t._zod.def,s=nn(o.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},Vc=(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 qc=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var Jc=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var Kc=(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"]})},Wc=(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)},Yc=(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},Hc=(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 Xc=(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)}},eu=(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"}]},tu=(t,e,n,r)=>{let o=t._zod.def;J(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType},nu=(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))},ru=(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)))},ou=(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},su=(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},iu=(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 Qo=(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 Ld=g("ZodISODateTime",(t,e)=>{ba.init(t,e),q.init(t,e)});function cu(t){return vc(Ld,t)}var Md=g("ZodISODate",(t,e)=>{wa.init(t,e),q.init(t,e)});function uu(t){return kc(Md,t)}var Fd=g("ZodISOTime",(t,e)=>{_a.init(t,e),q.init(t,e)});function lu(t){return Dc(Fd,t)}var Zd=g("ZodISODuration",(t,e)=>{xa.init(t,e),q.init(t,e)});function fu(t){return Rc(Zd,t)}var Ud=(t,e)=>{Gn.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>Xs(t,n)},flatten:{value:n=>Hs(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,Et,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,Et,2)}},isEmpty:{get(){return t.issues.length===0}}})};var ue=g("ZodError",Ud,{Parent:Error});var du=Vn(ue),pu=qn(ue),mu=an(ue),hu=cn(ue),yu=ni(ue),gu=ri(ue),bu=oi(ue),wu=si(ue),_u=ii(ue),xu=ai(ue),Su=ci(ue),Au=ui(ue);var Eu=new WeakMap;function pn(t,e,n){let r=Object.getPrototypeOf(t),o=Eu.get(r);if(o||(o=new Set,Eu.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 G=g("ZodType",(t,e)=>(U.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:dn(t,"input"),output:dn(t,"output")}}),t.toJSONSchema=Mc(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,r)=>du(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>mu(t,n,r),t.parseAsync=async(n,r)=>pu(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>hu(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>yu(t,n,r),t.decode=(n,r)=>gu(t,n,r),t.encodeAsync=async(n,r)=>bu(t,n,r),t.decodeAsync=async(n,r)=>wu(t,n,r),t.safeEncode=(n,r)=>_u(t,n,r),t.safeDecode=(n,r)=>xu(t,n,r),t.safeEncodeAsync=async(n,r)=>Su(t,n,r),t.safeDecodeAsync=async(n,r)=>Au(t,n,r),pn(t,"ZodType",{check(...n){let r=this.def;return this.clone(L.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 we(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Lp(n,r))},superRefine(n,r){return this.check(Mp(n,r))},overwrite(n){return this.check(tt(n))},optional(){return Ou(this)},exactOptional(){return Ap(this)},nullable(){return Iu(this)},nullish(){return Ou(Iu(this))},nonoptional(n){return Op(this,n)},array(){return V(this)},or(n){return ir([this,n])},and(n){return bp(this,n)},transform(n){return Cu(this,xp(n))},default(n){return kp(this,n)},prefault(n){return Rp(this,n)},catch(n){return Cp(this,n)},pipe(n){return Cu(this,n)},readonly(){return Tp(this)},describe(n){let r=this.clone();return yt.add(r,{description:n}),r},meta(...n){if(n.length===0)return yt.get(this);let r=this.clone();return yt.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 yt.get(t)?.description},configurable:!0}),t)),Nu=g("_ZodString",(t,e)=>{Hn.init(t,e),G.init(t,e),t._zod.processJSONSchema=(r,o,s)=>Fc(t,r,o,s);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,pn(t,"_ZodString",{regex(...r){return this.check(Io(...r))},includes(...r){return this.check($o(...r))},startsWith(...r){return this.check(To(...r))},endsWith(...r){return this.check(zo(...r))},min(...r){return this.check(Dt(...r))},max(...r){return this.check(nr(...r))},length(...r){return this.check(rr(...r))},nonempty(...r){return this.check(Dt(1,...r))},lowercase(r){return this.check(Co(r))},uppercase(r){return this.check(No(r))},trim(){return this.check(Lo())},normalize(...r){return this.check(Po(...r))},toLowerCase(){return this.check(Mo())},toUpperCase(){return this.check(Fo())},slugify(){return this.check(Zo())}})}),Gd=g("ZodString",(t,e)=>{Hn.init(t,e),Nu.init(t,e),t.email=n=>t.check(oc(Vd,n)),t.url=n=>t.check(uc(qd,n)),t.jwt=n=>t.check(Ec(cp,n)),t.emoji=n=>t.check(lc(Jd,n)),t.guid=n=>t.check(Oo(vu,n)),t.uuid=n=>t.check(sc(sr,n)),t.uuidv4=n=>t.check(ic(sr,n)),t.uuidv6=n=>t.check(ac(sr,n)),t.uuidv7=n=>t.check(cc(sr,n)),t.nanoid=n=>t.check(fc(Kd,n)),t.guid=n=>t.check(Oo(vu,n)),t.cuid=n=>t.check(dc(Wd,n)),t.cuid2=n=>t.check(pc(Yd,n)),t.ulid=n=>t.check(mc(Hd,n)),t.base64=n=>t.check(xc(sp,n)),t.base64url=n=>t.check(Sc(ip,n)),t.xid=n=>t.check(hc(Xd,n)),t.ksuid=n=>t.check(yc(ep,n)),t.ipv4=n=>t.check(gc(tp,n)),t.ipv6=n=>t.check(bc(np,n)),t.cidrv4=n=>t.check(wc(rp,n)),t.cidrv6=n=>t.check(_c(op,n)),t.e164=n=>t.check(Ac(ap,n)),t.datetime=n=>t.check(cu(n)),t.date=n=>t.check(uu(n)),t.time=n=>t.check(lu(n)),t.duration=n=>t.check(fu(n))});function v(t){return rc(Gd,t)}var q=g("ZodStringFormat",(t,e)=>{Q.init(t,e),Nu.init(t,e)}),Vd=g("ZodEmail",(t,e)=>{ua.init(t,e),q.init(t,e)});var vu=g("ZodGUID",(t,e)=>{aa.init(t,e),q.init(t,e)});var sr=g("ZodUUID",(t,e)=>{ca.init(t,e),q.init(t,e)});var qd=g("ZodURL",(t,e)=>{la.init(t,e),q.init(t,e)});var Jd=g("ZodEmoji",(t,e)=>{fa.init(t,e),q.init(t,e)});var Kd=g("ZodNanoID",(t,e)=>{da.init(t,e),q.init(t,e)});var Wd=g("ZodCUID",(t,e)=>{pa.init(t,e),q.init(t,e)});var Yd=g("ZodCUID2",(t,e)=>{ma.init(t,e),q.init(t,e)});var Hd=g("ZodULID",(t,e)=>{ha.init(t,e),q.init(t,e)});var Xd=g("ZodXID",(t,e)=>{ya.init(t,e),q.init(t,e)});var ep=g("ZodKSUID",(t,e)=>{ga.init(t,e),q.init(t,e)});var tp=g("ZodIPv4",(t,e)=>{Sa.init(t,e),q.init(t,e)});var np=g("ZodIPv6",(t,e)=>{Aa.init(t,e),q.init(t,e)});var rp=g("ZodCIDRv4",(t,e)=>{Ea.init(t,e),q.init(t,e)});var op=g("ZodCIDRv6",(t,e)=>{va.init(t,e),q.init(t,e)});var sp=g("ZodBase64",(t,e)=>{Da.init(t,e),q.init(t,e)});var ip=g("ZodBase64URL",(t,e)=>{Ra.init(t,e),q.init(t,e)});var ap=g("ZodE164",(t,e)=>{Oa.init(t,e),q.init(t,e)});var cp=g("ZodJWT",(t,e)=>{Ia.init(t,e),q.init(t,e)});var $u=g("ZodNumber",(t,e)=>{vo.init(t,e),G.init(t,e),t._zod.processJSONSchema=(r,o,s)=>Zc(t,r,o,s),pn(t,"ZodNumber",{gt(r,o){return this.check(er(r,o))},gte(r,o){return this.check(fn(r,o))},min(r,o){return this.check(fn(r,o))},lt(r,o){return this.check(Xn(r,o))},lte(r,o){return this.check(ln(r,o))},max(r,o){return this.check(ln(r,o))},int(r){return this.check(ku(r))},safe(r){return this.check(ku(r))},positive(r){return this.check(er(0,r))},nonnegative(r){return this.check(fn(0,r))},negative(r){return this.check(Xn(0,r))},nonpositive(r){return this.check(ln(0,r))},multipleOf(r,o){return this.check(tr(r,o))},step(r,o){return this.check(tr(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 j(t){return Oc($u,t)}var up=g("ZodNumberFormat",(t,e)=>{Ca.init(t,e),$u.init(t,e)});function ku(t){return Ic(up,t)}var lp=g("ZodBoolean",(t,e)=>{Na.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>jc(t,n,r,o)});function nt(t){return Cc(lp,t)}var fp=g("ZodNull",(t,e)=>{$a.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Bc(t,n,r,o)});function dp(t){return Nc(fp,t)}var pp=g("ZodUnknown",(t,e)=>{Ta.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Qc(t,n,r,o)});function Du(){return $c(pp)}var mp=g("ZodNever",(t,e)=>{za.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Uc(t,n,r,o)});function Tu(t){return Tc(mp,t)}var hp=g("ZodArray",(t,e)=>{Pa.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Kc(t,n,r,o),t.element=e.element,pn(t,"ZodArray",{min(n,r){return this.check(Dt(n,r))},nonempty(n){return this.check(Dt(1,n))},max(n,r){return this.check(nr(n,r))},length(n,r){return this.check(rr(n,r))},unwrap(){return this.element}})});function V(t,e){return zc(hp,t,e)}var zu=g("ZodObject",(t,e)=>{Fa.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Wc(t,n,r,o),L.defineLazy(t,"shape",()=>e.shape),pn(t,"ZodObject",{keyof(){return le(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Du()})},loose(){return this.clone({...this._zod.def,catchall:Du()})},strict(){return this.clone({...this._zod.def,catchall:Tu()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return L.extend(this,n)},safeExtend(n){return L.safeExtend(this,n)},merge(n){return L.merge(this,n)},pick(n){return L.pick(this,n)},omit(n){return L.omit(this,n)},partial(...n){return L.partial(Lu,this,n[0])},required(...n){return L.required(Mu,this,n[0])}})});function ye(t,e){let n={type:"object",shape:t??{},...L.normalizeParams(e)};return new zu(n)}function C(t,e){return new zu({type:"object",shape:t,catchall:Tu(),...L.normalizeParams(e)})}var Pu=g("ZodUnion",(t,e)=>{ko.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Yc(t,n,r,o),t.options=e.options});function ir(t,e){return new Pu({type:"union",options:t,...L.normalizeParams(e)})}var yp=g("ZodDiscriminatedUnion",(t,e)=>{Pu.init(t,e),Za.init(t,e)});function Rt(t,e,n){return new yp({type:"union",options:e,discriminator:t,...L.normalizeParams(n)})}var gp=g("ZodIntersection",(t,e)=>{ja.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Hc(t,n,r,o)});function bp(t,e){return new gp({type:"intersection",left:t,right:e})}var Ru=g("ZodRecord",(t,e)=>{Ba.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Xc(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType});function _e(t,e,n){return!e||!e._zod?new Ru({type:"record",keyType:v(),valueType:t,...L.normalizeParams(e)}):new Ru({type:"record",keyType:t,valueType:e,...L.normalizeParams(n)})}var Go=g("ZodEnum",(t,e)=>{Ua.init(t,e),G.init(t,e),t._zod.processJSONSchema=(r,o,s)=>Gc(t,r,o,s),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Go({...e,checks:[],...L.normalizeParams(o),entries:s})},t.exclude=(r,o)=>{let s={...e.entries};for(let i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Go({...e,checks:[],...L.normalizeParams(o),entries:s})}});function le(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new Go({type:"enum",entries:n,...L.normalizeParams(e)})}var wp=g("ZodLiteral",(t,e)=>{Qa.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Vc(t,n,r,o),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function F(t,e){return new wp({type:"literal",values:Array.isArray(t)?t:[t],...L.normalizeParams(e)})}var _p=g("ZodTransform",(t,e)=>{Ga.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Jc(t,n,r,o),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new St(t.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(L.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(L.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 xp(t){return new _p({type:"transform",transform:t})}var Lu=g("ZodOptional",(t,e)=>{Do.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Qo(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Ou(t){return new Lu({type:"optional",innerType:t})}var Sp=g("ZodExactOptional",(t,e)=>{Va.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Qo(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Ap(t){return new Sp({type:"optional",innerType:t})}var Ep=g("ZodNullable",(t,e)=>{qa.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>eu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Iu(t){return new Ep({type:"nullable",innerType:t})}var vp=g("ZodDefault",(t,e)=>{Ja.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>nu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function kp(t,e){return new vp({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():L.shallowClone(e)}})}var Dp=g("ZodPrefault",(t,e)=>{Ka.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ru(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Rp(t,e){return new Dp({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():L.shallowClone(e)}})}var Mu=g("ZodNonOptional",(t,e)=>{Wa.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>tu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Op(t,e){return new Mu({type:"nonoptional",innerType:t,...L.normalizeParams(e)})}var Ip=g("ZodCatch",(t,e)=>{Ya.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ou(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Cp(t,e){return new Ip({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Np=g("ZodPipe",(t,e)=>{Ha.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>su(t,n,r,o),t.in=e.in,t.out=e.out});function Cu(t,e){return new Np({type:"pipe",in:t,out:e})}var $p=g("ZodReadonly",(t,e)=>{Xa.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>iu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Tp(t){return new $p({type:"readonly",innerType:t})}var zp=g("ZodLazy",(t,e)=>{ec.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>au(t,n,r,o),t.unwrap=()=>t._zod.def.getter()});function Vo(t){return new zp({type:"lazy",getter:t})}var Pp=g("ZodCustom",(t,e)=>{tc.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>qc(t,n,r,o)});function Lp(t,e={}){return Pc(Pp,t,e)}function Mp(t,e){return Lc(t,e)}function rt(t){let e=Vo(()=>ir([v(t),j(),nt(),dp(),V(e),_e(v(),e)]));return e}var Fu=t=>"field"in t?[t]:("all"in t?t.all:t.any).flatMap(Fu),mn=t=>Fu(t);var Ot=(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=Ot(o,e);if(s===!1)return!1;r||=s===void 0}return r?void 0:!0}for(let o of n){let s=Ot(o,e);if(s===!0)return!0;r||=s===void 0}return r?void 0:!1},Zu=t=>JSON.stringify(t),qo=t=>{if("field"in t)return{conditions:1,depth:0};let e="all"in t?t.all:t.any,n=0,r=1;for(let o of e){let s=qo(o);n+=s.conditions,r=Math.max(r,s.depth+1)}return{conditions:n,depth:r}},ju=(t,e={})=>{let n=o=>{let s=V(o),i=e.maximumChildren===void 0?s:s.max(e.maximumChildren);return ir([t,C({all:i}),C({any:i})])},r=Vo(()=>n(r));return e.maximumConditions===void 0&&e.maximumDepth===void 0?r:r.superRefine((o,s)=>{let{conditions:i,depth:a}=qo(o);e.maximumConditions!==void 0&&i>e.maximumConditions&&s.addIssue({code:"custom",message:e.maximumConditionsMessage??"Query exceeds the condition limit"}),e.maximumDepth!==void 0&&a>e.maximumDepth&&s.addIssue({code:"custom",message:e.maximumDepthMessage??"Query exceeds the nesting limit"})})};var R={requestBytes:524288,filterCount:32,filterDepth:8,sortCount:8,outputFieldCount:256,fieldPathDepth:9,defaultResultCount:20,resultCount:1e3,resultBytes:16777216,candidateDocuments:1e3,databaseBytes:512e3,frontmatterBytes:65536,frontmatterDepth:8,frontmatterFields:256,frontmatterStringBytes:16384,jsonBytes:1048576,jsonDepth:8,jsonFields:256,jsonStringBytes:16384,indexedPropertiesBytes:65536,excerptBytes:2048,hydratedFileBytes:1048576,hydratedTotalBytes:2097152,hydratedFileCount:20,hydratedRangeBytes:262144,concurrentContentReads:8};function gt(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=gt(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=>gt(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(`${gt(o)}:${gt(t[o],e)}`);n=`{${r.join(",")}}`}return e.delete(t),n}var Fp=new TextEncoder,It=t=>Fp.encode(t),Ne=t=>It(t).byteLength,re=class extends Error{constructor(){super("Byte stream exceeds the configured limit"),this.name="ByteLimitExceededError"}},Zp=(t,e)=>{let n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.byteLength;return n},Ct=t=>typeof t=="string"?{async*[Symbol.asyncIterator](){yield It(t)}}:t instanceof Uint8Array?{async*[Symbol.asyncIterator](){yield t}}:t,Jo=async(t,e)=>{let n=[],r=0;for await(let o of Ct(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 Zp(n,r)},$e=async(t,e)=>{let n=await Jo(t,e+1);if(n.byteLength>e)throw new re;return n},fe=t=>new TextDecoder("utf-8",{fatal:!0}).decode(t),Nt=t=>t.charCodeAt(0)===65279?t.slice(1):t;var Bu=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")}},Ko=(t,e)=>{if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return Bu(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(Ko(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))Bu(o),s!==void 0&&Object.defineProperty(r,o,{value:Ko(s,e),enumerable:!0,configurable:!0,writable:!0})}finally{e.delete(t)}return r}throw new Error("Value cannot be represented as JSON")},ot=t=>Ko(t,new Set),de=t=>{let e=gt(ot(t));if(e===void 0)throw new Error("Value cannot be represented as canonical JSON");return e},hn=(t,e)=>t===void 0||e===void 0?t===e:de(t)===de(e),Te=(t,e)=>t<e?-1:t>e?1:0,Wo=async t=>{let e=typeof t=="string"?It(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("")},Uu=async t=>`sha256:${await Wo(t)}`;var Qu=Rt("type",[C({type:F("document")}),C({type:F("json"),path:V(v()).min(1)}),C({type:F("markdown-body")}),C({type:F("markdown-frontmatter")})]),Yo=C({documentId:v().min(1),revision:v().min(1),representation:Qu}),jp=t=>{let e=Qu.parse(t);return e.type==="json"?Object.freeze({...e,path:Object.freeze([...e.path])}):Object.freeze(e)},Gu=t=>{let e=Yo.parse(t);return Object.freeze({...e,representation:jp(e.representation)})};var ar=C({id:v().min(1),revision:v().min(1),contentRef:v().min(1),format:le(["json","markdown"]).optional()}),cr=C({sourceId:v().min(1),referenceId:v().min(1),reference:Yo});var $t=t=>{let e=new Map;for(let n of t){let r=e.get(n.sourceId)??[];r.push(n),e.set(n.sourceId,r)}return e};var ze=class extends Error{code;documentIds;constructor({code:e,message:n,documentIds:r=[]}){super(n),this.name="DocumentGraphError",this.code=e,this.documentIds=Object.freeze([...r])}},Bp=(t,e)=>Te(t.sourceId,e.sourceId)||Te(t.referenceId,e.referenceId),yn=({nodes:t,edges:e})=>{let n=t.map(a=>Object.freeze(ar.parse(a))).sort((a,c)=>Te(a.id,c.id)),r=new Map,o=new Map;for(let a of n){if(r.has(a.id))throw new ze({code:"DUPLICATE_NODE",message:`Document graph contains duplicate node ${a.id}`,documentIds:[a.id]});r.set(a.id,a);let c=o.get(a.contentRef);if(c!==void 0&&(c.revision!==a.revision||c.format!==a.format))throw new ze({code:"CONTENT_IDENTITY_CONFLICT",message:`Document graph content reference ${a.contentRef} has conflicting identities`,documentIds:[c.id,a.id]});o.set(a.contentRef,a)}let s=e.map(a=>{let c=cr.parse(a);return Object.freeze({...c,reference:Gu(c.reference)})}).sort(Bp),i=new Set;for(let a of s){if(r.get(a.sourceId)===void 0)throw new ze({code:"SOURCE_NOT_FOUND",message:`Document graph source ${a.sourceId} does not exist`,documentIds:[a.sourceId]});let u=r.get(a.reference.documentId);if(u===void 0)throw new ze({code:"TARGET_NOT_FOUND",message:`Document graph target ${a.reference.documentId} does not exist`,documentIds:[a.sourceId,a.reference.documentId]});if(u.revision!==a.reference.revision)throw new ze({code:"TARGET_REVISION_MISMATCH",message:`Document graph target ${u.id} revision does not match its reference`,documentIds:[a.sourceId,u.id]});let d=`${a.sourceId}\0${a.referenceId}`;if(i.has(d))throw new ze({code:"DUPLICATE_REFERENCE",message:`Document ${a.sourceId} contains duplicate reference ID ${a.referenceId}`,documentIds:[a.sourceId]});i.add(d)}return Object.freeze({nodes:Object.freeze(n),edges:Object.freeze(s)})},Up=t=>new Map(t.nodes.map(e=>[e.id,e]));var ur=({graph:t,rootIds:e})=>{let n=Up(t),r=$t(t.edges),o=new Map,s=[],i=[],a=c=>{let u=n.get(c);if(u===void 0)throw new ze({code:"ROOT_NOT_FOUND",message:`Document graph root ${c} does not exist`,documentIds:[c]});let d=o.get(c);if(d!=="visited"){if(d==="visiting"){let l=s.indexOf(c),f=[...s.slice(l),c];throw new ze({code:"CYCLE",message:`Document graph contains a cycle: ${f.join(" -> ")}`,documentIds:f})}o.set(c,"visiting"),s.push(c);for(let l of r.get(c)??[])a(l.reference.documentId);s.pop(),o.set(c,"visited"),i.push(u)}};for(let c of[...new Set(e)].sort(Te))a(c);return Object.freeze(i)};var Qp=v().regex(/^sha256:[a-f0-9]{64}$/),Vu=C({format:F("webstudio-document-graph"),version:F(1),nodes:V(ar),edges:V(cr),integrity:C({algorithm:F("sha256"),checksum:Qp})});var Gp=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"}),Ku=C({_id:v().min(1),_type:F("asset.file"),name:v().min(1),description:v().optional(),path:Gp,key:v(),folderId:v().min(1).optional(),extension:v().regex(/^[a-z0-9]*$/),mimeType:v().min(1),size:j().int().nonnegative(),createdAt:v().datetime().optional(),revision:v().min(1),contentRef:v().min(1),properties:_e(v(),rt()),excerpt:v().optional(),metadataError:C({code:v().min(1),message:v().min(1)}).optional()}),Xo=Ku.partial().required({_id:!0}),Vp=le(["null","boolean","number","string","object","array"]),qp=ye({format:F("webstudio-builder-asset-field-catalog"),version:F(1),canonicalRevision:v().regex(/^sha256:[a-f0-9]{64}$/),documentCount:j().int().nonnegative(),fields:_e(v().min(1),ye({queryPath:V(v().min(1)).min(1).max(R.fieldPathDepth).optional(),types:V(Vp).min(1),occurrences:j().int().positive(),optional:F(!0).optional(),mixed:F(!0).optional()}))}).superRefine((t,e)=>{for(let[n,r]of Object.entries(t.fields)){let o=[...new Set(r.types)].sort();JSON.stringify(r.types)!==JSON.stringify(o)&&e.addIssue({code:"custom",path:["fields",n,"types"],message:"Observed field types must be unique and sorted"}),r.occurrences>t.documentCount&&e.addIssue({code:"custom",path:["fields",n,"occurrences"],message:"Field occurrences cannot exceed the document count"});let s=r.occurrences<t.documentCount;r.optional===!0!==s&&e.addIssue({code:"custom",path:["fields",n,"optional"],message:"Field optionality must match its occurrence count"});let i=o.length>1;r.mixed===!0!==i&&e.addIssue({code:"custom",path:["fields",n,"mixed"],message:"Mixed status must match the observed types"})}}),lr=v().regex(/^sha256:[a-f0-9]{64}$/),Wu=C({fields:V(V(v().min(1)).min(1).max(R.fieldPathDepth)).min(1).max(R.outputFieldCount+1),rows:V(V(rt())).max(R.resultCount),totalCount:j().int().nonnegative().max(R.candidateDocuments),hasMore:nt()}).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"})}),qu=C({format:F("webstudio-content-database"),version:F(1),assetRevision:lr,documents:V(Xo),documentGraph:Vu.optional(),contents:_e(v().min(1),v()).optional(),assetReferences:_e(v().min(1),V(C({start:j().int().nonnegative(),end:j().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:_e(v().min(1),V(C({path:V(v().min(1).or(j().int().nonnegative())).min(1),assetId:v().min(1),suffix:v().min(1).optional()}))).optional(),fieldCatalog:qp,queries:_e(lr,Wu).optional(),database:C({maxBytes:j().int().positive(),unboundedBytes:j().int().nonnegative(),sourceDocumentCount:j().int().nonnegative(),includedDocumentCount:j().int().nonnegative().optional()}).optional(),integrity:C({algorithm:F("sha256"),checksum:lr})}).superRefine((t,e)=>{t.documents.length>R.candidateDocuments&&e.addIssue({code:"custom",path:["documents"],message:"Asset index exceeds the document limit"}),(t.fieldCatalog.canonicalRevision!==t.assetRevision||t.fieldCatalog.documentCount!==t.documents.length)&&e.addIssue({code:"custom",path:["fieldCatalog"],message:"Asset index field catalog does not match its documents"}),t.database!==void 0&&t.database.sourceDocumentCount<t.documents.length&&e.addIssue({code:"custom",path:["database","sourceDocumentCount"],message:"Source document count cannot be smaller than the database"}),t.database?.includedDocumentCount!==void 0&&(t.database.includedDocumentCount<t.documents.length||t.database.includedDocumentCount>t.database.sourceDocumentCount)&&e.addIssue({code:"custom",path:["database","includedDocumentCount"],message:"Included document count must match the database bounds"});let n;for(let[o,s]of t.documents.entries())n!==void 0&&s._id<=n&&e.addIssue({code:"custom",path:["documents",o,"_id"],message:"Asset index documents must have unique sorted IDs"}),n=s._id;let r=new Set(t.documents.flatMap(({contentRef:o})=>o===void 0?[]:[o]));for(let o of Object.keys(t.contents??{}))r.has(o)===!1&&e.addIssue({code:"custom",path:["contents",o],message:"Embedded content must belong to an indexed document"});for(let o of Object.keys(t.assetReferences??{}))r.has(o)===!1&&e.addIssue({code:"custom",path:["assetReferences",o],message:"Asset references must belong to an indexed document"})}),Jp=Rt("mode",[ye({mode:F("none")}),ye({mode:F("full"),maxBytes:j().int().positive().max(R.hydratedFileBytes).optional()}),ye({mode:F("range"),offset:j().int().nonnegative(),length:j().int().positive().max(R.hydratedRangeBytes)}),ye({mode:F("markdown-body-ref"),maxBytes:j().int().positive().max(R.hydratedFileBytes).optional()})]),es={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"]},Yu=Object.keys(es),Hu=["url","width","height"],fr=t=>Hu.includes(t),Xu=Yu.filter(t=>fr(t)===!1&&t!=="excerpt"),el=Xu.filter(t=>t!=="id"),tl=t=>Xu.includes(t),Kp=le(Yu),gn=V(v().min(1)).min(1).max(R.fieldPathDepth).superRefine((t,e)=>{if(t[0]==="properties"){t.length<2&&e.addIssue({code:"custom",message:"A properties field path must select a property"});return}(t.length!==1||Kp.safeParse(t[0]).success===!1)&&e.addIssue({code:"custom",message:"Asset query field path is unsupported"})}),Ho=nt().default(!0),Wp=Rt("mode",[C({mode:F("all"),includeMetadata:Ho}),C({mode:F("base"),includeMetadata:Ho}),C({mode:F("fields"),includeMetadata:Ho,fields:V(gn).max(R.outputFieldCount).refine(t=>new Set(t.map(Zu)).size===t.length,{error:"Selected output fields must be unique"})})]),Yp={mode:"fields",includeMetadata:!1,fields:Hu.map(t=>[t])},nl=["eq","ne","contains","startsWith","endsWith","gt","gte","lt","lte"],yb=[...nl,"in","exists","isEmpty"],Hp=C({field:gn,operator:le(nl),value:rt()}),Xp=C({field:gn,operator:F("in"),value:V(rt()).max(R.resultCount)}),em=C({field:gn,operator:le(["exists","isEmpty"]),value:nt()}),tm=Rt("operator",[Hp,Xp,em]),nm=ju(tm,{maximumChildren:R.filterCount,maximumConditions:R.filterCount,maximumDepth:R.filterDepth,maximumConditionsMessage:"Asset query exceeds the filter limit",maximumDepthMessage:"Asset query exceeds the filter nesting limit"});var rm=nm,rl=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]},om=C({field:gn,direction:le(["asc","desc"])}),sm=({output:t,content:e})=>t.includeMetadata||t.mode==="all"||t.mode==="fields"&&t.fields.length>0||e.mode!=="none",st=C({where:rm.default({all:[]}),sort:V(om).max(R.sortCount).default([]),limit:j().int().nonnegative().max(R.resultCount).default(R.defaultResultCount),offset:j().int().nonnegative().max(R.candidateDocuments).default(0),output:Wp.default(Yp),content:Jp.default({mode:"none"})}).refine(sm,{error:"Select at least one asset query output"}),ol=C({query:st,indexRevision:v().min(1).max(255).optional()}),im=ye({_id:v().min(1),revision:v().min(1),contentRef:v().min(1),encoding:F("utf-8"),text:v(),range:ye({offset:j().int().nonnegative(),length:j().int().nonnegative(),total:j().int().nonnegative()}).optional()}),am=im.omit({_id:!0,revision:!0,contentRef:!0}),cm=Ku.omit({_id:!0,_type:!0,contentRef:!0}).partial().extend({id:v().min(1),url:v().min(1).optional(),width:j().positive().optional(),height:j().positive().optional(),content:am.optional()}).refine(t=>t.width===void 0==(t.height===void 0),{error:"Asset dimensions must include both width and height"}),um=C({format:F("webstudio-content-database"),version:F(1),revision:lr,usedBytes:j().int().nonnegative(),maxBytes:j().int().positive(),unboundedBytes:j().int().nonnegative(),includedDocumentCount:j().int().nonnegative(),omittedDocumentCount:j().int().nonnegative(),omissionReason:le(["size","unavailable"]).optional(),truncated:nt()}),Ju=um.pick({usedBytes:!0,maxBytes:!0,unboundedBytes:!0,includedDocumentCount:!0,omittedDocumentCount:!0,omissionReason:!0,truncated:!0}),dr=C({items:V(cm),totalCount:j().int().nonnegative(),hasMore:nt()}),lm=C({scope:F("query-preview"),query:Ju,database:Ju,artifacts:C({query:qu,database:qu}).optional(),unresolved:dr.optional()}),gb=C({data:dr,__diagnostics__:lm}),fm=le(["INVALID_REQUEST","REQUEST_CANCELLED","UNAUTHORIZED","FORBIDDEN","STALE_INDEX","CONTENT_IDENTITY_REQUIRED","CONTENT_NOT_TEXT","CONTENT_DECODING_FAILED","CONTENT_LIMIT_EXCEEDED","INTERNAL_ERROR"]),dm=ye({ok:F(!1),error:ye({code:fm,message:v().min(1),retryable:nt(),details:_e(v(),rt()).optional()}),meta:ye({queryHash:v().min(1).optional(),indexRevision:v().min(1).optional(),assetRevision:v().min(1).optional()}).optional()}),sl=({code:t,message:e,retryable:n=!1,details:r})=>dm.parse({ok:!1,error:{code:t,message:e,retryable:n,details:r}});var il=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 mm(o)}};var ts=(t,e)=>e+"/"+pm(t),pm=t=>t.toString().replace(/~/g,"~0").replace(/\//g,"~1"),mm=t=>t.toString().replace(/~1/g,"/").replace(/~0/g,"~");var pr=async(t,e,n)=>{if(Number.isSafeInteger(e)===!1||e<=0)throw new Error("Concurrency must be a positive safe integer");let r=0,o=new Array(t.length),s=async()=>{for(;r<t.length;){let u=r;r+=1,o[u]=await n(t[u])}},i=Array.from({length:Math.min(e,t.length)},s),c=(await Promise.allSettled(i)).find(u=>u.status==="rejected");if(c!==void 0)throw c.reason;return o};var Tt=t=>typeof t=="object"&&t!==null&&Array.isArray(t)===!1,al=t=>{if(Tt(t)===!1)return;let e=Object.keys(t);if(!(e.length!==1||e[0]!=="$ref"))return t.$ref};var pe=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}},hm=(t,e)=>{let n=al(t);if(n!==void 0){if(typeof n!="string")throw new pe({code:"INVALID_REFERENCE_MARKER",message:`JSON reference marker ${e} must contain a string $ref`,referenceId:e});return n}},ym=t=>`#${t}`;var cl=async({source:t,maximumBytes:e=R.hydratedFileBytes})=>{let n;try{n=await $e(t,e)}catch(o){throw o instanceof re?new pe({code:"CONTENT_LIMIT_EXCEEDED",message:"JSON document exceeds the byte limit",cause:o}):o}let r;try{r=Nt(fe(n))}catch(o){throw new pe({code:"CONTENT_DECODING_FAILED",message:"JSON document is not valid UTF-8",cause:o})}try{return ot(JSON.parse(r))}catch(o){throw new pe({code:"INVALID_DOCUMENT",message:"JSON document is invalid",cause:o})}};var gm=(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(Tt(n)&&Object.hasOwn(n,r)){n=n[r];continue}return}return n},ul=({document:t,representation:e})=>{let n=ot(t);if(e.type==="document")return n;if(e.type!=="json")throw new pe({code:"UNSUPPORTED_REPRESENTATION",message:`JSON documents do not support ${e.type}`});let r=gm(n,e.path);if(r===void 0)throw new pe({code:"JSON_PATH_NOT_FOUND",message:"JSON document path does not exist"});return r},bm=(t,e,n)=>{Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0})},mr=({document:t,references:e,allowUnresolvedReferences:n=!1})=>{let r=ot(t),o=new Set,s=(a,c)=>{let u=ym(c);if(hm(a,u)!==void 0){if(e.has(u)===!1){if(n)return a;throw new pe({code:"REFERENCE_NOT_FOUND",message:`Resolved JSON reference ${u} is unavailable`,referenceId:u})}o.add(u);try{return ot(e.get(u))}catch(l){throw new pe({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,ts(String(f),c)));if(Tt(a)){let l={};for(let[f,p]of Object.entries(a))bm(l,f,s(p,ts(f,c)));return l}return a},i=s(r,"");for(let a of[...e.keys()].sort())if(o.has(a)===!1)throw new pe({code:"UNUSED_REFERENCE",message:`Resolved JSON reference ${a} has no marker`,referenceId:a});return i};var hr=Symbol.for("yaml.alias"),yr=Symbol.for("yaml.document"),xe=Symbol.for("yaml.map"),ns=Symbol.for("yaml.pair"),me=Symbol.for("yaml.scalar"),qe=Symbol.for("yaml.seq"),oe=Symbol.for("yaml.node.type"),Se=t=>!!t&&typeof t=="object"&&t[oe]===hr,Pe=t=>!!t&&typeof t=="object"&&t[oe]===yr,Ae=t=>!!t&&typeof t=="object"&&t[oe]===xe,T=t=>!!t&&typeof t=="object"&&t[oe]===ns,N=t=>!!t&&typeof t=="object"&&t[oe]===me,Ee=t=>!!t&&typeof t=="object"&&t[oe]===qe;function Z(t){if(t&&typeof t=="object")switch(t[oe]){case xe:case qe:return!0}return!1}function P(t){if(t&&typeof t=="object")switch(t[oe]){case hr:case xe:case me:case qe:return!0}return!1}var gr=t=>(N(t)||Z(t))&&!!t.anchor;var ce=Symbol("break visit"),ll=Symbol("skip children"),Le=Symbol("remove node");function Me(t,e){let n=fl(e);Pe(t)?zt(null,t.contents,n,Object.freeze([t]))===Le&&(t.contents=null):zt(null,t,n,Object.freeze([]))}Me.BREAK=ce;Me.SKIP=ll;Me.REMOVE=Le;function zt(t,e,n,r){let o=dl(t,e,n,r);if(P(o)||T(o))return pl(t,r,o),zt(t,o,n,r);if(typeof o!="symbol"){if(Z(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===Le&&(e.items.splice(s,1),s-=1)}}}else if(T(e)){r=Object.freeze(r.concat(e));let s=zt("key",e.key,n,r);if(s===ce)return ce;s===Le&&(e.key=null);let i=zt("value",e.value,n,r);if(i===ce)return ce;i===Le&&(e.value=null)}}return o}async function br(t,e){let n=fl(e);Pe(t)?await Pt(null,t.contents,n,Object.freeze([t]))===Le&&(t.contents=null):await Pt(null,t,n,Object.freeze([]))}br.BREAK=ce;br.SKIP=ll;br.REMOVE=Le;async function Pt(t,e,n,r){let o=await dl(t,e,n,r);if(P(o)||T(o))return pl(t,r,o),Pt(t,o,n,r);if(typeof o!="symbol"){if(Z(e)){r=Object.freeze(r.concat(e));for(let s=0;s<e.items.length;++s){let i=await Pt(s,e.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===ce)return ce;i===Le&&(e.items.splice(s,1),s-=1)}}}else if(T(e)){r=Object.freeze(r.concat(e));let s=await Pt("key",e.key,n,r);if(s===ce)return ce;s===Le&&(e.key=null);let i=await Pt("value",e.value,n,r);if(i===ce)return ce;i===Le&&(e.value=null)}}return o}function fl(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 dl(t,e,n,r){if(typeof n=="function")return n(t,e,r);if(Ae(e))return n.Map?.(t,e,r);if(Ee(e))return n.Seq?.(t,e,r);if(T(e))return n.Pair?.(t,e,r);if(N(e))return n.Scalar?.(t,e,r);if(Se(e))return n.Alias?.(t,e,r)}function pl(t,e,n){let r=e[e.length-1];if(Z(r))r.items[t]=n;else if(T(r))t==="key"?r.key=n:r.value=n;else if(Pe(r))r.contents=n;else{let o=Se(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}var wm={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},_m=t=>t.replace(/[!,[\]{}]/g,e=>wm[e]),Fe=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let r=e.trim().split(/[ \t]+/),o=r.shift();switch(o){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[s,i]=r;return this.tags[s]=i,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=r;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let i=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,i),!1}}default:return n(0,`Unknown directive ${o}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let i=e.slice(2,-1);return i==="!"||i==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),i)}let[,r,o]=e.match(/^(.*!)([^!]*)$/s);o||n(`The ${e} tag has no suffix`);let s=this.tags[r];if(s)try{return s+decodeURIComponent(o)}catch(i){return n(String(i)),null}return r==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,r]of Object.entries(this.tags))if(e.startsWith(r))return n+_m(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&&P(e.contents)){let s={};Me(e.contents,(i,a)=>{P(a)&&a.tag&&(s[a.tag]=!0)}),o=Object.keys(s)}else o=[];for(let[s,i]of r)s==="!!"&&i==="tag:yaml.org,2002:"||(!e||o.some(a=>a.startsWith(i)))&&n.push(`%TAG ${s} ${i}`);return n.join(`
-`)}};Fe.defaultYaml={explicit:!1,version:"1.2"};Fe.defaultTags={"!!":"tag:yaml.org,2002:"};function wr(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 rs(t){let e=new Set;return Me(t,{Value(n,r){r.anchor&&e.add(r.anchor)}}),e}function os(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=rs(t));let i=os(e,o);return o.add(i),i},setAnchors:()=>{for(let s of n){let i=r.get(s);if(typeof i=="object"&&i.anchor&&(N(i.node)||Z(i.node)))i.node.anchor=i.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:r}}function it(t,e,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let o=0,s=r.length;o<s;++o){let i=r[o],a=it(t,r,String(o),i);a===void 0?delete r[o]:a!==i&&(r[o]=a)}else if(r instanceof Map)for(let o of Array.from(r.keys())){let s=r.get(o),i=it(t,r,o,s);i===void 0?r.delete(o):i!==s&&r.set(o,i)}else if(r instanceof Set)for(let o of Array.from(r)){let s=it(t,r,o,o);s===void 0?r.delete(o):s!==o&&(r.delete(o),r.add(s))}else for(let[o,s]of Object.entries(r)){let i=it(t,r,o,s);i===void 0?delete r[o]:i!==s&&(r[o]=i)}return t.call(e,n,r)}function Y(t,e,n){if(Array.isArray(t))return t.map((r,o)=>Y(r,String(o),n));if(t&&typeof t.toJSON=="function"){if(!n||!gr(t))return t.toJSON(e,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(t,r),n.onCreate=s=>{r.res=s,delete n.onCreate};let o=t.toJSON(e,n);return n.onCreate&&n.onCreate(o),o}return typeof t=="bigint"&&!n?.keep?Number(t):t}var at=class{constructor(e){Object.defineProperty(this,oe,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:r,onAnchor:o,reviver:s}={}){if(!Pe(e))throw new TypeError("A document argument is required");let i={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=Y(this,"",i);if(typeof o=="function")for(let{count:c,res:u}of i.anchors.values())o(u,c);return typeof s=="function"?it(s,{"":a},"",a):a}};var Je=class extends at{constructor(e){super(hr),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],Me(e,{Node:(s,i)=>{(Se(i)||gr(i))&&r.push(i)}}),n&&(n.aliasResolveCache=r));let o;for(let s of r){if(s===this)break;s.anchor===this.source&&(o=s)}return o}toJSON(e,n){if(!n)return{source:this.source};let{anchors:r,doc:o,maxAliasCount:s}=n,i=this.resolve(o,n);if(!i){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=r.get(i);if(a||(Y(i,null,n),a=r.get(i)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=_r(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(wr(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 _r(t,e,n){if(Se(e)){let r=e.resolve(t),o=n&&r&&n.get(r);return o?o.count*o.aliasCount:0}else if(Z(e)){let r=0;for(let o of e.items){let s=_r(t,o,n);s>r&&(r=s)}return r}else if(T(e)){let r=_r(t,e.key,n),o=_r(t,e.value,n);return Math.max(r,o)}return 1}var xr=t=>!t||typeof t!="function"&&typeof t!="object",D=class extends at{constructor(e){super(me),this.value=e}toJSON(e,n){return n?.keep?this.value:Y(this.value,e,n)}toString(){return String(this.value)}};D.BLOCK_FOLDED="BLOCK_FOLDED";D.BLOCK_LITERAL="BLOCK_LITERAL";D.PLAIN="PLAIN";D.QUOTE_DOUBLE="QUOTE_DOUBLE";D.QUOTE_SINGLE="QUOTE_SINGLE";var xm="tag:yaml.org,2002:";function Sm(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 Ke(t,e,n){if(Pe(t)&&(t=t.contents),P(t))return t;if(T(t)){let l=n.schema[xe].createNode?.(n.schema,null,n);return l.items.push(t),l}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:r,onAnchor:o,onTagObj:s,schema:i,sourceObjects:a}=n,c;if(r&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=o(t)),new Je(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=xm+e.slice(2));let u=Sm(t,e,i.tags);if(!u){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let l=new D(t);return c&&(c.node=l),l}u=t instanceof Map?i[xe]:Symbol.iterator in Object(t)?i[qe]:i[xe]}s&&(s(u),delete n.onTagObj);let d=u?.createNode?u.createNode(n.schema,t,n):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(n.schema,t,n):new D(t);return e?d.tag=e:u.default||(d.tag=u.tag),c&&(c.node=d),d}function bn(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 Ke(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 Mt=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Lt=class extends at{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(r=>P(r)||T(r)?r.clone(e):r),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(Mt(e))this.add(n);else{let[r,...o]=e,s=this.get(r,!0);if(Z(s))s.addIn(o,n);else if(s===void 0&&this.schema)this.set(r,bn(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(Z(o))return o.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(e,n){let[r,...o]=e,s=this.get(r,!0);return o.length===0?!n&&N(s)?s.value:s:Z(s)?s.getIn(o,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!T(n))return!1;let r=n.value;return r==null||e&&N(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[n,...r]=e;if(r.length===0)return this.has(n);let o=this.get(n,!0);return Z(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(Z(s))s.setIn(o,n);else if(s===void 0&&this.schema)this.set(r,bn(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}};var hl=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function ge(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Ze=(t,e,n)=>t.endsWith(`
+Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of t.seen.entries()){let a=i[1];if(e===i[0]){s(i);continue}if(t.external){let u=t.external.registry.get(i[0])?.id;if(e!==i[0]&&u){s(i);continue}}if(t.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&t.reused==="ref"){s(i);continue}}}function Uo(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,d={...u},l=c.ref;if(c.ref=null,l){r(l);let p=t.seen.get(l),y=p.schema;if(y.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(y)):Object.assign(u,y),Object.assign(u,d),a._zod.parent===l)for(let h in u)h==="$ref"||h==="allOf"||h in d||delete u[h];if(y.$ref&&p.def)for(let h in u)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(u[h])===JSON.stringify(p.def[h])&&delete u[h]}let f=a._zod.parent;if(f&&f!==l){r(f);let p=t.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let y in u)y==="$ref"||y==="allOf"||y in p.def&&JSON.stringify(u[y])===JSON.stringify(p.def[y])&&delete u[y]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())r(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,n.def??n.schema);let s=t.metadataRegistry.get(e)?.id;s!==void 0&&o.id===s&&delete o.id;let i=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:pn(e,"input",t.processors),output:pn(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function ne(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let r=t._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return ne(r.element,n);if(r.type==="set")return ne(r.valueType,n);if(r.type==="lazy")return ne(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return ne(r.innerType,n);if(r.type==="intersection")return ne(r.left,n)||ne(r.right,n);if(r.type==="record"||r.type==="map")return ne(r.keyType,n)||ne(r.valueType,n);if(r.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:ne(r.in,n)||ne(r.out,n);if(r.type==="object"){for(let o in r.shape)if(ne(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(ne(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(ne(o,n))return!0;return!!(r.rest&&ne(r.rest,n))}return!1}var Fc=(t,e={})=>n=>{let r=jo({...n,processors:e});return J(t,r),Bo(r,t),Uo(r,t)},pn=(t,e,n={})=>r=>{let{libraryOptions:o,target:s}=r??{},i=jo({...o??{},target:s,io:e,processors:n});return J(t,i),Bo(i,t),Uo(i,t)};var $d={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Zc=(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=$d[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}))])}},jc=(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)},Bc=(t,e,n,r)=>{n.type="boolean"};var Uc=(t,e,n,r)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"};var Qc=(t,e,n,r)=>{n.not={}};var Gc=(t,e,n,r)=>{};var Vc=(t,e,n,r)=>{let o=t._zod.def,s=rn(o.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},qc=(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 Jc=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var Kc=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var Wc=(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"]})},Yc=(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)},Hc=(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},Xc=(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 eu=(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)}},tu=(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"}]},nu=(t,e,n,r)=>{let o=t._zod.def;J(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType},ru=(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))},ou=(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)))},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;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i},iu=(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},au=(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 Qo=(t,e,n,r)=>{let o=t._zod.def;J(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType},cu=(t,e,n,r)=>{let o=t._zod.innerType;J(o,e,r);let s=e.seen.get(t);s.ref=o};var Zd=g("ZodISODateTime",(t,e)=>{wa.init(t,e),q.init(t,e)});function uu(t){return kc(Zd,t)}var jd=g("ZodISODate",(t,e)=>{_a.init(t,e),q.init(t,e)});function lu(t){return Dc(jd,t)}var Bd=g("ZodISOTime",(t,e)=>{xa.init(t,e),q.init(t,e)});function fu(t){return Rc(Bd,t)}var Ud=g("ZodISODuration",(t,e)=>{Sa.init(t,e),q.init(t,e)});function du(t){return Ic(Ud,t)}var Vd=(t,e)=>{qn.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>ei(t,n)},flatten:{value:n=>Xs(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,Et,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,Et,2)}},isEmpty:{get(){return t.issues.length===0}}})};var le=g("ZodError",Vd,{Parent:Error});var pu=Jn(le),mu=Kn(le),hu=cn(le),yu=un(le),gu=ri(le),bu=oi(le),wu=si(le),_u=ii(le),xu=ai(le),Su=ci(le),Au=ui(le),Eu=li(le);var vu=new WeakMap;function mn(t,e,n){let r=Object.getPrototypeOf(t),o=vu.get(r);if(o||(o=new Set,vu.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 G=g("ZodType",(t,e)=>(U.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:pn(t,"input"),output:pn(t,"output")}}),t.toJSONSchema=Fc(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,r)=>pu(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>hu(t,n,r),t.parseAsync=async(n,r)=>mu(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>yu(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>gu(t,n,r),t.decode=(n,r)=>bu(t,n,r),t.encodeAsync=async(n,r)=>wu(t,n,r),t.decodeAsync=async(n,r)=>_u(t,n,r),t.safeEncode=(n,r)=>xu(t,n,r),t.safeDecode=(n,r)=>Su(t,n,r),t.safeEncodeAsync=async(n,r)=>Au(t,n,r),t.safeDecodeAsync=async(n,r)=>Eu(t,n,r),mn(t,"ZodType",{check(...n){let r=this.def;return this.clone(L.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 we(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Zp(n,r))},superRefine(n,r){return this.check(jp(n,r))},overwrite(n){return this.check(tt(n))},optional(){return Ou(this)},exactOptional(){return kp(this)},nullable(){return Cu(this)},nullish(){return Ou(Cu(this))},nonoptional(n){return Np(this,n)},array(){return V(this)},or(n){return Rt([this,n])},and(n){return xp(this,n)},transform(n){return Nu(this,Ep(n))},default(n){return Ip(this,n)},prefault(n){return Cp(this,n)},catch(n){return Tp(this,n)},pipe(n){return Nu(this,n)},readonly(){return Lp(this)},describe(n){let r=this.clone();return yt.add(r,{description:n}),r},meta(...n){if(n.length===0)return yt.get(this);let r=this.clone();return yt.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 yt.get(t)?.description},configurable:!0}),t)),$u=g("_ZodString",(t,e)=>{er.init(t,e),G.init(t,e),t._zod.processJSONSchema=(r,o,s)=>Zc(t,r,o,s);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,mn(t,"_ZodString",{regex(...r){return this.check(Oo(...r))},includes(...r){return this.check($o(...r))},startsWith(...r){return this.check(To(...r))},endsWith(...r){return this.check(zo(...r))},min(...r){return this.check(Dt(...r))},max(...r){return this.check(or(...r))},length(...r){return this.check(sr(...r))},nonempty(...r){return this.check(Dt(1,...r))},lowercase(r){return this.check(Co(r))},uppercase(r){return this.check(No(r))},trim(){return this.check(Lo())},normalize(...r){return this.check(Po(...r))},toLowerCase(){return this.check(Mo())},toUpperCase(){return this.check(Fo())},slugify(){return this.check(Zo())}})}),Jd=g("ZodString",(t,e)=>{er.init(t,e),$u.init(t,e),t.email=n=>t.check(sc(Kd,n)),t.url=n=>t.check(lc(Wd,n)),t.jwt=n=>t.check(vc(fp,n)),t.emoji=n=>t.check(fc(Yd,n)),t.guid=n=>t.check(Io(ku,n)),t.uuid=n=>t.check(ic(ar,n)),t.uuidv4=n=>t.check(ac(ar,n)),t.uuidv6=n=>t.check(cc(ar,n)),t.uuidv7=n=>t.check(uc(ar,n)),t.nanoid=n=>t.check(dc(Hd,n)),t.guid=n=>t.check(Io(ku,n)),t.cuid=n=>t.check(pc(Xd,n)),t.cuid2=n=>t.check(mc(ep,n)),t.ulid=n=>t.check(hc(tp,n)),t.base64=n=>t.check(Sc(cp,n)),t.base64url=n=>t.check(Ac(up,n)),t.xid=n=>t.check(yc(np,n)),t.ksuid=n=>t.check(gc(rp,n)),t.ipv4=n=>t.check(bc(op,n)),t.ipv6=n=>t.check(wc(sp,n)),t.cidrv4=n=>t.check(_c(ip,n)),t.cidrv6=n=>t.check(xc(ap,n)),t.e164=n=>t.check(Ec(lp,n)),t.datetime=n=>t.check(uu(n)),t.date=n=>t.check(lu(n)),t.time=n=>t.check(fu(n)),t.duration=n=>t.check(du(n))});function v(t){return oc(Jd,t)}var q=g("ZodStringFormat",(t,e)=>{Q.init(t,e),$u.init(t,e)}),Kd=g("ZodEmail",(t,e)=>{la.init(t,e),q.init(t,e)});var ku=g("ZodGUID",(t,e)=>{ca.init(t,e),q.init(t,e)});var ar=g("ZodUUID",(t,e)=>{ua.init(t,e),q.init(t,e)});var Wd=g("ZodURL",(t,e)=>{fa.init(t,e),q.init(t,e)});var Yd=g("ZodEmoji",(t,e)=>{da.init(t,e),q.init(t,e)});var Hd=g("ZodNanoID",(t,e)=>{pa.init(t,e),q.init(t,e)});var Xd=g("ZodCUID",(t,e)=>{ma.init(t,e),q.init(t,e)});var ep=g("ZodCUID2",(t,e)=>{ha.init(t,e),q.init(t,e)});var tp=g("ZodULID",(t,e)=>{ya.init(t,e),q.init(t,e)});var np=g("ZodXID",(t,e)=>{ga.init(t,e),q.init(t,e)});var rp=g("ZodKSUID",(t,e)=>{ba.init(t,e),q.init(t,e)});var op=g("ZodIPv4",(t,e)=>{Aa.init(t,e),q.init(t,e)});var sp=g("ZodIPv6",(t,e)=>{Ea.init(t,e),q.init(t,e)});var ip=g("ZodCIDRv4",(t,e)=>{va.init(t,e),q.init(t,e)});var ap=g("ZodCIDRv6",(t,e)=>{ka.init(t,e),q.init(t,e)});var cp=g("ZodBase64",(t,e)=>{Ra.init(t,e),q.init(t,e)});var up=g("ZodBase64URL",(t,e)=>{Ia.init(t,e),q.init(t,e)});var lp=g("ZodE164",(t,e)=>{Oa.init(t,e),q.init(t,e)});var fp=g("ZodJWT",(t,e)=>{Ca.init(t,e),q.init(t,e)});var Tu=g("ZodNumber",(t,e)=>{vo.init(t,e),G.init(t,e),t._zod.processJSONSchema=(r,o,s)=>jc(t,r,o,s),mn(t,"ZodNumber",{gt(r,o){return this.check(nr(r,o))},gte(r,o){return this.check(dn(r,o))},min(r,o){return this.check(dn(r,o))},lt(r,o){return this.check(tr(r,o))},lte(r,o){return this.check(fn(r,o))},max(r,o){return this.check(fn(r,o))},int(r){return this.check(Du(r))},safe(r){return this.check(Du(r))},positive(r){return this.check(nr(0,r))},nonnegative(r){return this.check(dn(0,r))},negative(r){return this.check(tr(0,r))},nonpositive(r){return this.check(fn(0,r))},multipleOf(r,o){return this.check(rr(r,o))},step(r,o){return this.check(rr(r,o))},finite(){return this}});let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function F(t){return Oc(Tu,t)}var dp=g("ZodNumberFormat",(t,e)=>{Na.init(t,e),Tu.init(t,e)});function Du(t){return Cc(dp,t)}var pp=g("ZodBoolean",(t,e)=>{$a.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Bc(t,n,r,o)});function nt(t){return Nc(pp,t)}var mp=g("ZodNull",(t,e)=>{Ta.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Uc(t,n,r,o)});function hp(t){return $c(mp,t)}var yp=g("ZodUnknown",(t,e)=>{za.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Gc(t,n,r,o)});function Ru(){return Tc(yp)}var gp=g("ZodNever",(t,e)=>{Pa.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Qc(t,n,r,o)});function zu(t){return zc(gp,t)}var bp=g("ZodArray",(t,e)=>{La.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Wc(t,n,r,o),t.element=e.element,mn(t,"ZodArray",{min(n,r){return this.check(Dt(n,r))},nonempty(n){return this.check(Dt(1,n))},max(n,r){return this.check(or(n,r))},length(n,r){return this.check(sr(n,r))},unwrap(){return this.element}})});function V(t,e){return Pc(bp,t,e)}var Pu=g("ZodObject",(t,e)=>{Za.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Yc(t,n,r,o),L.defineLazy(t,"shape",()=>e.shape),mn(t,"ZodObject",{keyof(){return ce(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Ru()})},loose(){return this.clone({...this._zod.def,catchall:Ru()})},strict(){return this.clone({...this._zod.def,catchall:zu()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return L.extend(this,n)},safeExtend(n){return L.safeExtend(this,n)},merge(n){return L.merge(this,n)},pick(n){return L.pick(this,n)},omit(n){return L.omit(this,n)},partial(...n){return L.partial(Mu,this,n[0])},required(...n){return L.required(Fu,this,n[0])}})});function ye(t,e){let n={type:"object",shape:t??{},...L.normalizeParams(e)};return new Pu(n)}function C(t,e){return new Pu({type:"object",shape:t,catchall:zu(),...L.normalizeParams(e)})}var Lu=g("ZodUnion",(t,e)=>{ko.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Hc(t,n,r,o),t.options=e.options});function Rt(t,e){return new Lu({type:"union",options:t,...L.normalizeParams(e)})}var wp=g("ZodDiscriminatedUnion",(t,e)=>{Lu.init(t,e),ja.init(t,e)});function It(t,e,n){return new wp({type:"union",options:e,discriminator:t,...L.normalizeParams(n)})}var _p=g("ZodIntersection",(t,e)=>{Ba.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Xc(t,n,r,o)});function xp(t,e){return new _p({type:"intersection",left:t,right:e})}var Iu=g("ZodRecord",(t,e)=>{Ua.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>eu(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType});function _e(t,e,n){return!e||!e._zod?new Iu({type:"record",keyType:v(),valueType:t,...L.normalizeParams(e)}):new Iu({type:"record",keyType:t,valueType:e,...L.normalizeParams(n)})}var Go=g("ZodEnum",(t,e)=>{Qa.init(t,e),G.init(t,e),t._zod.processJSONSchema=(r,o,s)=>Vc(t,r,o,s),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Go({...e,checks:[],...L.normalizeParams(o),entries:s})},t.exclude=(r,o)=>{let s={...e.entries};for(let i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Go({...e,checks:[],...L.normalizeParams(o),entries:s})}});function ce(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new Go({type:"enum",entries:n,...L.normalizeParams(e)})}var Sp=g("ZodLiteral",(t,e)=>{Ga.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>qc(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 Sp({type:"literal",values:Array.isArray(t)?t:[t],...L.normalizeParams(e)})}var Ap=g("ZodTransform",(t,e)=>{Va.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Kc(t,n,r,o),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new St(t.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(L.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(L.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 Ep(t){return new Ap({type:"transform",transform:t})}var Mu=g("ZodOptional",(t,e)=>{Do.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Qo(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Ou(t){return new Mu({type:"optional",innerType:t})}var vp=g("ZodExactOptional",(t,e)=>{qa.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Qo(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function kp(t){return new vp({type:"optional",innerType:t})}var Dp=g("ZodNullable",(t,e)=>{Ja.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>tu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Cu(t){return new Dp({type:"nullable",innerType:t})}var Rp=g("ZodDefault",(t,e)=>{Ka.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ru(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Ip(t,e){return new Rp({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():L.shallowClone(e)}})}var Op=g("ZodPrefault",(t,e)=>{Wa.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ou(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Cp(t,e){return new Op({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():L.shallowClone(e)}})}var Fu=g("ZodNonOptional",(t,e)=>{Ya.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>nu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Np(t,e){return new Fu({type:"nonoptional",innerType:t,...L.normalizeParams(e)})}var $p=g("ZodCatch",(t,e)=>{Ha.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>su(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Tp(t,e){return new $p({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var zp=g("ZodPipe",(t,e)=>{Xa.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>iu(t,n,r,o),t.in=e.in,t.out=e.out});function Nu(t,e){return new zp({type:"pipe",in:t,out:e})}var Pp=g("ZodReadonly",(t,e)=>{ec.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>au(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Lp(t){return new Pp({type:"readonly",innerType:t})}var Mp=g("ZodLazy",(t,e)=>{tc.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>cu(t,n,r,o),t.unwrap=()=>t._zod.def.getter()});function Vo(t){return new Mp({type:"lazy",getter:t})}var Fp=g("ZodCustom",(t,e)=>{nc.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Jc(t,n,r,o)});function Zp(t,e={}){return Lc(Fp,t,e)}function jp(t,e){return Mc(t,e)}function rt(t){let e=Vo(()=>Rt([v(t),F(),nt(),hp(),V(e),_e(v(),e)]));return e}var Zu=t=>"field"in t?[t]:("all"in t?t.all:t.any).flatMap(Zu),hn=t=>Zu(t);var Ot=(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=Ot(o,e);if(s===!1)return!1;r||=s===void 0}return r?void 0:!0}for(let o of n){let s=Ot(o,e);if(s===!0)return!0;r||=s===void 0}return r?void 0:!1},ju=t=>JSON.stringify(t),qo=t=>{if("field"in t)return{conditions:1,depth:0};let e="all"in t?t.all:t.any,n=0,r=1;for(let o of e){let s=qo(o);n+=s.conditions,r=Math.max(r,s.depth+1)}return{conditions:n,depth:r}},Bu=(t,e={})=>{let n=o=>{let s=V(o),i=e.maximumChildren===void 0?s:s.max(e.maximumChildren);return Rt([t,C({all:i}),C({any:i})])},r=Vo(()=>n(r));return e.maximumConditions===void 0&&e.maximumDepth===void 0?r:r.superRefine((o,s)=>{let{conditions:i,depth:a}=qo(o);e.maximumConditions!==void 0&&i>e.maximumConditions&&s.addIssue({code:"custom",message:e.maximumConditionsMessage??"Query exceeds the condition limit"}),e.maximumDepth!==void 0&&a>e.maximumDepth&&s.addIssue({code:"custom",message:e.maximumDepthMessage??"Query exceeds the nesting limit"})})};var R={requestBytes:524288,filterCount:32,filterDepth:8,sortCount:8,outputFieldCount:256,fieldPathDepth:9,defaultResultCount:20,resultCount:1e3,resultBytes:16777216,candidateDocuments:1e3,databaseBytes:512e3,frontmatterBytes:65536,frontmatterDepth:8,frontmatterFields:256,frontmatterStringBytes:16384,jsonBytes:1048576,jsonDepth:8,jsonFields:256,jsonStringBytes:16384,indexedPropertiesBytes:65536,excerptBytes:2048,hydratedFileBytes:1048576,hydratedTotalBytes:2097152,hydratedFileCount:20,hydratedRangeBytes:262144,concurrentContentReads:8};function gt(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=gt(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=>gt(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(`${gt(o)}:${gt(t[o],e)}`);n=`{${r.join(",")}}`}return e.delete(t),n}var Bp=new TextEncoder,Ct=t=>Bp.encode(t),$e=t=>Ct(t).byteLength,re=class extends Error{constructor(){super("Byte stream exceeds the configured limit"),this.name="ByteLimitExceededError"}},Up=(t,e)=>{let n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.byteLength;return n},Nt=t=>typeof t=="string"?{async*[Symbol.asyncIterator](){yield Ct(t)}}:t instanceof Uint8Array?{async*[Symbol.asyncIterator](){yield t}}:t,Jo=async(t,e)=>{let n=[],r=0;for await(let o of Nt(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 Up(n,r)},Te=async(t,e)=>{let n=await Jo(t,e+1);if(n.byteLength>e)throw new re;return n},fe=t=>new TextDecoder("utf-8",{fatal:!0}).decode(t),$t=t=>t.charCodeAt(0)===65279?t.slice(1):t;var Uu=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")}},Ko=(t,e)=>{if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return Uu(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(Ko(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))Uu(o),s!==void 0&&Object.defineProperty(r,o,{value:Ko(s,e),enumerable:!0,configurable:!0,writable:!0})}finally{e.delete(t)}return r}throw new Error("Value cannot be represented as JSON")},ot=t=>Ko(t,new Set),de=t=>{let e=gt(ot(t));if(e===void 0)throw new Error("Value cannot be represented as canonical JSON");return e},yn=(t,e)=>t===void 0||e===void 0?t===e:de(t)===de(e),ze=(t,e)=>t<e?-1:t>e?1:0,Wo=async t=>{let e=typeof t=="string"?Ct(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("")},Qu=async t=>`sha256:${await Wo(t)}`;var Gu=It("type",[C({type:Z("document")}),C({type:Z("json"),path:V(v()).min(1)}),C({type:Z("markdown-body")}),C({type:Z("markdown-frontmatter")})]),Yo=C({documentId:v().min(1),revision:v().min(1),representation:Gu}),Qp=t=>{let e=Gu.parse(t);return e.type==="json"?Object.freeze({...e,path:Object.freeze([...e.path])}):Object.freeze(e)},Vu=t=>{let e=Yo.parse(t);return Object.freeze({...e,representation:Qp(e.representation)})};var cr=C({id:v().min(1),revision:v().min(1),contentRef:v().min(1),format:ce(["json","markdown"]).optional()}),ur=C({sourceId:v().min(1),referenceId:v().min(1),reference:Yo});var Tt=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])}},Gp=(t,e)=>ze(t.sourceId,e.sourceId)||ze(t.referenceId,e.referenceId),gn=({nodes:t,edges:e})=>{let n=t.map(a=>Object.freeze(cr.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=ur.parse(a);return Object.freeze({...c,reference:Vu(c.reference)})}).sort(Gp),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)})},Vp=t=>new Map(t.nodes.map(e=>[e.id,e]));var lr=({graph:t,rootIds:e})=>{let n=Vp(t),r=Tt(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 qp=v().regex(/^sha256:[a-f0-9]{64}$/),qu=C({format:Z("webstudio-document-graph"),version:Z(1),nodes:V(cr),edges:V(ur),integrity:C({algorithm:Z("sha256"),checksum:qp})});var Jp=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"}),Wu=C({_id:v().min(1),_type:Z("asset.file"),name:v().min(1),description:v().optional(),path:Jp,key:v(),folderId:v().min(1).optional(),extension:v().regex(/^[a-z0-9]*$/),mimeType:v().min(1),size:F().int().nonnegative(),createdAt:v().datetime().optional(),revision:v().min(1),contentRef:v().min(1),properties:_e(v(),rt()),excerpt:v().optional(),metadataError:C({code:v().min(1),message:v().min(1)}).optional()}),Xo=Wu.partial().required({_id:!0}),Kp=ce(["null","boolean","number","string","object","array"]),Wp=ye({format:Z("webstudio-builder-asset-field-catalog"),version:Z(1),canonicalRevision:v().regex(/^sha256:[a-f0-9]{64}$/),documentCount:F().int().nonnegative(),fields:_e(v().min(1),ye({queryPath:V(v().min(1)).min(1).max(R.fieldPathDepth).optional(),types:V(Kp).min(1),occurrences:F().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"})}}),fr=v().regex(/^sha256:[a-f0-9]{64}$/),Yu=C({fields:V(V(v().min(1)).min(1).max(R.fieldPathDepth)).min(1).max(R.outputFieldCount+1),rows:V(V(rt())).max(R.resultCount),totalCount:F().int().nonnegative().max(R.candidateDocuments),hasMore:nt()}).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"})}),Ju=C({format:Z("webstudio-content-database"),version:Z(1),assetRevision:fr,documents:V(Xo),documentGraph:qu.optional(),contents:_e(v().min(1),v()).optional(),assetReferences:_e(v().min(1),V(C({start:F().int().nonnegative(),end:F().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:_e(v().min(1),V(C({path:V(v().min(1).or(F().int().nonnegative())).min(1),assetId:v().min(1),suffix:v().min(1).optional()}))).optional(),fieldCatalog:Wp,queries:_e(fr,Yu).optional(),database:C({maxBytes:F().int().positive(),unboundedBytes:F().int().nonnegative(),sourceDocumentCount:F().int().nonnegative(),includedDocumentCount:F().int().nonnegative().optional()}).optional(),integrity:C({algorithm:Z("sha256"),checksum:fr})}).superRefine((t,e)=>{t.documents.length>R.candidateDocuments&&e.addIssue({code:"custom",path:["documents"],message:"Asset index exceeds the document limit"}),(t.fieldCatalog.canonicalRevision!==t.assetRevision||t.fieldCatalog.documentCount!==t.documents.length)&&e.addIssue({code:"custom",path:["fieldCatalog"],message:"Asset index field catalog does not match its documents"}),t.database!==void 0&&t.database.sourceDocumentCount<t.documents.length&&e.addIssue({code:"custom",path:["database","sourceDocumentCount"],message:"Source document count cannot be smaller than the database"}),t.database?.includedDocumentCount!==void 0&&(t.database.includedDocumentCount<t.documents.length||t.database.includedDocumentCount>t.database.sourceDocumentCount)&&e.addIssue({code:"custom",path:["database","includedDocumentCount"],message:"Included document count must match the database bounds"});let n;for(let[o,s]of t.documents.entries())n!==void 0&&s._id<=n&&e.addIssue({code:"custom",path:["documents",o,"_id"],message:"Asset index documents must have unique sorted IDs"}),n=s._id;let r=new Set(t.documents.flatMap(({contentRef:o})=>o===void 0?[]:[o]));for(let o of Object.keys(t.contents??{}))r.has(o)===!1&&e.addIssue({code:"custom",path:["contents",o],message:"Embedded content must belong to an indexed document"});for(let o of Object.keys(t.assetReferences??{}))r.has(o)===!1&&e.addIssue({code:"custom",path:["assetReferences",o],message:"Asset references must belong to an indexed document"})}),Yp=It("mode",[ye({mode:Z("none")}),ye({mode:Z("full"),maxBytes:F().int().positive().max(R.hydratedFileBytes).optional()}),ye({mode:Z("range"),offset:F().int().nonnegative(),length:F().int().positive().max(R.hydratedRangeBytes)}),ye({mode:Z("markdown-body-ref"),maxBytes:F().int().positive().max(R.hydratedFileBytes).optional()})]),es={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"]},Hu=Object.keys(es),Xu=["url","width","height"],dr=t=>Xu.includes(t),el=Hu.filter(t=>dr(t)===!1&&t!=="excerpt"),tl=el.filter(t=>t!=="id"),nl=t=>el.includes(t),Hp=ce(Hu),bn=V(v().min(1)).min(1).max(R.fieldPathDepth).superRefine((t,e)=>{if(t[0]==="properties"){t.length<2&&e.addIssue({code:"custom",message:"A properties field path must select a property"});return}(t.length!==1||Hp.safeParse(t[0]).success===!1)&&e.addIssue({code:"custom",message:"Asset query field path is unsupported"})}),Ho=nt().default(!0),Xp=It("mode",[C({mode:Z("all"),includeMetadata:Ho}),C({mode:Z("base"),includeMetadata:Ho}),C({mode:Z("fields"),includeMetadata:Ho,fields:V(bn).max(R.outputFieldCount).refine(t=>new Set(t.map(ju)).size===t.length,{error:"Selected output fields must be unique"})})]),em={mode:"fields",includeMetadata:!1,fields:Xu.map(t=>[t])},rl=["eq","ne","contains","startsWith","endsWith","gt","gte","lt","lte"],_b=[...rl,"in","exists","isEmpty"],tm=C({field:bn,operator:ce(rl),value:rt()}),nm=C({field:bn,operator:Z("in"),value:V(rt()).max(R.resultCount)}),rm=C({field:bn,operator:ce(["exists","isEmpty"]),value:nt()}),om=It("operator",[tm,nm,rm]),sm=Bu(om,{maximumChildren:R.filterCount,maximumConditions:R.filterCount,maximumDepth:R.filterDepth,maximumConditionsMessage:"Asset query exceeds the filter limit",maximumDepthMessage:"Asset query exceeds the filter nesting limit"});var im=sm,ol=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]},am=C({field:bn,direction:ce(["asc","desc"])}),cm=ce(["many","one","first","last"]),um=({output:t,content:e})=>t.includeMetadata||t.mode==="all"||t.mode==="fields"&&t.fields.length>0||e.mode!=="none",st=C({result:cm.default("many"),where:im.default({all:[]}),sort:V(am).max(R.sortCount).default([]),limit:F().int().nonnegative().max(R.resultCount).default(R.defaultResultCount),offset:F().int().nonnegative().max(R.candidateDocuments).default(0),output:Xp.default(em),content:Yp.default({mode:"none"})}).superRefine((t,e)=>{um(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."})}),sl=C({query:st,indexRevision:v().min(1).max(255).optional()}),lm=ye({_id:v().min(1),revision:v().min(1),contentRef:v().min(1),encoding:Z("utf-8"),text:v(),range:ye({offset:F().int().nonnegative(),length:F().int().nonnegative(),total:F().int().nonnegative()}).optional()}),fm=lm.omit({_id:!0,revision:!0,contentRef:!0}),il=Wu.omit({_id:!0,_type:!0,contentRef:!0}).partial().extend({id:v().min(1),url:v().min(1).optional(),width:F().positive().optional(),height:F().positive().optional(),content:fm.optional()}).refine(t=>t.width===void 0==(t.height===void 0),{error:"Asset dimensions must include both width and height"}),dm=C({format:Z("webstudio-content-database"),version:Z(1),revision:fr,usedBytes:F().int().nonnegative(),maxBytes:F().int().positive(),unboundedBytes:F().int().nonnegative(),includedDocumentCount:F().int().nonnegative(),omittedDocumentCount:F().int().nonnegative(),omissionReason:ce(["size","unavailable"]).optional(),truncated:nt()}),Ku=dm.pick({usedBytes:!0,maxBytes:!0,unboundedBytes:!0,includedDocumentCount:!0,omittedDocumentCount:!0,omissionReason:!0,truncated:!0}),ts=C({items:V(il),totalCount:F().int().nonnegative(),hasMore:nt()}),pm=C({item:il.nullable(),totalCount:F().int().nonnegative()}),al=Rt([ts,pm]),mm=C({scope:Z("query-preview"),query:Ku,database:Ku,artifacts:C({query:Ju,database:Ju}).optional(),unresolved:al.optional()}),xb=C({data:al,__diagnostics__:mm}),hm=ce(["INVALID_REQUEST","REQUEST_CANCELLED","UNAUTHORIZED","FORBIDDEN","STALE_INDEX","CONTENT_IDENTITY_REQUIRED","CONTENT_NOT_TEXT","CONTENT_DECODING_FAILED","CONTENT_LIMIT_EXCEEDED","MULTIPLE_RESULTS","INTERNAL_ERROR"]),ym=ye({ok:Z(!1),error:ye({code:hm,message:v().min(1),retryable:nt(),details:_e(v(),rt()).optional()}),meta:ye({queryHash:v().min(1).optional(),indexRevision:v().min(1).optional(),assetRevision:v().min(1).optional()}).optional()}),cl=({code:t,message:e,retryable:n=!1,details:r})=>ym.parse({ok:!1,error:{code:t,message:e,retryable:n,details:r}});var ul=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 bm(o)}};var ns=(t,e)=>e+"/"+gm(t),gm=t=>t.toString().replace(/~/g,"~0").replace(/\//g,"~1"),bm=t=>t.toString().replace(/~1/g,"/").replace(/~0/g,"~");var pr=async(t,e,n)=>{if(Number.isSafeInteger(e)===!1||e<=0)throw new Error("Concurrency must be a positive safe integer");let r=0,o=new Array(t.length),s=async()=>{for(;r<t.length;){let u=r;r+=1,o[u]=await n(t[u])}},i=Array.from({length:Math.min(e,t.length)},s),c=(await Promise.allSettled(i)).find(u=>u.status==="rejected");if(c!==void 0)throw c.reason;return o};var zt=t=>typeof t=="object"&&t!==null&&Array.isArray(t)===!1,ll=t=>{if(zt(t)===!1)return;let e=Object.keys(t);if(!(e.length!==1||e[0]!=="$ref"))return t.$ref};var pe=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=ll(t);if(n!==void 0){if(typeof n!="string")throw new pe({code:"INVALID_REFERENCE_MARKER",message:`JSON reference marker ${e} must contain a string $ref`,referenceId:e});return n}},_m=t=>`#${t}`;var fl=async({source:t,maximumBytes:e=R.hydratedFileBytes})=>{let n;try{n=await Te(t,e)}catch(o){throw o instanceof re?new pe({code:"CONTENT_LIMIT_EXCEEDED",message:"JSON document exceeds the byte limit",cause:o}):o}let r;try{r=$t(fe(n))}catch(o){throw new pe({code:"CONTENT_DECODING_FAILED",message:"JSON document is not valid UTF-8",cause:o})}try{return ot(JSON.parse(r))}catch(o){throw new pe({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(zt(n)&&Object.hasOwn(n,r)){n=n[r];continue}return}return n},dl=({document:t,representation:e})=>{let n=ot(t);if(e.type==="document")return n;if(e.type!=="json")throw new pe({code:"UNSUPPORTED_REPRESENTATION",message:`JSON documents do not support ${e.type}`});let r=xm(n,e.path);if(r===void 0)throw new pe({code:"JSON_PATH_NOT_FOUND",message:"JSON document path does not exist"});return r},Sm=(t,e,n)=>{Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0})},mr=({document:t,references:e,allowUnresolvedReferences:n=!1})=>{let r=ot(t),o=new Set,s=(a,c)=>{let u=_m(c);if(wm(a,u)!==void 0){if(e.has(u)===!1){if(n)return a;throw new pe({code:"REFERENCE_NOT_FOUND",message:`Resolved JSON reference ${u} is unavailable`,referenceId:u})}o.add(u);try{return ot(e.get(u))}catch(l){throw new pe({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,ns(String(f),c)));if(zt(a)){let l={};for(let[f,p]of Object.entries(a))Sm(l,f,s(p,ns(f,c)));return l}return a},i=s(r,"");for(let a of[...e.keys()].sort())if(o.has(a)===!1)throw new pe({code:"UNUSED_REFERENCE",message:`Resolved JSON reference ${a} has no marker`,referenceId:a});return i};var hr=Symbol.for("yaml.alias"),yr=Symbol.for("yaml.document"),xe=Symbol.for("yaml.map"),rs=Symbol.for("yaml.pair"),me=Symbol.for("yaml.scalar"),qe=Symbol.for("yaml.seq"),oe=Symbol.for("yaml.node.type"),Se=t=>!!t&&typeof t=="object"&&t[oe]===hr,Le=t=>!!t&&typeof t=="object"&&t[oe]===yr,Ae=t=>!!t&&typeof t=="object"&&t[oe]===xe,T=t=>!!t&&typeof t=="object"&&t[oe]===rs,N=t=>!!t&&typeof t=="object"&&t[oe]===me,Ee=t=>!!t&&typeof t=="object"&&t[oe]===qe;function j(t){if(t&&typeof t=="object")switch(t[oe]){case xe:case qe:return!0}return!1}function P(t){if(t&&typeof t=="object")switch(t[oe]){case hr:case xe:case me:case qe:return!0}return!1}var gr=t=>(N(t)||j(t))&&!!t.anchor;var ue=Symbol("break visit"),pl=Symbol("skip children"),Me=Symbol("remove node");function Fe(t,e){let n=ml(e);Le(t)?Pt(null,t.contents,n,Object.freeze([t]))===Me&&(t.contents=null):Pt(null,t,n,Object.freeze([]))}Fe.BREAK=ue;Fe.SKIP=pl;Fe.REMOVE=Me;function Pt(t,e,n,r){let o=hl(t,e,n,r);if(P(o)||T(o))return yl(t,r,o),Pt(t,o,n,r);if(typeof o!="symbol"){if(j(e)){r=Object.freeze(r.concat(e));for(let s=0;s<e.items.length;++s){let i=Pt(s,e.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===ue)return ue;i===Me&&(e.items.splice(s,1),s-=1)}}}else if(T(e)){r=Object.freeze(r.concat(e));let s=Pt("key",e.key,n,r);if(s===ue)return ue;s===Me&&(e.key=null);let i=Pt("value",e.value,n,r);if(i===ue)return ue;i===Me&&(e.value=null)}}return o}async function br(t,e){let n=ml(e);Le(t)?await Lt(null,t.contents,n,Object.freeze([t]))===Me&&(t.contents=null):await Lt(null,t,n,Object.freeze([]))}br.BREAK=ue;br.SKIP=pl;br.REMOVE=Me;async function Lt(t,e,n,r){let o=await hl(t,e,n,r);if(P(o)||T(o))return yl(t,r,o),Lt(t,o,n,r);if(typeof o!="symbol"){if(j(e)){r=Object.freeze(r.concat(e));for(let s=0;s<e.items.length;++s){let i=await Lt(s,e.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===ue)return ue;i===Me&&(e.items.splice(s,1),s-=1)}}}else if(T(e)){r=Object.freeze(r.concat(e));let s=await Lt("key",e.key,n,r);if(s===ue)return ue;s===Me&&(e.key=null);let i=await Lt("value",e.value,n,r);if(i===ue)return ue;i===Me&&(e.value=null)}}return o}function ml(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 hl(t,e,n,r){if(typeof n=="function")return n(t,e,r);if(Ae(e))return n.Map?.(t,e,r);if(Ee(e))return n.Seq?.(t,e,r);if(T(e))return n.Pair?.(t,e,r);if(N(e))return n.Scalar?.(t,e,r);if(Se(e))return n.Alias?.(t,e,r)}function yl(t,e,n){let r=e[e.length-1];if(j(r))r.items[t]=n;else if(T(r))t==="key"?r.key=n:r.value=n;else if(Le(r))r.contents=n;else{let o=Se(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}var Am={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Em=t=>t.replace(/[!,[\]{}]/g,e=>Am[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+Em(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&&P(e.contents)){let s={};Fe(e.contents,(i,a)=>{P(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 wr(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 os(t){let e=new Set;return Fe(t,{Value(n,r){r.anchor&&e.add(r.anchor)}}),e}function ss(t,e){for(let n=1;;++n){let r=`${t}${n}`;if(!e.has(r))return r}}function gl(t,e){let n=[],r=new Map,o=null;return{onAnchor:s=>{n.push(s),o??(o=os(t));let i=ss(e,o);return o.add(i),i},setAnchors:()=>{for(let s of n){let i=r.get(s);if(typeof i=="object"&&i.anchor&&(N(i.node)||j(i.node)))i.node.anchor=i.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:r}}function it(t,e,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let o=0,s=r.length;o<s;++o){let i=r[o],a=it(t,r,String(o),i);a===void 0?delete r[o]:a!==i&&(r[o]=a)}else if(r instanceof Map)for(let o of Array.from(r.keys())){let s=r.get(o),i=it(t,r,o,s);i===void 0?r.delete(o):i!==s&&r.set(o,i)}else if(r instanceof Set)for(let o of Array.from(r)){let s=it(t,r,o,o);s===void 0?r.delete(o):s!==o&&(r.delete(o),r.add(s))}else for(let[o,s]of Object.entries(r)){let i=it(t,r,o,s);i===void 0?delete r[o]:i!==s&&(r[o]=i)}return t.call(e,n,r)}function Y(t,e,n){if(Array.isArray(t))return t.map((r,o)=>Y(r,String(o),n));if(t&&typeof t.toJSON=="function"){if(!n||!gr(t))return t.toJSON(e,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(t,r),n.onCreate=s=>{r.res=s,delete n.onCreate};let o=t.toJSON(e,n);return n.onCreate&&n.onCreate(o),o}return typeof t=="bigint"&&!n?.keep?Number(t):t}var at=class{constructor(e){Object.defineProperty(this,oe,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:r,onAnchor:o,reviver:s}={}){if(!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=Y(this,"",i);if(typeof o=="function")for(let{count:c,res:u}of i.anchors.values())o(u,c);return typeof s=="function"?it(s,{"":a},"",a):a}};var Je=class extends at{constructor(e){super(hr),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)=>{(Se(i)||gr(i))&&r.push(i)}}),n&&(n.aliasResolveCache=r));let o;for(let s of r){if(s===this)break;s.anchor===this.source&&(o=s)}return o}toJSON(e,n){if(!n)return{source:this.source};let{anchors:r,doc:o,maxAliasCount:s}=n,i=this.resolve(o,n);if(!i){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=r.get(i);if(a||(Y(i,null,n),a=r.get(i)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=_r(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(wr(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 _r(t,e,n){if(Se(e)){let r=e.resolve(t),o=n&&r&&n.get(r);return o?o.count*o.aliasCount:0}else if(j(e)){let r=0;for(let o of e.items){let s=_r(t,o,n);s>r&&(r=s)}return r}else if(T(e)){let r=_r(t,e.key,n),o=_r(t,e.value,n);return Math.max(r,o)}return 1}var xr=t=>!t||typeof t!="function"&&typeof t!="object",D=class extends at{constructor(e){super(me),this.value=e}toJSON(e,n){return n?.keep?this.value:Y(this.value,e,n)}toString(){return String(this.value)}};D.BLOCK_FOLDED="BLOCK_FOLDED";D.BLOCK_LITERAL="BLOCK_LITERAL";D.PLAIN="PLAIN";D.QUOTE_DOUBLE="QUOTE_DOUBLE";D.QUOTE_SINGLE="QUOTE_SINGLE";var vm="tag:yaml.org,2002:";function km(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 Ke(t,e,n){if(Le(t)&&(t=t.contents),P(t))return t;if(T(t)){let l=n.schema[xe].createNode?.(n.schema,null,n);return l.items.push(t),l}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:r,onAnchor:o,onTagObj:s,schema:i,sourceObjects:a}=n,c;if(r&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=o(t)),new Je(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=vm+e.slice(2));let u=km(t,e,i.tags);if(!u){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let l=new D(t);return c&&(c.node=l),l}u=t instanceof Map?i[xe]:Symbol.iterator in Object(t)?i[qe]:i[xe]}s&&(s(u),delete n.onTagObj);let d=u?.createNode?u.createNode(n.schema,t,n):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(n.schema,t,n):new D(t);return e?d.tag=e:u.default||(d.tag=u.tag),c&&(c.node=d),d}function wn(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 Ke(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 Ft=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Mt=class extends at{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(r=>P(r)||T(r)?r.clone(e):r),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(Ft(e))this.add(n);else{let[r,...o]=e,s=this.get(r,!0);if(j(s))s.addIn(o,n);else if(s===void 0&&this.schema)this.set(r,wn(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(j(o))return o.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(e,n){let[r,...o]=e,s=this.get(r,!0);return o.length===0?!n&&N(s)?s.value:s:j(s)?s.getIn(o,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!T(n))return!1;let r=n.value;return r==null||e&&N(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[n,...r]=e;if(r.length===0)return this.has(n);let o=this.get(n,!0);return j(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(j(s))s.setIn(o,n);else if(s===void 0&&this.schema)this.set(r,wn(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}};var bl=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function ge(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var je=(t,e,n)=>t.endsWith(`
`)?ge(n,e):n.includes(`
`)?`
-`+ge(n,e):(t.endsWith(" ")?"":" ")+n;var ss="flow",Sr="block",wn="quoted";function _n(t,e,n="flow",{indentAtStart:r,lineWidth:o=80,minContentWidth:s=20,onFold:i,onOverflow:a}={}){if(!o||o<0)return t;o<s&&(s=0);let c=Math.max(1+s,1+o-e.length);if(t.length<=c)return t;let u=[],d={},l=o-e.length;typeof r=="number"&&(r>o-Math.max(2,s)?u.push(0):l=o-r);let f,p,y=!1,m=-1,h=-1,w=-1;n===Sr&&(m=yl(t,m,e.length),m!==-1&&(l=m+c));for(let A;A=t[m+=1];){if(n===wn&&A==="\\"){switch(h=m,t[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}w=m}if(A===`
-`)n===Sr&&(m=yl(t,m,e.length)),l=m+e.length+c,f=void 0;else{if(A===" "&&p&&p!==" "&&p!==`
+`+ge(n,e):(t.endsWith(" ")?"":" ")+n;var is="flow",Sr="block",_n="quoted";function xn(t,e,n="flow",{indentAtStart:r,lineWidth:o=80,minContentWidth:s=20,onFold:i,onOverflow:a}={}){if(!o||o<0)return t;o<s&&(s=0);let c=Math.max(1+s,1+o-e.length);if(t.length<=c)return t;let u=[],d={},l=o-e.length;typeof r=="number"&&(r>o-Math.max(2,s)?u.push(0):l=o-r);let f,p,y=!1,m=-1,h=-1,b=-1;n===Sr&&(m=wl(t,m,e.length),m!==-1&&(l=m+c));for(let A;A=t[m+=1];){if(n===_n&&A==="\\"){switch(h=m,t[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}b=m}if(A===`
+`)n===Sr&&(m=wl(t,m,e.length)),l=m+e.length+c,f=void 0;else{if(A===" "&&p&&p!==" "&&p!==`
`&&p!==" "){let _=t[m+1];_&&_!==" "&&_!==`
-`&&_!==" "&&(f=m)}if(m>=l)if(f)u.push(f),l=f+c,f=void 0;else if(n===wn){for(;p===" "||p===" ";)p=A,A=t[m+=1],y=!0;let _=m>w+1?m-2:h-1;if(d[_])return t;u.push(_),d[_]=!0,l=_+c,f=void 0}else y=!0}p=A}if(y&&a&&a(),u.length===0)return t;i&&i();let S=t.slice(0,u[0]);for(let A=0;A<u.length;++A){let _=u[A],b=u[A+1]||t.length;_===0?S=`
-${e}${t.slice(0,b)}`:(n===wn&&d[_]&&(S+=`${t[_]}\\`),S+=`
-${e}${t.slice(_+1,b)}`)}return S}function yl(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 Er=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),vr=t=>/^(%|---|\.\.\.)/m.test(t);function Am(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 xn(t,e){let n=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=e,o=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(vr(t)?" ":""),i="",a=0;for(let c=0,u=n[c];u;u=n[++c])if(u===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(i+=n.slice(a,c)+"\\ ",c+=1,a=c,u="\\"),u==="\\")switch(n[c+1]){case"u":{i+=n.slice(a,c);let d=n.substr(c+2,4);switch(d){case"0000":i+="\\0";break;case"0007":i+="\\a";break;case"000b":i+="\\v";break;case"001b":i+="\\e";break;case"0085":i+="\\N";break;case"00a0":i+="\\_";break;case"2028":i+="\\L";break;case"2029":i+="\\P";break;default:d.substr(0,2)==="00"?i+="\\x"+d.substr(2):i+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(r||n[c+2]==='"'||n.length<o)c+=1;else{for(i+=n.slice(a,c)+`
+`&&_!==" "&&(f=m)}if(m>=l)if(f)u.push(f),l=f+c,f=void 0;else if(n===_n){for(;p===" "||p===" ";)p=A,A=t[m+=1],y=!0;let _=m>b+1?m-2:h-1;if(d[_])return t;u.push(_),d[_]=!0,l=_+c,f=void 0}else y=!0}p=A}if(y&&a&&a(),u.length===0)return t;i&&i();let S=t.slice(0,u[0]);for(let A=0;A<u.length;++A){let _=u[A],w=u[A+1]||t.length;_===0?S=`
+${e}${t.slice(0,w)}`:(n===_n&&d[_]&&(S+=`${t[_]}\\`),S+=`
+${e}${t.slice(_+1,w)}`)}return S}function wl(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 Er=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),vr=t=>/^(%|---|\.\.\.)/m.test(t);function Dm(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 Sn(t,e){let n=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=e,o=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(vr(t)?" ":""),i="",a=0;for(let c=0,u=n[c];u;u=n[++c])if(u===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(i+=n.slice(a,c)+"\\ ",c+=1,a=c,u="\\"),u==="\\")switch(n[c+1]){case"u":{i+=n.slice(a,c);let d=n.substr(c+2,4);switch(d){case"0000":i+="\\0";break;case"0007":i+="\\a";break;case"000b":i+="\\v";break;case"001b":i+="\\e";break;case"0085":i+="\\N";break;case"00a0":i+="\\_";break;case"2028":i+="\\L";break;case"2029":i+="\\P";break;default:d.substr(0,2)==="00"?i+="\\x"+d.substr(2):i+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(r||n[c+2]==='"'||n.length<o)c+=1;else{for(i+=n.slice(a,c)+`
`;n[c+2]==="\\"&&n[c+3]==="n"&&n[c+4]!=='"';)i+=`
-`,c+=2;i+=s,n[c+2]===" "&&(i+="\\"),c+=1,a=c+1}break;default:c+=1}return i=a?i+n.slice(a):n,r?i:_n(i,s,wn,Er(e,!1))}function is(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
-`)||/[ \t]\n|\n[ \t]/.test(t))return xn(t,e);let n=e.indent||(vr(t)?" ":""),r="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
-${n}`)+"'";return e.implicitKey?r:_n(r,n,ss,Er(e,!1))}function Ft(t,e){let{singleQuote:n}=e.options,r;if(n===!1)r=xn;else{let o=t.includes('"'),s=t.includes("'");o&&!s?r=is:s&&!o?r=xn:r=n?is:xn}return r(t,e)}var as;try{as=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:xn(i,s,_n,Er(e,!1))}function as(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
+`)||/[ \t]\n|\n[ \t]/.test(t))return Sn(t,e);let n=e.indent||(vr(t)?" ":""),r="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
+${n}`)+"'";return e.implicitKey?r:xn(r,n,is,Er(e,!1))}function Zt(t,e){let{singleQuote:n}=e.options,r;if(n===!1)r=Sn;else{let o=t.includes('"'),s=t.includes("'");o&&!s?r=as:s&&!o?r=Sn:r=n?as:Sn}return r(t,e)}var cs;try{cs=new RegExp(`(^|(?<!
))
+(?!
-|$)`,"g")}catch{as=/\n+(?!\n|$)/g}function Ar({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 Ft(n,r);let u=r.indent||(r.forceBlockIndent||vr(n)?" ":""),d=i==="literal"?!0:i==="folded"||e===D.BLOCK_FOLDED?!1:e===D.BLOCK_LITERAL?!0:!Am(n,c,u.length);if(!n)return d?`|
+|$)`,"g")}catch{cs=/\n+(?!\n|$)/g}function Ar({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 Zt(n,r);let u=r.indent||(r.forceBlockIndent||vr(n)?" ":""),d=i==="literal"?!0:i==="folded"||e===D.BLOCK_FOLDED?!1:e===D.BLOCK_LITERAL?!0:!Dm(n,c,u.length);if(!n)return d?`|
`:`>
-`;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),y=p.indexOf(`
+`;let l,f;for(f=n.length;f>0;--f){let w=n[f-1];if(w!==`
+`&&w!==" "&&w!==" ")break}let p=n.substring(f),y=p.indexOf(`
`);y===-1?l="-":n===p||y!==p.length-1?(l="+",s&&s()):l="",p&&(n=n.slice(0,-p.length),p[p.length-1]===`
-`&&(p=p.slice(0,-1)),p=p.replace(as,`$&${u}`));let m=!1,h,w=-1;for(h=0;h<n.length;++h){let b=n[h];if(b===" ")m=!0;else if(b===`
-`)w=h;else break}let S=n.substring(0,w<h?w+1:h);S&&(n=n.substring(S.length),S=S.replace(/\n+/g,`$&${u}`));let _=(m?u?"2":"1":"")+l;if(t&&(_+=" "+a(t.replace(/ ?[\r\n]+/g," ")),o&&o()),!d){let b=n.replace(/\n+/g,`
-$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`),E=!1,k=Er(r,!0);i!=="folded"&&e!==D.BLOCK_FOLDED&&(k.onOverflow=()=>{E=!0});let x=_n(`${S}${b}${p}`,u,Sr,k);if(!E)return`>${_}
+`&&(p=p.slice(0,-1)),p=p.replace(cs,`$&${u}`));let m=!1,h,b=-1;for(h=0;h<n.length;++h){let w=n[h];if(w===" ")m=!0;else if(w===`
+`)b=h;else break}let S=n.substring(0,b<h?b+1:h);S&&(n=n.substring(S.length),S=S.replace(/\n+/g,`$&${u}`));let _=(m?u?"2":"1":"")+l;if(t&&(_+=" "+a(t.replace(/ ?[\r\n]+/g," ")),o&&o()),!d){let w=n.replace(/\n+/g,`
+$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`),E=!1,k=Er(r,!0);i!=="folded"&&e!==D.BLOCK_FOLDED&&(k.onOverflow=()=>{E=!0});let x=xn(`${S}${w}${p}`,u,Sr,k);if(!E)return`>${_}
${u}${x}`}return n=n.replace(/\n+/g,`$&${u}`),`|${_}
-${u}${S}${n}${p}`}function Em(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 Ft(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||d||!s.includes(`
-`)?Ft(s,e):Ar(t,e,n,r);if(!a&&!d&&o!==D.PLAIN&&s.includes(`
-`))return Ar(t,e,n,r);if(vr(s)){if(c==="")return e.forceBlockIndent=!0,Ar(t,e,n,r);if(a&&c===u)return Ft(s,e)}let l=s.replace(/\n+/g,`$&
-${c}`);if(i){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(l),{compat:p,tags:y}=e.doc.schema;if(y.some(f)||p?.some(f))return Ft(s,e)}return a?l:_n(l,c,ss,Er(e,!1))}function bt(t,e,n,r){let{implicitKey:o,inFlow:s}=e,i=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==D.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(i.value)&&(a=D.QUOTE_DOUBLE);let c=d=>{switch(d){case D.BLOCK_FOLDED:case D.BLOCK_LITERAL:return o||s?Ft(i.value,e):Ar(i,e,n,r);case D.QUOTE_DOUBLE:return xn(i.value,e);case D.QUOTE_SINGLE:return is(i.value,e);case D.PLAIN:return Em(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 kr(t,e){let n=Object.assign({blockQuote:!0,commentString:hl,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 vm(t,e){if(e.tag){let o=t.filter(s=>s.tag===e.tag);if(o.length>0)return o.find(s=>s.format===e.format)??o[0]}let n,r;if(N(e)){r=e.value;let o=t.filter(s=>s.identify?.(r));if(o.length>1){let s=o.filter(i=>i.test);s.length>0&&(o=s)}n=o.find(s=>s.format===e.format)??o.find(s=>!s.format)}else r=e,n=t.find(o=>o.nodeClass&&r instanceof o.nodeClass);if(!n){let o=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${o} value`)}return n}function km(t,e,{anchors:n,doc:r}){if(!r.directives)return"";let o=[],s=(N(t)||Z(t))&&t.anchor;s&&wr(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 We(t,e,n,r){if(T(t))return t.toString(e,n,r);if(Se(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=P(t)?t:e.doc.createNode(t,{onTagObj:c=>o=c});o??(o=vm(e.doc.schema.tags,s));let i=km(s,o,e);i.length>0&&(e.indentAtStart=(e.indentAtStart??0)+i.length+1);let a=typeof o.stringify=="function"?o.stringify(s,e,n,r):N(s)?bt(s,e,n,r):s.toString(e,n,r);return i?N(s)||a[0]==="{"||a[0]==="["?`${i} ${a}`:`${i}
-${e.indent}${a}`:a}function gl({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=P(t)&&t.comment||null;if(l){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Z(t)||!P(t)&&typeof t=="object"){let k="With simple keys, collection cannot be used as a key value";throw new Error(k)}}let p=!l&&(!t||f&&e==null&&!n.inFlow||Z(t)||(N(t)?t.type===D.BLOCK_FOLDED||t.type===D.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(l||!s),indent:a+c});let y=!1,m=!1,h=We(t,n,()=>y=!0,()=>m=!0);if(!p&&!n.inFlow&&h.length>1024){if(l)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(n.inFlow){if(s||e==null)return y&&r&&r(),h===""?"?":p?`? ${h}`:h}else if(s&&!l||e==null&&p)return h=`? ${h}`,f&&!y?h+=Ze(h,n.indent,u(f)):m&&o&&o(),h;y&&(f=null),p?(f&&(h+=Ze(h,n.indent,u(f))),h=`? ${h}
-${a}:`):(h=`${h}:`,f&&(h+=Ze(h,n.indent,u(f))));let w,S,A;P(e)?(w=!!e.spaceBefore,S=e.commentBefore,A=e.comment):(w=!1,S=null,A=null,e&&typeof e=="object"&&(e=i.createNode(e))),n.implicitKey=!1,!p&&!f&&N(e)&&(n.indentAtStart=h.length+1),m=!1,!d&&c.length>=2&&!n.inFlow&&!p&&Ee(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let _=!1,b=We(e,n,()=>_=!0,()=>m=!0),E=" ";if(f||w||S){if(E=w?`
+${u}${S}${n}${p}`}function Rm(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 Zt(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||d||!s.includes(`
+`)?Zt(s,e):Ar(t,e,n,r);if(!a&&!d&&o!==D.PLAIN&&s.includes(`
+`))return Ar(t,e,n,r);if(vr(s)){if(c==="")return e.forceBlockIndent=!0,Ar(t,e,n,r);if(a&&c===u)return Zt(s,e)}let l=s.replace(/\n+/g,`$&
+${c}`);if(i){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(l),{compat:p,tags:y}=e.doc.schema;if(y.some(f)||p?.some(f))return Zt(s,e)}return a?l:xn(l,c,is,Er(e,!1))}function bt(t,e,n,r){let{implicitKey:o,inFlow:s}=e,i=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==D.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(i.value)&&(a=D.QUOTE_DOUBLE);let c=d=>{switch(d){case D.BLOCK_FOLDED:case D.BLOCK_LITERAL:return o||s?Zt(i.value,e):Ar(i,e,n,r);case D.QUOTE_DOUBLE:return Sn(i.value,e);case D.QUOTE_SINGLE:return as(i.value,e);case D.PLAIN:return Rm(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 kr(t,e){let n=Object.assign({blockQuote:!0,commentString:bl,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 Im(t,e){if(e.tag){let o=t.filter(s=>s.tag===e.tag);if(o.length>0)return o.find(s=>s.format===e.format)??o[0]}let n,r;if(N(e)){r=e.value;let o=t.filter(s=>s.identify?.(r));if(o.length>1){let s=o.filter(i=>i.test);s.length>0&&(o=s)}n=o.find(s=>s.format===e.format)??o.find(s=>!s.format)}else r=e,n=t.find(o=>o.nodeClass&&r instanceof o.nodeClass);if(!n){let o=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${o} value`)}return n}function Om(t,e,{anchors:n,doc:r}){if(!r.directives)return"";let o=[],s=(N(t)||j(t))&&t.anchor;s&&wr(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 We(t,e,n,r){if(T(t))return t.toString(e,n,r);if(Se(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=P(t)?t:e.doc.createNode(t,{onTagObj:c=>o=c});o??(o=Im(e.doc.schema.tags,s));let i=Om(s,o,e);i.length>0&&(e.indentAtStart=(e.indentAtStart??0)+i.length+1);let a=typeof o.stringify=="function"?o.stringify(s,e,n,r):N(s)?bt(s,e,n,r):s.toString(e,n,r);return i?N(s)||a[0]==="{"||a[0]==="["?`${i} ${a}`:`${i}
+${e.indent}${a}`:a}function _l({key:t,value:e},n,r,o){let{allNullValues:s,doc:i,indent:a,indentStep:c,options:{commentString:u,indentSeq:d,simpleKeys:l}}=n,f=P(t)&&t.comment||null;if(l){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(j(t)||!P(t)&&typeof t=="object"){let k="With simple keys, collection cannot be used as a key value";throw new Error(k)}}let p=!l&&(!t||f&&e==null&&!n.inFlow||j(t)||(N(t)?t.type===D.BLOCK_FOLDED||t.type===D.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(l||!s),indent:a+c});let y=!1,m=!1,h=We(t,n,()=>y=!0,()=>m=!0);if(!p&&!n.inFlow&&h.length>1024){if(l)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(n.inFlow){if(s||e==null)return y&&r&&r(),h===""?"?":p?`? ${h}`:h}else if(s&&!l||e==null&&p)return h=`? ${h}`,f&&!y?h+=je(h,n.indent,u(f)):m&&o&&o(),h;y&&(f=null),p?(f&&(h+=je(h,n.indent,u(f))),h=`? ${h}
+${a}:`):(h=`${h}:`,f&&(h+=je(h,n.indent,u(f))));let b,S,A;P(e)?(b=!!e.spaceBefore,S=e.commentBefore,A=e.comment):(b=!1,S=null,A=null,e&&typeof e=="object"&&(e=i.createNode(e))),n.implicitKey=!1,!p&&!f&&N(e)&&(n.indentAtStart=h.length+1),m=!1,!d&&c.length>=2&&!n.inFlow&&!p&&Ee(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let _=!1,w=We(e,n,()=>_=!0,()=>m=!0),E=" ";if(f||b||S){if(E=b?`
`:"",S){let k=u(S);E+=`
-${ge(k,n.indent)}`}b===""&&!n.inFlow?E===`
+${ge(k,n.indent)}`}w===""&&!n.inFlow?E===`
`&&A&&(E=`
`):E+=`
-${n.indent}`}else if(!p&&Z(e)){let k=b[0],x=b.indexOf(`
-`),I=x!==-1,M=n.inFlow??e.flow??e.items.length===0;if(I||!M){let B=!1;if(I&&(k==="&"||k==="!")){let $=b.indexOf(" ");k==="&"&&$!==-1&&$<x&&b[$+1]==="!"&&($=b.indexOf(" ",$+1)),($===-1||x<$)&&(B=!0)}B||(E=`
-${n.indent}`)}}else(b===""||b[0]===`
-`)&&(E="");return h+=E+b,n.inFlow?_&&r&&r():A&&!_?h+=Ze(h,n.indent,u(A)):m&&o&&o(),h}function cs(t,e){(t==="debug"||t==="warn")&&console.warn(e)}var Dr="<<",ve={identify:t=>t===Dr||typeof t=="symbol"&&t.description===Dr,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new D(Symbol(Dr)),{addToJSMap:ls}),stringify:()=>Dr},bl=(t,e)=>(ve.identify(e)||N(e)&&(!e.type||e.type===D.PLAIN)&&ve.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===ve.tag&&n.default);function ls(t,e,n){let r=wl(t,n);if(Ee(r))for(let o of r.items)us(t,e,o);else if(Array.isArray(r))for(let o of r)us(t,e,o);else us(t,e,r)}function us(t,e,n){let r=wl(t,n);if(!Ae(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 wl(t,e){return t&&Se(e)?e.resolve(t.doc,t):e}function Rr(t,e,{key:n,value:r}){if(P(n)&&n.addToJSMap)n.addToJSMap(t,e,r);else if(bl(t,n))ls(t,e,r);else{let o=Y(n,"",t);if(e instanceof Map)e.set(o,Y(r,o,t));else if(e instanceof Set)e.add(o);else{let s=Dm(n,o,t),i=Y(r,s,t);s in e?Object.defineProperty(e,s,{value:i,writable:!0,enumerable:!0,configurable:!0}):e[s]=i}}return e}function Dm(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(P(t)&&n?.doc){let r=kr(n.doc,{});r.anchors=new Set;for(let s of n.anchors.keys())r.anchors.add(s.anchor);r.inFlow=!0,r.inStringifyKey=!0;let o=t.toString(r);if(!n.mapKeyWarned){let s=JSON.stringify(o);s.length>40&&(s=s.substring(0,36)+'..."'),cs(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 Zt(t,e,n){let r=Ke(t,void 0,n),o=Ke(e,void 0,n);return new K(r,o)}var K=class t{constructor(e,n=null){Object.defineProperty(this,oe,{value:ns}),this.key=e,this.value=n}clone(e){let{key:n,value:r}=this;return P(n)&&(n=n.clone(e)),P(r)&&(r=r.clone(e)),new t(n,r)}toJSON(e,n){let r=n?.mapAsMap?new Map:{};return Rr(n,r,this)}toString(e,n,r){return e?.doc?gl(this,e,n,r):JSON.stringify(this)}};function Ir(t,e,n){return(e.inFlow??t.flow?Om:Rm)(t,e,n)}function Rm({comment:t,items:e},n,{blockItemPrefix:r,flowChars:o,itemIndent:s,onChompKeep:i,onComment:a}){let{indent:c,options:{commentString:u}}=n,d=Object.assign({},n,{indent:s,type:null}),l=!1,f=[];for(let y=0;y<e.length;++y){let m=e[y],h=null;if(P(m))!l&&m.spaceBefore&&f.push(""),Or(n,f,m.commentBefore,l),m.comment&&(h=m.comment);else if(T(m)){let S=P(m.key)?m.key:null;S&&(!l&&S.spaceBefore&&f.push(""),Or(n,f,S.commentBefore,l))}l=!1;let w=We(m,d,()=>h=null,()=>l=!0);h&&(w+=Ze(w,s,u(h))),l&&h&&(l=!1),f.push(r+w)}let p;if(f.length===0)p=o.start+o.end;else{p=f[0];for(let y=1;y<f.length;++y){let m=f[y];p+=m?`
+${n.indent}`}else if(!p&&j(e)){let k=w[0],x=w.indexOf(`
+`),O=x!==-1,M=n.inFlow??e.flow??e.items.length===0;if(O||!M){let B=!1;if(O&&(k==="&"||k==="!")){let $=w.indexOf(" ");k==="&"&&$!==-1&&$<x&&w[$+1]==="!"&&($=w.indexOf(" ",$+1)),($===-1||x<$)&&(B=!0)}B||(E=`
+${n.indent}`)}}else(w===""||w[0]===`
+`)&&(E="");return h+=E+w,n.inFlow?_&&r&&r():A&&!_?h+=je(h,n.indent,u(A)):m&&o&&o(),h}function us(t,e){(t==="debug"||t==="warn")&&console.warn(e)}var Dr="<<",ve={identify:t=>t===Dr||typeof t=="symbol"&&t.description===Dr,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new D(Symbol(Dr)),{addToJSMap:fs}),stringify:()=>Dr},xl=(t,e)=>(ve.identify(e)||N(e)&&(!e.type||e.type===D.PLAIN)&&ve.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===ve.tag&&n.default);function fs(t,e,n){let r=Sl(t,n);if(Ee(r))for(let o of r.items)ls(t,e,o);else if(Array.isArray(r))for(let o of r)ls(t,e,o);else ls(t,e,r)}function ls(t,e,n){let r=Sl(t,n);if(!Ae(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 Sl(t,e){return t&&Se(e)?e.resolve(t.doc,t):e}function Rr(t,e,{key:n,value:r}){if(P(n)&&n.addToJSMap)n.addToJSMap(t,e,r);else if(xl(t,n))fs(t,e,r);else{let o=Y(n,"",t);if(e instanceof Map)e.set(o,Y(r,o,t));else if(e instanceof Set)e.add(o);else{let s=Cm(n,o,t),i=Y(r,s,t);s in e?Object.defineProperty(e,s,{value:i,writable:!0,enumerable:!0,configurable:!0}):e[s]=i}}return e}function Cm(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(P(t)&&n?.doc){let r=kr(n.doc,{});r.anchors=new Set;for(let s of n.anchors.keys())r.anchors.add(s.anchor);r.inFlow=!0,r.inStringifyKey=!0;let o=t.toString(r);if(!n.mapKeyWarned){let s=JSON.stringify(o);s.length>40&&(s=s.substring(0,36)+'..."'),us(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return o}return JSON.stringify(e)}function jt(t,e,n){let r=Ke(t,void 0,n),o=Ke(e,void 0,n);return new K(r,o)}var K=class t{constructor(e,n=null){Object.defineProperty(this,oe,{value:rs}),this.key=e,this.value=n}clone(e){let{key:n,value:r}=this;return P(n)&&(n=n.clone(e)),P(r)&&(r=r.clone(e)),new t(n,r)}toJSON(e,n){let r=n?.mapAsMap?new Map:{};return Rr(n,r,this)}toString(e,n,r){return e?.doc?_l(this,e,n,r):JSON.stringify(this)}};function Or(t,e,n){return(e.inFlow??t.flow?$m:Nm)(t,e,n)}function Nm({comment:t,items:e},n,{blockItemPrefix:r,flowChars:o,itemIndent:s,onChompKeep:i,onComment:a}){let{indent:c,options:{commentString:u}}=n,d=Object.assign({},n,{indent:s,type:null}),l=!1,f=[];for(let y=0;y<e.length;++y){let m=e[y],h=null;if(P(m))!l&&m.spaceBefore&&f.push(""),Ir(n,f,m.commentBefore,l),m.comment&&(h=m.comment);else if(T(m)){let S=P(m.key)?m.key:null;S&&(!l&&S.spaceBefore&&f.push(""),Ir(n,f,S.commentBefore,l))}l=!1;let b=We(m,d,()=>h=null,()=>l=!0);h&&(b+=je(b,s,u(h))),l&&h&&(l=!1),f.push(r+b)}let p;if(f.length===0)p=o.start+o.end;else{p=f[0];for(let y=1;y<f.length;++y){let m=f[y];p+=m?`
${c}${m}`:`
`}}return t?(p+=`
-`+ge(u(t),c),a&&a()):l&&i&&i(),p}function Om({items:t},e,{flowChars:n,itemIndent:r}){let{indent:o,indentStep:s,flowCollectionPadding:i,options:{commentString:a}}=e;r+=s;let c=Object.assign({},e,{indent:r,inFlow:!0,type:null}),u=!1,d=0,l=[];for(let y=0;y<t.length;++y){let m=t[y],h=null;if(P(m))m.spaceBefore&&l.push(""),Or(e,l,m.commentBefore,!1),m.comment&&(h=m.comment);else if(T(m)){let S=P(m.key)?m.key:null;S&&(S.spaceBefore&&l.push(""),Or(e,l,S.commentBefore,!1),S.comment&&(u=!0));let A=P(m.value)?m.value:null;A?(A.comment&&(h=A.comment),A.commentBefore&&(u=!0)):m.value==null&&S?.comment&&(h=S.comment)}h&&(u=!0);let w=We(m,c,()=>h=null);u||(u=l.length>d||w.includes(`
-`)),y<t.length-1?w+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(u||(u=l.reduce((S,A)=>S+A.length+2,2)+(w.length+2)>e.options.lineWidth)),u&&(w+=",")),h&&(w+=Ze(w,r,a(h))),l.push(w),d=l.length}let{start:f,end:p}=n;if(l.length===0)return f+p;if(!u){let y=l.reduce((m,h)=>m+h.length+2,2);u=e.options.lineWidth>0&&y>e.options.lineWidth}if(u){let y=f;for(let m of l)y+=m?`
+`+ge(u(t),c),a&&a()):l&&i&&i(),p}function $m({items:t},e,{flowChars:n,itemIndent:r}){let{indent:o,indentStep:s,flowCollectionPadding:i,options:{commentString:a}}=e;r+=s;let c=Object.assign({},e,{indent:r,inFlow:!0,type:null}),u=!1,d=0,l=[];for(let y=0;y<t.length;++y){let m=t[y],h=null;if(P(m))m.spaceBefore&&l.push(""),Ir(e,l,m.commentBefore,!1),m.comment&&(h=m.comment);else if(T(m)){let S=P(m.key)?m.key:null;S&&(S.spaceBefore&&l.push(""),Ir(e,l,S.commentBefore,!1),S.comment&&(u=!0));let A=P(m.value)?m.value:null;A?(A.comment&&(h=A.comment),A.commentBefore&&(u=!0)):m.value==null&&S?.comment&&(h=S.comment)}h&&(u=!0);let b=We(m,c,()=>h=null);u||(u=l.length>d||b.includes(`
+`)),y<t.length-1?b+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(u||(u=l.reduce((S,A)=>S+A.length+2,2)+(b.length+2)>e.options.lineWidth)),u&&(b+=",")),h&&(b+=je(b,r,a(h))),l.push(b),d=l.length}let{start:f,end:p}=n;if(l.length===0)return f+p;if(!u){let y=l.reduce((m,h)=>m+h.length+2,2);u=e.options.lineWidth>0&&y>e.options.lineWidth}if(u){let y=f;for(let m of l)y+=m?`
${s}${o}${m}`:`
`;return`${y}
-${o}${p}`}else return`${f}${i}${l.join(" ")}${i}${p}`}function Or({indent:t,options:{commentString:e}},n,r,o){if(r&&o&&(r=r.replace(/^\n+/,"")),r){let s=ge(e(r),t);n.push(s.trimStart())}}function ct(t,e){let n=N(e)?e.value:e;for(let r of t)if(T(r)&&(r.key===e||r.key===n||N(r.key)&&r.key.value===n))return r}var W=class extends Lt{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(xe,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(Zt(c,u,r))};if(n instanceof Map)for(let[c,u]of n)a(c,u);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&i.items.sort(e.sortMapEntries),i}add(e,n){let r;T(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new K(e,e?.value):r=new K(e.key,e.value);let o=ct(this.items,r.key),s=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${r.key} already set`);N(o.value)&&xr(r.value)?o.value.value=r.value:o.value=r.value}else if(s){let i=this.items.findIndex(a=>s(r,a)<0);i===-1?this.items.push(r):this.items.splice(i,0,r)}else this.items.push(r)}delete(e){let n=ct(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let o=ct(this.items,e)?.value;return(!n&&N(o)?o.value:o)??void 0}has(e){return!!ct(this.items,e)}set(e,n){this.add(new K(e,n),!0)}toJSON(e,n,r){let o=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(o);for(let s of this.items)Rr(n,o,s);return o}toString(e,n,r){if(!e)return JSON.stringify(this);for(let o of this.items)if(!T(o))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Ir(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:n})}};var ke={collection:"map",default:!0,nodeClass:W,tag:"tag:yaml.org,2002:map",resolve(t,e){return Ae(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>W.from(t,e,n)};var ee=class extends Lt{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(qe,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=Cr(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let r=Cr(e);if(typeof r!="number")return;let o=this.items[r];return!n&&N(o)?o.value:o}has(e){let n=Cr(e);return typeof n=="number"&&n<this.items.length}set(e,n){let r=Cr(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);let o=this.items[r];N(o)&&xr(n)?o.value=n:this.items[r]=n}toJSON(e,n){let r=[];n?.onCreate&&n.onCreate(r);let o=0;for(let s of this.items)r.push(Y(s,String(o++),n));return r}toString(e,n,r){return e?Ir(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(Ke(a,void 0,r))}}return s}};function Cr(t){let e=N(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}var De={collection:"seq",default:!0,nodeClass:ee,tag:"tag:yaml.org,2002:seq",resolve(t,e){return Ee(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>ee.from(t,e,n)};var ut={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,r){return e=Object.assign({actualString:!0},e),bt(t,e,n,r)}};var wt={identify:t=>t==null,createNode:()=>new D(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new D(null),stringify:({source:t},e)=>typeof t=="string"&&wt.test.test(t)?t:e.options.nullStr};var Sn={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new D(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&Sn.test.test(t)){let r=t[0]==="t"||t[0]==="T";if(e===r)return t}return e?n.options.trueStr:n.options.falseStr}};function te({format:t,minFractionDigits:e,tag:n,value:r}){if(typeof r=="bigint")return String(r);let o=typeof r=="number"?r:Number(r);if(!isFinite(o))return isNaN(o)?".nan":o<0?"-.inf":".inf";let s=Object.is(r,-0)?"-0":JSON.stringify(r);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let i=s.indexOf(".");i<0&&(i=s.length,s+=".");let a=e-(s.length-i-1);for(;a-- >0;)s+="0"}return s}var Nr={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:te},$r={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():te(t)}},Tr={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new D(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:te};var zr=t=>typeof t=="bigint"||Number.isInteger(t),fs=(t,e,n,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),n);function _l(t,e,n){let{value:r}=t;return zr(r)&&r>=0?n+r.toString(e):te(t)}var Pr={identify:t=>zr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>fs(t,2,8,n),stringify:t=>_l(t,8,"0o")},Lr={identify:zr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>fs(t,0,10,n),stringify:te},Mr={identify:t=>zr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>fs(t,2,16,n),stringify:t=>_l(t,16,"0x")};var xl=[ke,De,ut,wt,Sn,Pr,Lr,Mr,Nr,$r,Tr];function Sl(t){return typeof t=="bigint"||Number.isInteger(t)}var Fr=({value:t})=>JSON.stringify(t),Im=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:Fr},{identify:t=>t==null,createNode:()=>new D(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Fr},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:Fr},{identify:Sl,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})=>Sl(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:Fr}],Cm={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Al=[ke,De].concat(Im,Cm);var An={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),r=new Uint8Array(n.length);for(let o=0;o<n.length;++o)r[o]=n.charCodeAt(o);return r}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:n},r,o,s){if(!n)return"";let i=n,a;if(typeof btoa=="function"){let c="";for(let u=0;u<i.length;++u)c+=String.fromCharCode(i[u]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=D.BLOCK_LITERAL),e!==D.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),u=Math.ceil(a.length/c),d=new Array(u);for(let l=0,f=0;l<u;++l,f+=c)d[l]=a.substr(f,c);a=d.join(e===D.BLOCK_LITERAL?`
-`:" ")}return bt({comment:t,type:e,value:a},r,o,s)}};function ds(t,e){if(Ee(t))for(let n=0;n<t.items.length;++n){let r=t.items[n];if(!T(r)){if(Ae(r)){r.items.length>1&&e("Each pair must have its own sequence indicator");let o=r.items[0]||new K(new D(null));if(r.commentBefore&&(o.key.commentBefore=o.key.commentBefore?`${r.commentBefore}
+${o}${p}`}else return`${f}${i}${l.join(" ")}${i}${p}`}function Ir({indent:t,options:{commentString:e}},n,r,o){if(r&&o&&(r=r.replace(/^\n+/,"")),r){let s=ge(e(r),t);n.push(s.trimStart())}}function ct(t,e){let n=N(e)?e.value:e;for(let r of t)if(T(r)&&(r.key===e||r.key===n||N(r.key)&&r.key.value===n))return r}var W=class extends Mt{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(xe,e),this.items=[]}static from(e,n,r){let{keepUndefined:o,replacer:s}=r,i=new this(e),a=(c,u)=>{if(typeof s=="function")u=s.call(n,c,u);else if(Array.isArray(s)&&!s.includes(c))return;(u!==void 0||o)&&i.items.push(jt(c,u,r))};if(n instanceof Map)for(let[c,u]of n)a(c,u);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&i.items.sort(e.sortMapEntries),i}add(e,n){let r;T(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new K(e,e?.value):r=new K(e.key,e.value);let o=ct(this.items,r.key),s=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${r.key} already set`);N(o.value)&&xr(r.value)?o.value.value=r.value:o.value=r.value}else if(s){let i=this.items.findIndex(a=>s(r,a)<0);i===-1?this.items.push(r):this.items.splice(i,0,r)}else this.items.push(r)}delete(e){let n=ct(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let o=ct(this.items,e)?.value;return(!n&&N(o)?o.value:o)??void 0}has(e){return!!ct(this.items,e)}set(e,n){this.add(new K(e,n),!0)}toJSON(e,n,r){let o=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(o);for(let s of this.items)Rr(n,o,s);return o}toString(e,n,r){if(!e)return JSON.stringify(this);for(let o of this.items)if(!T(o))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Or(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:n})}};var ke={collection:"map",default:!0,nodeClass:W,tag:"tag:yaml.org,2002:map",resolve(t,e){return Ae(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>W.from(t,e,n)};var ee=class extends Mt{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(qe,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=Cr(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let r=Cr(e);if(typeof r!="number")return;let o=this.items[r];return!n&&N(o)?o.value:o}has(e){let n=Cr(e);return typeof n=="number"&&n<this.items.length}set(e,n){let r=Cr(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);let o=this.items[r];N(o)&&xr(n)?o.value=n:this.items[r]=n}toJSON(e,n){let r=[];n?.onCreate&&n.onCreate(r);let o=0;for(let s of this.items)r.push(Y(s,String(o++),n));return r}toString(e,n,r){return e?Or(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(Ke(a,void 0,r))}}return s}};function Cr(t){let e=N(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}var De={collection:"seq",default:!0,nodeClass:ee,tag:"tag:yaml.org,2002:seq",resolve(t,e){return Ee(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>ee.from(t,e,n)};var ut={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,r){return e=Object.assign({actualString:!0},e),bt(t,e,n,r)}};var wt={identify:t=>t==null,createNode:()=>new D(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new D(null),stringify:({source:t},e)=>typeof t=="string"&&wt.test.test(t)?t:e.options.nullStr};var An={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new D(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&An.test.test(t)){let r=t[0]==="t"||t[0]==="T";if(e===r)return t}return e?n.options.trueStr:n.options.falseStr}};function te({format:t,minFractionDigits:e,tag:n,value:r}){if(typeof r=="bigint")return String(r);let o=typeof r=="number"?r:Number(r);if(!isFinite(o))return isNaN(o)?".nan":o<0?"-.inf":".inf";let s=Object.is(r,-0)?"-0":JSON.stringify(r);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let i=s.indexOf(".");i<0&&(i=s.length,s+=".");let a=e-(s.length-i-1);for(;a-- >0;)s+="0"}return s}var Nr={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:te},$r={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():te(t)}},Tr={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new D(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:te};var zr=t=>typeof t=="bigint"||Number.isInteger(t),ds=(t,e,n,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),n);function Al(t,e,n){let{value:r}=t;return zr(r)&&r>=0?n+r.toString(e):te(t)}var Pr={identify:t=>zr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>ds(t,2,8,n),stringify:t=>Al(t,8,"0o")},Lr={identify:zr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>ds(t,0,10,n),stringify:te},Mr={identify:t=>zr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>ds(t,2,16,n),stringify:t=>Al(t,16,"0x")};var El=[ke,De,ut,wt,An,Pr,Lr,Mr,Nr,$r,Tr];function vl(t){return typeof t=="bigint"||Number.isInteger(t)}var Fr=({value:t})=>JSON.stringify(t),Tm=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:Fr},{identify:t=>t==null,createNode:()=>new D(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Fr},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:Fr},{identify:vl,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})=>vl(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:Fr}],zm={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},kl=[ke,De].concat(Tm,zm);var En={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),r=new Uint8Array(n.length);for(let o=0;o<n.length;++o)r[o]=n.charCodeAt(o);return r}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:n},r,o,s){if(!n)return"";let i=n,a;if(typeof btoa=="function"){let c="";for(let u=0;u<i.length;++u)c+=String.fromCharCode(i[u]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=D.BLOCK_LITERAL),e!==D.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),u=Math.ceil(a.length/c),d=new Array(u);for(let l=0,f=0;l<u;++l,f+=c)d[l]=a.substr(f,c);a=d.join(e===D.BLOCK_LITERAL?`
+`:" ")}return bt({comment:t,type:e,value:a},r,o,s)}};function ps(t,e){if(Ee(t))for(let n=0;n<t.items.length;++n){let r=t.items[n];if(!T(r)){if(Ae(r)){r.items.length>1&&e("Each pair must have its own sequence indicator");let o=r.items[0]||new K(new D(null));if(r.commentBefore&&(o.key.commentBefore=o.key.commentBefore?`${r.commentBefore}
${o.key.commentBefore}`:r.commentBefore),r.comment){let s=o.value??o.key;s.comment=s.comment?`${r.comment}
-${s.comment}`:r.comment}r=o}t.items[n]=T(r)?r:new K(r)}}else e("Expected a sequence for this tag");return t}function ps(t,e,n){let{replacer:r}=n,o=new ee(t);o.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let i of e){typeof r=="function"&&(i=r.call(e,String(s++),i));let a,c;if(Array.isArray(i))if(i.length===2)a=i[0],c=i[1];else throw new TypeError(`Expected [key, value] tuple: ${i}`);else if(i&&i instanceof Object){let u=Object.keys(i);if(u.length===1)a=u[0],c=i[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=i;o.items.push(Zt(a,c,n))}return o}var En={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ds,createNode:ps};var jt=class t extends ee{constructor(){super(),this.add=W.prototype.add.bind(this),this.delete=W.prototype.delete.bind(this),this.get=W.prototype.get.bind(this),this.has=W.prototype.has.bind(this),this.set=W.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let r=new Map;n?.onCreate&&n.onCreate(r);for(let o of this.items){let s,i;if(T(o)?(s=Y(o.key,"",n),i=Y(o.value,s,n)):s=Y(o,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,i)}return r}static from(e,n,r){let o=ps(e,n,r),s=new this;return s.items=o.items,s}};jt.tag="tag:yaml.org,2002:omap";var vn={collection:"seq",identify:t=>t instanceof Map,nodeClass:jt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=ds(t,e),r=[];for(let{key:o}of n.items)N(o)&&(r.includes(o.value)?e(`Ordered maps must not include duplicate keys: ${o.value}`):r.push(o.value));return Object.assign(new jt,n)},createNode:(t,e,n)=>jt.from(t,e,n)};function El({value:t,source:e},n){return e&&(t?ms:hs).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var ms={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new D(!0),stringify:El},hs={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new D(!1),stringify:El};var vl={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:te},kl={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():te(t)}},Dl={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new D(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let r=t.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:te};var kn=t=>typeof t=="bigint"||Number.isInteger(t);function Zr(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 ys(t,e,n){let{value:r}=t;if(kn(r)){let o=r.toString(e);return r<0?"-"+n+o.substr(1):n+o}return te(t)}var Rl={identify:kn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>Zr(t,2,2,n),stringify:t=>ys(t,2,"0b")},Ol={identify:kn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>Zr(t,1,8,n),stringify:t=>ys(t,8,"0")},Il={identify:kn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>Zr(t,0,10,n),stringify:te},Cl={identify:kn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>Zr(t,2,16,n),stringify:t=>ys(t,16,"0x")};var Bt=class t extends W{constructor(e){super(e),this.tag=t.tag}add(e){let n;T(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new K(e.key,null):n=new K(e,null),ct(this.items,n.key)||this.items.push(n)}get(e,n){let r=ct(this.items,e);return!n&&T(r)?N(r.key)?r.key.value:r.key:r}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=ct(this.items,e);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new K(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(e,n,r){let{replacer:o}=r,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let i of n)typeof o=="function"&&(i=o.call(n,i,i)),s.items.push(Zt(i,null,r));return s}};Bt.tag="tag:yaml.org,2002:set";var Dn={collection:"map",identify:t=>t instanceof Set,nodeClass:Bt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>Bt.from(t,e,n),resolve(t,e){if(Ae(t)){if(t.hasAllNullValues(!0))return Object.assign(new Bt,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};function gs(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 Nl(t){let{value:e}=t,n=i=>i;if(typeof e=="bigint")n=i=>BigInt(i);else if(isNaN(e)||!isFinite(e))return te(t);let r="";e<0&&(r="-",e*=n(-1));let o=n(60),s=[e%o];return e<60?s.unshift(0):(e=(e-s[0])/o,s.unshift(e%o),e>=60&&(e=(e-s[0])/o,s.unshift(e))),r+s.map(i=>String(i).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var jr={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>gs(t,n),stringify:Nl},Br={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=>gs(t,!1),stringify:Nl},Ut={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(Ut.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=gs(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 bs=[ke,De,ut,wt,ms,hs,Rl,Ol,Il,Cl,vl,kl,Dl,An,ve,vn,En,Dn,jr,Br,Ut];var $l=new Map([["core",xl],["failsafe",[ke,De,ut]],["json",Al],["yaml11",bs],["yaml-1.1",bs]]),Tl={binary:An,bool:Sn,float:Tr,floatExp:$r,floatNaN:Nr,floatTime:Br,int:Lr,intHex:Mr,intOct:Pr,intTime:jr,map:ke,merge:ve,null:wt,omap:vn,pairs:En,seq:De,set:Dn,timestamp:Ut},zl={"tag:yaml.org,2002:binary":An,"tag:yaml.org,2002:merge":ve,"tag:yaml.org,2002:omap":vn,"tag:yaml.org,2002:pairs":En,"tag:yaml.org,2002:set":Dn,"tag:yaml.org,2002:timestamp":Ut};function Ur(t,e,n){let r=$l.get(e);if(r&&!t)return n&&!r.includes(ve)?r.concat(ve):r.slice();let o=r;if(!o)if(Array.isArray(t))o=[];else{let s=Array.from($l.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(ve)),o.reduce((s,i)=>{let a=typeof i=="string"?Tl[i]:i;if(!a){let c=JSON.stringify(i),u=Object.keys(Tl).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 Nm=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,Rn=class t{constructor({compat:e,customTags:n,merge:r,resolveKnownTags:o,schema:s,sortMapEntries:i,toStringDefaults:a}){this.compat=Array.isArray(e)?Ur(e,"compat"):e?Ur(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=o?zl:{},this.tags=Ur(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,xe,{value:ke}),Object.defineProperty(this,me,{value:ut}),Object.defineProperty(this,qe,{value:De}),this.sortMapEntries=typeof i=="function"?i:i===!0?Nm:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function Pl(t,e){let n=[],r=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),r=!0):t.directives.docStart&&(r=!0)}r&&n.push("---");let o=kr(t,e),{commentString:s}=o.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(ge(c,""))}let i=!1,a=null;if(t.contents){if(P(t.contents)){if(t.contents.spaceBefore&&r&&n.push(""),t.contents.commentBefore){let d=s(t.contents.commentBefore);n.push(ge(d,""))}o.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>i=!0,u=We(t.contents,o,()=>a=null,c);a&&(u+=Ze(u,"",s(a))),(u[0]==="|"||u[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${u}`:n.push(u)}else n.push(We(t.contents,o));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(`
+${s.comment}`:r.comment}r=o}t.items[n]=T(r)?r:new K(r)}}else e("Expected a sequence for this tag");return t}function ms(t,e,n){let{replacer:r}=n,o=new ee(t);o.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let i of e){typeof r=="function"&&(i=r.call(e,String(s++),i));let a,c;if(Array.isArray(i))if(i.length===2)a=i[0],c=i[1];else throw new TypeError(`Expected [key, value] tuple: ${i}`);else if(i&&i instanceof Object){let u=Object.keys(i);if(u.length===1)a=u[0],c=i[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=i;o.items.push(jt(a,c,n))}return o}var vn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ps,createNode:ms};var Bt=class t extends ee{constructor(){super(),this.add=W.prototype.add.bind(this),this.delete=W.prototype.delete.bind(this),this.get=W.prototype.get.bind(this),this.has=W.prototype.has.bind(this),this.set=W.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let r=new Map;n?.onCreate&&n.onCreate(r);for(let o of this.items){let s,i;if(T(o)?(s=Y(o.key,"",n),i=Y(o.value,s,n)):s=Y(o,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,i)}return r}static from(e,n,r){let o=ms(e,n,r),s=new this;return s.items=o.items,s}};Bt.tag="tag:yaml.org,2002:omap";var kn={collection:"seq",identify:t=>t instanceof Map,nodeClass:Bt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=ps(t,e),r=[];for(let{key:o}of n.items)N(o)&&(r.includes(o.value)?e(`Ordered maps must not include duplicate keys: ${o.value}`):r.push(o.value));return Object.assign(new Bt,n)},createNode:(t,e,n)=>Bt.from(t,e,n)};function Dl({value:t,source:e},n){return e&&(t?hs:ys).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var hs={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new D(!0),stringify:Dl},ys={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new D(!1),stringify:Dl};var Rl={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:te},Il={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():te(t)}},Ol={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new D(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let r=t.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:te};var Dn=t=>typeof t=="bigint"||Number.isInteger(t);function Zr(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 gs(t,e,n){let{value:r}=t;if(Dn(r)){let o=r.toString(e);return r<0?"-"+n+o.substr(1):n+o}return te(t)}var Cl={identify:Dn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>Zr(t,2,2,n),stringify:t=>gs(t,2,"0b")},Nl={identify:Dn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>Zr(t,1,8,n),stringify:t=>gs(t,8,"0")},$l={identify:Dn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>Zr(t,0,10,n),stringify:te},Tl={identify:Dn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>Zr(t,2,16,n),stringify:t=>gs(t,16,"0x")};var Ut=class t extends W{constructor(e){super(e),this.tag=t.tag}add(e){let n;T(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new K(e.key,null):n=new K(e,null),ct(this.items,n.key)||this.items.push(n)}get(e,n){let r=ct(this.items,e);return!n&&T(r)?N(r.key)?r.key.value:r.key:r}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=ct(this.items,e);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new K(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(e,n,r){let{replacer:o}=r,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let i of n)typeof o=="function"&&(i=o.call(n,i,i)),s.items.push(jt(i,null,r));return s}};Ut.tag="tag:yaml.org,2002:set";var Rn={collection:"map",identify:t=>t instanceof Set,nodeClass:Ut,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>Ut.from(t,e,n),resolve(t,e){if(Ae(t)){if(t.hasAllNullValues(!0))return Object.assign(new Ut,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};function bs(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 zl(t){let{value:e}=t,n=i=>i;if(typeof e=="bigint")n=i=>BigInt(i);else if(isNaN(e)||!isFinite(e))return te(t);let r="";e<0&&(r="-",e*=n(-1));let o=n(60),s=[e%o];return e<60?s.unshift(0):(e=(e-s[0])/o,s.unshift(e%o),e>=60&&(e=(e-s[0])/o,s.unshift(e))),r+s.map(i=>String(i).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var jr={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>bs(t,n),stringify:zl},Br={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=>bs(t,!1),stringify:zl},Qt={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(Qt.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,o,s,i,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,u=Date.UTC(n,r-1,o,s||0,i||0,a||0,c),d=e[8];if(d&&d!=="Z"){let l=bs(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 ws=[ke,De,ut,wt,hs,ys,Cl,Nl,$l,Tl,Rl,Il,Ol,En,ve,kn,vn,Rn,jr,Br,Qt];var Pl=new Map([["core",El],["failsafe",[ke,De,ut]],["json",kl],["yaml11",ws],["yaml-1.1",ws]]),Ll={binary:En,bool:An,float:Tr,floatExp:$r,floatNaN:Nr,floatTime:Br,int:Lr,intHex:Mr,intOct:Pr,intTime:jr,map:ke,merge:ve,null:wt,omap:kn,pairs:vn,seq:De,set:Rn,timestamp:Qt},Ml={"tag:yaml.org,2002:binary":En,"tag:yaml.org,2002:merge":ve,"tag:yaml.org,2002:omap":kn,"tag:yaml.org,2002:pairs":vn,"tag:yaml.org,2002:set":Rn,"tag:yaml.org,2002:timestamp":Qt};function Ur(t,e,n){let r=Pl.get(e);if(r&&!t)return n&&!r.includes(ve)?r.concat(ve):r.slice();let o=r;if(!o)if(Array.isArray(t))o=[];else{let s=Array.from(Pl.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(ve)),o.reduce((s,i)=>{let a=typeof i=="string"?Ll[i]:i;if(!a){let c=JSON.stringify(i),u=Object.keys(Ll).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 Pm=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,In=class t{constructor({compat:e,customTags:n,merge:r,resolveKnownTags:o,schema:s,sortMapEntries:i,toStringDefaults:a}){this.compat=Array.isArray(e)?Ur(e,"compat"):e?Ur(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=o?Ml:{},this.tags=Ur(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,xe,{value:ke}),Object.defineProperty(this,me,{value:ut}),Object.defineProperty(this,qe,{value:De}),this.sortMapEntries=typeof i=="function"?i:i===!0?Pm:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function Fl(t,e){let n=[],r=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),r=!0):t.directives.docStart&&(r=!0)}r&&n.push("---");let o=kr(t,e),{commentString:s}=o.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(ge(c,""))}let i=!1,a=null;if(t.contents){if(P(t.contents)){if(t.contents.spaceBefore&&r&&n.push(""),t.contents.commentBefore){let d=s(t.contents.commentBefore);n.push(ge(d,""))}o.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>i=!0,u=We(t.contents,o,()=>a=null,c);a&&(u+=je(u,"",s(a))),(u[0]==="|"||u[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${u}`:n.push(u)}else n.push(We(t.contents,o));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(`
`)?(n.push("..."),n.push(ge(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(ge(s(c),"")))}return n.join(`
`)+`
-`}var lt=class t{constructor(e,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,oe,{value:yr});let o=null;typeof n=="function"||Array.isArray(n)?o=n:r===void 0&&n&&(r=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=s;let{version:i}=s;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(i=this.directives.yaml.version)):this.directives=new Fe({version:i}),this.setSchema(i,r),this.contents=e===void 0?null:this.createNode(e,o,r)}clone(){let e=Object.create(t.prototype,{[oe]:{value:yr}});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=P(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Qt(this.contents)&&this.contents.add(e)}addIn(e,n){Qt(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let r=rs(this);e.anchor=!n||r.has(n)?os(n||"a",r):n}return new Je(e.anchor)}createNode(e,n,r){let o;if(typeof n=="function")e=n.call({"":e},"",e),o=n;else if(Array.isArray(n)){let h=S=>typeof S=="number"||S instanceof String||S instanceof Number,w=n.filter(h).map(String);w.length>0&&(n=n.concat(w)),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"),y={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:l,onTagObj:u,replacer:o,schema:this.schema,sourceObjects:p},m=Ke(e,d,y);return a&&Z(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 Qt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Mt(e)?this.contents==null?!1:(this.contents=null,!0):Qt(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return Z(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return Mt(e)?!n&&N(this.contents)?this.contents.value:this.contents:Z(this.contents)?this.contents.getIn(e,n):void 0}has(e){return Z(this.contents)?this.contents.has(e):!1}hasIn(e){return Mt(e)?this.contents!==void 0:Z(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=bn(this.schema,[e],n):Qt(this.contents)&&this.contents.set(e,n)}setIn(e,n){Mt(e)?this.contents=n:this.contents==null?this.contents=bn(this.schema,Array.from(e),n):Qt(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let r;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Fe({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Fe({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let o=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${o}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(r)this.schema=new Rn(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:r,maxAliasCount:o,onAnchor:s,reviver:i}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof o=="number"?o:100},c=Y(this.contents,n??"",a);if(typeof s=="function")for(let{count:u,res:d}of a.anchors.values())s(d,u);return typeof i=="function"?it(i,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return Pl(this,e)}};function Qt(t){if(Z(t))return!0;throw new Error("Expected a YAML collection as document contents")}var On=class extends Error{constructor(e,n,r,o){super(),this.name=e,this.code=r,this.message=o,this.pos=n}},Re=class extends On{constructor(e,n,r){super("YAMLParseError",e,n,r)}},In=class extends On{constructor(e,n,r){super("YAMLWarning",e,n,r)}},ws=(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 lt=class t{constructor(e,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,oe,{value:yr});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,{[oe]:{value:yr}});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=P(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Gt(this.contents)&&this.contents.add(e)}addIn(e,n){Gt(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let r=os(this);e.anchor=!n||r.has(n)?ss(n||"a",r):n}return new Je(e.anchor)}createNode(e,n,r){let o;if(typeof n=="function")e=n.call({"":e},"",e),o=n;else if(Array.isArray(n)){let h=S=>typeof S=="number"||S instanceof String||S instanceof Number,b=n.filter(h).map(String);b.length>0&&(n=n.concat(b)),o=n}else r===void 0&&n&&(r=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:i,flow:a,keepUndefined:c,onTagObj:u,tag:d}=r??{},{onAnchor:l,setAnchors:f,sourceObjects:p}=gl(this,i||"a"),y={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:l,onTagObj:u,replacer:o,schema:this.schema,sourceObjects:p},m=Ke(e,d,y);return a&&j(m)&&(m.flow=!0),f(),m}createPair(e,n,r={}){let o=this.createNode(e,null,r),s=this.createNode(n,null,r);return new K(o,s)}delete(e){return Gt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ft(e)?this.contents==null?!1:(this.contents=null,!0):Gt(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return j(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return Ft(e)?!n&&N(this.contents)?this.contents.value:this.contents:j(this.contents)?this.contents.getIn(e,n):void 0}has(e){return j(this.contents)?this.contents.has(e):!1}hasIn(e){return Ft(e)?this.contents!==void 0:j(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=wn(this.schema,[e],n):Gt(this.contents)&&this.contents.set(e,n)}setIn(e,n){Ft(e)?this.contents=n:this.contents==null?this.contents=wn(this.schema,Array.from(e),n):Gt(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let r;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new 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 In(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:r,maxAliasCount:o,onAnchor:s,reviver:i}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof o=="number"?o:100},c=Y(this.contents,n??"",a);if(typeof s=="function")for(let{count:u,res:d}of a.anchors.values())s(d,u);return typeof i=="function"?it(i,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return Fl(this,e)}};function Gt(t){if(j(t))return!0;throw new Error("Expected a YAML collection as document contents")}var On=class extends Error{constructor(e,n,r,o){super(),this.name=e,this.code=r,this.message=o,this.pos=n}},Re=class extends On{constructor(e,n,r){super("YAMLParseError",e,n,r)}},Cn=class extends On{constructor(e,n,r){super("YAMLWarning",e,n,r)}},_s=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:r,col:o}=n.linePos[0];n.message+=` at line ${r}, column ${o}`;let s=o-1,i=t.substring(e.lineStarts[r-1],e.lineStarts[r]).replace(/[\n\r]+$/,"");if(s>=60&&i.length>80){let a=Math.min(s-39,i.length-79);i="\u2026"+i.substring(a),s-=a-1}if(i.length>80&&(i=i.substring(0,79)+"\u2026"),r>1&&/^ *$/.test(i.substring(0,s))){let a=t.substring(e.lineStarts[r-2],e.lineStarts[r-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
`),i=a+i}if(/[^ ]/.test(i)){let a=1,c=n.linePos[1];c?.line===r&&c.col>o&&(a=Math.max(1,Math.min(c.col-o,80-s)));let u=" ".repeat(s)+"^".repeat(a);n.message+=`:
${i}
${u}
-`}};function 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,y=!1,m=null,h=null,w=null,S=null,A=null,_=null,b=null;for(let x of t)switch(y&&(x.type!=="space"&&x.type!=="newline"&&x.type!=="comma"&&s(x.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),m&&(u&&x.type!=="comment"&&x.type!=="newline"&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),x.type){case"space":!e&&(n!=="doc-start"||r?.type!=="flow-collection")&&x.source.includes(" ")&&(m=x),d=!0;break;case"comment":{d||s(x,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let I=x.source.substring(1)||" ";l?l+=f+I:l=I,f="",u=!1;break}case"newline":u?l?l+=x.source:(!_||n!=="seq-item-ind")&&(c=!0):f+=x.source,u=!0,p=!0,(h||w)&&(S=x),d=!0;break;case"anchor":h&&s(x,"MULTIPLE_ANCHORS","A node can have at most one anchor"),x.source.endsWith(":")&&s(x.offset+x.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),h=x,b??(b=x.offset),u=!1,d=!1,y=!0;break;case"tag":{w&&s(x,"MULTIPLE_TAGS","A node can have at most one tag"),w=x,b??(b=x.offset),u=!1,d=!1,y=!0;break}case n:(h||w)&&s(x,"BAD_PROP_ORDER",`Anchors and tags must be after the ${x.source} indicator`),_&&s(x,"UNEXPECTED_TOKEN",`Unexpected ${x.source} in ${e??"collection"}`),_=x,u=n==="seq-item-ind"||n==="explicit-key-ind",d=!1;break;case"comma":if(e){A&&s(x,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),A=x,u=!1,d=!1;break}default:s(x,"UNEXPECTED_TOKEN",`Unexpected ${x.type} token`),u=!1,d=!1}let E=t[t.length-1],k=E?E.offset+E.source.length:o;return y&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&s(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(u&&m.indent<=i||r?.type==="block-map"||r?.type==="block-seq")&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:A,found:_,spaceBefore:c,comment:l,hasNewline:p,anchor:h,tag:w,newlineAfterProp:S,end:k,start:b??k}}function ft(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`
-`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(ft(e.key)||ft(e.value))return!0}return!1;default:return!0}}function Cn(t,e,n){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&ft(e)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function Qr(t,e,n){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let o=typeof r=="function"?r:(s,i)=>s===i||N(s)&&N(i)&&s.value===i.value;return e.some(s=>o(s.key,n))}var Ll="All mapping items must start at the same column";function Ml({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=s?.nodeClass??W,a=new i(n.schema);n.atRoot&&(n.atRoot=!1);let c=r.offset,u=null;for(let d of r.items){let{start:l,key:f,sep:p,value:y}=d,m=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",Ll)),!m.anchor&&!m.tag&&!p){u=m.end,m.comment&&(a.comment?a.comment+=`
-`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||ft(f))&&o(f??l[l.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==r.indent&&o(c,"BAD_INDENT",Ll);n.atKey=!0;let w=m.end,S=f?t(n,f,m,o):e(n,w,l,null,m,o);n.schema.compat&&Cn(r.indent,f,o),n.atKey=!1,Qr(n,a.items,S)&&o(w,"DUPLICATE_KEY","Map keys must be unique");let A=je(p??[],{indicator:"map-value-ind",next:y,offset:S.range[2],onError:o,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=A.end,A.found){h&&(y?.type==="block-map"&&!A.hasNewline&&o(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&m.start<A.found.offset-1024&&o(S.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let _=y?t(n,y,A,o):e(n,c,p,null,A,o);n.schema.compat&&Cn(r.indent,y,o),c=_.range[2];let b=new K(S,_);n.options.keepSourceTokens&&(b.srcToken=d),a.items.push(b)}else{h&&o(S.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),A.comment&&(S.comment?S.comment+=`
-`+A.comment:S.comment=A.comment);let _=new K(S);n.options.keepSourceTokens&&(_.srcToken=d),a.items.push(_)}}return u&&u<c&&o(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,c,u??c],a}function Fl({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=s?.nodeClass??ee,a=new i(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=r.offset,u=null;for(let{start:d,value:l}of r.items){let f=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&&Cn(r.indent,l,o),c=p.range[2],a.items.push(p)}return a.range=[r.offset,c,u??c],a}function Be(t,e,n,r){let o="";if(t){let s=!1,i="";for(let a of t){let{source:c,type:u}=a;switch(u){case"space":s=!0;break;case"comment":{n&&!s&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=c.substring(1)||" ";o?o+=i+d:o=d,i="";break}case"newline":o&&(i+=c),s=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=c.length}}return{comment:o,offset:e}}var _s="Block collections are not allowed within flow collections",xs=t=>t&&(t.type==="block-map"||t.type==="block-seq");function Zl({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=r.start.source==="{",a=i?"flow map":"flow sequence",c=s?.nodeClass??(i?W:ee),u=new c(n.schema);u.flow=!0;let d=n.atRoot;d&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let l=r.offset+r.start.source.length;for(let h=0;h<r.items.length;++h){let w=r.items[h],{start:S,key:A,sep:_,value:b}=w,E=je(S,{flow:a,indicator:"explicit-key-ind",next:A??_?.[0],offset:l,onError:o,parentIndent:r.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!_&&!b){h===0&&E.comma?o(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):h<r.items.length-1&&o(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),E.comment&&(u.comment?u.comment+=`
+`}};function Be(t,{flow:e,indicator:n,next:r,offset:o,onError:s,parentIndent:i,startOnNewline:a}){let c=!1,u=a,d=a,l="",f="",p=!1,y=!1,m=null,h=null,b=null,S=null,A=null,_=null,w=null;for(let x of t)switch(y&&(x.type!=="space"&&x.type!=="newline"&&x.type!=="comma"&&s(x.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),m&&(u&&x.type!=="comment"&&x.type!=="newline"&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),x.type){case"space":!e&&(n!=="doc-start"||r?.type!=="flow-collection")&&x.source.includes(" ")&&(m=x),d=!0;break;case"comment":{d||s(x,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let O=x.source.substring(1)||" ";l?l+=f+O:l=O,f="",u=!1;break}case"newline":u?l?l+=x.source:(!_||n!=="seq-item-ind")&&(c=!0):f+=x.source,u=!0,p=!0,(h||b)&&(S=x),d=!0;break;case"anchor":h&&s(x,"MULTIPLE_ANCHORS","A node can have at most one anchor"),x.source.endsWith(":")&&s(x.offset+x.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),h=x,w??(w=x.offset),u=!1,d=!1,y=!0;break;case"tag":{b&&s(x,"MULTIPLE_TAGS","A node can have at most one tag"),b=x,w??(w=x.offset),u=!1,d=!1,y=!0;break}case n:(h||b)&&s(x,"BAD_PROP_ORDER",`Anchors and tags must be after the ${x.source} indicator`),_&&s(x,"UNEXPECTED_TOKEN",`Unexpected ${x.source} in ${e??"collection"}`),_=x,u=n==="seq-item-ind"||n==="explicit-key-ind",d=!1;break;case"comma":if(e){A&&s(x,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),A=x,u=!1,d=!1;break}default:s(x,"UNEXPECTED_TOKEN",`Unexpected ${x.type} token`),u=!1,d=!1}let E=t[t.length-1],k=E?E.offset+E.source.length:o;return y&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&s(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(u&&m.indent<=i||r?.type==="block-map"||r?.type==="block-seq")&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:A,found:_,spaceBefore:c,comment:l,hasNewline:p,anchor:h,tag:b,newlineAfterProp:S,end:k,start:w??k}}function ft(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`
+`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(ft(e.key)||ft(e.value))return!0}return!1;default:return!0}}function Nn(t,e,n){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&ft(e)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function Qr(t,e,n){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let o=typeof r=="function"?r:(s,i)=>s===i||N(s)&&N(i)&&s.value===i.value;return e.some(s=>o(s.key,n))}var Zl="All mapping items must start at the same column";function jl({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=s?.nodeClass??W,a=new i(n.schema);n.atRoot&&(n.atRoot=!1);let c=r.offset,u=null;for(let d of r.items){let{start:l,key:f,sep:p,value:y}=d,m=Be(l,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:o,parentIndent:r.indent,startOnNewline:!0}),h=!m.found;if(h){if(f&&(f.type==="block-seq"?o(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&o(c,"BAD_INDENT",Zl)),!m.anchor&&!m.tag&&!p){u=m.end,m.comment&&(a.comment?a.comment+=`
+`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||ft(f))&&o(f??l[l.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==r.indent&&o(c,"BAD_INDENT",Zl);n.atKey=!0;let b=m.end,S=f?t(n,f,m,o):e(n,b,l,null,m,o);n.schema.compat&&Nn(r.indent,f,o),n.atKey=!1,Qr(n,a.items,S)&&o(b,"DUPLICATE_KEY","Map keys must be unique");let A=Be(p??[],{indicator:"map-value-ind",next:y,offset:S.range[2],onError:o,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=A.end,A.found){h&&(y?.type==="block-map"&&!A.hasNewline&&o(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&m.start<A.found.offset-1024&&o(S.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let _=y?t(n,y,A,o):e(n,c,p,null,A,o);n.schema.compat&&Nn(r.indent,y,o),c=_.range[2];let w=new K(S,_);n.options.keepSourceTokens&&(w.srcToken=d),a.items.push(w)}else{h&&o(S.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),A.comment&&(S.comment?S.comment+=`
+`+A.comment:S.comment=A.comment);let _=new K(S);n.options.keepSourceTokens&&(_.srcToken=d),a.items.push(_)}}return u&&u<c&&o(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,c,u??c],a}function Bl({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=s?.nodeClass??ee,a=new i(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=r.offset,u=null;for(let{start:d,value:l}of r.items){let f=Be(d,{indicator:"seq-item-ind",next:l,offset:c,onError:o,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||l)l?.type==="block-seq"?o(f.end,"BAD_INDENT","All sequence items must start at the same column"):o(c,"MISSING_CHAR","Sequence item without - indicator");else{u=f.end,f.comment&&(a.comment=f.comment);continue}let p=l?t(n,l,f,o):e(n,f.end,d,null,f,o);n.schema.compat&&Nn(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 xs="Block collections are not allowed within flow collections",Ss=t=>t&&(t.type==="block-map"||t.type==="block-seq");function Ul({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=r.start.source==="{",a=i?"flow map":"flow sequence",c=s?.nodeClass??(i?W:ee),u=new c(n.schema);u.flow=!0;let d=n.atRoot;d&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let l=r.offset+r.start.source.length;for(let h=0;h<r.items.length;++h){let b=r.items[h],{start:S,key:A,sep:_,value:w}=b,E=Be(S,{flow:a,indicator:"explicit-key-ind",next:A??_?.[0],offset:l,onError:o,parentIndent:r.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!_&&!w){h===0&&E.comma?o(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):h<r.items.length-1&&o(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),E.comment&&(u.comment?u.comment+=`
`+E.comment:u.comment=E.comment),l=E.end;continue}!i&&n.options.strict&&ft(A)&&o(A,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(h===0)E.comma&&o(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(E.comma||o(E.start,"MISSING_CHAR",`Missing , between ${a} items`),E.comment){let k="";e:for(let x of S)switch(x.type){case"comma":case"space":break;case"comment":k=x.source.substring(1);break e;default:break e}if(k){let x=u.items[u.items.length-1];T(x)&&(x=x.value??x.key),x.comment?x.comment+=`
-`+k:x.comment=k,E.comment=E.comment.substring(k.length+1)}}if(!i&&!_&&!E.found){let k=b?t(n,b,E,o):e(n,E.end,_,null,E,o);u.items.push(k),l=k.range[2],xs(b)&&o(k.range,"BLOCK_IN_FLOW",_s)}else{n.atKey=!0;let k=E.end,x=A?t(n,A,E,o):e(n,k,S,null,E,o);xs(A)&&o(x.range,"BLOCK_IN_FLOW",_s),n.atKey=!1;let I=je(_??[],{flow:a,indicator:"map-value-ind",next:b,offset:x.range[2],onError:o,parentIndent:r.indent,startOnNewline:!1});if(I.found){if(!i&&!E.found&&n.options.strict){if(_)for(let $ of _){if($===I.found)break;if($.type==="newline"){o($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.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 b&&("source"in b&&b.source?.[0]===":"?o(b,"MISSING_CHAR",`Missing space after : in ${a}`):o(I.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let M=b?t(n,b,I,o):I.found?e(n,I.end,_,null,I,o):null;M?xs(b)&&o(M.range,"BLOCK_IN_FLOW",_s):I.comment&&(x.comment?x.comment+=`
-`+I.comment:x.comment=I.comment);let B=new K(x,M);if(n.options.keepSourceTokens&&(B.srcToken=w),i){let $=u;Qr(n,$.items,x)&&o(k,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(B)}else{let $=new W(n.schema);$.flow=!0,$.items.push(B);let ae=(M??x).range;$.range=[x.range[0],ae[1],ae[2]],u.items.push($)}l=M?M.range[2]:I.end}}let f=i?"}":"]",[p,...y]=r.end,m=l;if(p?.source===f)m=p.offset+p.source.length;else{let h=a[0].toUpperCase()+a.substring(1),w=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",w),p&&p.source.length!==1&&y.unshift(p)}if(y.length>0){let h=Be(y,m,n.options.strict,o);h.comment&&(u.comment?u.comment+=`
-`+h.comment:u.comment=h.comment),u.range=[r.offset,m,h.offset]}else u.range=[r.offset,m,m];return u}function Ss(t,e,n,r,o,s){let i=n.type==="block-map"?Ml(t,e,n,r,s):n.type==="block-seq"?Fl(t,e,n,r,s):Zl(t,e,n,r,s),a=i.constructor;return o==="!"||o===a.tagName?(i.tag=a.tagName,i):(o&&(i.tag=o),i)}function jl(t,e,n,r,o){let s=r.tag,i=s?e.directives.tagName(s.source,f=>o(s,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=r,y=f&&s?f.offset>s.offset?f:s:f??s;y&&(!p||p.offset<y.offset)&&o(y,"MISSING_CHAR","Missing newline after block sequence props")}let a=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!s||!i||i==="!"||i===W.tagName&&a==="map"||i===ee.tagName&&a==="seq")return Ss(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),Ss(t,e,n,o,i)}let u=Ss(t,e,n,o,i,c),d=c.resolve?.(u,f=>o(s,"TAG_RESOLVE_FAILED",f),e.options)??u,l=P(d)?d:new D(d);return l.range=u.range,l.tag=i,c?.format&&(l.format=c.format),l}function As(t,e,n){let r=e.offset,o=$m(e,t.options.strict,n);if(!o)return{value:"",type:null,comment:"",range:[r,r,r]};let s=o.mode===">"?D.BLOCK_FOLDED:D.BLOCK_LITERAL,i=e.source?Tm(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,w]=i[m];if(w===""||w==="\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+w.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,w]=i[m];u+=h.length+w.length+1;let S=w[w.length-1]==="\r";if(S&&(w=w.slice(0,-1)),w&&h.length<c){let _=`Block scalar lines must not be less indented than their ${o.indent?"explicit indentation indicator":"first line"}`;n(u-w.length-(S?2:1),"BAD_INDENT",_),h=""}s===D.BLOCK_LITERAL?(l+=f+h.slice(c)+w,f=`
-`):h.length>c||w[0]===" "?(f===" "?f=`
+`+k:x.comment=k,E.comment=E.comment.substring(k.length+1)}}if(!i&&!_&&!E.found){let k=w?t(n,w,E,o):e(n,E.end,_,null,E,o);u.items.push(k),l=k.range[2],Ss(w)&&o(k.range,"BLOCK_IN_FLOW",xs)}else{n.atKey=!0;let k=E.end,x=A?t(n,A,E,o):e(n,k,S,null,E,o);Ss(A)&&o(x.range,"BLOCK_IN_FLOW",xs),n.atKey=!1;let O=Be(_??[],{flow:a,indicator:"map-value-ind",next:w,offset:x.range[2],onError:o,parentIndent:r.indent,startOnNewline:!1});if(O.found){if(!i&&!E.found&&n.options.strict){if(_)for(let $ of _){if($===O.found)break;if($.type==="newline"){o($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<O.found.offset-1024&&o(O.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else w&&("source"in w&&w.source?.[0]===":"?o(w,"MISSING_CHAR",`Missing space after : in ${a}`):o(O.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let M=w?t(n,w,O,o):O.found?e(n,O.end,_,null,O,o):null;M?Ss(w)&&o(M.range,"BLOCK_IN_FLOW",xs):O.comment&&(x.comment?x.comment+=`
+`+O.comment:x.comment=O.comment);let B=new K(x,M);if(n.options.keepSourceTokens&&(B.srcToken=b),i){let $=u;Qr(n,$.items,x)&&o(k,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(B)}else{let $=new W(n.schema);$.flow=!0,$.items.push(B);let ae=(M??x).range;$.range=[x.range[0],ae[1],ae[2]],u.items.push($)}l=M?M.range[2]:O.end}}let f=i?"}":"]",[p,...y]=r.end,m=l;if(p?.source===f)m=p.offset+p.source.length;else{let h=a[0].toUpperCase()+a.substring(1),b=d?`${h} must end with a ${f}`:`${h} in block collection must be sufficiently indented and end with a ${f}`;o(l,d?"MISSING_CHAR":"BAD_INDENT",b),p&&p.source.length!==1&&y.unshift(p)}if(y.length>0){let h=Ue(y,m,n.options.strict,o);h.comment&&(u.comment?u.comment+=`
+`+h.comment:u.comment=h.comment),u.range=[r.offset,m,h.offset]}else u.range=[r.offset,m,m];return u}function As(t,e,n,r,o,s){let i=n.type==="block-map"?jl(t,e,n,r,s):n.type==="block-seq"?Bl(t,e,n,r,s):Ul(t,e,n,r,s),a=i.constructor;return o==="!"||o===a.tagName?(i.tag=a.tagName,i):(o&&(i.tag=o),i)}function Ql(t,e,n,r,o){let s=r.tag,i=s?e.directives.tagName(s.source,f=>o(s,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=r,y=f&&s?f.offset>s.offset?f:s:f??s;y&&(!p||p.offset<y.offset)&&o(y,"MISSING_CHAR","Missing newline after block sequence props")}let a=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!s||!i||i==="!"||i===W.tagName&&a==="map"||i===ee.tagName&&a==="seq")return As(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),As(t,e,n,o,i)}let u=As(t,e,n,o,i,c),d=c.resolve?.(u,f=>o(s,"TAG_RESOLVE_FAILED",f),e.options)??u,l=P(d)?d:new D(d);return l.range=u.range,l.tag=i,c?.format&&(l.format=c.format),l}function Es(t,e,n){let r=e.offset,o=Lm(e,t.options.strict,n);if(!o)return{value:"",type:null,comment:"",range:[r,r,r]};let s=o.mode===">"?D.BLOCK_FOLDED:D.BLOCK_LITERAL,i=e.source?Mm(e.source):[],a=i.length;for(let m=i.length-1;m>=0;--m){let h=i[m][1];if(h===""||h==="\r")a=m;else break}if(a===0){let m=o.chomp==="+"&&i.length>0?`
+`.repeat(Math.max(1,i.length-1)):"",h=r+o.length;return e.source&&(h+=e.source.length),{value:m,type:s,comment:o.comment,range:[r,h,h]}}let c=e.indent+o.indent,u=e.offset+o.length,d=0;for(let m=0;m<a;++m){let[h,b]=i[m];if(b===""||b==="\r")o.indent===0&&h.length>c&&(c=h.length);else{h.length<c&&n(u+h.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),o.indent===0&&(c=h.length),d=m,c===0&&!t.atRoot&&n(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=h.length+b.length+1}for(let m=i.length-1;m>=a;--m)i[m][0].length>c&&(a=m+1);let l="",f="",p=!1;for(let m=0;m<d;++m)l+=i[m][0].slice(c)+`
+`;for(let m=d;m<a;++m){let[h,b]=i[m];u+=h.length+b.length+1;let S=b[b.length-1]==="\r";if(S&&(b=b.slice(0,-1)),b&&h.length<c){let _=`Block scalar lines must not be less indented than their ${o.indent?"explicit indentation indicator":"first line"}`;n(u-b.length-(S?2:1),"BAD_INDENT",_),h=""}s===D.BLOCK_LITERAL?(l+=f+h.slice(c)+b,f=`
+`):h.length>c||b[0]===" "?(f===" "?f=`
`:!p&&f===`
`&&(f=`
-`),l+=f+h.slice(c)+w,f=`
-`,p=!0):w===""?f===`
+`),l+=f+h.slice(c)+b,f=`
+`,p=!0):b===""?f===`
`?l+=`
`:f=`
-`:(l+=f+w,f=" ",p=!1)}switch(o.chomp){case"-":break;case"+":for(let m=a;m<i.length;++m)l+=`
+`:(l+=f+b,f=" ",p=!1)}switch(o.chomp){case"-":break;case"+":for(let m=a;m<i.length;++m)l+=`
`+i[m][0].slice(c);l[l.length-1]!==`
`&&(l+=`
`);break;default:l+=`
-`}let y=r+o.length+e.source.length;return{value:l,type:s,comment:o.comment,range:[r,y,y]}}function $m({offset:t,props:e},n,r){if(e[0].type!=="block-scalar-header")return r(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:o}=e[0],s=o[0],i=0,a="",c=-1;for(let f=1;f<o.length;++f){let p=o[f];if(!a&&(p==="-"||p==="+"))a=p;else{let y=Number(p);!i&&y?i=y:c===-1&&(c=t+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${o}`);let u=!1,d="",l=o.length;for(let f=1;f<e.length;++f){let p=e[f];switch(p.type){case"space":u=!0;case"newline":l+=p.source.length;break;case"comment":n&&!u&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),l+=p.source.length,d=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),l+=p.source.length;break;default:{let y=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",y);let m=p.source;m&&typeof m=="string"&&(l+=m.length)}}}return{mode:s,indent:i,chomp:a,comment:d,length:l}}function Tm(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 Es(t,e,n){let{offset:r,type:o,source:s,end:i}=t,a,c,u=(f,p,y)=>n(r+f,p,y);switch(o){case"scalar":a=D.PLAIN,c=zm(s,u);break;case"single-quoted-scalar":a=D.QUOTE_SINGLE,c=Pm(s,u);break;case"double-quoted-scalar":a=D.QUOTE_DOUBLE,c=Lm(s,u);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${o}`),{value:"",type:null,comment:"",range:[r,r+s.length,r+s.length]}}let d=r+s.length,l=Be(i,d,e,n);return{value:c,type:a,comment:l.comment,range:[r,d,l.offset]}}function zm(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}`),Bl(t)}function Pm(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),Bl(t.slice(1,-1)).replace(/''/g,"'")}function Bl(t){let e,n;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
+`}let y=r+o.length+e.source.length;return{value:l,type:s,comment:o.comment,range:[r,y,y]}}function Lm({offset:t,props:e},n,r){if(e[0].type!=="block-scalar-header")return r(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:o}=e[0],s=o[0],i=0,a="",c=-1;for(let f=1;f<o.length;++f){let p=o[f];if(!a&&(p==="-"||p==="+"))a=p;else{let y=Number(p);!i&&y?i=y:c===-1&&(c=t+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${o}`);let u=!1,d="",l=o.length;for(let f=1;f<e.length;++f){let p=e[f];switch(p.type){case"space":u=!0;case"newline":l+=p.source.length;break;case"comment":n&&!u&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),l+=p.source.length,d=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),l+=p.source.length;break;default:{let y=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",y);let m=p.source;m&&typeof m=="string"&&(l+=m.length)}}}return{mode:s,indent:i,chomp:a,comment:d,length:l}}function Mm(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 vs(t,e,n){let{offset:r,type:o,source:s,end:i}=t,a,c,u=(f,p,y)=>n(r+f,p,y);switch(o){case"scalar":a=D.PLAIN,c=Fm(s,u);break;case"single-quoted-scalar":a=D.QUOTE_SINGLE,c=Zm(s,u);break;case"double-quoted-scalar":a=D.QUOTE_DOUBLE,c=jm(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 Fm(t,e){let n="";switch(t[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),Gl(t)}function Zm(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),Gl(t.slice(1,-1)).replace(/''/g,"'")}function Gl(t){let e,n;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
`,"sy"),n=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=e.exec(t);if(!r)return t;let o=r[1],s=" ",i=e.lastIndex;for(n.lastIndex=i;r=n.exec(t);)r[1]===""?s===`
`?o+=s:s=`
-`:(o+=s+r[1],s=" "),i=n.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=i,r=a.exec(t),o+s+(r?.[1]??"")}function Lm(t,e){let n="";for(let r=1;r<t.length-1;++r){let o=t[r];if(!(o==="\r"&&t[r+1]===`
+`:(o+=s+r[1],s=" "),i=n.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=i,r=a.exec(t),o+s+(r?.[1]??"")}function jm(t,e){let n="";for(let r=1;r<t.length-1;++r){let o=t[r];if(!(o==="\r"&&t[r+1]===`
`))if(o===`
-`){let{fold:s,offset:i}=Mm(t,r);n+=s,r=i}else if(o==="\\"){let s=t[++r],i=Fm[s];if(i)n+=i;else if(s===`
+`){let{fold:s,offset:i}=Bm(t,r);n+=s,r=i}else if(o==="\\"){let s=t[++r],i=Um[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+=Zm(t,r+1,a,e),r+=a}else{let a=t.substr(r-1,2);e(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),n+=a}}else if(o===" "||o===" "){let s=r,i=t[r+1];for(;i===" "||i===" ";)i=t[++r+1];i!==`
+`)for(s=t[++r+1];s===" "||s===" ";)s=t[++r+1];else if(s==="x"||s==="u"||s==="U"){let a=s==="x"?2:s==="u"?4:8;n+=Qm(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 Mm(t,e){let n="",r=t[e+1];for(;(r===" "||r===" "||r===`
+`)&&(n+=r>s?t.slice(s,r+1):o)}else n+=o}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),n}function Bm(t,e){let n="",r=t[e+1];for(;(r===" "||r===" "||r===`
`||r==="\r")&&!(r==="\r"&&t[e+2]!==`
`);)r===`
`&&(n+=`
-`),e+=1,r=t[e+1];return n||(n=" "),{fold:n,offset:e}}var Fm={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
-`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Zm(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 vs(t,e,n,r){let{value:o,type:s,comment:i,range:a}=e.type==="block-scalar"?As(t,e,r):Es(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[me]:c?u=jm(t.schema,o,c,n,r):e.type==="scalar"?u=Bm(t,o,e,r):u=t.schema[me];let d;try{let l=u.resolve(o,f=>r(n??e,"TAG_RESOLVE_FAILED",f),t.options);d=N(l)?l:new D(l)}catch(l){let f=l instanceof Error?l.message:String(l);r(n??e,"TAG_RESOLVE_FAILED",f),d=new D(o)}return d.range=a,d.source=o,s&&(d.type=s),c&&(d.tag=c),u.format&&(d.format=u.format),i&&(d.comment=i),d}function jm(t,e,n,r,o){if(n==="!")return t[me];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[me])}function Bm({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[me];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(r))??n[me];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 Ul(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 Um={composeNode:ks,composeEmptyNode:Gr};function ks(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=Qm(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=vs(t,e,c,r),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{u=jl(Um,t,e,n,r),a&&(u.anchor=a.source.substring(1))}catch(l){let f=l instanceof Error?l.message:String(l);r(e,"RESOURCE_EXHAUSTION",f)}break;default:{let l=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",l),d=!1}}return u??(u=Gr(t,e.offset,void 0,null,n,r)),a&&u.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),o&&t.options.stringKeys&&(!N(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&r(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(u.spaceBefore=!0),i&&(e.type==="scalar"&&e.source===""?u.comment=i:u.commentBefore=i),t.options.keepSourceTokens&&d&&(u.srcToken=e),u}function Gr(t,e,n,r,{spaceBefore:o,comment:s,anchor:i,tag:a,end:c},u){let d={type:"scalar",offset:Ul(e,n,r),indent:-1,source:""},l=vs(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 Qm({options:t},{offset:e,source:n,end:r},o){let s=new Je(n.substring(1));s.source===""&&o(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&o(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let i=e+n.length,a=Be(r,i,t.strict,o);return s.range=[e,i,a.offset],a.comment&&(s.comment=a.comment),s}function Ql(t,e,{offset:n,start:r,value:o,end:s},i){let a=Object.assign({_directives:e},t),c=new lt(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?ks(u,o,d,i):Gr(u,d.end,r,null,d,i);let l=c.contents.range[2],f=Be(s,l,!1,i);return f.comment&&(c.comment=f.comment),c.range=[n,l,f.offset],c}function Nn(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 Gl(t){let e="",n=!1,r=!1;for(let o=0;o<t.length;++o){let s=t[o];switch(s[0]){case"#":e+=(e===""?"":r?`
+`),e+=1,r=t[e+1];return n||(n=" "),{fold:n,offset:e}}var Um={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
+`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Qm(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 ks(t,e,n,r){let{value:o,type:s,comment:i,range:a}=e.type==="block-scalar"?Es(t,e,r):vs(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[me]:c?u=Gm(t.schema,o,c,n,r):e.type==="scalar"?u=Vm(t,o,e,r):u=t.schema[me];let d;try{let l=u.resolve(o,f=>r(n??e,"TAG_RESOLVE_FAILED",f),t.options);d=N(l)?l:new D(l)}catch(l){let f=l instanceof Error?l.message:String(l);r(n??e,"TAG_RESOLVE_FAILED",f),d=new D(o)}return d.range=a,d.source=o,s&&(d.type=s),c&&(d.tag=c),u.format&&(d.format=u.format),i&&(d.comment=i),d}function Gm(t,e,n,r,o){if(n==="!")return t[me];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[me])}function Vm({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[me];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(r))??n[me];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 Vl(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 qm={composeNode:Ds,composeEmptyNode:Gr};function Ds(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=Jm(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=ks(t,e,c,r),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{u=Ql(qm,t,e,n,r),a&&(u.anchor=a.source.substring(1))}catch(l){let f=l instanceof Error?l.message:String(l);r(e,"RESOURCE_EXHAUSTION",f)}break;default:{let l=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",l),d=!1}}return u??(u=Gr(t,e.offset,void 0,null,n,r)),a&&u.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),o&&t.options.stringKeys&&(!N(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&r(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(u.spaceBefore=!0),i&&(e.type==="scalar"&&e.source===""?u.comment=i:u.commentBefore=i),t.options.keepSourceTokens&&d&&(u.srcToken=e),u}function Gr(t,e,n,r,{spaceBefore:o,comment:s,anchor:i,tag:a,end:c},u){let d={type:"scalar",offset:Vl(e,n,r),indent:-1,source:""},l=ks(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 Jm({options:t},{offset:e,source:n,end:r},o){let s=new Je(n.substring(1));s.source===""&&o(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&o(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let i=e+n.length,a=Ue(r,i,t.strict,o);return s.range=[e,i,a.offset],a.comment&&(s.comment=a.comment),s}function ql(t,e,{offset:n,start:r,value:o,end:s},i){let a=Object.assign({_directives:e},t),c=new lt(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=Be(r,{indicator:"doc-start",next:o??s?.[0],offset:n,onError:i,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,o&&(o.type==="block-map"||o.type==="block-seq")&&!d.hasNewline&&i(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=o?Ds(u,o,d,i):Gr(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 $n(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 Jl(t){let e="",n=!1,r=!1;for(let o=0;o<t.length;++o){let s=t[o];switch(s[0]){case"#":e+=(e===""?"":r?`
`:`
-`)+(s.substring(1)||" "),n=!0,r=!1;break;case"%":t[o+1]?.[0]!=="#"&&(o+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:e,afterEmptyLine:r}}var $n=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,o,s)=>{let i=Nn(n);s?this.warnings.push(new In(i,r,o)):this.errors.push(new Re(i,r,o))},this.directives=new Fe({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:r,afterEmptyLine:o}=Gl(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(Z(s)&&!s.flow&&s.items.length>0){let i=s.items[0];T(i)&&(i=i.key);let a=i.commentBefore;i.commentBefore=a?`${r}
+`)+(s.substring(1)||" "),n=!0,r=!1;break;case"%":t[o+1]?.[0]!=="#"&&(o+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:e,afterEmptyLine:r}}var Tn=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,o,s)=>{let i=$n(n);s?this.warnings.push(new Cn(i,r,o)):this.errors.push(new Re(i,r,o))},this.directives=new Ze({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:r,afterEmptyLine:o}=Jl(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(j(s)&&!s.flow&&s.items.length>0){let i=s.items[0];T(i)&&(i=i.key);let a=i.commentBefore;i.commentBefore=a?`${r}
${a}`:r}else{let i=s.commentBefore;s.commentBefore=i?`${r}
-${i}`:r}}if(n){for(let s=0;s<this.errors.length;++s)e.errors.push(this.errors[s]);for(let s=0;s<this.warnings.length;++s)e.warnings.push(this.warnings[s])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Gl(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=Nn(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",r,o)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=Ql(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,r=new Re(Nn(e),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new Re(Nn(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=Be(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
-${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new Re(Nn(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),o=new lt(void 0,r);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),o.range=[0,n,n],this.decorate(o,!1),yield o}}};var Ds=Symbol("break visit"),Gm=Symbol("skip children"),Vl=Symbol("remove item");function _t(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),ql(Object.freeze([]),t,e)}_t.BREAK=Ds;_t.SKIP=Gm;_t.REMOVE=Vl;_t.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};_t.parentCollection=(t,e)=>{let n=_t.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 ql(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=ql(Object.freeze(t.concat([[o,i]])),s.items[i],n);if(typeof a=="number")i=a-1;else{if(a===Ds)return Ds;a===Vl&&(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 Rs="\uFEFF",Os="",Is="",Vr="";function Jl(t){switch(t){case Rs:return"byte-order-mark";case Os:return"doc-mode";case Is:return"flow-error-end";case Vr:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
+${i}`:r}}if(n){for(let s=0;s<this.errors.length;++s)e.errors.push(this.errors[s]);for(let s=0;s<this.warnings.length;++s)e.warnings.push(this.warnings[s])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Jl(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=$n(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",r,o)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=ql(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,r=new Re($n(e),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new Re($n(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 Re($n(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),o=new lt(void 0,r);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),o.range=[0,n,n],this.decorate(o,!1),yield o}}};var Rs=Symbol("break visit"),Km=Symbol("skip children"),Kl=Symbol("remove item");function _t(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Wl(Object.freeze([]),t,e)}_t.BREAK=Rs;_t.SKIP=Km;_t.REMOVE=Kl;_t.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};_t.parentCollection=(t,e)=>{let n=_t.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 Wl(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=Wl(Object.freeze(t.concat([[o,i]])),s.items[i],n);if(typeof a=="number")i=a-1;else{if(a===Rs)return Rs;a===Kl&&(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 Is="\uFEFF",Os="",Cs="",Vr="";function Yl(t){switch(t){case Is:return"byte-order-mark";case Os:return"doc-mode";case Cs:return"flow-error-end";case Vr: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 Kl=new Set("0123456789ABCDEFabcdef"),qm=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),qr=new Set(",[]{}"),Jm=new Set(` ,[]{}
-\r `),Cs=t=>!t||Jm.has(t),Tn=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===`
+`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}function Ie(t){switch(t){case void 0:case" ":case`
+`:case"\r":case" ":return!0;default:return!1}}var Hl=new Set("0123456789ABCDEFabcdef"),Ym=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),qr=new Set(",[]{}"),Hm=new Set(` ,[]{}
+\r `),Ns=t=>!t||Hm.has(t),zn=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===`
`?!0:n==="\r"?this.buffer[e+1]===`
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let n=this.buffer[e];if(this.indentNext>0){let r=0;for(;n===" ";)n=this.buffer[++r+e];if(n==="\r"){let o=this.buffer[r+e+1];if(o===`
`||!o&&!this.atEnd)return e+r+1}return n===`
-`||r>=this.indentNext||!n&&!this.atEnd?e+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(e,3);if((r==="---"||r==="...")&&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]===Rs&&(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 Os,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(Cs),"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 Is,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(Cs),"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(`
+`||r>=this.indentNext||!n&&!this.atEnd?e+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(e,3);if((r==="---"||r==="...")&&Ie(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]===Is&&(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 Os,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==="...")&&Ie(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&&!Ie(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===":")&&Ie(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(Ns),"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("..."))&&Ie(o[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(o[0]==="]"||o[0]==="}")))return this.flowLevel=0,yield Cs,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(Ns),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let i=this.charAt(1);if(this.flowKey||Ie(i)||i===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),n=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;n!==-1&&this.buffer[n+1]==="'";)n=this.buffer.indexOf("'",n+2);else for(;n!==-1;){let s=0;for(;this.buffer[n-1-s]==="\\";)s+=1;if(s%2===0)break;n=this.buffer.indexOf('"',n+1)}let r=this.buffer.substring(0,n),o=r.indexOf(`
`,this.pos);if(o!==-1){for(;o!==-1;){let s=this.continueScalar(o+1);if(s===-1)break;o=r.indexOf(`
-`,s)}o!==-1&&(n=o-(r[o-1]==="\r"?2:1))}if(n===-1){if(!this.atEnd)return this.setNext("quoted-scalar");n=this.buffer.length}return yield*this.pushToIndex(n+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let n=this.buffer[++e];if(n==="+")this.blockScalarKeep=!0;else if(n>"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>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`
+`,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=>Ie(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 Vr,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&&qr.has(s))break;n=r}else if(Oe(o)){let s=this.buffer[r+1];if(o==="\r"&&(s===`
+`&&s>=this.pos&&s+1+n>a)e=s;else break}while(!0);return yield Vr,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(Ie(s)||e&&qr.has(s))break;n=r}else if(Ie(o)){let s=this.buffer[r+1];if(o==="\r"&&(s===`
`?(r+=1,o=`
`,s=this.buffer[r+1]):n=r),s==="#"||e&&qr.has(s))break;if(o===`
-`){let i=this.continueScalar(r+1);if(i===-1)break;r=Math.max(r,i-2)}}else{if(e&&qr.has(o))break;n=r}return!o&&!this.atEnd?this.setNext("plain-scalar"):(yield Vr,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(Cs),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(Oe(r)||n&&qr.has(r)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!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(qm.has(n))n=this.buffer[++e];else if(n==="%"&&Kl.has(this.buffer[e+1])&&Kl.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===`
+`){let i=this.continueScalar(r+1);if(i===-1)break;r=Math.max(r,i-2)}}else{if(e&&qr.has(o))break;n=r}return!o&&!this.atEnd?this.setNext("plain-scalar"):(yield Vr,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(Ns),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(Ie(r)||n&&qr.has(r)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!Ie(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(Ym.has(n))n=this.buffer[++e];else if(n==="%"&&Hl.has(this.buffer[e+1])&&Hl.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 zn=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,r=this.lineStarts.length;for(;n<r;){let s=n+r>>1;this.lineStarts[s]<e?n=s+1:r=s}if(this.lineStarts[n]===e)return{line:n+1,col:1};if(n===0)return{line:0,col:e};let o=this.lineStarts[n-1];return{line:n,col:e-o+1}}}};function dt(t,e){for(let n=0;n<t.length;++n)if(t[n].type===e)return!0;return!1}function Wl(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 Hl(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 Jr(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 Gt(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 Kr(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 Yl(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!dt(e.start,"explicit-key-ind")&&!dt(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Hl(e.value)?e.value.end?Kr(e.value.end,e.sep):e.value.end=e.sep:Kr(e.start,e.sep),delete e.sep)}var Pn=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 Tn,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=Jl(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"&&Yl(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&&Wl(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":{Wl(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=Jr(this.peek(2)),r=Gt(n),o;e.end?(o=e.end,o.push(this.sourceToken),delete e.end):o=[this.sourceToken];let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let n=this.source.indexOf(`
+`?yield*this.pushCount(2):0}*pushSpaces(e){let n=this.pos-1,r;do r=this.buffer[++n];while(r===" "||e&&r===" ");let o=n-this.pos;return o>0&&(yield this.buffer.substr(this.pos,o),this.pos=n),o}*pushUntil(e){let n=this.pos,r=this.buffer[n];for(;!e(r);)r=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};var Pn=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,r=this.lineStarts.length;for(;n<r;){let s=n+r>>1;this.lineStarts[s]<e?n=s+1:r=s}if(this.lineStarts[n]===e)return{line:n+1,col:1};if(n===0)return{line:0,col:e};let o=this.lineStarts[n-1];return{line:n,col:e-o+1}}}};function dt(t,e){for(let n=0;n<t.length;++n)if(t[n].type===e)return!0;return!1}function Xl(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 tf(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 Jr(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 Vt(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 Kr(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 ef(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!dt(e.start,"explicit-key-ind")&&!dt(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,tf(e.value)?e.value.end?Kr(e.value.end,e.sep):e.value.end=e.sep:Kr(e.start,e.sep),delete e.sep)}var Ln=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new zn,this.onNewLine=e}*parse(e,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(e,n))yield*this.next(r);n||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let n=Yl(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"&&ef(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&&Xl(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":{Xl(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=Jr(this.peek(2)),r=Vt(n),o;e.end?(o=e.end,o.push(this.sourceToken),delete e.end):o=[this.sourceToken];let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let n=this.source.indexOf(`
`)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
-`,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){Kr(o,n.start),o.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,o=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(o&&n.sep&&!n.value){let i=[];for(let a=0;a<n.sep.length;++a){let c=n.sep[a];switch(c.type){case"newline":i.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(i.length=0);break;default:i.length=0}}i.length>=2&&(s=n.sep.splice(i[1]))}switch(this.type){case"anchor":case"tag":o||n.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):o||n.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(dt(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(Hl(n.key)&&!dt(n.sep,"newline")){let i=Gt(n.start),a=n.key,c=n.sep;c.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:a,sep:c}]})}else s.length>0?n.sep=n.sep.concat(s,this.sourceToken):n.sep.push(this.sourceToken);else if(dt(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let i=Gt(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||o?e.items.push({start:s,key:null,sep:[this.sourceToken]}):dt(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);o||n.value?(e.items.push({start:s,key:i,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(i):(Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!0);return}default:{let i=this.startBlockValue(e);if(i){if(i.type==="block-seq"){if(!n.explicitKey&&n.sep&&!dt(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&e.items.push({start:s});this.stack.push(i);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){Kr(o,n.start),o.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=e.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;n.value||dt(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?e.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);!n||n.value?e.items.push({start:[],key:o,sep:[]}):n.sep?this.stack.push(o):Object.assign(n,{key:o,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let o=Jr(r),s=Gt(o);Yl(e);let i=e.end.splice(1,e.end.length);i.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let n=this.source.indexOf(`
+`,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){Kr(o,n.start),o.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,o=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(o&&n.sep&&!n.value){let i=[];for(let a=0;a<n.sep.length;++a){let c=n.sep[a];switch(c.type){case"newline":i.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(i.length=0);break;default:i.length=0}}i.length>=2&&(s=n.sep.splice(i[1]))}switch(this.type){case"anchor":case"tag":o||n.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):o||n.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(dt(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(tf(n.key)&&!dt(n.sep,"newline")){let i=Vt(n.start),a=n.key,c=n.sep;c.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:a,sep:c}]})}else s.length>0?n.sep=n.sep.concat(s,this.sourceToken):n.sep.push(this.sourceToken);else if(dt(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let i=Vt(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||o?e.items.push({start:s,key:null,sep:[this.sourceToken]}):dt(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);o||n.value?(e.items.push({start:s,key:i,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(i):(Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!0);return}default:{let i=this.startBlockValue(e);if(i){if(i.type==="block-seq"){if(!n.explicitKey&&n.sep&&!dt(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&e.items.push({start:s});this.stack.push(i);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){Kr(o,n.start),o.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=e.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;n.value||dt(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?e.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);!n||n.value?e.items.push({start:[],key:o,sep:[]}):n.sep?this.stack.push(o):Object.assign(n,{key:o,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let o=Jr(r),s=Vt(o);ef(e);let i=e.end.splice(1,e.end.length);i.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let n=this.source.indexOf(`
`)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
-`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Jr(e),r=Gt(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=Jr(e),r=Gt(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 Km(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new zn||null,prettyErrors:e}}function Ns(t,e={}){let{lineCounter:n,prettyErrors:r}=Km(e),o=new Pn(n?.addNewLine),s=new $n(e),i=null;for(let a of s.compose(o.parse(t),!0,t.length))if(!i)i=a;else if(i.options.logLevel!=="silent"){i.errors.push(new Re(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(i.errors.forEach(ws(t,n)),i.warnings.forEach(ws(t,n))),i}var Ie=class extends Error{code;constructor(e){super(`Structured data failed validation: ${e}`),this.name="StructuredDataError",this.code=e}},Ym=t=>Ne(JSON.stringify(t)),Xl=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},ef=(t,e)=>{if(Xl(t)===!1)throw new Ie("INVALID");let n=0,r=(s,i)=>{if(i>e.depth)throw new Ie("DEPTH_EXCEEDED");if(typeof s=="string"){if(Ne(s)>e.stringBytes)throw new Ie("STRING_BYTES_EXCEEDED");return s}if(s===null||typeof s=="boolean"||typeof s=="number"&&Number.isFinite(s)&&(Number.isInteger(s)===!1||Number.isSafeInteger(s)))return s;if(Array.isArray(s))return s.map(a=>{if(n+=1,n>e.fields)throw new Ie("FIELDS_EXCEEDED");return r(a,i+1)});if(Xl(s)){let a=Object.create(null);for(let[c,u]of Object.entries(s)){if(n+=1,n>e.fields)throw new Ie("FIELDS_EXCEEDED");a[c]=r(u,i+1)}return a}throw new Ie("INVALID")},o=r(t,1);if(Ym(o)>e.serializedBytes)throw new Ie("SERIALIZED_BYTES_EXCEEDED");return o};var H=class extends Error{code;constructor(e,n){super(n),this.name="MarkdownMetadataError",this.code=e}};var Ln=new Uint8Array([239,187,191]),tf=Ln.byteLength+10,Hm=(t,e,n=0)=>t.byteLength-n<e.byteLength?!1:e.every((r,o)=>t[n+o]===r),Mn=(t,e)=>{let n=0;if(Hm(t,Ln))n=Ln.byteLength;else if(t.byteLength<Ln.byteLength&&Ln.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 Xm={bytes:R.frontmatterBytes,depth:R.frontmatterDepth,fields:R.frontmatterFields,stringBytes:R.frontmatterStringBytes,serializedBytes:R.indexedPropertiesBytes},nf=t=>{try{return fe(t)}catch{throw new H("FRONTMATTER_DECODING_FAILED","Markdown frontmatter is not valid UTF-8")}},rf=(t,e)=>{let n=Ns(t,{schema:"core",uniqueKeys:!0});if(n.errors.length>0)throw new H("FRONTMATTER_INVALID","Markdown frontmatter contains invalid YAML");let r;try{r=n.toJS({maxAliasCount:0})}catch{throw new H("FRONTMATTER_INVALID","Markdown frontmatter contains unsupported YAML aliases")}if(r===null)return{};try{return ef(r,e)}catch(o){throw o instanceof Ie?o.code==="DEPTH_EXCEEDED"?new H("FRONTMATTER_DEPTH_EXCEEDED","Markdown frontmatter exceeds the nesting limit"):o.code==="FIELDS_EXCEEDED"?new H("FRONTMATTER_FIELDS_EXCEEDED","Markdown frontmatter exceeds the field limit"):o.code==="STRING_BYTES_EXCEEDED"?new H("FRONTMATTER_STRING_BYTES_EXCEEDED","Markdown frontmatter contains a string that exceeds the byte limit"):o.code==="SERIALIZED_BYTES_EXCEEDED"?new H("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter properties exceed the indexed byte limit"):new H("FRONTMATTER_INVALID","Markdown frontmatter must contain a JSON-compatible object"):o}},of=async(t,e={})=>{let n={...Xm,...e},r=n.bytes+tf,o=new Uint8Array(r),s=0;for await(let c of Ct(t)){let u=0;for(;u<c.byteLength;){let d=r-s;if(d<=0)break;let l=Math.max(0,6-s),f=Math.min(c.byteLength-u,l);if(l===0){let m=c.subarray(u,Math.min(c.byteLength,u+d)),h=m.indexOf(10);f=h===-1?m.byteLength:h+1}o.set(c.subarray(u,u+f),s),s+=f,u+=f;let p=o.subarray(0,s),y=Mn(p,!1);if(y===null)return{properties:{},frontmatterBytes:0,consumedBytes:p.length};if(y!==void 0){let m=y.yamlEnd-y.yamlStart;if(m>n.bytes)throw new H("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter exceeds the byte limit");let h=nf(p.subarray(y.yamlStart,y.yamlEnd));return{properties:rf(h,n),frontmatterBytes:m,consumedBytes:y.blockEnd}}}if(s>=r)break}let i=o.subarray(0,s),a=Mn(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=nf(i.subarray(a.yamlStart,a.yamlEnd));return{properties:rf(u,n),frontmatterBytes:c,consumedBytes:a.blockEnd}}}throw new H("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter is not closed within the byte limit")};var Wr=async(t,e=R.hydratedFileBytes)=>{if(Number.isInteger(e)===!1||e<=0||e>R.hydratedFileBytes)throw new H("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown body byte limit is outside the supported range");let n;try{n=await $e(t,e)}catch(a){throw a instanceof re?new H("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown content exceeds the byte limit"):a}let r;try{r=fe(n)}catch{throw new H("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}let s=Mn(n,!0)?.blockEnd??0,i;try{i=s===0?Nt(r):fe(n.subarray(s))}catch{throw new H("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}return{body:i,bodyBytes:Ne(i),sourceBytes:n.byteLength}};var pt=class extends Error{code;referenceId;constructor({code:e,message:n,referenceId:r,cause:o}){super(n,{cause:o}),this.name="MarkdownDocumentError",this.code=e,this.referenceId=r}},eh=C({source:v(),body:v(),frontmatter:_e(v(),rt())}),Hr=t=>{let e;try{e=eh.parse(t)}catch(n){throw new pt({code:"INVALID_DOCUMENT",message:"Markdown document is invalid",cause:n})}return Object.freeze({source:e.source,body:e.body,frontmatter:ot(e.frontmatter)})},Yr="#frontmatter",th=t=>`${Yr}${t.slice(1)}`,nh=t=>{if(t!==Yr&&t.startsWith(`${Yr}/`)===!1)throw new pt({code:"UNUSED_REFERENCE",message:`Resolved Markdown reference ${t} is outside frontmatter`,referenceId:t});return`#${t.slice(Yr.length)}`},rh=t=>{let e=t.referenceId===void 0?void 0:th(t.referenceId),n="INVALID_DOCUMENT";throw(t.code==="INVALID_REFERENCE_MARKER"||t.code==="INVALID_REFERENCE"||t.code==="REFERENCE_NOT_FOUND"||t.code==="INVALID_RESOLVED_VALUE"||t.code==="UNUSED_REFERENCE")&&(n=t.code),new pt({code:n,message:t.message,referenceId:e,cause:t})},sf=async({source:t,maximumBytes:e=R.hydratedFileBytes})=>{let n;try{n=await $e(t,e)}catch(i){throw i instanceof re?new pt({code:"CONTENT_LIMIT_EXCEEDED",message:"Markdown document exceeds the byte limit",cause:i}):i}let r;try{r=Nt(fe(n))}catch(i){throw new pt({code:"CONTENT_DECODING_FAILED",message:"Markdown document is not valid UTF-8",cause:i})}let[o,s]=await Promise.all([Wr(n,e),of(n)]);return Hr({source:r,body:o.body,frontmatter:s.properties})};var af=({document:t,references:e,allowUnresolvedReferences:n=!1})=>{let r=Hr(t),o=new Map;for(let[i,a]of e)o.set(nh(i),a);let s;try{s=mr({document:r.frontmatter,references:o,allowUnresolvedReferences:n})}catch(i){throw i instanceof pe&&rh(i),i}return Hr({...r,frontmatter:s})},cf=({document:t,representation:e})=>{let n=Hr(t);if(e.type==="document")return n.source;if(e.type==="markdown-body")return n.body;if(e.type==="markdown-frontmatter")return n.frontmatter;throw new pt({code:"UNSUPPORTED_REPRESENTATION",message:`Markdown documents do not support ${e.type}`})};var uf=t=>{let e=t.format==="markdown"?t.value.frontmatter:t.value;return Tt(e)?e:void 0},Xr=t=>Object.freeze(t),lf=async({format:t,source:e,maximumBytes:n=R.hydratedFileBytes})=>Xr(t==="json"?{format:t,value:await cl({source:e,maximumBytes:n})}:{format:t,value:await sf({source:e,maximumBytes:n})});var ff=({document:t,references:e,allowUnresolvedReferences:n})=>t.format==="json"?Xr({format:t.format,value:mr({document:t.value,references:e,allowUnresolvedReferences:n})}):Xr({format:t.format,value:af({document:t.value,references:e,allowUnresolvedReferences:n})}),df=({document:t,representation:e})=>t.format==="json"?ul({document:t.value,representation:e}):cf({document:t.value,representation:e});var eo=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}},Vt=({node:t,source:e})=>{if(e.revision!==t.revision)throw new eo({code:"REVISION_MISMATCH",documentId:t.id,expectedRevision:t.revision,actualRevision:e.revision});if(t.format!==void 0&&e.format!==t.format)throw new eo({code:"FORMAT_MISMATCH",documentId:t.id,expectedFormat:t.format,actualFormat:e.format});return e};var qt=t=>{if(typeof t=="object"&&t!==null){let e=Reflect.get(t,"code");if(typeof e=="string"&&e.length>0)return e;let n=Reflect.get(t,"name");if(typeof n=="string"&&n.length>0)return n}return"UNKNOWN"},se=(t,e)=>{try{t?.(e)}catch{}},pf=({load:t,onEvent:e})=>async(n,r)=>{let o={documentId:n.id,revision:n.revision};se(e,{type:"document-fetch-started",...o});try{let s=await t(n,r);return se(e,{type:"document-fetch-completed",...o}),s}catch(s){throw se(e,{type:"document-fetch-failed",...o,errorCode:qt(s)}),s}};var oh=C({format:le(["json","markdown"]),revision:v().min(1)}),Jt=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}},sh=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()}}}),mf=({fetch:t,getRequest:e,getMetadata:n,onEvent:r})=>pf({load:async(s,{signal:i})=>{let a;try{a=await t(e(s),{signal:i})}catch(d){throw new Jt({code:"REQUEST_FAILED",message:`Document ${s.id} request failed`,documentId:s.id,cause:d})}if(a.ok===!1)throw new Jt({code:"HTTP_STATUS",message:`Document ${s.id} request returned status ${a.status}`,documentId:s.id,status:a.status});let c;try{c=oh.parse(n({node:s,response:a}))}catch(d){throw new Jt({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 Jt({code:"BODY_MISSING",message:`Document ${s.id} response body is unavailable`,documentId:s.id});return Object.freeze({...c,source:sh(u)})},onEvent:r});var Kt=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,yf=new Set,$s=typeof process=="object"&&process?process:{},gf=(t,e,n,r)=>{typeof $s.emitWarning=="function"?$s.emitWarning(t,e,n,r):console.error(`[${n}] ${e}: ${t}`)},to=globalThis.AbortController,hf=globalThis.AbortSignal;if(typeof to>"u"){hf=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},to=class{constructor(){e()}signal=new hf;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=$s.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,gf("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var ih=t=>!yf.has(t),KE=Symbol("type"),mt=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),bf=t=>mt(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Wt:null:null,Wt=class extends Array{constructor(e){super(e),this.fill(0)}},Ts=class t{heap;length;static#c=!1;static create(e){let n=bf(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]}},Yt=class t{#c;#f;#h;#y;#I;#C;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#g;#r;#n;#e;#u;#d;#a;#s;#b;#i;#w;#_;#p;#x;#k;#l;static unsafeExposeInternals(e){return{starts:e.#_,ttls:e.#p,sizes:e.#w,keyMap:e.#r,keyList:e.#n,valList:e.#e,next:e.#u,prev:e.#d,get head(){return e.#a},get tail(){return e.#s},free:e.#b,isBackgroundFetch:n=>e.#t(n),backgroundFetch:(n,r,o,s)=>e.#T(n,r,o,s),moveToTail:n=>e.#O(n),indexes:n=>e.#S(n),rindexes:n=>e.#A(n),isStale:n=>e.#m(n)}}get max(){return this.#c}get maxSize(){return this.#f}get calculatedSize(){return this.#g}get size(){return this.#o}get fetchMethod(){return this.#I}get memoMethod(){return this.#C}get dispose(){return this.#h}get disposeAfter(){return this.#y}constructor(e){let{max:n=0,ttl:r,ttlResolution:o=1,ttlAutopurge:s,updateAgeOnGet:i,updateAgeOnHas:a,allowStale:c,dispose:u,disposeAfter:d,noDisposeOnSet:l,noUpdateTTL:f,maxSize:p=0,maxEntrySize:y=0,sizeCalculation:m,fetchMethod:h,memoMethod:w,noDeleteOnFetchRejection:S,noDeleteOnStaleGet:A,allowStaleOnFetchRejection:_,allowStaleOnFetchAbort:b,ignoreFetchAbort:E}=e;if(n!==0&&!mt(n))throw new TypeError("max option must be a nonnegative integer");let k=n?bf(n):Array;if(!k)throw new Error("invalid max value: "+n);if(this.#c=n,this.#f=p,this.maxEntrySize=y||this.#f,this.sizeCalculation=m,this.sizeCalculation){if(!this.#f&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(w!==void 0&&typeof w!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#C=w,h!==void 0&&typeof h!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#I=h,this.#k=!!h,this.#r=new Map,this.#n=new Array(n).fill(void 0),this.#e=new Array(n).fill(void 0),this.#u=new k(n),this.#d=new k(n),this.#a=0,this.#s=0,this.#b=Ts.create(n),this.#o=0,this.#g=0,typeof u=="function"&&(this.#h=u),typeof d=="function"?(this.#y=d,this.#i=[]):(this.#y=void 0,this.#i=void 0),this.#x=!!this.#h,this.#l=!!this.#y,this.noDisposeOnSet=!!l,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!S,this.allowStaleOnFetchRejection=!!_,this.allowStaleOnFetchAbort=!!b,this.ignoreFetchAbort=!!E,this.maxEntrySize!==0){if(this.#f!==0&&!mt(this.#f))throw new TypeError("maxSize must be a positive integer if specified");if(!mt(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#j()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!A,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!a,this.ttlResolution=mt(o)||o===0?o:1,this.ttlAutopurge=!!s,this.ttl=r||0,this.ttl){if(!mt(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#z()}if(this.#c===0&&this.ttl===0&&this.#f===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#c&&!this.#f){let x="LRU_CACHE_UNBOUNDED";ih(x)&&(yf.add(x),gf("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",x,t))}}getRemainingTTL(e){return this.#r.has(e)?1/0:0}#z(){let e=new Wt(this.#c),n=new Wt(this.#c);this.#p=e,this.#_=n,this.#P=(s,i,a=Kt.now())=>{if(n[s]=i!==0?a:0,e[s]=i,i!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#m(s)&&this.#E(this.#n[s],"expire")},i+1);c.unref&&c.unref()}},this.#D=s=>{n[s]=e[s]!==0?Kt.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=Kt.now();if(this.ttlResolution>0){r=s;let i=setTimeout(()=>r=0,this.ttlResolution);i.unref&&i.unref()}return s};this.getRemainingTTL=s=>{let i=this.#r.get(s);if(i===void 0)return 0;let a=e[i],c=n[i];if(!a||!c)return 1/0;let u=(r||o())-c;return a-u},this.#m=s=>{let i=n[s],a=e[s];return!!a&&!!i&&(r||o())-i>a}}#D=()=>{};#v=()=>{};#P=()=>{};#m=()=>!1;#j(){let e=new Wt(this.#c);this.#g=0,this.#w=e,this.#R=n=>{this.#g-=e[n],e[n]=0},this.#L=(n,r,o,s)=>{if(this.#t(r))return 0;if(!mt(o))if(s){if(typeof s!="function")throw new TypeError("sizeCalculation must be a function");if(o=s(r,n),!mt(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#N=(n,r,o)=>{if(e[n]=r,this.#f){let s=this.#f-e[n];for(;this.#g>s;)this.#$(!0)}this.#g+=e[n],o&&(o.entrySize=r,o.totalCalculatedSize=this.#g)}}#R=e=>{};#N=(e,n,r)=>{};#L=(e,n,r,o)=>{if(r||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#S({allowStale:e=this.allowStale}={}){if(this.#o)for(let n=this.#s;!(!this.#M(n)||((e||!this.#m(n))&&(yield n),n===this.#a));)n=this.#d[n]}*#A({allowStale:e=this.allowStale}={}){if(this.#o)for(let n=this.#a;!(!this.#M(n)||((e||!this.#m(n))&&(yield n),n===this.#s));)n=this.#u[n]}#M(e){return e!==void 0&&this.#r.get(this.#n[e])===e}*entries(){for(let e of this.#S())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*rentries(){for(let e of this.#A())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*keys(){for(let e of this.#S()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*rkeys(){for(let e of this.#A()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*values(){for(let e of this.#S())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#A())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,n={}){for(let r of this.#S()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;if(s!==void 0&&e(s,this.#n[r],this))return this.get(this.#n[r],n)}}forEach(e,n=this){for(let r of this.#S()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;s!==void 0&&e.call(n,s,this.#n[r],this)}}rforEach(e,n=this){for(let r of this.#A()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;s!==void 0&&e.call(n,s,this.#n[r],this)}}purgeStale(){let e=!1;for(let n of this.#A({allowStale:!0}))this.#m(n)&&(this.#E(this.#n[n],"expire"),e=!0);return e}info(e){let n=this.#r.get(e);if(n===void 0)return;let r=this.#e[n],o=this.#t(r)?r.__staleWhileFetching:r;if(o===void 0)return;let s={value:o};if(this.#p&&this.#_){let i=this.#p[n],a=this.#_[n];if(i&&a){let c=i-(Kt.now()-a);s.ttl=c,s.start=Date.now()}}return this.#w&&(s.size=this.#w[n]),s}dump(){let e=[];for(let n of this.#S({allowStale:!0})){let r=this.#n[n],o=this.#e[n],s=this.#t(o)?o.__staleWhileFetching:o;if(s===void 0||r===void 0)continue;let i={value:s};if(this.#p&&this.#_){i.ttl=this.#p[n];let a=Kt.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=Kt.now()-o}this.set(n,r.value,r)}}set(e,n,r={}){if(n===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:s,noDisposeOnSet:i=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=r,{noUpdateTTL:u=this.noUpdateTTL}=r,d=this.#L(e,n,r.size||0,a);if(this.maxEntrySize&&d>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#E(e,"set"),this;let l=this.#o===0?void 0:this.#r.get(e);if(l===void 0)l=this.#o===0?this.#s:this.#b.length!==0?this.#b.pop():this.#o===this.#c?this.#$(!1):this.#o,this.#n[l]=e,this.#e[l]=n,this.#r.set(e,l),this.#u[this.#s]=l,this.#d[l]=this.#s,this.#s=l,this.#o++,this.#N(l,d,c),c&&(c.set="add"),u=!1;else{this.#O(l);let f=this.#e[l];if(n!==f){if(this.#k&&this.#t(f)){f.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:p}=f;p!==void 0&&!i&&(this.#x&&this.#h?.(p,e,"set"),this.#l&&this.#i?.push([p,e,"set"]))}else i||(this.#x&&this.#h?.(f,e,"set"),this.#l&&this.#i?.push([f,e,"set"]));if(this.#R(l),this.#N(l,d,c),this.#e[l]=n,c){c.set="replace";let p=f&&this.#t(f)?f.__staleWhileFetching:f;p!==void 0&&(c.oldValue=p)}}else c&&(c.set="update")}if(o!==0&&!this.#p&&this.#z(),this.#p&&(u||this.#P(l,o,s),c&&this.#v(c,l)),!i&&this.#l&&this.#i){let f=this.#i,p;for(;p=f?.shift();)this.#y?.(...p)}return this}pop(){try{for(;this.#o;){let e=this.#e[this.#a];if(this.#$(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#l&&this.#i){let e=this.#i,n;for(;n=e?.shift();)this.#y?.(...n)}}}#$(e){let n=this.#a,r=this.#n[n],o=this.#e[n];return this.#k&&this.#t(o)?o.__abortController.abort(new Error("evicted")):(this.#x||this.#l)&&(this.#x&&this.#h?.(o,r,"evict"),this.#l&&this.#i?.push([o,r,"evict"])),this.#R(n),e&&(this.#n[n]=void 0,this.#e[n]=void 0,this.#b.push(n)),this.#o===1?(this.#a=this.#s=0,this.#b.length=0):this.#a=this.#u[n],this.#r.delete(r),this.#o--,n}has(e,n={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:o}=n,s=this.#r.get(e);if(s!==void 0){let i=this.#e[s];if(this.#t(i)&&i.__staleWhileFetching===void 0)return!1;if(this.#m(s))o&&(o.has="stale",this.#v(o,s));else return r&&this.#D(s),o&&(o.has="hit",this.#v(o,s)),!0}else o&&(o.has="miss");return!1}peek(e,n={}){let{allowStale:r=this.allowStale}=n,o=this.#r.get(e);if(o===void 0||!r&&this.#m(o))return;let s=this.#e[o];return this.#t(s)?s.__staleWhileFetching:s}#T(e,n,r,o){let s=n===void 0?void 0:this.#e[n];if(this.#t(s))return s;let i=new to,{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:w}=i.signal,S=r.ignoreFetchAbort&&m!==void 0;if(r.status&&(w&&!h?(r.status.fetchAborted=!0,r.status.fetchError=i.signal.reason,S&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),w&&!S&&!h)return l(i.signal.reason);let A=p;return this.#e[n]===p&&(m===void 0?A.__staleWhileFetching?this.#e[n]=A.__staleWhileFetching:this.#E(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,m,c.options))),m},d=m=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=m),l(m)),l=m=>{let{aborted:h}=i.signal,w=h&&r.allowStaleOnFetchAbort,S=w||r.allowStaleOnFetchRejection,A=S||r.noDeleteOnFetchRejection,_=p;if(this.#e[n]===p&&(!A||_.__staleWhileFetching===void 0?this.#E(e,"fetch"):w||(this.#e[n]=_.__staleWhileFetching)),S)return r.status&&_.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),_.__staleWhileFetching;if(_.__returned===_)throw m},f=(m,h)=>{let w=this.#I?.(e,s,c);w&&w instanceof Promise&&w.then(S=>m(S===void 0?void 0:S),h),i.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(m(void 0),r.allowStaleOnFetchAbort&&(m=S=>u(S,!0)))})};r.status&&(r.status.fetchDispatched=!0);let p=new Promise(f).then(u,d),y=Object.assign(p,{__abortController:i,__staleWhileFetching:s,__returned:void 0});return n===void 0?(this.set(e,y,{...c.options,status:void 0}),n=this.#r.get(e)):this.#e[n]=y,y}#t(e){if(!this.#k)return!1;let n=e;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof to}async fetch(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:l=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:y=this.allowStaleOnFetchAbort,context:m,forceRefresh:h=!1,status:w,signal:S}=n;if(!this.#k)return w&&(w.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,status:w});let A={allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,ttl:i,noDisposeOnSet:a,size:c,sizeCalculation:u,noUpdateTTL:d,noDeleteOnFetchRejection:l,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:y,ignoreFetchAbort:p,status:w,signal:S},_=this.#r.get(e);if(_===void 0){w&&(w.fetch="miss");let b=this.#T(e,_,A,m);return b.__returned=b}else{let b=this.#e[_];if(this.#t(b)){let M=r&&b.__staleWhileFetching!==void 0;return w&&(w.fetch="inflight",M&&(w.returnedStale=!0)),M?b.__staleWhileFetching:b.__returned=b}let E=this.#m(_);if(!h&&!E)return w&&(w.fetch="hit"),this.#O(_),o&&this.#D(_),w&&this.#v(w,_),b;let k=this.#T(e,_,A,m),I=k.__staleWhileFetching!==void 0&&r;return w&&(w.fetch=E?"stale":"refresh",I&&E&&(w.returnedStale=!0)),I?k.__staleWhileFetching:k.__returned=k}}async forceFetch(e,n={}){let r=await this.fetch(e,n);if(r===void 0)throw new Error("fetch() returned undefined");return r}memo(e,n={}){let r=this.#C;if(!r)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:s,...i}=n,a=this.get(e,i);if(!s&&a!==void 0)return a;let c=r(e,a,{options:i,context:o});return this.set(e,c,i),c}get(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,status:i}=n,a=this.#r.get(e);if(a!==void 0){let c=this.#e[a],u=this.#t(c);return i&&this.#v(i,a),this.#m(a)?(i&&(i.get="stale"),u?(i&&r&&c.__staleWhileFetching!==void 0&&(i.returnedStale=!0),r?c.__staleWhileFetching:void 0):(s||this.#E(e,"expire"),i&&r&&(i.returnedStale=!0),r?c:void 0)):(i&&(i.get="hit"),u?c.__staleWhileFetching:(this.#O(a),o&&this.#D(a),c))}else i&&(i.get="miss")}#F(e,n){this.#d[n]=e,this.#u[e]=n}#O(e){e!==this.#s&&(e===this.#a?this.#a=this.#u[e]:this.#F(this.#d[e],this.#u[e]),this.#F(this.#s,e),this.#s=e)}delete(e){return this.#E(e,"delete")}#E(e,n){let r=!1;if(this.#o!==0){let o=this.#r.get(e);if(o!==void 0)if(r=!0,this.#o===1)this.#Z(n);else{this.#R(o);let s=this.#e[o];if(this.#t(s)?s.__abortController.abort(new Error("deleted")):(this.#x||this.#l)&&(this.#x&&this.#h?.(s,e,n),this.#l&&this.#i?.push([s,e,n])),this.#r.delete(e),this.#n[o]=void 0,this.#e[o]=void 0,o===this.#s)this.#s=this.#d[o];else if(o===this.#a)this.#a=this.#u[o];else{let i=this.#d[o];this.#u[i]=this.#u[o];let a=this.#u[o];this.#d[a]=this.#d[o]}this.#o--,this.#b.push(o)}}if(this.#l&&this.#i?.length){let o=this.#i,s;for(;s=o?.shift();)this.#y?.(...s)}return r}clear(){return this.#Z("delete")}#Z(e){for(let n of this.#A({allowStale:!0})){let r=this.#e[n];if(this.#t(r))r.__abortController.abort(new Error("deleted"));else{let o=this.#n[n];this.#x&&this.#h?.(r,o,e),this.#l&&this.#i?.push([r,o,e])}}if(this.#r.clear(),this.#e.fill(void 0),this.#n.fill(void 0),this.#p&&this.#_&&(this.#p.fill(0),this.#_.fill(0)),this.#w&&this.#w.fill(0),this.#a=0,this.#s=0,this.#b.length=0,this.#g=0,this.#o=0,this.#l&&this.#i){let n=this.#i,r;for(;r=n?.shift();)this.#y?.(...r)}}};var zs=({maximumBytes:t=R.hydratedTotalBytes*4}={})=>{if(Number.isSafeInteger(t)===!1||t<=0)throw new TypeError("Document source cache byte limit must be positive");return new Yt({maxSize:t,sizeCalculation:e=>Math.max(1,e.bytes.byteLength)})},Fn=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}},no=({contentRef:t,revision:e,format:n})=>de([t,e,n??null]),ah=t=>{if(typeof t!="object"||t===null)return!1;let e=t;return(e.format==="json"||e.format==="markdown")&&typeof e.revision=="string"&&e.revision.length>0&&e.bytes instanceof Uint8Array},wf=t=>Object.freeze({format:t.format,revision:t.revision,source:t.bytes}),_f=({load:t,cache:e,maximumBytes:n=R.hydratedFileBytes,onEvent:r})=>{let o=new Map;return async(s,i)=>{let a=no(s),c=o.get(a)??new Map;o.set(a,c);let u=c.get(i.signal);if(u!==void 0)return await u;let d=(async()=>{let l;try{l=await e.get(a)}catch(m){se(r,{type:"document-cache-read-failed",documentId:s.id,revision:s.revision,errorCode:qt(m)})}if(ah(l)&&l.revision===s.revision&&l.bytes.byteLength<=n&&(s.format===void 0||l.format===s.format))return se(r,{type:"document-cache-hit",documentId:s.id,revision:s.revision}),wf(l);se(r,{type:"document-cache-miss",documentId:s.id,revision:s.revision});let f=Vt({node:s,source:await t(s,i)}),p;try{p=await $e(f.source,n)}catch(m){throw m instanceof re?new Fn({message:`Document ${s.id} exceeds the cache byte limit`,documentId:s.id,contentByteLimit:n,cause:m}):m}let y=Object.freeze({format:f.format,revision:f.revision,bytes:p});try{await e.set(a,y),se(r,{type:"document-cache-stored",documentId:s.id,revision:s.revision})}catch(m){se(r,{type:"document-cache-write-failed",documentId:s.id,revision:s.revision,errorCode:qt(m)})}return wf(y)})();c.set(i.signal,d);try{return await d}finally{c.delete(i.signal),c.size===0&&o.delete(a)}}};var Ye=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}},ro=t=>{if(t?.aborted)throw new Ye({code:"REQUEST_CANCELLED",message:"Document graph resolution was cancelled",cause:t.reason})},xf=async({graph:t,rootIds:e,concurrency:n,signal:r,load:o,select:s,assemble:i})=>{ro(r);let a=ur({graph:t,rootIds:e}),c=new Map(a.map(p=>[p.id,p])),u=new Map,d=new Map;for(let p of a){let y=d.get(p.contentRef);y===void 0?d.set(p.contentRef,{representative:p,nodes:[p]}):y.nodes.push(p)}await pr([...d.values()],n,async p=>{ro(r);let y=p.representative;try{let m=await o(y,{signal:r});for(let h of p.nodes)u.set(h.id,m)}catch(m){throw r?.aborted&&ro(r),new Ye({code:"DOCUMENT_LOAD_FAILED",message:`Document ${y.id} could not be loaded`,documentId:y.id,cause:m})}});let l=$t(t.edges),f=new Map;for(let p of a){ro(r);let y=new Map;for(let h of l.get(p.id)??[]){let w=c.get(h.reference.documentId);if(w===void 0||f.has(h.reference.documentId)===!1)throw new Ye({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${p.id} dependency ${h.reference.documentId} is unavailable`,documentId:p.id,referenceId:h.referenceId});let S=f.get(h.reference.documentId),A;if(s===void 0){if(h.reference.representation.type!=="document")throw new Ye({code:"REPRESENTATION_SELECTOR_REQUIRED",message:`Document ${p.id} reference ${h.referenceId} requires a representation selector`,documentId:p.id,referenceId:h.referenceId});A=S}else try{A=await s({reference:h.reference,value:S,sourceNode:p,targetNode:w})}catch(_){throw new Ye({code:"DOCUMENT_SELECTION_FAILED",message:`Document ${p.id} reference ${h.referenceId} could not be selected`,documentId:p.id,referenceId:h.referenceId,cause:_})}y.set(h.referenceId,A)}if(u.has(p.id)===!1)throw new Ye({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${p.id} source is unavailable`,documentId:p.id});let m=u.get(p.id);try{f.set(p.id,await i({node:p,source:m,references:y}))}catch(h){throw new Ye({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${p.id} could not be assembled`,documentId:p.id,cause:h})}}return Object.freeze({roots:Object.freeze(e.map(p=>f.get(p))),values:f})};var xt=class extends Error{code;documentId;documentCount;documentLimit;contentByteLimit;totalBytes;totalByteLimit;constructor({code:e,message:n,documentId:r,documentCount:o,documentLimit:s,contentByteLimit:i,totalBytes:a,totalByteLimit:c,cause:u}){super(n,{cause:u}),this.name="DocumentResolutionLimitError",this.code=e,this.documentId=r,this.documentCount=o,this.documentLimit=s,this.contentByteLimit=i,this.totalBytes=a,this.totalByteLimit=c}},ch=(t,e)=>{let n=0,r=[],o=async()=>{if(e?.throwIfAborted(),n<t){n+=1;return}await new Promise((i,a)=>{let c,u=()=>{let d=r.indexOf(c);d!==-1&&r.splice(d,1);try{e?.throwIfAborted()}catch(l){a(l)}};c={start:()=>{e?.removeEventListener("abort",u),i()}},r.push(c),e?.addEventListener("abort",u,{once:!0})})},s=()=>{let i=r.shift();if(i===void 0){n-=1;return}i.start()};return async i=>{await o();try{return await i()}finally{s()}}},uh=async({graph:t,rootIds:e,concurrency:n,maximumBytes:r,maximumTotalBytes:o=R.hydratedTotalBytes,maximumDocuments:s=R.hydratedFileCount,signal:i,onEvent:a,allowUnresolvedReferences:c=!1,load:u})=>{let d=ur({graph:t,rootIds:e}).length,l={rootCount:e.length,documentCount:d};se(a,{type:"resolution-started",...l});try{if(d>s)throw new xt({code:"DOCUMENT_COUNT_EXCEEDED",message:"Document graph resolution exceeds the document limit",documentCount:d,documentLimit:s});let f=0,p=Promise.resolve(),y=await xf({graph:t,rootIds:e,concurrency:n,signal:i,load:async(m,h)=>{let w=p,S=()=>{};p=new Promise(_=>{S=_});let A;try{A={status:"fulfilled",value:await u(m,h)}}catch(_){A={status:"rejected",reason:_}}await w;try{if(A.status==="rejected")throw A.reason;if(A.value.byteLength>r)throw new xt({code:"CONTENT_LIMIT_EXCEEDED",message:`Document ${m.id} exceeds the byte limit`,documentId:m.id,contentByteLimit:r,cause:new re});let _=f+A.value.byteLength;if(_>o)throw new xt({code:"TOTAL_BYTES_EXCEEDED",message:"Document graph resolution exceeds the total byte limit",documentId:m.id,totalBytes:_,totalByteLimit:o});return f=_,await A.value.parse()}finally{S()}},select:({reference:m,value:h})=>df({document:h,representation:m.representation}),assemble:({source:m,references:h})=>ff({document:m,references:h,allowUnresolvedReferences:c})});return se(a,{type:"resolution-completed",...l}),y}catch(f){throw se(a,{type:"resolution-failed",...l,errorCode:qt(f)}),f}},Sf=({load:t,concurrency:e,signal:n,maximumDocumentBytes:r=R.hydratedFileBytes,maximumCacheBytes:o=R.hydratedTotalBytes*4})=>{if(Number.isSafeInteger(e)===!1||e<=0)throw new TypeError("Document resolution concurrency must be positive");if(Number.isSafeInteger(r)===!1||r<=0)throw new TypeError("Document resolution byte limit must be positive");if(Number.isSafeInteger(o)===!1||o<=0)throw new TypeError("Document resolution cache byte limit must be positive");let s=new Yt({maxSize:o,sizeCalculation:({byteLength:f})=>Math.max(1,f)}),i=new Map,a=ch(e,n),c=f=>{if(f!==void 0&&f!==n)throw new TypeError("Document resolution session signal does not match");n?.throwIfAborted()},u=async f=>(c(),n===void 0?await f:await new Promise((p,y)=>{let m=()=>n.removeEventListener("abort",h),h=()=>{m();try{n.throwIfAborted()}catch(w){y(w)}};n.addEventListener("abort",h,{once:!0}),f.then(w=>{m(),p(w)},w=>{m(),y(w)}),n.aborted&&h()})),d=async(f,p)=>{c(p.signal);let y=no(f),m=s.get(y);if(m!==void 0)return m;let h=i.get(y);if(h!==void 0)return await u(h);let w=a(async()=>{c(p.signal);let S=Vt({node:f,source:await t(f,{signal:n})});c(p.signal);let A=await Jo(S.source,r+1);c(p.signal);let _,b=Object.freeze({format:S.format,revision:S.revision,bytes:A,byteLength:A.byteLength,parse:()=>(_??=lf({format:S.format,source:A,maximumBytes:r}),_)});return b.byteLength<=o&&s.set(y,b),b});i.set(y,w);try{return await u(w)}finally{i.delete(y)}};return Object.freeze({getCached:f=>{c();let p=s.get(no(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 uh({...f,concurrency:e,maximumBytes:r,signal:n,load:d})})};var Af=t=>{if(t.output.mode==="all")return"all";let e=[];for(let{field:n}of mn(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},Ef=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",...il(e)]}catch{return}},vf=(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},kf=({queryPaths:t,referenceId:e})=>{let n=Ef(e);return n!==void 0&&(t==="all"||t.some(r=>vf(r,n)))},Df=({graph:t,sourceId:e,field:n})=>n[0]!=="properties"?!1:t.edges.some(r=>{if(r.sourceId!==e)return!1;let o=Ef(r.referenceId);return o!==void 0&&vf(n,o)}),Rf=({graph:t,query:e})=>{let n=Af(e),r=new Set;for(let o of t.edges)kf({queryPaths:n,referenceId:o.referenceId})&&r.add(o.sourceId);return[...r]},Of=({graph:t,query:e,rootIds:n})=>{let r=Af(e),o=new Set(n),s=new Map(t.nodes.map(l=>[l.id,l])),i=$t(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)&&kf({queryPaths:r,referenceId:l.referenceId})&&(c.add(l),d(l.reference.documentId));return yn({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 If=({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:yn({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 lh=(t,e)=>{if(e===void 0||e.length===0)return t;let n=new URL("https://content.webstudio.invalid/__assets__/"),r=new URL(t,n),o=new URL(e,n);for(let[a,c]of o.searchParams)r.searchParams.append(a,c);if(o.hash!==""&&(r.hash=o.hash),URL.canParse(t))return r.href;if(t.startsWith("//"))return`//${r.host}${r.pathname}${r.search}${r.hash}`;if(t.startsWith("/"))return`${r.pathname}${r.search}${r.hash}`;let s=n.pathname;return`${r.pathname.startsWith(s)?r.pathname.slice(s.length):r.pathname}${r.search}${r.hash}`},Cf=({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=lh(i,s.suffix);o=`${o.slice(0,s.start)}${a}${o.slice(s.end)}`}return o};var ie=class extends Error{code;details;constructor({code:e,message:n,details:r}){super(n),this.name="AssetResourceHydrationError",this.code=e,this.details=r}},fh=t=>{if(t===null)return[];let e=Array.isArray(t)?t:[t],n=new Map;for(let r of e){if(typeof r!="object"||r===null||!("_id"in r)||typeof r._id!="string"||!("revision"in r)||typeof r.revision!="string"||!("contentRef"in r)||typeof r.contentRef!="string")throw new ie({code:"CONTENT_IDENTITY_REQUIRED",message:"Hydrated query results must retain _id, revision, and contentRef"});let o=n.get(r._id);if(o!==void 0&&(o.revision!==r.revision||o.contentRef!==r.contentRef))throw new ie({code:"CONTENT_IDENTITY_REQUIRED",message:"A selected asset ID has conflicting content identity",details:{assetId:r._id}});n.set(r._id,{_id:r._id,revision:r.revision,contentRef:r.contentRef})}return Array.from(n.values())},dh=t=>typeof t.mimeType=="string"&&(t.mimeType.startsWith("text/")||["application/json","application/javascript","application/xml","image/svg+xml"].includes(t.mimeType)),ph=async({read:t,contentRef:e,range:n,maximumBytes:r})=>{if(r===0)return new Uint8Array;let o=await t(e,n);try{return await $e(o.data,r)}catch(s){throw s instanceof re?new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Asset storage returned more content than requested"}):s}},mh=t=>{try{return fe(t)}catch{throw new ie({code:"CONTENT_DECODING_FAILED",message:"Selected asset content is not valid UTF-8"})}},hh=(t,e)=>{if(e.mode==="range")return Math.max(0,Math.min(e.length,t.size-e.offset));let n=e.maxBytes??R.hydratedFileBytes;if(t.size>n)throw new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected asset exceeds the per-file content limit",details:{assetId:t._id,assetBytes:t.size,fileByteLimit:n}});return t.size},Nf=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=fh(t);if(i.length>R.hydratedFileCount)throw new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Too many selected assets requested content hydration",details:{fileCount:i.length,fileCountLimit:R.hydratedFileCount}});let a=new Map(e.map(l=>[l._id,l])),c=i.map(l=>{let f=a.get(l._id);if(f===void 0||f.revision!==l.revision||f.contentRef!==l.contentRef||typeof f.size!="number"||typeof f.mimeType!="string")throw new ie({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset content identity is stale or unavailable",details:{assetId:l._id}});let p={...f,size:f.size,mimeType:f.mimeType};if(dh(p)===!1)throw new ie({code:"CONTENT_NOT_TEXT",message:"Selected binary asset cannot be embedded as text",details:{assetId:l._id,mimeType:p.mimeType}});return{identity:l,document:p,readLength:hh(p,n)}}),u=c.reduce((l,f)=>l+f.readLength,0);if(u>R.hydratedTotalBytes)throw new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected assets exceed the total hydrated-content limit",details:{totalReadBytes:u,totalByteLimit:R.hydratedTotalBytes}});let d=await pr(c,R.concurrentContentReads,async l=>{let f=n.mode==="range"?{offset:n.offset,length:l.readLength}:l.readLength===0?void 0:{offset:0,length:l.readLength},p=await ph({read:r,contentRef:l.identity.contentRef,range:f,maximumBytes:l.readLength});if(p.byteLength!==l.readLength)throw new ie({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset bytes do not match canonical metadata",details:{assetId:l.identity._id}});let y;if(n.mode==="markdown-body-ref")try{y=(await Wr(p,l.readLength||1)).body;let h=o?.[l.identity.contentRef];h!==void 0&&s!==void 0&&(y=Cf({markdown:y,references:h,assetUrls:s}))}catch{throw new ie({code:"CONTENT_DECODING_FAILED",message:"Selected Markdown body could not be decoded",details:{assetId:l.identity._id}})}else y=mh(p);let m=Ne(y);return{id:l.identity._id,returnedBytes:m,content:{...l.identity,encoding:"utf-8",text:y,...n.mode==="range"?{range:{offset:n.offset,length:p.byteLength,total:l.document.size}}:{}}}});return{content:Object.fromEntries(d.map(({id:l,content:f})=>[l,f])),hydratedFileCount:c.length,hydratedBytes:d.reduce((l,{returnedBytes:f})=>l+f,0)}};var $v=v().datetime({offset:!0}).transform(t=>new Date(t).toISOString());var yh=/^[A-Za-z_][A-Za-z0-9_]*$/,$f=(t,e)=>yh.test(e)?`${t}.${e}`:`${t}[${JSON.stringify(e)}]`;var Tf=({document:t,includes:e})=>{let n={};for(let r of el){let o=t[r];o!==void 0&&e(r)&&(n[r]=o)}return n},zf=({source:t,target:e,path:n})=>{let[r,...o]=n;if(r===void 0||Object.hasOwn(t,r)===!1)return;let s=t[r];if(o.length===0){Object.defineProperty(e,r,{value:s,enumerable:!0,configurable:!0,writable:!0});return}if(typeof s!="object"||s===null||Array.isArray(s))return;let i={};if(zf({source:s,target:i,path:o}),Object.keys(i).length===0)return;let a=e[r];Object.defineProperty(e,r,{value:{...typeof a=="object"&&a!==null&&Array.isArray(a)===!1?a:{},...i},enumerable:!0,configurable:!0,writable:!0})},Pf=({properties:t,fields:e})=>{let n={};for(let r of e)r[0]==="properties"&&zf({source:t,target:n,path:r.slice(1)});return n};var Zn=t=>Object.fromEntries(Object.entries(t??{}).map(([e,n])=>[e,n.url]));var gh=(t,e)=>{if(e===void 0)return t;let n="https://content.webstudio.invalid",r=new URL(t,`${n}/`),o=new URL(e,`${n}/`);for(let[s,i]of o.searchParams)r.searchParams.append(s,i);return o.hash!==""&&(r.hash=o.hash),t.startsWith("//")?`//${r.host}${r.pathname}${r.search}${r.hash}`:t.startsWith("/")?`${r.pathname}${r.search}${r.hash}`:r.href},Ps=({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]=Ps({value:t[r],path:o,replacement:n}),s}return typeof r!="string"?t:{...t,[r]:Ps({value:t[r],path:o,replacement:n})}},Ht=({value:t,references:e,assetUrls:n})=>{let r=t;for(let o of e??[]){let s=n[o.assetId];s!==void 0&&(r=Ps({value:r,path:o.path,replacement:gh(s,o.suffix)}))}return r};var Ue=class extends Error{constructor(e,n){super(e,n),this.name="AssetQueryExecutionError"}},en=class extends Error{constructor(){super("The requested asset index revision is stale"),this.name="AssetIndexRevisionError"}},Lf=t=>{if(t[0]!=="properties")return t[0];let e="properties";for(let n of t.slice(1))e=$f(e,n);return e},Mf=({filter:t,fieldTypes:e})=>rl(e).includes(t.operator),Ff=(t,e)=>t!==void 0&&Object.hasOwn(t.fields,e)?t.fields[e]:void 0,bh=({query:t,catalog:e})=>{let n=st.parse(t),r=new Map,o=[];for(let s of mn(n.where)){let i=Lf(s.field);if(r.set(i,s.field),s.field[0]==="properties"){let a=Ff(e,i);e!==void 0&&a===void 0?o.push(`Asset field ${i} is not currently observed`):a!==void 0&&Mf({filter:s,fieldTypes:a.types})===!1&&o.push(`Operator ${s.operator} is not compatible with the currently observed types of ${i}`)}else if(Mf({filter:s,fieldTypes:es[s.field[0]]})===!1)throw new Ue(`Operator ${s.operator} is incompatible with ${i}`)}for(let s of n.sort){let i=Lf(s.field);if(r.set(i,s.field),s.field[0]==="properties"){let a=Ff(e,i);e!==void 0&&a===void 0?o.push(`Asset field ${i} is not currently observed`):a!==void 0&&a.types.some(c=>c==="object"||c==="array")&&o.push(`Asset field ${i} currently includes structured values that use deterministic JSON sort order`)}}return{query:n,referencedFieldPaths:[...r.values()],warnings:[...new Set(o)]}},Ms=(t,e,n)=>{let r=e[0]==="id"?t._id:fr(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},wh=t=>typeof t=="string"||Array.isArray(t)?t.length===0:typeof t=="object"&&t!==null&&Object.keys(t).length===0,_h=(t,e)=>{if(typeof t=="number"&&typeof e=="number")return t-e;if(typeof t=="string"&&typeof e=="string")return Te(t,e)},Fs=(t,e,n)=>{let r=Ms(t,e.field,n);if(e.operator==="exists")return r!=null===e.value;if(e.operator==="isEmpty")return wh(r)===e.value;if(e.operator==="eq")return hn(r,e.value);if(e.operator==="ne")return hn(r,e.value)===!1;if(e.operator==="in")return e.value.some(s=>hn(r,s));if(e.operator==="contains")return typeof r=="string"&&typeof e.value=="string"?r.includes(e.value):Array.isArray(r)&&r.some(s=>hn(s,e.value));if(e.operator==="startsWith")return typeof r=="string"&&typeof e.value=="string"&&r.startsWith(e.value);if(e.operator==="endsWith")return typeof r=="string"&&typeof e.value=="string"&&r.endsWith(e.value);let o=_h(r,e.value);return o===void 0?!1:e.operator==="gt"?o>0:e.operator==="gte"?o>=0:e.operator==="lt"?o<0:o<=0},xh=({document:t,where:e,runtimeAsset:n,filterKeys:r,filterResults:o})=>Ot(e,s=>{let i=r.get(s)??de(s),a=o.get(i);if(a!==void 0)return a;let c=Fs(t,s,n);return o.set(i,c),c})===!0,Sh=({document:t,content:e})=>e.mode!=="markdown-body-ref"||t.mimeType==="text/markdown"||t.extension==="md",Ah=(t,e)=>{let n=t==null,r=e==null;return n||r?n===r?0:n?1:-1:typeof t=="number"&&typeof e=="number"?t-e:(typeof t=="string"||typeof t=="boolean")&&(typeof e=="string"||typeof e=="boolean")?Te(String(t),String(e)):Te(de(t),de(e))},Eh=({left:t,right:e,sort:n,runtimeAssets:r})=>{for(let o of n){let s=Ah(Ms(t,o.field,r?.[t._id]),Ms(e,o.field,r?.[e._id]));if(s!==0)return o.direction==="asc"?s:-s}return Te(t._id,e._id)};var vh=(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=Pf({properties:t.properties,fields:e.fields});return Object.keys(n).length===0?void 0:n},Xt=(t,e)=>t.includeMetadata&&tl(e)||t.mode==="fields"&&t.fields.some(n=>n.length===1&&n[0]===e),kh=t=>t.mode==="all"||t.mode==="fields"&&t.fields.some(e=>e.length===1&&e[0]==="excerpt"),Dh=(t,e,n)=>{if(Xt(e,"url")&&n===void 0)throw new Error(`Asset URL is unavailable for ${t._id}`);let r=vh(t,e),o=n?.width!==void 0&&n.height!==void 0;return{...n!==void 0&&Xt(e,"url")?{url:n.url}:{},...o&&Xt(e,"width")?{width:n.width}:{},...o&&Xt(e,"height")?{height:n.height}:{},...Tf({document:t,includes:s=>Xt(e,s)}),...r===void 0?{}:{properties:r},...t.excerpt===void 0||kh(e)===!1?{}:{excerpt:t.excerpt},...t.metadataError===void 0||e.includeMetadata===!1?{}:{metadataError:t.metadataError}}},Zs=t=>{if(Ne(de(t))>R.resultBytes)throw new Ue("Asset query result exceeds the byte limit")},oo=(t,e,n)=>{t[e]={status:"rejected",reason:n}},Rh=({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=bh({query:a,catalog:e}).query}catch(l){oo(n,i,l);continue}for(let l of mn(c.where))o.set(l,de(l));let u=de(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}},Zf=({preparedQueries:t,results:e,createReason:n})=>{for(let{index:r}of t)oo(e,r,n())},Ls=t=>t.map(e=>{if(e===void 0)throw new Error("Asset query result was not settled");return e}),Oh=({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(Sh({document:i,content:d.content})===!1||xh({document:i,where:d.where,runtimeAsset:a,filterKeys:n,filterResults:c})===!1)continue;let l=Dh(i,d.output,a);if(d.content.mode==="none"&&Object.keys(l).length===0&&Xt(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){oo(o,u.index,l)}}}for(let i of r.values())i.sorted=[...i.documents].sort((a,c)=>Eh({left:a,right:c,sort:i.sort,runtimeAssets:s}))},Ih=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(f=>{let p=s.matches.get(f);return p===void 0?[]:[p]}),c=a.slice(i.offset,i.offset+i.limit),u=c.map(({document:f})=>f),d=c.map(({item:f})=>f);if(i.content.mode!=="none"){let f=i.content;if(n===void 0)throw new Ue("Asset content reader is unavailable");let p=await Nf({result:u,documents:u,options:f,read:n,assetReferences:r,assetUrls:r===void 0?void 0:o});d=u.map((y,m)=>{let h=p.content[y._id];if(h===void 0)throw new Ue("Selected asset content could not be read");return{...d[m],content:{encoding:h.encoding,text:h.text,...h.range===void 0?{}:{range:h.range}}}})}let l={items:d,totalCount:a.length,hasMore:i.offset+c.length<a.length};Zs(l),e[s.index]={status:"fulfilled",value:l}}catch(a){oo(e,s.index,a)}}))},jf=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}=Rh({inputs:t,catalog:e,results:a});if(n.length>R.candidateDocuments)return Zf({preparedQueries:u,results:a,createReason:()=>new Ue("Asset query document limit was exceeded")}),Ls(a);let l=Zn(o),f;try{f=n.map(p=>Ht({value:p,references:i?.[p._id],assetUrls:l}))}catch(p){return Zf({preparedQueries:u,results:a,createReason:()=>p}),Ls(a)}return Oh({preparedQueries:u,documents:f,filterKeys:c,sortGroups:d,results:a,runtimeAssets:o}),await Ih({preparedQueries:u,results:a,read:r,assetReferences:s,assetUrls:l}),Ls(a)};var Ch=async t=>await Uu(de(st.parse(t)));var Nh=({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}},$h=t=>dr.parse({items:t.rows.map(e=>{let n={};for(let[r,o]of t.fields.entries())Nh({item:n,field:o,value:e[r]});return n}),totalCount:t.totalCount,hasMore:t.hasMore}),Bf=async({queries:t,query:e,assetValueReferences:n,assetUrls:r={}})=>{if(t===void 0)return;let o=t[await Ch(st.parse(e))];if(o===void 0)return;let s=$h(o),i={...s,items:s.items.map(a=>Ht({value:a,references:n?.[a.id],assetUrls:r}))};return Zs(i),i};var Th=(t,e)=>e===void 0?Ct(t):{async*[Symbol.asyncIterator](){let n=0,r=0;for await(let o of Ct(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}}},zh=({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=Vt({node:c,source:n(c)??await e(c,{signal:o})});return{data:Th(u.source,a),...a===void 0?{}:{contentLength:a.length}}}},Ph=({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 en},c=b=>async(E,k)=>{let x=t.contents?.[E];if(x===void 0){let B=b??s;if(B===void 0)throw new Error("Content is not embedded in this database");return await B(E,k)}let I=It(x),M=k===void 0?I:I.slice(k.offset,k.offset+k.length);return{data:async function*(){yield M}(),contentLength:M.byteLength}},u=b=>{if(b.status==="rejected")throw b.reason;return b.value},d=async({requests:b,queryContentReader:E,runtimeAssets:k,documents:x=t.documents})=>await jf({queries:b.map(({query:I})=>I),catalog:n,documents:x,read:c(E),runtimeAssets:k,assetReferences:t.assetReferences,assetValueReferences:t.assetValueReferences}),l=async({request:b,...E})=>u((await d({...E,requests:[b]}))[0]),f=async({requests:b,queryContentReader:E,runtimeAssets:k})=>{let x=Array.from({length:b.length}),I=Zn(k),M=[];for(let[B,$]of b.entries()){try{a($);let ae=await Bf({queries:t.queries,query:$.query,assetValueReferences:t.assetValueReferences,assetUrls:I});if(ae!==void 0){x[B]={status:"fulfilled",value:ae};continue}}catch(ae){x[B]={status:"rejected",reason:ae};continue}M.push(B)}if(M.length>0){let B=await d({requests:M.map($=>b[$]),queryContentReader:E,runtimeAssets:k});for(let[$,ae]of M.entries())x[ae]=B[$]}return x.map(B=>{if(B===void 0)throw new Error("Content database query was not settled");return B})},p=async(b,E,k)=>u((await f({requests:[b],queryContentReader:E,runtimeAssets:k}))[0]),y=async(...b)=>await p(...b),m=b=>async(E,k)=>{let x=o?.get(E.id);return x!==void 0?{format:"json",revision:E.revision,source:JSON.stringify(x.properties)}:await b(E,k)},h=({graph:b,query:E,runtimeAssets:k})=>{let x=Zn(k);return Rf({graph:b,query:E}).filter(I=>{let M=i.get(I),B=M===void 0?void 0:Ht({value:M,references:t.assetValueReferences?.[I],assetUrls:x});return B===void 0?!1:Ot(E.where,$=>{if(!Df({graph:b,sourceId:I,field:$.field}))return Fs(B,$,k?.[I])})!==!1})},w=({rootIds:b,roots:E})=>{let k=new Map(b.flatMap((x,I)=>{let M=uf(E[I]);return M===void 0?[]:[[x,M]]}));return t.documents.map(x=>{let I=k.get(x._id);return I===void 0?x:Xo.parse({...x,properties:I})})},S=async({request:b,graph:E,resolutionSession:k,contentReader:x,runtimeAssets:I,onEvent:M})=>{a(b);let B=st.parse(b.query),$=h({graph:E,query:B,runtimeAssets:I});if($.length===0)return await p(b,x,I);let ae=Of({graph:E,query:B,rootIds:$});se(M,{type:"roots-selected",rootCount:$.length});let io=await k.resolve({graph:ae,rootIds:$,onEvent:M,allowUnresolvedReferences:!0}),ao=w({rootIds:$,roots:io.roots});return await l({request:b,queryContentReader:x,runtimeAssets:I,documents:ao})},A=async({requests:b,load:E,resolutionSession:k,readContent:x,runtimeAssets:I,signal:M,onEvent:B})=>{if(r===void 0)return await f({requests:b,queryContentReader:x,runtimeAssets:I});let $=m(E),ae=k??Sf({load:$,concurrency:R.concurrentContentReads,signal:M}),io=zh({graph:r,load:$,getCached:ae.getCached,readFallback:x??s,signal:M});return await Promise.allSettled(b.map(ao=>S({request:ao,graph:r,resolutionSession:ae,contentReader:io,runtimeAssets:I,onEvent:B})))};return{query:y,queryManyWithDocumentGraph:A,queryWithDocumentGraph:async({request:b,...E})=>u((await A({...E,requests:[b]}))[0])}};var js=({artifact:t,readContent:e})=>{let n=If({artifact:t});return Ph({artifact:t,revision:t.revision,documentGraph:n?.graph,inlineDocuments:n?.inlineDocuments,readContent:e})};var so=class extends Error{constructor(e,n){super(e,n),this.name="AssetQueryRequestError"}},jn=class extends Error{},Lh=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},Uf=async t=>{let e;try{e=await Lh(t,R.requestBytes)}catch(n){throw n instanceof jn?new so("Asset query request exceeds the byte limit",{cause:n}):n}try{return ol.parse(JSON.parse(fe(e)))}catch(n){throw new so("Asset query request is invalid",{cause:n})}};var Qf=t=>{if(t instanceof en)return{code:"STALE_INDEX",message:t.message,retryable:!1,status:409};if(t instanceof Ue)return{code:"INVALID_REQUEST",message:t.message,retryable:!1,status:400};if(t instanceof ie)return{code:t.code,message:t.message,retryable:!1,details:t.details,status:400};let e=new Set,n=t;for(;n!==void 0&&e.has(n)===!1;){if(n instanceof xt){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 Fn)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 Mh="/$resources/assets",Gf=(t,e=200)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json; charset=utf-8"}}),Bn=({code:t,message:e,status:n,retryable:r=!1,details:o})=>Gf(sl({code:t,message:e,retryable:r,details:o}),n),Fh=(t,e,n)=>typeof t=="string"||t instanceof URL?new Request(new URL(t,e),n):new Request(t,n),Zh=async({deploymentId:t,artifact:e,request:n})=>{let r=await n.clone().text(),o=n.headers.get("cache-control"),s=await Wo(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"})},vk=({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,fetchDocument:s=globalThis.fetch,onDocumentGraphEvent:i})=>{Vf({artifact:e,runtimeAssets:n});let a=zs();return qf({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,database:js({artifact:e}),fetchDocument:s,documentCache:a,onDocumentGraphEvent:i})},jh=({baseUrl:t,runtimeAssets:e,fetchDocument:n,cache:r,onEvent:o})=>_f({cache:r,onEvent:o,load:mf({fetch:n,getRequest:s=>{let i=e[s.id];if(i===void 0)throw new Error(`Published document URL is unavailable for ${s.id}`);return new URL(i.url,t)},getMetadata:({node:s})=>({format:s.format,revision:s.revision}),onEvent:o})}),Vf=({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}`)},qf=({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,database:s,fetchDocument:i,documentCache:a,onDocumentGraphEvent:c})=>{let u=new URL(o).origin,d=jh({baseUrl:o,runtimeAssets:n,fetchDocument:i,cache:a,onEvent:c});return async(l,f)=>{let p=Fh(l,o,f),y=new URL(p.url);if(y.origin!==u||y.pathname!==Mh||p.method.toUpperCase()!=="POST")return;let m;try{m=await Uf(p.clone())}catch{return Bn({code:"INVALID_REQUEST",message:"Asset resource request is invalid",status:400})}let h=r===void 0||p.headers.has("cache-control")===!1?void 0:await Zh({deploymentId:t,artifact:e,request:p});if(h!==void 0&&r!==void 0){let w=await r.match(h).catch(()=>{});if(w!==void 0)return new Response(w.body,w)}try{if(p.signal.aborted)return Bn({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let w=Gf(await s.queryWithDocumentGraph({request:m,load:d,runtimeAssets:n,signal:p.signal,onEvent:c}));return h!==void 0&&r!==void 0&&p.signal.aborted===!1&&(w.headers.set("cache-control",p.headers.get("cache-control")),await r.put(h,w.clone()).catch(()=>{})),w}catch(w){if(p.signal.aborted)return Bn({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let S=Qf(w);return Bn(S!==void 0?S:{code:"INTERNAL_ERROR",message:"Published asset query failed",status:500,retryable:!0})}}},kk=({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)};Vf({artifact:e,runtimeAssets:n});let c=js({artifact:e}),u=zs();return async({request:d,fallback:l})=>{let f=new URL(d.url).origin,p=qf({deploymentId:t,artifact:e,runtimeAssets:n,cache:a,baseUrl:f,database:c,fetchDocument:l,documentCache:u,onDocumentGraphEvent:r});return async(y,m)=>await p(y,m)??l(y,m)}};export{kk as createGeneratedAssetResourceRuntime,vk as createPublishedAssetResourceFetch};
+`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Jr(e),r=Vt(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=Jr(e),r=Vt(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 Xm(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Pn||null,prettyErrors:e}}function $s(t,e={}){let{lineCounter:n,prettyErrors:r}=Xm(e),o=new Ln(n?.addNewLine),s=new Tn(e),i=null;for(let a of s.compose(o.parse(t),!0,t.length))if(!i)i=a;else if(i.options.logLevel!=="silent"){i.errors.push(new Re(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(i.errors.forEach(_s(t,n)),i.warnings.forEach(_s(t,n))),i}var Oe=class extends Error{code;constructor(e){super(`Structured data failed validation: ${e}`),this.name="StructuredDataError",this.code=e}},th=t=>$e(JSON.stringify(t)),nf=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},rf=(t,e)=>{if(nf(t)===!1)throw new Oe("INVALID");let n=0,r=(s,i)=>{if(i>e.depth)throw new Oe("DEPTH_EXCEEDED");if(typeof s=="string"){if($e(s)>e.stringBytes)throw new Oe("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 Oe("FIELDS_EXCEEDED");return r(a,i+1)});if(nf(s)){let a=Object.create(null);for(let[c,u]of Object.entries(s)){if(n+=1,n>e.fields)throw new Oe("FIELDS_EXCEEDED");a[c]=r(u,i+1)}return a}throw new Oe("INVALID")},o=r(t,1);if(th(o)>e.serializedBytes)throw new Oe("SERIALIZED_BYTES_EXCEEDED");return o};var H=class extends Error{code;constructor(e,n){super(n),this.name="MarkdownMetadataError",this.code=e}};var Mn=new Uint8Array([239,187,191]),of=Mn.byteLength+10,nh=(t,e,n=0)=>t.byteLength-n<e.byteLength?!1:e.every((r,o)=>t[n+o]===r),Fn=(t,e)=>{let n=0;if(nh(t,Mn))n=Mn.byteLength;else if(t.byteLength<Mn.byteLength&&Mn.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 rh={bytes:R.frontmatterBytes,depth:R.frontmatterDepth,fields:R.frontmatterFields,stringBytes:R.frontmatterStringBytes,serializedBytes:R.indexedPropertiesBytes},sf=t=>{try{return fe(t)}catch{throw new H("FRONTMATTER_DECODING_FAILED","Markdown frontmatter is not valid UTF-8")}},af=(t,e)=>{let n=$s(t,{schema:"core",uniqueKeys:!0});if(n.errors.length>0)throw new H("FRONTMATTER_INVALID","Markdown frontmatter contains invalid YAML");let r;try{r=n.toJS({maxAliasCount:0})}catch{throw new H("FRONTMATTER_INVALID","Markdown frontmatter contains unsupported YAML aliases")}if(r===null)return{};try{return rf(r,e)}catch(o){throw o instanceof Oe?o.code==="DEPTH_EXCEEDED"?new H("FRONTMATTER_DEPTH_EXCEEDED","Markdown frontmatter exceeds the nesting limit"):o.code==="FIELDS_EXCEEDED"?new H("FRONTMATTER_FIELDS_EXCEEDED","Markdown frontmatter exceeds the field limit"):o.code==="STRING_BYTES_EXCEEDED"?new H("FRONTMATTER_STRING_BYTES_EXCEEDED","Markdown frontmatter contains a string that exceeds the byte limit"):o.code==="SERIALIZED_BYTES_EXCEEDED"?new H("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter properties exceed the indexed byte limit"):new H("FRONTMATTER_INVALID","Markdown frontmatter must contain a JSON-compatible object"):o}},cf=async(t,e={})=>{let n={...rh,...e},r=n.bytes+of,o=new Uint8Array(r),s=0;for await(let c of Nt(t)){let u=0;for(;u<c.byteLength;){let d=r-s;if(d<=0)break;let l=Math.max(0,6-s),f=Math.min(c.byteLength-u,l);if(l===0){let m=c.subarray(u,Math.min(c.byteLength,u+d)),h=m.indexOf(10);f=h===-1?m.byteLength:h+1}o.set(c.subarray(u,u+f),s),s+=f,u+=f;let p=o.subarray(0,s),y=Fn(p,!1);if(y===null)return{properties:{},frontmatterBytes:0,consumedBytes:p.length};if(y!==void 0){let m=y.yamlEnd-y.yamlStart;if(m>n.bytes)throw new H("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter exceeds the byte limit");let h=sf(p.subarray(y.yamlStart,y.yamlEnd));return{properties:af(h,n),frontmatterBytes:m,consumedBytes:y.blockEnd}}}if(s>=r)break}let i=o.subarray(0,s),a=Fn(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=sf(i.subarray(a.yamlStart,a.yamlEnd));return{properties:af(u,n),frontmatterBytes:c,consumedBytes:a.blockEnd}}}throw new H("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter is not closed within the byte limit")};var Wr=async(t,e=R.hydratedFileBytes)=>{if(Number.isInteger(e)===!1||e<=0||e>R.hydratedFileBytes)throw new H("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown body byte limit is outside the supported range");let n;try{n=await Te(t,e)}catch(a){throw a instanceof re?new H("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown content exceeds the byte limit"):a}let r;try{r=fe(n)}catch{throw new H("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}let s=Fn(n,!0)?.blockEnd??0,i;try{i=s===0?$t(r):fe(n.subarray(s))}catch{throw new H("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}return{body:i,bodyBytes:$e(i),sourceBytes:n.byteLength}};var pt=class extends Error{code;referenceId;constructor({code:e,message:n,referenceId:r,cause:o}){super(n,{cause:o}),this.name="MarkdownDocumentError",this.code=e,this.referenceId=r}},oh=C({source:v(),body:v(),frontmatter:_e(v(),rt())}),Hr=t=>{let e;try{e=oh.parse(t)}catch(n){throw new pt({code:"INVALID_DOCUMENT",message:"Markdown document is invalid",cause:n})}return Object.freeze({source:e.source,body:e.body,frontmatter:ot(e.frontmatter)})},Yr="#frontmatter",sh=t=>`${Yr}${t.slice(1)}`,ih=t=>{if(t!==Yr&&t.startsWith(`${Yr}/`)===!1)throw new pt({code:"UNUSED_REFERENCE",message:`Resolved Markdown reference ${t} is outside frontmatter`,referenceId:t});return`#${t.slice(Yr.length)}`},ah=t=>{let e=t.referenceId===void 0?void 0:sh(t.referenceId),n="INVALID_DOCUMENT";throw(t.code==="INVALID_REFERENCE_MARKER"||t.code==="INVALID_REFERENCE"||t.code==="REFERENCE_NOT_FOUND"||t.code==="INVALID_RESOLVED_VALUE"||t.code==="UNUSED_REFERENCE")&&(n=t.code),new pt({code:n,message:t.message,referenceId:e,cause:t})},uf=async({source:t,maximumBytes:e=R.hydratedFileBytes})=>{let n;try{n=await Te(t,e)}catch(i){throw i instanceof re?new pt({code:"CONTENT_LIMIT_EXCEEDED",message:"Markdown document exceeds the byte limit",cause:i}):i}let r;try{r=$t(fe(n))}catch(i){throw new pt({code:"CONTENT_DECODING_FAILED",message:"Markdown document is not valid UTF-8",cause:i})}let[o,s]=await Promise.all([Wr(n,e),cf(n)]);return Hr({source:r,body:o.body,frontmatter:s.properties})};var lf=({document:t,references:e,allowUnresolvedReferences:n=!1})=>{let r=Hr(t),o=new Map;for(let[i,a]of e)o.set(ih(i),a);let s;try{s=mr({document:r.frontmatter,references:o,allowUnresolvedReferences:n})}catch(i){throw i instanceof pe&&ah(i),i}return Hr({...r,frontmatter:s})},ff=({document:t,representation:e})=>{let n=Hr(t);if(e.type==="document")return n.source;if(e.type==="markdown-body")return n.body;if(e.type==="markdown-frontmatter")return n.frontmatter;throw new pt({code:"UNSUPPORTED_REPRESENTATION",message:`Markdown documents do not support ${e.type}`})};var df=t=>{let e=t.format==="markdown"?t.value.frontmatter:t.value;return zt(e)?e:void 0},Xr=t=>Object.freeze(t),pf=async({format:t,source:e,maximumBytes:n=R.hydratedFileBytes})=>Xr(t==="json"?{format:t,value:await fl({source:e,maximumBytes:n})}:{format:t,value:await uf({source:e,maximumBytes:n})});var mf=({document:t,references:e,allowUnresolvedReferences:n})=>t.format==="json"?Xr({format:t.format,value:mr({document:t.value,references:e,allowUnresolvedReferences:n})}):Xr({format:t.format,value:lf({document:t.value,references:e,allowUnresolvedReferences:n})}),hf=({document:t,representation:e})=>t.format==="json"?dl({document:t.value,representation:e}):ff({document:t.value,representation:e});var eo=class extends Error{code;documentId;expectedRevision;actualRevision;expectedFormat;actualFormat;constructor({code:e,documentId:n,expectedRevision:r,actualRevision:o,expectedFormat:s,actualFormat:i}){super(`Document ${n} source ${e==="REVISION_MISMATCH"?"revision":"format"} does not match its graph`),this.name="DocumentSourceError",this.code=e,this.documentId=n,this.expectedRevision=r,this.actualRevision=o,this.expectedFormat=s,this.actualFormat=i}},qt=({node:t,source:e})=>{if(e.revision!==t.revision)throw new eo({code:"REVISION_MISMATCH",documentId:t.id,expectedRevision:t.revision,actualRevision:e.revision});if(t.format!==void 0&&e.format!==t.format)throw new eo({code:"FORMAT_MISMATCH",documentId:t.id,expectedFormat:t.format,actualFormat:e.format});return e};var Jt=t=>{if(typeof t=="object"&&t!==null){let e=Reflect.get(t,"code");if(typeof e=="string"&&e.length>0)return e;let n=Reflect.get(t,"name");if(typeof n=="string"&&n.length>0)return n}return"UNKNOWN"},se=(t,e)=>{try{t?.(e)}catch{}},yf=({load:t,onEvent:e})=>async(n,r)=>{let o={documentId:n.id,revision:n.revision};se(e,{type:"document-fetch-started",...o});try{let s=await t(n,r);return se(e,{type:"document-fetch-completed",...o}),s}catch(s){throw se(e,{type:"document-fetch-failed",...o,errorCode:Jt(s)}),s}};var ch=C({format:ce(["json","markdown"]),revision:v().min(1)}),Kt=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}},uh=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()}}}),gf=({fetch:t,getRequest:e,getMetadata:n,onEvent:r})=>yf({load:async(s,{signal:i})=>{let a;try{a=await t(e(s),{signal:i})}catch(d){throw new Kt({code:"REQUEST_FAILED",message:`Document ${s.id} request failed`,documentId:s.id,cause:d})}if(a.ok===!1)throw new Kt({code:"HTTP_STATUS",message:`Document ${s.id} request returned status ${a.status}`,documentId:s.id,status:a.status});let c;try{c=ch.parse(n({node:s,response:a}))}catch(d){throw new Kt({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 Kt({code:"BODY_MISSING",message:`Document ${s.id} response body is unavailable`,documentId:s.id});return Object.freeze({...c,source:uh(u)})},onEvent:r});var Wt=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,wf=new Set,Ts=typeof process=="object"&&process?process:{},_f=(t,e,n,r)=>{typeof Ts.emitWarning=="function"?Ts.emitWarning(t,e,n,r):console.error(`[${n}] ${e}: ${t}`)},to=globalThis.AbortController,bf=globalThis.AbortSignal;if(typeof to>"u"){bf=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},to=class{constructor(){e()}signal=new bf;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=Ts.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,_f("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 lh=t=>!wf.has(t),XE=Symbol("type"),mt=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),xf=t=>mt(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Yt:null:null,Yt=class extends Array{constructor(e){super(e),this.fill(0)}},zs=class t{heap;length;static#c=!1;static create(e){let n=xf(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]}},Ht=class t{#c;#f;#h;#y;#O;#C;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#g;#r;#n;#e;#u;#d;#a;#s;#b;#i;#w;#_;#p;#x;#k;#l;static unsafeExposeInternals(e){return{starts:e.#_,ttls:e.#p,sizes:e.#w,keyMap:e.#r,keyList:e.#n,valList:e.#e,next:e.#u,prev:e.#d,get head(){return e.#a},get tail(){return e.#s},free:e.#b,isBackgroundFetch:n=>e.#t(n),backgroundFetch:(n,r,o,s)=>e.#T(n,r,o,s),moveToTail:n=>e.#I(n),indexes:n=>e.#S(n),rindexes:n=>e.#A(n),isStale:n=>e.#m(n)}}get max(){return this.#c}get maxSize(){return this.#f}get calculatedSize(){return this.#g}get size(){return this.#o}get fetchMethod(){return this.#O}get memoMethod(){return this.#C}get dispose(){return this.#h}get disposeAfter(){return this.#y}constructor(e){let{max:n=0,ttl:r,ttlResolution:o=1,ttlAutopurge:s,updateAgeOnGet:i,updateAgeOnHas:a,allowStale:c,dispose:u,disposeAfter:d,noDisposeOnSet:l,noUpdateTTL:f,maxSize:p=0,maxEntrySize:y=0,sizeCalculation:m,fetchMethod:h,memoMethod:b,noDeleteOnFetchRejection:S,noDeleteOnStaleGet:A,allowStaleOnFetchRejection:_,allowStaleOnFetchAbort:w,ignoreFetchAbort:E}=e;if(n!==0&&!mt(n))throw new TypeError("max option must be a nonnegative integer");let k=n?xf(n):Array;if(!k)throw new Error("invalid max value: "+n);if(this.#c=n,this.#f=p,this.maxEntrySize=y||this.#f,this.sizeCalculation=m,this.sizeCalculation){if(!this.#f&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(b!==void 0&&typeof b!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#C=b,h!==void 0&&typeof h!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=h,this.#k=!!h,this.#r=new Map,this.#n=new Array(n).fill(void 0),this.#e=new Array(n).fill(void 0),this.#u=new k(n),this.#d=new k(n),this.#a=0,this.#s=0,this.#b=zs.create(n),this.#o=0,this.#g=0,typeof u=="function"&&(this.#h=u),typeof d=="function"?(this.#y=d,this.#i=[]):(this.#y=void 0,this.#i=void 0),this.#x=!!this.#h,this.#l=!!this.#y,this.noDisposeOnSet=!!l,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!S,this.allowStaleOnFetchRejection=!!_,this.allowStaleOnFetchAbort=!!w,this.ignoreFetchAbort=!!E,this.maxEntrySize!==0){if(this.#f!==0&&!mt(this.#f))throw new TypeError("maxSize must be a positive integer if specified");if(!mt(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#j()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!A,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!a,this.ttlResolution=mt(o)||o===0?o:1,this.ttlAutopurge=!!s,this.ttl=r||0,this.ttl){if(!mt(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#z()}if(this.#c===0&&this.ttl===0&&this.#f===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#c&&!this.#f){let x="LRU_CACHE_UNBOUNDED";lh(x)&&(wf.add(x),_f("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",x,t))}}getRemainingTTL(e){return this.#r.has(e)?1/0:0}#z(){let e=new Yt(this.#c),n=new Yt(this.#c);this.#p=e,this.#_=n,this.#P=(s,i,a=Wt.now())=>{if(n[s]=i!==0?a:0,e[s]=i,i!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#m(s)&&this.#E(this.#n[s],"expire")},i+1);c.unref&&c.unref()}},this.#D=s=>{n[s]=e[s]!==0?Wt.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=Wt.now();if(this.ttlResolution>0){r=s;let i=setTimeout(()=>r=0,this.ttlResolution);i.unref&&i.unref()}return s};this.getRemainingTTL=s=>{let i=this.#r.get(s);if(i===void 0)return 0;let a=e[i],c=n[i];if(!a||!c)return 1/0;let u=(r||o())-c;return a-u},this.#m=s=>{let i=n[s],a=e[s];return!!a&&!!i&&(r||o())-i>a}}#D=()=>{};#v=()=>{};#P=()=>{};#m=()=>!1;#j(){let e=new Yt(this.#c);this.#g=0,this.#w=e,this.#R=n=>{this.#g-=e[n],e[n]=0},this.#L=(n,r,o,s)=>{if(this.#t(r))return 0;if(!mt(o))if(s){if(typeof s!="function")throw new TypeError("sizeCalculation must be a function");if(o=s(r,n),!mt(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#N=(n,r,o)=>{if(e[n]=r,this.#f){let s=this.#f-e[n];for(;this.#g>s;)this.#$(!0)}this.#g+=e[n],o&&(o.entrySize=r,o.totalCalculatedSize=this.#g)}}#R=e=>{};#N=(e,n,r)=>{};#L=(e,n,r,o)=>{if(r||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#S({allowStale:e=this.allowStale}={}){if(this.#o)for(let n=this.#s;!(!this.#M(n)||((e||!this.#m(n))&&(yield n),n===this.#a));)n=this.#d[n]}*#A({allowStale:e=this.allowStale}={}){if(this.#o)for(let n=this.#a;!(!this.#M(n)||((e||!this.#m(n))&&(yield n),n===this.#s));)n=this.#u[n]}#M(e){return e!==void 0&&this.#r.get(this.#n[e])===e}*entries(){for(let e of this.#S())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*rentries(){for(let e of this.#A())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*keys(){for(let e of this.#S()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*rkeys(){for(let e of this.#A()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*values(){for(let e of this.#S())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#A())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,n={}){for(let r of this.#S()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;if(s!==void 0&&e(s,this.#n[r],this))return this.get(this.#n[r],n)}}forEach(e,n=this){for(let r of this.#S()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;s!==void 0&&e.call(n,s,this.#n[r],this)}}rforEach(e,n=this){for(let r of this.#A()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;s!==void 0&&e.call(n,s,this.#n[r],this)}}purgeStale(){let e=!1;for(let n of this.#A({allowStale:!0}))this.#m(n)&&(this.#E(this.#n[n],"expire"),e=!0);return e}info(e){let n=this.#r.get(e);if(n===void 0)return;let r=this.#e[n],o=this.#t(r)?r.__staleWhileFetching:r;if(o===void 0)return;let s={value:o};if(this.#p&&this.#_){let i=this.#p[n],a=this.#_[n];if(i&&a){let c=i-(Wt.now()-a);s.ttl=c,s.start=Date.now()}}return this.#w&&(s.size=this.#w[n]),s}dump(){let e=[];for(let n of this.#S({allowStale:!0})){let r=this.#n[n],o=this.#e[n],s=this.#t(o)?o.__staleWhileFetching:o;if(s===void 0||r===void 0)continue;let i={value:s};if(this.#p&&this.#_){i.ttl=this.#p[n];let a=Wt.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=Wt.now()-o}this.set(n,r.value,r)}}set(e,n,r={}){if(n===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:s,noDisposeOnSet:i=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=r,{noUpdateTTL:u=this.noUpdateTTL}=r,d=this.#L(e,n,r.size||0,a);if(this.maxEntrySize&&d>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#E(e,"set"),this;let l=this.#o===0?void 0:this.#r.get(e);if(l===void 0)l=this.#o===0?this.#s:this.#b.length!==0?this.#b.pop():this.#o===this.#c?this.#$(!1):this.#o,this.#n[l]=e,this.#e[l]=n,this.#r.set(e,l),this.#u[this.#s]=l,this.#d[l]=this.#s,this.#s=l,this.#o++,this.#N(l,d,c),c&&(c.set="add"),u=!1;else{this.#I(l);let f=this.#e[l];if(n!==f){if(this.#k&&this.#t(f)){f.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:p}=f;p!==void 0&&!i&&(this.#x&&this.#h?.(p,e,"set"),this.#l&&this.#i?.push([p,e,"set"]))}else i||(this.#x&&this.#h?.(f,e,"set"),this.#l&&this.#i?.push([f,e,"set"]));if(this.#R(l),this.#N(l,d,c),this.#e[l]=n,c){c.set="replace";let p=f&&this.#t(f)?f.__staleWhileFetching:f;p!==void 0&&(c.oldValue=p)}}else c&&(c.set="update")}if(o!==0&&!this.#p&&this.#z(),this.#p&&(u||this.#P(l,o,s),c&&this.#v(c,l)),!i&&this.#l&&this.#i){let f=this.#i,p;for(;p=f?.shift();)this.#y?.(...p)}return this}pop(){try{for(;this.#o;){let e=this.#e[this.#a];if(this.#$(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#l&&this.#i){let e=this.#i,n;for(;n=e?.shift();)this.#y?.(...n)}}}#$(e){let n=this.#a,r=this.#n[n],o=this.#e[n];return this.#k&&this.#t(o)?o.__abortController.abort(new Error("evicted")):(this.#x||this.#l)&&(this.#x&&this.#h?.(o,r,"evict"),this.#l&&this.#i?.push([o,r,"evict"])),this.#R(n),e&&(this.#n[n]=void 0,this.#e[n]=void 0,this.#b.push(n)),this.#o===1?(this.#a=this.#s=0,this.#b.length=0):this.#a=this.#u[n],this.#r.delete(r),this.#o--,n}has(e,n={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:o}=n,s=this.#r.get(e);if(s!==void 0){let i=this.#e[s];if(this.#t(i)&&i.__staleWhileFetching===void 0)return!1;if(this.#m(s))o&&(o.has="stale",this.#v(o,s));else return r&&this.#D(s),o&&(o.has="hit",this.#v(o,s)),!0}else o&&(o.has="miss");return!1}peek(e,n={}){let{allowStale:r=this.allowStale}=n,o=this.#r.get(e);if(o===void 0||!r&&this.#m(o))return;let s=this.#e[o];return this.#t(s)?s.__staleWhileFetching:s}#T(e,n,r,o){let s=n===void 0?void 0:this.#e[n];if(this.#t(s))return s;let i=new to,{signal:a}=r;a?.addEventListener("abort",()=>i.abort(a.reason),{signal:i.signal});let c={signal:i.signal,options:r,context:o},u=(m,h=!1)=>{let{aborted:b}=i.signal,S=r.ignoreFetchAbort&&m!==void 0;if(r.status&&(b&&!h?(r.status.fetchAborted=!0,r.status.fetchError=i.signal.reason,S&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),b&&!S&&!h)return l(i.signal.reason);let A=p;return this.#e[n]===p&&(m===void 0?A.__staleWhileFetching?this.#e[n]=A.__staleWhileFetching:this.#E(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,m,c.options))),m},d=m=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=m),l(m)),l=m=>{let{aborted:h}=i.signal,b=h&&r.allowStaleOnFetchAbort,S=b||r.allowStaleOnFetchRejection,A=S||r.noDeleteOnFetchRejection,_=p;if(this.#e[n]===p&&(!A||_.__staleWhileFetching===void 0?this.#E(e,"fetch"):b||(this.#e[n]=_.__staleWhileFetching)),S)return r.status&&_.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),_.__staleWhileFetching;if(_.__returned===_)throw m},f=(m,h)=>{let b=this.#O?.(e,s,c);b&&b instanceof Promise&&b.then(S=>m(S===void 0?void 0:S),h),i.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(m(void 0),r.allowStaleOnFetchAbort&&(m=S=>u(S,!0)))})};r.status&&(r.status.fetchDispatched=!0);let p=new Promise(f).then(u,d),y=Object.assign(p,{__abortController:i,__staleWhileFetching:s,__returned:void 0});return n===void 0?(this.set(e,y,{...c.options,status:void 0}),n=this.#r.get(e)):this.#e[n]=y,y}#t(e){if(!this.#k)return!1;let n=e;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof to}async fetch(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:l=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:y=this.allowStaleOnFetchAbort,context:m,forceRefresh:h=!1,status:b,signal:S}=n;if(!this.#k)return b&&(b.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,status:b});let A={allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,ttl:i,noDisposeOnSet:a,size:c,sizeCalculation:u,noUpdateTTL:d,noDeleteOnFetchRejection:l,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:y,ignoreFetchAbort:p,status:b,signal:S},_=this.#r.get(e);if(_===void 0){b&&(b.fetch="miss");let w=this.#T(e,_,A,m);return w.__returned=w}else{let w=this.#e[_];if(this.#t(w)){let M=r&&w.__staleWhileFetching!==void 0;return b&&(b.fetch="inflight",M&&(b.returnedStale=!0)),M?w.__staleWhileFetching:w.__returned=w}let E=this.#m(_);if(!h&&!E)return b&&(b.fetch="hit"),this.#I(_),o&&this.#D(_),b&&this.#v(b,_),w;let k=this.#T(e,_,A,m),O=k.__staleWhileFetching!==void 0&&r;return b&&(b.fetch=E?"stale":"refresh",O&&E&&(b.returnedStale=!0)),O?k.__staleWhileFetching:k.__returned=k}}async forceFetch(e,n={}){let r=await this.fetch(e,n);if(r===void 0)throw new Error("fetch() returned undefined");return r}memo(e,n={}){let r=this.#C;if(!r)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:s,...i}=n,a=this.get(e,i);if(!s&&a!==void 0)return a;let c=r(e,a,{options:i,context:o});return this.set(e,c,i),c}get(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,status:i}=n,a=this.#r.get(e);if(a!==void 0){let c=this.#e[a],u=this.#t(c);return i&&this.#v(i,a),this.#m(a)?(i&&(i.get="stale"),u?(i&&r&&c.__staleWhileFetching!==void 0&&(i.returnedStale=!0),r?c.__staleWhileFetching:void 0):(s||this.#E(e,"expire"),i&&r&&(i.returnedStale=!0),r?c:void 0)):(i&&(i.get="hit"),u?c.__staleWhileFetching:(this.#I(a),o&&this.#D(a),c))}else i&&(i.get="miss")}#F(e,n){this.#d[n]=e,this.#u[e]=n}#I(e){e!==this.#s&&(e===this.#a?this.#a=this.#u[e]:this.#F(this.#d[e],this.#u[e]),this.#F(this.#s,e),this.#s=e)}delete(e){return this.#E(e,"delete")}#E(e,n){let r=!1;if(this.#o!==0){let o=this.#r.get(e);if(o!==void 0)if(r=!0,this.#o===1)this.#Z(n);else{this.#R(o);let s=this.#e[o];if(this.#t(s)?s.__abortController.abort(new Error("deleted")):(this.#x||this.#l)&&(this.#x&&this.#h?.(s,e,n),this.#l&&this.#i?.push([s,e,n])),this.#r.delete(e),this.#n[o]=void 0,this.#e[o]=void 0,o===this.#s)this.#s=this.#d[o];else if(o===this.#a)this.#a=this.#u[o];else{let i=this.#d[o];this.#u[i]=this.#u[o];let a=this.#u[o];this.#d[a]=this.#d[o]}this.#o--,this.#b.push(o)}}if(this.#l&&this.#i?.length){let o=this.#i,s;for(;s=o?.shift();)this.#y?.(...s)}return r}clear(){return this.#Z("delete")}#Z(e){for(let n of this.#A({allowStale:!0})){let r=this.#e[n];if(this.#t(r))r.__abortController.abort(new Error("deleted"));else{let o=this.#n[n];this.#x&&this.#h?.(r,o,e),this.#l&&this.#i?.push([r,o,e])}}if(this.#r.clear(),this.#e.fill(void 0),this.#n.fill(void 0),this.#p&&this.#_&&(this.#p.fill(0),this.#_.fill(0)),this.#w&&this.#w.fill(0),this.#a=0,this.#s=0,this.#b.length=0,this.#g=0,this.#o=0,this.#l&&this.#i){let n=this.#i,r;for(;r=n?.shift();)this.#y?.(...r)}}};var Ps=({maximumBytes:t=R.hydratedTotalBytes*4}={})=>{if(Number.isSafeInteger(t)===!1||t<=0)throw new TypeError("Document source cache byte limit must be positive");return new Ht({maxSize:t,sizeCalculation:e=>Math.max(1,e.bytes.byteLength)})},Zn=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}},no=({contentRef:t,revision:e,format:n})=>de([t,e,n??null]),fh=t=>{if(typeof t!="object"||t===null)return!1;let e=t;return(e.format==="json"||e.format==="markdown")&&typeof e.revision=="string"&&e.revision.length>0&&e.bytes instanceof Uint8Array},Sf=t=>Object.freeze({format:t.format,revision:t.revision,source:t.bytes}),Af=({load:t,cache:e,maximumBytes:n=R.hydratedFileBytes,onEvent:r})=>{let o=new Map;return async(s,i)=>{let a=no(s),c=o.get(a)??new Map;o.set(a,c);let u=c.get(i.signal);if(u!==void 0)return await u;let d=(async()=>{let l;try{l=await e.get(a)}catch(m){se(r,{type:"document-cache-read-failed",documentId:s.id,revision:s.revision,errorCode:Jt(m)})}if(fh(l)&&l.revision===s.revision&&l.bytes.byteLength<=n&&(s.format===void 0||l.format===s.format))return se(r,{type:"document-cache-hit",documentId:s.id,revision:s.revision}),Sf(l);se(r,{type:"document-cache-miss",documentId:s.id,revision:s.revision});let f=qt({node:s,source:await t(s,i)}),p;try{p=await Te(f.source,n)}catch(m){throw m instanceof re?new Zn({message:`Document ${s.id} exceeds the cache byte limit`,documentId:s.id,contentByteLimit:n,cause:m}):m}let y=Object.freeze({format:f.format,revision:f.revision,bytes:p});try{await e.set(a,y),se(r,{type:"document-cache-stored",documentId:s.id,revision:s.revision})}catch(m){se(r,{type:"document-cache-write-failed",documentId:s.id,revision:s.revision,errorCode:Jt(m)})}return Sf(y)})();c.set(i.signal,d);try{return await d}finally{c.delete(i.signal),c.size===0&&o.delete(a)}}};var Ye=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}},ro=t=>{if(t?.aborted)throw new Ye({code:"REQUEST_CANCELLED",message:"Document graph resolution was cancelled",cause:t.reason})},Ef=async({graph:t,rootIds:e,concurrency:n,signal:r,load:o,select:s,assemble:i})=>{ro(r);let a=lr({graph:t,rootIds:e}),c=new Map(a.map(p=>[p.id,p])),u=new Map,d=new Map;for(let p of a){let y=d.get(p.contentRef);y===void 0?d.set(p.contentRef,{representative:p,nodes:[p]}):y.nodes.push(p)}await pr([...d.values()],n,async p=>{ro(r);let y=p.representative;try{let m=await o(y,{signal:r});for(let h of p.nodes)u.set(h.id,m)}catch(m){throw r?.aborted&&ro(r),new Ye({code:"DOCUMENT_LOAD_FAILED",message:`Document ${y.id} could not be loaded`,documentId:y.id,cause:m})}});let l=Tt(t.edges),f=new Map;for(let p of a){ro(r);let y=new Map;for(let h of l.get(p.id)??[]){let b=c.get(h.reference.documentId);if(b===void 0||f.has(h.reference.documentId)===!1)throw new Ye({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${p.id} dependency ${h.reference.documentId} is unavailable`,documentId:p.id,referenceId:h.referenceId});let S=f.get(h.reference.documentId),A;if(s===void 0){if(h.reference.representation.type!=="document")throw new Ye({code:"REPRESENTATION_SELECTOR_REQUIRED",message:`Document ${p.id} reference ${h.referenceId} requires a representation selector`,documentId:p.id,referenceId:h.referenceId});A=S}else try{A=await s({reference:h.reference,value:S,sourceNode:p,targetNode:b})}catch(_){throw new Ye({code:"DOCUMENT_SELECTION_FAILED",message:`Document ${p.id} reference ${h.referenceId} could not be selected`,documentId:p.id,referenceId:h.referenceId,cause:_})}y.set(h.referenceId,A)}if(u.has(p.id)===!1)throw new Ye({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${p.id} source is unavailable`,documentId:p.id});let m=u.get(p.id);try{f.set(p.id,await i({node:p,source:m,references:y}))}catch(h){throw new Ye({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${p.id} could not be assembled`,documentId:p.id,cause:h})}}return Object.freeze({roots:Object.freeze(e.map(p=>f.get(p))),values:f})};var xt=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}},dh=(t,e)=>{let n=0,r=[],o=async()=>{if(e?.throwIfAborted(),n<t){n+=1;return}await new Promise((i,a)=>{let c,u=()=>{let d=r.indexOf(c);d!==-1&&r.splice(d,1);try{e?.throwIfAborted()}catch(l){a(l)}};c={start:()=>{e?.removeEventListener("abort",u),i()}},r.push(c),e?.addEventListener("abort",u,{once:!0})})},s=()=>{let i=r.shift();if(i===void 0){n-=1;return}i.start()};return async i=>{await o();try{return await i()}finally{s()}}},ph=async({graph:t,rootIds:e,concurrency:n,maximumBytes:r,maximumTotalBytes:o=R.hydratedTotalBytes,maximumDocuments:s=R.hydratedFileCount,signal:i,onEvent:a,allowUnresolvedReferences:c=!1,load:u})=>{let d=lr({graph:t,rootIds:e}).length,l={rootCount:e.length,documentCount:d};se(a,{type:"resolution-started",...l});try{if(d>s)throw new xt({code:"DOCUMENT_COUNT_EXCEEDED",message:"Document graph resolution exceeds the document limit",documentCount:d,documentLimit:s});let f=0,p=Promise.resolve(),y=await Ef({graph:t,rootIds:e,concurrency:n,signal:i,load:async(m,h)=>{let b=p,S=()=>{};p=new Promise(_=>{S=_});let A;try{A={status:"fulfilled",value:await u(m,h)}}catch(_){A={status:"rejected",reason:_}}await b;try{if(A.status==="rejected")throw A.reason;if(A.value.byteLength>r)throw new xt({code:"CONTENT_LIMIT_EXCEEDED",message:`Document ${m.id} exceeds the byte limit`,documentId:m.id,contentByteLimit:r,cause:new re});let _=f+A.value.byteLength;if(_>o)throw new xt({code:"TOTAL_BYTES_EXCEEDED",message:"Document graph resolution exceeds the total byte limit",documentId:m.id,totalBytes:_,totalByteLimit:o});return f=_,await A.value.parse()}finally{S()}},select:({reference:m,value:h})=>hf({document:h,representation:m.representation}),assemble:({source:m,references:h})=>mf({document:m,references:h,allowUnresolvedReferences:c})});return se(a,{type:"resolution-completed",...l}),y}catch(f){throw se(a,{type:"resolution-failed",...l,errorCode:Jt(f)}),f}},vf=({load:t,concurrency:e,signal:n,maximumDocumentBytes:r=R.hydratedFileBytes,maximumCacheBytes:o=R.hydratedTotalBytes*4})=>{if(Number.isSafeInteger(e)===!1||e<=0)throw new TypeError("Document resolution concurrency must be positive");if(Number.isSafeInteger(r)===!1||r<=0)throw new TypeError("Document resolution byte limit must be positive");if(Number.isSafeInteger(o)===!1||o<=0)throw new TypeError("Document resolution cache byte limit must be positive");let s=new Ht({maxSize:o,sizeCalculation:({byteLength:f})=>Math.max(1,f)}),i=new Map,a=dh(e,n),c=f=>{if(f!==void 0&&f!==n)throw new TypeError("Document resolution session signal does not match");n?.throwIfAborted()},u=async f=>(c(),n===void 0?await f:await new Promise((p,y)=>{let m=()=>n.removeEventListener("abort",h),h=()=>{m();try{n.throwIfAborted()}catch(b){y(b)}};n.addEventListener("abort",h,{once:!0}),f.then(b=>{m(),p(b)},b=>{m(),y(b)}),n.aborted&&h()})),d=async(f,p)=>{c(p.signal);let y=no(f),m=s.get(y);if(m!==void 0)return m;let h=i.get(y);if(h!==void 0)return await u(h);let b=a(async()=>{c(p.signal);let S=qt({node:f,source:await t(f,{signal:n})});c(p.signal);let A=await Jo(S.source,r+1);c(p.signal);let _,w=Object.freeze({format:S.format,revision:S.revision,bytes:A,byteLength:A.byteLength,parse:()=>(_??=pf({format:S.format,source:A,maximumBytes:r}),_)});return w.byteLength<=o&&s.set(y,w),w});i.set(y,b);try{return await u(b)}finally{i.delete(y)}};return Object.freeze({getCached:f=>{c();let p=s.get(no(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 ph({...f,concurrency:e,maximumBytes:r,signal:n,load:d})})};var kf=t=>{if(t.output.mode==="all")return"all";let e=[];for(let{field:n}of hn(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},Df=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",...ul(e)]}catch{return}},Rf=(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},If=({queryPaths:t,referenceId:e})=>{let n=Df(e);return n!==void 0&&(t==="all"||t.some(r=>Rf(r,n)))},Of=({graph:t,sourceId:e,field:n})=>n[0]!=="properties"?!1:t.edges.some(r=>{if(r.sourceId!==e)return!1;let o=Df(r.referenceId);return o!==void 0&&Rf(n,o)}),Cf=({graph:t,query:e})=>{let n=kf(e),r=new Set;for(let o of t.edges)If({queryPaths:n,referenceId:o.referenceId})&&r.add(o.sourceId);return[...r]},Nf=({graph:t,query:e,rootIds:n})=>{let r=kf(e),o=new Set(n),s=new Map(t.nodes.map(l=>[l.id,l])),i=Tt(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)&&If({queryPaths:r,referenceId:l.referenceId})&&(c.add(l),d(l.reference.documentId));return gn({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 $f=({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:gn({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 mh=(t,e)=>{if(e===void 0||e.length===0)return t;let n=new URL("https://content.webstudio.invalid/__assets__/"),r=new URL(t,n),o=new URL(e,n);for(let[a,c]of o.searchParams)r.searchParams.append(a,c);if(o.hash!==""&&(r.hash=o.hash),URL.canParse(t))return r.href;if(t.startsWith("//"))return`//${r.host}${r.pathname}${r.search}${r.hash}`;if(t.startsWith("/"))return`${r.pathname}${r.search}${r.hash}`;let s=n.pathname;return`${r.pathname.startsWith(s)?r.pathname.slice(s.length):r.pathname}${r.search}${r.hash}`},Tf=({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=mh(i,s.suffix);o=`${o.slice(0,s.start)}${a}${o.slice(s.end)}`}return o};var ie=class extends Error{code;details;constructor({code:e,message:n,details:r}){super(n),this.name="AssetResourceHydrationError",this.code=e,this.details=r}},hh=t=>{if(t===null)return[];let e=Array.isArray(t)?t:[t],n=new Map;for(let r of e){if(typeof r!="object"||r===null||!("_id"in r)||typeof r._id!="string"||!("revision"in r)||typeof r.revision!="string"||!("contentRef"in r)||typeof r.contentRef!="string")throw new ie({code:"CONTENT_IDENTITY_REQUIRED",message:"Hydrated query results must retain _id, revision, and contentRef"});let o=n.get(r._id);if(o!==void 0&&(o.revision!==r.revision||o.contentRef!==r.contentRef))throw new ie({code:"CONTENT_IDENTITY_REQUIRED",message:"A selected asset ID has conflicting content identity",details:{assetId:r._id}});n.set(r._id,{_id:r._id,revision:r.revision,contentRef:r.contentRef})}return Array.from(n.values())},yh=t=>typeof t.mimeType=="string"&&(t.mimeType.startsWith("text/")||["application/json","application/javascript","application/xml","image/svg+xml"].includes(t.mimeType)),gh=async({read:t,contentRef:e,range:n,maximumBytes:r})=>{if(r===0)return new Uint8Array;let o=await t(e,n);try{return await Te(o.data,r)}catch(s){throw s instanceof re?new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Asset storage returned more content than requested"}):s}},bh=t=>{try{return fe(t)}catch{throw new ie({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??R.hydratedFileBytes;if(t.size>n)throw new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected asset exceeds the per-file content limit",details:{assetId:t._id,assetBytes:t.size,fileByteLimit:n}});return t.size},zf=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=hh(t);if(i.length>R.hydratedFileCount)throw new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Too many selected assets requested content hydration",details:{fileCount:i.length,fileCountLimit:R.hydratedFileCount}});let a=new Map(e.map(l=>[l._id,l])),c=i.map(l=>{let f=a.get(l._id);if(f===void 0||f.revision!==l.revision||f.contentRef!==l.contentRef||typeof f.size!="number"||typeof f.mimeType!="string")throw new ie({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset content identity is stale or unavailable",details:{assetId:l._id}});let p={...f,size:f.size,mimeType:f.mimeType};if(yh(p)===!1)throw new ie({code:"CONTENT_NOT_TEXT",message:"Selected binary asset cannot be embedded as text",details:{assetId:l._id,mimeType:p.mimeType}});return{identity:l,document:p,readLength:wh(p,n)}}),u=c.reduce((l,f)=>l+f.readLength,0);if(u>R.hydratedTotalBytes)throw new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected assets exceed the total hydrated-content limit",details:{totalReadBytes:u,totalByteLimit:R.hydratedTotalBytes}});let d=await pr(c,R.concurrentContentReads,async l=>{let f=n.mode==="range"?{offset:n.offset,length:l.readLength}:l.readLength===0?void 0:{offset:0,length:l.readLength},p=await gh({read:r,contentRef:l.identity.contentRef,range:f,maximumBytes:l.readLength});if(p.byteLength!==l.readLength)throw new ie({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset bytes do not match canonical metadata",details:{assetId:l.identity._id}});let y;if(n.mode==="markdown-body-ref")try{y=(await Wr(p,l.readLength||1)).body;let h=o?.[l.identity.contentRef];h!==void 0&&s!==void 0&&(y=Tf({markdown:y,references:h,assetUrls:s}))}catch{throw new ie({code:"CONTENT_DECODING_FAILED",message:"Selected Markdown body could not be decoded",details:{assetId:l.identity._id}})}else y=bh(p);let m=$e(y);return{id:l.identity._id,returnedBytes:m,content:{...l.identity,encoding:"utf-8",text:y,...n.mode==="range"?{range:{offset:n.offset,length:p.byteLength,total:l.document.size}}:{}}}});return{content:Object.fromEntries(d.map(({id:l,content:f})=>[l,f])),hydratedFileCount:c.length,hydratedBytes:d.reduce((l,{returnedBytes:f})=>l+f,0)}};var Lv=v().datetime({offset:!0}).transform(t=>new Date(t).toISOString());var _h=/^[A-Za-z_][A-Za-z0-9_]*$/,Pf=(t,e)=>_h.test(e)?`${t}.${e}`:`${t}[${JSON.stringify(e)}]`;var Lf=({document:t,includes:e})=>{let n={};for(let r of tl){let o=t[r];o!==void 0&&e(r)&&(n[r]=o)}return n},Mf=({source:t,target:e,path:n})=>{let[r,...o]=n;if(r===void 0||Object.hasOwn(t,r)===!1)return;let s=t[r];if(o.length===0){Object.defineProperty(e,r,{value:s,enumerable:!0,configurable:!0,writable:!0});return}if(typeof s!="object"||s===null||Array.isArray(s))return;let i={};if(Mf({source:s,target:i,path:o}),Object.keys(i).length===0)return;let a=e[r];Object.defineProperty(e,r,{value:{...typeof a=="object"&&a!==null&&Array.isArray(a)===!1?a:{},...i},enumerable:!0,configurable:!0,writable:!0})},Ff=({properties:t,fields:e})=>{let n={};for(let r of e)r[0]==="properties"&&Mf({source:t,target:n,path:r.slice(1)});return n};var jn=t=>Object.fromEntries(Object.entries(t??{}).map(([e,n])=>[e,n.url]));var xh=(t,e)=>{if(e===void 0)return t;let n="https://content.webstudio.invalid",r=new URL(t,`${n}/`),o=new URL(e,`${n}/`);for(let[s,i]of o.searchParams)r.searchParams.append(s,i);return o.hash!==""&&(r.hash=o.hash),t.startsWith("//")?`//${r.host}${r.pathname}${r.search}${r.hash}`:t.startsWith("/")?`${r.pathname}${r.search}${r.hash}`:r.href},Ls=({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]=Ls({value:t[r],path:o,replacement:n}),s}return typeof r!="string"?t:{...t,[r]:Ls({value:t[r],path:o,replacement:n})}},Xt=({value:t,references:e,assetUrls:n})=>{let r=t;for(let o of e??[]){let s=n[o.assetId];s!==void 0&&(r=Ls({value:r,path:o.path,replacement:xh(s,o.suffix)}))}return r};var Ce=class extends Error{constructor(e,n){super(e,n),this.name="AssetQueryExecutionError"}},Bn=class extends Ce{code="MULTIPLE_RESULTS";matchedCount;constructor(e){super(`Expected at most one asset, but the query matched ${e}.`),this.matchedCount=e,this.name="AssetQueryMultipleResultsError"}},tn=class extends Error{constructor(){super("The requested asset index revision is stale"),this.name="AssetIndexRevisionError"}},Zf=t=>{if(t[0]!=="properties")return t[0];let e="properties";for(let n of t.slice(1))e=Pf(e,n);return e},jf=({filter:t,fieldTypes:e})=>ol(e).includes(t.operator),Bf=(t,e)=>t!==void 0&&Object.hasOwn(t.fields,e)?t.fields[e]:void 0,Sh=({query:t,catalog:e})=>{let n=st.parse(t),r=new Map,o=[];for(let s of hn(n.where)){let i=Zf(s.field);if(r.set(i,s.field),s.field[0]==="properties"){let a=Bf(e,i);e!==void 0&&a===void 0?o.push(`Asset field ${i} is not currently observed`):a!==void 0&&jf({filter:s,fieldTypes:a.types})===!1&&o.push(`Operator ${s.operator} is not compatible with the currently observed types of ${i}`)}else if(jf({filter:s,fieldTypes:es[s.field[0]]})===!1)throw new Ce(`Operator ${s.operator} is incompatible with ${i}`)}for(let s of n.sort){let i=Zf(s.field);if(r.set(i,s.field),s.field[0]==="properties"){let a=Bf(e,i);e!==void 0&&a===void 0?o.push(`Asset field ${i} is not currently observed`):a!==void 0&&a.types.some(c=>c==="object"||c==="array")&&o.push(`Asset field ${i} currently includes structured values that use deterministic JSON sort order`)}}return{query:n,referencedFieldPaths:[...r.values()],warnings:[...new Set(o)]}},Fs=(t,e,n)=>{let r=e[0]==="id"?t._id:dr(e[0])?n?.[e[0]]:t[e[0]];for(let o of e.slice(1)){if(typeof r!="object"||r===null||Object.hasOwn(r,o)===!1)return;r=r[o]}return r},Ah=t=>typeof t=="string"||Array.isArray(t)?t.length===0:typeof t=="object"&&t!==null&&Object.keys(t).length===0,Eh=(t,e)=>{if(typeof t=="number"&&typeof e=="number")return t-e;if(typeof t=="string"&&typeof e=="string")return ze(t,e)},Zs=(t,e,n)=>{let r=Fs(t,e.field,n);if(e.operator==="exists")return r!=null===e.value;if(e.operator==="isEmpty")return Ah(r)===e.value;if(e.operator==="eq")return yn(r,e.value);if(e.operator==="ne")return yn(r,e.value)===!1;if(e.operator==="in")return e.value.some(s=>yn(r,s));if(e.operator==="contains")return typeof r=="string"&&typeof e.value=="string"?r.includes(e.value):Array.isArray(r)&&r.some(s=>yn(s,e.value));if(e.operator==="startsWith")return typeof r=="string"&&typeof e.value=="string"&&r.startsWith(e.value);if(e.operator==="endsWith")return typeof r=="string"&&typeof e.value=="string"&&r.endsWith(e.value);let o=Eh(r,e.value);return o===void 0?!1:e.operator==="gt"?o>0:e.operator==="gte"?o>=0:e.operator==="lt"?o<0:o<=0},vh=({document:t,where:e,runtimeAsset:n,filterKeys:r,filterResults:o})=>Ot(e,s=>{let i=r.get(s)??de(s),a=o.get(i);if(a!==void 0)return a;let c=Zs(t,s,n);return o.set(i,c),c})===!0,kh=({document:t,content:e})=>e.mode!=="markdown-body-ref"||t.mimeType==="text/markdown"||t.extension==="md",Dh=(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(de(t),de(e))},Rh=({left:t,right:e,sort:n,runtimeAssets:r})=>{for(let o of n){let s=Dh(Fs(t,o.field,r?.[t._id]),Fs(e,o.field,r?.[e._id]));if(s!==0)return o.direction==="asc"?s:-s}return ze(t._id,e._id)};var Ih=(t,e)=>{if(t.properties===void 0)return;if(e.mode==="all")return Object.keys(t.properties).length===0?void 0:t.properties;if(e.mode!=="fields"||e.fields.some(r=>r[0]==="properties")===!1)return;let n=Ff({properties:t.properties,fields:e.fields});return Object.keys(n).length===0?void 0:n},en=(t,e)=>t.includeMetadata&&nl(e)||t.mode==="fields"&&t.fields.some(n=>n.length===1&&n[0]===e),Oh=t=>t.mode==="all"||t.mode==="fields"&&t.fields.some(e=>e.length===1&&e[0]==="excerpt"),Ch=(t,e,n)=>{if(en(e,"url")&&n===void 0)throw new Error(`Asset URL is unavailable for ${t._id}`);let r=Ih(t,e),o=n?.width!==void 0&&n.height!==void 0;return{...n!==void 0&&en(e,"url")?{url:n.url}:{},...o&&en(e,"width")?{width:n.width}:{},...o&&en(e,"height")?{height:n.height}:{},...Lf({document:t,includes:s=>en(e,s)}),...r===void 0?{}:{properties:r},...t.excerpt===void 0||Oh(e)===!1?{}:{excerpt:t.excerpt},...t.metadataError===void 0||e.includeMetadata===!1?{}:{metadataError:t.metadataError}}},js=t=>{if($e(de(t))>R.resultBytes)throw new Ce("Asset query result exceeds the byte limit")},oo=(t,e,n)=>{t[e]={status:"rejected",reason:n}},Nh=({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=Sh({query:a,catalog:e}).query}catch(l){oo(n,i,l);continue}for(let l of hn(c.where))o.set(l,de(l));let u=de(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}},Uf=({preparedQueries:t,results:e,createReason:n})=>{for(let{index:r}of t)oo(e,r,n())},Ms=t=>t.map(e=>{if(e===void 0)throw new Error("Asset query result was not settled");return e}),$h=({preparedQueries:t,documents:e,filterKeys:n,sortGroups:r,results:o,runtimeAssets:s})=>{for(let i of e){let a=s?.[i._id],c=new Map;for(let u of t){if(o[u.index]!==void 0)continue;let{query:d}=u;try{if(kh({document:i,content:d.content})===!1||vh({document:i,where:d.where,runtimeAsset:a,filterKeys:n,filterResults:c})===!1)continue;let l=Ch(i,d.output,a);if(d.content.mode==="none"&&Object.keys(l).length===0&&en(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){oo(o,u.index,l)}}}for(let i of r.values())i.sorted=[...i.documents].sort((a,c)=>Rh({left:a,right:c,sort:i.sort,runtimeAssets:s}))},Th=async({preparedQueries:t,results:e,read:n,assetReferences:r,assetUrls:o})=>{await Promise.all(t.map(async s=>{if(e[s.index]!==void 0)return;let{query:i}=s;try{let a=s.sortGroup.sorted.flatMap(p=>{let y=s.matches.get(p);return y===void 0?[]:[y]}),c=i.result??"many";if(c==="one"&&a.length>1)throw new Bn(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 Ce("Asset content reader is unavailable");let y=await zf({result:d,documents:d,options:p,read:n,assetReferences:r,assetUrls:r===void 0?void 0:o});l=d.map((m,h)=>{let b=y.content[m._id];if(b===void 0)throw new Ce("Selected asset content could not be read");return{...l[h],content:{encoding:b.encoding,text:b.text,...b.range===void 0?{}:{range:b.range}}}})}let f=c==="many"?{items:l,totalCount:a.length,hasMore:i.offset+u.length<a.length}:{item:l[0]??null,totalCount:a.length};js(f),e[s.index]={status:"fulfilled",value:f}}catch(a){oo(e,s.index,a)}}))},Qf=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}=Nh({inputs:t,catalog:e,results:a});if(n.length>R.candidateDocuments)return Uf({preparedQueries:u,results:a,createReason:()=>new Ce("Asset query document limit was exceeded")}),Ms(a);let l=jn(o),f;try{f=n.map(p=>Xt({value:p,references:i?.[p._id],assetUrls:l}))}catch(p){return Uf({preparedQueries:u,results:a,createReason:()=>p}),Ms(a)}return $h({preparedQueries:u,documents:f,filterKeys:c,sortGroups:d,results:a,runtimeAssets:o}),await Th({preparedQueries:u,results:a,read:r,assetReferences:s,assetUrls:l}),Ms(a)};var zh=async t=>await Qu(de(st.parse(t)));var Ph=({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}},Lh=t=>ts.parse({items:t.rows.map(e=>{let n={};for(let[r,o]of t.fields.entries())Ph({item:n,field:o,value:e[r]});return n}),totalCount:t.totalCount,hasMore:t.hasMore}),Gf=async({queries:t,query:e,assetValueReferences:n,assetUrls:r={}})=>{if(t===void 0)return;let o=t[await zh(st.parse(e))];if(o===void 0)return;let s=Lh(o),i={...s,items:s.items.map(a=>Xt({value:a,references:n?.[a.id],assetUrls:r}))};return js(i),i};var Mh=(t,e)=>e===void 0?Nt(t):{async*[Symbol.asyncIterator](){let n=0,r=0;for await(let o of Nt(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}}},Fh=({graph:t,load:e,getCached:n,readFallback:r,signal:o})=>{let s=new Map(t.nodes.map(i=>[i.contentRef,i]));return async(i,a)=>{let c=s.get(i);if(c===void 0){if(r!==void 0)return await r(i,a);throw new Error(`Document content reference ${i} is unavailable`)}let u=qt({node:c,source:n(c)??await e(c,{signal:o})});return{data:Mh(u.source,a),...a===void 0?{}:{contentLength:a.length}}}},Zh=({artifact:t,revision:e,catalog:n,documentGraph:r,inlineDocuments:o,readContent:s})=>{let i=new Map(t.documents.map(w=>[w._id,w])),a=w=>{if(w.indexRevision!==void 0&&w.indexRevision!==e)throw new tn},c=w=>async(E,k)=>{let x=t.contents?.[E];if(x===void 0){let B=w??s;if(B===void 0)throw new Error("Content is not embedded in this database");return await B(E,k)}let O=Ct(x),M=k===void 0?O:O.slice(k.offset,k.offset+k.length);return{data:async function*(){yield M}(),contentLength:M.byteLength}},u=w=>{if(w.status==="rejected")throw w.reason;return w.value},d=async({requests:w,queryContentReader:E,runtimeAssets:k,documents:x=t.documents})=>await Qf({queries:w.map(({query:O})=>O),catalog:n,documents:x,read:c(E),runtimeAssets:k,assetReferences:t.assetReferences,assetValueReferences:t.assetValueReferences}),l=async({request:w,...E})=>u((await d({...E,requests:[w]}))[0]),f=async({requests:w,queryContentReader:E,runtimeAssets:k})=>{let x=Array.from({length:w.length}),O=jn(k),M=[];for(let[B,$]of w.entries()){try{a($);let ae=await Gf({queries:t.queries,query:$.query,assetValueReferences:t.assetValueReferences,assetUrls:O});if(ae!==void 0){x[B]={status:"fulfilled",value:ae};continue}}catch(ae){x[B]={status:"rejected",reason:ae};continue}M.push(B)}if(M.length>0){let B=await d({requests:M.map($=>w[$]),queryContentReader:E,runtimeAssets:k});for(let[$,ae]of M.entries())x[ae]=B[$]}return x.map(B=>{if(B===void 0)throw new Error("Content database query was not settled");return B})},p=async(w,E,k)=>u((await f({requests:[w],queryContentReader:E,runtimeAssets:k}))[0]),y=async(...w)=>await p(...w),m=w=>async(E,k)=>{let x=o?.get(E.id);return x!==void 0?{format:"json",revision:E.revision,source:JSON.stringify(x.properties)}:await w(E,k)},h=({graph:w,query:E,runtimeAssets:k})=>{let x=jn(k);return Cf({graph:w,query:E}).filter(O=>{let M=i.get(O),B=M===void 0?void 0:Xt({value:M,references:t.assetValueReferences?.[O],assetUrls:x});return B===void 0?!1:Ot(E.where,$=>{if(!Of({graph:w,sourceId:O,field:$.field}))return Zs(B,$,k?.[O])})!==!1})},b=({rootIds:w,roots:E})=>{let k=new Map(w.flatMap((x,O)=>{let M=df(E[O]);return M===void 0?[]:[[x,M]]}));return t.documents.map(x=>{let O=k.get(x._id);return O===void 0?x:Xo.parse({...x,properties:O})})},S=async({request:w,graph:E,resolutionSession:k,contentReader:x,runtimeAssets:O,onEvent:M})=>{a(w);let B=st.parse(w.query),$=h({graph:E,query:B,runtimeAssets:O});if($.length===0)return await p(w,x,O);let ae=Nf({graph:E,query:B,rootIds:$});se(M,{type:"roots-selected",rootCount:$.length});let io=await k.resolve({graph:ae,rootIds:$,onEvent:M,allowUnresolvedReferences:!0}),ao=b({rootIds:$,roots:io.roots});return await l({request:w,queryContentReader:x,runtimeAssets:O,documents:ao})},A=async({requests:w,load:E,resolutionSession:k,readContent:x,runtimeAssets:O,signal:M,onEvent:B})=>{if(r===void 0)return await f({requests:w,queryContentReader:x,runtimeAssets:O});let $=m(E),ae=k??vf({load:$,concurrency:R.concurrentContentReads,signal:M}),io=Fh({graph:r,load:$,getCached:ae.getCached,readFallback:x??s,signal:M});return await Promise.allSettled(w.map(ao=>S({request:ao,graph:r,resolutionSession:ae,contentReader:io,runtimeAssets:O,onEvent:B})))};return{query:y,queryManyWithDocumentGraph:A,queryWithDocumentGraph:async({request:w,...E})=>u((await A({...E,requests:[w]}))[0])}};var Bs=({artifact:t,readContent:e})=>{let n=$f({artifact:t});return Zh({artifact:t,revision:t.revision,documentGraph:n?.graph,inlineDocuments:n?.inlineDocuments,readContent:e})};var so=class extends Error{constructor(e,n){super(e,n),this.name="AssetQueryRequestError"}},Un=class extends Error{},jh=async(t,e)=>{if(Number.isSafeInteger(e)===!1||e<0)throw new TypeError("Request byte limit must be a non-negative integer");let n=Number(t.headers.get("content-length"));if(Number.isFinite(n)&&n>e)throw new Un("Request exceeds the byte limit");let r=t.body?.getReader(),o=[],s=0;if(r!==void 0)for(;;){let{done:c,value:u}=await r.read();if(c)break;if(s+=u.byteLength,s>e){try{await r.cancel()}catch{}throw new Un("Request exceeds the byte limit")}o.push(u)}let i=new Uint8Array(s),a=0;for(let c of o)i.set(c,a),a+=c.byteLength;return i},Vf=async t=>{let e;try{e=await jh(t,R.requestBytes)}catch(n){throw n instanceof Un?new so("Asset query request exceeds the byte limit",{cause:n}):n}try{return sl.parse(JSON.parse(fe(e)))}catch(n){throw new so("Asset query request is invalid",{cause:n})}};var qf=t=>{if(t instanceof tn)return{code:"STALE_INDEX",message:t.message,retryable:!1,status:409};if(t instanceof Bn)return{code:t.code,message:t.message,retryable:!1,details:{matchedCount:t.matchedCount},status:409};if(t instanceof Ce)return{code:"INVALID_REQUEST",message:t.message,retryable:!1,status:400};if(t instanceof ie)return{code:t.code,message:t.message,retryable:!1,details:t.details,status:400};let e=new Set,n=t;for(;n!==void 0&&e.has(n)===!1;){if(n instanceof xt){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 Zn)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 Bh="/$resources/assets",Jf=(t,e=200)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json; charset=utf-8"}}),Qn=({code:t,message:e,status:n,retryable:r=!1,details:o})=>Jf(cl({code:t,message:e,retryable:r,details:o}),n),Uh=(t,e,n)=>typeof t=="string"||t instanceof URL?new Request(new URL(t,e),n):new Request(t,n),Qh=async({deploymentId:t,artifact:e,request:n})=>{let r=await n.clone().text(),o=n.headers.get("cache-control"),s=await Wo(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"})},Ik=({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,fetchDocument:s=globalThis.fetch,onDocumentGraphEvent:i})=>{Kf({artifact:e,runtimeAssets:n});let a=Ps();return Wf({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,database:Bs({artifact:e}),fetchDocument:s,documentCache:a,onDocumentGraphEvent:i})},Gh=({baseUrl:t,runtimeAssets:e,fetchDocument:n,cache:r,onEvent:o})=>Af({cache:r,onEvent:o,load:gf({fetch:n,getRequest:s=>{let i=e[s.id];if(i===void 0)throw new Error(`Published document URL is unavailable for ${s.id}`);return new URL(i.url,t)},getMetadata:({node:s})=>({format:s.format,revision:s.revision}),onEvent:o})}),Kf=({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}`)},Wf=({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,database:s,fetchDocument:i,documentCache:a,onDocumentGraphEvent:c})=>{let u=new URL(o).origin,d=Gh({baseUrl:o,runtimeAssets:n,fetchDocument:i,cache:a,onEvent:c});return async(l,f)=>{let p=Uh(l,o,f),y=new URL(p.url);if(y.origin!==u||y.pathname!==Bh||p.method.toUpperCase()!=="POST")return;let m;try{m=await Vf(p.clone())}catch{return Qn({code:"INVALID_REQUEST",message:"Asset resource request is invalid",status:400})}let h=r===void 0||p.headers.has("cache-control")===!1?void 0:await Qh({deploymentId:t,artifact:e,request:p});if(h!==void 0&&r!==void 0){let b=await r.match(h).catch(()=>{});if(b!==void 0)return new Response(b.body,b)}try{if(p.signal.aborted)return Qn({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let b=Jf(await s.queryWithDocumentGraph({request:m,load:d,runtimeAssets:n,signal:p.signal,onEvent:c}));return h!==void 0&&r!==void 0&&p.signal.aborted===!1&&(b.headers.set("cache-control",p.headers.get("cache-control")),await r.put(h,b.clone()).catch(()=>{})),b}catch(b){if(p.signal.aborted)return Qn({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let S=qf(b);return Qn(S!==void 0?S:{code:"INTERNAL_ERROR",message:"Published asset query failed",status:500,retryable:!0})}}},Ok=({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)};Kf({artifact:e,runtimeAssets:n});let c=Bs({artifact:e}),u=Ps();return async({request:d,fallback:l})=>{let f=new URL(d.url).origin,p=Wf({deploymentId:t,artifact:e,runtimeAssets:n,cache:a,baseUrl:f,database:c,fetchDocument:l,documentCache:u,onDocumentGraphEvent:r});return async(y,m)=>await p(y,m)??l(y,m)}};export{Ok as createGeneratedAssetResourceRuntime,Ik as createPublishedAssetResourceFetch};
diff --git a/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx
index 36b49b0dbb..19d72d077f 100644
--- a/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx
@@ -18,16 +18,17 @@ export const getResources = (_props: { system: System }) => {
body: {
query: ({
output: {
- mode: "fields",
- includeMetadata: false,
- fields: [["url"], ["width"], ["height"]],
- },
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["url"], ["width"], ["height"]],
+ },
content: {
- mode: "none",
- },
+ mode: "none",
+ },
+ result: "many",
where: {
- all: [],
- },
+ all: [],
+ },
sort: [],
limit: 1000,
offset: 0,
diff --git a/packages/asset-uploader/src/asset-repository.ts b/packages/asset-uploader/src/asset-repository.ts
index 6bae6f91bd..72334468fa 100644
--- a/packages/asset-uploader/src/asset-repository.ts
+++ b/packages/asset-uploader/src/asset-repository.ts
@@ -14,8 +14,9 @@ import {
requiresStructuredProperties,
type AssetQueryRequestInput,
type AssetQueryPreviewResult,
+ type AssetQueryExecutionPreviewResult,
type AssetQuery,
- type AssetQueryResult,
+ type AssetQueryExecutionResult,
type AssetRuntimeData,
type BuilderAssetFieldCatalog,
type ContentArtifactV1,
@@ -148,7 +149,7 @@ type AssetQueryPreviewOptions = {
signal?: AbortSignal;
};
-type AssetQueryResultOnly = { data: AssetQueryResult };
+type AssetQueryResultOnly = { data: AssetQueryExecutionResult };
type AssetQueryOptionsWithoutDiagnostics = AssetQueryPreviewOptions & {
includeDiagnostics: false;
};
@@ -964,7 +965,7 @@ export class PostgresAssetRepository implements AssetRepository {
});
signal?.throwIfAborted();
let batchExecution:
- | Promise<PromiseSettledResult<AssetQueryResult>[]>
+ | Promise<PromiseSettledResult<AssetQueryExecutionResult>[]>
| undefined;
const executeBatch = () => {
batchExecution ??= database.queryManyWithDocumentGraph({
@@ -1038,7 +1039,7 @@ export class PostgresAssetRepository implements AssetRepository {
async query(
request: AssetQueryRequestInput,
options: AssetQueryPreviewOptions = {}
- ): Promise<AssetQueryPreviewResult | AssetQueryResultOnly> {
+ ): Promise<AssetQueryExecutionPreviewResult | AssetQueryResultOnly> {
await this.assertCanView();
return await this.queryAfterAuthorization(request, options);
}
@@ -1052,7 +1053,7 @@ export class PostgresAssetRepository implements AssetRepository {
includeUnresolvedDiagnostics = false,
signal,
}: AssetQueryPreviewOptions = {}
- ): Promise<AssetQueryPreviewResult | AssetQueryResultOnly> {
+ ): Promise<AssetQueryExecutionPreviewResult | AssetQueryResultOnly> {
signal?.throwIfAborted();
const query = assetQuery.parse(request.query);
const plan = createContentCompilationPlan([
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 28f8ff364b..5123ea09da 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -19,6 +19,7 @@
"typecheck": "tsc --noEmit",
"generate-docs": "tsx scripts/generate-docs.ts && oxfmt src/docs.generated.ts",
"build:content-runtime": "esbuild @webstudio-is/content-engine/runtime --bundle --format=esm --platform=browser --target=es2022 --conditions=webstudio --minify --outfile=lib/content-runtime.js",
+ "fixtures:build": "pnpm build:content-runtime",
"build": "pnpm generate-docs && rm -rf lib && vite build && pnpm build:content-runtime",
"pretest": "mkdir -p lib && pnpm build:content-runtime",
"evaluations": "tsx --import ../../scripts/register-react-global.ts --conditions=webstudio evaluations/high-impact/run-local-agent.ts",
diff --git a/packages/cli/src/commands/api-command-docs.test.ts b/packages/cli/src/commands/api-command-docs.test.ts
index b6922030cc..2d752b7bed 100644
--- a/packages/cli/src/commands/api-command-docs.test.ts
+++ b/packages/cli/src/commands/api-command-docs.test.ts
@@ -215,7 +215,7 @@ test("documents the Assets result shape", () => {
expect(contents).toContain("<dataSourceName>.meta");
expect(contents).toContain("posts.data");
expect(contents).toContain("post.data");
- expect(contents).toContain("content.text");
+ expect(contents).toContain("post.data?.content?.text");
}
});
@@ -238,7 +238,7 @@ test("directs agents to deferred Markdown bodies", () => {
expect(contents).toContain('content.mode:"markdown-body-ref"');
expect(contents).toContain("document reference");
expect(contents).toContain("selected Markdown");
- expect(contents).toContain("content.text");
+ expect(contents).toContain("post.data?.content?.text");
}
const tools = createMetadataOnlyMcpAdapter().listTools();
@@ -246,7 +246,8 @@ test("directs agents to deferred Markdown bodies", () => {
const description = tools.find((tool) => tool.name === name)?.description;
expect(description).toContain("markdown-body-ref");
expect(description).toContain("document reference");
- expect(description).toContain("item.content.text");
+ expect(description).toContain("<dataSourceName>.data");
+ expect(description).toContain("content.text");
}
});
diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.ts
index 2cd88e6bee..16a34b4bcf 100644
--- a/packages/cli/src/docs.generated.ts
+++ b/packages/cli/src/docs.generated.ts
@@ -2,11 +2,11 @@
// Edit markdown files in src/docs instead.
export const cliDocs = {
"api-use-cases":
- '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get-more-tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get-more-tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search labels, text, props, resource URLs, asset metadata, and styles.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nested asset folders and upload, inspect, move, duplicate, download, replace, delete, and inspect usage for assets.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- `preview.status` reports whether generated output is `stale`. When present, `renderedProjectVersion` is the last project version materialized into the preview.\n- A managed `screenshot` or another `preview.start` refreshes stale generated output before capture.\n\n- Use this after page/content/style mutations so a vision-capable AI can see the generated site from the current MCP session. Use `path`; never pass a Webstudio Builder/share URL or capture Builder chrome.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- Iterative mode is the default: after MCP mutations, path screenshots ensure generated project files are current, wait for the exact session version, and perform an ordinary page reload without Vite HMR. The preview server and browser stay alive. Use `{"mode":"production"}` only for release-like verification; rendered audit does this automatically.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":200}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599 or a JavaScript expression string for a dynamic status.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## Submit marketplace product\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"marketplace-thumbnail.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"<uploadedAssetId>","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: publish {"target":"production"}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nNotes:\n\n- Wait for the production publish to complete before submitting the product for review.\n- Submission requires complete, valid marketplace metadata.\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}\n- webstudio duplicate-page --page <pageId> --name Paris --path /paris --substitutions \'{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}\' --json\n\nNotes:\n\n- Text substitutions replace exact fixed text only in the duplicated page\'s text children, string props, title, and metadata.\n- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.\n- Existing expressions and cloned variable/resource references keep their remapped ids.\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {}\n- MCP tool: list-pages {}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\'section\' ws:style={css`padding: 32px;`}><ws.element ws:tag=\'h2\'>Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- The `ws:` namespace contains specific Webstudio core components; it is not HTML-tag shorthand. Use `<ws.element ws:tag="div">` for a native `div` and `<ws.element ws:tag="form">` for a native form, never `<ws.div>` or `<ws.form>`.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use ``ws:style={css`...`}`` for Webstudio-native CSS, or use React-style object syntax such as `style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside the Content Block\'s `ws:block-template` child. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: 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":{"where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","draft"],"operator":"ne","value":{"type":"literal","value":true}}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"}],"limit":{"type":"literal","value":20},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["properties","excerpt"]]},"content":{"mode":"none"}}}\n- MCP tool: create-assets-resource {"name":"Post by slug or ID","scopeInstanceId":"<instanceId>","dataSourceName":"post","query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"}]},"limit":{"type":"literal","value":1},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","publishedAt"]]},"content":{"mode":"markdown-body-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":{"where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","slug"],"operator":"eq","value":"hello-world"}]},"limit":1,"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"]]},"content":{"mode":"markdown-body-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 Markdown files.\n- Minimize the deployed content database by using `output.mode:"fields"` and selecting only fields the rendered page needs. Keep `includeMetadata:false` unless the rendered value needs file metadata such as name, path, MIME type, or creation date, and avoid `output.mode:"all"` as a convenience default. Query diagnostics are returned separately and do not require metadata output. Filters and sorting may still require their referenced fields in the database.\n- Every reachable Assets data source contributes to the shared published database. Keep one final resource per rendered query. Update an existing scoped resource rather than creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicates.\n- Keep bounded overview filters, limits, and offsets literal and add a deterministic ID tie-breaker to the sort. With `content.mode:"none"`, compilation can materialize the small overview result instead of retaining its output fields across every candidate document. Use runtime expressions only for genuinely dynamic values such as the detail slug.\n- Combine filters with `where.all` (AND) and `where.any` (OR), including nested groups. Filter values, limit, and offset on a saved resource may be Webstudio expressions evaluated at render time. Preview queries use concrete JSON values.\n- Query Markdown files directly and use `content.mode:"markdown-body-ref"` when rendering their bodies. The published database retains metadata and a document reference, then fetches only the selected Markdown files from Asset storage at runtime; it does not embed their bodies. Filter and paginate before content is loaded.\n- `full` and bounded `range` continue to request embedded file bytes. Use them only when the caller requires the complete source or a byte range.\n- In Markdown, reference sibling Assets with conventional relative URLs such as `../images/hero.png`. Deferred `markdown-body-ref` content resolves matching files against the Markdown file\'s folder and emits the correct Builder or published Asset URL. Keep external URLs absolute.\n- Markdown Embed renders sanitized authored HTML for figures, captions, audio, video, and iframes. Scripts, inline event handlers, `srcdoc`, and unsafe URL protocols are removed. Executable component composition remains separate future MDX work.\n- Preview each query with concrete values before saving it. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes must not be summed and are not separate allowances. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A completed Markdown blog should include every source document without truncation, contain no embedded Markdown bodies, and retain only its intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files.\n- Read Assets from the ID-keyed map at `<dataSourceName>.data`, with collection information such as `totalCount` and `hasMore` at `<dataSourceName>.meta`. Bind a listing Collection to `posts.data` and a one-result detail Collection to `post.data`. On each value, selected file fields such as `id`, `name`, and `extension` are top-level, Markdown frontmatter and JSON fields are under `properties`, and a resolved Markdown body is at `content.text`.\n- Assets has one response shape and always executes a structured query. Omit `query` to use the default query, which selects URL and optional image dimensions. Provide query configuration to control filtering, sorting, pagination, selected fields, or file content. Set `values.query:null` to restore the default query.\n- `create-assets-resource` and `update-assets-resource` are the semantic authoring path. Do not construct the internal query URL, headers, or body expression manually.\n- The shared metadata index is maintained automatically and is emitted only when a configured Assets resource is reachable.\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: list-assets {"verbose":true}\n\nNotes:\n\n- Compact results include each asset\'s folder id. Use `verbose:true` to include complete records for a page of assets, or `get-asset` to read one complete record including description, folder, creation time, and image/font metadata.\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Get asset\n\nCommands:\n\n- MCP tool: get-asset {"assetId":"<assetId>"}\n\n## List asset folders\n\nCommands:\n\n- MCP tool: list-asset-folders {}\n\n## Create asset folder\n\nCommands:\n\n- MCP tool: create-asset-folder {"name":"Marketing"}\n- MCP tool: create-asset-folder {"name":"Photos","parentId":"<parentFolderId>"}\n\n## Update asset folder\n\nCommands:\n\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"name":"Brand"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":"<parentFolderId>"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":null}}\n\nNotes:\n\n- Updating `parentId` is the folder equivalent of cut and paste. Use `null` to move a folder to Root.\n\n## Duplicate asset folder\n\nCommands:\n\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>"}\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>","parentId":"<targetFolderId>"}\n\nNotes:\n\n- Duplication recursively copies descendant folders and assets. This is the folder equivalent of copy and paste.\n\n## Delete asset folder\n\nCommands:\n\n- MCP tool: delete-asset-folder {"folderId":"<folderId>"}\n\nNotes:\n\n- Deleting a folder recursively deletes its descendant folders and assets.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n- MCP tool: update-asset {"assetId":"<fontAssetId>","values":{"meta":{"family":"Rajdhani","style":"normal","weight":600}}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n- Font metadata updates merge with the detected metadata and are validated before committing; use this to correct a family, style, or weight after upload.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","folderId":"<folderId>","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\n## Duplicate asset\n\nCommands:\n\n- MCP tool: duplicate-asset {"assetId":"<assetId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":"<targetFolderId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":null}\n\nNotes:\n\n- Duplication is the asset equivalent of copy and paste. Updating `folderId` is the equivalent of cut and paste; use `null` for Root.\n\n## Download asset\n\nCommands:\n\n- MCP tool: download-asset {"assetId":"<assetId>"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","scopes":["resources"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- Use `search-project` for query-driven lookup across labels, text, prop values, resource URLs, asset metadata, and styles. Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility --scopes seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- webstudio audit --rendered --page-path /pricing --json\n- webstudio audit --rendered --route-example post=/blog/hello --json\n- webstudio audit --rendered --image-domain images.example.com --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"scopes":["craft"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`\n (or MCP `routeExamples`) supplies a concrete path. The path must not contain\n unresolved `:` or `*` parameters.\n- Plans above 120 captures return a short-lived confirmation token. Review the\n unchanged plan, then rerun with `--confirm-large-run` and\n `--confirmation-token`.\n- Detailed rendered evidence is stored in a versioned manifest under\n `.webstudio/audits`; compact output includes its path and screenshot count.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Verify dynamic bindings\n\nCommands:\n\n- webstudio verify-bindings --json\n- MCP tool: verify-bindings {"pagePath":"/pricing"}\n- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}\n\nNotes:\n\n- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.\n- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.\n- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.\n- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \'query Post($slug: String!) { post(slug: $slug) { title } }\', variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Render an array or object as repeated content\n\nCommands:\n\n- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<ws.element ws:tag=\'article\'><ws.element ws:tag=\'h2\'>{expression`collectionItem.title`}</ws.element></ws.element>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\n\nNotes:\n\n- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.\n- Pass `insert-collection` the complete array or object. Do not pass the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result\'s `data` field or deeper.\n- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\n- Wrap multiple repeated sibling instances in one Element inside Collection.\n- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.\n- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.\n- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.\n- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.\n- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Inspect and reuse the project\'s existing auth convention before authoring. Do\n not add a second provider or session model implicitly.\n- Model signed-out, loading, signed-in, and failed-auth states explicitly.\n- Never store credentials, service-role keys, refresh tokens, private session\n values, or authenticated response bodies in project data, command output,\n screenshots, agent instructions, or error reports. Privileged provider calls\n and authorization enforcement belong server-side.\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still\n uses the existing resource, variable, prop, binding, and embed tools; there is\n no provider-specific installer.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page"}\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\'section\'><ws.element ws:tag=\'p\'>Section copy</ws.element></ws.element>"}\n- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpointId":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after the agent can inspect the supplied design. There is no direct\n Figma, screenshot, Inception, or `design.md` import command.\n- Inspect and reuse existing variables, tokens, styles, components, assets, and\n page patterns before authoring. Build semantic editable structure rather than\n flattening the design into an image or absolute-positioned approximation.\n- Verify one familiar viewport inside every distinct Builder breakpoint range,\n then run rendered audit and inspect the screenshots before completion.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio mcp run .temp/projects.json\n- webstudio mcp run .temp/projects.json --dry-run\n- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2\n\nNotes:\n\n- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.\n- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.\n- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCall `meta.guide` with the provider-authenticated page goal, then create the\npage, resources, variables, props, bindings, and embeds with existing semantic\ntools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nCall `meta.guide` with the design-input goal, let the agent inspect the supplied\ndesign, then use semantic page, token, asset, fragment, style, preview,\nscreenshot, and audit tools. Use `apply-patch` only when no semantic operation\nfits.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',
+ '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get-more-tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get-more-tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search labels, text, props, resource URLs, asset metadata, and styles.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nested asset folders and upload, inspect, move, duplicate, download, replace, delete, and inspect usage for assets.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- `preview.status` reports whether generated output is `stale`. When present, `renderedProjectVersion` is the last project version materialized into the preview.\n- A managed `screenshot` or another `preview.start` refreshes stale generated output before capture.\n\n- Use this after page/content/style mutations so a vision-capable AI can see the generated site from the current MCP session. Use `path`; never pass a Webstudio Builder/share URL or capture Builder chrome.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- Iterative mode is the default: after MCP mutations, path screenshots ensure generated project files are current, wait for the exact session version, and perform an ordinary page reload without Vite HMR. The preview server and browser stay alive. Use `{"mode":"production"}` only for release-like verification; rendered audit does this automatically.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":200}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599 or a JavaScript expression string for a dynamic status.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## Submit marketplace product\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"marketplace-thumbnail.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"<uploadedAssetId>","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: publish {"target":"production"}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nNotes:\n\n- Wait for the production publish to complete before submitting the product for review.\n- Submission requires complete, valid marketplace metadata.\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}\n- webstudio duplicate-page --page <pageId> --name Paris --path /paris --substitutions \'{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}\' --json\n\nNotes:\n\n- Text substitutions replace exact fixed text only in the duplicated page\'s text children, string props, title, and metadata.\n- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.\n- Existing expressions and cloned variable/resource references keep their remapped ids.\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {}\n- MCP tool: list-pages {}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\'section\' ws:style={css`padding: 32px;`}><ws.element ws:tag=\'h2\'>Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- The `ws:` namespace contains specific Webstudio core components; it is not HTML-tag shorthand. Use `<ws.element ws:tag="div">` for a native `div` and `<ws.element ws:tag="form">` for a native form, never `<ws.div>` or `<ws.form>`.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use ``ws:style={css`...`}`` for Webstudio-native CSS, or use React-style object syntax such as `style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside the Content Block\'s `ws:block-template` child. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: 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 Markdown files.\n- Minimize the deployed content database by using `output.mode:"fields"` and selecting only fields the rendered page needs. Keep `includeMetadata:false` unless the rendered value needs file metadata such as name, path, MIME type, or creation date, and avoid `output.mode:"all"` as a convenience default. Query diagnostics are returned separately and do not require metadata output. Filters and sorting may still require their referenced fields in the database.\n- Every reachable Assets data source contributes to the shared published database. Keep one final resource per rendered query. Update an existing scoped resource rather than creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicates.\n- Keep bounded overview filters, limits, and offsets literal and add a deterministic ID tie-breaker to the sort. With `content.mode:"none"`, compilation can materialize the small overview result instead of retaining its output fields across every candidate document. Use runtime expressions only for genuinely dynamic values such as the detail slug.\n- Combine filters with `where.all` (AND) and `where.any` (OR), including nested groups. Filter values, limit, and offset on a saved resource may be Webstudio expressions evaluated at render time. Preview queries use concrete JSON values.\n- Query Markdown files directly and use `content.mode:"markdown-body-ref"` when rendering their bodies. The published database retains metadata and a document reference, then fetches only the selected Markdown files from Asset storage at runtime; it does not embed their bodies. Filter and paginate before content is loaded.\n- `full` and bounded `range` continue to request embedded file bytes. Use them only when the caller requires the complete source or a byte range.\n- In Markdown, reference sibling Assets with conventional relative URLs such as `../images/hero.png`. Deferred `markdown-body-ref` content resolves matching files against the Markdown file\'s folder and emits the correct Builder or published Asset URL. Keep external URLs absolute.\n- Markdown Embed renders sanitized authored HTML for figures, captions, audio, video, and iframes. Scripts, inline event handlers, `srcdoc`, and unsafe URL protocols are removed. Executable component composition remains separate future MDX work.\n- Preview each query with concrete values before saving it. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes must not be summed and are not separate allowances. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A completed Markdown blog should include every source document without truncation, contain no embedded Markdown bodies, and retain only its intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files.\n- 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\n## Duplicate asset\n\nCommands:\n\n- MCP tool: duplicate-asset {"assetId":"<assetId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":"<targetFolderId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":null}\n\nNotes:\n\n- Duplication is the asset equivalent of copy and paste. Updating `folderId` is the equivalent of cut and paste; use `null` for Root.\n\n## Download asset\n\nCommands:\n\n- MCP tool: download-asset {"assetId":"<assetId>"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","scopes":["resources"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- Use `search-project` for query-driven lookup across labels, text, prop values, resource URLs, asset metadata, and styles. Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility --scopes seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- webstudio audit --rendered --page-path /pricing --json\n- webstudio audit --rendered --route-example post=/blog/hello --json\n- webstudio audit --rendered --image-domain images.example.com --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"scopes":["craft"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`\n (or MCP `routeExamples`) supplies a concrete path. The path must not contain\n unresolved `:` or `*` parameters.\n- Plans above 120 captures return a short-lived confirmation token. Review the\n unchanged plan, then rerun with `--confirm-large-run` and\n `--confirmation-token`.\n- Detailed rendered evidence is stored in a versioned manifest under\n `.webstudio/audits`; compact output includes its path and screenshot count.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Verify dynamic bindings\n\nCommands:\n\n- webstudio verify-bindings --json\n- MCP tool: verify-bindings {"pagePath":"/pricing"}\n- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}\n\nNotes:\n\n- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.\n- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.\n- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.\n- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \'query Post($slug: String!) { post(slug: $slug) { title } }\', variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Render an array or object as repeated content\n\nCommands:\n\n- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<ws.element ws:tag=\'article\'><ws.element ws:tag=\'h2\'>{expression`collectionItem.title`}</ws.element></ws.element>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\n\nNotes:\n\n- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.\n- Pass `insert-collection` the complete array or object. Do not pass the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result\'s `data` field or deeper.\n- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\n- Wrap multiple repeated sibling instances in one Element inside Collection.\n- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.\n- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.\n- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.\n- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.\n- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Inspect and reuse the project\'s existing auth convention before authoring. Do\n not add a second provider or session model implicitly.\n- Model signed-out, loading, signed-in, and failed-auth states explicitly.\n- Never store credentials, service-role keys, refresh tokens, private session\n values, or authenticated response bodies in project data, command output,\n screenshots, agent instructions, or error reports. Privileged provider calls\n and authorization enforcement belong server-side.\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still\n uses the existing resource, variable, prop, binding, and embed tools; there is\n no provider-specific installer.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page"}\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\'section\'><ws.element ws:tag=\'p\'>Section copy</ws.element></ws.element>"}\n- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpointId":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after the agent can inspect the supplied design. There is no direct\n Figma, screenshot, Inception, or `design.md` import command.\n- Inspect and reuse existing variables, tokens, styles, components, assets, and\n page patterns before authoring. Build semantic editable structure rather than\n flattening the design into an image or absolute-positioned approximation.\n- Verify one familiar viewport inside every distinct Builder breakpoint range,\n then run rendered audit and inspect the screenshots before completion.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio mcp run .temp/projects.json\n- webstudio mcp run .temp/projects.json --dry-run\n- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2\n\nNotes:\n\n- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.\n- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.\n- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCall `meta.guide` with the provider-authenticated page goal, then create the\npage, resources, variables, props, bindings, and embeds with existing semantic\ntools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nCall `meta.guide` with the design-input goal, let the agent inspect the supplied\ndesign, then use semantic page, token, asset, fragment, style, preview,\nscreenshot, and audit tools. Use `apply-patch` only when no semantic operation\nfits.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',
"manual-api":
'# Webstudio API CLI Manual\n\nThe API commands operate on the single project configured by:\n\n- .webstudio/config.json: projectId\n- global Webstudio config: origin and token\n\n- Pass --json to API/discovery commands that support it. Do not add --json to top-level commands unless their help/schema documents it.\n- Never pass a project id. Commands use configured project only.\n- Read ids before writing. Do not invent ids for existing records.\n- stdout is one JSON object. stderr is diagnostics.\n- Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.\n\n## Start\n\n{{start}}\n\n## Read First\n\n{{readFirst}}\n\n## Project Session Cache\n\n- CLI commands use one local ProjectSession snapshot for the configured project.\n- Local-capable reads use cached namespaces when compatible and fetch only missing or stale namespaces.\n- Local-capable mutations build patches from the local snapshot, then commit with the cached build version.\n- Successful mutation commits update the local snapshot only after the remote commit succeeds.\n- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.\n- Use --refresh on local-capable commands to refresh required namespaces before running.\n- Successful JSON responses include compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.\n\n## CLI Capability Inventory\n\nFor a short end-consumer summary of what MCP can do, see\n`manual mcp` / `webstudio man mcp`. The MCP inventory describes the same\nproject, page, element, style, data, asset, publish, domain, and visual\nverification capabilities without internal command names.\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP Tool Operations\n\nThese are MCP tools. From a shell, call them with the shortcut form `webstudio <tool> \'<json>\'` or with the explicit form `webstudio mcp single-op-call <tool> \'<json>\'`:\n\n{{mcpOnlyCommandIndex}}\n\n## Task Recipes\n\n{{taskRecipeIndex}}\n\n## Use Case Index\n\n{{useCaseIndex}}\n\n## Known CLI Gaps\n\n{{knownCliGapIndex}}\n\n## Input File Shapes\n\n{{inputFileShapeIndex}}\n\n## Raw Patch Fallback\n\napply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.\n\nEach transaction has:\n\n{\n"id": "patch-transaction-label",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\n\nThe transaction id is a patch label used for optimistic synchronization. It is\nnot a Builder record id. Do not invent ids for pages, instances, props,\nbreakpoints, resources, variables, folders, assets, or other project records.\n\nPatch paths are JSON-patch-like paths into Builder store data. Map-like namespaces use ids as the first path item.\n\nSupported namespaces:\n\n- pages: redirects, page records, and folders\n- projectSettings: project-wide metadata and compiler settings\n- instances: element instances and children, including text/expression children\n- props: element props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and reusable design tokens\n- styleSourceSelections: instance-to-style-source connections\n- dataSources: data variables, parameters, and resource data sources\n- resources: data resource definitions\n- assets: project asset records handled by the existing asset patch path\n- breakpoints: responsive breakpoints\n- marketplaceProduct: marketplace metadata\n\n## Data Sources\n\n`dataSources` is the internal Builder namespace for variables. Public API, CLI,\nand MCP tools expose it through two user-facing groups:\n\n- data variables: `list-variables`, `create-variable`, `update-variable`, and\n `delete-variable`\n- data resources: `list-resources`, `create-resource`, `update-resource`, and\n `delete-resource`\n\nFor raw `snapshot`, request the public `variables` namespace rather than the\ninternal `dataSources` name. Raw patch payloads still use `dataSources` when\napplying direct changes.\n\nVariables can be scoped to an instance. Expressions under that instance can use\nthe variable by name; nested variables with the same name mask outer variables.\nVariable values support `string`, `number`, `boolean`, and `json`. Use `json`\nfor all arrays and objects, including tags, selected categories, and nested API\nfilter state.\nParameters are internal scoped runtime values provided by pages, collections,\nor components. They are not a public authoring surface: do not create, update,\nor delete parameter records. Public tools should preserve existing parameter\nrecords and may reference documented context values such as `system` in\nexpressions where they are already in scope.\n\nResource `url` accepts plain fixed URLs and paths, for example\n`https://api.example.com/posts` or `/$resources/current-date`. Dynamic URLs can\ncombine strings and variables, for example\n`"https://api.example.com/posts?tag=" + filters.tag`. Prefer `searchParams` for\nquery parameters that should be encoded separately:\n`[{ "name": "tag", "value": "filters.tag" }]`. Header values, search parameter\nvalues, and bodies are expressions for dynamic content. For fixed text, use\n`{ "type": "literal", "value": "application/json" }`; Webstudio stores the\nrequired string expression. Headers can still read variables such as\n`"Bearer " + auth.token`, and GraphQL bodies can return objects such as\n`{ query: "...", variables: { slug: system.params.slug } }`.\n\nCreate a GET resource with `scopeInstanceId` when the fetched resource result\nshould be available as a read data variable. Scoped GET resources default to\n`exposeAsDataSource: true`, are generated into the page resource `data` map,\nand may be loaded during page rendering. Use `dataSourceName` to choose the\nvariable name.\n\nFor submit/write/action resources, create the resource without\n`scopeInstanceId`, then bind a component prop such as a Form `action` to the\nresource with `bind-props` and `binding.type: "resource"`. Prop-bound resources\nare generated into the page resource `action` map instead of the read `data`\nmap. Use this shape for POST, PUT, DELETE, webhook, and other resources that\nshould run only from an explicit form/action flow, not merely because the page\nrendered.\n\nPOST, PUT, and DELETE resources default to `exposeAsDataSource: false` even\nwhen a scope is supplied. Set `exposeAsDataSource: true` only when a write-method\nresource intentionally provides render-time data, such as a read-only GraphQL\nPOST query. A scope is required, and the result includes a warning because the\nrequest may execute during page rendering. Set `exposeAsDataSource: false` on\n`update-resource` to detach an existing render-time data source.\n\nResource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read\ndata. Use POST for creates, GraphQL requests, webhooks, and form submissions.\nUse PUT for full updates/replacements. Use DELETE for deletion actions.\nOptional `control` values are `graphql` and `system`: `graphql` marks a\nGraphQL-style resource, usually POST with a query body; `system` marks a\nresource intended to use the built-in `system` parameter or one of the built-in\nlocal resource URLs: `"/$resources/sitemap.xml"`,\n`"/$resources/current-date"`, and `"/$resources/assets"`. The system parameter\nfields are `system.origin`, `system.pathname`, `system.params`, and\n`system.search`.\n\nUse prop bindings for dynamic values that read variables or resources; use\ndirect props for static values.\n\nCommit raw patch:\n\nMCP tool: apply-patch\n\n## Raw Patch Examples\n\nRename the site:\n\n[\n{\n"id": "patch-site-name",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "add", "path": ["meta", "siteName"], "value": "Acme Studio" }\n]\n}\n]\n}\n]\n\nUpdate page title metadata:\n\n[\n{\n"id": "patch-page-title",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["pages", "page-id", "meta", "title"], "value": "Pricing" }\n]\n}\n]\n}\n]\n\nUpdate a text child on an element:\n\n[\n{\n"id": "patch-text",\n"payload": [\n{\n"namespace": "instances",\n"patches": [\n{ "op": "replace", "path": ["instance-id", "children", 0, "value"], "value": "Launch faster" }\n]\n}\n]\n}\n]\n\nCreate records with semantic operations such as create-variable,\ncreate-resource, create-design-token, create-page, create-folder,\nand create-breakpoint. Raw patch rejects generated record\ncreation, collection replacement, record replacement with a different `id`, and\nrecord id field mutations in id-keyed namespaces because Webstudio must generate\nand preserve record ids.\n\n## Safety Rules\n\n- For MCP apply-patch, read the latest version with MCP snapshot before writing.\n- Reuse ids from MCP snapshot output when updating existing records.\n- Do not create generated records, replace generated record collections, replace records with different ids, or mutate record id fields with raw patch. Use semantic create operations so Webstudio generates ids.\n- If apply-patch reports a version conflict, read the latest build and regenerate the patch.\n- Prefer semantic MCP read tools for discovery, then use MCP snapshot for exact patch paths.\n\n## Command Index\n\n{{commandIndex}}\n',
"manual-llm":
- '# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Use MCP locally or optionally connect a client\n\nDo not install, register, or connect an MCP server merely because the user asks\nyou to edit a Webstudio project. If Webstudio MCP tools are already available,\nuse them. If you have shell access, use the local CLI shortcuts such as\n`webstudio meta.index` and `webstudio list-pages`; they expose the same project\noperations without changing client configuration or restarting the app.\n\nOnly when the user explicitly asks for persistent native MCP integration, run\nthe command for their client:\n\n- Claude Code: `webstudio connect claude`\n- Codex: `webstudio connect codex`\n- Cursor: `webstudio connect cursor`\n- VS Code or GitHub Copilot: `webstudio connect vscode`\n\nRun project operations from the linked project root. If the folder is not\nlinked, ask for an editable Builder share link and run\n`webstudio init --link <share-link> --json`. You can then use local CLI\nshortcuts immediately. Do not run `webstudio sync`, `webstudio connect`, or\nrestart the app unless the user specifically wants native MCP registration:\nMCP reads and edits the latest editable Builder build directly, including for\nprojects that have never been published. Treat the share link as a credential\nand do not include it in committed files, logs, screenshots, or issue reports.\n\nThe optional `connect` command verifies project access before changing client configuration. For\nClaude Code, Cursor, and VS Code it safely merges the `webstudio` server into\nthe client\'s project configuration. For Codex it runs both `codex mcp add` and\n`codex mcp get webstudio`; do not repeat those commands separately. Follow the\nreload, restart, or approval instruction printed by `connect`, then verify the\nloaded MCP connection by asking the client to use Webstudio MCP and list the\nproject pages. Use `--print` only to inspect the generated setup without\nchanging configuration or requiring project access.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a compact MCP tool overview. Add `--verbose` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get-more-tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment --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": "<ws.element ws:tag=\'section\' ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag=\'h2\'>Launch Kit</ws.element><ws.element ws:tag=\'p\'>A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag=\'button\'>Get started</ws.element></ws.element>"\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 the block\'s `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nDo not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.\n\nUse Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/Webstudio names. Do not use React-only aliases such as `className` or `htmlFor`; the runtime rejects them with the Webstudio prop name to use.\n\nUse Webstudio actions for event/action props. Do not pass JavaScript functions such as `onClick={() => ...}`; the runtime rejects them because functions cannot be persisted as Webstudio project data.\n\n```tsx\n<ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n>\n Open\n</ws.element>\n```\n\nPlain JSX prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n\nIf a component has a registered template with required parts, JSX must include those parts explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.\n\n## Animation Components\n\nBefore creating animation examples, inspect the exact components with focused discovery:\n\n```sh\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateChildren"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateText"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:StaggerAnimation"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:VideoAnimation"}\'\n```\n\nUse Animation Group (`AnimateChildren`) as the controller. Put normal instances directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it. Text, Stagger, and Video are helper components with `contentModel.category: "none"` and should not be used as standalone section roots.\n\nDefine timing and CSS changes on the Animation Group `action` prop. Use `type:"view"` for viewport entry/exit progress and `type:"scroll"` for scroll-progress timelines. For in animations, keep the canvas styles as the final state and use `fill:"backwards"` with keyframes that describe the starting state. For out animations, use `fill:"forwards"` with keyframes that describe the ending state.\n\nText Animation settings: `slidingWindow` defaults to `5`, `easing` defaults to `linear`, and `splitBy` defaults to `char`. Use `splitBy:"space"` for word-by-word animation. The parent Animation Group keyframes provide the actual opacity, translate, scale, or other styles.\n\nStagger Animation settings: `slidingWindow` defaults to `1` and `easing` defaults to `linear`. It applies parent Animation Group progress across its direct children. Use `slidingWindow:0` for instant sequential steps, `1` for one child at a time, and values above `1` for overlapping waves.\n\nVideo Animation settings: `timeline` is a boolean. Prefer `insert-component` for Video Animation so the Video child template is inserted, then configure the Video child asset/source. Use short, seek-friendly videos for smooth scroll-linked playback.\n\nUse JSX fragments for authored animation structures when you need styled, editable examples. Put the final visual state in `ws:style` and put the starting or ending animated state in the Animation Group `action` keyframes. Include an explicit `offset` on every keyframe: use `offset: 0` for starting-state keyframes with `fill:"backwards"` and `offset: 1` for ending-state keyframes with `fill:"forwards"`.\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n axis: "block",\n animations: [\n {\n name: "Fade up on entry",\n timing: {\n fill: "backwards",\n rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 24, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n ],\n }}\n>\n <ws.element\n ws:tag="section"\n ws:style={css`\n display: grid;\n gap: 16px;\n padding: 48px;\n border-radius: 24px;\n background: #111827;\n color: white;\n `}\n >\n <ws.element ws:tag="h2">Launch metrics</ws.element>\n <ws.element ws:tag="p">\n A polished card that fades up as it enters the viewport.\n </ws.element>\n </ws.element>\n</animation.AnimateChildren>\n```\n\nFor Text Animation, keep `animation.AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Parallax In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 100, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Opacity In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n {\n name: "Scale In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Parallax Out",\n timing: {\n fill: "forwards",\n rangeStart: ["cover", { type: "unit", value: 50, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 1,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: -100, unit: "px" },\n ],\n },\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n insetStart: { type: "unit", value: 5, unit: "%" },\n insetEnd: { type: "unit", value: 5, unit: "%" },\n isPinned: true,\n }}\n>\n <animation.AnimateText\n splitBy="space"\n slidingWindow={5}\n easing="easeOutQuart"\n >\n <ws.element ws:tag="h2">Animate words with controlled rhythm</ws.element>\n </animation.AnimateText>\n</animation.AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `animation.StaggerAnimation`:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n timing: {\n fill: "backwards",\n rangeStart: ["contain", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["contain", { type: "unit", value: 30, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n }}\n>\n <animation.StaggerAnimation>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </ws.element>\n </animation.StaggerAnimation>\n</animation.AnimateChildren>\n```\n\nFor Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Video progress",\n timing: {\n fill: "both",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [{ offset: 0, styles: {} }],\n },\n ],\n }}\n>\n <animation.VideoAnimation timeline={true}>\n <$.Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </animation.VideoAnimation>\n</animation.AnimateChildren>\n```\n\n## Command Surface Boundary\n\n- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, registry inspection, man, and starting MCP.\n- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.\n- From a shell, call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio insert-fragment \'<json>\' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.\n- For experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- 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. Inspect current project state with semantic reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, `list-breakpoints`, and `snapshot` only when needed. Before changing a project, read `get-project-settings` and follow any non-empty `meta.agentInstructions`. These are shared project instructions, not a place for secrets.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.\n4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.\n5. For visual/design work, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate before final response.\n6. Report what changed and what verification ran.\n\n## Visual Design Workflow\n\nFor requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:\n\n1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.\n2. Do not use generated route/component files as the source of truth for editable content.\n3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.\n4. Keep generated project files current, start preview, and capture the changed page with `screenshot`.\n5. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n6. If vision or screenshot tooling is unavailable, state that explicitly and explain what fallback verification was used.\n\n## Responsive Verification Workflow\n\nFor responsive page work, use Builder breakpoints as the source of truth:\n\n1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.\n2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.\n3. Pick screenshot viewport widths from the project breakpoints: include a desktop width, each defined max-width or min-width edge, and a narrow mobile width.\n4. Capture each viewport with `screenshot`, for example `{"path":"/","output":"home-375.png","viewport":{"width":375,"height":812}}` and `{"path":"/","output":"home-1440.png","viewport":{"width":1440,"height":900}}`.\n5. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n6. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.\n\n## Generated Files Guardrails\n\n- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.\n- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.\n- Generated files are build artifacts and may be overwritten by `webstudio build`.\n- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.\n\n## Values vs Bindings\n\nBefore authoring unfamiliar expressions, read `webstudio://project/expressions` with MCP `resources/read` or `webstudio mcp read-resource webstudio://project/expressions`. It documents the supported expression subset, method allowlist, scope, Collection context, and validation limits.\n\n- Use direct value tools for fixed content. For one visible text child, use `update-text` with plain `text`. For a bounded multi-instance literal replacement, use `replace-text` with `find`, `replace`, `pagePath` or `pageId`, and `limit`; it does not change expression children. Use `replace-prop-text` for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop\'s direct type/value.\n- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.\n- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.\n- Expression binding example: `{"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}`.\n- Page metadata fields such as `title`, `description`, `language`, `redirect`, and custom meta content accept plain fixed text. For computed values, pass JavaScript expression code such as `pageTitle ?? "Pricing | Acme"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599, for example `302`. For a dynamic status, pass JavaScript expression code such as `system.status`.\n- Page metadata update example: use `update-page` with `{"pageId":"page-id","values":{"title":"Pricing | Acme","meta":{"description":"Plans for teams"}}}`.\n- Draft a page with `update-page` and `{"pageId":"page-id","values":{"isDraft":true}}`. It remains editable and previewable but is omitted from every publish target, including staging, and from sitemap output.\n- Stage a draft page for a future publish with `{"pageId":"page-id","values":{"isDraft":false}}`. This clears draft state but does not deploy the site. The home page and `/*` catch-all page cannot be drafts.\n- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.\n- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.\n- Assets is one system resource with one response shape and always executes a structured query. `create-assets-resource` without `query` uses the default URL and optional image-dimensions output. Provide query configuration to control filtering, sorting, pagination, selected fields, or file content.\n- For a Markdown-backed blog, create exactly two Builder page definitions: a fixed `/blog` overview and one `/blog/:slug` detail page. Both pages load content through Assets resources. Never create one Builder page per post or duplicate Markdown content into static page structures. Read `get-asset-field-catalog`, validate each structured query with `validate-asset-query`, then call `create-assets-resource` or `update-assets-resource`. Set `values.query:null` to restore the default query.\n- Optimize every explicit Assets query for the deployed content-database size. Use `output.mode:"fields"` and select only fields that are actually rendered or otherwise required by the query. Keep `includeMetadata:false` unless the rendered value needs file metadata; diagnostics are returned separately. Do not use `output.mode:"all"` as a convenience default.\n- Every reachable Assets data source contributes to the shared database. Keep one final resource per rendered query. Update an existing scoped resource instead of creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicate resources and data sources.\n- Make a bounded overview fully static: use literal values for its filters, limit, and offset, add a deterministic ID tie-breaker to its sort, and use `content.mode:"none"`. This lets compilation materialize the small overview result instead of retaining overview-only fields across every candidate article. Reserve runtime expressions for values that are truly dynamic, such as `system.params.slug` on the detail route.\n- Query Markdown files directly and use `content.mode:"markdown-body-ref"` when rendering their bodies. The published database keeps only metadata and document references, filters and paginates first, and fetches the selected Markdown bodies from Asset storage at runtime. Do not create companion JSON descriptors merely to avoid embedding Markdown.\n- `full` and bounded `range` request embedded file bytes. Use them only when the caller explicitly requires the complete source or a byte range.\n- Deferred Markdown bodies exclude frontmatter and resolve conventional relative links and images such as `../images/hero.png` to matching Assets. Markdown Embed permits sanitized figures, audio, video, and iframes, but removes scripts, inline event handlers, and unsafe URLs.\n- Assets expose an ID-keyed map at `<dataSourceName>.data` and collection information at `<dataSourceName>.meta`. Bind a listing Collection to `posts.data` and a one-result detail Collection to `post.data`; each item value contains selected fields and its item key is the asset ID. Read frontmatter or JSON fields from `item.properties` and the resolved Markdown body from `item.content.text`.\n- Use `preview-asset-query` with concrete values before binding expressions in the saved resource. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes are not separate allowances and must not be summed. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A finished Markdown blog must include every source document without truncation, contain no embedded Markdown bodies, and retain only the intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files. Inspect saved mode and configuration with `list-assets-resources` or `get-assets-resource`; shared index maintenance is automatic.\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays, objects, filters, and nested data.\n- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.\n- Use scoped resources for read data. A GET resource created with `scopeInstanceId`/`dataSourceName` defaults to `exposeAsDataSource:true`, becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Read the loaded resource result from its wrapper, usually `.data`.\n- Use prop-bound resources for actions. A resource created without `scopeInstanceId` and bound to a component prop such as Form `action` with `bind-props` and `binding.type: "resource"` becomes an action resource in the page resource `action` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.\n- POST, PUT, and DELETE resources default to `exposeAsDataSource:false`, even with a scope. Set `exposeAsDataSource:true` only for an intentional render-time read such as a GraphQL POST query; provide `scopeInstanceId` and inspect the returned warning. Set it to `false` during `update-resource` to detach existing render-time exposure.\n- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Use `{"type":"literal","value":"website"}` for fixed request text. Header values can 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. Prefer optional chaining, nullish coalescing, ternaries, property/index access, operators, and the documented string/array methods.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- For visual/design work, verify the rendered result with vision before finishing.\n- Do not edit generated files for normal Webstudio content/design requests.\n- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.\n- Use plain fixed text where documented. Only encode a quoted JavaScript string literal when a field is explicitly documented as an expression-only value.\n- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n',
+ '# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Use MCP locally or optionally connect a client\n\nDo not install, register, or connect an MCP server merely because the user asks\nyou to edit a Webstudio project. If Webstudio MCP tools are already available,\nuse them. If you have shell access, use the local CLI shortcuts such as\n`webstudio meta.index` and `webstudio list-pages`; they expose the same project\noperations without changing client configuration or restarting the app.\n\nOnly when the user explicitly asks for persistent native MCP integration, run\nthe command for their client:\n\n- Claude Code: `webstudio connect claude`\n- Codex: `webstudio connect codex`\n- Cursor: `webstudio connect cursor`\n- VS Code or GitHub Copilot: `webstudio connect vscode`\n\nRun project operations from the linked project root. If the folder is not\nlinked, ask for an editable Builder share link and run\n`webstudio init --link <share-link> --json`. You can then use local CLI\nshortcuts immediately. Do not run `webstudio sync`, `webstudio connect`, or\nrestart the app unless the user specifically wants native MCP registration:\nMCP reads and edits the latest editable Builder build directly, including for\nprojects that have never been published. Treat the share link as a credential\nand do not include it in committed files, logs, screenshots, or issue reports.\n\nThe optional `connect` command verifies project access before changing client configuration. For\nClaude Code, Cursor, and VS Code it safely merges the `webstudio` server into\nthe client\'s project configuration. For Codex it runs both `codex mcp add` and\n`codex mcp get webstudio`; do not repeat those commands separately. Follow the\nreload, restart, or approval instruction printed by `connect`, then verify the\nloaded MCP connection by asking the client to use Webstudio MCP and list the\nproject pages. Use `--print` only to inspect the generated setup without\nchanging configuration or requiring project access.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a compact MCP tool overview. Add `--verbose` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get-more-tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment --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": "<ws.element ws:tag=\'section\' ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag=\'h2\'>Launch Kit</ws.element><ws.element ws:tag=\'p\'>A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag=\'button\'>Get started</ws.element></ws.element>"\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 the block\'s `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nDo not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.\n\nUse Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/Webstudio names. Do not use React-only aliases such as `className` or `htmlFor`; the runtime rejects them with the Webstudio prop name to use.\n\nUse Webstudio actions for event/action props. Do not pass JavaScript functions such as `onClick={() => ...}`; the runtime rejects them because functions cannot be persisted as Webstudio project data.\n\n```tsx\n<ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n>\n Open\n</ws.element>\n```\n\nPlain JSX prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n\nIf a component has a registered template with required parts, JSX must include those parts explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.\n\n## Animation Components\n\nBefore creating animation examples, inspect the exact components with focused discovery:\n\n```sh\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateChildren"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateText"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:StaggerAnimation"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:VideoAnimation"}\'\n```\n\nUse Animation Group (`AnimateChildren`) as the controller. Put normal instances directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it. Text, Stagger, and Video are helper components with `contentModel.category: "none"` and should not be used as standalone section roots.\n\nDefine timing and CSS changes on the Animation Group `action` prop. Use `type:"view"` for viewport entry/exit progress and `type:"scroll"` for scroll-progress timelines. For in animations, keep the canvas styles as the final state and use `fill:"backwards"` with keyframes that describe the starting state. For out animations, use `fill:"forwards"` with keyframes that describe the ending state.\n\nText Animation settings: `slidingWindow` defaults to `5`, `easing` defaults to `linear`, and `splitBy` defaults to `char`. Use `splitBy:"space"` for word-by-word animation. The parent Animation Group keyframes provide the actual opacity, translate, scale, or other styles.\n\nStagger Animation settings: `slidingWindow` defaults to `1` and `easing` defaults to `linear`. It applies parent Animation Group progress across its direct children. Use `slidingWindow:0` for instant sequential steps, `1` for one child at a time, and values above `1` for overlapping waves.\n\nVideo Animation settings: `timeline` is a boolean. Prefer `insert-component` for Video Animation so the Video child template is inserted, then configure the Video child asset/source. Use short, seek-friendly videos for smooth scroll-linked playback.\n\nUse JSX fragments for authored animation structures when you need styled, editable examples. Put the final visual state in `ws:style` and put the starting or ending animated state in the Animation Group `action` keyframes. Include an explicit `offset` on every keyframe: use `offset: 0` for starting-state keyframes with `fill:"backwards"` and `offset: 1` for ending-state keyframes with `fill:"forwards"`.\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n axis: "block",\n animations: [\n {\n name: "Fade up on entry",\n timing: {\n fill: "backwards",\n rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 24, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n ],\n }}\n>\n <ws.element\n ws:tag="section"\n ws:style={css`\n display: grid;\n gap: 16px;\n padding: 48px;\n border-radius: 24px;\n background: #111827;\n color: white;\n `}\n >\n <ws.element ws:tag="h2">Launch metrics</ws.element>\n <ws.element ws:tag="p">\n A polished card that fades up as it enters the viewport.\n </ws.element>\n </ws.element>\n</animation.AnimateChildren>\n```\n\nFor Text Animation, keep `animation.AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Parallax In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 100, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Opacity In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n {\n name: "Scale In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Parallax Out",\n timing: {\n fill: "forwards",\n rangeStart: ["cover", { type: "unit", value: 50, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 1,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: -100, unit: "px" },\n ],\n },\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n insetStart: { type: "unit", value: 5, unit: "%" },\n insetEnd: { type: "unit", value: 5, unit: "%" },\n isPinned: true,\n }}\n>\n <animation.AnimateText\n splitBy="space"\n slidingWindow={5}\n easing="easeOutQuart"\n >\n <ws.element ws:tag="h2">Animate words with controlled rhythm</ws.element>\n </animation.AnimateText>\n</animation.AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `animation.StaggerAnimation`:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n timing: {\n fill: "backwards",\n rangeStart: ["contain", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["contain", { type: "unit", value: 30, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n }}\n>\n <animation.StaggerAnimation>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </ws.element>\n </animation.StaggerAnimation>\n</animation.AnimateChildren>\n```\n\nFor Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Video progress",\n timing: {\n fill: "both",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [{ offset: 0, styles: {} }],\n },\n ],\n }}\n>\n <animation.VideoAnimation timeline={true}>\n <$.Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </animation.VideoAnimation>\n</animation.AnimateChildren>\n```\n\n## Command Surface Boundary\n\n- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, registry inspection, man, and starting MCP.\n- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.\n- From a shell, call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio insert-fragment \'<json>\' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.\n- For experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- 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. Inspect current project state with semantic reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, `list-breakpoints`, and `snapshot` only when needed. Before changing a project, read `get-project-settings` and follow any non-empty `meta.agentInstructions`. These are shared project instructions, not a place for secrets.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.\n4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.\n5. For visual/design work, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate before final response.\n6. Report what changed and what verification ran.\n\n## Visual Design Workflow\n\nFor requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:\n\n1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.\n2. Do not use generated route/component files as the source of truth for editable content.\n3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.\n4. Keep generated project files current, start preview, and capture the changed page with `screenshot`.\n5. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n6. If vision or screenshot tooling is unavailable, state that explicitly and explain what fallback verification was used.\n\n## Responsive Verification Workflow\n\nFor responsive page work, use Builder breakpoints as the source of truth:\n\n1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.\n2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.\n3. Pick screenshot viewport widths from the project breakpoints: include a desktop width, each defined max-width or min-width edge, and a narrow mobile width.\n4. Capture each viewport with `screenshot`, for example `{"path":"/","output":"home-375.png","viewport":{"width":375,"height":812}}` and `{"path":"/","output":"home-1440.png","viewport":{"width":1440,"height":900}}`.\n5. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n6. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.\n\n## Generated Files Guardrails\n\n- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.\n- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.\n- Generated files are build artifacts and may be overwritten by `webstudio build`.\n- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.\n\n## Values vs Bindings\n\nBefore authoring unfamiliar expressions, read `webstudio://project/expressions` with MCP `resources/read` or `webstudio mcp read-resource webstudio://project/expressions`. It documents the supported expression subset, method allowlist, scope, Collection context, and validation limits.\n\n- Use direct value tools for fixed content. For one visible text child, use `update-text` with plain `text`. For a bounded multi-instance literal replacement, use `replace-text` with `find`, `replace`, `pagePath` or `pageId`, and `limit`; it does not change expression children. Use `replace-prop-text` for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop\'s direct type/value.\n- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.\n- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.\n- Expression binding example: `{"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}`.\n- Page metadata fields such as `title`, `description`, `language`, `redirect`, and custom meta content accept plain fixed text. For computed values, pass JavaScript expression code such as `pageTitle ?? "Pricing | Acme"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599, for example `302`. For a dynamic status, pass JavaScript expression code such as `system.status`.\n- Page metadata update example: use `update-page` with `{"pageId":"page-id","values":{"title":"Pricing | Acme","meta":{"description":"Plans for teams"}}}`.\n- Draft a page with `update-page` and `{"pageId":"page-id","values":{"isDraft":true}}`. It remains editable and previewable but is omitted from every publish target, including staging, and from sitemap output.\n- Stage a draft page for a future publish with `{"pageId":"page-id","values":{"isDraft":false}}`. This clears draft state but does not deploy the site. The home page and `/*` catch-all page cannot be drafts.\n- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.\n- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.\n- Assets is one system resource 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 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 Markdown bodies from Asset storage at runtime. Do not create companion JSON descriptors merely to avoid embedding Markdown.\n- `full` and bounded `range` request embedded file bytes. Use them only when the caller explicitly requires the complete source or a byte range.\n- Deferred Markdown bodies exclude frontmatter and resolve conventional relative links and images such as `../images/hero.png` to matching Assets. Markdown Embed permits sanitized figures, audio, video, and iframes, but removes scripts, inline event handlers, and unsafe URLs.\n- 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. Prefer optional chaining, nullish coalescing, ternaries, property/index access, operators, and the documented string/array methods.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- For visual/design work, verify the rendered result with vision before finishing.\n- Do not edit generated files for normal Webstudio content/design requests.\n- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.\n- Use plain fixed text where documented. Only encode a quoted JavaScript string literal when a field is explicitly documented as an expression-only value.\n- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n',
"manual-mcp":
'# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\nIf you are already working with a shell-capable agent, it can use the local CLI\ndirectly. Native MCP client registration is optional. Give the editable Builder\nshare link only when the trusted agent asks for it. Treat the share link as a\ncredential: do not include it in committed files, screenshots, logs, or issue\nreports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nDo not run `webstudio sync`, install an MCP server, change client configuration,\nor restart the app for this local CLI workflow.\n\nWhen the user explicitly wants persistent native MCP integration, run\n`webstudio connect claude`, `webstudio connect codex`, `webstudio connect\ncursor`, or `webstudio connect vscode`. This optional command changes client\nconfiguration, so follow its client-specific reload or restart instruction.\nUse `--print` to inspect the generated setup without changing configuration or\nrequiring project access. For Codex, `connect` registers and verifies the server\nthrough the Codex CLI. Before changing client configuration, `connect` verifies\nthat the saved project endpoint is reachable and its credential is accepted.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\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`.\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": "<ws.element ws:tag=\'section\' ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag=\'h2\'>Northstar Product OS</ws.element><ws.element ws:tag=\'p\'>Reusable patterns for teams.</ws.element></ws.element>"\n}\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<ws.element\n ws:tag="section"\n style={{ padding: 32, borderRadius: 16 }}\n>\n <ws.element ws:tag="h2">Operations Console</ws.element>\n <ws.element ws:tag="p">\n React-style object styles become editable Webstudio styles.\n </ws.element>\n</ws.element>\n\n<ws.element\n ws:tag="section"\n ws:tokens={[token("accent", css`color: #0f766e;`)]}\n>\n <ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n >\n Track launch\n </ws.element>\n</ws.element>\n\n<ws.element ws:tag="section">\n <radix.Switch>\n <radix.SwitchThumb />\n </radix.Switch>\n</ws.element>\n```\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\n- In `insert-fragment` JSX, use ``ws:style={css`...`}`` for Webstudio-native CSS, or use React-style object syntax such as `style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build version. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- To work with another previously linked project without changing the directory\'s default link, start MCP or a shell call with `--project <projectId>`, for example `webstudio mcp --project <projectId>` or `webstudio mcp single-op-call list-pages --project <projectId>`. Selected projects use isolated local session and checkpoint files.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get-more-tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details\n- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: compact metadata for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, and JSON variables. Arrays use JSON.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List and inspect complete asset metadata; upload, download, update, move, duplicate, find usage for, replace, and delete assets.\n- List, create, rename, move, recursively duplicate, and recursively delete nested asset folders.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- 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 visual/design work, verify the rendered result with vision before finishing.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP argument examples\n\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## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',
"mcp-startup-epilogue":
@@ -83,7 +83,7 @@ export const cliDocSections = {
'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.',
'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 with one response shape and always executes a structured query. create-assets-resource without query uses the default URL and optional image-dimensions output. Provide query configuration to control filtering, sorting, pagination, selected fields, or file content.",
+ '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.',
"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.",
@@ -91,7 +91,7 @@ export const cliDocSections = {
'Query Markdown 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 Markdown bodies from Asset storage at runtime. Do not create companion JSON descriptors merely to avoid embedding Markdown.',
"full and bounded range request embedded file bytes. Use them only when the caller explicitly requires the complete source or a byte range.",
"Deferred Markdown bodies exclude frontmatter and resolve conventional relative links and images such as ../images/hero.png to matching Assets. Markdown Embed permits sanitized figures, audio, video, and iframes, but removes scripts, inline event handlers, and unsafe URLs.",
- "Assets expose an ID-keyed map at <dataSourceName>.data and collection information at <dataSourceName>.meta. Bind a listing Collection to posts.data and a one-result detail Collection to post.data; each item value contains selected fields and its item key is the asset ID. Read frontmatter or JSON fields from item.properties and the resolved Markdown body from item.content.text.",
+ '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.',
"Use preview-asset-query with concrete values before binding expressions in the saved resource. Inspect __diagnostics__.query for the temporary query-only footprint and __diagnostics__.database for the merged database built from all reachable Assets queries. Only database.usedBytes counts toward database.maxBytes; query sizes are not separate allowances and must not be summed. Compare usedBytes, unboundedBytes, and truncated within both scopes. A finished Markdown blog must include every source document without truncation, contain no embedded Markdown bodies, and retain only the intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files. Inspect saved mode and configuration with list-assets-resources or get-assets-resource; shared index maintenance is automatic.",
"Data variable values support string, number, boolean, and json. Use json for all arrays, objects, filters, and nested data.",
"Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as system in expressions where they are already in scope.",
diff --git a/packages/cli/src/docs/api-use-cases.md b/packages/cli/src/docs/api-use-cases.md
index 9429bdb8d1..1446a7fa38 100644
--- a/packages/cli/src/docs/api-use-cases.md
+++ b/packages/cli/src/docs/api-use-cases.md
@@ -749,12 +749,12 @@ Commands:
- MCP tool: get-asset-field-catalog {}
- MCP tool: validate-asset-query {"query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","draft"],"operator":"ne","value":true}]},"limit":20}}
- MCP tool: create-assets-resource {"name":"All assets","scopeInstanceId":"<instanceId>","dataSourceName":"assets"}
-- MCP tool: create-assets-resource {"name":"Published posts","scopeInstanceId":"<instanceId>","dataSourceName":"posts","query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","draft"],"operator":"ne","value":{"type":"literal","value":true}}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"}],"limit":{"type":"literal","value":20},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["properties","excerpt"]]},"content":{"mode":"none"}}}
-- MCP tool: create-assets-resource {"name":"Post by slug or ID","scopeInstanceId":"<instanceId>","dataSourceName":"post","query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"}]},"limit":{"type":"literal","value":1},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","publishedAt"]]},"content":{"mode":"markdown-body-ref"}}}
+- 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"}}}
+- 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"}}}
- MCP tool: list-assets-resources {}
- MCP tool: get-assets-resource {"resourceId":"<resourceId>"}
- MCP tool: update-assets-resource {"resourceId":"<resourceId>","values":{"query":null}}
-- MCP tool: preview-asset-query {"query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","slug"],"operator":"eq","value":"hello-world"}]},"limit":1,"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"]]},"content":{"mode":"markdown-body-ref"}}}
+- 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"}}}
Notes:
@@ -768,8 +768,9 @@ Notes:
- In Markdown, reference sibling Assets with conventional relative URLs such as `../images/hero.png`. Deferred `markdown-body-ref` content resolves matching files against the Markdown file's folder and emits the correct Builder or published Asset URL. Keep external URLs absolute.
- Markdown Embed renders sanitized authored HTML for figures, captions, audio, video, and iframes. Scripts, inline event handlers, `srcdoc`, and unsafe URL protocols are removed. Executable component composition remains separate future MDX work.
- Preview each query with concrete values before saving it. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes must not be summed and are not separate allowances. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A completed Markdown blog should include every source document without truncation, contain no embedded Markdown bodies, and retain only its intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files.
-- Read Assets from the ID-keyed map at `<dataSourceName>.data`, with collection information such as `totalCount` and `hasMore` at `<dataSourceName>.meta`. Bind a listing Collection to `posts.data` and a one-result detail Collection to `post.data`. On each value, selected file fields such as `id`, `name`, and `extension` are top-level, Markdown frontmatter and JSON fields are under `properties`, and a resolved Markdown body is at `content.text`.
-- Assets has one response shape and always executes a structured query. Omit `query` to use the default query, which selects URL and optional image dimensions. Provide query configuration to control filtering, sorting, pagination, selected fields, or file content. Set `values.query:null` to restore the default query.
+- 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`.
+- 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.
+- 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.
- `create-assets-resource` and `update-assets-resource` are the semantic authoring path. Do not construct the internal query URL, headers, or body expression manually.
- The shared metadata index is maintained automatically and is emitted only when a configured Assets resource is reachable.
diff --git a/packages/cli/src/docs/manual-llm.md b/packages/cli/src/docs/manual-llm.md
index b52f8d64ea..d395fa60b1 100644
--- a/packages/cli/src/docs/manual-llm.md
+++ b/packages/cli/src/docs/manual-llm.md
@@ -469,7 +469,7 @@ Before authoring unfamiliar expressions, read `webstudio://project/expressions`
- 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.
- 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 with one response shape and always executes a structured query. `create-assets-resource` without `query` uses the default URL and optional image-dimensions output. Provide query configuration to control filtering, sorting, pagination, selected fields, or file content.
+- 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.
- 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.
@@ -477,7 +477,7 @@ Before authoring unfamiliar expressions, read `webstudio://project/expressions`
- Query Markdown 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 Markdown bodies from Asset storage at runtime. Do not create companion JSON descriptors merely to avoid embedding Markdown.
- `full` and bounded `range` request embedded file bytes. Use them only when the caller explicitly requires the complete source or a byte range.
- Deferred Markdown bodies exclude frontmatter and resolve conventional relative links and images such as `../images/hero.png` to matching Assets. Markdown Embed permits sanitized figures, audio, video, and iframes, but removes scripts, inline event handlers, and unsafe URLs.
-- Assets expose an ID-keyed map at `<dataSourceName>.data` and collection information at `<dataSourceName>.meta`. Bind a listing Collection to `posts.data` and a one-result detail Collection to `post.data`; each item value contains selected fields and its item key is the asset ID. Read frontmatter or JSON fields from `item.properties` and the resolved Markdown body from `item.content.text`.
+- 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.
- Use `preview-asset-query` with concrete values before binding expressions in the saved resource. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes are not separate allowances and must not be summed. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A finished Markdown blog must include every source document without truncation, contain no embedded Markdown bodies, and retain only the intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files. Inspect saved mode and configuration with `list-assets-resources` or `get-assets-resource`; shared index maintenance is automatic.
- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays, objects, filters, and nested data.
- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.
diff --git a/packages/content-engine/src/compilation-plan.ts b/packages/content-engine/src/compilation-plan.ts
index 8d3acc3b51..4d266d7553 100644
--- a/packages/content-engine/src/compilation-plan.ts
+++ b/packages/content-engine/src/compilation-plan.ts
@@ -77,6 +77,7 @@ export type ContentCompilationWhere = QueryWhereTree<{
export type ContentCompilationQuery = {
id: string;
+ result?: AssetQuery["result"];
where: ContentCompilationWhere;
sort: AssetQuery["sort"];
limit: ContentCompilationValue;
@@ -519,6 +520,7 @@ export const createLiteralContentCompilationQuery = ({
query: AssetQuery;
}): ContentCompilationQuery => ({
id,
+ result: query.result ?? "many",
where: toLiteralWhere(query.where),
sort: query.sort,
limit: { type: "literal", value: query.limit },
diff --git a/packages/content-engine/src/content-database.ts b/packages/content-engine/src/content-database.ts
index f22d3b0a28..19ce9df05d 100644
--- a/packages/content-engine/src/content-database.ts
+++ b/packages/content-engine/src/content-database.ts
@@ -3,6 +3,7 @@ import type {
ContentArtifactV1,
AssetQueryRequestInput,
AssetQueryResult,
+ AssetQueryExecutionResult,
BuilderAssetFieldCatalog,
ContentDatabaseStats,
ContentDatabaseDocument,
@@ -214,8 +215,8 @@ const createQueryableContentDatabase = ({
};
};
const getSettledValue = (
- result: PromiseSettledResult<AssetQueryResult>
- ): AssetQueryResult => {
+ result: PromiseSettledResult<AssetQueryExecutionResult>
+ ): AssetQueryExecutionResult => {
if (result.status === "rejected") {
throw result.reason;
}
@@ -266,9 +267,10 @@ const createQueryableContentDatabase = ({
requests: readonly AssetQueryRequestInput[];
queryContentReader?: AssetResourceContentReader;
runtimeAssets?: Readonly<Record<string, AssetRuntimeData>>;
- }): Promise<PromiseSettledResult<AssetQueryResult>[]> => {
- const results: Array<PromiseSettledResult<AssetQueryResult> | undefined> =
- Array.from({ length: requests.length });
+ }): Promise<PromiseSettledResult<AssetQueryExecutionResult>[]> => {
+ const results: Array<
+ PromiseSettledResult<AssetQueryExecutionResult> | undefined
+ > = Array.from({ length: requests.length });
const assetUrls = getRuntimeAssetUrls(runtimeAssets);
const pendingIndexes: number[] = [];
for (const [index, request] of requests.entries()) {
@@ -453,64 +455,69 @@ const createQueryableContentDatabase = ({
documents,
});
};
- const queryManyWithDocumentGraph: ContentDatabase["queryManyWithDocumentGraph"] =
- async ({
- requests,
- load,
- resolutionSession: sharedResolutionSession,
- readContent: queryContentReader,
- runtimeAssets,
- signal,
- onEvent,
- }) => {
- if (documentGraph === undefined) {
- return await executeQueries({
- requests,
- queryContentReader,
- runtimeAssets,
- });
- }
- const documentLoader = createInlineAwareLoader(load);
- const resolutionSession =
- sharedResolutionSession ??
- createDocumentResolutionSession({
- load: documentLoader,
- concurrency: contentEngineLimits.concurrentContentReads,
- signal,
- });
- const contentReader = createDocumentContentReader({
- graph: documentGraph,
+ const queryManyWithDocumentGraph = async ({
+ requests,
+ load,
+ resolutionSession: sharedResolutionSession,
+ readContent: queryContentReader,
+ runtimeAssets,
+ signal,
+ onEvent,
+ }: Parameters<ContentDatabase["queryManyWithDocumentGraph"]>[0]) => {
+ if (documentGraph === undefined) {
+ return await executeQueries({
+ requests,
+ queryContentReader,
+ runtimeAssets,
+ });
+ }
+ const documentLoader = createInlineAwareLoader(load);
+ const resolutionSession =
+ sharedResolutionSession ??
+ createDocumentResolutionSession({
load: documentLoader,
- getCached: resolutionSession.getCached,
- readFallback: queryContentReader ?? readContent,
+ concurrency: contentEngineLimits.concurrentContentReads,
signal,
});
- // Share only graph resolution, like a request-scoped GraphQL DataLoader.
- // Running each query independently preserves partial-result semantics.
- return await Promise.allSettled(
- requests.map((request) =>
- executeQueryWithDocumentGraph({
- request,
- graph: documentGraph,
- resolutionSession,
- contentReader,
- runtimeAssets,
- onEvent,
- })
- )
- );
- };
- const queryWithDocumentGraph: ContentDatabase["queryWithDocumentGraph"] =
- async ({ request, ...input }) =>
- getSettledValue(
- (
- await queryManyWithDocumentGraph({
- ...input,
- requests: [request],
- })
- )[0]
- );
- return { query, queryManyWithDocumentGraph, queryWithDocumentGraph };
+ const contentReader = createDocumentContentReader({
+ graph: documentGraph,
+ load: documentLoader,
+ getCached: resolutionSession.getCached,
+ readFallback: queryContentReader ?? readContent,
+ signal,
+ });
+ // Share only graph resolution, like a request-scoped GraphQL DataLoader.
+ // Running each query independently preserves partial-result semantics.
+ return await Promise.allSettled(
+ requests.map((request) =>
+ executeQueryWithDocumentGraph({
+ request,
+ graph: documentGraph,
+ resolutionSession,
+ contentReader,
+ runtimeAssets,
+ onEvent,
+ })
+ )
+ );
+ };
+ const queryWithDocumentGraph = async ({
+ request,
+ ...input
+ }: Parameters<ContentDatabase["queryWithDocumentGraph"]>[0]) =>
+ getSettledValue(
+ (
+ await queryManyWithDocumentGraph({
+ ...input,
+ requests: [request],
+ })
+ )[0]
+ );
+ return {
+ query,
+ queryManyWithDocumentGraph,
+ queryWithDocumentGraph,
+ } as unknown as RuntimeContentDatabase;
};
export const createContentDatabase = ({
diff --git a/packages/content-engine/src/materialized-query.ts b/packages/content-engine/src/materialized-query.ts
index 1880c79d58..6f7d4f9a9a 100644
--- a/packages/content-engine/src/materialized-query.ts
+++ b/packages/content-engine/src/materialized-query.ts
@@ -6,7 +6,7 @@ import { serializeJsonDeterministically, sha256 } from "./canonical-json";
import type { ContentCompilationQuery } from "./compilation-plan";
import {
assetQuery,
- assetQueryResult,
+ assetQueryCollectionResult,
isAssetQueryRuntimeField,
materializedAssetQuery,
type AssetQuery,
@@ -14,6 +14,7 @@ import {
type AssetQueryInput,
type AssetQueryItem,
type AssetQueryResult,
+ type AssetQueryExecutionResult,
type BuilderAssetFieldCatalog,
type ContentDatabaseDocument,
type MaterializedAssetQuery,
@@ -42,6 +43,7 @@ const getMaterializedFields = (
query: ContentCompilationQuery
): AssetQueryFieldPath[] | undefined => {
if (
+ (query.result ?? "many") !== "many" ||
query.content.mode !== "none" ||
query.output.mode !== "fields" ||
query.output.includeMetadata
@@ -142,7 +144,7 @@ const materializeQuery = async ({
if (fields === undefined || literalQuery === undefined) {
return;
}
- let result: AssetQueryResult;
+ let result: AssetQueryExecutionResult;
try {
result = await executeAssetQuery({
query: literalQuery,
@@ -155,6 +157,9 @@ const materializeQuery = async ({
}
throw error;
}
+ if ("items" in result === false) {
+ return;
+ }
const rows = result.items.map((item) =>
fields.map((field) => getItemFieldValue(item, field))
);
@@ -239,7 +244,7 @@ const setItemFieldValue = ({
const hydrateMaterializedQuery = (
query: MaterializedAssetQuery
): AssetQueryResult =>
- assetQueryResult.parse({
+ assetQueryCollectionResult.parse({
items: query.rows.map((row) => {
const item: Record<string, unknown> = {};
for (const [index, field] of query.fields.entries()) {
diff --git a/packages/content-engine/src/published-runtime.test.ts b/packages/content-engine/src/published-runtime.test.ts
index 4b9f5d6460..8b588340fb 100644
--- a/packages/content-engine/src/published-runtime.test.ts
+++ b/packages/content-engine/src/published-runtime.test.ts
@@ -413,6 +413,7 @@ describe("published asset resource runtime", () => {
const plan = createContentCompilationPlan([
{
id: "post",
+ result: "one",
where: {
all: [
{
@@ -423,7 +424,7 @@ describe("published asset resource runtime", () => {
],
},
sort: [],
- limit: { type: "literal", value: 1 },
+ limit: { type: "literal", value: 20 },
offset: { type: "literal", value: 0 },
output: {
mode: "fields",
@@ -477,6 +478,7 @@ describe("published asset resource runtime", () => {
method: "POST",
body: JSON.stringify({
query: {
+ result: "one",
where: {
all: [
{
@@ -486,7 +488,6 @@ describe("published asset resource runtime", () => {
},
],
},
- limit: 1,
output: {
mode: "fields",
includeMetadata: false,
@@ -498,13 +499,12 @@ describe("published asset resource runtime", () => {
});
await expect(response?.json()).resolves.toMatchObject({
- items: [
- {
- id: "second",
- properties: { title: "Second" },
- content: { text: "Second stored body\n" },
- },
- ],
+ item: {
+ id: "second",
+ properties: { title: "Second" },
+ content: { text: "Second stored body\n" },
+ },
+ totalCount: 1,
});
expect(fetchDocument).toHaveBeenCalledOnce();
expect(String(fetchDocument.mock.calls[0][0])).toContain("second.md");
diff --git a/packages/content-engine/src/query-error.test.ts b/packages/content-engine/src/query-error.test.ts
index fd1267cb6c..f065b3e874 100644
--- a/packages/content-engine/src/query-error.test.ts
+++ b/packages/content-engine/src/query-error.test.ts
@@ -4,8 +4,21 @@ import {
DocumentResolutionLimitError,
} from "./document-graph";
import { getAssetResourceQueryError } from "./query-error";
+import { AssetQueryMultipleResultsError } from "./structured-query";
describe("asset resource graph query errors", () => {
+ test("maps ambiguous exactly-one queries to a structured error", () => {
+ expect(
+ getAssetResourceQueryError(new AssetQueryMultipleResultsError(2))
+ ).toEqual({
+ code: "MULTIPLE_RESULTS",
+ message: "Expected at most one asset, but the query matched 2.",
+ retryable: false,
+ details: { matchedCount: 2 },
+ status: 409,
+ });
+ });
+
test("maps nested document graph limits to structured content errors", () => {
const error = new DocumentGraphResolutionError({
code: "DOCUMENT_LOAD_FAILED",
diff --git a/packages/content-engine/src/query-error.ts b/packages/content-engine/src/query-error.ts
index 27a38d400a..7bbce7ef5e 100644
--- a/packages/content-engine/src/query-error.ts
+++ b/packages/content-engine/src/query-error.ts
@@ -3,6 +3,7 @@ import { AssetResourceHydrationError } from "./hydration";
import {
AssetIndexRevisionError,
AssetQueryExecutionError,
+ AssetQueryMultipleResultsError,
} from "./structured-query";
import { DocumentResolutionLimitError } from "./document-graph/document-resolution";
import { CachedDocumentLoaderError } from "./document-graph/cached-document-loader";
@@ -27,6 +28,15 @@ export const getAssetResourceQueryError = (
status: 409,
};
}
+ if (error instanceof AssetQueryMultipleResultsError) {
+ return {
+ code: error.code,
+ message: error.message,
+ retryable: false,
+ details: { matchedCount: error.matchedCount },
+ status: 409,
+ };
+ }
if (error instanceof AssetQueryExecutionError) {
return {
code: "INVALID_REQUEST",
diff --git a/packages/content-engine/src/query-source.ts b/packages/content-engine/src/query-source.ts
index 8696b7ea3f..d9c543f3df 100644
--- a/packages/content-engine/src/query-source.ts
+++ b/packages/content-engine/src/query-source.ts
@@ -13,8 +13,19 @@ import {
getAssetQueryOperatorsForFieldTypes,
type AssetObservedFieldType,
type AssetQueryFilter,
+ type AssetQueryResultMode,
} from "./schema";
+export const assetQueryResultOptions = [
+ { value: "many", label: "Many" },
+ { value: "one", label: "Exactly one" },
+ { value: "first", label: "First" },
+ { value: "last", label: "Last" },
+] as const satisfies readonly {
+ value: AssetQueryResultMode;
+ label: string;
+}[];
+
const getDefaultFilterValue = (operator: AssetQueryFilter["operator"]) =>
operator === "in"
? "[]"
@@ -102,6 +113,14 @@ export const assetQuerySourceDefinition = {
io: "input",
}),
},
+ {
+ type: "select" as const,
+ key: "result",
+ label: "Result",
+ sectionLabel: "Result",
+ defaultValue: "many",
+ options: assetQueryResultOptions,
+ },
{
type: "filter" as const,
key: "where",
diff --git a/packages/content-engine/src/schema.ts b/packages/content-engine/src/schema.ts
index 7f97cb93f7..0f9c2964bf 100644
--- a/packages/content-engine/src/schema.ts
+++ b/packages/content-engine/src/schema.ts
@@ -10,6 +10,7 @@ import {
record,
strictObject,
string,
+ union,
type ZodType,
type infer as Infer,
type input as Input,
@@ -519,6 +520,10 @@ export const assetQuerySort = strictObject({
export type AssetQuerySort = Infer<typeof assetQuerySort>;
+export const assetQueryResultMode = zEnum(["many", "one", "first", "last"]);
+
+export type AssetQueryResultMode = Infer<typeof assetQueryResultMode>;
+
export const hasAssetQueryOutput = ({
output,
content,
@@ -533,6 +538,7 @@ export const hasAssetQueryOutput = ({
/** Typed configuration for the query mode of the Assets system resource. */
export const assetQuery = strictObject({
+ result: assetQueryResultMode.default("many"),
where: assetQueryWhere.default({ all: [] }),
sort: array(assetQuerySort).max(contentEngineLimits.sortCount).default([]),
limit: number()
@@ -549,11 +555,28 @@ export const assetQuery = strictObject({
defaultAssetResourceOutputSelection
),
content: assetResourceContentOptions.default({ mode: "none" }),
-}).refine(hasAssetQueryOutput, {
- error: "Select at least one asset query output",
+}).superRefine((query, context) => {
+ if (hasAssetQueryOutput(query) === false) {
+ context.addIssue({
+ code: "custom",
+ message: "Select at least one asset query output",
+ });
+ }
+ if (
+ (query.result === "first" || query.result === "last") &&
+ query.sort.length === 0
+ ) {
+ context.addIssue({
+ code: "custom",
+ path: ["sort"],
+ message: "Add sorting to define which item is first.",
+ });
+ }
});
-export type AssetQuery = Infer<typeof assetQuery>;
+export type AssetQuery = Omit<Infer<typeof assetQuery>, "result"> & {
+ result?: AssetQueryResultMode;
+};
export type AssetQueryInput = Input<typeof assetQuery>;
export const assetQueryRequest = strictObject({
@@ -629,13 +652,29 @@ const contentDatabaseCapacityStats = contentDatabaseStats.pick({
truncated: true,
});
-export const assetQueryResult = strictObject({
+export const assetQueryCollectionResult = strictObject({
items: array(assetQueryItem),
totalCount: number().int().nonnegative(),
hasMore: boolean(),
});
-export type AssetQueryResult = Infer<typeof assetQueryResult>;
+export const assetQuerySingleResult = strictObject({
+ item: assetQueryItem.nullable(),
+ totalCount: number().int().nonnegative(),
+});
+
+export const assetQueryResult = union([
+ assetQueryCollectionResult,
+ assetQuerySingleResult,
+]);
+
+export type AssetQueryCollectionResult = Infer<
+ typeof assetQueryCollectionResult
+>;
+export type AssetQuerySingleResult = Infer<typeof assetQuerySingleResult>;
+export type AssetQueryExecutionResult = Infer<typeof assetQueryResult>;
+/** Backward-compatible collection result type for existing many-result APIs. */
+export type AssetQueryResult = AssetQueryCollectionResult;
export const assetQueryPreviewDiagnostics = strictObject({
scope: literal("query-preview"),
@@ -651,13 +690,26 @@ export const assetQueryPreviewDiagnostics = strictObject({
export type AssetQueryPreviewDiagnostics = Infer<
typeof assetQueryPreviewDiagnostics
>;
+type AssetQueryCollectionPreviewDiagnostics = Omit<
+ AssetQueryPreviewDiagnostics,
+ "unresolved"
+> & { unresolved?: AssetQueryCollectionResult };
export const assetQueryPreviewResult = strictObject({
data: assetQueryResult,
__diagnostics__: assetQueryPreviewDiagnostics,
});
-export type AssetQueryPreviewResult = Infer<typeof assetQueryPreviewResult>;
+export type AssetQueryExecutionPreviewResult = Infer<
+ typeof assetQueryPreviewResult
+>;
+export type AssetQueryPreviewResult = Omit<
+ AssetQueryExecutionPreviewResult,
+ "data" | "__diagnostics__"
+> & {
+ data: AssetQueryCollectionResult;
+ __diagnostics__: AssetQueryCollectionPreviewDiagnostics;
+};
export const assetResourceErrorCode = zEnum([
"INVALID_REQUEST",
@@ -669,6 +721,7 @@ export const assetResourceErrorCode = zEnum([
"CONTENT_NOT_TEXT",
"CONTENT_DECODING_FAILED",
"CONTENT_LIMIT_EXCEEDED",
+ "MULTIPLE_RESULTS",
"INTERNAL_ERROR",
]);
diff --git a/packages/content-engine/src/structured-query.test.ts b/packages/content-engine/src/structured-query.test.ts
index 54ec1d7a11..b2cac43061 100644
--- a/packages/content-engine/src/structured-query.test.ts
+++ b/packages/content-engine/src/structured-query.test.ts
@@ -94,6 +94,165 @@ const runtimeAssets = Object.fromEntries(
);
describe("structured asset query", () => {
+ test("returns direct items for single-result modes", async () => {
+ const empty = await executeAssetQuery({
+ documents,
+ query: {
+ result: "one",
+ where: {
+ all: [
+ {
+ field: ["properties", "title"],
+ operator: "eq",
+ value: "Missing",
+ },
+ ],
+ },
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["properties", "title"]],
+ },
+ },
+ });
+ const one = await executeAssetQuery({
+ documents,
+ query: {
+ result: "one",
+ where: {
+ all: [
+ {
+ field: ["properties", "title"],
+ operator: "eq",
+ value: "Alpha",
+ },
+ ],
+ },
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["properties", "title"]],
+ },
+ },
+ });
+
+ expect(empty).toEqual({ item: null, totalCount: 0 });
+ expect(one).toEqual({
+ item: { id: "alpha", properties: { title: "Alpha" } },
+ totalCount: 1,
+ });
+ });
+
+ test("rejects ambiguous exactly-one results before pagination", async () => {
+ await expect(
+ executeAssetQuery({
+ documents,
+ query: {
+ result: "one",
+ where: { all: [] },
+ limit: 1,
+ offset: 2,
+ },
+ runtimeAssets,
+ })
+ ).rejects.toMatchObject({
+ code: "MULTIPLE_RESULTS",
+ matchedCount: 3,
+ });
+ });
+
+ test("returns deterministic first and last results", async () => {
+ const tied = [
+ document({ id: "charlie", properties: { order: 1 } }),
+ document({ id: "alpha", properties: { order: 1 } }),
+ document({ id: "bravo", properties: { order: 1 } }),
+ ];
+ const query = {
+ where: { all: [] as never[] },
+ sort: [
+ {
+ field: ["properties", "order"],
+ direction: "asc" as const,
+ },
+ ],
+ output: {
+ mode: "fields" as const,
+ includeMetadata: false,
+ fields: [["properties", "order"]],
+ },
+ };
+
+ await expect(
+ executeAssetQuery({
+ documents: tied,
+ query: { ...query, result: "first" },
+ })
+ ).resolves.toEqual({
+ item: { id: "alpha", properties: { order: 1 } },
+ totalCount: 3,
+ });
+ await expect(
+ executeAssetQuery({
+ documents: tied,
+ query: { ...query, result: "last" },
+ })
+ ).resolves.toEqual({
+ item: { id: "charlie", properties: { order: 1 } },
+ totalCount: 3,
+ });
+ });
+
+ test("requires sorting for first and last results", async () => {
+ for (const result of ["first", "last"] as const) {
+ await expect(
+ executeAssetQuery({
+ documents,
+ query: { result, sort: [] },
+ runtimeAssets,
+ })
+ ).rejects.toThrow("Add sorting to define which item is first.");
+ }
+ });
+
+ test("hydrates only the selected single Markdown result", async () => {
+ const body = new TextEncoder().encode("# Body\n");
+ const read = vi.fn(async () => ({
+ data: {
+ async *[Symbol.asyncIterator]() {
+ yield body;
+ },
+ },
+ contentLength: body.byteLength,
+ }));
+ const result = await executeAssetQuery({
+ documents: documents.map((item) => ({ ...item, size: body.byteLength })),
+ query: {
+ result: "first",
+ sort: [{ field: ["properties", "publishedAt"], direction: "desc" }],
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["properties", "title"]],
+ },
+ content: { mode: "markdown-body-ref" },
+ },
+ read,
+ });
+
+ expect(result).toMatchObject({
+ item: {
+ id: "gamma",
+ content: { text: "# Body\n" },
+ },
+ totalCount: 3,
+ });
+ expect(read).toHaveBeenCalledOnce();
+ expect(read).toHaveBeenCalledWith("files/gamma.md", {
+ offset: 0,
+ length: body.byteLength,
+ });
+ });
+
test("executes sibling queries in one scan with independent windows and counts", async () => {
const readCommon = vi.fn(() => "blog");
const candidates = [
diff --git a/packages/content-engine/src/structured-query.ts b/packages/content-engine/src/structured-query.ts
index 72e4be5cbc..748ffb97a5 100644
--- a/packages/content-engine/src/structured-query.ts
+++ b/packages/content-engine/src/structured-query.ts
@@ -14,7 +14,10 @@ import {
type AssetQueryInput,
type AssetQueryFieldPath,
type AssetQueryFilter,
- type AssetQueryResult,
+ type AssetQueryCollectionResult,
+ type AssetQueryExecutionResult,
+ type AssetQueryItem,
+ type AssetQuerySingleResult,
type AssetQueryWhere,
type AssetResourceContentOptions,
type AssetResourceOutputSelection,
@@ -55,6 +58,18 @@ export class AssetQueryExecutionError extends Error {
}
}
+export class AssetQueryMultipleResultsError extends AssetQueryExecutionError {
+ readonly code = "MULTIPLE_RESULTS";
+
+ readonly matchedCount: number;
+
+ constructor(matchedCount: number) {
+ super(`Expected at most one asset, but the query matched ${matchedCount}.`);
+ this.matchedCount = matchedCount;
+ this.name = "AssetQueryMultipleResultsError";
+ }
+}
+
export class AssetIndexRevisionError extends Error {
constructor() {
super("The requested asset index revision is stale");
@@ -428,7 +443,9 @@ const toQueryItem = (
};
};
-export const assertAssetQueryResultSize = (result: AssetQueryResult) => {
+export const assertAssetQueryResultSize = (
+ result: AssetQueryExecutionResult
+) => {
if (
getUtf8ByteLength(serializeJsonDeterministically(result)) >
contentEngineLimits.resultBytes
@@ -441,7 +458,7 @@ export const assertAssetQueryResultSize = (result: AssetQueryResult) => {
type AssetQueryMatch = {
document: ContentDatabaseDocument;
- item: AssetQueryResult["items"][number];
+ item: AssetQueryItem;
};
type AssetQuerySortGroup = {
@@ -458,7 +475,7 @@ type PreparedAssetQuery = {
};
type AssetQuerySettlements = Array<
- PromiseSettledResult<AssetQueryResult> | undefined
+ PromiseSettledResult<AssetQueryExecutionResult> | undefined
>;
const rejectAssetQuery = (
@@ -629,10 +646,16 @@ const finalizeAssetQueries = async ({
const match = state.matches.get(document);
return match === undefined ? [] : [match];
});
- const selected = matched.slice(
- query.offset,
- query.offset + query.limit
- );
+ const resultMode = query.result ?? "many";
+ if (resultMode === "one" && matched.length > 1) {
+ throw new AssetQueryMultipleResultsError(matched.length);
+ }
+ const selected =
+ resultMode === "many"
+ ? matched.slice(query.offset, query.offset + query.limit)
+ : resultMode === "last"
+ ? matched.slice(-1)
+ : matched.slice(0, 1);
const selectedDocuments = selected.map(({ document }) => document);
let items = selected.map(({ item }) => item);
if (query.content.mode !== "none") {
@@ -669,11 +692,17 @@ const finalizeAssetQueries = async ({
};
});
}
- const result = {
- items,
- totalCount: matched.length,
- hasMore: query.offset + selected.length < matched.length,
- } satisfies AssetQueryResult;
+ const result: AssetQueryExecutionResult =
+ resultMode === "many"
+ ? {
+ items,
+ totalCount: matched.length,
+ hasMore: query.offset + selected.length < matched.length,
+ }
+ : {
+ item: items[0] ?? null,
+ totalCount: matched.length,
+ };
assertAssetQueryResultSize(result);
results[state.index] = { status: "fulfilled", value: result };
} catch (error) {
@@ -699,7 +728,7 @@ export const executeAssetQueries = async ({
runtimeAssets?: Readonly<Record<string, AssetRuntimeData>>;
assetReferences?: MarkdownAssetReferences;
assetValueReferences?: AssetValueReferences;
-}): Promise<PromiseSettledResult<AssetQueryResult>[]> => {
+}): Promise<PromiseSettledResult<AssetQueryExecutionResult>[]> => {
const results: AssetQuerySettlements = Array.from({ length: inputs.length });
const { filterKeys, preparedQueries, sortGroups } = prepareAssetQueries({
inputs,
@@ -754,10 +783,7 @@ export const executeAssetQueries = async ({
return requireSettledAssetQueryResults(results);
};
-export const executeAssetQuery = async ({
- query,
- ...input
-}: {
+type ExecuteAssetQueryInput = {
query: AssetQueryInput;
catalog?: BuilderAssetFieldCatalog;
documents: readonly ContentDatabaseDocument[];
@@ -765,7 +791,25 @@ export const executeAssetQuery = async ({
runtimeAssets?: Readonly<Record<string, AssetRuntimeData>>;
assetReferences?: MarkdownAssetReferences;
assetValueReferences?: AssetValueReferences;
-}): Promise<AssetQueryResult> => {
+};
+
+export function executeAssetQuery(
+ input: Omit<ExecuteAssetQueryInput, "query"> & {
+ query: AssetQueryInput & { result: "one" | "first" | "last" };
+ }
+): Promise<AssetQuerySingleResult>;
+export function executeAssetQuery(
+ input: Omit<ExecuteAssetQueryInput, "query"> & {
+ query: AssetQueryInput & { result?: "many" };
+ }
+): Promise<AssetQueryCollectionResult>;
+export function executeAssetQuery(
+ input: ExecuteAssetQueryInput
+): Promise<AssetQueryExecutionResult>;
+export async function executeAssetQuery({
+ query,
+ ...input
+}: ExecuteAssetQueryInput): Promise<AssetQueryExecutionResult> {
const [result] = await executeAssetQueries({
...input,
queries: [query],
@@ -774,4 +818,4 @@ export const executeAssetQuery = async ({
throw result.reason;
}
return result.value;
-};
+}
diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
index 4abea52079..dd25bef6e6 100644
--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
@@ -67723,6 +67723,11 @@ export const runtimeOperationContractData = [
query: {
type: "object",
properties: {
+ result: {
+ default: "many",
+ type: "string",
+ enum: ["many", "one", "first", "last"],
+ },
where: {
default: {
all: [],
@@ -68294,6 +68299,10 @@ export const runtimeOperationContractData = [
{
type: "object",
properties: {
+ result: {
+ type: "string",
+ enum: ["many", "one", "first", "last"],
+ },
where: {
description:
"A boolean filter tree. Use { all: [...] } for AND and { any: [...] } for OR; leaves contain field, operator, and value.",
diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.ts
index d3607f3194..bc2331f484 100644
--- a/packages/project-build/src/mcp.test.ts
+++ b/packages/project-build/src/mcp.test.ts
@@ -1178,7 +1178,8 @@ describe("project session mcp adapter", () => {
expect(tool.description).toContain("<dataSourceName>.meta");
expect(tool.description).toContain("markdown-body-ref");
expect(tool.description).toContain("document reference");
- expect(tool.description).toContain("item.content.text");
+ expect(tool.description).toContain("content.text");
+ expect(tool.description).toContain("result one");
expect(tool.description).toContain(
"one final resource per rendered query"
);
@@ -4597,6 +4598,7 @@ describe("project session mcp adapter", () => {
overviewResource: expect.objectContaining({
dataSourceName: "posts",
query: expect.objectContaining({
+ result: "many",
limit: { type: "literal", value: 20 },
offset: { type: "literal", value: 0 },
}),
@@ -4604,8 +4606,7 @@ describe("project session mcp adapter", () => {
detailResource: expect.objectContaining({
dataSourceName: "post",
query: expect.objectContaining({
- limit: { type: "literal", value: 1 },
- offset: { type: "literal", value: 0 },
+ result: "one",
content: { mode: "markdown-body-ref" },
}),
}),
@@ -4614,10 +4615,8 @@ describe("project session mcp adapter", () => {
"collectionItem.properties.author.name"
),
}),
- detailCollection: expect.objectContaining({
- itemFragment: expect.stringContaining(
- "collectionItem.content.text"
- ),
+ detailFragment: expect.objectContaining({
+ fragment: expect.stringContaining("post.data?.content?.text"),
}),
}),
workflow: expect.arrayContaining([
@@ -4640,7 +4639,8 @@ describe("project session mcp adapter", () => {
),
expect.stringContaining("only one materialized overview query"),
expect.stringContaining('content.mode:"markdown-body-ref"'),
- expect.stringContaining("Do not reshape or stringify any field"),
+ expect.stringContaining('result:"one"'),
+ expect.stringContaining("do not wrap the detail result"),
expect.stringContaining('"value":"posts.data"'),
expect.stringContaining("only the Markdown document reference"),
expect.stringContaining('field:["extension"]'),
diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.ts
index b980d1c5c6..f8f92f808b 100644
--- a/packages/project-build/src/mcp.ts
+++ b/packages/project-build/src/mcp.ts
@@ -824,7 +824,7 @@ const insertCollectionMcpInputSchema = getOperationInputSchema({
});
const assetsResourceResultDescription =
- "Pass query as structured tool input using Webstudio JavaScript expressions rather than a JSON-stringified expression or manually authored resource body. Every reachable Assets resource contributes to one shared published database, so create only one final resource per rendered query; update an existing resource instead of creating a replacement, and remove obsolete duplicates. Keep static filters, limits, and offsets literal so bounded overview queries can be materialized. Use output mode fields, select only rendered fields, keep includeMetadata false, and use content mode none when file content is not rendered. For a Markdown detail page, query the Markdown asset directly and use content mode markdown-body-ref; compilation keeps only its document reference in the bundle and fetches the selected body from Asset storage at runtime. Bind the resolved body from item.content.text. Assets expose an ID-keyed map at <dataSourceName>.data and collection information at <dataSourceName>.meta.";
+ "Pass query as structured tool input with Webstudio JavaScript expressions. Keep one final resource per rendered query and remove obsolete duplicates. Use result many for listings and result one for unique details; first and last require sorting. Keep static filters, limits, and offsets literal; single modes omit pagination. Select only rendered fields, keep includeMetadata false, and use content mode none unless file content is rendered. For Markdown details, use markdown-body-ref; compilation keeps a document reference and fetches the body at runtime. Bind <dataSourceName>.data, including id and content.text. Many returns an ID map plus totalCount and hasMore at <dataSourceName>.meta; single modes return an item or null plus totalCount.";
const mcpOperationOverrides = new Map<
string,
@@ -5592,11 +5592,11 @@ const metaGoalGuides = [
'Ensure the blog has exactly two Builder pages: an overview at the fixed path "/blog" and one detail page at the dynamic path "/blog/:slug". Create each page once with a committed call; do not dry-run it. Both pages load their content from Assets resources. Do not create one page per post or copy Markdown content into page-specific static structures.',
"Every reachable Assets data source contributes its query to one shared published database. Keep exactly one final Assets resource for the overview and one for the detail page. Never create a placeholder, preview copy, or repair replacement; update the existing scoped resource when requirements change and remove obsolete duplicates.",
'Field paths are arrays of segments, for example field:["extension"]. Literal query values use {"type":"literal","value":"..."}; raw strings are runtime expressions. Keep every overview filter value, limit, and offset literal so the bounded metadata-only result can be materialized instead of retaining its fields across every article. Use a deterministic secondary ID sort. Query Markdown posts with static extension and blog-folder constraints before any dynamic condition. Use output.mode:"fields", includeMetadata:false, and only fields rendered by that route.',
- 'Keep content.mode:"none" on the overview and use content.mode:"markdown-body-ref" only on the detail route. The detail query should have exactly one dynamic value, system.params.slug, a literal limit of 1, and only the title and author metadata rendered above Markdown Embed. The published database keeps only the Markdown document reference and fetches the selected body from Asset storage at runtime.',
+ 'Keep content.mode:"none" on the overview and use content.mode:"markdown-body-ref" only on the detail route. Set result:"one" on the detail query, use exactly one dynamic value, system.params.slug, omit limit and offset, and select only the title and author metadata rendered above Markdown Embed. The published database keeps only the Markdown document reference and fetches the selected body from Asset storage at runtime.',
"Call create-assets-resource exactly once with recipe.overviewResource after substituting the returned /blog root id and Blog folder id. Then call it exactly once with recipe.detailResource after substituting the returned /blog/:slug root id and the same Blog folder id.",
- 'Call insert-collection exactly once with the entire recipe.overviewCollection object and exactly once with the entire recipe.detailCollection object, changing only parentInstanceId to the returned root id. Do not reshape or stringify any field: data must remain the recipe object {"type":"expression","value":"posts.data"} or {"type":"expression","value":"post.data"}. Do not improvise another fragment or call meta.get-more-tools again.',
+ 'Call insert-collection exactly once with the entire recipe.overviewCollection object, changing only parentInstanceId to the returned overview root id. Call insert-fragment-verified exactly once with recipe.detailFragment, changing only parentInstanceId to the detail root id. Keep the listing data object exactly as {"type":"expression","value":"posts.data"} and bind detail fields directly from post.data; do not wrap the detail result in a Collection or call meta.get-more-tools again.',
"Validate both queries and preview the detail query with one concrete slug before saving dynamic expressions. Query-preview diagnostics report this query separately from the merged published database; use the merged database measurement when checking the deployment limit. The merged database must contain every source document without truncation, no embedded Markdown contents, and only one materialized overview query.",
- "Verify only after both Collections succeed and confirm that both pages load their content from Assets. Call verify-page-responsive once for /blog and once for one concrete detail route, including empty/not-found behavior, before finishing. If any call fails, stop and report it without retrying.",
+ "Verify only after both insertions succeed and confirm that both pages load their content from Assets. Call verify-page-responsive once for /blog and once for one concrete detail route, including empty/not-found behavior, before finishing. If any call fails, stop and report it without retrying.",
],
recipe: {
overviewResource: {
@@ -5604,6 +5604,7 @@ const metaGoalGuides = [
scopeInstanceId: "<overview-root-id>",
dataSourceName: "posts",
query: {
+ result: "many",
where: {
all: [
{
@@ -5648,6 +5649,7 @@ const metaGoalGuides = [
scopeInstanceId: "<detail-root-id>",
dataSourceName: "post",
query: {
+ result: "one",
where: {
all: [
{
@@ -5667,8 +5669,6 @@ const metaGoalGuides = [
},
],
},
- limit: { type: "literal", value: 1 },
- offset: { type: "literal", value: 0 },
output: {
mode: "fields",
includeMetadata: false,
@@ -5686,11 +5686,10 @@ const metaGoalGuides = [
itemFragment:
'<ws.element ws:tag="article"><ws.element ws:tag="h2">{expression`collectionItem.properties.title ?? "Untitled"`}</ws.element><ws.element ws:tag="p">{expression`collectionItem.properties.excerpt ?? ""`}</ws.element><ws.element ws:tag="p">By {expression`collectionItem.properties.author.name`}</ws.element><ws.element ws:tag="time">{expression`collectionItem.properties.publishedAt ?? ""`}</ws.element><ws.element ws:tag="a" href={expression`"/blog/" + collectionItem.properties.slug`}>Read article</ws.element></ws.element>',
},
- detailCollection: {
+ detailFragment: {
parentInstanceId: "<detail-root-id>",
- data: { type: "expression", value: "post.data" },
- itemFragment:
- '<ws.element ws:tag="article"><ws.element ws:tag="h1">{expression`collectionItem.properties.title ?? "Untitled"`}</ws.element><ws.element ws:tag="p">By {expression`collectionItem.properties.author.name`}</ws.element><$.MarkdownEmbed code={expression`collectionItem.content.text`} /></ws.element>',
+ fragment:
+ '<ws.element ws:tag="article"><ws.element ws:tag="h1">{expression`post.data?.properties?.title ?? "Untitled"`}</ws.element><ws.element ws:tag="p">By {expression`post.data?.properties?.author?.name ?? ""`}</ws.element><$.MarkdownEmbed code={expression`post.data?.content?.text ?? ""`} /></ws.element>',
},
},
},
diff --git a/packages/protocol/src/asset-resource-api.test.ts b/packages/protocol/src/asset-resource-api.test.ts
index 3d739ebc48..65888c674e 100644
--- a/packages/protocol/src/asset-resource-api.test.ts
+++ b/packages/protocol/src/asset-resource-api.test.ts
@@ -415,6 +415,21 @@ describe("Assets OpenAPI description", () => {
type: "variant",
config: { selection: { label: "Output", emptyOption: "none" } },
});
+ expect(
+ definition.source.controls.find(({ key }) => key === "result")
+ ).toEqual({
+ type: "select",
+ key: "result",
+ label: "Result",
+ sectionLabel: "Result",
+ defaultValue: "many",
+ options: [
+ { value: "many", label: "Many" },
+ { value: "one", label: "Exactly one" },
+ { value: "first", label: "First" },
+ { value: "last", label: "Last" },
+ ],
+ });
expect(definition.description).toMatch(
/^Autocomplete includes \d+ of 4096 observed content fields/
);
diff --git a/packages/protocol/src/asset-resource-api.ts b/packages/protocol/src/asset-resource-api.ts
index c615be4a15..556145d228 100644
--- a/packages/protocol/src/asset-resource-api.ts
+++ b/packages/protocol/src/asset-resource-api.ts
@@ -10,6 +10,7 @@ import {
import {
assetQueryRequest,
assetQueryPreviewResult,
+ assetQueryResultOptions,
assetQuerySourceDefinition,
assetQueryResult,
assetResourceQueryFailure,
@@ -325,6 +326,7 @@ const operatorLabels = new Map(
);
const queryPropertyLabels: Record<string, string> = {
+ result: "Result",
where: "Filters",
sort: "Sort",
limit: "Limit",
@@ -336,6 +338,10 @@ const queryPropertyLabels: Record<string, string> = {
length: "Content byte length",
};
+const queryResultLabels: Readonly<Record<string, string>> = Object.fromEntries(
+ assetQueryResultOptions.map(({ value, label }) => [value, label])
+);
+
const queryModeLabels: Record<string, string> = {
"output:all": "All content fields",
"output:base": "File metadata only",
@@ -531,6 +537,18 @@ const decorateAssetQuerySchema = ({
if (property !== undefined && queryPropertyLabels[property] !== undefined) {
next.title = queryPropertyLabels[property];
}
+ if (
+ property === "result" &&
+ Array.isArray(next.enum) &&
+ next.enum.every((value) => typeof value === "string")
+ ) {
+ next.oneOf = next.enum.map((value) => ({
+ const: value,
+ title: queryResultLabels[value] ?? value,
+ }));
+ delete next.enum;
+ next["x-webstudio-section"] = "Result";
+ }
if (
(property === "field" || property === "fields") &&
next.type === "array" &&
@@ -674,8 +692,8 @@ const findAssetQueryObjectSchema = (value: unknown): JsonSchema | undefined => {
}
if (
isObject(value.properties) &&
- ["where", "sort", "limit", "offset", "output", "content"].every((key) =>
- Object.hasOwn(value.properties as object, key)
+ ["result", "where", "sort", "limit", "offset", "output", "content"].every(
+ (key) => Object.hasOwn(value.properties as object, key)
)
) {
return value;
diff --git a/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts b/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
index b8871ec3bb..da34565097 100644
--- a/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
+++ b/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
@@ -501,6 +501,11 @@ export const serverOnlyRouterOperationMetadata = {
query: {
type: "object",
properties: {
+ result: {
+ default: "many",
+ type: "string",
+ enum: ["many", "one", "first", "last"],
+ },
where: {
default: {
all: [],
@@ -882,6 +887,11 @@ export const serverOnlyRouterOperationMetadata = {
query: {
type: "object",
properties: {
+ result: {
+ default: "many",
+ type: "string",
+ enum: ["many", "one", "first", "last"],
+ },
where: {
default: {
all: [],
diff --git a/packages/protocol/src/builder-api/operation-docs.ts b/packages/protocol/src/builder-api/operation-docs.ts
index 4423c31b24..cd20492c4d 100644
--- a/packages/protocol/src/builder-api/operation-docs.ts
+++ b/packages/protocol/src/builder-api/operation-docs.ts
@@ -629,7 +629,7 @@ const curatedPublicApiOperationDocumentation = [
{
command: "create-assets-resource",
description:
- 'Create a scoped Assets resource. Omit query to use the minimal default query. For an explicit query, minimize the content database by selecting only fields the page renders, keeping includeMetadata false, and using content mode none. Use markdown-body-ref when querying a Markdown body directly; it requires storage-backed document resolution and never embeds the body in the content database. A structured document may instead select a field such as { "$ref": "./article.md#body" }. Preview concrete queries and inspect size diagnostics before saving.',
+ 'Create a scoped Assets resource. Omit query to use the minimal default query. Use result many for collections and result one for unique detail routes; first and last require sorting. For an explicit query, minimize the content database by selecting only fields the page renders, keeping includeMetadata false, and using content mode none. Use markdown-body-ref when querying a Markdown body directly; it requires storage-backed document resolution and never embeds the body in the content database. A structured document may instead select a field such as { "$ref": "./article.md#body" }. Preview concrete queries and inspect size diagnostics before saving.',
requiredOptions: ["input", "json"],
examples: [
"webstudio create-assets-resource --input assets-resource.json --json",
@@ -638,7 +638,7 @@ const curatedPublicApiOperationDocumentation = [
{
command: "update-assets-resource",
description:
- 'Update an Assets resource. Set query to null to restore the minimal default query. Keep explicit queries storage-efficient by selecting only rendered fields, keeping includeMetadata false, and using content mode none. Use markdown-body-ref for a directly queried Markdown body; it requires storage-backed document resolution and never embeds the body in the content database. A structured document may instead select a field such as { "$ref": "./article.md#body" }.',
+ 'Update an Assets resource. Set query to null to restore the minimal default query. Use result many for collections and result one for unique detail routes; first and last require sorting. Keep explicit queries storage-efficient by selecting only rendered fields, keeping includeMetadata false, and using content mode none. Use markdown-body-ref for a directly queried Markdown body; it requires storage-backed document resolution and never embeds the body in the content database. A structured document may instead select a field such as { "$ref": "./article.md#body" }.',
requiredOptions: ["input", "json"],
examples: [
"webstudio update-assets-resource --input assets-resource-update.json --json",
diff --git a/packages/query-builder-react/src/index.test.tsx b/packages/query-builder-react/src/index.test.tsx
index 8c4d167170..b10ea3d53d 100644
--- a/packages/query-builder-react/src/index.test.tsx
+++ b/packages/query-builder-react/src/index.test.tsx
@@ -236,6 +236,50 @@ const GroupedSelectionFixture = () => {
};
describe("structured query builder", () => {
+ test("renders and updates a select control", () => {
+ const capabilities = {
+ version: 1,
+ fields: [],
+ operators: [],
+ source: {
+ fieldPathSchema: true,
+ controls: [
+ {
+ type: "select",
+ key: "result",
+ label: "Result",
+ sectionLabel: "Result",
+ defaultValue: "many",
+ options: [
+ { value: "many", label: "Many" },
+ { value: "one", label: "Exactly one" },
+ ],
+ },
+ ],
+ },
+ } as const satisfies QueryDefinition;
+
+ const Fixture = () => {
+ const [query, setQuery] = useState({ result: "many" });
+ return (
+ <StructuredQueryBuilder
+ value={query}
+ capabilities={capabilities}
+ onChange={setQuery}
+ />
+ );
+ };
+ render(<Fixture />);
+
+ expect(screen.getByText("Result")).toBeTruthy();
+ expect(screen.queryByText("Return")).toBeNull();
+ fireEvent.click(screen.getByLabelText("Result"));
+ fireEvent.click(screen.getByText("Exactly one"));
+ expect(
+ (screen.getByLabelText("Query") as HTMLTextAreaElement).value
+ ).toContain('result: "one"');
+ });
+
test("renders and edits solely from provider-neutral capabilities", () => {
render(<QueryBuilderFixture />);
diff --git a/packages/query-builder-react/src/index.tsx b/packages/query-builder-react/src/index.tsx
index e3172dd680..421fb0e7f1 100644
--- a/packages/query-builder-react/src/index.tsx
+++ b/packages/query-builder-react/src/index.tsx
@@ -1155,6 +1155,43 @@ export const StructuredQueryBuilder = <
/>
);
}
+ if (control.type === "select") {
+ const selected =
+ control.options.find(
+ ({ value: option }) =>
+ option === (value[control.key] ?? control.defaultValue)
+ ) ?? control.options[0];
+ return (
+ <Grid
+ key={control.key}
+ gap={2}
+ css={{
+ paddingInline: sectionPaddingInline,
+ borderTop: `1px solid ${theme.colors.borderMain}`,
+ paddingTop: theme.spacing[7],
+ }}
+ >
+ {control.sectionLabel === undefined ? null : (
+ <Label text="title">{control.sectionLabel}</Label>
+ )}
+ <Grid gap={1}>
+ {control.sectionLabel === undefined ? (
+ <Label>{control.label}</Label>
+ ) : null}
+ <Select<(typeof control.options)[number]>
+ aria-label={control.label}
+ options={control.options}
+ getLabel={(option) => option.label}
+ getValue={(option) => option.value}
+ value={selected}
+ onChange={(option) =>
+ commit({ ...value, [control.key]: option.value } as Query)
+ }
+ />
+ </Grid>
+ </Grid>
+ );
+ }
const controlIndex = capabilities.source.controls.indexOf(control);
let expressionRunStart = controlIndex;
while (
diff --git a/packages/query-builder/src/openapi.ts b/packages/query-builder/src/openapi.ts
index a74ccd820a..ea53726131 100644
--- a/packages/query-builder/src/openapi.ts
+++ b/packages/query-builder/src/openapi.ts
@@ -6,6 +6,7 @@ import type {
QueryFilterControl,
QueryOperator,
QueryParameterControlField,
+ QuerySelectControl,
} from "./types";
import { getQueryFieldKey } from "./runtime";
@@ -731,6 +732,21 @@ const createDefinition = ({
});
continue;
}
+ const choices = getChoices(document, property);
+ if (property.type === "string" && choices.length > 0) {
+ controls.push({
+ type: "select",
+ key,
+ label,
+ sectionLabel:
+ typeof property["x-webstudio-section"] === "string"
+ ? property["x-webstudio-section"]
+ : undefined,
+ defaultValue: String(defaultFromSchema(document, property)),
+ options: choices,
+ } satisfies QuerySelectControl);
+ continue;
+ }
const variant = createVariantControl({ document, key, schema: property });
if (variant !== undefined) {
controls.push(variant);
diff --git a/packages/query-builder/src/schema.ts b/packages/query-builder/src/schema.ts
index 0a59532f1e..d2f63037e5 100644
--- a/packages/query-builder/src/schema.ts
+++ b/packages/query-builder/src/schema.ts
@@ -104,6 +104,14 @@ const control = z.discriminatedUnion("type", [
exclusiveMax: z.boolean().optional(),
integer: z.boolean().optional(),
}),
+ z.strictObject({
+ type: z.literal("select"),
+ key: z.string().min(1),
+ label: z.string().min(1),
+ sectionLabel: z.string().min(1).optional(),
+ defaultValue: z.string().min(1),
+ options: z.array(choice).min(1),
+ }),
z.strictObject({
type: z.literal("variant"),
key: z.string().min(1),
@@ -269,6 +277,18 @@ export const queryDefinition = z
});
}
}
+ if (item.type === "select") {
+ const values = item.options.map(({ value }) => value);
+ if (
+ new Set(values).size !== values.length ||
+ values.includes(item.defaultValue) === false
+ ) {
+ context.addIssue({
+ code: "custom",
+ message: "Select options and default must be valid",
+ });
+ }
+ }
if (item.type === "variant") {
let parser: z.ZodType | undefined;
try {
diff --git a/packages/query-builder/src/source.ts b/packages/query-builder/src/source.ts
index 0a7b74eb12..96e6d3986f 100644
--- a/packages/query-builder/src/source.ts
+++ b/packages/query-builder/src/source.ts
@@ -294,6 +294,20 @@ export const createQuerySourceCodec = <
value[control.key] = expression;
continue;
}
+ if (control.type === "select") {
+ const selected = parseJsonExpression(expression);
+ if (
+ typeof selected !== "string" ||
+ control.options.some(({ value }) => value === selected) === false
+ ) {
+ return {
+ success: false,
+ message: `Select a valid ${control.label.toLowerCase()}.`,
+ };
+ }
+ value[control.key] = selected;
+ continue;
+ }
if (control.type === "filter") {
const where = parseWhere({
expression,
@@ -355,6 +369,17 @@ export const createQuerySourceCodec = <
fields.set(control.key, value);
continue;
}
+ if (control.type === "select") {
+ if (
+ typeof value !== "string" ||
+ control.options.some(({ value: option }) => option === value) ===
+ false
+ ) {
+ throw new Error(`Query ${control.key} is invalid`);
+ }
+ fields.set(control.key, generateJsonExpression(value));
+ continue;
+ }
if (control.type === "filter") {
const where = value as QueryWhere<string[], Operator>;
const metrics = getQueryWhereMetrics(where);
diff --git a/packages/query-builder/src/types.ts b/packages/query-builder/src/types.ts
index 845c8aac83..b1d4247a90 100644
--- a/packages/query-builder/src/types.ts
+++ b/packages/query-builder/src/types.ts
@@ -124,10 +124,20 @@ export type QueryExpressionControl = {
integer?: boolean;
};
+export type QuerySelectControl = {
+ type: "select";
+ key: string;
+ label: string;
+ sectionLabel?: string;
+ defaultValue: string;
+ options: readonly { value: string; label: string }[];
+};
+
export type QueryControl<Operator extends string = string> =
| QueryFilterControl<Operator>
| QuerySortControl
| QueryExpressionControl
+ | QuerySelectControl
| QueryVariantControl;
export type QueryDefinition<
@@ -159,6 +169,7 @@ export type QuerySourceDefinition<
| QueryFilterControl<Operator>
| QuerySortControl
| QueryExpressionControl
+ | QuerySelectControl
| QuerySourceVariantControl
)[];
};
diff --git a/packages/sdk/src/asset-resource-config.test.ts b/packages/sdk/src/asset-resource-config.test.ts
index f769df73b9..bd589c5260 100644
--- a/packages/sdk/src/asset-resource-config.test.ts
+++ b/packages/sdk/src/asset-resource-config.test.ts
@@ -223,6 +223,7 @@ describe("asset query resource configuration", () => {
test("round-trips typed filters with Webstudio value expressions", () => {
const configuration = {
+ result: "many" as const,
where: {
all: [
{
@@ -263,6 +264,40 @@ describe("asset query resource configuration", () => {
expect(body).toContain("value: $ws$dataSource$routeSlug");
});
+ test("omits pagination from saved single-result queries", () => {
+ const configuration =
+ createDefaultStructuredAssetQueryResourceConfiguration();
+ const body = createStructuredAssetQueryResourceBody({
+ ...configuration,
+ result: "one",
+ limit: "1",
+ offset: "4",
+ });
+ const query = parseExpressionObject(body)?.get("query");
+ const fields = parseExpressionObject(query ?? "");
+
+ expect(fields?.has("limit")).toBe(false);
+ expect(fields?.has("offset")).toBe(false);
+ expect(parseStructuredAssetQueryResourceBody(body)).toMatchObject({
+ result: "one",
+ limit: String(assetResourceLimits.defaultResultCount),
+ offset: "0",
+ });
+ });
+
+ test("defaults existing serialized queries to many results", () => {
+ expect(
+ parseStructuredAssetQueryResourceBody(`({ query: {
+ where: { all: [] },
+ sort: [],
+ limit: 1,
+ offset: 0,
+ output: { mode: "base", includeMetadata: true },
+ content: { mode: "none" },
+ } })`)
+ ).toMatchObject({ result: "many", limit: "1", offset: "0" });
+ });
+
test("rejects malformed structured resource bodies", () => {
expect(
parseStructuredAssetQueryResourceBody('{ "query": { "where": 1 } }')
diff --git a/packages/sdk/src/asset-resource-config.ts b/packages/sdk/src/asset-resource-config.ts
index cc5d217b00..51284010e7 100644
--- a/packages/sdk/src/asset-resource-config.ts
+++ b/packages/sdk/src/asset-resource-config.ts
@@ -24,6 +24,7 @@ import {
type AssetQueryFieldPath,
type AssetQueryFilter,
type AssetQuerySort,
+ type AssetQueryResultMode,
type AssetResourceContentOptions,
type AssetResourceOutputSelection,
type ContentCompilationPlan,
@@ -67,6 +68,7 @@ export type StructuredAssetQueryWhereBinding =
QueryWhereTree<StructuredAssetQueryFilterBinding>;
export type StructuredAssetQueryResourceConfiguration = {
+ result: AssetQueryResultMode;
where: StructuredAssetQueryWhereBinding;
sort: AssetQuerySort[];
limit: string;
@@ -75,6 +77,11 @@ export type StructuredAssetQueryResourceConfiguration = {
content: AssetResourceContentOptions;
};
+type StructuredAssetQueryResourceConfigurationInput = Omit<
+ StructuredAssetQueryResourceConfiguration,
+ "result"
+> & { result?: AssetQueryResultMode };
+
const toContentCompilationWhere = (
where: StructuredAssetQueryWhereBinding
): ContentCompilationWhere =>
@@ -113,6 +120,7 @@ const createAssetContentCompilationQuery = ({
configuration: StructuredAssetQueryResourceConfiguration;
}): ContentCompilationQuery => ({
id: resourceId,
+ result: configuration.result,
where: toContentCompilationWhere(configuration.where),
sort: configuration.sort,
limit: toContentCompilationInteger(configuration.limit),
@@ -195,17 +203,19 @@ export const parseStructuredAssetQueryResourceBody = (
};
export const createStructuredAssetQueryResourceBody = ({
+ result = "many",
where,
sort,
limit,
offset,
output = defaultAssetResourceOutputSelection,
content,
-}: StructuredAssetQueryResourceConfiguration) => {
+}: StructuredAssetQueryResourceConfigurationInput) => {
if (hasAssetQueryOutput({ output, content }) === false) {
throw new Error("Select at least one asset query output");
}
const query = assetQuerySourceCodec.format({
+ result,
where,
sort,
limit,
@@ -213,5 +223,15 @@ export const createStructuredAssetQueryResourceBody = ({
output,
content: assetResourceContentOptions.parse(content),
});
- return generateObjectExpression(new Map([["query", query]]));
+ const fields = parseExpressionObject(query);
+ if (fields === undefined) {
+ throw new Error("Assets query could not be serialized");
+ }
+ if (result !== "many") {
+ fields.delete("limit");
+ fields.delete("offset");
+ }
+ return generateObjectExpression(
+ new Map([["query", `(${generateObjectExpression(fields)})`]])
+ );
};
diff --git a/packages/sdk/src/resource-loader.test.ts b/packages/sdk/src/resource-loader.test.ts
index a00d2b7de1..1a069c1e4a 100644
--- a/packages/sdk/src/resource-loader.test.ts
+++ b/packages/sdk/src/resource-loader.test.ts
@@ -269,7 +269,10 @@ describe("loadResource", () => {
meta: { totalCount: 5, hasMore: true },
__diagnostics__: { scope: "query-preview" },
});
- expect(Object.keys(result.data)).toEqual(["second", "first"]);
+ expect(Object.keys(result.data as Record<string, unknown>)).toEqual([
+ "second",
+ "first",
+ ]);
});
test("retains ID in Assets values only when selected", async () => {
@@ -303,6 +306,38 @@ describe("loadResource", () => {
expect(result.data).toEqual({ asset: { id: "asset", name: "Asset" } });
});
+ test("exposes a single Assets result as a direct item with identity", async () => {
+ mockFetch.mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ data: {
+ item: { id: "post", properties: { title: "Post" } },
+ totalCount: 1,
+ },
+ __diagnostics__: { scope: "query-preview" },
+ })
+ )
+ );
+
+ const result = await loadResource(mockFetch, {
+ name: "assets",
+ url: "/$resources/assets",
+ searchParams: [],
+ method: "post",
+ headers: [],
+ body: { query: { result: "one" } },
+ });
+
+ expect(result).toEqual({
+ ok: true,
+ status: 200,
+ statusText: "",
+ data: { id: "post", properties: { title: "Post" } },
+ meta: { totalCount: 1 },
+ __diagnostics__: { scope: "query-preview" },
+ });
+ });
+
test("does not reshape arbitrary POST resources", async () => {
const collection = {
items: [{ id: "item" }],
diff --git a/packages/sdk/src/resource-loader.ts b/packages/sdk/src/resource-loader.ts
index 0ca44d5c10..60a7c418ad 100644
--- a/packages/sdk/src/resource-loader.ts
+++ b/packages/sdk/src/resource-loader.ts
@@ -150,6 +150,28 @@ const formatAssetsResourceResult = (value: unknown, body: unknown) => {
const preview =
isRecord(value) && isRecord(value.data) ? value.data : undefined;
const collection = preview ?? value;
+ const resultMode =
+ isRecord(body) &&
+ isRecord(body.query) &&
+ typeof body.query.result === "string"
+ ? body.query.result
+ : "many";
+ const diagnostics = isRecord(value) ? value.__diagnostics__ : undefined;
+ if (
+ resultMode !== "many" &&
+ isRecord(collection) &&
+ Object.hasOwn(collection, "item") &&
+ (collection.item === null || isRecord(collection.item)) &&
+ typeof collection.totalCount === "number"
+ ) {
+ return {
+ data: collection.item,
+ meta: { totalCount: collection.totalCount },
+ ...(preview === undefined || diagnostics === undefined
+ ? {}
+ : { __diagnostics__: diagnostics }),
+ };
+ }
if (
isRecord(collection) === false ||
Array.isArray(collection.items) === false ||
@@ -159,7 +181,6 @@ const formatAssetsResourceResult = (value: unknown, body: unknown) => {
return;
}
const includeId = includesAssetId(body);
- const diagnostics = isRecord(value) ? value.__diagnostics__ : undefined;
const entries: Array<[string, Record<string, unknown>]> = [];
for (const item of collection.items) {
if (isRecord(item) === false || typeof item.id !== "string") {
diff --git a/packages/sdk/src/schema/asset-resource.ts b/packages/sdk/src/schema/asset-resource.ts
index e35a3bd996..f9852a25cf 100644
--- a/packages/sdk/src/schema/asset-resource.ts
+++ b/packages/sdk/src/schema/asset-resource.ts
@@ -6,6 +6,7 @@ import {
import { isQueryExpression } from "@webstudio-is/query-builder";
import {
assetQueryFieldPath,
+ assetQueryResultMode,
assetQueryOperators,
assetQuerySort,
defaultAssetResourceOutputSelection,
@@ -75,6 +76,7 @@ export const assetQueryOffsetExpression = z.union([
]);
export const assetQueryResourceConfigurationInput = z.strictObject({
+ result: assetQueryResultMode.default("many"),
where: assetQueryWhereExpression
.describe(
"A boolean filter tree. Use { all: [...] } for AND and { any: [...] } for OR; leaves contain field, operator, and value."
@@ -98,6 +100,9 @@ export const assetQueryResourceConfigurationInput = z.strictObject({
});
export const assetQueryResourceConfigurationPatchInput = z.strictObject({
+ result: assetQueryResourceConfigurationInput.shape.result
+ .removeDefault()
+ .optional(),
where: assetQueryResourceConfigurationInput.shape.where
.removeDefault()
.optional(),