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.

fix: Allow Form Resources to reach sibling API hosts (#6623)

Oleg Isonen7cab28b633ed
diff --git a/docs/university/core-components/form.md b/docs/university/core-components/form.md
index fc3f6267d1..867f58d655 100644
--- a/docs/university/core-components/form.md
+++ b/docs/university/core-components/form.md
@@ -332,6 +332,7 @@ Limits count the whole request or message, not each file separately.
| **25 MiB per published Form submission** | The complete incoming multipart request: fields, files, and multipart encoding. |
| **4.5 MB per Preview Form submission** | The complete request: fields, files, and multipart encoding. Leave room for fields and encoding when choosing file sizes. |
| **25 MiB per outbound HTTP Resource body** | Webstudio's body-size check for a Form action. The destination or its network path may allow less. |
+| **1 MiB per HTTP Resource response** | The complete response after decompression, for actions and their HTTP dependencies. Request fewer fields or use pagination if it exceeds the limit. |
| **32 attachments per email** | All files attached to that email. |
| **7 MiB per email-service request** | The complete JSON request, including email text, attachment data encoded as Base64, and other fields. |
diff --git a/docs/university/foundations/variables.md b/docs/university/foundations/variables.md
index 917059a5cb..d1ff1a3588 100644
--- a/docs/university/foundations/variables.md
+++ b/docs/university/foundations/variables.md
@@ -114,6 +114,10 @@ For a Form-scoped HTTP resource, leave the body unset to forward every named For
Once the Resource fetches data, you'll use the [Expression editor](expression-editor.md) to bind data from the response to your website. See [Binding](expression-editor.md#binding) for more information.
+HTTP Resource responses are limited to **1 MiB (1,048,576 bytes) after decompression**. This applies to REST and GraphQL Resources in the Builder and published sites, including Form actions, dependencies, and cached responses. Responses over the limit fail; Webstudio does not truncate them. Request fewer fields or use the API's pagination options to reduce each response.
+
+This is a response limit, separate from Form upload limits. It does not limit images or other files loaded directly by the browser, and it does not replace the separate limits for Assets and Email Resources.
+
#### Dependent resources
Bind a Resource request field to another Resource variable when one request needs data from an earlier response. For example, bind an author ID from one Resource into the URL or search parameters of a second Resource that loads the author's posts.
diff --git a/fixtures/react-router-cloudflare/app/__generated__/$resources.managed-form-fetch.server.ts b/fixtures/react-router-cloudflare/app/__generated__/$resources.managed-form-fetch.server.ts
index 39c9256613..3b85487d93 100644
--- a/fixtures/react-router-cloudflare/app/__generated__/$resources.managed-form-fetch.server.ts
+++ b/fixtures/react-router-cloudflare/app/__generated__/$resources.managed-form-fetch.server.ts
@@ -1,6 +1,5 @@
import {
createCloudflareProtectedResourceFetch,
- getDeniedResourceHostnames,
} from "@webstudio-is/sdk/protected-resource-fetch";
import { createCloudflareManagedFormEmailSender, createCloudflareManagedFormEmailSenderWithUrl, validateCloudflareManagedFormEmail } from "@webstudio-is/sdk/form/server";
export const validateManagedFormEmail = validateCloudflareManagedFormEmail;
@@ -18,9 +17,13 @@ export const createManagedFormEmailSender = ({ context, formData, projectId }: {
export const createManagedFormResourceFetch = ({ request, context, projectDomain }: { request: Request; context: unknown; projectDomain?: string }) => {
void context;
return createCloudflareProtectedResourceFetch({
- ownZoneHostnames: getDeniedResourceHostnames([
+ projectId: "d845c167-ea07-4875-b08d-83e97c09dcce",
+ // The generated Cloudflare templates and hosted Worker use public fetch routing.
+ publicRouting: true,
+ ownZoneHostnames: [
new URL(request.url).hostname,
projectDomain,
- ]) as [string, ...string[]],
+ ...["cli-basic-test-d0osr"],
+ ].filter((hostname): hostname is string => hostname !== undefined) as [string, ...string[]],
});
};
diff --git a/fixtures/react-router-cloudflare/workers/app.ts b/fixtures/react-router-cloudflare/workers/app.ts
index 45e3c89694..be407918d5 100644
--- a/fixtures/react-router-cloudflare/workers/app.ts
+++ b/fixtures/react-router-cloudflare/workers/app.ts
@@ -1,4 +1,7 @@
import { createRequestHandler } from "react-router";
+import { isProtectedResourceReentry } from "@webstudio-is/sdk/protected-resource-fetch";
+// @ts-ignore - generated by the Webstudio CLI at build time
+import { projectId } from "../app/__generated__/_index";
declare module "react-router" {
export interface AppLoadContext {
@@ -17,6 +20,9 @@ const requestHandler = createRequestHandler(
export default {
async fetch(request, env, ctx) {
+ if (isProtectedResourceReentry(request, projectId)) {
+ return new Response(null, { status: 508 });
+ }
return requestHandler(request, {
EXCLUDE_FROM_SEARCH: false,
cloudflare: { env, ctx },
diff --git a/fixtures/react-router-cloudflare/wrangler.jsonc b/fixtures/react-router-cloudflare/wrangler.jsonc
index b63ac1bed7..765bda8f04 100644
--- a/fixtures/react-router-cloudflare/wrangler.jsonc
+++ b/fixtures/react-router-cloudflare/wrangler.jsonc
@@ -2,5 +2,6 @@
"$schema": "node_modules/wrangler/config-schema.json",
"name": "webstudio-app",
"compatibility_date": "2025-04-28",
+ "compatibility_flags": ["global_fetch_strictly_public"],
"main": "./workers/app.ts"
}
diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.managed-form-fetch.server.ts b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.managed-form-fetch.server.ts
index 39c9256613..c9fa291e5f 100644
--- a/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.managed-form-fetch.server.ts
+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.managed-form-fetch.server.ts
@@ -1,6 +1,5 @@
import {
createCloudflareProtectedResourceFetch,
- getDeniedResourceHostnames,
} from "@webstudio-is/sdk/protected-resource-fetch";
import { createCloudflareManagedFormEmailSender, createCloudflareManagedFormEmailSenderWithUrl, validateCloudflareManagedFormEmail } from "@webstudio-is/sdk/form/server";
export const validateManagedFormEmail = validateCloudflareManagedFormEmail;
@@ -18,9 +17,13 @@ export const createManagedFormEmailSender = ({ context, formData, projectId }: {
export const createManagedFormResourceFetch = ({ request, context, projectDomain }: { request: Request; context: unknown; projectDomain?: string }) => {
void context;
return createCloudflareProtectedResourceFetch({
- ownZoneHostnames: getDeniedResourceHostnames([
+ projectId: "d845c167-ea07-4875-b08d-83e97c09dcce",
+ // The generated Cloudflare templates and hosted Worker use public fetch routing.
+ publicRouting: true,
+ ownZoneHostnames: [
new URL(request.url).hostname,
projectDomain,
- ]) as [string, ...string[]],
+ ...[],
+ ].filter((hostname): hostname is string => hostname !== undefined) as [string, ...string[]],
});
};
diff --git a/fixtures/webstudio-cloudflare-template/functions/[[path]].ts b/fixtures/webstudio-cloudflare-template/functions/[[path]].ts
index 943b55594f..81571ea4a3 100644
--- a/fixtures/webstudio-cloudflare-template/functions/[[path]].ts
+++ b/fixtures/webstudio-cloudflare-template/functions/[[path]].ts
@@ -1,4 +1,7 @@
import { createPagesFunctionHandler } from "@remix-run/cloudflare-pages";
+import { isProtectedResourceReentry } from "@webstudio-is/sdk/protected-resource-fetch";
+// @ts-ignore - generated by the Webstudio CLI at build time
+import { projectId } from "../app/__generated__/_index";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore - the server build file is generated by `remix vite:build`
@@ -6,4 +9,11 @@ import * as build from "../build/server";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore - the server build file is generated by `remix vite:build`
-export const onRequest = createPagesFunctionHandler({ build });
+const requestHandler = createPagesFunctionHandler({ build });
+
+export const onRequest: typeof requestHandler = async (context) => {
+ if (isProtectedResourceReentry(context.request, projectId)) {
+ return new Response(null, { status: 508 });
+ }
+ return requestHandler(context);
+};
diff --git a/fixtures/webstudio-cloudflare-template/wrangler.jsonc b/fixtures/webstudio-cloudflare-template/wrangler.jsonc
index f338f6c6d7..b0a0b90f70 100644
--- a/fixtures/webstudio-cloudflare-template/wrangler.jsonc
+++ b/fixtures/webstudio-cloudflare-template/wrangler.jsonc
@@ -3,5 +3,6 @@
// Hosted deployments publish Workers. This takes precedence over the Cloudflare Pages
// template's wrangler.toml; publish workflows provide the name and date.
"name": "webstudio-remix-app",
- "compatibility_date": "2024-04-05"
+ "compatibility_date": "2024-04-05",
+ "compatibility_flags": ["global_fetch_strictly_public"]
}
diff --git a/fixtures/webstudio-cloudflare-template/wrangler.toml b/fixtures/webstudio-cloudflare-template/wrangler.toml
index a7b57800e8..6d3d9fd4fb 100644
--- a/fixtures/webstudio-cloudflare-template/wrangler.toml
+++ b/fixtures/webstudio-cloudflare-template/wrangler.toml
@@ -2,6 +2,7 @@
# https://developers.cloudflare.com/pages/functions/wrangler-configuration/
name = "webstudio-remix-app"
compatibility_date = "2024-04-05"
+compatibility_flags = ["global_fetch_strictly_public"]
pages_build_output_dir="./build"
# Variable bindings. These are arbitrary, plaintext strings (similar to environment variables)
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 595dd79f50..b69bb50f00 100644
--- a/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js
+++ b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js
@@ -61,7 +61,7 @@ var mm=Object.defineProperty;var wa=(e,t)=>{for(var n in t)mm(e,n,{get:t[n],enum
`)}d.write("payload.value = newResult;"),d.write("return payload;");let A=d.compile();return(S,E)=>A(p,S,E)},s,i=Ut,a=!tn.jitless,u=a&&xs.value,f=t.catchall,l;e._zod.parse=(p,d)=>{l??(l=r.value);let w=p.value;return i(w)?a&&u&&d?.async===!1&&d.jitless!==!0?(s||(s=o(t.shape)),p=s(p,d),f?gu([],w,p,d,l,e):p):n(p,d):(p.issues.push({expected:"object",code:"invalid_type",input:w,inst:e}),p)}});function Oc(e,t,n,r){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let o=e.filter(s=>!_t(s));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(s=>s.issues.map(i=>Oe(i,r,qe())))}),t)}var Ns=k("$ZodUnion",(e,t)=>{Y.init(e,t),G(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),G(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),G(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),G(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){let r=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>Bn(o.source)).join("|")})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,o)=>{if(n)return n(r,o);let s=!1,i=[];for(let a of t.options){let c=a._zod.run({value:r.value,issues:[]},o);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}return s?Promise.all(i).then(a=>Oc(a,r,e,o)):Oc(i,r,e,o)}});var bu=k("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Ns.init(e,t);let n=e._zod.parse;G(e._zod,"propValues",()=>{let o={};for(let s of t.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let r=rn(()=>{let o=t.options,s=new Map;for(let i of o){let a=i._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});e._zod.parse=(o,s)=>{let i=o.value;if(!Ut(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;let a=r.value.get(i?.[t.discriminator]);return a?a._zod.run(o,s):t.unionFallback||s.direction==="backward"?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(r.value.keys()),input:i,path:[t.discriminator],inst:e}),o)}}),wu=k("$ZodIntersection",(e,t)=>{Y.init(e,t),e._zod.parse=(n,r)=>{let o=n.value,s=t.left._zod.run({value:o,issues:[]},r),i=t.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Nc(n,c,u)):Nc(n,s,i)}});function Ts(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(xt(e)&&xt(t)){let n=Object.keys(t),r=Object.keys(e).filter(s=>n.indexOf(s)!==-1),o={...e,...t};for(let s of r){let i=Ts(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let o=e[r],s=t[r],i=Ts(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Nc(e,t,n){let r=new Map,o;for(let a of t.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(let c of a.keys)r.has(c)||r.set(c,{}),r.get(c).l=!0}else e.issues.push(a);for(let a of n.issues)if(a.code==="unrecognized_keys")for(let c of a.keys)r.has(c)||r.set(c,{}),r.get(c).r=!0;else e.issues.push(a);let s=[...r].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&o&&e.issues.push({...o,keys:s}),_t(e))return e;let i=Ts(t.value,n.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}var xu=k("$ZodRecord",(e,t)=>{Y.init(e,t),e._zod.parse=(n,r)=>{let o=n.value;if(!xt(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;let s=[],i=t.keyType._zod.values;if(i){n.value={};let a=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let f=t.keyType._zod.run({value:u,issues:[]},r);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(f.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map(d=>Oe(d,r,qe())),input:u,path:[u],inst:e});continue}let l=f.value,p=t.valueType._zod.run({value:o[u],issues:[]},r);p instanceof Promise?s.push(p.then(d=>{d.issues.length&&n.issues.push(...dt(u,d.issues)),n.value[l]=d.value})):(p.issues.length&&n.issues.push(...dt(u,p.issues)),n.value[l]=p.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:c})}else{n.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=t.keyType._zod.run({value:a,issues:[]},r);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&Ds.test(a)&&c.issues.length){let l=t.keyType._zod.run({value:Number(a),issues:[]},r);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");l.issues.length===0&&(c=l)}if(c.issues.length){t.mode==="loose"?n.value[a]=o[a]:n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(l=>Oe(l,r,qe())),input:a,path:[a],inst:e});continue}let f=t.valueType._zod.run({value:o[a],issues:[]},r);f instanceof Promise?s.push(f.then(l=>{l.issues.length&&n.issues.push(...dt(a,l.issues)),n.value[c.value]=l.value})):(f.issues.length&&n.issues.push(...dt(a,f.issues)),n.value[c.value]=f.value)}}return s.length?Promise.all(s).then(()=>n):n}});var _u=k("$ZodEnum",(e,t)=>{Y.init(e,t);let n=Fn(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(o=>_s.has(typeof o)).map(o=>typeof o=="string"?ft(o):o.toString()).join("|")})$`),e._zod.parse=(o,s)=>{let i=o.value;return r.has(i)||o.issues.push({code:"invalid_value",values:n,input:i,inst:e}),o}}),Su=k("$ZodLiteral",(e,t)=>{if(Y.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");let n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?ft(r):r?ft(r.toString()):String(r)).join("|")})$`),e._zod.parse=(r,o)=>{let s=r.value;return n.has(s)||r.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),r}});var Eu=k("$ZodTransform",(e,t)=>{Y.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new en(e.constructor.name);let o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n.fallback=!0,n));if(o instanceof Promise)throw new He;return n.value=o,n.fallback=!0,n}});function zc(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var zs=k("$ZodOptional",(e,t)=>{Y.init(e,t),e._zod.optin="optional",e._zod.optout="optional",G(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),G(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bn(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){let o=n.value,s=t.innerType._zod.run(n,r);return s instanceof Promise?s.then(i=>zc(i,o)):zc(s,o)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),Au=k("$ZodExactOptional",(e,t)=>{zs.init(e,t),G(e._zod,"values",()=>t.innerType._zod.values),G(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),ku=k("$ZodNullable",(e,t)=>{Y.init(e,t),G(e._zod,"optin",()=>t.innerType._zod.optin),G(e._zod,"optout",()=>t.innerType._zod.optout),G(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bn(n.source)}|null)$`):void 0}),G(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),vu=k("$ZodDefault",(e,t)=>{Y.init(e,t),e._zod.optin="optional",G(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>$c(s,t)):$c(o,t)}});function $c(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Ru=k("$ZodPrefault",(e,t)=>{Y.init(e,t),e._zod.optin="optional",G(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),Du=k("$ZodNonOptional",(e,t)=>{Y.init(e,t),G(e._zod,"values",()=>{let n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Lc(s,e)):Lc(o,e)}});function Lc(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var Iu=k("$ZodCatch",(e,t)=>{Y.init(e,t),e._zod.optin="optional",G(e._zod,"optout",()=>t.innerType._zod.optout),G(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(i=>Oe(i,r,qe()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(s=>Oe(s,r,qe()))},input:n.value}),n.issues=[],n.fallback=!0),n)}});var Cu=k("$ZodPipe",(e,t)=>{Y.init(e,t),G(e._zod,"values",()=>t.in._zod.values),G(e._zod,"optin",()=>t.in._zod.optin),G(e._zod,"optout",()=>t.out._zod.optout),G(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){let s=t.out._zod.run(n,r);return s instanceof Promise?s.then(i=>Br(i,t.in,r)):Br(s,t.in,r)}let o=t.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Br(s,t.out,r)):Br(o,t.out,r)}});function Br(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var Tu=k("$ZodReadonly",(e,t)=>{Y.init(e,t),G(e._zod,"propValues",()=>t.innerType._zod.propValues),G(e._zod,"values",()=>t.innerType._zod.values),G(e._zod,"optin",()=>t.innerType?._zod?.optin),G(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(Pc):Pc(o)}});function Pc(e){return e.value=Object.freeze(e.value),e}var Ou=k("$ZodLazy",(e,t)=>{Y.init(e,t),G(e._zod,"innerType",()=>{let n=t;return n._cachedInner||(n._cachedInner=t.getter()),n._cachedInner}),G(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),G(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),G(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),G(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),Nu=k("$ZodCustom",(e,t)=>{de.init(e,t),Y.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{let r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(s=>Fc(s,n,r,e));Fc(o,n,r,e)}});function Fc(e,t,n,r){if(!e){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(on(o))}}var zu,rx=Symbol("ZodOutput"),ox=Symbol("ZodInput"),$s=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){let r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){let n=t._zod.parent;if(n){let r={...this.get(n)??{}};delete r.id;let o={...r,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};function Gm(){return new $s}(zu=globalThis).__zod_globalRegistry??(zu.__zod_globalRegistry=Gm());var jt=globalThis.__zod_globalRegistry;function $u(e,t){return new e({type:"string",...$(t)})}function Lu(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...$(t)})}function Ls(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...$(t)})}function Pu(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...$(t)})}function Fu(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...$(t)})}function Mu(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...$(t)})}function Bu(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...$(t)})}function qu(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...$(t)})}function Zu(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...$(t)})}function Uu(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...$(t)})}function ju(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...$(t)})}function Vu(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...$(t)})}function Qu(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...$(t)})}function Gu(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...$(t)})}function Ju(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...$(t)})}function Wu(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...$(t)})}function Ku(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...$(t)})}function Hu(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...$(t)})}function Yu(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...$(t)})}function Xu(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...$(t)})}function el(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...$(t)})}function tl(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...$(t)})}function nl(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...$(t)})}function rl(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...$(t)})}function ol(e,t){return new e({type:"string",format:"date",check:"string_format",...$(t)})}function sl(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...$(t)})}function il(e,t){return new e({type:"string",format:"duration",check:"string_format",...$(t)})}function al(e,t){return new e({type:"number",checks:[],...$(t)})}function cl(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...$(t)})}function ul(e,t){return new e({type:"boolean",...$(t)})}function ll(e,t){return new e({type:"null",...$(t)})}function fl(e){return new e({type:"unknown"})}function dl(e,t){return new e({type:"never",...$(t)})}function Ur(e,t){return new Is({check:"less_than",...$(t),value:e,inclusive:!1})}function Vn(e,t){return new Is({check:"less_than",...$(t),value:e,inclusive:!0})}function jr(e,t){return new Cs({check:"greater_than",...$(t),value:e,inclusive:!1})}function Qn(e,t){return new Cs({check:"greater_than",...$(t),value:e,inclusive:!0})}function Vr(e,t){return new yc({check:"multiple_of",...$(t),value:e})}function Qr(e,t){return new wc({check:"max_length",...$(t),maximum:e})}function sn(e,t){return new xc({check:"min_length",...$(t),minimum:e})}function Gr(e,t){return new _c({check:"length_equals",...$(t),length:e})}function Ps(e,t){return new Sc({check:"string_format",format:"regex",...$(t),pattern:e})}function Fs(e){return new Ec({check:"string_format",format:"lowercase",...$(e)})}function Ms(e){return new Ac({check:"string_format",format:"uppercase",...$(e)})}function Bs(e,t){return new kc({check:"string_format",format:"includes",...$(t),includes:e})}function qs(e,t){return new vc({check:"string_format",format:"starts_with",...$(t),prefix:e})}function Zs(e,t){return new Rc({check:"string_format",format:"ends_with",...$(t),suffix:e})}function St(e){return new Dc({check:"overwrite",tx:e})}function Us(e){return St(t=>t.normalize(e))}function js(){return St(e=>e.trim())}function Vs(){return St(e=>e.toLowerCase())}function Qs(){return St(e=>e.toUpperCase())}function Gs(){return St(e=>ws(e))}function pl(e,t,n){return new e({type:"array",element:t,...$(n)})}function ml(e,t,n){return new e({type:"custom",check:"custom",fn:t,...$(n)})}function hl(e,t){let n=Jm(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(on(o,r.value,n._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),r.issues.push(on(s))}},e(r.value,r)),t);return n}function Jm(e,t){let n=new de({check:"custom",...$(t)});return n._zod.check=e,n}function Js(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??jt,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function re(e,t,n={path:[],schemaPath:[]}){var r;let o=e._zod.def,s=t.seen.get(e);if(s)return s.count++,n.schemaPath.includes(e)&&(s.cycle=n.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,i);let a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{let f={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,f);else{let p=i.schema,d=t.processors[o.type];if(!d)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);d(e,t,p,f)}let l=e._zod.parent;l&&(i.ref||(i.ref=l),re(l,t,f),t.seen.get(l).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(i.schema,c),t.io==="input"&&be(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&"_prefault"in i.schema&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function Ws(e,t){let n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=new Map;for(let i of e.seen.entries()){let a=e.metadataRegistry.get(i[0])?.id;if(a){let c=r.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,i[0])}}let o=i=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let l=e.external.registry.get(i[0])?.id,p=e.external.uri??(w=>w);if(l)return{ref:p(l)};let d=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=d,{defId:d,ref:`${p("__shared")}#/${a}/${d}`}}if(i[1]===n)return{ref:"#"};let u=`#/${a}/`,f=i[1].schema.id??`__schema${e.counter++}`;return{defId:f,ref:u+f}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=o(i);a.def={...a.schema},u&&(a.defId=u);let f=a.schema;for(let l in f)delete f[l];f.$ref=c};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
-Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){s(i);continue}if(e.external){let u=e.external.registry.get(i[0])?.id;if(t!==i[0]&&u){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&e.reused==="ref"){s(i);continue}}}function Ks(e,t){let n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=a=>{let c=e.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,f={...u},l=c.ref;if(c.ref=null,l){r(l);let d=e.seen.get(l),w=d.schema;if(w.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(w)):Object.assign(u,w),Object.assign(u,f),a._zod.parent===l)for(let y in u)y==="$ref"||y==="allOf"||y in f||delete u[y];if(w.$ref&&d.def)for(let y in u)y==="$ref"||y==="allOf"||y in d.def&&JSON.stringify(u[y])===JSON.stringify(d.def[y])&&delete u[y]}let p=a._zod.parent;if(p&&p!==l){r(p);let d=e.seen.get(p);if(d?.schema.$ref&&(u.$ref=d.schema.$ref,d.def))for(let w in u)w==="$ref"||w==="allOf"||w in d.def&&JSON.stringify(u[w])===JSON.stringify(d.def[w])&&delete u[w]}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...e.seen.entries()].reverse())r(a[0]);let o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Object.assign(o,n.def??n.schema);let s=e.metadataRegistry.get(t)?.id;s!==void 0&&o.id===s&&delete o.id;let i=e.external?.defs??{};for(let a of e.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Gn(t,"input",e.processors),output:Gn(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function be(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return be(r.element,n);if(r.type==="set")return be(r.valueType,n);if(r.type==="lazy")return be(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return be(r.innerType,n);if(r.type==="intersection")return be(r.left,n)||be(r.right,n);if(r.type==="record"||r.type==="map")return be(r.keyType,n)||be(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:be(r.in,n)||be(r.out,n);if(r.type==="object"){for(let o in r.shape)if(be(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(be(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(be(o,n))return!0;return!!(r.rest&&be(r.rest,n))}return!1}var gl=(e,t={})=>n=>{let r=Js({...n,processors:t});return re(e,r),Ws(r,e),Ks(r,e)},Gn=(e,t,n={})=>r=>{let{libraryOptions:o,target:s}=r??{},i=Js({...o??{},target:s,io:t,processors:n});return re(e,i),Ws(i,e),Ks(i,e)};var Wm={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},yl=(e,t,n,r)=>{let o=n;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=Wm[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),u&&(o.contentEncoding=u),c&&c.size>0){let f=[...c];f.length===1?o.pattern=f[0].source:f.length>1&&(o.allOf=[...f.map(l=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:l.source}))])}},bl=(e,t,n,r)=>{let o=n,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:f}=e._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";let l=typeof f=="number"&&f>=(s??Number.NEGATIVE_INFINITY),p=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),d=t.target==="draft-04"||t.target==="openapi-3.0";l?d?(o.minimum=f,o.exclusiveMinimum=!0):o.exclusiveMinimum=f:typeof s=="number"&&(o.minimum=s),p?d?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof c=="number"&&(o.multipleOf=c)},wl=(e,t,n,r)=>{n.type="boolean"};var xl=(e,t,n,r)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"};var _l=(e,t,n,r)=>{n.not={}};var Sl=(e,t,n,r)=>{};var El=(e,t,n,r)=>{let o=e._zod.def,s=Fn(o.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},Al=(e,t,n,r)=>{let o=e._zod.def,s=[];for(let i of o.values)if(i===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){let i=s[0];n.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[i]:n.const=i}else s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),s.every(i=>typeof i=="boolean")&&(n.type="boolean"),s.every(i=>i===null)&&(n.type="null"),n.enum=s};var kl=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var vl=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var Rl=(e,t,n,r)=>{let o=n,s=e._zod.def,{minimum:i,maximum:a}=e._zod.bag;typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=re(s.element,t,{...r,path:[...r.path,"items"]})},Dl=(e,t,n,r)=>{let o=n,s=e._zod.def;o.type="object",o.properties={};let i=s.shape;for(let u in i)o.properties[u]=re(i[u],t,{...r,path:[...r.path,"properties",u]});let a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{let f=s.shape[u]._zod;return t.io==="input"?f.optin===void 0:f.optout===void 0}));c.size>0&&(o.required=Array.from(c)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=re(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},Il=(e,t,n,r)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>re(a,t,{...r,path:[...r.path,s?"oneOf":"anyOf",c]}));s?n.oneOf=i:n.anyOf=i},Cl=(e,t,n,r)=>{let o=e._zod.def,s=re(o.left,t,{...r,path:[...r.path,"allOf",0]}),i=re(o.right,t,{...r,path:[...r.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];n.allOf=c};var Tl=(e,t,n,r)=>{let o=n,s=e._zod.def;o.type="object";let i=s.keyType,c=i._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let f=re(s.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let l of c)o.patternProperties[l.source]=f}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=re(s.keyType,t,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=re(s.valueType,t,{...r,path:[...r.path,"additionalProperties"]});let u=i._zod.values;if(u){let f=[...u].filter(l=>typeof l=="string"||typeof l=="number");f.length>0&&(o.required=f)}},Ol=(e,t,n,r)=>{let o=e._zod.def,s=re(o.innerType,t,r),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=o.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},Nl=(e,t,n,r)=>{let o=e._zod.def;re(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType},zl=(e,t,n,r)=>{let o=e._zod.def;re(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},$l=(e,t,n,r)=>{let o=e._zod.def;re(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},Ll=(e,t,n,r)=>{let o=e._zod.def;re(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i},Pl=(e,t,n,r)=>{let o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?o.out:o.in:o.out;re(i,t,r);let a=t.seen.get(e);a.ref=i},Fl=(e,t,n,r)=>{let o=e._zod.def;re(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType,n.readOnly=!0};var Hs=(e,t,n,r)=>{let o=e._zod.def;re(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType},Ml=(e,t,n,r)=>{let o=e._zod.innerType;re(o,t,r);let s=t.seen.get(e);s.ref=o};var nh=k("ZodISODateTime",(e,t)=>{Kc.init(e,t),te.init(e,t)});function Bl(e){return rl(nh,e)}var rh=k("ZodISODate",(e,t)=>{Hc.init(e,t),te.init(e,t)});function ql(e){return ol(rh,e)}var oh=k("ZodISOTime",(e,t)=>{Yc.init(e,t),te.init(e,t)});function Zl(e){return sl(oh,e)}var sh=k("ZodISODuration",(e,t)=>{Xc.init(e,t),te.init(e,t)});function Ul(e){return il(sh,e)}var jl=(e,t)=>{$r.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Ta(e,n)},flatten:{value:n=>Ca(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,nn,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,nn,2)}},isEmpty:{get(){return e.issues.length===0}}})},Vl=k("ZodError",jl),ke=k("ZodError",jl,{Parent:Error});var Ql=Lr(ke),Gl=Pr(ke),Jl=Zn(ke),Wl=Un(ke),Kl=za(ke),Hl=$a(ke),Yl=La(ke),Xl=Pa(ke),ef=Fa(ke),tf=Ma(ke),nf=Ba(ke),rf=qa(ke);var of=new WeakMap;function Jn(e,t,n){let r=Object.getPrototypeOf(e),o=of.get(r);if(o||(o=new Set,of.set(r,o)),!o.has(t)){o.add(t);for(let s in n){let i=n[s];Object.defineProperty(r,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var ee=k("ZodType",(e,t)=>(Y.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Gn(e,"input"),output:Gn(e,"output")}}),e.toJSONSchema=gl(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>Ql(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>Jl(e,n,r),e.parseAsync=async(n,r)=>Gl(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Wl(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>Kl(e,n,r),e.decode=(n,r)=>Hl(e,n,r),e.encodeAsync=async(n,r)=>Yl(e,n,r),e.decodeAsync=async(n,r)=>Xl(e,n,r),e.safeEncode=(n,r)=>ef(e,n,r),e.safeDecode=(n,r)=>tf(e,n,r),e.safeEncodeAsync=async(n,r)=>nf(e,n,r),e.safeDecodeAsync=async(n,r)=>rf(e,n,r),Jn(e,"ZodType",{check(...n){let r=this.def;return this.clone(J.mergeDefs(r,{checks:[...r.checks??[],...n.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return Ze(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(tg(n,r))},superRefine(n,r){return this.check(ng(n,r))},overwrite(n){return this.check(St(n))},optional(){return lf(this)},exactOptional(){return qh(this)},nullable(){return ff(this)},nullish(){return lf(ff(this))},nonoptional(n){return Gh(this,n)},array(){return H(this)},or(n){return an([this,n])},and(n){return Lh(this,n)},transform(n){return df(this,Mh(n))},default(n){return jh(this,n)},prefault(n){return Qh(this,n)},catch(n){return Wh(this,n)},pipe(n){return df(this,n)},readonly(){return Yh(this)},describe(n){let r=this.clone();return jt.add(r,{description:n}),r},meta(...n){if(n.length===0)return jt.get(this);let r=this.clone();return jt.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return jt.get(e)?.description},configurable:!0}),e)),pf=k("_ZodString",(e,t)=>{Zr.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,s)=>yl(e,r,o,s);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Jn(e,"_ZodString",{regex(...r){return this.check(Ps(...r))},includes(...r){return this.check(Bs(...r))},startsWith(...r){return this.check(qs(...r))},endsWith(...r){return this.check(Zs(...r))},min(...r){return this.check(sn(...r))},max(...r){return this.check(Qr(...r))},length(...r){return this.check(Gr(...r))},nonempty(...r){return this.check(sn(1,...r))},lowercase(r){return this.check(Fs(r))},uppercase(r){return this.check(Ms(r))},trim(){return this.check(js())},normalize(...r){return this.check(Us(...r))},toLowerCase(){return this.check(Vs())},toUpperCase(){return this.check(Qs())},slugify(){return this.check(Gs())}})}),uh=k("ZodString",(e,t)=>{Zr.init(e,t),pf.init(e,t),e.email=n=>e.check(Lu(lh,n)),e.url=n=>e.check(qu(fh,n)),e.jwt=n=>e.check(nl(vh,n)),e.emoji=n=>e.check(Zu(dh,n)),e.guid=n=>e.check(Ls(sf,n)),e.uuid=n=>e.check(Pu(Wr,n)),e.uuidv4=n=>e.check(Fu(Wr,n)),e.uuidv6=n=>e.check(Mu(Wr,n)),e.uuidv7=n=>e.check(Bu(Wr,n)),e.nanoid=n=>e.check(Uu(ph,n)),e.guid=n=>e.check(Ls(sf,n)),e.cuid=n=>e.check(ju(mh,n)),e.cuid2=n=>e.check(Vu(hh,n)),e.ulid=n=>e.check(Qu(gh,n)),e.base64=n=>e.check(Xu(Eh,n)),e.base64url=n=>e.check(el(Ah,n)),e.xid=n=>e.check(Gu(yh,n)),e.ksuid=n=>e.check(Ju(bh,n)),e.ipv4=n=>e.check(Wu(wh,n)),e.ipv6=n=>e.check(Ku(xh,n)),e.cidrv4=n=>e.check(Hu(_h,n)),e.cidrv6=n=>e.check(Yu(Sh,n)),e.e164=n=>e.check(tl(kh,n)),e.datetime=n=>e.check(Bl(n)),e.date=n=>e.check(ql(n)),e.time=n=>e.check(Zl(n)),e.duration=n=>e.check(Ul(n))});function D(e){return $u(uh,e)}var te=k("ZodStringFormat",(e,t)=>{X.init(e,t),pf.init(e,t)}),lh=k("ZodEmail",(e,t)=>{qc.init(e,t),te.init(e,t)});var sf=k("ZodGUID",(e,t)=>{Mc.init(e,t),te.init(e,t)});var Wr=k("ZodUUID",(e,t)=>{Bc.init(e,t),te.init(e,t)});var fh=k("ZodURL",(e,t)=>{Zc.init(e,t),te.init(e,t)});var dh=k("ZodEmoji",(e,t)=>{Uc.init(e,t),te.init(e,t)});var ph=k("ZodNanoID",(e,t)=>{jc.init(e,t),te.init(e,t)});var mh=k("ZodCUID",(e,t)=>{Vc.init(e,t),te.init(e,t)});var hh=k("ZodCUID2",(e,t)=>{Qc.init(e,t),te.init(e,t)});var gh=k("ZodULID",(e,t)=>{Gc.init(e,t),te.init(e,t)});var yh=k("ZodXID",(e,t)=>{Jc.init(e,t),te.init(e,t)});var bh=k("ZodKSUID",(e,t)=>{Wc.init(e,t),te.init(e,t)});var wh=k("ZodIPv4",(e,t)=>{eu.init(e,t),te.init(e,t)});var xh=k("ZodIPv6",(e,t)=>{tu.init(e,t),te.init(e,t)});var _h=k("ZodCIDRv4",(e,t)=>{nu.init(e,t),te.init(e,t)});var Sh=k("ZodCIDRv6",(e,t)=>{ru.init(e,t),te.init(e,t)});var Eh=k("ZodBase64",(e,t)=>{su.init(e,t),te.init(e,t)});var Ah=k("ZodBase64URL",(e,t)=>{iu.init(e,t),te.init(e,t)});var kh=k("ZodE164",(e,t)=>{au.init(e,t),te.init(e,t)});var vh=k("ZodJWT",(e,t)=>{cu.init(e,t),te.init(e,t)});var mf=k("ZodNumber",(e,t)=>{Os.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,s)=>bl(e,r,o,s),Jn(e,"ZodNumber",{gt(r,o){return this.check(jr(r,o))},gte(r,o){return this.check(Qn(r,o))},min(r,o){return this.check(Qn(r,o))},lt(r,o){return this.check(Ur(r,o))},lte(r,o){return this.check(Vn(r,o))},max(r,o){return this.check(Vn(r,o))},int(r){return this.check(af(r))},safe(r){return this.check(af(r))},positive(r){return this.check(jr(0,r))},nonnegative(r){return this.check(Qn(0,r))},negative(r){return this.check(Ur(0,r))},nonpositive(r){return this.check(Vn(0,r))},multipleOf(r,o){return this.check(Vr(r,o))},step(r,o){return this.check(Vr(r,o))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function U(e){return al(mf,e)}var Rh=k("ZodNumberFormat",(e,t)=>{uu.init(e,t),mf.init(e,t)});function af(e){return cl(Rh,e)}var Dh=k("ZodBoolean",(e,t)=>{lu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>wl(e,n,r,o)});function pt(e){return ul(Dh,e)}var Ih=k("ZodNull",(e,t)=>{fu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>xl(e,n,r,o)});function Ch(e){return ll(Ih,e)}var Th=k("ZodUnknown",(e,t)=>{du.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Sl(e,n,r,o)});function cf(){return fl(Th)}var Oh=k("ZodNever",(e,t)=>{pu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>_l(e,n,r,o)});function hf(e){return dl(Oh,e)}var Nh=k("ZodArray",(e,t)=>{mu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Rl(e,n,r,o),e.element=t.element,Jn(e,"ZodArray",{min(n,r){return this.check(sn(n,r))},nonempty(n){return this.check(sn(1,n))},max(n,r){return this.check(Qr(n,r))},length(n,r){return this.check(Gr(n,r))},unwrap(){return this.element}})});function H(e,t){return pl(Nh,e,t)}var gf=k("ZodObject",(e,t)=>{yu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Dl(e,n,r,o),J.defineLazy(e,"shape",()=>t.shape),Jn(e,"ZodObject",{keyof(){return fe(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:cf()})},loose(){return this.clone({...this._zod.def,catchall:cf()})},strict(){return this.clone({...this._zod.def,catchall:hf()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return J.extend(this,n)},safeExtend(n){return J.safeExtend(this,n)},merge(n){return J.merge(this,n)},pick(n){return J.pick(this,n)},omit(n){return J.omit(this,n)},partial(...n){return J.partial(bf,this,n[0])},required(...n){return J.required(wf,this,n[0])}})});function Et(e,t){let n={type:"object",shape:e??{},...J.normalizeParams(t)};return new gf(n)}function L(e,t){return new gf({type:"object",shape:e,catchall:hf(),...J.normalizeParams(t)})}var yf=k("ZodUnion",(e,t)=>{Ns.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Il(e,n,r,o),e.options=t.options});function an(e,t){return new yf({type:"union",options:e,...J.normalizeParams(t)})}var zh=k("ZodDiscriminatedUnion",(e,t)=>{yf.init(e,t),bu.init(e,t)});function cn(e,t,n){return new zh({type:"union",options:t,discriminator:e,...J.normalizeParams(n)})}var $h=k("ZodIntersection",(e,t)=>{wu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Cl(e,n,r,o)});function Lh(e,t){return new $h({type:"intersection",left:e,right:t})}var uf=k("ZodRecord",(e,t)=>{xu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Tl(e,n,r,o),e.keyType=t.keyType,e.valueType=t.valueType});function Ne(e,t,n){return!t||!t._zod?new uf({type:"record",keyType:D(),valueType:e,...J.normalizeParams(t)}):new uf({type:"record",keyType:e,valueType:t,...J.normalizeParams(n)})}var Ys=k("ZodEnum",(e,t)=>{_u.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,s)=>El(e,r,o,s),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Ys({...t,checks:[],...J.normalizeParams(o),entries:s})},e.exclude=(r,o)=>{let s={...t.entries};for(let i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Ys({...t,checks:[],...J.normalizeParams(o),entries:s})}});function fe(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Ys({type:"enum",entries:n,...J.normalizeParams(t)})}var Ph=k("ZodLiteral",(e,t)=>{Su.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Al(e,n,r,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function W(e,t){return new Ph({type:"literal",values:Array.isArray(e)?e:[e],...J.normalizeParams(t)})}var Fh=k("ZodTransform",(e,t)=>{Eu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>vl(e,n,r,o),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new en(e.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(J.issue(s,n.value,t));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),n.issues.push(J.issue(i))}};let o=t.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});function Mh(e){return new Fh({type:"transform",transform:e})}var bf=k("ZodOptional",(e,t)=>{zs.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Hs(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function lf(e){return new bf({type:"optional",innerType:e})}var Bh=k("ZodExactOptional",(e,t)=>{Au.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Hs(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function qh(e){return new Bh({type:"optional",innerType:e})}var Zh=k("ZodNullable",(e,t)=>{ku.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ol(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function ff(e){return new Zh({type:"nullable",innerType:e})}var Uh=k("ZodDefault",(e,t)=>{vu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>zl(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function jh(e,t){return new Uh({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():J.shallowClone(t)}})}var Vh=k("ZodPrefault",(e,t)=>{Ru.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>$l(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Qh(e,t){return new Vh({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():J.shallowClone(t)}})}var wf=k("ZodNonOptional",(e,t)=>{Du.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Nl(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Gh(e,t){return new wf({type:"nonoptional",innerType:e,...J.normalizeParams(t)})}var Jh=k("ZodCatch",(e,t)=>{Iu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ll(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Wh(e,t){return new Jh({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Kh=k("ZodPipe",(e,t)=>{Cu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Pl(e,n,r,o),e.in=t.in,e.out=t.out});function df(e,t){return new Kh({type:"pipe",in:e,out:t})}var Hh=k("ZodReadonly",(e,t)=>{Tu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Fl(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Yh(e){return new Hh({type:"readonly",innerType:e})}var Xh=k("ZodLazy",(e,t)=>{Ou.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ml(e,n,r,o),e.unwrap=()=>e._zod.def.getter()});function Xs(e){return new Xh({type:"lazy",getter:e})}var eg=k("ZodCustom",(e,t)=>{Nu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>kl(e,n,r,o)});function tg(e,t={}){return ml(eg,e,t)}function ng(e,t){return hl(e,t)}function At(e){let t=Xs(()=>an([D(e),U(),pt(),Ch(),H(t),Ne(D(),t)]));return t}var xf=e=>"field"in e?[e]:("all"in e?e.all:e.any).flatMap(xf),Kr=e=>xf(e);var un=(e,t)=>{if("field"in e)return t(e);let n="all"in e?e.all:e.any,r=!1;if("all"in e){for(let o of n){let s=un(o,t);if(s===!1)return!1;r||=s===void 0}return r?void 0:!0}for(let o of n){let s=un(o,t);if(s===!0)return!0;r||=s===void 0}return r?void 0:!1},_f=e=>JSON.stringify(e),ei=e=>{if("field"in e)return{conditions:1,depth:0};let t="all"in e?e.all:e.any,n=0,r=1;for(let o of t){let s=ei(o);n+=s.conditions,r=Math.max(r,s.depth+1)}return{conditions:n,depth:r}},Sf=(e,t={})=>{let n=o=>{let s=H(o),i=t.maximumChildren===void 0?s:s.max(t.maximumChildren);return an([e,L({all:i}),L({any:i})])},r=Xs(()=>n(r));return t.maximumConditions===void 0&&t.maximumDepth===void 0?r:r.superRefine((o,s)=>{let{conditions:i,depth:a}=ei(o);t.maximumConditions!==void 0&&i>t.maximumConditions&&s.addIssue({code:"custom",message:t.maximumConditionsMessage??"Query exceeds the condition limit"}),t.maximumDepth!==void 0&&a>t.maximumDepth&&s.addIssue({code:"custom",message:t.maximumDepthMessage??"Query exceeds the nesting limit"})})};var N={requestBytes:524288,filterCount:32,filterDepth:8,sortCount:8,outputFieldCount:256,fieldPathDepth:9,defaultResultCount:20,resultCount:1e3,resultBytes:16777216,candidateDocuments:1e3,documentGraphDocuments:2e3,databaseBytes:512e3,frontmatterBytes:65536,frontmatterDepth:8,frontmatterFields:256,frontmatterStringBytes:16384,jsonBytes:1048576,jsonDepth:8,jsonFields:256,jsonStringBytes:16384,indexedPropertiesBytes:65536,excerptBytes:2048,mdxDepth:100,mdxNodes:2e4,mdxProps:4e3,hydratedFileBytes:1048576,hydratedTotalBytes:2097152,hydratedFileCount:20,hydratedRangeBytes:262144,concurrentContentReads:8};function Vt(e,t=new Set){if(typeof e=="number"&&isNaN(e))throw new Error("NaN is not allowed");if(typeof e=="number"&&!isFinite(e))throw new Error("Infinity is not allowed");if(e===null||typeof e!="object")return JSON.stringify(e);if(typeof e.toJSON=="function"){if(t.has(e))throw new Error("Circular reference detected");t.add(e);let r=Vt(e.toJSON(),t);return t.delete(e),r}if(t.has(e))throw new Error("Circular reference detected");t.add(e);let n;if(Array.isArray(e))n=`[${e.map(o=>Vt(o===void 0||typeof o=="symbol"?null:o,t)).join(",")}]`;else{let r=[];for(let o of Object.keys(e).sort())e[o]===void 0||typeof e[o]=="symbol"||r.push(`${Vt(o)}:${Vt(e[o],t)}`);n=`{${r.join(",")}}`}return t.delete(e),n}var rg=new TextEncoder,kt=e=>rg.encode(e),Ye=e=>kt(e).byteLength,we=class extends Error{constructor(){super("Byte stream exceeds the configured limit"),this.name="ByteLimitExceededError"}},og=(e,t)=>{let n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.byteLength;return n},Wn=e=>typeof e=="string"?{async*[Symbol.asyncIterator](){yield kt(e)}}:e instanceof Uint8Array?{async*[Symbol.asyncIterator](){yield e}}:e,Hr=(e,t)=>t===void 0?Wn(e):{async*[Symbol.asyncIterator](){let n=0,r=0;for await(let o of Wn(e)){if(r===t.length)return;if(n+o.byteLength<=t.offset){n+=o.byteLength;continue}let s=Math.max(0,t.offset-n),i=Math.min(o.byteLength-s,t.length-r);i>0&&(yield o.subarray(s,s+i),r+=i),n+=o.byteLength}}},Yr=e=>({async*[Symbol.asyncIterator](){let t=e.getReader(),n=!1;try{for(;;){let r=await t.read();if(r.done){n=!0;return}yield r.value}}finally{if(n===!1)try{await t.cancel()}catch{}t.releaseLock()}}}),ti=async(e,t)=>{let n=[],r=0;for await(let o of Wn(e)){let s=t-r;if(s<=0)break;let i=o.subarray(0,s);if(n.push(i),r+=i.byteLength,r===t)break}return og(n,r)},Xe=async(e,t)=>{let n=await ti(e,t+1);if(n.byteLength>t)throw new we;return n},ve=e=>new TextDecoder("utf-8",{fatal:!0}).decode(e),ln=e=>e.charCodeAt(0)===65279?e.slice(1):e;var Ef=e=>{for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n>=55296&&n<=56319){let r=e.charCodeAt(t+1);if(t+1>=e.length||r<56320||r>57343)throw new Error("JSON strings cannot contain lone Unicode surrogates");t+=1;continue}if(n>=56320&&n<=57343)throw new Error("JSON strings cannot contain lone Unicode surrogates")}},ni=(e,t)=>{if(e===null||typeof e=="boolean")return e;if(typeof e=="string")return Ef(e),e;if(typeof e=="number"){if(Number.isFinite(e)===!1)throw new Error("JSON cannot contain non-finite numbers");return e}if(Array.isArray(e)){if(Object.getOwnPropertySymbols(e).length>0)throw new Error("JSON arrays cannot contain symbol properties");if(t.has(e))throw new Error("JSON cannot contain circular references");t.add(e);try{let n=[];for(let r=0;r<e.length;r+=1){if(Object.hasOwn(e,r)===!1)throw new Error("JSON arrays cannot be sparse");let o=e[r];if(o===void 0)throw new Error("JSON arrays cannot contain undefined values");n.push(ni(o,t))}if(Object.keys(e).length!==e.length)throw new Error("JSON arrays cannot contain named properties");return n}finally{t.delete(e)}}if(typeof e=="object"){let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new Error("JSON can contain only plain objects");if(Object.getOwnPropertySymbols(e).length>0)throw new Error("JSON objects cannot contain symbol properties");if(t.has(e))throw new Error("JSON cannot contain circular references");t.add(e);let r={};try{for(let[o,s]of Object.entries(e))Ef(o),s!==void 0&&Object.defineProperty(r,o,{value:ni(s,t),enumerable:!0,configurable:!0,writable:!0})}finally{t.delete(e)}return r}throw new Error("Value cannot be represented as JSON")},vt=e=>ni(e,new Set),Re=e=>{let t=Vt(vt(e));if(t===void 0)throw new Error("Value cannot be represented as canonical JSON");return t},Kn=(e,t)=>e===void 0||t===void 0?e===t:Re(e)===Re(t),et=(e,t)=>e<t?-1:e>t?1:0,ri=async e=>{let t=typeof e=="string"?kt(e):e,n=await globalThis.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")},Af=async e=>`sha256:${await ri(e)}`;var kf=cn("type",[L({type:W("document")}),L({type:W("json"),path:H(D()).min(1)}),L({type:W("markdown-body")}),L({type:W("markdown-frontmatter")})]),oi=L({documentId:D().min(1),revision:D().min(1),representation:kf}),sg=e=>{let t=kf.parse(e);return t.type==="json"?Object.freeze({...t,path:Object.freeze([...t.path])}):Object.freeze(t)},vf=e=>{let t=oi.parse(e);return Object.freeze({...t,representation:sg(t.representation)})};var Hn=["json","markdown","mdx"],Rf=e=>typeof e=="string"&&Hn.includes(e),Df=e=>{let t=e.split(";",1)[0].trim().toLowerCase();if(t==="application/json")return"json";if(t==="text/markdown")return"markdown";if(t==="text/mdx")return"mdx"};var Xr=L({id:D().min(1),revision:D().min(1),contentRef:D().min(1),format:fe(Hn).optional()}),eo=L({sourceId:D().min(1),referenceId:D().min(1),reference:oi});var fn=e=>{let t=new Map;for(let n of e){let r=t.get(n.sourceId)??[];r.push(n),t.set(n.sourceId,r)}return t};var tt=class extends Error{code;documentIds;constructor({code:t,message:n,documentIds:r=[]}){super(n),this.name="DocumentGraphError",this.code=t,this.documentIds=Object.freeze([...r])}},ig=(e,t)=>et(e.sourceId,t.sourceId)||et(e.referenceId,t.referenceId),Yn=({nodes:e,edges:t})=>{let n=e.map(a=>Object.freeze(Xr.parse(a))).sort((a,c)=>et(a.id,c.id)),r=new Map,o=new Map;for(let a of n){if(r.has(a.id))throw new tt({code:"DUPLICATE_NODE",message:`Document graph contains duplicate node ${a.id}`,documentIds:[a.id]});r.set(a.id,a);let c=o.get(a.contentRef);if(c!==void 0&&(c.revision!==a.revision||c.format!==a.format))throw new tt({code:"CONTENT_IDENTITY_CONFLICT",message:`Document graph content reference ${a.contentRef} has conflicting identities`,documentIds:[c.id,a.id]});o.set(a.contentRef,a)}let s=t.map(a=>{let c=eo.parse(a);return Object.freeze({...c,reference:vf(c.reference)})}).sort(ig),i=new Set;for(let a of s){if(r.get(a.sourceId)===void 0)throw new tt({code:"SOURCE_NOT_FOUND",message:`Document graph source ${a.sourceId} does not exist`,documentIds:[a.sourceId]});let u=r.get(a.reference.documentId);if(u===void 0)throw new tt({code:"TARGET_NOT_FOUND",message:`Document graph target ${a.reference.documentId} does not exist`,documentIds:[a.sourceId,a.reference.documentId]});if(u.revision!==a.reference.revision)throw new tt({code:"TARGET_REVISION_MISMATCH",message:`Document graph target ${u.id} revision does not match its reference`,documentIds:[a.sourceId,u.id]});let f=`${a.sourceId}\0${a.referenceId}`;if(i.has(f))throw new tt({code:"DUPLICATE_REFERENCE",message:`Document ${a.sourceId} contains duplicate reference ID ${a.referenceId}`,documentIds:[a.sourceId]});i.add(f)}return Object.freeze({nodes:Object.freeze(n),edges:Object.freeze(s)})},ag=e=>new Map(e.nodes.map(t=>[t.id,t]));var to=({graph:e,rootIds:t})=>{let n=ag(e),r=fn(e.edges),o=new Map,s=[],i=[],a=c=>{let u=n.get(c);if(u===void 0)throw new tt({code:"ROOT_NOT_FOUND",message:`Document graph root ${c} does not exist`,documentIds:[c]});let f=o.get(c);if(f!=="visited"){if(f==="visiting"){let l=s.indexOf(c),p=[...s.slice(l),c];throw new tt({code:"CYCLE",message:`Document graph contains a cycle: ${p.join(" -> ")}`,documentIds:p})}o.set(c,"visiting"),s.push(c);for(let l of r.get(c)??[])a(l.reference.documentId);s.pop(),o.set(c,"visited"),i.push(u)}};for(let c of[...new Set(t)].sort(et))a(c);return Object.freeze(i)};var cg=D().regex(/^sha256:[a-f0-9]{64}$/),If=L({format:W("webstudio-document-graph"),version:W(1),nodes:H(Xr),edges:H(eo),integrity:L({algorithm:W("sha256"),checksum:cg})});var ug=D().min(1).refine(e=>e.startsWith("/")===!1,{error:"Asset path must be relative"}).refine(e=>e.includes("\\")===!1&&e.split("/").every(t=>t.length>0&&t!==".."&&t!=="."),{error:"Asset path must be normalized and must not contain dot segments"}),Nf=L({_id:D().min(1),_type:W("asset.file"),name:D().min(1),description:D().optional(),path:ug,key:D(),folderId:D().min(1).optional(),extension:D().regex(/^[a-z0-9]*$/),mimeType:D().min(1),size:U().int().nonnegative(),createdAt:D().datetime().optional(),revision:D().min(1),contentRef:D().min(1),properties:Ne(D(),At()),excerpt:D().optional(),metadataError:L({code:D().min(1),message:D().min(1),reason:D().min(1).optional(),line:U().int().positive().optional(),column:U().int().positive().optional()}).optional()}),ii=Nf.partial().required({_id:!0}),lg=fe(["null","boolean","number","string","object","array"]),fg=Et({format:W("webstudio-builder-asset-field-catalog"),version:W(1),canonicalRevision:D().regex(/^sha256:[a-f0-9]{64}$/),documentCount:U().int().nonnegative(),fields:Ne(D().min(1),Et({queryPath:H(D().min(1)).min(1).max(N.fieldPathDepth).optional(),types:H(lg).min(1),occurrences:U().int().positive(),optional:W(!0).optional(),mixed:W(!0).optional()}))}).superRefine((e,t)=>{for(let[n,r]of Object.entries(e.fields)){let o=[...new Set(r.types)].sort();JSON.stringify(r.types)!==JSON.stringify(o)&&t.addIssue({code:"custom",path:["fields",n,"types"],message:"Observed field types must be unique and sorted"}),r.occurrences>e.documentCount&&t.addIssue({code:"custom",path:["fields",n,"occurrences"],message:"Field occurrences cannot exceed the document count"});let s=r.occurrences<e.documentCount;r.optional===!0!==s&&t.addIssue({code:"custom",path:["fields",n,"optional"],message:"Field optionality must match its occurrence count"});let i=o.length>1;r.mixed===!0!==i&&t.addIssue({code:"custom",path:["fields",n,"mixed"],message:"Mixed status must match the observed types"})}}),no=D().regex(/^sha256:[a-f0-9]{64}$/),zf=L({fields:H(H(D().min(1)).min(1).max(N.fieldPathDepth)).min(1).max(N.outputFieldCount+1),rows:H(H(At())).max(N.resultCount),totalCount:U().int().nonnegative().max(N.candidateDocuments),hasMore:pt()}).superRefine(({fields:e,rows:t},n)=>{for(let[r,o]of t.entries())o.length!==e.length&&n.addIssue({code:"custom",path:["rows",r],message:"Materialized query rows must match the field count"})}),Cf=L({format:W("webstudio-content-database"),version:W(1),assetRevision:no,documents:H(ii),documentGraph:If.optional(),contents:Ne(D().min(1),D()).optional(),assetPaths:Ne(D().min(1),D().min(1)).optional(),assetReferences:Ne(D().min(1),H(L({start:U().int().nonnegative(),end:U().int().positive(),assetId:D().min(1),suffix:D().min(1).optional()}).refine(({start:e,end:t})=>t>e,{message:"Markdown asset reference range must not be empty"}))).optional(),assetValueReferences:Ne(D().min(1),H(L({path:H(D().min(1).or(U().int().nonnegative())).min(1),assetId:D().min(1),suffix:D().min(1).optional(),structured:W(!0).optional()}))).optional(),fieldCatalog:fg,queries:Ne(no,zf).optional(),database:L({maxBytes:U().int().positive(),unboundedBytes:U().int().nonnegative(),sourceDocumentCount:U().int().nonnegative(),includedDocumentCount:U().int().nonnegative().optional()}).optional(),integrity:L({algorithm:W("sha256"),checksum:no})}).superRefine((e,t)=>{e.documents.length>N.candidateDocuments&&t.addIssue({code:"custom",path:["documents"],message:"Asset index exceeds the document limit"}),(e.fieldCatalog.canonicalRevision!==e.assetRevision||e.fieldCatalog.documentCount!==e.documents.length)&&t.addIssue({code:"custom",path:["fieldCatalog"],message:"Asset index field catalog does not match its documents"}),e.database!==void 0&&e.database.sourceDocumentCount<e.documents.length&&t.addIssue({code:"custom",path:["database","sourceDocumentCount"],message:"Source document count cannot be smaller than the database"}),e.database?.includedDocumentCount!==void 0&&(e.database.includedDocumentCount<e.documents.length||e.database.includedDocumentCount>e.database.sourceDocumentCount)&&t.addIssue({code:"custom",path:["database","includedDocumentCount"],message:"Included document count must match the database bounds"});let n;for(let[o,s]of e.documents.entries())n!==void 0&&s._id<=n&&t.addIssue({code:"custom",path:["documents",o,"_id"],message:"Asset index documents must have unique sorted IDs"}),n=s._id;let r=new Set(e.documents.flatMap(({contentRef:o})=>o===void 0?[]:[o]));for(let o of e.documentGraph?.nodes??[])r.add(o.contentRef);for(let o of Object.keys(e.contents??{}))r.has(o)===!1&&t.addIssue({code:"custom",path:["contents",o],message:"Embedded content must belong to an indexed document"});for(let o of Object.keys(e.assetReferences??{}))r.has(o)===!1&&t.addIssue({code:"custom",path:["assetReferences",o],message:"Asset references must belong to an indexed document"})}),dg=cn("mode",[L({mode:W("none")}),L({mode:W("full"),maxBytes:U().int().positive().max(N.hydratedFileBytes).optional()}),L({mode:W("range"),offset:U().int().nonnegative(),length:U().int().positive().max(N.hydratedRangeBytes)}),L({mode:W("markdown-body-ref"),maxBytes:U().int().positive().max(N.hydratedFileBytes).optional()})]),ai={id:["string"],url:["string"],width:["number"],height:["number"],name:["string"],description:["string"],path:["string"],key:["string"],folderId:["string"],extension:["string"],mimeType:["string"],size:["number"],createdAt:["string"],revision:["string"],excerpt:["string"]},$f=Object.keys(ai),Lf=["url","width","height"],ro=e=>Lf.includes(e),Pf=$f.filter(e=>ro(e)===!1&&e!=="excerpt"),Ff=Pf.filter(e=>e!=="id"),Mf=e=>Pf.includes(e),pg=fe($f),Xn=H(D().min(1)).min(1).max(N.fieldPathDepth).superRefine((e,t)=>{if(e[0]==="properties"){e.length<2&&t.addIssue({code:"custom",message:"A properties field path must select a property"});return}(e.length!==1||pg.safeParse(e[0]).success===!1)&&t.addIssue({code:"custom",message:"Asset query field path is unsupported"})}),si=pt().default(!0),mg=cn("mode",[L({mode:W("all"),includeMetadata:si}),L({mode:W("base"),includeMetadata:si}),L({mode:W("fields"),includeMetadata:si,fields:H(Xn).max(N.outputFieldCount).refine(e=>new Set(e.map(_f)).size===e.length,{error:"Selected output fields must be unique"})})]),hg={mode:"fields",includeMetadata:!1,fields:Lf.map(e=>[e])},Bf=["eq","ne","contains","startsWith","endsWith","gt","gte","lt","lte"],hS=[...Bf,"in","exists","isEmpty"],gg=L({field:Xn,operator:fe(Bf),value:At()}),yg=L({field:Xn,operator:W("in"),value:H(At()).max(N.resultCount)}),bg=L({field:Xn,operator:fe(["exists","isEmpty"]),value:pt()}),wg=cn("operator",[gg,yg,bg]),xg=Sf(wg,{maximumChildren:N.filterCount,maximumConditions:N.filterCount,maximumDepth:N.filterDepth,maximumConditionsMessage:"Asset query exceeds the filter limit",maximumDepthMessage:"Asset query exceeds the filter nesting limit"});var _g=xg,qf=e=>{let t=new Set(["eq","ne","in","exists"]);return e.some(n=>n==="string"||n==="array")&&t.add("contains"),e.includes("string")&&(t.add("startsWith"),t.add("endsWith")),e.some(n=>n==="string"||n==="number")&&(t.add("gt"),t.add("gte"),t.add("lt"),t.add("lte")),e.some(n=>n==="string"||n==="array"||n==="object")&&t.add("isEmpty"),[...t]},Sg=L({field:Xn,direction:fe(["asc","desc"])}),Eg=fe(["many","one","first","last"]),Ag=({output:e,content:t})=>e.includeMetadata||e.mode==="all"||e.mode==="fields"&&e.fields.length>0||t.mode!=="none",Rt=L({result:Eg.default("many"),where:_g.default({all:[]}),sort:H(Sg).max(N.sortCount).default([]),limit:U().int().nonnegative().max(N.resultCount).default(N.defaultResultCount),offset:U().int().nonnegative().max(N.candidateDocuments).default(0),output:mg.default(hg),content:dg.default({mode:"none"})}).superRefine((e,t)=>{Ag(e)===!1&&t.addIssue({code:"custom",message:"Select at least one asset query output"}),(e.result==="first"||e.result==="last")&&e.sort.length===0&&t.addIssue({code:"custom",path:["sort"],message:"Add sorting to define which item is first."})}),Zf=L({query:Rt,indexRevision:D().min(1).max(255).optional()}),kg=Et({_id:D().min(1),revision:D().min(1),contentRef:D().min(1),encoding:W("utf-8"),text:D(),range:Et({offset:U().int().nonnegative(),length:U().int().nonnegative(),total:U().int().nonnegative()}).optional()}),vg=kg.omit({_id:!0,revision:!0,contentRef:!0}),Uf=Nf.omit({_id:!0,_type:!0,contentRef:!0}).partial().extend({id:D().min(1),url:D().min(1).optional(),width:U().positive().optional(),height:U().positive().optional(),content:vg.optional()}).refine(e=>e.width===void 0==(e.height===void 0),{error:"Asset dimensions must include both width and height"}),Rg=L({format:W("webstudio-content-database"),version:W(1),revision:no,usedBytes:U().int().nonnegative(),maxBytes:U().int().positive(),unboundedBytes:U().int().nonnegative(),includedDocumentCount:U().int().nonnegative(),omittedDocumentCount:U().int().nonnegative(),omissionReason:fe(["size","unavailable"]).optional(),truncated:pt()}),Tf=Rg.pick({usedBytes:!0,maxBytes:!0,unboundedBytes:!0,includedDocumentCount:!0,omittedDocumentCount:!0,omissionReason:!0,truncated:!0}),ci=L({items:H(Uf),totalCount:U().int().nonnegative(),hasMore:pt()}),Dg=L({item:Uf.nullable(),totalCount:U().int().nonnegative()}),jf=an([ci,Dg]),Of=L({line:U().int().positive(),column:U().int().positive(),offset:U().int().nonnegative().optional()}),Ig=L({severity:fe(["error","warning"]),scope:fe(["query","database"]),phase:fe(["metadata","reference","source"]),code:D().min(1),message:D().min(1),assetId:D().min(1),path:D().min(1),line:U().int().positive().optional(),column:U().int().positive().optional(),reference:D().min(1).optional(),nodeType:D().min(1).optional(),reason:D().min(1).optional(),sourceRange:L({start:Of,end:Of}).optional()}),Cg=L({severity:fe(["error","warning"]),code:D().min(1),path:H(D()),message:D().min(1)}),Tg=L({scope:W("query-preview"),queryIssues:H(Cg).optional(),queryWarnings:H(D().min(1)).optional(),query:Tf,database:Tf,artifacts:L({query:Cf,database:Cf}).optional(),unresolved:jf.optional(),issues:H(Ig).optional(),issueCount:U().int().nonnegative().optional(),issuesTruncated:pt().optional()}),gS=L({data:jf,__diagnostics__:Tg}),Og=fe(["INVALID_REQUEST","REQUEST_CANCELLED","UNAUTHORIZED","FORBIDDEN","STALE_INDEX","CONTENT_IDENTITY_REQUIRED","CONTENT_NOT_TEXT","CONTENT_DECODING_FAILED","CONTENT_LIMIT_EXCEEDED","MULTIPLE_RESULTS","INTERNAL_ERROR"]),Ng=Et({ok:W(!1),error:Et({code:Og,message:D().min(1),retryable:pt(),details:Ne(D(),At()).optional()}),meta:Et({queryHash:D().min(1).optional(),indexRevision:D().min(1).optional(),assetRevision:D().min(1).optional()}).optional()}),Vf=({code:e,message:t,retryable:n=!1,details:r})=>Ng.parse({ok:!1,error:{code:e,message:t,retryable:n,details:r}});var Qf=function*(e){if(e.length>0&&!e.startsWith("/")||/~(?![01])/.test(e))throw Error("Invalid JSON Pointer");let t=1,n=0;for(;n<e.length;){let r=e.indexOf("/",t);n=r===-1?e.length:r;let o=e.slice(t,n);t=n+1,yield $g(o)}};var ui=(e,t)=>t+"/"+zg(e),zg=e=>e.toString().replace(/~/g,"~0").replace(/\//g,"~1"),$g=e=>e.toString().replace(/~1/g,"/").replace(/~0/g,"~");var oo=async(e,t,n)=>{if(Number.isSafeInteger(t)===!1||t<=0)throw new Error("Concurrency must be a positive safe integer");let r=0,o=new Array(e.length),s=async()=>{for(;r<e.length;){let u=r;r+=1,o[u]=await n(e[u])}},i=Array.from({length:Math.min(t,e.length)},s),c=(await Promise.allSettled(i)).find(u=>u.status==="rejected");if(c!==void 0)throw c.reason;return o},li=e=>e.reason??new DOMException("The operation was aborted","AbortError"),Gf=e=>{if(e?.aborted)throw li(e)},dn=async(e,t)=>t===void 0?await e:await new Promise((n,r)=>{let o=()=>t.removeEventListener("abort",s),s=()=>{o(),r(li(t))};t.addEventListener("abort",s,{once:!0}),Promise.resolve(e).then(i=>{o(),n(i)},i=>{o(),r(i)}),t.aborted&&s()}),so=({concurrency:e,signal:t})=>{if(Number.isSafeInteger(e)===!1||e<=0)throw new TypeError("Concurrency must be a positive safe integer");let n=0,r=[],o=async()=>{if(Gf(t),n<e){n+=1;return}await new Promise((i,a)=>{let c,u=()=>{let f=r.indexOf(c);f!==-1&&r.splice(f,1),t!==void 0&&a(li(t))};c={start:()=>{t?.removeEventListener("abort",u),i()}},r.push(c),t?.addEventListener("abort",u,{once:!0})})},s=()=>{let i=r.shift();if(i===void 0){n-=1;return}i.start()};return async i=>{await o();try{return Gf(t),await i()}finally{s()}}};var pn=e=>typeof e=="object"&&e!==null&&Array.isArray(e)===!1,io=e=>{if(pn(e)===!1)return;let t=Object.keys(e);if(!(t.length!==1||t[0]!=="$ref"))return e.$ref};var De=class extends Error{code;referenceId;constructor({code:t,message:n,referenceId:r,cause:o}){super(n,{cause:o}),this.name="JsonDocumentError",this.code=t,this.referenceId=r}},Lg=(e,t)=>{let n=io(e);if(n!==void 0){if(typeof n!="string")throw new De({code:"INVALID_REFERENCE_MARKER",message:`JSON reference marker ${t} must contain a string $ref`,referenceId:t});return n}},Pg=e=>`#${e}`;var Jf=async({source:e,maximumBytes:t=N.hydratedFileBytes})=>{let n;try{n=await Xe(e,t)}catch(o){throw o instanceof we?new De({code:"CONTENT_LIMIT_EXCEEDED",message:"JSON document exceeds the byte limit",cause:o}):o}let r;try{r=ln(ve(n))}catch(o){throw new De({code:"CONTENT_DECODING_FAILED",message:"JSON document is not valid UTF-8",cause:o})}try{return vt(JSON.parse(r))}catch(o){throw new De({code:"INVALID_DOCUMENT",message:"JSON document is invalid",cause:o})}};var Fg=(e,t)=>{let n=e;for(let r of t){if(Array.isArray(n)){let o=Number(r);if(Number.isSafeInteger(o)===!1||o<0||String(o)!==r||o>=n.length)return;n=n[o];continue}if(pn(n)&&Object.hasOwn(n,r)){n=n[r];continue}return}return n},Wf=({document:e,representation:t})=>{let n=vt(e);if(t.type==="document")return n;if(t.type!=="json")throw new De({code:"UNSUPPORTED_REPRESENTATION",message:`JSON documents do not support ${t.type}`});let r=Fg(n,t.path);if(r===void 0)throw new De({code:"JSON_PATH_NOT_FOUND",message:"JSON document path does not exist"});return r},Mg=(e,t,n)=>{Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})},ao=({document:e,references:t,allowUnresolvedReferences:n=!1})=>{let r=vt(e),o=new Set,s=(a,c)=>{let u=Pg(c);if(Lg(a,u)!==void 0){if(t.has(u)===!1){if(n)return a;throw new De({code:"REFERENCE_NOT_FOUND",message:`Resolved JSON reference ${u} is unavailable`,referenceId:u})}o.add(u);try{return vt(t.get(u))}catch(l){throw new De({code:"INVALID_RESOLVED_VALUE",message:`Resolved JSON reference ${u} is not JSON-compatible`,referenceId:u,cause:l})}}if(Array.isArray(a))return a.map((l,p)=>s(l,ui(String(p),c)));if(pn(a)){let l={};for(let[p,d]of Object.entries(a))Mg(l,p,s(d,ui(p,c)));return l}return a},i=s(r,"");for(let a of[...t.keys()].sort())if(o.has(a)===!1)throw new De({code:"UNUSED_REFERENCE",message:`Resolved JSON reference ${a} has no marker`,referenceId:a});return i};var co=Symbol.for("yaml.alias"),uo=Symbol.for("yaml.document"),Ue=Symbol.for("yaml.map"),fi=Symbol.for("yaml.pair"),Ie=Symbol.for("yaml.scalar"),mt=Symbol.for("yaml.seq"),xe=Symbol.for("yaml.node.type"),ze=e=>!!e&&typeof e=="object"&&e[xe]===co,nt=e=>!!e&&typeof e=="object"&&e[xe]===uo,$e=e=>!!e&&typeof e=="object"&&e[xe]===Ue,j=e=>!!e&&typeof e=="object"&&e[xe]===fi,B=e=>!!e&&typeof e=="object"&&e[xe]===Ie,Le=e=>!!e&&typeof e=="object"&&e[xe]===mt;function K(e){if(e&&typeof e=="object")switch(e[xe]){case Ue:case mt:return!0}return!1}function V(e){if(e&&typeof e=="object")switch(e[xe]){case co:case Ue:case Ie:case mt:return!0}return!1}var lo=e=>(B(e)||K(e))&&!!e.anchor;var Ae=Symbol("break visit"),Kf=Symbol("skip children"),rt=Symbol("remove node");function ot(e,t){let n=Hf(t);nt(e)?mn(null,e.contents,n,Object.freeze([e]))===rt&&(e.contents=null):mn(null,e,n,Object.freeze([]))}ot.BREAK=Ae;ot.SKIP=Kf;ot.REMOVE=rt;function mn(e,t,n,r){let o=Yf(e,t,n,r);if(V(o)||j(o))return Xf(e,r,o),mn(e,o,n,r);if(typeof o!="symbol"){if(K(t)){r=Object.freeze(r.concat(t));for(let s=0;s<t.items.length;++s){let i=mn(s,t.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===Ae)return Ae;i===rt&&(t.items.splice(s,1),s-=1)}}}else if(j(t)){r=Object.freeze(r.concat(t));let s=mn("key",t.key,n,r);if(s===Ae)return Ae;s===rt&&(t.key=null);let i=mn("value",t.value,n,r);if(i===Ae)return Ae;i===rt&&(t.value=null)}}return o}async function fo(e,t){let n=Hf(t);nt(e)?await hn(null,e.contents,n,Object.freeze([e]))===rt&&(e.contents=null):await hn(null,e,n,Object.freeze([]))}fo.BREAK=Ae;fo.SKIP=Kf;fo.REMOVE=rt;async function hn(e,t,n,r){let o=await Yf(e,t,n,r);if(V(o)||j(o))return Xf(e,r,o),hn(e,o,n,r);if(typeof o!="symbol"){if(K(t)){r=Object.freeze(r.concat(t));for(let s=0;s<t.items.length;++s){let i=await hn(s,t.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===Ae)return Ae;i===rt&&(t.items.splice(s,1),s-=1)}}}else if(j(t)){r=Object.freeze(r.concat(t));let s=await hn("key",t.key,n,r);if(s===Ae)return Ae;s===rt&&(t.key=null);let i=await hn("value",t.value,n,r);if(i===Ae)return Ae;i===rt&&(t.value=null)}}return o}function Hf(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Yf(e,t,n,r){if(typeof n=="function")return n(e,t,r);if($e(t))return n.Map?.(e,t,r);if(Le(t))return n.Seq?.(e,t,r);if(j(t))return n.Pair?.(e,t,r);if(B(t))return n.Scalar?.(e,t,r);if(ze(t))return n.Alias?.(e,t,r)}function Xf(e,t,n){let r=t[t.length-1];if(K(r))r.items[e]=n;else if(j(r))e==="key"?r.key=n:r.value=n;else if(nt(r))r.contents=n;else{let o=ze(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}var Bg={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},qg=e=>e.replace(/[!,[\]{}]/g,t=>Bg[t]),st=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),o=r.shift();switch(o){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[s,i]=r;return this.tags[s]=i,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=r;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let i=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,i),!1}}default:return n(0,`Unknown directive ${o}`,!0),!1}}tagName(t,n){if(t==="!")return"!";if(t[0]!=="!")return n(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let i=t.slice(2,-1);return i==="!"||i==="!!"?(n(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&n("Verbatim tags must end with a >"),i)}let[,r,o]=t.match(/^(.*!)([^!]*)$/s);o||n(`The ${t} tag has no suffix`);let s=this.tags[r];if(s)try{return s+decodeURIComponent(o)}catch(i){return n(String(i)),null}return r==="!"?t:(n(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[n,r]of Object.entries(this.tags))if(t.startsWith(r))return n+qg(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),o;if(t&&r.length>0&&V(t.contents)){let s={};ot(t.contents,(i,a)=>{V(a)&&a.tag&&(s[a.tag]=!0)}),o=Object.keys(s)}else o=[];for(let[s,i]of r)s==="!!"&&i==="tag:yaml.org,2002:"||(!t||o.some(a=>a.startsWith(i)))&&n.push(`%TAG ${s} ${i}`);return n.join(`
+Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){s(i);continue}if(e.external){let u=e.external.registry.get(i[0])?.id;if(t!==i[0]&&u){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&e.reused==="ref"){s(i);continue}}}function Ks(e,t){let n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=a=>{let c=e.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,f={...u},l=c.ref;if(c.ref=null,l){r(l);let d=e.seen.get(l),w=d.schema;if(w.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(w)):Object.assign(u,w),Object.assign(u,f),a._zod.parent===l)for(let y in u)y==="$ref"||y==="allOf"||y in f||delete u[y];if(w.$ref&&d.def)for(let y in u)y==="$ref"||y==="allOf"||y in d.def&&JSON.stringify(u[y])===JSON.stringify(d.def[y])&&delete u[y]}let p=a._zod.parent;if(p&&p!==l){r(p);let d=e.seen.get(p);if(d?.schema.$ref&&(u.$ref=d.schema.$ref,d.def))for(let w in u)w==="$ref"||w==="allOf"||w in d.def&&JSON.stringify(u[w])===JSON.stringify(d.def[w])&&delete u[w]}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...e.seen.entries()].reverse())r(a[0]);let o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Object.assign(o,n.def??n.schema);let s=e.metadataRegistry.get(t)?.id;s!==void 0&&o.id===s&&delete o.id;let i=e.external?.defs??{};for(let a of e.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Gn(t,"input",e.processors),output:Gn(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function be(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return be(r.element,n);if(r.type==="set")return be(r.valueType,n);if(r.type==="lazy")return be(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return be(r.innerType,n);if(r.type==="intersection")return be(r.left,n)||be(r.right,n);if(r.type==="record"||r.type==="map")return be(r.keyType,n)||be(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:be(r.in,n)||be(r.out,n);if(r.type==="object"){for(let o in r.shape)if(be(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(be(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(be(o,n))return!0;return!!(r.rest&&be(r.rest,n))}return!1}var gl=(e,t={})=>n=>{let r=Js({...n,processors:t});return re(e,r),Ws(r,e),Ks(r,e)},Gn=(e,t,n={})=>r=>{let{libraryOptions:o,target:s}=r??{},i=Js({...o??{},target:s,io:t,processors:n});return re(e,i),Ws(i,e),Ks(i,e)};var Wm={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},yl=(e,t,n,r)=>{let o=n;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=Wm[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),u&&(o.contentEncoding=u),c&&c.size>0){let f=[...c];f.length===1?o.pattern=f[0].source:f.length>1&&(o.allOf=[...f.map(l=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:l.source}))])}},bl=(e,t,n,r)=>{let o=n,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:f}=e._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";let l=typeof f=="number"&&f>=(s??Number.NEGATIVE_INFINITY),p=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),d=t.target==="draft-04"||t.target==="openapi-3.0";l?d?(o.minimum=f,o.exclusiveMinimum=!0):o.exclusiveMinimum=f:typeof s=="number"&&(o.minimum=s),p?d?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof c=="number"&&(o.multipleOf=c)},wl=(e,t,n,r)=>{n.type="boolean"};var xl=(e,t,n,r)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"};var _l=(e,t,n,r)=>{n.not={}};var Sl=(e,t,n,r)=>{};var El=(e,t,n,r)=>{let o=e._zod.def,s=Fn(o.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},Al=(e,t,n,r)=>{let o=e._zod.def,s=[];for(let i of o.values)if(i===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){let i=s[0];n.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[i]:n.const=i}else s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),s.every(i=>typeof i=="boolean")&&(n.type="boolean"),s.every(i=>i===null)&&(n.type="null"),n.enum=s};var kl=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var vl=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var Rl=(e,t,n,r)=>{let o=n,s=e._zod.def,{minimum:i,maximum:a}=e._zod.bag;typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=re(s.element,t,{...r,path:[...r.path,"items"]})},Dl=(e,t,n,r)=>{let o=n,s=e._zod.def;o.type="object",o.properties={};let i=s.shape;for(let u in i)o.properties[u]=re(i[u],t,{...r,path:[...r.path,"properties",u]});let a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{let f=s.shape[u]._zod;return t.io==="input"?f.optin===void 0:f.optout===void 0}));c.size>0&&(o.required=Array.from(c)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=re(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},Il=(e,t,n,r)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>re(a,t,{...r,path:[...r.path,s?"oneOf":"anyOf",c]}));s?n.oneOf=i:n.anyOf=i},Cl=(e,t,n,r)=>{let o=e._zod.def,s=re(o.left,t,{...r,path:[...r.path,"allOf",0]}),i=re(o.right,t,{...r,path:[...r.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];n.allOf=c};var Tl=(e,t,n,r)=>{let o=n,s=e._zod.def;o.type="object";let i=s.keyType,c=i._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let f=re(s.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let l of c)o.patternProperties[l.source]=f}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=re(s.keyType,t,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=re(s.valueType,t,{...r,path:[...r.path,"additionalProperties"]});let u=i._zod.values;if(u){let f=[...u].filter(l=>typeof l=="string"||typeof l=="number");f.length>0&&(o.required=f)}},Ol=(e,t,n,r)=>{let o=e._zod.def,s=re(o.innerType,t,r),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=o.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},Nl=(e,t,n,r)=>{let o=e._zod.def;re(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType},zl=(e,t,n,r)=>{let o=e._zod.def;re(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},$l=(e,t,n,r)=>{let o=e._zod.def;re(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},Ll=(e,t,n,r)=>{let o=e._zod.def;re(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i},Pl=(e,t,n,r)=>{let o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?o.out:o.in:o.out;re(i,t,r);let a=t.seen.get(e);a.ref=i},Fl=(e,t,n,r)=>{let o=e._zod.def;re(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType,n.readOnly=!0};var Hs=(e,t,n,r)=>{let o=e._zod.def;re(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType},Ml=(e,t,n,r)=>{let o=e._zod.innerType;re(o,t,r);let s=t.seen.get(e);s.ref=o};var nh=k("ZodISODateTime",(e,t)=>{Kc.init(e,t),te.init(e,t)});function Bl(e){return rl(nh,e)}var rh=k("ZodISODate",(e,t)=>{Hc.init(e,t),te.init(e,t)});function ql(e){return ol(rh,e)}var oh=k("ZodISOTime",(e,t)=>{Yc.init(e,t),te.init(e,t)});function Zl(e){return sl(oh,e)}var sh=k("ZodISODuration",(e,t)=>{Xc.init(e,t),te.init(e,t)});function Ul(e){return il(sh,e)}var jl=(e,t)=>{$r.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Ta(e,n)},flatten:{value:n=>Ca(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,nn,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,nn,2)}},isEmpty:{get(){return e.issues.length===0}}})},Vl=k("ZodError",jl),ke=k("ZodError",jl,{Parent:Error});var Ql=Lr(ke),Gl=Pr(ke),Jl=Zn(ke),Wl=Un(ke),Kl=za(ke),Hl=$a(ke),Yl=La(ke),Xl=Pa(ke),ef=Fa(ke),tf=Ma(ke),nf=Ba(ke),rf=qa(ke);var of=new WeakMap;function Jn(e,t,n){let r=Object.getPrototypeOf(e),o=of.get(r);if(o||(o=new Set,of.set(r,o)),!o.has(t)){o.add(t);for(let s in n){let i=n[s];Object.defineProperty(r,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var ee=k("ZodType",(e,t)=>(Y.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Gn(e,"input"),output:Gn(e,"output")}}),e.toJSONSchema=gl(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>Ql(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>Jl(e,n,r),e.parseAsync=async(n,r)=>Gl(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Wl(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>Kl(e,n,r),e.decode=(n,r)=>Hl(e,n,r),e.encodeAsync=async(n,r)=>Yl(e,n,r),e.decodeAsync=async(n,r)=>Xl(e,n,r),e.safeEncode=(n,r)=>ef(e,n,r),e.safeDecode=(n,r)=>tf(e,n,r),e.safeEncodeAsync=async(n,r)=>nf(e,n,r),e.safeDecodeAsync=async(n,r)=>rf(e,n,r),Jn(e,"ZodType",{check(...n){let r=this.def;return this.clone(J.mergeDefs(r,{checks:[...r.checks??[],...n.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return Ze(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(tg(n,r))},superRefine(n,r){return this.check(ng(n,r))},overwrite(n){return this.check(St(n))},optional(){return lf(this)},exactOptional(){return qh(this)},nullable(){return ff(this)},nullish(){return lf(ff(this))},nonoptional(n){return Gh(this,n)},array(){return H(this)},or(n){return an([this,n])},and(n){return Lh(this,n)},transform(n){return df(this,Mh(n))},default(n){return jh(this,n)},prefault(n){return Qh(this,n)},catch(n){return Wh(this,n)},pipe(n){return df(this,n)},readonly(){return Yh(this)},describe(n){let r=this.clone();return jt.add(r,{description:n}),r},meta(...n){if(n.length===0)return jt.get(this);let r=this.clone();return jt.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return jt.get(e)?.description},configurable:!0}),e)),pf=k("_ZodString",(e,t)=>{Zr.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,s)=>yl(e,r,o,s);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Jn(e,"_ZodString",{regex(...r){return this.check(Ps(...r))},includes(...r){return this.check(Bs(...r))},startsWith(...r){return this.check(qs(...r))},endsWith(...r){return this.check(Zs(...r))},min(...r){return this.check(sn(...r))},max(...r){return this.check(Qr(...r))},length(...r){return this.check(Gr(...r))},nonempty(...r){return this.check(sn(1,...r))},lowercase(r){return this.check(Fs(r))},uppercase(r){return this.check(Ms(r))},trim(){return this.check(js())},normalize(...r){return this.check(Us(...r))},toLowerCase(){return this.check(Vs())},toUpperCase(){return this.check(Qs())},slugify(){return this.check(Gs())}})}),uh=k("ZodString",(e,t)=>{Zr.init(e,t),pf.init(e,t),e.email=n=>e.check(Lu(lh,n)),e.url=n=>e.check(qu(fh,n)),e.jwt=n=>e.check(nl(vh,n)),e.emoji=n=>e.check(Zu(dh,n)),e.guid=n=>e.check(Ls(sf,n)),e.uuid=n=>e.check(Pu(Wr,n)),e.uuidv4=n=>e.check(Fu(Wr,n)),e.uuidv6=n=>e.check(Mu(Wr,n)),e.uuidv7=n=>e.check(Bu(Wr,n)),e.nanoid=n=>e.check(Uu(ph,n)),e.guid=n=>e.check(Ls(sf,n)),e.cuid=n=>e.check(ju(mh,n)),e.cuid2=n=>e.check(Vu(hh,n)),e.ulid=n=>e.check(Qu(gh,n)),e.base64=n=>e.check(Xu(Eh,n)),e.base64url=n=>e.check(el(Ah,n)),e.xid=n=>e.check(Gu(yh,n)),e.ksuid=n=>e.check(Ju(bh,n)),e.ipv4=n=>e.check(Wu(wh,n)),e.ipv6=n=>e.check(Ku(xh,n)),e.cidrv4=n=>e.check(Hu(_h,n)),e.cidrv6=n=>e.check(Yu(Sh,n)),e.e164=n=>e.check(tl(kh,n)),e.datetime=n=>e.check(Bl(n)),e.date=n=>e.check(ql(n)),e.time=n=>e.check(Zl(n)),e.duration=n=>e.check(Ul(n))});function D(e){return $u(uh,e)}var te=k("ZodStringFormat",(e,t)=>{X.init(e,t),pf.init(e,t)}),lh=k("ZodEmail",(e,t)=>{qc.init(e,t),te.init(e,t)});var sf=k("ZodGUID",(e,t)=>{Mc.init(e,t),te.init(e,t)});var Wr=k("ZodUUID",(e,t)=>{Bc.init(e,t),te.init(e,t)});var fh=k("ZodURL",(e,t)=>{Zc.init(e,t),te.init(e,t)});var dh=k("ZodEmoji",(e,t)=>{Uc.init(e,t),te.init(e,t)});var ph=k("ZodNanoID",(e,t)=>{jc.init(e,t),te.init(e,t)});var mh=k("ZodCUID",(e,t)=>{Vc.init(e,t),te.init(e,t)});var hh=k("ZodCUID2",(e,t)=>{Qc.init(e,t),te.init(e,t)});var gh=k("ZodULID",(e,t)=>{Gc.init(e,t),te.init(e,t)});var yh=k("ZodXID",(e,t)=>{Jc.init(e,t),te.init(e,t)});var bh=k("ZodKSUID",(e,t)=>{Wc.init(e,t),te.init(e,t)});var wh=k("ZodIPv4",(e,t)=>{eu.init(e,t),te.init(e,t)});var xh=k("ZodIPv6",(e,t)=>{tu.init(e,t),te.init(e,t)});var _h=k("ZodCIDRv4",(e,t)=>{nu.init(e,t),te.init(e,t)});var Sh=k("ZodCIDRv6",(e,t)=>{ru.init(e,t),te.init(e,t)});var Eh=k("ZodBase64",(e,t)=>{su.init(e,t),te.init(e,t)});var Ah=k("ZodBase64URL",(e,t)=>{iu.init(e,t),te.init(e,t)});var kh=k("ZodE164",(e,t)=>{au.init(e,t),te.init(e,t)});var vh=k("ZodJWT",(e,t)=>{cu.init(e,t),te.init(e,t)});var mf=k("ZodNumber",(e,t)=>{Os.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,s)=>bl(e,r,o,s),Jn(e,"ZodNumber",{gt(r,o){return this.check(jr(r,o))},gte(r,o){return this.check(Qn(r,o))},min(r,o){return this.check(Qn(r,o))},lt(r,o){return this.check(Ur(r,o))},lte(r,o){return this.check(Vn(r,o))},max(r,o){return this.check(Vn(r,o))},int(r){return this.check(af(r))},safe(r){return this.check(af(r))},positive(r){return this.check(jr(0,r))},nonnegative(r){return this.check(Qn(0,r))},negative(r){return this.check(Ur(0,r))},nonpositive(r){return this.check(Vn(0,r))},multipleOf(r,o){return this.check(Vr(r,o))},step(r,o){return this.check(Vr(r,o))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function U(e){return al(mf,e)}var Rh=k("ZodNumberFormat",(e,t)=>{uu.init(e,t),mf.init(e,t)});function af(e){return cl(Rh,e)}var Dh=k("ZodBoolean",(e,t)=>{lu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>wl(e,n,r,o)});function pt(e){return ul(Dh,e)}var Ih=k("ZodNull",(e,t)=>{fu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>xl(e,n,r,o)});function Ch(e){return ll(Ih,e)}var Th=k("ZodUnknown",(e,t)=>{du.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Sl(e,n,r,o)});function cf(){return fl(Th)}var Oh=k("ZodNever",(e,t)=>{pu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>_l(e,n,r,o)});function hf(e){return dl(Oh,e)}var Nh=k("ZodArray",(e,t)=>{mu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Rl(e,n,r,o),e.element=t.element,Jn(e,"ZodArray",{min(n,r){return this.check(sn(n,r))},nonempty(n){return this.check(sn(1,n))},max(n,r){return this.check(Qr(n,r))},length(n,r){return this.check(Gr(n,r))},unwrap(){return this.element}})});function H(e,t){return pl(Nh,e,t)}var gf=k("ZodObject",(e,t)=>{yu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Dl(e,n,r,o),J.defineLazy(e,"shape",()=>t.shape),Jn(e,"ZodObject",{keyof(){return fe(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:cf()})},loose(){return this.clone({...this._zod.def,catchall:cf()})},strict(){return this.clone({...this._zod.def,catchall:hf()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return J.extend(this,n)},safeExtend(n){return J.safeExtend(this,n)},merge(n){return J.merge(this,n)},pick(n){return J.pick(this,n)},omit(n){return J.omit(this,n)},partial(...n){return J.partial(bf,this,n[0])},required(...n){return J.required(wf,this,n[0])}})});function Et(e,t){let n={type:"object",shape:e??{},...J.normalizeParams(t)};return new gf(n)}function L(e,t){return new gf({type:"object",shape:e,catchall:hf(),...J.normalizeParams(t)})}var yf=k("ZodUnion",(e,t)=>{Ns.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Il(e,n,r,o),e.options=t.options});function an(e,t){return new yf({type:"union",options:e,...J.normalizeParams(t)})}var zh=k("ZodDiscriminatedUnion",(e,t)=>{yf.init(e,t),bu.init(e,t)});function cn(e,t,n){return new zh({type:"union",options:t,discriminator:e,...J.normalizeParams(n)})}var $h=k("ZodIntersection",(e,t)=>{wu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Cl(e,n,r,o)});function Lh(e,t){return new $h({type:"intersection",left:e,right:t})}var uf=k("ZodRecord",(e,t)=>{xu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Tl(e,n,r,o),e.keyType=t.keyType,e.valueType=t.valueType});function Ne(e,t,n){return!t||!t._zod?new uf({type:"record",keyType:D(),valueType:e,...J.normalizeParams(t)}):new uf({type:"record",keyType:e,valueType:t,...J.normalizeParams(n)})}var Ys=k("ZodEnum",(e,t)=>{_u.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,s)=>El(e,r,o,s),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Ys({...t,checks:[],...J.normalizeParams(o),entries:s})},e.exclude=(r,o)=>{let s={...t.entries};for(let i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Ys({...t,checks:[],...J.normalizeParams(o),entries:s})}});function fe(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Ys({type:"enum",entries:n,...J.normalizeParams(t)})}var Ph=k("ZodLiteral",(e,t)=>{Su.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Al(e,n,r,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function W(e,t){return new Ph({type:"literal",values:Array.isArray(e)?e:[e],...J.normalizeParams(t)})}var Fh=k("ZodTransform",(e,t)=>{Eu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>vl(e,n,r,o),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new en(e.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(J.issue(s,n.value,t));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),n.issues.push(J.issue(i))}};let o=t.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});function Mh(e){return new Fh({type:"transform",transform:e})}var bf=k("ZodOptional",(e,t)=>{zs.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Hs(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function lf(e){return new bf({type:"optional",innerType:e})}var Bh=k("ZodExactOptional",(e,t)=>{Au.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Hs(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function qh(e){return new Bh({type:"optional",innerType:e})}var Zh=k("ZodNullable",(e,t)=>{ku.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ol(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function ff(e){return new Zh({type:"nullable",innerType:e})}var Uh=k("ZodDefault",(e,t)=>{vu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>zl(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function jh(e,t){return new Uh({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():J.shallowClone(t)}})}var Vh=k("ZodPrefault",(e,t)=>{Ru.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>$l(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Qh(e,t){return new Vh({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():J.shallowClone(t)}})}var wf=k("ZodNonOptional",(e,t)=>{Du.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Nl(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Gh(e,t){return new wf({type:"nonoptional",innerType:e,...J.normalizeParams(t)})}var Jh=k("ZodCatch",(e,t)=>{Iu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ll(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Wh(e,t){return new Jh({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Kh=k("ZodPipe",(e,t)=>{Cu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Pl(e,n,r,o),e.in=t.in,e.out=t.out});function df(e,t){return new Kh({type:"pipe",in:e,out:t})}var Hh=k("ZodReadonly",(e,t)=>{Tu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Fl(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Yh(e){return new Hh({type:"readonly",innerType:e})}var Xh=k("ZodLazy",(e,t)=>{Ou.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ml(e,n,r,o),e.unwrap=()=>e._zod.def.getter()});function Xs(e){return new Xh({type:"lazy",getter:e})}var eg=k("ZodCustom",(e,t)=>{Nu.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(n,r,o)=>kl(e,n,r,o)});function tg(e,t={}){return ml(eg,e,t)}function ng(e,t){return hl(e,t)}function At(e){let t=Xs(()=>an([D(e),U(),pt(),Ch(),H(t),Ne(D(),t)]));return t}var xf=e=>"field"in e?[e]:("all"in e?e.all:e.any).flatMap(xf),Kr=e=>xf(e);var un=(e,t)=>{if("field"in e)return t(e);let n="all"in e?e.all:e.any,r=!1;if("all"in e){for(let o of n){let s=un(o,t);if(s===!1)return!1;r||=s===void 0}return r?void 0:!0}for(let o of n){let s=un(o,t);if(s===!0)return!0;r||=s===void 0}return r?void 0:!1},_f=e=>JSON.stringify(e),ei=e=>{if("field"in e)return{conditions:1,depth:0};let t="all"in e?e.all:e.any,n=0,r=1;for(let o of t){let s=ei(o);n+=s.conditions,r=Math.max(r,s.depth+1)}return{conditions:n,depth:r}},Sf=(e,t={})=>{let n=o=>{let s=H(o),i=t.maximumChildren===void 0?s:s.max(t.maximumChildren);return an([e,L({all:i}),L({any:i})])},r=Xs(()=>n(r));return t.maximumConditions===void 0&&t.maximumDepth===void 0?r:r.superRefine((o,s)=>{let{conditions:i,depth:a}=ei(o);t.maximumConditions!==void 0&&i>t.maximumConditions&&s.addIssue({code:"custom",message:t.maximumConditionsMessage??"Query exceeds the condition limit"}),t.maximumDepth!==void 0&&a>t.maximumDepth&&s.addIssue({code:"custom",message:t.maximumDepthMessage??"Query exceeds the nesting limit"})})};var N={requestBytes:524288,filterCount:32,filterDepth:8,sortCount:8,outputFieldCount:256,fieldPathDepth:9,defaultResultCount:20,resultCount:1e3,resultBytes:16777216,candidateDocuments:1e3,documentGraphDocuments:2e3,databaseBytes:512e3,frontmatterBytes:65536,frontmatterDepth:8,frontmatterFields:256,frontmatterStringBytes:16384,jsonBytes:1048576,jsonDepth:8,jsonFields:256,jsonStringBytes:16384,indexedPropertiesBytes:65536,excerptBytes:2048,mdxDepth:100,mdxNodes:2e4,mdxProps:4e3,hydratedFileBytes:1048576,hydratedTotalBytes:2097152,hydratedFileCount:20,hydratedRangeBytes:262144,concurrentContentReads:8};function Vt(e,t=new Set){if(typeof e=="number"&&isNaN(e))throw new Error("NaN is not allowed");if(typeof e=="number"&&!isFinite(e))throw new Error("Infinity is not allowed");if(e===null||typeof e!="object")return JSON.stringify(e);if(typeof e.toJSON=="function"){if(t.has(e))throw new Error("Circular reference detected");t.add(e);let r=Vt(e.toJSON(),t);return t.delete(e),r}if(t.has(e))throw new Error("Circular reference detected");t.add(e);let n;if(Array.isArray(e))n=`[${e.map(o=>Vt(o===void 0||typeof o=="symbol"?null:o,t)).join(",")}]`;else{let r=[];for(let o of Object.keys(e).sort())e[o]===void 0||typeof e[o]=="symbol"||r.push(`${Vt(o)}:${Vt(e[o],t)}`);n=`{${r.join(",")}}`}return t.delete(e),n}var rg=new TextEncoder,kt=e=>rg.encode(e),Ye=e=>kt(e).byteLength,we=class extends Error{constructor(){super("Byte stream exceeds the configured limit"),this.name="ByteLimitExceededError"}},og=(e,t)=>{let n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.byteLength;return n},Wn=e=>typeof e=="string"?{async*[Symbol.asyncIterator](){yield kt(e)}}:e instanceof Uint8Array?{async*[Symbol.asyncIterator](){yield e}}:e,Hr=(e,t)=>t===void 0?Wn(e):{async*[Symbol.asyncIterator](){let n=0,r=0;for await(let o of Wn(e)){if(r===t.length)return;if(n+o.byteLength<=t.offset){n+=o.byteLength;continue}let s=Math.max(0,t.offset-n),i=Math.min(o.byteLength-s,t.length-r);i>0&&(yield o.subarray(s,s+i),r+=i),n+=o.byteLength}}},Yr=e=>({async*[Symbol.asyncIterator](){let t=e.getReader(),n=!1;try{for(;;){let r=await t.read();if(r.done){n=!0;return}yield r.value}}finally{n===!1&&t.cancel().catch(()=>{}),t.releaseLock()}}}),ti=async(e,t)=>{let n=[],r=0;for await(let o of Wn(e)){let s=t-r;if(s<=0)break;let i=o.subarray(0,s);if(n.push(i),r+=i.byteLength,r===t)break}return og(n,r)},Xe=async(e,t,n=new we)=>{let r=await ti(e,t+1);if(r.byteLength>t)throw n;return r},ve=e=>new TextDecoder("utf-8",{fatal:!0}).decode(e),ln=e=>e.charCodeAt(0)===65279?e.slice(1):e;var Ef=e=>{for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n>=55296&&n<=56319){let r=e.charCodeAt(t+1);if(t+1>=e.length||r<56320||r>57343)throw new Error("JSON strings cannot contain lone Unicode surrogates");t+=1;continue}if(n>=56320&&n<=57343)throw new Error("JSON strings cannot contain lone Unicode surrogates")}},ni=(e,t)=>{if(e===null||typeof e=="boolean")return e;if(typeof e=="string")return Ef(e),e;if(typeof e=="number"){if(Number.isFinite(e)===!1)throw new Error("JSON cannot contain non-finite numbers");return e}if(Array.isArray(e)){if(Object.getOwnPropertySymbols(e).length>0)throw new Error("JSON arrays cannot contain symbol properties");if(t.has(e))throw new Error("JSON cannot contain circular references");t.add(e);try{let n=[];for(let r=0;r<e.length;r+=1){if(Object.hasOwn(e,r)===!1)throw new Error("JSON arrays cannot be sparse");let o=e[r];if(o===void 0)throw new Error("JSON arrays cannot contain undefined values");n.push(ni(o,t))}if(Object.keys(e).length!==e.length)throw new Error("JSON arrays cannot contain named properties");return n}finally{t.delete(e)}}if(typeof e=="object"){let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new Error("JSON can contain only plain objects");if(Object.getOwnPropertySymbols(e).length>0)throw new Error("JSON objects cannot contain symbol properties");if(t.has(e))throw new Error("JSON cannot contain circular references");t.add(e);let r={};try{for(let[o,s]of Object.entries(e))Ef(o),s!==void 0&&Object.defineProperty(r,o,{value:ni(s,t),enumerable:!0,configurable:!0,writable:!0})}finally{t.delete(e)}return r}throw new Error("Value cannot be represented as JSON")},vt=e=>ni(e,new Set),Re=e=>{let t=Vt(vt(e));if(t===void 0)throw new Error("Value cannot be represented as canonical JSON");return t},Kn=(e,t)=>e===void 0||t===void 0?e===t:Re(e)===Re(t),et=(e,t)=>e<t?-1:e>t?1:0,ri=async e=>{let t=typeof e=="string"?kt(e):e,n=await globalThis.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")},Af=async e=>`sha256:${await ri(e)}`;var kf=cn("type",[L({type:W("document")}),L({type:W("json"),path:H(D()).min(1)}),L({type:W("markdown-body")}),L({type:W("markdown-frontmatter")})]),oi=L({documentId:D().min(1),revision:D().min(1),representation:kf}),sg=e=>{let t=kf.parse(e);return t.type==="json"?Object.freeze({...t,path:Object.freeze([...t.path])}):Object.freeze(t)},vf=e=>{let t=oi.parse(e);return Object.freeze({...t,representation:sg(t.representation)})};var Hn=["json","markdown","mdx"],Rf=e=>typeof e=="string"&&Hn.includes(e),Df=e=>{let t=e.split(";",1)[0].trim().toLowerCase();if(t==="application/json")return"json";if(t==="text/markdown")return"markdown";if(t==="text/mdx")return"mdx"};var Xr=L({id:D().min(1),revision:D().min(1),contentRef:D().min(1),format:fe(Hn).optional()}),eo=L({sourceId:D().min(1),referenceId:D().min(1),reference:oi});var fn=e=>{let t=new Map;for(let n of e){let r=t.get(n.sourceId)??[];r.push(n),t.set(n.sourceId,r)}return t};var tt=class extends Error{code;documentIds;constructor({code:t,message:n,documentIds:r=[]}){super(n),this.name="DocumentGraphError",this.code=t,this.documentIds=Object.freeze([...r])}},ig=(e,t)=>et(e.sourceId,t.sourceId)||et(e.referenceId,t.referenceId),Yn=({nodes:e,edges:t})=>{let n=e.map(a=>Object.freeze(Xr.parse(a))).sort((a,c)=>et(a.id,c.id)),r=new Map,o=new Map;for(let a of n){if(r.has(a.id))throw new tt({code:"DUPLICATE_NODE",message:`Document graph contains duplicate node ${a.id}`,documentIds:[a.id]});r.set(a.id,a);let c=o.get(a.contentRef);if(c!==void 0&&(c.revision!==a.revision||c.format!==a.format))throw new tt({code:"CONTENT_IDENTITY_CONFLICT",message:`Document graph content reference ${a.contentRef} has conflicting identities`,documentIds:[c.id,a.id]});o.set(a.contentRef,a)}let s=t.map(a=>{let c=eo.parse(a);return Object.freeze({...c,reference:vf(c.reference)})}).sort(ig),i=new Set;for(let a of s){if(r.get(a.sourceId)===void 0)throw new tt({code:"SOURCE_NOT_FOUND",message:`Document graph source ${a.sourceId} does not exist`,documentIds:[a.sourceId]});let u=r.get(a.reference.documentId);if(u===void 0)throw new tt({code:"TARGET_NOT_FOUND",message:`Document graph target ${a.reference.documentId} does not exist`,documentIds:[a.sourceId,a.reference.documentId]});if(u.revision!==a.reference.revision)throw new tt({code:"TARGET_REVISION_MISMATCH",message:`Document graph target ${u.id} revision does not match its reference`,documentIds:[a.sourceId,u.id]});let f=`${a.sourceId}\0${a.referenceId}`;if(i.has(f))throw new tt({code:"DUPLICATE_REFERENCE",message:`Document ${a.sourceId} contains duplicate reference ID ${a.referenceId}`,documentIds:[a.sourceId]});i.add(f)}return Object.freeze({nodes:Object.freeze(n),edges:Object.freeze(s)})},ag=e=>new Map(e.nodes.map(t=>[t.id,t]));var to=({graph:e,rootIds:t})=>{let n=ag(e),r=fn(e.edges),o=new Map,s=[],i=[],a=c=>{let u=n.get(c);if(u===void 0)throw new tt({code:"ROOT_NOT_FOUND",message:`Document graph root ${c} does not exist`,documentIds:[c]});let f=o.get(c);if(f!=="visited"){if(f==="visiting"){let l=s.indexOf(c),p=[...s.slice(l),c];throw new tt({code:"CYCLE",message:`Document graph contains a cycle: ${p.join(" -> ")}`,documentIds:p})}o.set(c,"visiting"),s.push(c);for(let l of r.get(c)??[])a(l.reference.documentId);s.pop(),o.set(c,"visited"),i.push(u)}};for(let c of[...new Set(t)].sort(et))a(c);return Object.freeze(i)};var cg=D().regex(/^sha256:[a-f0-9]{64}$/),If=L({format:W("webstudio-document-graph"),version:W(1),nodes:H(Xr),edges:H(eo),integrity:L({algorithm:W("sha256"),checksum:cg})});var ug=D().min(1).refine(e=>e.startsWith("/")===!1,{error:"Asset path must be relative"}).refine(e=>e.includes("\\")===!1&&e.split("/").every(t=>t.length>0&&t!==".."&&t!=="."),{error:"Asset path must be normalized and must not contain dot segments"}),Nf=L({_id:D().min(1),_type:W("asset.file"),name:D().min(1),description:D().optional(),path:ug,key:D(),folderId:D().min(1).optional(),extension:D().regex(/^[a-z0-9]*$/),mimeType:D().min(1),size:U().int().nonnegative(),createdAt:D().datetime().optional(),revision:D().min(1),contentRef:D().min(1),properties:Ne(D(),At()),excerpt:D().optional(),metadataError:L({code:D().min(1),message:D().min(1),reason:D().min(1).optional(),line:U().int().positive().optional(),column:U().int().positive().optional()}).optional()}),ii=Nf.partial().required({_id:!0}),lg=fe(["null","boolean","number","string","object","array"]),fg=Et({format:W("webstudio-builder-asset-field-catalog"),version:W(1),canonicalRevision:D().regex(/^sha256:[a-f0-9]{64}$/),documentCount:U().int().nonnegative(),fields:Ne(D().min(1),Et({queryPath:H(D().min(1)).min(1).max(N.fieldPathDepth).optional(),types:H(lg).min(1),occurrences:U().int().positive(),optional:W(!0).optional(),mixed:W(!0).optional()}))}).superRefine((e,t)=>{for(let[n,r]of Object.entries(e.fields)){let o=[...new Set(r.types)].sort();JSON.stringify(r.types)!==JSON.stringify(o)&&t.addIssue({code:"custom",path:["fields",n,"types"],message:"Observed field types must be unique and sorted"}),r.occurrences>e.documentCount&&t.addIssue({code:"custom",path:["fields",n,"occurrences"],message:"Field occurrences cannot exceed the document count"});let s=r.occurrences<e.documentCount;r.optional===!0!==s&&t.addIssue({code:"custom",path:["fields",n,"optional"],message:"Field optionality must match its occurrence count"});let i=o.length>1;r.mixed===!0!==i&&t.addIssue({code:"custom",path:["fields",n,"mixed"],message:"Mixed status must match the observed types"})}}),no=D().regex(/^sha256:[a-f0-9]{64}$/),zf=L({fields:H(H(D().min(1)).min(1).max(N.fieldPathDepth)).min(1).max(N.outputFieldCount+1),rows:H(H(At())).max(N.resultCount),totalCount:U().int().nonnegative().max(N.candidateDocuments),hasMore:pt()}).superRefine(({fields:e,rows:t},n)=>{for(let[r,o]of t.entries())o.length!==e.length&&n.addIssue({code:"custom",path:["rows",r],message:"Materialized query rows must match the field count"})}),Cf=L({format:W("webstudio-content-database"),version:W(1),assetRevision:no,documents:H(ii),documentGraph:If.optional(),contents:Ne(D().min(1),D()).optional(),assetPaths:Ne(D().min(1),D().min(1)).optional(),assetReferences:Ne(D().min(1),H(L({start:U().int().nonnegative(),end:U().int().positive(),assetId:D().min(1),suffix:D().min(1).optional()}).refine(({start:e,end:t})=>t>e,{message:"Markdown asset reference range must not be empty"}))).optional(),assetValueReferences:Ne(D().min(1),H(L({path:H(D().min(1).or(U().int().nonnegative())).min(1),assetId:D().min(1),suffix:D().min(1).optional(),structured:W(!0).optional()}))).optional(),fieldCatalog:fg,queries:Ne(no,zf).optional(),database:L({maxBytes:U().int().positive(),unboundedBytes:U().int().nonnegative(),sourceDocumentCount:U().int().nonnegative(),includedDocumentCount:U().int().nonnegative().optional()}).optional(),integrity:L({algorithm:W("sha256"),checksum:no})}).superRefine((e,t)=>{e.documents.length>N.candidateDocuments&&t.addIssue({code:"custom",path:["documents"],message:"Asset index exceeds the document limit"}),(e.fieldCatalog.canonicalRevision!==e.assetRevision||e.fieldCatalog.documentCount!==e.documents.length)&&t.addIssue({code:"custom",path:["fieldCatalog"],message:"Asset index field catalog does not match its documents"}),e.database!==void 0&&e.database.sourceDocumentCount<e.documents.length&&t.addIssue({code:"custom",path:["database","sourceDocumentCount"],message:"Source document count cannot be smaller than the database"}),e.database?.includedDocumentCount!==void 0&&(e.database.includedDocumentCount<e.documents.length||e.database.includedDocumentCount>e.database.sourceDocumentCount)&&t.addIssue({code:"custom",path:["database","includedDocumentCount"],message:"Included document count must match the database bounds"});let n;for(let[o,s]of e.documents.entries())n!==void 0&&s._id<=n&&t.addIssue({code:"custom",path:["documents",o,"_id"],message:"Asset index documents must have unique sorted IDs"}),n=s._id;let r=new Set(e.documents.flatMap(({contentRef:o})=>o===void 0?[]:[o]));for(let o of e.documentGraph?.nodes??[])r.add(o.contentRef);for(let o of Object.keys(e.contents??{}))r.has(o)===!1&&t.addIssue({code:"custom",path:["contents",o],message:"Embedded content must belong to an indexed document"});for(let o of Object.keys(e.assetReferences??{}))r.has(o)===!1&&t.addIssue({code:"custom",path:["assetReferences",o],message:"Asset references must belong to an indexed document"})}),dg=cn("mode",[L({mode:W("none")}),L({mode:W("full"),maxBytes:U().int().positive().max(N.hydratedFileBytes).optional()}),L({mode:W("range"),offset:U().int().nonnegative(),length:U().int().positive().max(N.hydratedRangeBytes)}),L({mode:W("markdown-body-ref"),maxBytes:U().int().positive().max(N.hydratedFileBytes).optional()})]),ai={id:["string"],url:["string"],width:["number"],height:["number"],name:["string"],description:["string"],path:["string"],key:["string"],folderId:["string"],extension:["string"],mimeType:["string"],size:["number"],createdAt:["string"],revision:["string"],excerpt:["string"]},$f=Object.keys(ai),Lf=["url","width","height"],ro=e=>Lf.includes(e),Pf=$f.filter(e=>ro(e)===!1&&e!=="excerpt"),Ff=Pf.filter(e=>e!=="id"),Mf=e=>Pf.includes(e),pg=fe($f),Xn=H(D().min(1)).min(1).max(N.fieldPathDepth).superRefine((e,t)=>{if(e[0]==="properties"){e.length<2&&t.addIssue({code:"custom",message:"A properties field path must select a property"});return}(e.length!==1||pg.safeParse(e[0]).success===!1)&&t.addIssue({code:"custom",message:"Asset query field path is unsupported"})}),si=pt().default(!0),mg=cn("mode",[L({mode:W("all"),includeMetadata:si}),L({mode:W("base"),includeMetadata:si}),L({mode:W("fields"),includeMetadata:si,fields:H(Xn).max(N.outputFieldCount).refine(e=>new Set(e.map(_f)).size===e.length,{error:"Selected output fields must be unique"})})]),hg={mode:"fields",includeMetadata:!1,fields:Lf.map(e=>[e])},Bf=["eq","ne","contains","startsWith","endsWith","gt","gte","lt","lte"],hS=[...Bf,"in","exists","isEmpty"],gg=L({field:Xn,operator:fe(Bf),value:At()}),yg=L({field:Xn,operator:W("in"),value:H(At()).max(N.resultCount)}),bg=L({field:Xn,operator:fe(["exists","isEmpty"]),value:pt()}),wg=cn("operator",[gg,yg,bg]),xg=Sf(wg,{maximumChildren:N.filterCount,maximumConditions:N.filterCount,maximumDepth:N.filterDepth,maximumConditionsMessage:"Asset query exceeds the filter limit",maximumDepthMessage:"Asset query exceeds the filter nesting limit"});var _g=xg,qf=e=>{let t=new Set(["eq","ne","in","exists"]);return e.some(n=>n==="string"||n==="array")&&t.add("contains"),e.includes("string")&&(t.add("startsWith"),t.add("endsWith")),e.some(n=>n==="string"||n==="number")&&(t.add("gt"),t.add("gte"),t.add("lt"),t.add("lte")),e.some(n=>n==="string"||n==="array"||n==="object")&&t.add("isEmpty"),[...t]},Sg=L({field:Xn,direction:fe(["asc","desc"])}),Eg=fe(["many","one","first","last"]),Ag=({output:e,content:t})=>e.includeMetadata||e.mode==="all"||e.mode==="fields"&&e.fields.length>0||t.mode!=="none",Rt=L({result:Eg.default("many"),where:_g.default({all:[]}),sort:H(Sg).max(N.sortCount).default([]),limit:U().int().nonnegative().max(N.resultCount).default(N.defaultResultCount),offset:U().int().nonnegative().max(N.candidateDocuments).default(0),output:mg.default(hg),content:dg.default({mode:"none"})}).superRefine((e,t)=>{Ag(e)===!1&&t.addIssue({code:"custom",message:"Select at least one asset query output"}),(e.result==="first"||e.result==="last")&&e.sort.length===0&&t.addIssue({code:"custom",path:["sort"],message:"Add sorting to define which item is first."})}),Zf=L({query:Rt,indexRevision:D().min(1).max(255).optional()}),kg=Et({_id:D().min(1),revision:D().min(1),contentRef:D().min(1),encoding:W("utf-8"),text:D(),range:Et({offset:U().int().nonnegative(),length:U().int().nonnegative(),total:U().int().nonnegative()}).optional()}),vg=kg.omit({_id:!0,revision:!0,contentRef:!0}),Uf=Nf.omit({_id:!0,_type:!0,contentRef:!0}).partial().extend({id:D().min(1),url:D().min(1).optional(),width:U().positive().optional(),height:U().positive().optional(),content:vg.optional()}).refine(e=>e.width===void 0==(e.height===void 0),{error:"Asset dimensions must include both width and height"}),Rg=L({format:W("webstudio-content-database"),version:W(1),revision:no,usedBytes:U().int().nonnegative(),maxBytes:U().int().positive(),unboundedBytes:U().int().nonnegative(),includedDocumentCount:U().int().nonnegative(),omittedDocumentCount:U().int().nonnegative(),omissionReason:fe(["size","unavailable"]).optional(),truncated:pt()}),Tf=Rg.pick({usedBytes:!0,maxBytes:!0,unboundedBytes:!0,includedDocumentCount:!0,omittedDocumentCount:!0,omissionReason:!0,truncated:!0}),ci=L({items:H(Uf),totalCount:U().int().nonnegative(),hasMore:pt()}),Dg=L({item:Uf.nullable(),totalCount:U().int().nonnegative()}),jf=an([ci,Dg]),Of=L({line:U().int().positive(),column:U().int().positive(),offset:U().int().nonnegative().optional()}),Ig=L({severity:fe(["error","warning"]),scope:fe(["query","database"]),phase:fe(["metadata","reference","source"]),code:D().min(1),message:D().min(1),assetId:D().min(1),path:D().min(1),line:U().int().positive().optional(),column:U().int().positive().optional(),reference:D().min(1).optional(),nodeType:D().min(1).optional(),reason:D().min(1).optional(),sourceRange:L({start:Of,end:Of}).optional()}),Cg=L({severity:fe(["error","warning"]),code:D().min(1),path:H(D()),message:D().min(1)}),Tg=L({scope:W("query-preview"),queryIssues:H(Cg).optional(),queryWarnings:H(D().min(1)).optional(),query:Tf,database:Tf,artifacts:L({query:Cf,database:Cf}).optional(),unresolved:jf.optional(),issues:H(Ig).optional(),issueCount:U().int().nonnegative().optional(),issuesTruncated:pt().optional()}),gS=L({data:jf,__diagnostics__:Tg}),Og=fe(["INVALID_REQUEST","REQUEST_CANCELLED","UNAUTHORIZED","FORBIDDEN","STALE_INDEX","CONTENT_IDENTITY_REQUIRED","CONTENT_NOT_TEXT","CONTENT_DECODING_FAILED","CONTENT_LIMIT_EXCEEDED","MULTIPLE_RESULTS","INTERNAL_ERROR"]),Ng=Et({ok:W(!1),error:Et({code:Og,message:D().min(1),retryable:pt(),details:Ne(D(),At()).optional()}),meta:Et({queryHash:D().min(1).optional(),indexRevision:D().min(1).optional(),assetRevision:D().min(1).optional()}).optional()}),Vf=({code:e,message:t,retryable:n=!1,details:r})=>Ng.parse({ok:!1,error:{code:e,message:t,retryable:n,details:r}});var Qf=function*(e){if(e.length>0&&!e.startsWith("/")||/~(?![01])/.test(e))throw Error("Invalid JSON Pointer");let t=1,n=0;for(;n<e.length;){let r=e.indexOf("/",t);n=r===-1?e.length:r;let o=e.slice(t,n);t=n+1,yield $g(o)}};var ui=(e,t)=>t+"/"+zg(e),zg=e=>e.toString().replace(/~/g,"~0").replace(/\//g,"~1"),$g=e=>e.toString().replace(/~1/g,"/").replace(/~0/g,"~");var oo=async(e,t,n)=>{if(Number.isSafeInteger(t)===!1||t<=0)throw new Error("Concurrency must be a positive safe integer");let r=0,o=new Array(e.length),s=async()=>{for(;r<e.length;){let u=r;r+=1,o[u]=await n(e[u])}},i=Array.from({length:Math.min(t,e.length)},s),c=(await Promise.allSettled(i)).find(u=>u.status==="rejected");if(c!==void 0)throw c.reason;return o},li=e=>e.reason??new DOMException("The operation was aborted","AbortError"),Gf=e=>{if(e?.aborted)throw li(e)},dn=async(e,t)=>t===void 0?await e:await new Promise((n,r)=>{let o=()=>t.removeEventListener("abort",s),s=()=>{o(),r(li(t))};t.addEventListener("abort",s,{once:!0}),Promise.resolve(e).then(i=>{o(),n(i)},i=>{o(),r(i)}),t.aborted&&s()}),so=({concurrency:e,signal:t})=>{if(Number.isSafeInteger(e)===!1||e<=0)throw new TypeError("Concurrency must be a positive safe integer");let n=0,r=[],o=async()=>{if(Gf(t),n<e){n+=1;return}await new Promise((i,a)=>{let c,u=()=>{let f=r.indexOf(c);f!==-1&&r.splice(f,1),t!==void 0&&a(li(t))};c={start:()=>{t?.removeEventListener("abort",u),i()}},r.push(c),t?.addEventListener("abort",u,{once:!0})})},s=()=>{let i=r.shift();if(i===void 0){n-=1;return}i.start()};return async i=>{await o();try{return Gf(t),await i()}finally{s()}}};var pn=e=>typeof e=="object"&&e!==null&&Array.isArray(e)===!1,io=e=>{if(pn(e)===!1)return;let t=Object.keys(e);if(!(t.length!==1||t[0]!=="$ref"))return e.$ref};var De=class extends Error{code;referenceId;constructor({code:t,message:n,referenceId:r,cause:o}){super(n,{cause:o}),this.name="JsonDocumentError",this.code=t,this.referenceId=r}},Lg=(e,t)=>{let n=io(e);if(n!==void 0){if(typeof n!="string")throw new De({code:"INVALID_REFERENCE_MARKER",message:`JSON reference marker ${t} must contain a string $ref`,referenceId:t});return n}},Pg=e=>`#${e}`;var Jf=async({source:e,maximumBytes:t=N.hydratedFileBytes})=>{let n;try{n=await Xe(e,t)}catch(o){throw o instanceof we?new De({code:"CONTENT_LIMIT_EXCEEDED",message:"JSON document exceeds the byte limit",cause:o}):o}let r;try{r=ln(ve(n))}catch(o){throw new De({code:"CONTENT_DECODING_FAILED",message:"JSON document is not valid UTF-8",cause:o})}try{return vt(JSON.parse(r))}catch(o){throw new De({code:"INVALID_DOCUMENT",message:"JSON document is invalid",cause:o})}};var Fg=(e,t)=>{let n=e;for(let r of t){if(Array.isArray(n)){let o=Number(r);if(Number.isSafeInteger(o)===!1||o<0||String(o)!==r||o>=n.length)return;n=n[o];continue}if(pn(n)&&Object.hasOwn(n,r)){n=n[r];continue}return}return n},Wf=({document:e,representation:t})=>{let n=vt(e);if(t.type==="document")return n;if(t.type!=="json")throw new De({code:"UNSUPPORTED_REPRESENTATION",message:`JSON documents do not support ${t.type}`});let r=Fg(n,t.path);if(r===void 0)throw new De({code:"JSON_PATH_NOT_FOUND",message:"JSON document path does not exist"});return r},Mg=(e,t,n)=>{Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})},ao=({document:e,references:t,allowUnresolvedReferences:n=!1})=>{let r=vt(e),o=new Set,s=(a,c)=>{let u=Pg(c);if(Lg(a,u)!==void 0){if(t.has(u)===!1){if(n)return a;throw new De({code:"REFERENCE_NOT_FOUND",message:`Resolved JSON reference ${u} is unavailable`,referenceId:u})}o.add(u);try{return vt(t.get(u))}catch(l){throw new De({code:"INVALID_RESOLVED_VALUE",message:`Resolved JSON reference ${u} is not JSON-compatible`,referenceId:u,cause:l})}}if(Array.isArray(a))return a.map((l,p)=>s(l,ui(String(p),c)));if(pn(a)){let l={};for(let[p,d]of Object.entries(a))Mg(l,p,s(d,ui(p,c)));return l}return a},i=s(r,"");for(let a of[...t.keys()].sort())if(o.has(a)===!1)throw new De({code:"UNUSED_REFERENCE",message:`Resolved JSON reference ${a} has no marker`,referenceId:a});return i};var co=Symbol.for("yaml.alias"),uo=Symbol.for("yaml.document"),Ue=Symbol.for("yaml.map"),fi=Symbol.for("yaml.pair"),Ie=Symbol.for("yaml.scalar"),mt=Symbol.for("yaml.seq"),xe=Symbol.for("yaml.node.type"),ze=e=>!!e&&typeof e=="object"&&e[xe]===co,nt=e=>!!e&&typeof e=="object"&&e[xe]===uo,$e=e=>!!e&&typeof e=="object"&&e[xe]===Ue,j=e=>!!e&&typeof e=="object"&&e[xe]===fi,B=e=>!!e&&typeof e=="object"&&e[xe]===Ie,Le=e=>!!e&&typeof e=="object"&&e[xe]===mt;function K(e){if(e&&typeof e=="object")switch(e[xe]){case Ue:case mt:return!0}return!1}function V(e){if(e&&typeof e=="object")switch(e[xe]){case co:case Ue:case Ie:case mt:return!0}return!1}var lo=e=>(B(e)||K(e))&&!!e.anchor;var Ae=Symbol("break visit"),Kf=Symbol("skip children"),rt=Symbol("remove node");function ot(e,t){let n=Hf(t);nt(e)?mn(null,e.contents,n,Object.freeze([e]))===rt&&(e.contents=null):mn(null,e,n,Object.freeze([]))}ot.BREAK=Ae;ot.SKIP=Kf;ot.REMOVE=rt;function mn(e,t,n,r){let o=Yf(e,t,n,r);if(V(o)||j(o))return Xf(e,r,o),mn(e,o,n,r);if(typeof o!="symbol"){if(K(t)){r=Object.freeze(r.concat(t));for(let s=0;s<t.items.length;++s){let i=mn(s,t.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===Ae)return Ae;i===rt&&(t.items.splice(s,1),s-=1)}}}else if(j(t)){r=Object.freeze(r.concat(t));let s=mn("key",t.key,n,r);if(s===Ae)return Ae;s===rt&&(t.key=null);let i=mn("value",t.value,n,r);if(i===Ae)return Ae;i===rt&&(t.value=null)}}return o}async function fo(e,t){let n=Hf(t);nt(e)?await hn(null,e.contents,n,Object.freeze([e]))===rt&&(e.contents=null):await hn(null,e,n,Object.freeze([]))}fo.BREAK=Ae;fo.SKIP=Kf;fo.REMOVE=rt;async function hn(e,t,n,r){let o=await Yf(e,t,n,r);if(V(o)||j(o))return Xf(e,r,o),hn(e,o,n,r);if(typeof o!="symbol"){if(K(t)){r=Object.freeze(r.concat(t));for(let s=0;s<t.items.length;++s){let i=await hn(s,t.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===Ae)return Ae;i===rt&&(t.items.splice(s,1),s-=1)}}}else if(j(t)){r=Object.freeze(r.concat(t));let s=await hn("key",t.key,n,r);if(s===Ae)return Ae;s===rt&&(t.key=null);let i=await hn("value",t.value,n,r);if(i===Ae)return Ae;i===rt&&(t.value=null)}}return o}function Hf(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Yf(e,t,n,r){if(typeof n=="function")return n(e,t,r);if($e(t))return n.Map?.(e,t,r);if(Le(t))return n.Seq?.(e,t,r);if(j(t))return n.Pair?.(e,t,r);if(B(t))return n.Scalar?.(e,t,r);if(ze(t))return n.Alias?.(e,t,r)}function Xf(e,t,n){let r=t[t.length-1];if(K(r))r.items[e]=n;else if(j(r))e==="key"?r.key=n:r.value=n;else if(nt(r))r.contents=n;else{let o=ze(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}var Bg={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},qg=e=>e.replace(/[!,[\]{}]/g,t=>Bg[t]),st=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),o=r.shift();switch(o){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[s,i]=r;return this.tags[s]=i,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=r;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let i=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,i),!1}}default:return n(0,`Unknown directive ${o}`,!0),!1}}tagName(t,n){if(t==="!")return"!";if(t[0]!=="!")return n(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let i=t.slice(2,-1);return i==="!"||i==="!!"?(n(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&n("Verbatim tags must end with a >"),i)}let[,r,o]=t.match(/^(.*!)([^!]*)$/s);o||n(`The ${t} tag has no suffix`);let s=this.tags[r];if(s)try{return s+decodeURIComponent(o)}catch(i){return n(String(i)),null}return r==="!"?t:(n(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[n,r]of Object.entries(this.tags))if(t.startsWith(r))return n+qg(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),o;if(t&&r.length>0&&V(t.contents)){let s={};ot(t.contents,(i,a)=>{V(a)&&a.tag&&(s[a.tag]=!0)}),o=Object.keys(s)}else o=[];for(let[s,i]of r)s==="!!"&&i==="tag:yaml.org,2002:"||(!t||o.some(a=>a.startsWith(i)))&&n.push(`%TAG ${s} ${i}`);return n.join(`
`)}};st.defaultYaml={explicit:!1,version:"1.2"};st.defaultTags={"!!":"tag:yaml.org,2002:"};function po(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(n)}return!0}function di(e){let t=new Set;return ot(e,{Value(n,r){r.anchor&&t.add(r.anchor)}}),t}function pi(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function ed(e,t){let n=[],r=new Map,o=null;return{onAnchor:s=>{n.push(s),o??(o=di(e));let i=pi(t,o);return o.add(i),i},setAnchors:()=>{for(let s of n){let i=r.get(s);if(typeof i=="object"&&i.anchor&&(B(i.node)||K(i.node)))i.node.anchor=i.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:r}}function Dt(e,t,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let o=0,s=r.length;o<s;++o){let i=r[o],a=Dt(e,r,String(o),i);a===void 0?delete r[o]:a!==i&&(r[o]=a)}else if(r instanceof Map)for(let o of Array.from(r.keys())){let s=r.get(o),i=Dt(e,r,o,s);i===void 0?r.delete(o):i!==s&&r.set(o,i)}else if(r instanceof Set)for(let o of Array.from(r)){let s=Dt(e,r,o,o);s===void 0?r.delete(o):s!==o&&(r.delete(o),r.add(s))}else for(let[o,s]of Object.entries(r)){let i=Dt(e,r,o,s);i===void 0?delete r[o]:i!==s&&(r[o]=i)}return e.call(t,n,r)}function le(e,t,n){if(Array.isArray(e))return e.map((r,o)=>le(r,String(o),n));if(e&&typeof e.toJSON=="function"){if(!n||!lo(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=s=>{r.res=s,delete n.onCreate};let o=e.toJSON(t,n);return n.onCreate&&n.onCreate(o),o}return typeof e=="bigint"&&!n?.keep?Number(e):e}var It=class{constructor(t){Object.defineProperty(this,xe,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:n,maxAliasCount:r,onAnchor:o,reviver:s}={}){if(!nt(t))throw new TypeError("A document argument is required");let i={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=le(this,"",i);if(typeof o=="function")for(let{count:c,res:u}of i.anchors.values())o(u,c);return typeof s=="function"?Dt(s,{"":a},"",a):a}};var ht=class extends It{constructor(t){super(co),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],ot(t,{Node:(s,i)=>{(ze(i)||lo(i))&&r.push(i)}}),n&&(n.aliasResolveCache=r));let o;for(let s of r){if(s===this)break;s.anchor===this.source&&(o=s)}return o}toJSON(t,n){if(!n)return{source:this.source};let{anchors:r,doc:o,maxAliasCount:s}=n,i=this.resolve(o,n);if(!i){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=r.get(i);if(a||(le(i,null,n),a=r.get(i)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=mo(o,i,r)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(t,n,r){let o=`*${this.source}`;if(t){if(po(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(t.implicitKey)return`${o} `}return o}};function mo(e,t,n){if(ze(t)){let r=t.resolve(e),o=n&&r&&n.get(r);return o?o.count*o.aliasCount:0}else if(K(t)){let r=0;for(let o of t.items){let s=mo(e,o,n);s>r&&(r=s)}return r}else if(j(t)){let r=mo(e,t.key,n),o=mo(e,t.value,n);return Math.max(r,o)}return 1}var ho=e=>!e||typeof e!="function"&&typeof e!="object",T=class extends It{constructor(t){super(Ie),this.value=t}toJSON(t,n){return n?.keep?this.value:le(this.value,t,n)}toString(){return String(this.value)}};T.BLOCK_FOLDED="BLOCK_FOLDED";T.BLOCK_LITERAL="BLOCK_LITERAL";T.PLAIN="PLAIN";T.QUOTE_DOUBLE="QUOTE_DOUBLE";T.QUOTE_SINGLE="QUOTE_SINGLE";var Zg="tag:yaml.org,2002:";function Ug(e,t,n){if(t){let r=n.filter(s=>s.tag===t),o=r.find(s=>!s.format)??r[0];if(!o)throw new Error(`Tag ${t} not found`);return o}return n.find(r=>r.identify?.(e)&&!r.format)}function gt(e,t,n){if(nt(e)&&(e=e.contents),V(e))return e;if(j(e)){let l=n.schema[Ue].createNode?.(n.schema,null,n);return l.items.push(e),l}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:o,onTagObj:s,schema:i,sourceObjects:a}=n,c;if(r&&e&&typeof e=="object"){if(c=a.get(e),c)return c.anchor??(c.anchor=o(e)),new ht(c.anchor);c={anchor:null,node:null},a.set(e,c)}t?.startsWith("!!")&&(t=Zg+t.slice(2));let u=Ug(e,t,i.tags);if(!u){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let l=new T(e);return c&&(c.node=l),l}u=e instanceof Map?i[Ue]:Symbol.iterator in Object(e)?i[mt]:i[Ue]}s&&(s(u),delete n.onTagObj);let f=u?.createNode?u.createNode(n.schema,e,n):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(n.schema,e,n):new T(e);return t?f.tag=t:u.default||(f.tag=u.tag),c&&(c.node=f),f}function er(e,t,n){let r=n;for(let o=t.length-1;o>=0;--o){let s=t[o];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let i=[];i[s]=r,r=i}else r=new Map([[s,r]])}return gt(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var yn=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,gn=class extends It{constructor(t,n){super(t),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(t){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(n.schema=t),n.items=n.items.map(r=>V(r)||j(r)?r.clone(t):r),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(yn(t))this.add(n);else{let[r,...o]=t,s=this.get(r,!0);if(K(s))s.addIn(o,n);else if(s===void 0&&this.schema)this.set(r,er(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}deleteIn(t){let[n,...r]=t;if(r.length===0)return this.delete(n);let o=this.get(n,!0);if(K(o))return o.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(t,n){let[r,...o]=t,s=this.get(r,!0);return o.length===0?!n&&B(s)?s.value:s:K(s)?s.getIn(o,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!j(n))return!1;let r=n.value;return r==null||t&&B(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[n,...r]=t;if(r.length===0)return this.has(n);let o=this.get(n,!0);return K(o)?o.hasIn(r):!1}setIn(t,n){let[r,...o]=t;if(o.length===0)this.set(r,n);else{let s=this.get(r,!0);if(K(s))s.setIn(o,n);else if(s===void 0&&this.schema)this.set(r,er(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}};var td=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Pe(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var it=(e,t,n)=>e.endsWith(`
`)?Pe(n,t):n.includes(`
`)?`
diff --git a/packages/cli/src/prebuild.test.ts b/packages/cli/src/prebuild.test.ts
index 43699b1aca..52524c1b06 100644
--- a/packages/cli/src/prebuild.test.ts
+++ b/packages/cli/src/prebuild.test.ts
@@ -24,6 +24,7 @@ import {
import { build } from "esbuild";
import { loadConfigFromFile } from "vite";
import { bundleVersion } from "@webstudio-is/protocol";
+import { isProtectedResourceReentry } from "@webstudio-is/sdk/protected-resource-fetch";
import type { Asset, DataSource, Instance, Prop } from "@webstudio-is/sdk";
import {
createDocumentGraph,
@@ -1022,6 +1023,114 @@ describe("prebuild", () => {
expect(nodeAdapter).not.toContain("EMAIL_SERVICE");
});
+ test.each(["saas", undefined] as const)(
+ "allows sibling API hosts but blocks published site aliases on Cloudflare (%s)",
+ async (destination) => {
+ const siteData = createSiteData();
+ siteData.projectDomain = "project.wstd.io";
+ await writeFile(
+ ".webstudio/data.json",
+ JSON.stringify({
+ ...siteData,
+ build: {
+ ...siteData.build,
+ deployment: {
+ destination,
+ domains: ["site.example.com", "alias.example.net"],
+ },
+ },
+ })
+ );
+ await prebuild({
+ assets: false,
+ template: ["react-router", "react-router-cloudflare"],
+ });
+ await symlink(join(originalCwd, "node_modules"), "node_modules", "dir");
+ const bundle = await build({
+ entryPoints: [
+ join(
+ tempDir,
+ "app/__generated__/$resources.managed-form-fetch.server.ts"
+ ),
+ ],
+ bundle: true,
+ format: "esm",
+ platform: "node",
+ conditions: ["webstudio"],
+ write: false,
+ });
+ const adapter = (await import(
+ /* @vite-ignore */
+ `data:text/javascript;base64,${Buffer.from(bundle.outputFiles[0].text).toString("base64")}`
+ )) as {
+ createManagedFormResourceFetch: (input: {
+ request: Request;
+ context: unknown;
+ projectDomain: string;
+ }) => typeof fetch & { validateDestination: (url: URL) => void };
+ };
+ const metadataBundle = await build({
+ stdin: {
+ contents: 'export { projectId } from "./app/__generated__/_index";',
+ resolveDir: tempDir,
+ },
+ platform: "node",
+ conditions: ["webstudio"],
+ bundle: true,
+ format: "esm",
+ write: false,
+ });
+ const { projectId } = await import(
+ /* @vite-ignore */
+ `data:text/javascript;base64,${Buffer.from(metadataBundle.outputFiles[0].text).toString("base64")}`
+ );
+ expect(projectId).toBe(siteData.build.projectId);
+ vi.stubGlobal(
+ "fetch",
+ async (input: RequestInfo | URL, init?: RequestInit) => {
+ const request = new Request(input, init);
+ const receivingProjectId =
+ new URL(request.url).hostname === "api.example.com"
+ ? "other-project"
+ : projectId;
+ return new Response(null, {
+ status: isProtectedResourceReentry(request, receivingProjectId)
+ ? 508
+ : 200,
+ });
+ }
+ );
+ const protectedFetch = adapter.createManagedFormResourceFetch({
+ request: new Request("https://site.example.com"),
+ context: {},
+ projectDomain: siteData.projectDomain,
+ });
+
+ try {
+ expect((await protectedFetch("https://api.example.com")).status).toBe(
+ 200
+ );
+ expect(
+ (await protectedFetch("https://unknown-alias.example.com")).status
+ ).toBe(508);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ expect(() =>
+ protectedFetch.validateDestination(new URL("https://api.example.com"))
+ ).not.toThrow();
+ for (const hostname of [
+ "site.example.com",
+ "alias.example.net",
+ "project.wstd.io",
+ ]) {
+ expect(() =>
+ protectedFetch.validateDestination(new URL(`https://${hostname}`))
+ ).toThrow();
+ }
+ }
+ );
+
test("publishes configured file-input attributes", async () => {
await writeSiteData(
createSiteData({
diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.ts
index 6a7cbd81e4..ef51eaf665 100644
--- a/packages/cli/src/prebuild.ts
+++ b/packages/cli/src/prebuild.ts
@@ -1073,7 +1073,6 @@ export const prebuild = async (options: {
isCloudflareTemplate
? `import {
createCloudflareProtectedResourceFetch,
- getDeniedResourceHostnames,
} from "@webstudio-is/sdk/protected-resource-fetch";
import { createCloudflareManagedFormEmailSender, createCloudflareManagedFormEmailSenderWithUrl, validateCloudflareManagedFormEmail } from "@webstudio-is/sdk/form/server";
export const validateManagedFormEmail = validateCloudflareManagedFormEmail;
@@ -1091,10 +1090,19 @@ export const createManagedFormEmailSender = ({ context, formData, projectId }: {
export const createManagedFormResourceFetch = ({ request, context, projectDomain }: { request: Request; context: unknown; projectDomain?: string }) => {
void context;
return createCloudflareProtectedResourceFetch({
- ownZoneHostnames: getDeniedResourceHostnames([
+ projectId: ${JSON.stringify(siteData.build.projectId)},
+ // The generated Cloudflare templates and hosted Worker use public fetch routing.
+ publicRouting: true,
+ ownZoneHostnames: [
new URL(request.url).hostname,
projectDomain,
- ]) as [string, ...string[]],
+ ...${JSON.stringify(
+ siteData.build.deployment !== undefined &&
+ "domains" in siteData.build.deployment
+ ? siteData.build.deployment.domains
+ : []
+ )},
+ ].filter((hostname): hostname is string => hostname !== undefined) as [string, ...string[]],
});
};
`
diff --git a/packages/cli/templates/cloudflare/functions/[[path]].ts b/packages/cli/templates/cloudflare/functions/[[path]].ts
index 943b55594f..81571ea4a3 100644
--- a/packages/cli/templates/cloudflare/functions/[[path]].ts
+++ b/packages/cli/templates/cloudflare/functions/[[path]].ts
@@ -1,4 +1,7 @@
import { createPagesFunctionHandler } from "@remix-run/cloudflare-pages";
+import { isProtectedResourceReentry } from "@webstudio-is/sdk/protected-resource-fetch";
+// @ts-ignore - generated by the Webstudio CLI at build time
+import { projectId } from "../app/__generated__/_index";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore - the server build file is generated by `remix vite:build`
@@ -6,4 +9,11 @@ import * as build from "../build/server";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore - the server build file is generated by `remix vite:build`
-export const onRequest = createPagesFunctionHandler({ build });
+const requestHandler = createPagesFunctionHandler({ build });
+
+export const onRequest: typeof requestHandler = async (context) => {
+ if (isProtectedResourceReentry(context.request, projectId)) {
+ return new Response(null, { status: 508 });
+ }
+ return requestHandler(context);
+};
diff --git a/packages/cli/templates/cloudflare/wrangler.toml b/packages/cli/templates/cloudflare/wrangler.toml
index a7b57800e8..6d3d9fd4fb 100644
--- a/packages/cli/templates/cloudflare/wrangler.toml
+++ b/packages/cli/templates/cloudflare/wrangler.toml
@@ -2,6 +2,7 @@
# https://developers.cloudflare.com/pages/functions/wrangler-configuration/
name = "webstudio-remix-app"
compatibility_date = "2024-04-05"
+compatibility_flags = ["global_fetch_strictly_public"]
pages_build_output_dir="./build"
# Variable bindings. These are arbitrary, plaintext strings (similar to environment variables)
diff --git a/packages/cli/templates/react-router-cloudflare/workers/app.ts b/packages/cli/templates/react-router-cloudflare/workers/app.ts
index 45e3c89694..be407918d5 100644
--- a/packages/cli/templates/react-router-cloudflare/workers/app.ts
+++ b/packages/cli/templates/react-router-cloudflare/workers/app.ts
@@ -1,4 +1,7 @@
import { createRequestHandler } from "react-router";
+import { isProtectedResourceReentry } from "@webstudio-is/sdk/protected-resource-fetch";
+// @ts-ignore - generated by the Webstudio CLI at build time
+import { projectId } from "../app/__generated__/_index";
declare module "react-router" {
export interface AppLoadContext {
@@ -17,6 +20,9 @@ const requestHandler = createRequestHandler(
export default {
async fetch(request, env, ctx) {
+ if (isProtectedResourceReentry(request, projectId)) {
+ return new Response(null, { status: 508 });
+ }
return requestHandler(request, {
EXCLUDE_FROM_SEARCH: false,
cloudflare: { env, ctx },
diff --git a/packages/cli/templates/react-router-cloudflare/wrangler.jsonc b/packages/cli/templates/react-router-cloudflare/wrangler.jsonc
index b63ac1bed7..765bda8f04 100644
--- a/packages/cli/templates/react-router-cloudflare/wrangler.jsonc
+++ b/packages/cli/templates/react-router-cloudflare/wrangler.jsonc
@@ -2,5 +2,6 @@
"$schema": "node_modules/wrangler/config-schema.json",
"name": "webstudio-app",
"compatibility_date": "2025-04-28",
+ "compatibility_flags": ["global_fetch_strictly_public"],
"main": "./workers/app.ts"
}
diff --git a/packages/cli/templates/saas-helpers/wrangler.jsonc b/packages/cli/templates/saas-helpers/wrangler.jsonc
index f338f6c6d7..b0a0b90f70 100644
--- a/packages/cli/templates/saas-helpers/wrangler.jsonc
+++ b/packages/cli/templates/saas-helpers/wrangler.jsonc
@@ -3,5 +3,6 @@
// Hosted deployments publish Workers. This takes precedence over the Cloudflare Pages
// template's wrangler.toml; publish workflows provide the name and date.
"name": "webstudio-remix-app",
- "compatibility_date": "2024-04-05"
+ "compatibility_date": "2024-04-05",
+ "compatibility_flags": ["global_fetch_strictly_public"]
}
diff --git a/packages/content-engine/package.json b/packages/content-engine/package.json
index 1ceca28491..f05706581e 100644
--- a/packages/content-engine/package.json
+++ b/packages/content-engine/package.json
@@ -10,7 +10,7 @@
"scripts": {
"benchmark:index": "NODE_OPTIONS=--conditions=webstudio pnpm tsx scripts/benchmark-index.mjs",
"benchmark:scale": "NODE_OPTIONS=--conditions=webstudio pnpm tsx scripts/benchmark-scale.mjs",
- "build": "rm -rf lib && esbuild src/index.ts src/asset-content-repository.ts src/asset-content-session.ts src/compiler.ts src/jsx-attributes.ts src/limits.ts src/markdown-assets.ts src/markdown-references.ts src/mdx.ts src/published-runtime.ts src/remark-github-alerts.ts --outdir=lib --bundle --format=esm --packages=external",
+ "build": "rm -rf lib && esbuild src/index.ts src/byte-stream.ts src/asset-content-repository.ts src/asset-content-session.ts src/compiler.ts src/jsx-attributes.ts src/limits.ts src/markdown-assets.ts src/markdown-references.ts src/mdx.ts src/published-runtime.ts src/remark-github-alerts.ts --outdir=lib --bundle --format=esm --packages=external",
"dts": "tsc --project tsconfig.dts.json",
"test": "vitest run",
"typecheck": "tsc --noEmit"
@@ -56,6 +56,12 @@
"import": "./lib/index.js",
"default": "./src/index.ts"
},
+ "./byte-stream": {
+ "webstudio": "./src/byte-stream.ts",
+ "types": "./lib/types/byte-stream.d.ts",
+ "import": "./lib/byte-stream.js",
+ "default": "./src/byte-stream.ts"
+ },
"./compiler": {
"webstudio": "./src/compiler.ts",
"types": "./lib/types/compiler.d.ts",
diff --git a/packages/content-engine/src/byte-stream.ts b/packages/content-engine/src/byte-stream.ts
index 18664854db..5367a0acf8 100644
--- a/packages/content-engine/src/byte-stream.ts
+++ b/packages/content-engine/src/byte-stream.ts
@@ -93,11 +93,9 @@ export const readableStreamToAsyncIterable = (
}
} finally {
if (completed === false) {
- try {
- await reader.cancel();
- } catch {
- // Preserve the consumer error that stopped the stream.
- }
+ // Cancelling a tee waits for its other branch. Start cleanup without
+ // delaying the consumer or replacing its error if cancellation fails.
+ reader.cancel().catch(() => {});
}
reader.releaseLock();
}
@@ -127,11 +125,12 @@ export const readBytePrefix = async (
export const readBoundedBytes = async (
source: ByteSource,
- maximumBytes: number
+ maximumBytes: number,
+ limitError = new ByteLimitExceededError()
) => {
const bytes = await readBytePrefix(source, maximumBytes + 1);
if (bytes.byteLength > maximumBytes) {
- throw new ByteLimitExceededError();
+ throw limitError;
}
return bytes;
};
diff --git a/packages/sdk/src/form/server-submission.ts b/packages/sdk/src/form/server-submission.ts
index 2e6a8fe09a..c66715cc1d 100644
--- a/packages/sdk/src/form/server-submission.ts
+++ b/packages/sdk/src/form/server-submission.ts
@@ -1,3 +1,4 @@
+import { readLimitedBytes } from "../resource-response";
import { getReachableResources } from "./resource-graph";
import { formBotFieldName, managedFormArrayNamesFieldName } from "./fields";
import {
@@ -165,31 +166,11 @@ export const readFormDataWithLimit = async (
if (request.body === null) {
return new FormData();
}
- const reader = request.body.getReader();
- const chunks: Uint8Array[] = [];
- let totalBytes = 0;
- try {
- while (true) {
- const { done, value } = await reader.read();
- if (done) {
- break;
- }
- totalBytes += value.byteLength;
- if (totalBytes > maximumBytes) {
- await reader.cancel();
- throw formRequestTooLarge(maximumBytes);
- }
- chunks.push(value);
- }
- } finally {
- reader.releaseLock();
- }
- const body = new Uint8Array(totalBytes);
- let offset = 0;
- for (const chunk of chunks) {
- body.set(chunk, offset);
- offset += chunk.byteLength;
- }
+ const body = await readLimitedBytes(
+ request.body,
+ maximumBytes,
+ formRequestTooLarge(maximumBytes)
+ );
const headers = new Headers(request.headers);
headers.delete("content-length");
return new Request(request.url, {
diff --git a/packages/sdk/src/protected-resource-fetch.test.ts b/packages/sdk/src/protected-resource-fetch.test.ts
index 3e4161fd2f..20dc093411 100644
--- a/packages/sdk/src/protected-resource-fetch.test.ts
+++ b/packages/sdk/src/protected-resource-fetch.test.ts
@@ -3,6 +3,7 @@ import {
createCloudflareProtectedResourceFetch,
createProtectedResourceFetch,
getDeniedResourceHostnames,
+ isProtectedResourceReentry,
} from "./protected-resource-fetch";
describe("protected Resource fetch", () => {
@@ -30,19 +31,86 @@ describe("protected Resource fetch", () => {
expect(transport).not.toHaveBeenCalled();
});
- test("requires an explicit Worker zone and blocks its own origin", async () => {
+ test("requires a site hostname and blocks requests back to the site", async () => {
expect(() =>
- createCloudflareProtectedResourceFetch({ ownZoneHostnames: [""] })
+ createCloudflareProtectedResourceFetch({
+ projectId: "project-a",
+ ownZoneHostnames: [""],
+ })
).toThrow("Worker zones must be specified");
const workerFetch = vi.fn<typeof fetch>();
const protectedFetch = createCloudflareProtectedResourceFetch({
- ownZoneHostnames: ["example.com"],
+ projectId: "project-a",
+ ownZoneHostnames: ["site.example.com", "alias.example.net"],
+ publicRouting: true,
+ workerFetch,
+ });
+ for (const hostname of ["site.example.com", "alias.example.net"]) {
+ await expect(
+ protectedFetch(`https://${hostname}/submit`, { method: "POST" })
+ ).rejects.toThrow("not allowed");
+ }
+ expect(workerFetch).not.toHaveBeenCalled();
+ });
+
+ test("allows a sibling API hostname on a public-routed Worker", async () => {
+ const workerFetch = vi
+ .fn<typeof fetch>()
+ .mockResolvedValue(new Response("ok"));
+ const protectedFetch = createCloudflareProtectedResourceFetch({
+ projectId: "project-a",
+ ownZoneHostnames: ["site.example.com"],
+ publicRouting: true,
workerFetch,
});
+
await expect(
- protectedFetch("https://private.example.com/submit", { method: "POST" })
- ).rejects.toThrow("not allowed");
+ protectedFetch("https://api.site.example.com/submit", { method: "POST" })
+ ).resolves.toBeInstanceOf(Response);
+ expect(workerFetch).toHaveBeenCalledOnce();
+ });
+
+ test("marks Cloudflare Resource requests so another site alias can reject reentry", async () => {
+ const workerFetch = vi
+ .fn<typeof fetch>()
+ .mockResolvedValue(new Response("ok"));
+ const protectedFetch = createCloudflareProtectedResourceFetch({
+ projectId: "project-a",
+ ownZoneHostnames: ["site.example.com"],
+ publicRouting: true,
+ workerFetch,
+ });
+
+ await protectedFetch("https://same-site.pages.dev/data");
+ const [, init] = workerFetch.mock.calls[0];
+ expect(
+ isProtectedResourceReentry(
+ new Request("https://same-site.pages.dev/data", init),
+ "project-a"
+ )
+ ).toBe(true);
+ expect(
+ isProtectedResourceReentry(
+ new Request("https://same-site.pages.dev/data"),
+ "project-a"
+ )
+ ).toBe(false);
+ });
+
+ test("keeps the zone-wide block without public routing", async () => {
+ const workerFetch = vi.fn<typeof fetch>();
+ const protectedFetch = createCloudflareProtectedResourceFetch({
+ projectId: "project-a",
+ ownZoneHostnames: ["site.example.com"],
+ workerFetch,
+ });
+
+ expect(() =>
+ protectedFetch.validateDestination(
+ new URL("https://api.site.example.com/submit")
+ )
+ ).toThrow("not allowed");
expect(workerFetch).not.toHaveBeenCalled();
});
@@ -82,6 +150,7 @@ describe("protected Resource fetch", () => {
)
.mockResolvedValueOnce(new Response("ok"));
const protectedFetch = createCloudflareProtectedResourceFetch({
+ projectId: "project-a",
ownZoneHostnames: ["own.example"],
workerFetch,
});
@@ -114,6 +183,7 @@ describe("protected Resource fetch", () => {
})
);
const protectedFetch = createCloudflareProtectedResourceFetch({
+ projectId: "project-a",
ownZoneHostnames: ["own.example"],
workerFetch,
});
@@ -138,6 +208,7 @@ describe("protected Resource fetch", () => {
)
.mockResolvedValueOnce(new Response("ok"));
const protectedFetch = createCloudflareProtectedResourceFetch({
+ projectId: "project-a",
ownZoneHostnames: ["own.example"],
workerFetch,
});
@@ -160,7 +231,9 @@ describe("protected Resource fetch", () => {
expect(new Headers(first?.headers).get("authorization")).toBe(
"Bearer secret"
);
- expect([...new Headers(second?.headers)]).toEqual([]);
+ expect([...new Headers(second?.headers)]).toEqual([
+ ["x-webstudio-protected-resource", "project-a"],
+ ]);
expect(second?.body).toBeUndefined();
expect(second?.redirect).toBe("manual");
});
@@ -173,6 +246,7 @@ describe("protected Resource fetch", () => {
})
);
const protectedFetch = createCloudflareProtectedResourceFetch({
+ projectId: "project-a",
ownZoneHostnames: ["own.example"],
workerFetch,
});
@@ -200,11 +274,33 @@ describe("protected Resource fetch", () => {
const large = createProtectedResourceFetch({
deniedHostnames: [],
transport: async () => ({
- response: new Response(new Uint8Array(2 * 1024 * 1024 + 1)),
+ response: new Response(new Uint8Array(1024 * 1024 + 1)),
}),
});
- await expect(large("https://api.example/data")).rejects.toThrow(
- "too large"
- );
+ await expect(large("https://api.example/data")).rejects.toMatchObject({
+ code: "RESPONSE_TOO_LARGE",
+ });
+ });
+});
+
+test("allows another project but rejects the originating project through any alias", async () => {
+ const resourceFetch = createCloudflareProtectedResourceFetch({
+ projectId: "project-a",
+ ownZoneHostnames: ["site-a.example"],
+ publicRouting: true,
+ workerFetch: async (input, init) => {
+ const request = new Request(input, init);
+ const projectId =
+ new URL(request.url).hostname === "site-b.example"
+ ? "project-b"
+ : "project-a";
+ return new Response(null, {
+ status: isProtectedResourceReentry(request, projectId) ? 508 : 200,
+ });
+ },
});
+ expect((await resourceFetch("https://site-b.example/data")).status).toBe(200);
+ expect((await resourceFetch("https://alias-a.example/data")).status).toBe(
+ 508
+ );
});
diff --git a/packages/sdk/src/protected-resource-fetch.ts b/packages/sdk/src/protected-resource-fetch.ts
index f44e0baa94..94636458c0 100644
--- a/packages/sdk/src/protected-resource-fetch.ts
+++ b/packages/sdk/src/protected-resource-fetch.ts
@@ -1,4 +1,5 @@
import { getDomain } from "tldts";
+import { readLimitedBytes, readResourceResponse } from "./resource-response";
/** Transport for visitor-triggered Resource requests. */
export type ProtectedResourceHop = {
@@ -20,9 +21,20 @@ export type ProtectedResourceFetch = typeof fetch & {
const redirectStatuses = new Set([301, 302, 303, 307, 308]);
const defaultMaxRedirects = 3;
const maxRequestBytes = 25 * 1024 * 1024;
-const maxResponseBytes = 2 * 1024 * 1024;
-/** Include each site's registrable domain to block sibling hosts in its zone. */
+const protectedResourceRequestHeader = "x-webstudio-protected-resource";
+
+/** Project identity survives aliases while allowing calls to other projects.
+ * This cooperative marker is not a sandbox for untrusted code or proxies that strip it.
+ */
+export const isProtectedResourceReentry = (
+ request: Request,
+ projectId: string
+) =>
+ projectId !== "" &&
+ request.headers.get(protectedResourceRequestHeader) === projectId;
+
+/** Preserve the domain-wide policy for Node and Workers without public routing. */
export const getDeniedResourceHostnames = (
hostnames: readonly (string | undefined)[]
) =>
@@ -36,45 +48,11 @@ export const getDeniedResourceHostnames = (
])
);
-const readLimitedBytes = async (
- stream: ReadableStream<Uint8Array> | null,
- maximum: number
-) => {
- if (stream === null) {
- return;
- }
- const reader = stream.getReader();
- const chunks: Uint8Array[] = [];
- let length = 0;
- try {
- while (true) {
- const { done, value } = await reader.read();
- if (done) {
- break;
- }
- length += value.byteLength;
- if (length > maximum) {
- await reader.cancel();
- throw new Error("Resource request or response is too large");
- }
- chunks.push(value);
- }
- } finally {
- reader.releaseLock();
- }
- const bytes = new Uint8Array(length);
- let offset = 0;
- for (const chunk of chunks) {
- bytes.set(chunk, offset);
- offset += chunk.byteLength;
- }
- return bytes;
-};
-
/** Deterministic destination policy; connection and redirect checks stay in the transport. */
export const validateProtectedResourceDestination = (
url: URL,
- deniedHostnames: readonly string[]
+ deniedHostnames: readonly string[],
+ matchSubdomains = true
) => {
if (
(url.protocol !== "http:" && url.protocol !== "https:") ||
@@ -90,7 +68,8 @@ export const validateProtectedResourceDestination = (
const domain = denied.toLowerCase().replace(/\.$/, "");
if (
domain !== "" &&
- (hostname === domain || hostname.endsWith(`.${domain}`))
+ (hostname === domain ||
+ (matchSubdomains && hostname.endsWith(`.${domain}`)))
) {
throw new Error("Resource destination is not allowed");
}
@@ -104,12 +83,16 @@ export const validateProtectedResourceDestination = (
export const createProtectedResourceFetch = ({
transport,
deniedHostnames,
+ matchSubdomains = true,
maxRedirects = defaultMaxRedirects,
}: {
transport: ProtectedResourceTransport;
deniedHostnames: readonly string[];
+ matchSubdomains?: boolean;
maxRedirects?: number;
}): ProtectedResourceFetch => {
+ const validateDestination = (url: URL) =>
+ validateProtectedResourceDestination(url, deniedHostnames, matchSubdomains);
const protectedFetch: typeof fetch = async (input, init) => {
const original = new Request(input, init);
const body = await readLimitedBytes(original.body, maxRequestBytes);
@@ -121,7 +104,7 @@ export const createProtectedResourceFetch = ({
let redirects = 0;
while (true) {
- validateProtectedResourceDestination(url, deniedHostnames);
+ validateDestination(url);
const { response, release } = await transport({
url,
method: original.method,
@@ -132,7 +115,8 @@ export const createProtectedResourceFetch = ({
try {
const location = response.headers.get("location");
if (redirectStatuses.has(response.status) && location !== null) {
- await response.body?.cancel();
+ // A cloned response may have an unread peer; do not wait for it.
+ response.body?.cancel().catch(() => {});
if (redirects >= maxRedirects) {
throw new Error("Resource destination redirected too many times");
}
@@ -147,7 +131,7 @@ export const createProtectedResourceFetch = ({
);
}
const next = new URL(location, url);
- validateProtectedResourceDestination(next, deniedHostnames);
+ validateDestination(next);
if (next.origin !== url.origin) {
if (
(original.method !== "GET" && original.method !== "HEAD") ||
@@ -165,38 +149,28 @@ export const createProtectedResourceFetch = ({
redirects += 1;
continue;
}
- const bytes = await readLimitedBytes(response.body, maxResponseBytes);
- return new Response(
- response.status === 204 ||
- response.status === 205 ||
- response.status === 304
- ? null
- : bytes,
- {
- status: response.status,
- statusText: response.statusText,
- headers: response.headers,
- }
- );
+ return await readResourceResponse(response);
} finally {
await release?.();
}
}
};
- return Object.assign(protectedFetch, {
- validateDestination: (url: URL) =>
- validateProtectedResourceDestination(url, deniedHostnames),
- });
+ return Object.assign(protectedFetch, { validateDestination });
};
/** Cloudflare's outbound proxy checks the destination at each fetch hop. */
export const createCloudflareProtectedResourceFetch = ({
+ projectId,
ownZoneHostnames,
+ publicRouting = false,
workerFetch = fetch,
}: {
- // Cloudflare permits requests to the Worker's own origin, including private
- // origins. The caller must supply every zone hosted by this Worker.
+ projectId: string;
+ // With global_fetch_strictly_public, supply every site hostname to prevent
+ // recursive requests. Without that flag, supply each zone to block origin access.
ownZoneHostnames: readonly [string, ...string[]];
+ // Set true only when the Worker is deployed with global_fetch_strictly_public.
+ publicRouting?: boolean;
workerFetch?: typeof fetch;
}): ProtectedResourceFetch => {
if (
@@ -209,14 +183,21 @@ export const createCloudflareProtectedResourceFetch = ({
}
return createProtectedResourceFetch({
deniedHostnames: ownZoneHostnames,
- transport: async ({ url, method, headers, body, signal }) => ({
- response: await workerFetch(url, {
- method,
- headers,
- body: body?.slice().buffer as ArrayBuffer | undefined,
- signal,
- redirect: "manual",
- }),
- }),
+ matchSubdomains: !publicRouting,
+ transport: async ({ url, method, headers, body, signal }) => {
+ const outgoingHeaders = new Headers(headers);
+ // The hostname list cannot include every self-hosted alias. Mark each hop
+ // so a request routed back to this app is rejected before it runs.
+ outgoingHeaders.set(protectedResourceRequestHeader, projectId);
+ return {
+ response: await workerFetch(url, {
+ method,
+ headers: outgoingHeaders,
+ body: body?.slice().buffer as ArrayBuffer | undefined,
+ signal,
+ redirect: "manual",
+ }),
+ };
+ },
});
};
diff --git a/packages/sdk/src/resource-loader.ts b/packages/sdk/src/resource-loader.ts
index 9e7c98486d..463b2e2a41 100644
--- a/packages/sdk/src/resource-loader.ts
+++ b/packages/sdk/src/resource-loader.ts
@@ -1,4 +1,8 @@
import hash from "@emotion/hash";
+import {
+ readResourceResponse,
+ ResourceResponseTooLargeError,
+} from "./resource-response";
import {
awaitWithSignal,
resolveResources as resolveResourceGraph,
@@ -394,7 +398,11 @@ const transportFailure = ({
retryable,
status,
}: {
- code: "REQUEST_CANCELLED" | "REQUEST_TIMEOUT" | "NETWORK_ERROR";
+ code:
+ | "REQUEST_CANCELLED"
+ | "REQUEST_TIMEOUT"
+ | "NETWORK_ERROR"
+ | "RESPONSE_TOO_LARGE";
message: string;
retryable: boolean;
status: number;
@@ -549,7 +557,14 @@ export const loadResource = async (
signal
);
- let data = await awaitWithSignal(response.text(), signal);
+ // System Resources have their own limits. HTTP Resources share this limit
+ // across Builder, published sites, Form actions, and cached responses.
+ let data = await awaitWithSignal(
+ isLocalResource(href)
+ ? response.text()
+ : readResourceResponse(response).then((response) => response.text()),
+ signal
+ );
try {
// If it looks like JSON and quacks like JSON, then it probably is JSON.
@@ -600,12 +615,23 @@ export const loadResource = async (
retryable: false,
status: 499,
})
- : transportFailure({
- code: "NETWORK_ERROR",
- message: "Resource request failed",
- retryable: true,
- status: 502,
- });
+ : // SDK entry points are bundled separately, so compare the stable code
+ // rather than relying on class identity across those bundles.
+ error instanceof Error &&
+ "code" in error &&
+ error.code === "RESPONSE_TOO_LARGE"
+ ? transportFailure({
+ code: "RESPONSE_TOO_LARGE",
+ message: new ResourceResponseTooLargeError().message,
+ retryable: false,
+ status: 502,
+ })
+ : transportFailure({
+ code: "NETWORK_ERROR",
+ message: "Resource request failed",
+ retryable: true,
+ status: 502,
+ });
if (!didTimeout && !options.signal?.aborted) {
console.error("Resource request failed");
}
@@ -674,6 +700,11 @@ export const loadResources = async (
return load().then((result) =>
rootIds.has(resource.id) &&
result.ok === false &&
+ !(
+ isRecord(result.data) &&
+ isRecord(result.data.error) &&
+ result.data.error.retryable === false
+ ) &&
shouldRetryFailedRoot?.(resource.id, resolvedRequest, result) ===
true &&
!signal?.aborted &&
@@ -748,7 +779,9 @@ export const cachedFetch = async (
// put Cache-Control from request into response
// https://developers.cloudflare.com/workers/reference/how-the-cache-works/#cache-api
// response.clone() does not remove read-only constraint from headers
- response = new Response(response.body, response);
+ // Bound the body before cloning: cache.put consumes its branch of the
+ // stream and would otherwise buffer an unlimited response before loading.
+ response = await readResourceResponse(response);
response.headers.set("Cache-Control", requestCacheControl);
// avoid mutating cached response
await cache.put(cacheKey, response.clone());
diff --git a/packages/sdk/src/resource-response.test.ts b/packages/sdk/src/resource-response.test.ts
new file mode 100644
index 0000000000..ac04f1d3cc
--- /dev/null
+++ b/packages/sdk/src/resource-response.test.ts
@@ -0,0 +1,290 @@
+import { createServer } from "node:http";
+import { gzipSync } from "node:zlib";
+import { afterEach, expect, test, vi } from "vitest";
+import { cachedFetch, loadResource, loadResources } from "./resource-loader";
+import { createProtectedResourceFetch } from "./protected-resource-fetch";
+import { shouldRetryManagedFormDestination } from "./form/server-submission";
+import type { ResourceRequest } from "./schema/resources";
+
+const request: ResourceRequest = {
+ name: "CMS",
+ method: "get",
+ url: "https://cms.example/data",
+ headers: [],
+ searchParams: [],
+};
+const limit = 1024 * 1024;
+const failure = {
+ ok: false,
+ data: { error: { code: "RESPONSE_TOO_LARGE", retryable: false } },
+};
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+for (const protectedTransport of [false, true]) {
+ test.each(["get", "post"] as const)(
+ `limits %s response bytes with protected transport ${protectedTransport}`,
+ async (method) => {
+ let content = "é".repeat(limit / 2);
+ const transport = async () => new Response(content);
+ const resourceFetch = protectedTransport
+ ? createProtectedResourceFetch({
+ deniedHostnames: [],
+ transport: async () => ({ response: await transport() }),
+ })
+ : transport;
+ expect(
+ await loadResource(resourceFetch, { ...request, method })
+ ).toMatchObject({ ok: true, data: content });
+ content += "a";
+ expect(
+ await loadResource(resourceFetch, { ...request, method })
+ ).toMatchObject(failure);
+ }
+ );
+}
+
+test.each([undefined, "1"])(
+ "cancels a streamed overflow with Content-Length %s",
+ async (length) => {
+ let pulls = 0;
+ const cancel = vi.fn();
+ const body = new ReadableStream(
+ {
+ pull(controller) {
+ pulls++;
+ controller.enqueue(new Uint8Array(pulls === 1 ? limit : 1));
+ if (pulls === 3) {
+ controller.close();
+ }
+ },
+ cancel,
+ },
+ { highWaterMark: 0 }
+ );
+ const result = await loadResource(
+ async () =>
+ new Response(body, {
+ headers: length ? { "content-length": length } : {},
+ }),
+ request
+ );
+ expect(result).toMatchObject(failure);
+ expect(cancel).toHaveBeenCalledOnce();
+ expect(pulls).toBe(2);
+ }
+);
+
+test("limits decompressed HTTP bytes, not the compressed Content-Length", async () => {
+ const compressed = gzipSync("x".repeat(limit + 1));
+ const server = createServer((_req, res) => {
+ res.writeHead(200, {
+ "content-encoding": "gzip",
+ "content-length": compressed.length,
+ });
+ res.end(compressed);
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ try {
+ const address = server.address();
+ if (!address || typeof address === "string") {
+ throw new Error("Missing port");
+ }
+ expect(compressed.length).toBeLessThan(limit);
+ expect(
+ await loadResource(fetch, {
+ ...request,
+ url: `http://127.0.0.1:${address.port}`,
+ })
+ ).toMatchObject(failure);
+ } finally {
+ server.closeAllConnections();
+ await new Promise<void>((resolve, reject) =>
+ server.close((error) => (error ? reject(error) : resolve()))
+ );
+ }
+});
+
+test.each([false, true])(
+ "rejects oversized cached Resources (cache hit: %s)",
+ async (hit) => {
+ const cache = {
+ match: vi.fn(async () =>
+ hit ? new Response("x".repeat(limit + 1)) : undefined
+ ),
+ put: vi.fn(),
+ };
+ const upstream = vi.fn(async () => new Response("x".repeat(limit + 1)));
+ vi.stubGlobal("caches", { open: async () => cache });
+ vi.stubGlobal("fetch", upstream);
+ expect(
+ await loadResource((input, init) => cachedFetch("project", input, init), {
+ ...request,
+ headers: [{ name: "cache-control", value: "max-age=60" }],
+ })
+ ).toMatchObject(failure);
+ expect(cache.put).not.toHaveBeenCalled();
+ expect(upstream).toHaveBeenCalledTimes(hit ? 0 : 1);
+ }
+);
+
+test("Form roots do not retry an oversized response and dependencies use the same limit", async () => {
+ const resourceFetch = vi.fn(async () => new Response("x".repeat(limit + 1)));
+ const createRequest = () => ({ ...request, method: "post" as const });
+ const dependencyResults: unknown[] = [];
+ const result = await loadResources(
+ resourceFetch,
+ {
+ resources: [
+ {
+ id: "dependency",
+ outputName: "Dependency",
+ dependencies: [],
+ createRequest,
+ },
+ {
+ id: "action",
+ outputName: "Action",
+ dependencies: ["dependency"],
+ createRequest: (documents) => {
+ dependencyResults.push(documents.get("dependency"));
+ return createRequest();
+ },
+ },
+ ],
+ rootIds: ["action"],
+ },
+ undefined,
+ { shouldRetryFailedRoot: shouldRetryManagedFormDestination }
+ );
+ expect(dependencyResults).toMatchObject([failure]);
+ expect(result).toMatchObject({ Action: failure });
+ expect(resourceFetch).toHaveBeenCalledTimes(2);
+});
+
+test("caches decoded responses with accurate headers and preserves empty responses", async () => {
+ let stored: Response | undefined;
+ let response = new Response("decoded body", {
+ headers: {
+ "content-encoding": "gzip",
+ "content-length": "30",
+ "content-type": "text/plain",
+ },
+ });
+ const cache = {
+ match: async () => stored?.clone(),
+ put: async (_key: URL, value: Response) => {
+ stored = new Response(
+ value.body === null ? null : await value.arrayBuffer(),
+ value
+ );
+ },
+ };
+ const upstream = vi.fn(async () => response);
+ vi.stubGlobal("caches", { open: async () => cache });
+ vi.stubGlobal("fetch", upstream);
+ const resourceFetch: typeof fetch = (input, init) =>
+ cachedFetch("project", input, init);
+ const cachedRequest = {
+ ...request,
+ headers: [{ name: "cache-control", value: "max-age=60" }],
+ };
+ for (let index = 0; index < 2; index++) {
+ expect(await loadResource(resourceFetch, cachedRequest)).toMatchObject({
+ ok: true,
+ data: "decoded body",
+ });
+ }
+ expect(upstream).toHaveBeenCalledOnce();
+ expect(stored?.headers.get("content-encoding")).toBeNull();
+ expect(stored?.headers.get("content-length")).toBeNull();
+ expect(stored?.headers.get("content-type")).toBe("text/plain");
+ expect(stored?.headers.get("cache-control")).toBe("max-age=60");
+ stored = undefined;
+ response = new Response(null, { status: 204 });
+ expect(await loadResource(resourceFetch, cachedRequest)).toMatchObject({
+ ok: true,
+ status: 204,
+ data: "",
+ });
+});
+
+test("classifies a size error by code across bundles, independently of its wording", async () => {
+ const result = await loadResource(async () => {
+ throw Object.assign(new Error("different wording"), {
+ code: "RESPONSE_TOO_LARGE",
+ });
+ }, request);
+ expect(result).toMatchObject(failure);
+ // This exact recovery message was approved as the user-facing size-limit contract.
+ expect(result.statusText).toBe(
+ "Resource response exceeds 1 MiB. Request fewer fields or use pagination."
+ );
+});
+
+test("protected responses describe the decoded body and release the transport", async () => {
+ const release = vi.fn(async () => {});
+ const resourceFetch = createProtectedResourceFetch({
+ deniedHostnames: [],
+ transport: async () => ({
+ response: new Response("decoded body", {
+ status: 201,
+ headers: {
+ "content-encoding": "gzip",
+ "content-length": "30",
+ "content-type": "text/plain",
+ },
+ }),
+ release,
+ }),
+ });
+ const response = await resourceFetch(request.url);
+ expect(response.status).toBe(201);
+ expect(await response.text()).toBe("decoded body");
+ expect(release).toHaveBeenCalledOnce();
+ expect(response.headers.get("content-type")).toBe("text/plain");
+ expect(response.headers.has("content-encoding")).toBe(false);
+ expect(response.headers.has("content-length")).toBe(false);
+});
+
+test.each(["overflow", "redirect"])(
+ "handles %s without waiting for an unread response clone",
+ async (scenario) => {
+ const original =
+ scenario === "overflow"
+ ? new Response("x".repeat(limit + 1))
+ : new Response("redirect", {
+ status: 302,
+ headers: { location: "/next" },
+ });
+ const clone = original.clone();
+ const resourceFetch = createProtectedResourceFetch({
+ deniedHostnames: [],
+ transport: async ({ url }) => ({
+ response: url.pathname === "/next" ? new Response("ok") : clone,
+ }),
+ });
+ const result = loadResource(resourceFetch, request);
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ // Cancelling one tee branch waits for the other; loading must not.
+ expect(
+ await Promise.race([
+ result,
+ new Promise((resolve) => {
+ timer = setTimeout(() => resolve("blocked by unread clone"), 1000);
+ }),
+ ])
+ ).toMatchObject(
+ scenario === "overflow" ? failure : { ok: true, data: "ok" }
+ );
+ expect(clone.body?.locked).toBe(false);
+ } finally {
+ clearTimeout(timer);
+ await original.body?.cancel();
+ await result;
+ }
+ }
+);
diff --git a/packages/sdk/src/resource-response.ts b/packages/sdk/src/resource-response.ts
new file mode 100644
index 0000000000..9a26c4a222
--- /dev/null
+++ b/packages/sdk/src/resource-response.ts
@@ -0,0 +1,44 @@
+import {
+ readBoundedBytes,
+ readableStreamToAsyncIterable,
+} from "@webstudio-is/content-engine/byte-stream";
+
+// Limits decoded body bytes, not Content-Length (which may describe compressed bytes).
+const maxResourceResponseBytes = 1024 * 1024;
+
+export class ResourceResponseTooLargeError extends Error {
+ readonly code = "RESPONSE_TOO_LARGE";
+ constructor() {
+ super(
+ "Resource response exceeds 1 MiB. Request fewer fields or use pagination."
+ );
+ }
+}
+
+export const readLimitedBytes = (
+ stream: ReadableStream<Uint8Array> | null,
+ maximum: number,
+ error = new Error("Resource request or response is too large")
+) => {
+ if (stream === null) {
+ return;
+ }
+ return readBoundedBytes(
+ readableStreamToAsyncIterable(stream),
+ maximum,
+ error
+ );
+};
+
+/** Buffer before cloning or caching, with headers describing the decoded body. */
+export const readResourceResponse = async (response: Response) => {
+ const body = await readLimitedBytes(
+ response.body,
+ maxResourceResponseBytes,
+ new ResourceResponseTooLargeError()
+ );
+ const result = new Response(body, response);
+ result.headers.delete("content-length");
+ result.headers.delete("content-encoding");
+ return result;
+};