Skip to content

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

feat: add queryable Assets resources (#5946)

Oleg Isonenefbc3098c490
diff --git a/.github/workflows/cli-r2-static.yaml b/.github/workflows/cli-r2-static.yaml
index bedb31b9ac..8eb1af737e 100644
--- a/.github/workflows/cli-r2-static.yaml
+++ b/.github/workflows/cli-r2-static.yaml
@@ -61,6 +61,10 @@ jobs:
- name: pnpm deploy
run: pnpm --filter 'ssg-cloudflare-pages' deploy "${{ github.workspace }}/../ssg-template"
+ - name: Verify optional Assets build dependency is omitted
+ run: test ! -e node_modules/@webstudio-is/content-engine/package.json
+ working-directory: ${{ github.workspace }}/../ssg-template
+
- name: Make archive
run: |
tar --use-compress-program="zstd -19" -cf ssg-template.tar.zst ssg-template
diff --git a/.github/workflows/cli-r2.yaml b/.github/workflows/cli-r2.yaml
index e72ed30b14..fcd945c718 100644
--- a/.github/workflows/cli-r2.yaml
+++ b/.github/workflows/cli-r2.yaml
@@ -62,6 +62,10 @@ jobs:
- name: pnpm deploy
run: pnpm --filter 'webstudio-cloudflare-template' deploy "${{ github.workspace }}/../cloudflare-template"
+ - name: Verify optional Assets build dependency is omitted
+ run: test ! -e node_modules/@webstudio-is/content-engine/package.json
+ working-directory: ${{ github.workspace }}/../cloudflare-template
+
- name: Make archive
run: |
tar --use-compress-program="zstd -19" -cf cloudflare-template.tar.zst cloudflare-template
diff --git a/.github/workflows/fixtures-test.yml b/.github/workflows/fixtures-test.yml
index 9062792579..08738b288a 100644
--- a/.github/workflows/fixtures-test.yml
+++ b/.github/workflows/fixtures-test.yml
@@ -65,6 +65,9 @@ jobs:
exit "$sync_status"
fi
+ - name: Build CLI content runtime
+ run: mkdir -p packages/cli/lib && pnpm --filter webstudio build:content-runtime
+
- name: Testing cli build command
run: pnpm --filter='./fixtures/*' run --parallel fixtures:build
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
index 4d09b1a779..c337503a17 100644
--- a/.github/workflows/main.yml
+++ b/.github/workflows/main.yml
@@ -147,7 +147,7 @@ jobs:
const results = [
await assertSize('./fixtures/ssg-cloudflare-pages/dist/client', 356),
await assertSize('./fixtures/react-router-netlify/build/client', 376),
- await assertSize('./fixtures/webstudio-features/build/client', 3312),
+ await assertSize('./fixtures/webstudio-features/build/client', 3684),
]
for (const result of results) {
if (result.passed) {
diff --git a/.oxfmtrc.json b/.oxfmtrc.json
index 89407842ab..09c41567d6 100644
--- a/.oxfmtrc.json
+++ b/.oxfmtrc.json
@@ -11,6 +11,7 @@
"**/*.yaml",
"**/*.toml",
"**/*.jsonc",
- "packages/cli/templates/**"
+ "packages/cli/templates/**",
+ "fixtures/**/__generated__/**"
]
}
diff --git a/apps/builder/.env b/apps/builder/.env
index 0a25a02949..fc32dccaf6 100644
--- a/apps/builder/.env
+++ b/apps/builder/.env
@@ -1,10 +1,10 @@
# To override environment variables, add a .env.development file in the same directory.
# For more details, visit: https://vitejs.dev/guide/env-and-mode#env-files
-DATABASE_URL=postgresql://postgres:pass@localhost:55432/webstudio?pgbouncer=true
-DIRECT_URL=postgresql://postgres:pass@localhost:55432/webstudio
+DATABASE_URL=postgresql://supabase_admin:pass@localhost:55432/webstudio?pgbouncer=true
+DIRECT_URL=postgresql://supabase_admin:pass@localhost:55432/webstudio
PGPORT=55432
POSTGRES_DB=webstudio
-POSTGRES_USER=postgres
+POSTGRES_USER=supabase_admin
POSTGRES_PASSWORD=pass
AUTH_SECRET=0000
diff --git a/apps/builder/app/builder/features/assets/assets.tsx b/apps/builder/app/builder/features/assets/assets.tsx
index bdd98edeea..cd3aeaf22d 100644
--- a/apps/builder/app/builder/features/assets/assets.tsx
+++ b/apps/builder/app/builder/features/assets/assets.tsx
@@ -11,7 +11,7 @@ import {
import { BrushCleaningIcon, PlusIcon } from "@webstudio-is/icons";
import { useRef, useState } from "react";
import { useStore } from "@nanostores/react";
-import { isTextFileAsset } from "@webstudio-is/sdk";
+import { getAssetUrl, isTextFileAsset } from "@webstudio-is/sdk";
import { AssetManager } from "~/builder/shared/asset-manager";
import { AssetUpload, type AssetUploadHandle } from "~/builder/shared/assets";
import { openDeleteUnusedAssetsDialog } from "~/builder/shared/asset-manager/delete-unused-assets";
@@ -22,7 +22,6 @@ import type { Publish } from "~/shared/pubsub";
import { useImageAssetCanvasDrag } from "./use-image-asset-canvas-drag";
import { TextFileEditor } from "~/builder/features/text-file-editor/text-file-editor";
import { CreateTextFileDialog } from "~/builder/features/text-file-editor/create-text-file-dialog";
-import { getAssetUrl } from "~/builder/shared/assets/asset-utils";
export const AssetsPanel = ({
publish,
diff --git a/apps/builder/app/builder/features/pages/custom-metadata.tsx b/apps/builder/app/builder/features/pages/custom-metadata.tsx
index 7d7885614c..0c6e8b788c 100644
--- a/apps/builder/app/builder/features/pages/custom-metadata.tsx
+++ b/apps/builder/app/builder/features/pages/custom-metadata.tsx
@@ -11,12 +11,9 @@ import {
theme,
} from "@webstudio-is/design-system";
import { TrashIcon, PlusIcon } from "@webstudio-is/icons";
-import { isLiteralExpression } from "@webstudio-is/sdk";
+import { isLiteralExpression } from "@webstudio-is/expression";
import { computeExpression } from "@webstudio-is/project-build/runtime";
-import {
- BindingControl,
- BindingPopover,
-} from "~/builder/shared/binding-popover";
+import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
import { $pageRootScope } from "./page-utils";
type Meta = {
@@ -75,45 +72,35 @@ const MetadataItem = (props: {
<Label htmlFor={contentId} css={{ gridArea: "content" }}>
Content
</Label>
- <BindingControl>
- {props.showBindingControls && (
- <BindingPopover
- scope={scope}
- aliases={aliases}
- variant={isLiteralExpression(props.content) ? "default" : "bound"}
- value={props.content}
- onChange={(value) => {
- props.onChange(props.property, value);
- }}
- onRemove={(evaluatedValue) => {
- props.onChange(
- props.property,
- JSON.stringify(evaluatedValue ?? "")
- );
- }}
- />
+ <BindableExpressionControl
+ expression={props.content}
+ value={String(content ?? "")}
+ bound={isLiteralExpression(props.content) === false}
+ allowBindingOverwrite={false}
+ showBinding={props.showBindingControls}
+ scope={scope}
+ aliases={aliases}
+ onChangeValue={(value) =>
+ props.onChange(props.property, JSON.stringify(value))
+ }
+ onChangeExpression={(value) => props.onChange(props.property, value)}
+ onRemove={(value) =>
+ props.onChange(props.property, JSON.stringify(value ?? ""))
+ }
+ renderControl={({ value, readOnly, onChangeValue }) => (
+ <InputErrorsTooltip errors={undefined}>
+ <InputField
+ css={{ gridArea: "content-input" }}
+ disabled={props.disabled || readOnly}
+ color={typeof content !== "string" ? "error" : undefined}
+ id={contentId}
+ property="path"
+ value={value}
+ onChange={(event) => onChangeValue(event.target.value)}
+ />
+ </InputErrorsTooltip>
)}
- <InputErrorsTooltip errors={undefined}>
- <InputField
- css={{
- gridArea: "content-input",
- }}
- disabled={
- props.disabled || isLiteralExpression(props.content) === false
- }
- color={typeof content !== "string" ? "error" : undefined}
- id={contentId}
- property="path"
- value={content}
- onChange={(event) => {
- props.onChange(
- props.property,
- JSON.stringify(event.target.value)
- );
- }}
- />
- </InputErrorsTooltip>
- </BindingControl>
+ />
<Grid
css={{
gridArea: "button",
diff --git a/apps/builder/app/builder/features/pages/page-settings/page-settings.tsx b/apps/builder/app/builder/features/pages/page-settings/page-settings.tsx
index b2cbe1f12f..819f3ea7e5 100644
--- a/apps/builder/app/builder/features/pages/page-settings/page-settings.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings/page-settings.tsx
@@ -5,8 +5,8 @@ import {
findPageByIdOrPath,
getPageDraftabilityError,
isPageDraft,
- isLiteralExpression,
} from "@webstudio-is/sdk";
+import { isLiteralExpression } from "@webstudio-is/expression";
import {
theme,
Button,
diff --git a/apps/builder/app/builder/features/pages/page-settings/section-general.tsx b/apps/builder/app/builder/features/pages/page-settings/section-general.tsx
index fa56b5891a..474bf8bffa 100644
--- a/apps/builder/app/builder/features/pages/page-settings/section-general.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings/section-general.tsx
@@ -16,16 +16,10 @@ import {
rawTheme,
theme,
} from "@webstudio-is/design-system";
-import {
- documentTypes,
- isLiteralExpression,
- type Pages,
-} from "@webstudio-is/sdk";
+import { isLiteralExpression } from "@webstudio-is/expression";
+import { documentTypes, type Pages } from "@webstudio-is/sdk";
import { HomeIcon, InfoCircleIcon } from "@webstudio-is/icons";
-import {
- BindingControl,
- BindingPopover,
-} from "~/builder/shared/binding-popover";
+import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
import { computeExpression } from "@webstudio-is/project-build/runtime";
import { $permissions } from "~/shared/nano-states";
import { $pageRootScope } from "../page-utils";
@@ -123,6 +117,13 @@ const StatusField = ({
}) => {
const id = useId();
const { variableValues, scope, aliases } = useStore($pageRootScope);
+ const parseStatus = (value: string) => {
+ if (value === "") {
+ return;
+ }
+ const number = Number(value);
+ return Number.isNaN(number) || String(number) !== value ? value : number;
+ };
return (
<Grid gap={1}>
<Flex align="center" gap={1}>
@@ -150,42 +151,39 @@ const StatusField = ({
/>
</Tooltip>
</Flex>
- <BindingControl>
- {showBindingControls && (
- <BindingPopover
- scope={scope}
- aliases={aliases}
- variant={isLiteralExpression(value) ? "default" : "bound"}
- value={value}
- onChange={onChange}
- onRemove={(evaluatedValue) =>
- onChange(JSON.stringify(evaluatedValue ?? ""))
- }
- />
+ <BindableExpressionControl
+ expression={value ?? ""}
+ value={String(computeExpression(value, variableValues) ?? "")}
+ bound={value !== undefined && isLiteralExpression(value) === false}
+ allowBindingOverwrite={false}
+ showBinding={showBindingControls}
+ scope={scope}
+ aliases={aliases}
+ parseValue={parseStatus}
+ onChangeValue={(value) => {
+ const status = parseStatus(value);
+ if (status === undefined) {
+ onChange(undefined);
+ return;
+ }
+ onChange(JSON.stringify(status));
+ }}
+ onChangeExpression={onChange}
+ onRemove={(value) => onChange(JSON.stringify(value ?? ""))}
+ renderControl={({ value, readOnly, onChangeValue }) => (
+ <InputErrorsTooltip errors={errors}>
+ <InputField
+ inputMode="numeric"
+ color={errors && "error"}
+ id={id}
+ placeholder="200"
+ disabled={disabled || readOnly}
+ value={value}
+ onChange={(event) => onChangeValue(event.target.value)}
+ />
+ </InputErrorsTooltip>
)}
- <InputErrorsTooltip errors={errors}>
- <InputField
- inputMode="numeric"
- color={errors && "error"}
- id={id}
- placeholder="200"
- disabled={disabled || isLiteralExpression(value) === false}
- value={String(computeExpression(value, variableValues) ?? "")}
- onChange={(event) => {
- if (event.target.value === "") {
- onChange(undefined);
- } else {
- const number = Number(event.target.value);
- const status =
- Number.isNaN(number) || String(number) !== event.target.value
- ? event.target.value
- : number;
- onChange(JSON.stringify(status));
- }
- }}
- />
- </InputErrorsTooltip>
- </BindingControl>
+ />
</Grid>
);
};
@@ -249,30 +247,30 @@ const RedirectField = ({
</Tooltip>
</Flex>
- <BindingControl>
- {showBindingControls && (
- <BindingPopover
- scope={scope}
- aliases={aliases}
- variant={isLiteralExpression(value) ? "default" : "bound"}
- value={value}
- onChange={onChange}
- onRemove={(evaluatedValue) =>
- onChange(JSON.stringify(evaluatedValue ?? ""))
- }
- />
+ <BindableExpressionControl
+ expression={value ?? ""}
+ value={computePageSettingsText(value, variableValues)}
+ bound={value !== undefined && isLiteralExpression(value) === false}
+ allowBindingOverwrite={false}
+ showBinding={showBindingControls}
+ scope={scope}
+ aliases={aliases}
+ onChangeValue={(value) => onChange(JSON.stringify(value))}
+ onChangeExpression={onChange}
+ onRemove={(value) => onChange(JSON.stringify(value ?? ""))}
+ renderControl={({ value, readOnly, onChangeValue }) => (
+ <InputErrorsTooltip errors={errors}>
+ <InputField
+ color={errors && "error"}
+ id={id}
+ placeholder="/another-path"
+ disabled={disabled || readOnly}
+ value={value}
+ onChange={(event) => onChangeValue(event.target.value)}
+ />
+ </InputErrorsTooltip>
)}
- <InputErrorsTooltip errors={errors}>
- <InputField
- color={errors && "error"}
- id={id}
- placeholder="/another-path"
- disabled={disabled || isLiteralExpression(value) === false}
- value={computePageSettingsText(value, variableValues)}
- onChange={(event) => onChange(JSON.stringify(event.target.value))}
- />
- </InputErrorsTooltip>
- </BindingControl>
+ />
</Grid>
);
};
diff --git a/apps/builder/app/builder/features/pages/page-settings/section-search.tsx b/apps/builder/app/builder/features/pages/page-settings/section-search.tsx
index a02b288530..d948239423 100644
--- a/apps/builder/app/builder/features/pages/page-settings/section-search.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings/section-search.tsx
@@ -10,11 +10,8 @@ import {
TextArea,
theme,
} from "@webstudio-is/design-system";
-import { isLiteralExpression } from "@webstudio-is/sdk";
-import {
- BindingControl,
- BindingPopover,
-} from "~/builder/shared/binding-popover";
+import { isLiteralExpression } from "@webstudio-is/expression";
+import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
import { computeExpression } from "@webstudio-is/project-build/runtime";
import type {
PageSettingsErrors,
@@ -44,30 +41,30 @@ const LanguageField = ({
return (
<Grid gap={1}>
<Label htmlFor={id}>Language</Label>
- <BindingControl>
- {showBindingControls && (
- <BindingPopover
- scope={scope}
- aliases={aliases}
- variant={isLiteralExpression(value) ? "default" : "bound"}
- value={value}
- onChange={onChange}
- onRemove={(evaluatedValue) =>
- onChange(JSON.stringify(evaluatedValue ?? ""))
- }
- />
+ <BindableExpressionControl
+ expression={value}
+ value={computePageSettingsText(value, variableValues)}
+ bound={isLiteralExpression(value) === false}
+ allowBindingOverwrite={false}
+ showBinding={showBindingControls}
+ scope={scope}
+ aliases={aliases}
+ onChangeValue={(value) => onChange(JSON.stringify(value))}
+ onChangeExpression={onChange}
+ onRemove={(value) => onChange(JSON.stringify(value ?? ""))}
+ renderControl={({ value, readOnly, onChangeValue }) => (
+ <InputErrorsTooltip errors={errors}>
+ <InputField
+ color={errors && "error"}
+ id={id}
+ placeholder="en-US"
+ disabled={disabled || readOnly}
+ value={value}
+ onChange={(event) => onChangeValue(event.target.value)}
+ />
+ </InputErrorsTooltip>
)}
- <InputErrorsTooltip errors={errors}>
- <InputField
- color={errors && "error"}
- id={id}
- placeholder="en-US"
- disabled={disabled || isLiteralExpression(value) === false}
- value={computePageSettingsText(value, variableValues)}
- onChange={(event) => onChange(JSON.stringify(event.target.value))}
- />
- </InputErrorsTooltip>
- </BindingControl>
+ />
</Grid>
);
};
@@ -146,150 +143,120 @@ export const SearchSection = ({
<Grid gap={1}>
<Label htmlFor={titleId}>Title</Label>
- <BindingControl>
- {showBindingControls && (
- <BindingPopover
- scope={scope}
- aliases={aliases}
- variant={isLiteralExpression(values.title) ? "default" : "bound"}
- value={values.title}
- onChange={(value) => {
- onChange({
- field: "title",
- value,
- });
- }}
- onRemove={(evaluatedValue) => {
- onChange({
- field: "title",
- value: JSON.stringify(evaluatedValue ?? ""),
- });
- }}
- />
+ <BindableExpressionControl
+ expression={values.title}
+ value={title}
+ bound={isLiteralExpression(values.title) === false}
+ allowBindingOverwrite={false}
+ showBinding={showBindingControls}
+ scope={scope}
+ aliases={aliases}
+ onChangeValue={(value) =>
+ onChange({ field: "title", value: JSON.stringify(value) })
+ }
+ onChangeExpression={(value) => onChange({ field: "title", value })}
+ onRemove={(value) =>
+ onChange({ field: "title", value: JSON.stringify(value ?? "") })
+ }
+ renderControl={({ value, readOnly, onChangeValue }) => (
+ <InputErrorsTooltip errors={errors.title}>
+ <InputField
+ color={errors.title && "error"}
+ id={titleId}
+ name="title"
+ placeholder="My awesome project - About"
+ disabled={canEditTitle === false || readOnly}
+ value={value}
+ onChange={(event) => onChangeValue(event.target.value)}
+ />
+ </InputErrorsTooltip>
)}
- <InputErrorsTooltip errors={errors.title}>
- <InputField
- color={errors.title && "error"}
- id={titleId}
- name="title"
- placeholder="My awesome project - About"
- disabled={
- canEditTitle === false ||
- isLiteralExpression(values.title) === false
- }
- value={title}
- onChange={(event) => {
- onChange({
- field: "title",
- value: JSON.stringify(event.target.value),
- });
- }}
- />
- </InputErrorsTooltip>
- </BindingControl>
+ />
</Grid>
<Grid gap={1}>
<Label htmlFor={descriptionId}>Description</Label>
- <BindingControl>
- {showBindingControls && (
- <BindingPopover
- scope={scope}
- aliases={aliases}
- variant={
- isLiteralExpression(values.description) ? "default" : "bound"
- }
- value={values.description}
- onChange={(value) => {
- onChange({
- field: "description",
- value,
- });
- }}
- onRemove={(evaluatedValue) => {
- onChange({
- field: "description",
- value: JSON.stringify(evaluatedValue ?? ""),
- });
- }}
- />
+ <BindableExpressionControl
+ expression={values.description}
+ value={description}
+ bound={isLiteralExpression(values.description) === false}
+ allowBindingOverwrite={false}
+ showBinding={showBindingControls}
+ scope={scope}
+ aliases={aliases}
+ onChangeValue={(value) =>
+ onChange({ field: "description", value: JSON.stringify(value) })
+ }
+ onChangeExpression={(value) =>
+ onChange({ field: "description", value })
+ }
+ onRemove={(value) =>
+ onChange({
+ field: "description",
+ value: JSON.stringify(value ?? ""),
+ })
+ }
+ renderControl={({ value, readOnly, onChangeValue }) => (
+ <InputErrorsTooltip errors={errors.description}>
+ <TextArea
+ color={errors.description ? "error" : undefined}
+ id={descriptionId}
+ name="description"
+ disabled={canEditDescription === false || readOnly}
+ value={value}
+ onChange={onChangeValue}
+ autoGrow
+ maxRows={10}
+ />
+ </InputErrorsTooltip>
)}
- <InputErrorsTooltip errors={errors.description}>
- <TextArea
- color={errors.description ? "error" : undefined}
- id={descriptionId}
- name="description"
- disabled={
- canEditDescription === false ||
- isLiteralExpression(values.description) === false
- }
- value={description}
- onChange={(value) => {
- onChange({
- field: "description",
- value: JSON.stringify(value),
- });
- }}
- autoGrow
- maxRows={10}
- />
- </InputErrorsTooltip>
- </BindingControl>
- <BindingControl>
- <Grid
- flow={"column"}
- gap={1}
- justify={"start"}
- align={"center"}
- css={{ py: theme.spacing[2] }}
- >
- {showBindingControls && (
- <BindingPopover
- scope={scope}
- aliases={aliases}
- variant={
- isLiteralExpression(values.excludePageFromSearch)
- ? "default"
- : "bound"
- }
- value={values.excludePageFromSearch}
- onChange={(value) => {
- onChange({
- field: "excludePageFromSearch",
- value,
- });
- }}
- onRemove={(evaluatedValue) => {
- onChange({
- field: "excludePageFromSearch",
- value: JSON.stringify(evaluatedValue ?? ""),
- });
- }}
+ />
+ <BindableExpressionControl
+ expression={values.excludePageFromSearch}
+ value={excludePageFromSearch}
+ bound={isLiteralExpression(values.excludePageFromSearch) === false}
+ allowBindingOverwrite={false}
+ showBinding={showBindingControls}
+ scope={scope}
+ aliases={aliases}
+ onChangeValue={(value) =>
+ onChange({
+ field: "excludePageFromSearch",
+ value: value.toString(),
+ })
+ }
+ onChangeExpression={(value) =>
+ onChange({ field: "excludePageFromSearch", value })
+ }
+ onRemove={(value) =>
+ onChange({
+ field: "excludePageFromSearch",
+ value: JSON.stringify(value ?? ""),
+ })
+ }
+ renderControl={({ value, readOnly, onChangeValue }) => (
+ <Grid
+ flow={"column"}
+ gap={1}
+ justify={"start"}
+ align={"center"}
+ css={{ py: theme.spacing[2] }}
+ >
+ <Checkbox
+ id={excludePageFromSearchId}
+ disabled={canEditExcludePageFromSearch === false || readOnly}
+ checked={value}
+ onCheckedChange={() => onChangeValue(!value)}
/>
- )}
- <Checkbox
- id={excludePageFromSearchId}
- disabled={
- canEditExcludePageFromSearch === false ||
- isLiteralExpression(values.excludePageFromSearch) === false
- }
- checked={excludePageFromSearch}
- onCheckedChange={() => {
- const newValue = !excludePageFromSearch;
- onChange({
- field: "excludePageFromSearch",
- value: newValue.toString(),
- });
- }}
- />
- <InputErrorsTooltip errors={errors.excludePageFromSearch}>
- <Label htmlFor={excludePageFromSearchId}>
- Exclude this page from search results
- </Label>
- </InputErrorsTooltip>
- </Grid>
- </BindingControl>
+ <InputErrorsTooltip errors={errors.excludePageFromSearch}>
+ <Label htmlFor={excludePageFromSearchId}>
+ Exclude this page from search results
+ </Label>
+ </InputErrorsTooltip>
+ </Grid>
+ )}
+ />
</Grid>
<LanguageField
diff --git a/apps/builder/app/builder/features/pages/page-settings/section-social-image.tsx b/apps/builder/app/builder/features/pages/page-settings/section-social-image.tsx
index 20bfbc90f8..96dc9b7086 100644
--- a/apps/builder/app/builder/features/pages/page-settings/section-social-image.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings/section-social-image.tsx
@@ -7,17 +7,14 @@ import {
InputField,
Text,
} from "@webstudio-is/design-system";
-import {
- BindingControl,
- BindingPopover,
-} from "~/builder/shared/binding-popover";
+import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
import type {
PageSettingsErrors,
PageSettingsValues,
} from "@webstudio-is/project-build/runtime";
import { ImageControl } from "~/shared/project-settings";
import { $assets } from "~/shared/sync/data-stores";
-import { isLiteralExpression } from "@webstudio-is/sdk";
+import { isLiteralExpression } from "@webstudio-is/expression";
import { $pageRootScope } from "../page-utils";
import { ImageInfo } from "../image-info";
import { SocialPreview } from "../social-preview";
@@ -58,47 +55,39 @@ export const SocialImageSection = ({
settings will be used. The optimal dimensions for the image are 1200x630
px or larger with a 1.91:1 aspect ratio.
</Text>
- <BindingControl>
- {showBindingControls && (
- <BindingPopover
- scope={scope}
- aliases={aliases}
- variant={
- isLiteralExpression(values.socialImageUrl) ? "default" : "bound"
- }
- value={values.socialImageUrl}
- onChange={(value) => {
- onChange({
- field: "socialImageUrl",
- value,
- });
- }}
- onRemove={(evaluatedValue) => {
- onChange({
- field: "socialImageUrl",
- value: JSON.stringify(evaluatedValue ?? ""),
- });
- }}
- />
+ <BindableExpressionControl
+ expression={values.socialImageUrl}
+ value={socialImageUrl}
+ bound={isLiteralExpression(values.socialImageUrl) === false}
+ allowBindingOverwrite={false}
+ showBinding={showBindingControls}
+ scope={scope}
+ aliases={aliases}
+ onChangeValue={(value) => {
+ onChange({ field: "socialImageUrl", value: JSON.stringify(value) });
+ onChange({ field: "socialImageAssetId", value: "" });
+ }}
+ onChangeExpression={(value) =>
+ onChange({ field: "socialImageUrl", value })
+ }
+ onRemove={(value) =>
+ onChange({
+ field: "socialImageUrl",
+ value: JSON.stringify(value ?? ""),
+ })
+ }
+ renderControl={({ value, readOnly, onChangeValue }) => (
+ <InputErrorsTooltip errors={errors.socialImageUrl}>
+ <InputField
+ placeholder="https://www.url.com"
+ disabled={disabled || readOnly}
+ color={errors.socialImageUrl && "error"}
+ value={value}
+ onChange={(event) => onChangeValue(event.target.value)}
+ />
+ </InputErrorsTooltip>
)}
- <InputErrorsTooltip errors={errors.socialImageUrl}>
- <InputField
- placeholder="https://www.url.com"
- disabled={
- disabled || isLiteralExpression(values.socialImageUrl) === false
- }
- color={errors.socialImageUrl && "error"}
- value={socialImageUrl}
- onChange={(event) => {
- onChange({
- field: "socialImageUrl",
- value: JSON.stringify(event.target.value),
- });
- onChange({ field: "socialImageAssetId", value: "" });
- }}
- />
- </InputErrorsTooltip>
- </BindingControl>
+ />
<Grid gap={1} flow={"column"}>
<ImageControl
onAssetIdChange={(socialImageAssetId) => {
diff --git a/apps/builder/app/builder/features/pages/page-settings/section-text-content.tsx b/apps/builder/app/builder/features/pages/page-settings/section-text-content.tsx
index e7bae20e50..4f70658662 100644
--- a/apps/builder/app/builder/features/pages/page-settings/section-text-content.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings/section-text-content.tsx
@@ -1,11 +1,8 @@
import { useId } from "react";
import { useStore } from "@nanostores/react";
import { Grid, Label, Text, TextArea } from "@webstudio-is/design-system";
-import { isLiteralExpression } from "@webstudio-is/sdk";
-import {
- BindingControl,
- BindingPopover,
-} from "~/builder/shared/binding-popover";
+import { isLiteralExpression } from "@webstudio-is/expression";
+import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
import { computeExpression } from "@webstudio-is/project-build/runtime";
import type {
PageSettingsErrors,
@@ -31,39 +28,37 @@ export const TextContentSection = ({
<Text color="subtle">The plain text content served for this page.</Text>
<Grid gap={1}>
<Label htmlFor={contentId}>Text</Label>
- <BindingControl>
- <BindingPopover
- scope={scope}
- aliases={aliases}
- variant={isLiteralExpression(values.content) ? "default" : "bound"}
- value={values.content}
- onChange={(value) => {
- onChange({ field: "content", value });
- }}
- onRemove={(evaluatedValue) => {
- onChange({
- field: "content",
- value: JSON.stringify(evaluatedValue ?? ""),
- });
- }}
- />
- <TextArea
- id={contentId}
- color={errors.content ? "error" : undefined}
- disabled={isLiteralExpression(values.content) === false}
- value={String(
- computeExpression(values.content, variableValues) ?? ""
- )}
- onChange={(value) => {
- onChange({
- field: "content",
- value: JSON.stringify(value),
- });
- }}
- autoGrow
- maxRows={20}
- />
- </BindingControl>
+ <BindableExpressionControl
+ expression={values.content}
+ value={String(
+ computeExpression(values.content, variableValues) ?? ""
+ )}
+ bound={isLiteralExpression(values.content) === false}
+ allowBindingOverwrite={false}
+ scope={scope}
+ aliases={aliases}
+ onChangeValue={(value) =>
+ onChange({ field: "content", value: JSON.stringify(value) })
+ }
+ onChangeExpression={(value) => onChange({ field: "content", value })}
+ onRemove={(value) =>
+ onChange({
+ field: "content",
+ value: JSON.stringify(value ?? ""),
+ })
+ }
+ renderControl={({ value, readOnly, onChangeValue }) => (
+ <TextArea
+ id={contentId}
+ color={errors.content ? "error" : undefined}
+ disabled={readOnly}
+ value={value}
+ onChange={onChangeValue}
+ autoGrow
+ maxRows={20}
+ />
+ )}
+ />
</Grid>
</Grid>
);
diff --git a/apps/builder/app/builder/features/pages/template-settings.tsx b/apps/builder/app/builder/features/pages/template-settings.tsx
index 8306a2a17a..701d286adb 100644
--- a/apps/builder/app/builder/features/pages/template-settings.tsx
+++ b/apps/builder/app/builder/features/pages/template-settings.tsx
@@ -1,11 +1,7 @@
import { useState, type JSX } from "react";
import { useStore } from "@nanostores/react";
-import {
- type PageTemplate,
- type Page,
- type Pages,
- isLiteralExpression,
-} from "@webstudio-is/sdk";
+import { type PageTemplate, type Page, type Pages } from "@webstudio-is/sdk";
+import { isLiteralExpression } from "@webstudio-is/expression";
import {
Button,
DialogClose,
diff --git a/apps/builder/app/builder/features/publish/content-database-publish-warning.test.ts b/apps/builder/app/builder/features/publish/content-database-publish-warning.test.ts
new file mode 100644
index 0000000000..215acc77dc
--- /dev/null
+++ b/apps/builder/app/builder/features/publish/content-database-publish-warning.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, test } from "vitest";
+import { getContentDatabasePublishWarning } from "./content-database-publish-warning";
+
+describe("content database publish warning", () => {
+ test("reports bounded files and dynamic resources", () => {
+ expect(
+ getContentDatabasePublishWarning({
+ stats: {
+ usedBytes: 500 * 1024,
+ maxBytes: 500 * 1024,
+ includedDocumentCount: 80,
+ omittedDocumentCount: 20,
+ truncated: true,
+ },
+ potentiallyAffectedResources: [
+ { id: "overview", name: "Blog overview" },
+ { id: "detail", name: "Blog article" },
+ ],
+ hasDynamicValues: true,
+ })
+ ).toEqual({
+ includedDocumentCount: 80,
+ totalDocumentCount: 100,
+ omittedDocumentCount: 20,
+ usedKiB: 500,
+ maxKiB: 500,
+ affectedResourceNames: ["Blog overview", "Blog article"],
+ affectedResourceKind: "dynamic",
+ });
+ });
+
+ test("does not warn for a complete database", () => {
+ expect(
+ getContentDatabasePublishWarning({
+ stats: {
+ usedBytes: 100,
+ maxBytes: 500 * 1024,
+ includedDocumentCount: 5,
+ omittedDocumentCount: 0,
+ truncated: false,
+ },
+ potentiallyAffectedResources: [],
+ hasDynamicValues: false,
+ })
+ ).toBeUndefined();
+ });
+
+ test("identifies statically affected resources", () => {
+ expect(
+ getContentDatabasePublishWarning({
+ stats: {
+ usedBytes: 1025,
+ maxBytes: 2048,
+ includedDocumentCount: 1,
+ omittedDocumentCount: 1,
+ truncated: true,
+ },
+ potentiallyAffectedResources: [{ id: "overview", name: "Overview" }],
+ hasDynamicValues: false,
+ })
+ ).toMatchObject({
+ usedKiB: 2,
+ affectedResourceNames: ["Overview"],
+ affectedResourceKind: "static",
+ });
+ });
+});
diff --git a/apps/builder/app/builder/features/publish/content-database-publish-warning.ts b/apps/builder/app/builder/features/publish/content-database-publish-warning.ts
new file mode 100644
index 0000000000..a7af779359
--- /dev/null
+++ b/apps/builder/app/builder/features/publish/content-database-publish-warning.ts
@@ -0,0 +1,48 @@
+type ContentDatabasePublishDiagnostics = {
+ stats: {
+ usedBytes: number;
+ maxBytes: number;
+ includedDocumentCount: number;
+ omittedDocumentCount: number;
+ truncated: boolean;
+ };
+ potentiallyAffectedResources: { id: string; name: string }[];
+ hasDynamicValues: boolean;
+};
+
+export type ContentDatabasePublishWarning = {
+ includedDocumentCount: number;
+ totalDocumentCount: number;
+ omittedDocumentCount: number;
+ usedKiB: number;
+ maxKiB: number;
+ affectedResourceNames: string[];
+ affectedResourceKind: "dynamic" | "static" | undefined;
+};
+
+export const getContentDatabasePublishWarning = (
+ diagnostics: ContentDatabasePublishDiagnostics | undefined
+) => {
+ if (diagnostics?.stats.truncated !== true) {
+ return;
+ }
+ const { stats } = diagnostics;
+ const affectedResourceNames = diagnostics.potentiallyAffectedResources.map(
+ ({ name }) => name
+ );
+ return {
+ includedDocumentCount: stats.includedDocumentCount,
+ totalDocumentCount:
+ stats.includedDocumentCount + stats.omittedDocumentCount,
+ omittedDocumentCount: stats.omittedDocumentCount,
+ usedKiB: Math.ceil(stats.usedBytes / 1024),
+ maxKiB: Math.ceil(stats.maxBytes / 1024),
+ affectedResourceNames,
+ affectedResourceKind:
+ affectedResourceNames.length === 0
+ ? undefined
+ : diagnostics.hasDynamicValues
+ ? "dynamic"
+ : "static",
+ } satisfies ContentDatabasePublishWarning;
+};
diff --git a/apps/builder/app/builder/features/publish/publish.tsx b/apps/builder/app/builder/features/publish/publish.tsx
index 5751c23b82..cc0aa8ddea 100644
--- a/apps/builder/app/builder/features/publish/publish.tsx
+++ b/apps/builder/app/builder/features/publish/publish.tsx
@@ -75,7 +75,10 @@ import {
import { AddDomain } from "./add-domain";
import { humanizeString } from "~/shared/string-utils";
import { trpcClient, nativeClient } from "~/shared/trpc/trpc-client";
-import { type Templates } from "@webstudio-is/sdk";
+import {
+ createReachableAssetContentCompilationPlan,
+ type Templates,
+} from "@webstudio-is/sdk";
import { DomainCheckbox, domainToPublishName } from "./domain-checkbox";
import { CopyToClipboard } from "~/shared/copy-to-clipboard";
import { $openProjectSettings } from "~/shared/nano-states/project-settings";
@@ -102,6 +105,10 @@ import {
runPrePublishAudit,
type PrePublishAuditFinding,
} from "@webstudio-is/project-build/runtime";
+import {
+ getContentDatabasePublishWarning,
+ type ContentDatabasePublishWarning,
+} from "./content-database-publish-warning";
const PrePublishAuditMessage = ({
finding,
@@ -183,6 +190,64 @@ const getPrePublishAuditMessages = () => {
};
};
+const loadContentDatabasePublishWarning = async (projectId: string) => {
+ const plan = createReachableAssetContentCompilationPlan({
+ props: [...$props.get().values()],
+ dataSources: [...$dataSources.get().values()],
+ resources: [...$resources.get().values()],
+ });
+ if (plan === undefined) {
+ return;
+ }
+ return getContentDatabasePublishWarning(
+ await nativeClient.build.contentDatabasePublishDiagnostics.query({
+ projectId,
+ })
+ );
+};
+
+const ContentDatabasePublishWarningMessage = ({
+ warning,
+}: {
+ warning: ContentDatabasePublishWarning;
+}) => (
+ <>
+ The published content database will include {warning.includedDocumentCount}{" "}
+ of {warning.totalDocumentCount} files ({warning.usedKiB} of {warning.maxKiB}{" "}
+ KiB). {warning.omittedDocumentCount} files will be omitted.
+ {warning.affectedResourceKind === "dynamic" && (
+ <>
+ {" "}
+ Queries with route or variable values may be incomplete in:{" "}
+ {warning.affectedResourceNames.join(", ")}.
+ </>
+ )}
+ {warning.affectedResourceKind === "static" && (
+ <>
+ {" "}
+ Potentially affected Assets resources:{" "}
+ {warning.affectedResourceNames.join(", ")}.
+ </>
+ )}
+ </>
+);
+
+const showContentDatabasePublishWarning = async ({
+ projectId,
+ setWarning,
+}: {
+ projectId: Project["id"];
+ setWarning: (warning: JSX.Element) => void;
+}) => {
+ const warning = await loadContentDatabasePublishWarning(projectId);
+ if (warning === undefined) {
+ return;
+ }
+ const message = <ContentDatabasePublishWarningMessage warning={warning} />;
+ toast.warn(message);
+ setWarning(message);
+};
+
type ChangeProjectDomainProps = {
project: Project;
projectState: "idle" | "submitting";
@@ -412,12 +477,20 @@ const ChangeProjectDomain = ({
};
const $restrictedFeatures = computed(
- [$pages, $projectSettings, $dataSources, $instances, $permissions],
- (pages, projectSettings, dataSources, instances, permissions) =>
+ [
+ $pages,
+ $projectSettings,
+ $dataSources,
+ $resources,
+ $instances,
+ $permissions,
+ ],
+ (pages, projectSettings, dataSources, resources, instances, permissions) =>
getRestrictedFeatures({
pages,
projectSettings,
dataSources,
+ resources,
instances,
permissions,
})
@@ -645,6 +718,20 @@ const Publish = ({
}
startTransition(async () => {
+ try {
+ await showContentDatabasePublishWarning({
+ projectId: project.id,
+ setWarning: setPublishWarning,
+ });
+ } catch (error) {
+ const message =
+ error instanceof Error
+ ? error.message
+ : "Content database validation failed";
+ toast.error(message);
+ setPublishError(message);
+ return;
+ }
await publish(domains);
});
};
@@ -795,6 +882,11 @@ const PublishStatic = ({
try {
setIsPendingOptimistic(true);
+ await showContentDatabasePublishWarning({
+ projectId,
+ setWarning: setPublishWarning,
+ });
+
const result = await nativeClient.domain.publish.mutate({
projectId,
destination: "static",
diff --git a/apps/builder/app/builder/features/publish/restricted-features.test.ts b/apps/builder/app/builder/features/publish/restricted-features.test.ts
index b53f71bbef..32222e91b6 100644
--- a/apps/builder/app/builder/features/publish/restricted-features.test.ts
+++ b/apps/builder/app/builder/features/publish/restricted-features.test.ts
@@ -6,6 +6,7 @@ import {
type Instance,
type Page,
type Pages,
+ type Resource,
} from "@webstudio-is/sdk";
import {
getRestrictedFeatures,
@@ -68,18 +69,21 @@ const getFeatures = ({
projectSettings,
permissions,
dataSources = new Map<string, DataSource>(),
+ resources = new Map<string, Resource>(),
instances = new Map<string, Instance>(),
}: {
pages: Pages | undefined;
projectSettings?: ProjectSettings;
permissions: Partial<RestrictedFeaturesPermissions>;
dataSources?: Map<string, DataSource>;
+ resources?: Map<string, Resource>;
instances?: Map<string, Instance>;
}) =>
getRestrictedFeatures({
pages,
projectSettings,
dataSources,
+ resources,
instances,
permissions: { ...defaultPermissions, ...permissions },
});
@@ -219,4 +223,64 @@ describe("getRestrictedFeatures", () => {
"Resource variable",
]);
});
+
+ test("identifies an Assets resource as a restricted custom-domain feature", () => {
+ const resources = new Map<string, Resource>([
+ [
+ "assets-resource",
+ {
+ id: "assets-resource",
+ name: "Assets",
+ control: "system",
+ method: "post",
+ url: '"/$resources/assets"',
+ searchParams: [],
+ headers: [],
+ body: "({ query: {} })",
+ },
+ ],
+ ]);
+ const dataSources = new Map<string, DataSource>([
+ [
+ "assets-variable",
+ {
+ type: "resource",
+ id: "assets-variable",
+ resourceId: "assets-resource",
+ scopeInstanceId: homePage.rootInstanceId,
+ name: "assets",
+ },
+ ],
+ ]);
+ const instances = new Map<string, Instance>([
+ [
+ homePage.rootInstanceId,
+ {
+ type: "instance",
+ id: homePage.rootInstanceId,
+ component: "ws:element",
+ children: [],
+ },
+ ],
+ ]);
+ const features = getFeatures({
+ pages: createPages(),
+ permissions: { allowDynamicData: false },
+ dataSources,
+ resources,
+ instances,
+ });
+
+ expect([...features.keys()]).toEqual(["Assets resource"]);
+
+ expect(
+ getFeatures({
+ pages: createPages(),
+ permissions: { allowDynamicData: true },
+ dataSources,
+ resources,
+ instances,
+ }).size
+ ).toBe(0);
+ });
});
diff --git a/apps/builder/app/builder/features/publish/restricted-features.ts b/apps/builder/app/builder/features/publish/restricted-features.ts
index 884631bf16..3b73a28794 100644
--- a/apps/builder/app/builder/features/publish/restricted-features.ts
+++ b/apps/builder/app/builder/features/publish/restricted-features.ts
@@ -1,10 +1,12 @@
import type { ReactNode } from "react";
import {
getPublishablePages,
+ isAssetsResource,
isPathnamePattern,
type DataSource,
type Instance,
type Pages,
+ type Resources,
} from "@webstudio-is/sdk";
import { findPageAndSelectorByInstanceId } from "@webstudio-is/project-build/runtime";
import type { ProjectSettings } from "@webstudio-is/project-build";
@@ -27,12 +29,14 @@ export const getRestrictedFeatures = ({
pages,
projectSettings,
dataSources,
+ resources,
instances,
permissions,
}: {
pages: Pages | undefined;
projectSettings?: ProjectSettings;
dataSources: Map<string, DataSource>;
+ resources: Resources;
instances: Map<string, Instance>;
permissions: RestrictedFeaturesPermissions;
}) => {
@@ -89,9 +93,15 @@ export const getRestrictedFeatures = ({
if (publishablePageIds.has(navigate.pageId) === false) {
continue;
}
- features.set("Resource variable", {
- navigate,
- });
+ const resource = resources.get(dataSource.resourceId);
+ features.set(
+ resource !== undefined && isAssetsResource(resource)
+ ? "Assets resource"
+ : "Resource variable",
+ {
+ navigate,
+ }
+ );
}
}
}
diff --git a/apps/builder/app/builder/features/settings-panel/asset-query-form.test.tsx b/apps/builder/app/builder/features/settings-panel/asset-query-form.test.tsx
new file mode 100644
index 0000000000..de6a52c790
--- /dev/null
+++ b/apps/builder/app/builder/features/settings-panel/asset-query-form.test.tsx
@@ -0,0 +1,77 @@
+import { createRoot, type Root } from "react-dom/client";
+import { act } from "react-dom/test-utils";
+import { afterEach, expect, test, vi } from "vitest";
+import {
+ createAssetQueryJsonSchema,
+ createAssetResourceOpenApi,
+} from "@webstudio-is/protocol/asset-resource-api";
+import { AssetQueryForm, __testing__ } from "./asset-query-form";
+
+const { loadAssetQueryDefinition } = __testing__;
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+let root: Root | undefined;
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = undefined;
+ document.body.innerHTML = "";
+});
+
+test("renders a centered message while the OpenAPI description is loading", () => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ act(() => {
+ root?.render(
+ <AssetQueryForm
+ scope={{}}
+ aliases={new Map()}
+ fetchDescription={() => new Promise(() => {})}
+ />
+ );
+ });
+
+ expect(container.textContent).toContain("Loading query editor…");
+});
+
+test("loads the external query schema declared by OpenAPI", async () => {
+ const openApi = createAssetResourceOpenApi({
+ builderSessionCookieName: "session",
+ querySchemaReference: "/rest/assets/query-schema.json",
+ });
+ const querySchema = createAssetQueryJsonSchema({
+ catalog: {
+ format: "webstudio-builder-asset-field-catalog",
+ version: 1,
+ canonicalRevision: `sha256:${"a".repeat(64)}`,
+ documentCount: 1,
+ fields: {
+ title: {
+ queryPath: ["properties", "title"],
+ types: ["string"],
+ occurrences: 1,
+ },
+ },
+ },
+ });
+ const fetchDescription = vi.fn(async (input: RequestInfo | URL) =>
+ Response.json(
+ String(input).includes("query-schema.json") ? querySchema : openApi
+ )
+ );
+
+ const definition = await loadAssetQueryDefinition(fetchDescription);
+
+ expect(fetchDescription).toHaveBeenCalledTimes(2);
+ expect(fetchDescription.mock.calls[1][0]).toBe(
+ "http://localhost:3000/rest/assets/query-schema.json"
+ );
+ expect(definition.fields).toContainEqual(
+ expect.objectContaining({ path: ["properties", "title"] })
+ );
+});
diff --git a/apps/builder/app/builder/features/settings-panel/asset-query-form.tsx b/apps/builder/app/builder/features/settings-panel/asset-query-form.tsx
new file mode 100644
index 0000000000..578e1c6bf2
--- /dev/null
+++ b/apps/builder/app/builder/features/settings-panel/asset-query-form.tsx
@@ -0,0 +1,210 @@
+import { useEffect, useMemo, useState } from "react";
+import { useStore } from "@nanostores/react";
+import {
+ createDefaultStructuredAssetQueryResourceConfiguration,
+ createStructuredAssetQueryResourceBody,
+ parseStructuredAssetQueryResourceBody,
+ type Resource,
+ type StructuredAssetQueryFilterBinding,
+ type StructuredAssetQueryResourceConfiguration,
+} from "@webstudio-is/sdk";
+import { assetsOpenApiUrl } from "@webstudio-is/sdk/runtime";
+import {
+ addConfiguredQueryFields,
+ createQuerySourceCodec,
+ loadOpenApiQueryDefinition,
+ type QueryDefinition,
+} from "@webstudio-is/query-builder";
+import {
+ getQueryConditions,
+ getQueryFieldKey,
+} from "@webstudio-is/query-builder/runtime";
+import { Text, theme } from "@webstudio-is/design-system";
+import { $assets } from "~/shared/sync/data-stores";
+import { BindableQueryBuilder } from "~/builder/shared/query-builder";
+import { fetch as builderFetch } from "~/shared/fetch.client";
+import { CenteredPanelMessage, Row } from "./shared";
+
+type AssetQueryDefinition = QueryDefinition<
+ string,
+ StructuredAssetQueryFilterBinding["operator"]
+>;
+
+const defaultConfiguration: StructuredAssetQueryResourceConfiguration =
+ createDefaultStructuredAssetQueryResourceConfiguration();
+
+const normalizeConfiguration = (
+ value: StructuredAssetQueryResourceConfiguration
+): StructuredAssetQueryResourceConfiguration => ({
+ ...value,
+ where: "field" in value.where ? { all: [value.where] } : value.where,
+});
+
+const loadAssetQueryDefinition = async (
+ fetchDescription: typeof globalThis.fetch
+) => {
+ const response = await fetchDescription(assetsOpenApiUrl);
+ if (response.ok === false) {
+ throw new Error("Builder Assets OpenAPI request failed");
+ }
+ const descriptionUrl =
+ response.url || new URL(assetsOpenApiUrl, window.location.href).href;
+ const descriptionOrigin = new URL(descriptionUrl).origin;
+ const definition = await loadOpenApiQueryDefinition({
+ document: await response.json(),
+ documentUrl: descriptionUrl,
+ operationId: "queryAssets",
+ loadReference: async (url) => {
+ if (new URL(url).origin !== descriptionOrigin) {
+ throw new Error("Cross-origin OpenAPI references are unsupported");
+ }
+ const reference = await fetchDescription(url);
+ if (reference.ok === false) {
+ throw new Error("Builder Assets query schema request failed");
+ }
+ return await reference.json();
+ },
+ });
+ return definition as AssetQueryDefinition;
+};
+
+export const AssetQueryForm = ({
+ resource,
+ scope,
+ aliases,
+ sourceContainer,
+ fetchDescription = builderFetch,
+}: {
+ resource?: Resource;
+ scope: Record<string, unknown>;
+ aliases: Map<string, string>;
+ sourceContainer?: Element | null;
+ fetchDescription?: typeof globalThis.fetch;
+}) => {
+ const assets = useStore($assets);
+ const initial = useMemo(
+ () =>
+ parseStructuredAssetQueryResourceBody(resource?.body) ??
+ defaultConfiguration,
+ [resource?.body]
+ );
+ const [configuration, setConfiguration] =
+ useState<StructuredAssetQueryResourceConfiguration>(() =>
+ normalizeConfiguration(initial)
+ );
+ const [baseDefinition, setBaseDefinition] = useState<AssetQueryDefinition>();
+ const [descriptionError, setDescriptionError] = useState<string>();
+ const configuredPaths = useMemo(
+ () =>
+ [
+ ...getQueryConditions<StructuredAssetQueryFilterBinding>(
+ configuration.where
+ ).map(({ field }) => field),
+ ...configuration.sort.map(({ field }) => field),
+ ...(configuration.output.mode === "fields"
+ ? configuration.output.fields
+ : []),
+ ].sort((left, right) =>
+ getQueryFieldKey(left).localeCompare(getQueryFieldKey(right))
+ ),
+ [configuration]
+ );
+ const definition = useMemo(
+ () =>
+ baseDefinition === undefined
+ ? undefined
+ : addConfiguredQueryFields({
+ definition: baseDefinition,
+ paths: configuredPaths,
+ fallbackType: "string",
+ }),
+ [baseDefinition, configuredPaths]
+ );
+ const configurationError = useMemo(() => {
+ if (definition === undefined) {
+ return;
+ }
+ try {
+ createQuerySourceCodec<
+ string,
+ StructuredAssetQueryFilterBinding["operator"],
+ StructuredAssetQueryResourceConfiguration
+ >(definition).format(configuration);
+ } catch {
+ return "Complete every Assets query field.";
+ }
+ }, [configuration, definition]);
+
+ useEffect(() => {
+ setConfiguration(normalizeConfiguration(initial));
+ }, [initial, resource?.id]);
+
+ const body =
+ configurationError === undefined
+ ? createStructuredAssetQueryResourceBody(configuration)
+ : (resource?.body ?? "");
+
+ useEffect(() => {
+ let ignore = false;
+ loadAssetQueryDefinition(fetchDescription)
+ .then((definition) => {
+ if (ignore) {
+ return;
+ }
+ setBaseDefinition(definition);
+ setDescriptionError(undefined);
+ })
+ .catch(() => {
+ if (ignore === false) {
+ setDescriptionError("Unable to load the Assets API description.");
+ }
+ });
+ return () => {
+ ignore = true;
+ };
+ }, [assets, fetchDescription]);
+
+ return (
+ <>
+ <input
+ type="hidden"
+ name="asset-query-valid"
+ value={configurationError === undefined ? "true" : "false"}
+ />
+ <input type="hidden" name="header-name" value="Content-Type" />
+ <input type="hidden" name="header-value" value='"application/json"' />
+ <input type="hidden" name="body" value={body} />
+ {descriptionError !== undefined ? (
+ <CenteredPanelMessage color="destructive">
+ {descriptionError}
+ </CenteredPanelMessage>
+ ) : definition !== undefined ? (
+ <BindableQueryBuilder<
+ string,
+ StructuredAssetQueryFilterBinding["operator"],
+ StructuredAssetQueryResourceConfiguration
+ >
+ key={resource?.id}
+ value={configuration}
+ capabilities={definition}
+ scope={scope}
+ aliases={aliases}
+ sourceContainer={sourceContainer}
+ sectionPaddingInline={theme.panel.paddingInline}
+ onChange={(value) => {
+ setConfiguration(value);
+ }}
+ />
+ ) : (
+ <CenteredPanelMessage>Loading query editor…</CenteredPanelMessage>
+ )}
+ {descriptionError === undefined && configurationError !== undefined && (
+ <Row>
+ <Text color="destructive">{configurationError}</Text>
+ </Row>
+ )}
+ </>
+ );
+};
+
+export const __testing__ = { loadAssetQueryDefinition };
diff --git a/apps/builder/app/builder/features/settings-panel/content-database-diagnostics.test.ts b/apps/builder/app/builder/features/settings-panel/content-database-diagnostics.test.ts
new file mode 100644
index 0000000000..0d99654610
--- /dev/null
+++ b/apps/builder/app/builder/features/settings-panel/content-database-diagnostics.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, test } from "vitest";
+import { isDatabaseSizeNearLimit } from "./content-database-diagnostics";
+
+describe("content database diagnostics", () => {
+ test("warns when the database reaches 90% of its limit", () => {
+ expect(isDatabaseSizeNearLimit({ usedBytes: 899, maxBytes: 1_000 })).toBe(
+ false
+ );
+ expect(isDatabaseSizeNearLimit({ usedBytes: 900, maxBytes: 1_000 })).toBe(
+ true
+ );
+ expect(isDatabaseSizeNearLimit({ usedBytes: 1_000, maxBytes: 1_000 })).toBe(
+ true
+ );
+ });
+});
diff --git a/apps/builder/app/builder/features/settings-panel/content-database-diagnostics.tsx b/apps/builder/app/builder/features/settings-panel/content-database-diagnostics.tsx
new file mode 100644
index 0000000000..1f86e15e8d
--- /dev/null
+++ b/apps/builder/app/builder/features/settings-panel/content-database-diagnostics.tsx
@@ -0,0 +1,70 @@
+import type { AssetQueryPreviewDiagnostics } from "@webstudio-is/content-engine";
+import { PanelBanner, Text } from "@webstudio-is/design-system";
+import prettyBytes from "pretty-bytes";
+import {
+ RequestDiagnosticsContent,
+ RequestDiagnosticsRow,
+ RequestDiagnosticsTable,
+} from "./request-inspector";
+
+const databaseSizeWarningRatio = 0.9;
+
+export const isDatabaseSizeNearLimit = ({
+ usedBytes,
+ maxBytes,
+}: Pick<AssetQueryPreviewDiagnostics, "usedBytes" | "maxBytes">) =>
+ usedBytes >= maxBytes * databaseSizeWarningRatio;
+
+export const ContentDatabaseDiagnostics = ({
+ value,
+}: {
+ value: AssetQueryPreviewDiagnostics;
+}) => {
+ const totalDocumentCount =
+ value.includedDocumentCount + value.omittedDocumentCount;
+ const candidateFilesLabel = `${totalDocumentCount} candidate ${totalDocumentCount === 1 ? "file" : "files"}`;
+ const omittedFilesLabel = `${value.omittedDocumentCount} ${value.omittedDocumentCount === 1 ? "file" : "files"}`;
+ const isNearLimit = isDatabaseSizeNearLimit(value);
+ return (
+ <RequestDiagnosticsContent>
+ <PanelBanner variant={value.truncated ? "warning" : "success"}>
+ <Text>
+ {value.truncated
+ ? `${value.includedDocumentCount} of ${candidateFilesLabel} fit in the content database. ${omittedFilesLabel} may be omitted from published query results.`
+ : totalDocumentCount === 1
+ ? "The candidate file fits in the content database."
+ : `All ${candidateFilesLabel} fit in the content database.`}
+ </Text>
+ </PanelBanner>
+ <RequestDiagnosticsTable>
+ <RequestDiagnosticsRow label="Scope" value="Query preview" />
+ <RequestDiagnosticsRow
+ label="Status"
+ value={value.truncated ? "Truncated" : "Complete"}
+ />
+ <RequestDiagnosticsRow
+ label="Database size"
+ value={prettyBytes(value.usedBytes)}
+ valueColor={isNearLimit ? "destructive" : undefined}
+ description="To reduce the database size, select only the output fields your pages use, narrow filters to fewer files, and avoid full file content when a byte range is enough."
+ />
+ <RequestDiagnosticsRow
+ label="Database limit"
+ value={prettyBytes(value.maxBytes)}
+ />
+ <RequestDiagnosticsRow
+ label="Estimated full size"
+ value={prettyBytes(value.unboundedBytes)}
+ />
+ <RequestDiagnosticsRow
+ label="Included files"
+ value={value.includedDocumentCount}
+ />
+ <RequestDiagnosticsRow
+ label="Omitted files"
+ value={value.omittedDocumentCount}
+ />
+ </RequestDiagnosticsTable>
+ </RequestDiagnosticsContent>
+ );
+};
diff --git a/apps/builder/app/builder/features/settings-panel/controls/boolean.tsx b/apps/builder/app/builder/features/settings-panel/controls/boolean.tsx
index 6433d5de6b..31abe5bd52 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/boolean.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/boolean.tsx
@@ -1,18 +1,9 @@
-import { useStore } from "@nanostores/react";
import { Grid, Switch, theme } from "@webstudio-is/design-system";
-import {
- BindingControl,
- BindingPopover,
-} from "~/builder/shared/binding-popover";
+import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
import { validatePrimitiveValue } from "@webstudio-is/project-build/runtime";
-import {
- type ControlProps,
- $selectedInstanceScope,
- updateExpressionValue,
- useBindingState,
- humanizeAttribute,
-} from "../shared";
+import { type ControlProps, humanizeAttribute } from "../shared";
import { PropertyLabel } from "../property-label";
+import { useBindableControl } from "./use-bindable-control";
export const BooleanControl = ({
meta,
@@ -22,12 +13,10 @@ export const BooleanControl = ({
onChange,
}: ControlProps<"boolean">) => {
const label = humanizeAttribute(meta.label || propName);
- const { scope, aliases } = useStore($selectedInstanceScope);
- const expression =
- prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
- const { overwritable, variant } = useBindingState(
- prop?.type === "expression" ? prop.value : undefined
- );
+ const binding = useBindableControl({
+ boundExpression: prop?.type === "expression" ? prop.value : undefined,
+ fallbackExpression: JSON.stringify(computedValue),
+ });
return (
<Grid
@@ -39,33 +28,27 @@ export const BooleanControl = ({
align="center"
gap="2"
>
- <PropertyLabel name={propName} readOnly={overwritable === false} />
- <BindingControl>
- <Switch
- disabled={overwritable === false}
- checked={Boolean(computedValue ?? false)}
- onCheckedChange={(value) => {
- if (prop?.type === "expression") {
- updateExpressionValue(prop.value, value);
- } else {
- onChange({ type: "boolean", value });
- }
- }}
- />
- <BindingPopover
- scope={scope}
- aliases={aliases}
- validate={(value) => validatePrimitiveValue(value, label)}
- variant={variant}
- value={expression}
- onChange={(newExpression) =>
- onChange({ type: "expression", value: newExpression })
- }
- onRemove={(evaluatedValue) =>
- onChange({ type: "boolean", value: Boolean(evaluatedValue) })
- }
- />
- </BindingControl>
+ <PropertyLabel
+ name={propName}
+ readOnly={binding.bindingState.overwritable === false}
+ />
+ <BindableExpressionControl
+ {...binding}
+ value={Boolean(computedValue ?? false)}
+ validate={(value) => validatePrimitiveValue(value, label)}
+ onChangeValue={(value) => onChange({ type: "boolean", value })}
+ onChangeExpression={(value) => onChange({ type: "expression", value })}
+ onRemove={(value) =>
+ onChange({ type: "boolean", value: Boolean(value) })
+ }
+ renderControl={({ value, readOnly, onChangeValue }) => (
+ <Switch
+ disabled={readOnly}
+ checked={value}
+ onCheckedChange={onChangeValue}
+ />
+ )}
+ />
</Grid>
);
};
diff --git a/apps/builder/app/builder/features/settings-panel/controls/check.tsx b/apps/builder/app/builder/features/settings-panel/controls/check.tsx
index c399b3de68..c71ed2e85a 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/check.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/check.tsx
@@ -1,20 +1,14 @@
import { useId } from "react";
-import { useStore } from "@nanostores/react";
import { Checkbox, CheckboxAndLabel } from "@webstudio-is/design-system";
-import {
- BindingControl,
- BindingPopover,
-} from "~/builder/shared/binding-popover";
+import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
import {
type ControlProps,
VerticalLayout,
Label,
- $selectedInstanceScope,
- updateExpressionValue,
- useBindingState,
humanizeAttribute,
} from "../shared";
import { PropertyLabel } from "../property-label";
+import { useBindableControl } from "./use-bindable-control";
const add = (array: string[], item: string) => {
if (array.includes(item)) {
@@ -46,66 +40,61 @@ export const CheckControl = ({
const id = useId();
const label = humanizeAttribute(meta.label || propName);
- const { scope, aliases } = useStore($selectedInstanceScope);
- const expression =
- prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
- const { overwritable, variant } = useBindingState(
- prop?.type === "expression" ? prop.value : undefined
- );
+ const binding = useBindableControl({
+ boundExpression: prop?.type === "expression" ? prop.value : undefined,
+ fallbackExpression: JSON.stringify(computedValue),
+ });
return (
<VerticalLayout
label={
- <PropertyLabel name={propName} readOnly={overwritable === false} />
+ <PropertyLabel
+ name={propName}
+ readOnly={binding.bindingState.overwritable === false}
+ />
}
>
- <BindingControl>
- {options.map((option) => (
- <CheckboxAndLabel key={option}>
- <Checkbox
- disabled={overwritable === false}
- checked={value.includes(option)}
- onCheckedChange={(checked) => {
- const newValue = checked
- ? add(value, option)
- : remove(value, option);
- if (prop?.type === "expression") {
- updateExpressionValue(prop.value, newValue);
- } else {
- onChange({ type: "string[]", value: newValue });
- }
- }}
- id={`${id}:${option}`}
- />
- <Label htmlFor={`${id}:${option}`}>{option}</Label>
- </CheckboxAndLabel>
- ))}
- <BindingPopover
- scope={scope}
- aliases={aliases}
- validate={(value) => {
- const valid =
- Array.isArray(value) &&
- value.every((item) => typeof item === "string");
- if (value !== undefined && valid === false) {
- return `${label} expects an array of strings`;
- }
- }}
- variant={variant}
- value={expression}
- onChange={(newExpression) =>
- onChange({ type: "expression", value: newExpression })
+ <BindableExpressionControl
+ {...binding}
+ value={value}
+ onChangeValue={(value) => onChange({ type: "string[]", value })}
+ onChangeExpression={(value) => onChange({ type: "expression", value })}
+ validate={(value) => {
+ const valid =
+ Array.isArray(value) &&
+ value.every((item) => typeof item === "string");
+ if (value !== undefined && valid === false) {
+ return `${label} expects an array of strings`;
}
- onRemove={(evaluatedValue) =>
- onChange({
- type: "string[]",
- value: Array.isArray(evaluatedValue)
- ? evaluatedValue.map((item) => String(item))
- : [],
- })
- }
- />
- </BindingControl>
+ }}
+ onRemove={(value) =>
+ onChange({
+ type: "string[]",
+ value: Array.isArray(value)
+ ? value.map((item) => String(item))
+ : [],
+ })
+ }
+ renderControl={({ value, readOnly, onChangeValue }) => (
+ <>
+ {options.map((option) => (
+ <CheckboxAndLabel key={option}>
+ <Checkbox
+ disabled={readOnly}
+ checked={value.includes(option)}
+ onCheckedChange={(checked) =>
+ onChangeValue(
+ checked ? add(value, option) : remove(value, option)
+ )
+ }
+ id={`${id}:${option}`}
+ />
+ <Label htmlFor={`${id}:${option}`}>{option}</Label>
+ </CheckboxAndLabel>
+ ))}
+ </>
+ )}
+ />
</VerticalLayout>
);
};
diff --git a/apps/builder/app/builder/features/settings-panel/controls/code.tsx b/apps/builder/app/builder/features/settings-panel/controls/code.tsx
index 60cde42765..6d6298697a 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/code.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/code.tsx
@@ -1,4 +1,3 @@
-import { useStore } from "@nanostores/react";
import { useState } from "react";
import {
Button,
@@ -16,9 +15,9 @@ import {
import { InfoCircleIcon } from "@webstudio-is/icons";
import { CodeEditor } from "~/shared/code-editor";
import {
- BindingControl,
- BindingPopover,
-} from "~/builder/shared/binding-popover";
+ BindableExpressionControl,
+ updateBindableValue,
+} from "~/builder/shared/bindable-expression";
import {
validateHtmlEmbedCode,
type HtmlEmbedCodeError,
@@ -28,12 +27,10 @@ import { useDraftValue } from "~/builder/shared/use-draft-value";
import {
type ControlProps,
VerticalLayout,
- updateExpressionValue,
- $selectedInstanceScope,
- useBindingState,
humanizeAttribute,
} from "../shared";
import { PropertyLabel } from "../property-label";
+import { useBindableControl } from "./use-bindable-control";
export type CodeIssue = HtmlEmbedCodeError & {
severity?: "error" | "warning";
};
@@ -141,21 +138,19 @@ export const CodeControl = ({
}
}
- if (prop?.type === "expression") {
- updateExpressionValue(prop.value, storedValue);
- } else {
- onChange({ type: "string", value: storedValue });
- }
+ updateBindableValue({
+ expression: prop?.type === "expression" ? prop.value : undefined,
+ value: storedValue,
+ onChangeValue: (value) => onChange({ type: "string", value }),
+ });
},
{ autoSave: behavior?.autoSave ?? true }
);
- const { scope, aliases } = useStore($selectedInstanceScope);
- const expression =
- prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
- const { overwritable, variant } = useBindingState(
- prop?.type === "expression" ? prop.value : undefined
- );
+ const binding = useBindableControl({
+ boundExpression: prop?.type === "expression" ? prop.value : undefined,
+ fallbackExpression: JSON.stringify(computedValue),
+ });
const errorInfo = (
<ErrorInfo
@@ -173,69 +168,69 @@ export const CodeControl = ({
<VerticalLayout
label={
<Flex gap="1" align="center">
- <PropertyLabel name={propName} readOnly={overwritable === false} />
+ <PropertyLabel
+ name={propName}
+ readOnly={binding.bindingState.overwritable === false}
+ />
{errorInfo}
</Flex>
}
>
- <BindingControl>
- <CodeEditor
- lang={lang}
- title={
- <DialogTitle
- maximizable
- suffix={
- <DialogTitleActions>
- <DialogMaximize />
- <DialogClose />
- </DialogTitleActions>
- }
- >
- <Flex gap="1" align="center">
- <Text variant="labels">Code editor</Text>
- {errorInfo}
- </Flex>
- </DialogTitle>
- }
- readOnly={overwritable === false}
- invalid={error !== undefined && error.severity !== "warning"}
- value={localValue.value}
- onChange={(value) => {
- setError(undefined);
- localValue.set(value);
- }}
- onChangeComplete={localValue.save}
- />
- <BindingPopover
- scope={scope}
- aliases={aliases}
- validate={(value) =>
- behavior
- ? behavior.validateBinding(value, label)
- : validatePrimitiveValue(value, label)
- }
- variant={variant}
- value={expression}
- onChange={(newExpression) =>
- onChange({ type: "expression", value: newExpression })
- }
- onRemove={(evaluatedValue) => {
- if (behavior) {
- const fixedValue = behavior.getFixedValue(evaluatedValue, label);
- if (fixedValue.success === false) {
- setError({
- message: fixedValue.message,
- value: String(evaluatedValue),
- });
- return;
- }
- onChange({ type: "string", value: fixedValue.value });
+ <BindableExpressionControl
+ {...binding}
+ value={localValue.value}
+ validate={(value) =>
+ behavior
+ ? behavior.validateBinding(value, label)
+ : validatePrimitiveValue(value, label)
+ }
+ onChangeValue={(value) => onChange({ type: "string", value })}
+ onChangeExpression={(value) => onChange({ type: "expression", value })}
+ onRemove={(value) => {
+ if (behavior) {
+ const fixedValue = behavior.getFixedValue(value, label);
+ if (fixedValue.success === false) {
+ setError({
+ message: fixedValue.message,
+ value: String(value),
+ });
return;
}
- onChange({ type: "string", value: String(evaluatedValue) });
- }}
- />
- </BindingControl>
+ onChange({ type: "string", value: fixedValue.value });
+ return;
+ }
+ onChange({ type: "string", value: String(value) });
+ }}
+ renderControl={({ readOnly }) => (
+ <CodeEditor
+ lang={lang}
+ title={
+ <DialogTitle
+ maximizable
+ suffix={
+ <DialogTitleActions>
+ <DialogMaximize />
+ <DialogClose />
+ </DialogTitleActions>
+ }
+ >
+ <Flex gap="1" align="center">
+ <Text variant="labels">Code editor</Text>
+ {errorInfo}
+ </Flex>
+ </DialogTitle>
+ }
+ readOnly={readOnly}
+ invalid={error !== undefined && error.severity !== "warning"}
+ value={localValue.value}
+ onChange={(value) => {
+ setError(undefined);
+ localValue.set(value);
+ }}
+ onChangeComplete={localValue.save}
+ />
+ )}
+ />
</VerticalLayout>
);
};
diff --git a/apps/builder/app/builder/features/settings-panel/controls/file.tsx b/apps/builder/app/builder/features/settings-panel/controls/file.tsx
index 1301eb1be0..8e5072bc3d 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/file.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/file.tsx
@@ -1,22 +1,19 @@
-import { useStore } from "@nanostores/react";
import { useId } from "react";
import { Flex, InputField, theme } from "@webstudio-is/design-system";
import {
- BindingControl,
- BindingPopover,
-} from "~/builder/shared/binding-popover";
+ BindableExpressionControl,
+ updateBindableValue,
+} from "~/builder/shared/bindable-expression";
import { validatePrimitiveValue } from "@webstudio-is/project-build/runtime";
import { useDraftValue } from "~/builder/shared/use-draft-value";
import {
type ControlProps,
VerticalLayout,
- updateExpressionValue,
- $selectedInstanceScope,
- useBindingState,
humanizeAttribute,
} from "../shared";
import { SelectAsset } from "./select-asset";
import { PropertyLabel } from "../property-label";
+import { useBindableControl } from "./use-bindable-control";
const UrlInput = ({
id,
@@ -61,45 +58,44 @@ export const FileControl = ({
(value) => {
if (value === undefined) {
return;
- } else if (prop?.type === "expression") {
- updateExpressionValue(prop.value, value);
- } else {
- onChange({ type: "string", value });
}
+ updateBindableValue({
+ expression: prop?.type === "expression" ? prop.value : undefined,
+ value,
+ onChangeValue: (value) => onChange({ type: "string", value }),
+ });
}
);
const label = humanizeAttribute(meta.label || propName);
- const { scope, aliases } = useStore($selectedInstanceScope);
- const expression =
- prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
- const { overwritable, variant } = useBindingState(
- prop?.type === "expression" ? prop.value : undefined
- );
-
+ const binding = useBindableControl({
+ boundExpression: prop?.type === "expression" ? prop.value : undefined,
+ fallbackExpression: JSON.stringify(computedValue),
+ });
return (
<VerticalLayout label={<PropertyLabel name={propName} />}>
<Flex css={{ gap: theme.spacing[3] }} direction="column" justify="center">
- <BindingControl>
- <UrlInput
- id={id}
- readOnly={overwritable === false}
- localValue={localStringValue}
- />
- <BindingPopover
- scope={scope}
- aliases={aliases}
- validate={(value) => validatePrimitiveValue(value, label)}
- variant={variant}
- value={expression}
- onChange={(newExpression) =>
- onChange({ type: "expression", value: newExpression })
- }
- onRemove={(evaluatedValue) =>
- onChange({ type: "string", value: String(evaluatedValue) })
- }
- />
- </BindingControl>
+ <BindableExpressionControl
+ {...binding}
+ value={localStringValue.value}
+ validate={(value) => validatePrimitiveValue(value, label)}
+ onChangeValue={(value) =>
+ onChange({ type: "string", value: value ?? "" })
+ }
+ onChangeExpression={(value) =>
+ onChange({ type: "expression", value })
+ }
+ onRemove={(value) =>
+ onChange({ type: "string", value: String(value) })
+ }
+ renderControl={({ readOnly }) => (
+ <UrlInput
+ id={id}
+ readOnly={readOnly}
+ localValue={localStringValue}
+ />
+ )}
+ />
<SelectAsset
prop={prop?.type === "asset" ? prop : undefined}
accept={meta.accept}
diff --git a/apps/builder/app/builder/features/settings-panel/controls/json.tsx b/apps/builder/app/builder/features/settings-panel/controls/json.tsx
index 9c571678c9..116be920f7 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/json.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/json.tsx
@@ -1,23 +1,17 @@
import { useState } from "react";
-import { useStore } from "@nanostores/react";
-import { isLiteralExpression } from "@webstudio-is/sdk";
+import { isLiteralExpression } from "@webstudio-is/expression";
import { useDraftValue } from "~/builder/shared/use-draft-value";
import {
- type ControlProps,
- VerticalLayout,
- updateExpressionValue,
- $selectedInstanceScope,
- useBindingState,
-} from "../shared";
+ BindableExpressionControl,
+ updateBindableValue,
+} from "~/builder/shared/bindable-expression";
+import { type ControlProps, VerticalLayout } from "../shared";
import {
ExpressionEditor,
formatValue,
} from "~/builder/shared/expression-editor";
-import {
- BindingControl,
- BindingPopover,
-} from "~/builder/shared/binding-popover";
import { PropertyLabel } from "../property-label";
+import { useBindableControl } from "./use-bindable-control";
export const JsonControl = ({
prop,
@@ -37,49 +31,46 @@ export const JsonControl = ({
try {
// wrap into parens to treat object expression as value instead of block
const parsedValue = eval(`(${value})`);
- if (prop?.type === "expression") {
- updateExpressionValue(prop.value, parsedValue);
- } else {
- onChange({ type: "json", value: parsedValue });
- }
+ updateBindableValue({
+ expression: prop?.type === "expression" ? prop.value : undefined,
+ value: parsedValue,
+ onChangeValue: (value) => onChange({ type: "json", value }),
+ });
} catch {
// empty block
}
});
- const { scope, aliases } = useStore($selectedInstanceScope);
- const expression = prop?.type === "expression" ? prop.value : valueString;
- const { overwritable, variant } = useBindingState(
- prop?.type === "expression" ? prop.value : undefined
- );
+ const binding = useBindableControl({
+ boundExpression: prop?.type === "expression" ? prop.value : undefined,
+ fallbackExpression: valueString,
+ });
return (
<VerticalLayout
label={
- <PropertyLabel name={propName} readOnly={overwritable === false} />
+ <PropertyLabel
+ name={propName}
+ readOnly={binding.bindingState.overwritable === false}
+ />
}
>
- <BindingControl>
- <ExpressionEditor
- color={error ? "error" : undefined}
- readOnly={overwritable === false}
- value={localValue.value}
- onChange={localValue.set}
- onChangeComplete={localValue.save}
- />
- <BindingPopover
- scope={scope}
- aliases={aliases}
- variant={variant}
- value={expression}
- onChange={(newExpression) =>
- onChange({ type: "expression", value: newExpression })
- }
- onRemove={(evaluatedValue) =>
- onChange({ type: "json", value: evaluatedValue })
- }
- />
- </BindingControl>
+ <BindableExpressionControl
+ {...binding}
+ value={computedValue}
+ onChangeValue={(value) => onChange({ type: "json", value })}
+ onChangeExpression={(value) => onChange({ type: "expression", value })}
+ onRemove={(value) => onChange({ type: "json", value })}
+ renderControl={({ readOnly }) => (
+ <ExpressionEditor
+ color={error ? "error" : undefined}
+ readOnly={readOnly}
+ value={localValue.value}
+ onChange={localValue.set}
+ onChangeComplete={localValue.save}
+ />
+ )}
+ />
</VerticalLayout>
);
};
diff --git a/apps/builder/app/builder/features/settings-panel/controls/number.tsx b/apps/builder/app/builder/features/settings-panel/controls/number.tsx
index 9b0e45d527..8b0ec241b0 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/number.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/number.tsx
@@ -1,20 +1,17 @@
import { useId, useState } from "react";
-import { useStore } from "@nanostores/react";
import { InputField } from "@webstudio-is/design-system";
-import {
- BindingControl,
- BindingPopover,
-} from "~/builder/shared/binding-popover";
import { useDraftValue } from "~/builder/shared/use-draft-value";
+import {
+ BindableExpressionControl,
+ updateBindableValue,
+} from "~/builder/shared/bindable-expression";
import {
type ControlProps,
ResponsiveLayout,
- updateExpressionValue,
- $selectedInstanceScope,
- useBindingState,
humanizeAttribute,
} from "../shared";
import { PropertyLabel } from "../property-label";
+import { useBindableControl } from "./use-bindable-control";
export const NumberControl = ({
meta,
@@ -31,11 +28,11 @@ export const NumberControl = ({
Number.isNaN(number) ? "" : number,
(value) => {
if (typeof value === "number") {
- if (prop?.type === "expression") {
- updateExpressionValue(prop.value, value);
- } else {
- onChange({ type: "number", value });
- }
+ updateBindableValue({
+ expression: prop?.type === "expression" ? prop.value : undefined,
+ value,
+ onChangeValue: (value) => onChange({ type: "number", value }),
+ });
}
if (value === "") {
setIsInvalid(true);
@@ -44,59 +41,63 @@ export const NumberControl = ({
);
const label = humanizeAttribute(meta.label || propName);
- const { scope, aliases } = useStore($selectedInstanceScope);
- const expression =
- prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
- const { overwritable, variant } = useBindingState(
- prop?.type === "expression" ? prop.value : undefined
- );
+ const binding = useBindableControl({
+ boundExpression: prop?.type === "expression" ? prop.value : undefined,
+ fallbackExpression: JSON.stringify(computedValue),
+ });
return (
<ResponsiveLayout
label={
- <PropertyLabel name={propName} readOnly={overwritable === false} />
+ <PropertyLabel
+ name={propName}
+ readOnly={binding.bindingState.overwritable === false}
+ />
}
>
- <BindingControl>
- <InputField
- id={id}
- disabled={overwritable === false}
- type="number"
- value={localValue.value}
- color={isInvalid ? "error" : undefined}
- onChange={({ target: { valueAsNumber, value } }) => {
- localValue.set(Number.isNaN(valueAsNumber) ? value : valueAsNumber);
- setIsInvalid(false);
- }}
- onBlur={localValue.save}
- onKeyDown={(event) => {
- if (event.key === "Enter") {
- localValue.save();
- }
- }}
- />
- <BindingPopover
- scope={scope}
- aliases={aliases}
- validate={(value) => {
- if (value !== undefined && typeof value !== "number") {
- return `${label} expects a number value`;
- }
- }}
- variant={variant}
- value={expression}
- onChange={(newExpression) =>
- onChange({ type: "expression", value: newExpression })
+ <BindableExpressionControl
+ {...binding}
+ value={localValue.value}
+ validate={(value) => {
+ if (value !== undefined && typeof value !== "number") {
+ return `${label} expects a number value`;
}
- onRemove={(evaluatedValue) => {
- const number = Number(evaluatedValue);
- onChange({
- type: "number",
- value: Number.isNaN(number) ? 0 : number,
- });
- }}
- />
- </BindingControl>
+ }}
+ onChangeValue={(value) => {
+ if (typeof value === "number") {
+ onChange({ type: "number", value });
+ }
+ }}
+ onChangeExpression={(value) => onChange({ type: "expression", value })}
+ onRemove={(value) => {
+ const number = Number(value);
+ onChange({
+ type: "number",
+ value: Number.isNaN(number) ? 0 : number,
+ });
+ }}
+ renderControl={({ readOnly }) => (
+ <InputField
+ id={id}
+ disabled={readOnly}
+ type="number"
+ value={localValue.value}
+ color={isInvalid ? "error" : undefined}
+ onChange={({ target: { valueAsNumber, value } }) => {
+ localValue.set(
+ Number.isNaN(valueAsNumber) ? value : valueAsNumber
+ );
+ setIsInvalid(false);
+ }}
+ onBlur={localValue.save}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ localValue.save();
+ }
+ }}
+ />
+ )}
+ />
</ResponsiveLayout>
);
};
diff --git a/apps/builder/app/builder/features/settings-panel/controls/radio.tsx b/apps/builder/app/builder/features/settings-panel/controls/radio.tsx
index a8986485b5..7c166b0d69 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/radio.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/radio.tsx
@@ -1,20 +1,9 @@
import { useId } from "react";
-import { useStore } from "@nanostores/react";
import { RadioGroup, Radio, RadioAndLabel } from "@webstudio-is/design-system";
-import {
- BindingControl,
- BindingPopover,
-} from "~/builder/shared/binding-popover";
-import {
- type ControlProps,
- VerticalLayout,
- Label,
- $selectedInstanceScope,
- updateExpressionValue,
- useBindingState,
- humanizeAttribute,
-} from "../shared";
+import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
+import { type ControlProps, VerticalLayout, Label } from "../shared";
import { PropertyLabel } from "../property-label";
+import { useStringOptions } from "./use-string-options";
export const RadioControl = ({
meta,
@@ -23,21 +12,14 @@ export const RadioControl = ({
computedValue,
onChange,
}: ControlProps<"radio" | "inline-radio">) => {
- const value = computedValue === undefined ? undefined : String(computedValue);
- // making sure that the current value is in the list of options
- const options =
- value === undefined || meta.options.includes(value)
- ? meta.options
- : [value, ...meta.options];
-
const id = useId();
- const label = humanizeAttribute(meta.label || propName);
- const { scope, aliases } = useStore($selectedInstanceScope);
- const expression =
- prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
- const { overwritable, variant } = useBindingState(
- prop?.type === "expression" ? prop.value : undefined
- );
+ const { options, overwritable, binding } = useStringOptions({
+ meta,
+ prop,
+ propName,
+ computedValue,
+ onChange,
+ });
return (
<VerticalLayout
@@ -45,51 +27,24 @@ export const RadioControl = ({
<PropertyLabel name={propName} readOnly={overwritable === false} />
}
>
- <BindingControl>
- <RadioGroup
- disabled={overwritable === false}
- name="value"
- value={value}
- onValueChange={(value) => {
- if (prop?.type === "expression") {
- updateExpressionValue(prop.value, value);
- } else {
- onChange({ type: "string", value });
- }
- }}
- >
- {options.map((value) => (
- <RadioAndLabel key={value}>
- <Radio value={value} id={`${id}:${value}`} />
- <Label htmlFor={`${id}:${value}`}>{value}</Label>
- </RadioAndLabel>
- ))}
- </RadioGroup>
- <BindingPopover
- scope={scope}
- aliases={aliases}
- validate={(value) => {
- if (
- value !== undefined &&
- meta.options.includes(String(value)) === false
- ) {
- const formatter = new Intl.ListFormat(undefined, {
- type: "disjunction",
- });
- const options = formatter.format(meta.options);
- return `${label} expects one of ${options}`;
- }
- }}
- variant={variant}
- value={expression}
- onChange={(newExpression) =>
- onChange({ type: "expression", value: newExpression })
- }
- onRemove={(evaluatedValue) =>
- onChange({ type: "string", value: String(evaluatedValue) })
- }
- />
- </BindingControl>
+ <BindableExpressionControl
+ {...binding}
+ renderControl={({ value, readOnly, onChangeValue }) => (
+ <RadioGroup
+ disabled={readOnly}
+ name="value"
+ value={value}
+ onValueChange={onChangeValue}
+ >
+ {options.map((value) => (
+ <RadioAndLabel key={value}>
+ <Radio value={value} id={`${id}:${value}`} />
+ <Label htmlFor={`${id}:${value}`}>{value}</Label>
+ </RadioAndLabel>
+ ))}
+ </RadioGroup>
+ )}
+ />
</VerticalLayout>
);
};
diff --git a/apps/builder/app/builder/features/settings-panel/controls/resource-control.tsx b/apps/builder/app/builder/features/settings-panel/controls/resource-control.tsx
index a2effc003e..1288efa9f8 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/resource-control.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/resource-control.tsx
@@ -17,12 +17,9 @@ import {
NestedInputButton,
theme,
} from "@webstudio-is/design-system";
-import { isLiteralExpression, type Resource } from "@webstudio-is/sdk";
-import {
- BindingControl,
- BindingPopover,
- type BindingVariant,
-} from "~/builder/shared/binding-popover";
+import { isLiteralExpression } from "@webstudio-is/expression";
+import type { Resource } from "@webstudio-is/sdk";
+import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
import { validatePrimitiveValue } from "@webstudio-is/project-build/runtime";
import { $variableValuesByInstanceSelector } from "~/shared/nano-states";
import { $dataSources } from "~/shared/sync/data-stores";
@@ -278,56 +275,54 @@ export const ResourceControl = ({
};
const id = useId();
- let variant: BindingVariant = "bound";
- let readOnly = true;
- if (isLiteralExpression(urlExpression)) {
- variant = "default";
- readOnly = false;
- }
+ const bound = isLiteralExpression(urlExpression) === false;
const localValue = useDraftValue(
String(computeExpression(resource.url, variableValues) ?? ""),
(value) => updateResource({ ...resource, url: JSON.stringify(value) })
);
return (
- <VerticalLayout
- label={<PropertyLabel name={propName} readOnly={readOnly} />}
- >
- <BindingControl>
- <InputField
- id={id}
- disabled={readOnly}
- value={localValue.value}
- onChange={(event) => localValue.set(event.target.value)}
- onBlur={localValue.save}
- onSubmit={localValue.save}
- suffix={
- isFeatureEnabled("resourceProp") && (
- <ResourceControlPanel
- resource={resource}
- propName={propName}
- onChange={updateResource}
- />
- )
- }
- />
- <BindingPopover
- scope={scope}
- aliases={aliases}
- validate={(value) => validatePrimitiveValue(value, "URL")}
- variant={variant}
- value={urlExpression}
- onChange={(newExpression) =>
- updateResource({ ...resource, url: newExpression })
- }
- onRemove={(evaluatedValue) =>
- updateResource({
- ...resource,
- url: JSON.stringify(String(evaluatedValue)),
- })
- }
- />
- </BindingControl>
+ <VerticalLayout label={<PropertyLabel name={propName} readOnly={bound} />}>
+ <BindableExpressionControl
+ expression={urlExpression}
+ value={localValue.value}
+ bound={bound}
+ allowBindingOverwrite={false}
+ scope={scope}
+ aliases={aliases}
+ validate={(value) => validatePrimitiveValue(value, "URL")}
+ onChangeValue={(value) =>
+ updateResource({ ...resource, url: JSON.stringify(value) })
+ }
+ onChangeExpression={(value) =>
+ updateResource({ ...resource, url: value })
+ }
+ onRemove={(value) =>
+ updateResource({
+ ...resource,
+ url: JSON.stringify(String(value)),
+ })
+ }
+ renderControl={({ readOnly }) => (
+ <InputField
+ id={id}
+ disabled={readOnly}
+ value={localValue.value}
+ onChange={(event) => localValue.set(event.target.value)}
+ onBlur={localValue.save}
+ onSubmit={localValue.save}
+ suffix={
+ isFeatureEnabled("resourceProp") && (
+ <ResourceControlPanel
+ resource={resource}
+ propName={propName}
+ onChange={updateResource}
+ />
+ )
+ }
+ />
+ )}
+ />
</VerticalLayout>
);
};
diff --git a/apps/builder/app/builder/features/settings-panel/controls/select.tsx b/apps/builder/app/builder/features/settings-panel/controls/select.tsx
index 5923c0899e..09d7c55976 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/select.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/select.tsx
@@ -1,19 +1,9 @@
import { useId } from "react";
-import { useStore } from "@nanostores/react";
import { Select } from "@webstudio-is/design-system";
-import {
- BindingControl,
- BindingPopover,
-} from "~/builder/shared/binding-popover";
-import {
- type ControlProps,
- VerticalLayout,
- $selectedInstanceScope,
- updateExpressionValue,
- useBindingState,
- humanizeAttribute,
-} from "../shared";
+import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
+import { type ControlProps, VerticalLayout } from "../shared";
import { PropertyLabel } from "../property-label";
+import { useStringOptions } from "./use-string-options";
export const SelectControl = ({
meta,
@@ -24,20 +14,14 @@ export const SelectControl = ({
}: ControlProps<"select">) => {
const id = useId();
- const value = computedValue === undefined ? undefined : String(computedValue);
- // making sure that the current value is in the list of options
- const options =
- value === undefined || value.length === 0 || meta.options.includes(value)
- ? meta.options
- : [value, ...meta.options];
-
- const label = humanizeAttribute(meta.label || propName);
- const { scope, aliases } = useStore($selectedInstanceScope);
- const expression =
- prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
- const { overwritable, variant } = useBindingState(
- prop?.type === "expression" ? prop.value : undefined
- );
+ const { options, overwritable, binding } = useStringOptions({
+ meta,
+ prop,
+ propName,
+ computedValue,
+ onChange,
+ allowEmptyValue: true,
+ });
return (
<VerticalLayout
@@ -45,46 +29,19 @@ export const SelectControl = ({
<PropertyLabel name={propName} readOnly={overwritable === false} />
}
>
- <BindingControl>
- <Select
- fullWidth
- id={id}
- disabled={overwritable === false}
- value={value}
- options={options}
- onChange={(value) => {
- if (prop?.type === "expression") {
- updateExpressionValue(prop.value, value);
- } else {
- onChange({ type: "string", value });
- }
- }}
- />
- <BindingPopover
- scope={scope}
- aliases={aliases}
- validate={(value) => {
- if (
- value !== undefined &&
- meta.options.includes(String(value)) === false
- ) {
- const formatter = new Intl.ListFormat(undefined, {
- type: "disjunction",
- });
- const options = formatter.format(meta.options);
- return `${label} expects one of ${options}`;
- }
- }}
- variant={variant}
- value={expression}
- onChange={(newExpression) =>
- onChange({ type: "expression", value: newExpression })
- }
- onRemove={(evaluatedValue) =>
- onChange({ type: "string", value: String(evaluatedValue) })
- }
- />
- </BindingControl>
+ <BindableExpressionControl
+ {...binding}
+ renderControl={({ value, readOnly, onChangeValue }) => (
+ <Select
+ fullWidth
+ id={id}
+ disabled={readOnly}
+ value={value}
+ options={options}
+ onChange={onChangeValue}
+ />
+ )}
+ />
</VerticalLayout>
);
};
diff --git a/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx b/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx
index d162514ab8..0a04094b10 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx
@@ -13,22 +13,17 @@ import {
import type { Instance } from "@webstudio-is/sdk";
import { AlertIcon } from "@webstudio-is/icons";
import { $instances } from "~/shared/sync/data-stores";
-import {
- BindingControl,
- BindingPopover,
-} from "~/builder/shared/binding-popover";
import { validatePrimitiveValue } from "@webstudio-is/project-build/runtime";
import { useDraftValue } from "~/builder/shared/use-draft-value";
+import {
+ BindableExpressionControl,
+ updateBindableValue,
+} from "~/builder/shared/bindable-expression";
import { executeRuntimeMutation } from "~/shared/instance-utils/data";
import { CodeEditor } from "~/shared/code-editor";
-import {
- type ControlProps,
- VerticalLayout,
- $selectedInstanceScope,
- updateExpressionValue,
- useBindingState,
-} from "../shared";
+import { type ControlProps, VerticalLayout } from "../shared";
import { FieldLabel, useIsBindingResetForbidden } from "../property-label";
+import { useBindableControl } from "./use-bindable-control";
const useInstance = (instanceId: Instance["id"]) => {
const $store = useMemo(() => {
@@ -62,14 +57,13 @@ export const TextContent = ({
// text content control is rendered only when empty or single child are present
const child = instance?.children?.[0] ?? { type: "text", value: "" };
const localValue = useDraftValue(String(computedValue ?? ""), (value) => {
- if (child.type === "expression") {
- updateExpressionValue(child.value, value);
- } else {
- updateChildren(instanceId, "text", value);
- }
+ updateBindableValue({
+ expression: child.type === "expression" ? child.value : undefined,
+ value,
+ onChangeValue: (value) => updateChildren(instanceId, "text", value),
+ });
});
- const { scope, aliases } = useStore($selectedInstanceScope);
let expression: undefined | string;
if (child.type === "text") {
expression = JSON.stringify(child.value);
@@ -78,9 +72,10 @@ export const TextContent = ({
expression = child.value;
}
- const { overwritable, variant } = useBindingState(
- child.type === "expression" ? child.value : undefined
- );
+ const binding = useBindableControl({
+ boundExpression: child.type === "expression" ? expression : undefined,
+ fallbackExpression: expression ?? "",
+ });
const isBindingResetForbidden = useIsBindingResetForbidden();
const isResetDisabled =
child.type === "expression" && isBindingResetForbidden;
@@ -93,7 +88,7 @@ export const TextContent = ({
<>
Plain text content that can be bound to either a variable or a
resource value.
- {overwritable === false && (
+ {binding.bindingState.overwritable === false && (
<Flex gap="1">
<AlertIcon
color={rawTheme.colors.backgroundAlertMain}
@@ -123,43 +118,39 @@ export const TextContent = ({
</FieldLabel>
}
>
- <BindingControl>
- <CodeEditor
- title={
- <DialogTitle
- maximizable
- suffix={
- <DialogTitleActions>
- <DialogMaximize />
- <DialogClose />
- </DialogTitleActions>
- }
- >
- <Text variant="labels">Text content</Text>
- </DialogTitle>
- }
- size="small"
- readOnly={overwritable === false}
- value={localValue.value}
- onChange={localValue.set}
- onChangeComplete={localValue.save}
- />
- {expression !== undefined && (
- <BindingPopover
- scope={scope}
- aliases={aliases}
- validate={(value) => validatePrimitiveValue(value, "Text Content")}
- variant={variant}
- value={expression}
- onChange={(newExpression) => {
- updateChildren(instanceId, "expression", newExpression);
- }}
- onRemove={(evaluatedValue) =>
- updateChildren(instanceId, "text", String(evaluatedValue))
+ <BindableExpressionControl
+ {...binding}
+ value={localValue.value}
+ showBinding={expression !== undefined}
+ validate={(value) => validatePrimitiveValue(value, "Text Content")}
+ onChangeValue={(value) => updateChildren(instanceId, "text", value)}
+ onChangeExpression={(value) =>
+ updateChildren(instanceId, "expression", value)
+ }
+ onRemove={(value) => updateChildren(instanceId, "text", String(value))}
+ renderControl={({ readOnly }) => (
+ <CodeEditor
+ title={
+ <DialogTitle
+ maximizable
+ suffix={
+ <DialogTitleActions>
+ <DialogMaximize />
+ <DialogClose />
+ </DialogTitleActions>
+ }
+ >
+ <Text variant="labels">Text content</Text>
+ </DialogTitle>
}
+ size="small"
+ readOnly={readOnly}
+ value={localValue.value}
+ onChange={localValue.set}
+ onChangeComplete={localValue.save}
/>
)}
- </BindingControl>
+ />
</VerticalLayout>
);
};
diff --git a/apps/builder/app/builder/features/settings-panel/controls/text.tsx b/apps/builder/app/builder/features/settings-panel/controls/text.tsx
index b02bce288c..767e913822 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/text.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/text.tsx
@@ -1,21 +1,18 @@
import { useId } from "react";
-import { useStore } from "@nanostores/react";
import { TextArea } from "@webstudio-is/design-system";
-import {
- BindingControl,
- BindingPopover,
-} from "~/builder/shared/binding-popover";
import { validatePrimitiveValue } from "@webstudio-is/project-build/runtime";
import { useDraftValue } from "~/builder/shared/use-draft-value";
+import {
+ BindableExpressionControl,
+ updateBindableValue,
+} from "~/builder/shared/bindable-expression";
import {
type ControlProps,
ResponsiveLayout,
- updateExpressionValue,
- $selectedInstanceScope,
- useBindingState,
humanizeAttribute,
} from "../shared";
import { PropertyLabel } from "../property-label";
+import { useBindableControl } from "./use-bindable-control";
export const TextControl = ({
meta,
@@ -25,56 +22,51 @@ export const TextControl = ({
onChange,
}: ControlProps<"text">) => {
const localValue = useDraftValue(String(computedValue ?? ""), (value) => {
- if (prop?.type === "expression") {
- updateExpressionValue(prop.value, value);
- } else {
- onChange({ type: "string", value });
- }
+ updateBindableValue({
+ expression: prop?.type === "expression" ? prop.value : undefined,
+ value,
+ onChangeValue: (value) => onChange({ type: "string", value }),
+ });
});
const id = useId();
const label = humanizeAttribute(meta.label || propName);
- const { scope, aliases } = useStore($selectedInstanceScope);
- const expression =
- prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
- const { overwritable, variant } = useBindingState(
- prop?.type === "expression" ? prop.value : undefined
- );
+ const binding = useBindableControl({
+ boundExpression: prop?.type === "expression" ? prop.value : undefined,
+ fallbackExpression: JSON.stringify(computedValue),
+ });
const input = (
- <BindingControl>
- <TextArea
- id={id}
- disabled={overwritable === false}
- autoGrow
- value={localValue.value}
- rows={meta.rows ?? 1}
- // Set maxRows to 3 when meta.rows is undefined or equal to 1, otherwise set it to rows * 2
- maxRows={Math.max(2 * (meta.rows ?? 1), 3)}
- onChange={localValue.set}
- onBlur={localValue.save}
- onSubmit={localValue.save}
- />
-
- <BindingPopover
- scope={scope}
- aliases={aliases}
- validate={(value) => validatePrimitiveValue(value, label)}
- variant={variant}
- value={expression}
- onChange={(newExpression) =>
- onChange({ type: "expression", value: newExpression })
- }
- onRemove={(evaluatedValue) =>
- onChange({ type: "string", value: String(evaluatedValue) })
- }
- />
- </BindingControl>
+ <BindableExpressionControl
+ {...binding}
+ value={localValue.value}
+ validate={(value) => validatePrimitiveValue(value, label)}
+ onChangeValue={(value) => onChange({ type: "string", value })}
+ onChangeExpression={(value) => onChange({ type: "expression", value })}
+ onRemove={(value) => onChange({ type: "string", value: String(value) })}
+ renderControl={({ readOnly }) => (
+ <TextArea
+ id={id}
+ disabled={readOnly}
+ autoGrow
+ value={localValue.value}
+ rows={meta.rows ?? 1}
+ // Set maxRows to 3 when meta.rows is undefined or equal to 1, otherwise set it to rows * 2
+ maxRows={Math.max(2 * (meta.rows ?? 1), 3)}
+ onChange={localValue.set}
+ onBlur={localValue.save}
+ onSubmit={localValue.save}
+ />
+ )}
+ />
);
return (
<ResponsiveLayout
label={
- <PropertyLabel name={propName} readOnly={overwritable === false} />
+ <PropertyLabel
+ name={propName}
+ readOnly={binding.bindingState.overwritable === false}
+ />
}
>
{input}
diff --git a/apps/builder/app/builder/features/settings-panel/controls/time-zone.tsx b/apps/builder/app/builder/features/settings-panel/controls/time-zone.tsx
index e5199807ca..32a2ce1070 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/time-zone.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/time-zone.tsx
@@ -2,22 +2,20 @@ import { useId } from "react";
import { useStore } from "@nanostores/react";
import { matchSorter } from "match-sorter";
import { Box, Combobox, Text, theme } from "@webstudio-is/design-system";
-import {
- BindingControl,
- BindingPopover,
-} from "~/builder/shared/binding-popover";
import { validatePrimitiveValue } from "@webstudio-is/project-build/runtime";
import { useDraftValue } from "~/builder/shared/use-draft-value";
+import {
+ BindableExpressionControl,
+ updateBindableValue,
+} from "~/builder/shared/bindable-expression";
import { $props } from "~/shared/sync/data-stores";
import {
type ControlProps,
ResponsiveLayout,
- updateExpressionValue,
- $selectedInstanceScope,
- useBindingState,
humanizeAttribute,
} from "../shared";
import { PropertyLabel } from "../property-label";
+import { useBindableControl } from "./use-bindable-control";
type TimeZoneItem = {
value: string;
@@ -198,22 +196,20 @@ export const TimeZoneControl = ({
computedValue ?? meta.defaultValue ?? defaultTimeZone
);
const localValue = useDraftValue(savedValue, (value) => {
- if (prop?.type === "expression") {
- updateExpressionValue(prop.value, value);
- } else {
- onChange({ type: "string", value });
- }
+ updateBindableValue({
+ expression: prop?.type === "expression" ? prop.value : undefined,
+ value,
+ onChangeValue: (value) => onChange({ type: "string", value }),
+ });
});
const timeZoneItems = getTimeZoneItems(meta.options);
const selectedItem = getTimeZoneItem(savedValue);
const currentItem = getTimeZoneItem(localValue.value);
const label = humanizeAttribute(meta.label || propName);
- const { scope, aliases } = useStore($selectedInstanceScope);
- const expression =
- prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
- const { overwritable, variant } = useBindingState(
- prop?.type === "expression" ? prop.value : undefined
- );
+ const binding = useBindableControl({
+ boundExpression: prop?.type === "expression" ? prop.value : undefined,
+ fallbackExpression: JSON.stringify(computedValue),
+ });
const datetime = getStringProp(
props,
@@ -247,57 +243,55 @@ export const TimeZoneControl = ({
return (
<ResponsiveLayout
label={
- <PropertyLabel name={propName} readOnly={overwritable === false} />
+ <PropertyLabel
+ name={propName}
+ readOnly={binding.bindingState.overwritable === false}
+ />
}
>
- <BindingControl>
- <Combobox<TimeZoneItem>
- name={id}
- disabled={overwritable === false}
- getItems={() => timeZoneItems}
- itemToString={itemToString}
- value={currentItem}
- selectedItem={selectedItem}
- match={matchOrSuggestTimeZone}
- onChange={(value) => {
- if (value !== undefined) {
- localValue.set(value.trim());
- }
- }}
- onItemSelect={(item) => {
- localValue.set(item.value.trim());
- localValue.flush();
- }}
- getDescription={(item) => {
- const preview = getTimeZonePreview({
- item,
- date,
- locale,
- dateStyle,
- timeStyle,
- format,
- });
- return (
- <Box css={{ width: theme.spacing[28] }}>
- <Text>{preview ?? "Select or type an IANA timezone."}</Text>
- </Box>
- );
- }}
- />
- <BindingPopover
- scope={scope}
- aliases={aliases}
- validate={(value) => validatePrimitiveValue(value, label)}
- variant={variant}
- value={expression}
- onChange={(newExpression) =>
- onChange({ type: "expression", value: newExpression })
- }
- onRemove={(evaluatedValue) =>
- onChange({ type: "string", value: String(evaluatedValue) })
- }
- />
- </BindingControl>
+ <BindableExpressionControl
+ {...binding}
+ value={localValue.value}
+ validate={(value) => validatePrimitiveValue(value, label)}
+ onChangeValue={(value) => onChange({ type: "string", value })}
+ onChangeExpression={(value) => onChange({ type: "expression", value })}
+ onRemove={(value) => onChange({ type: "string", value: String(value) })}
+ renderControl={({ readOnly }) => (
+ <Combobox<TimeZoneItem>
+ name={id}
+ disabled={readOnly}
+ getItems={() => timeZoneItems}
+ itemToString={itemToString}
+ value={currentItem}
+ selectedItem={selectedItem}
+ match={matchOrSuggestTimeZone}
+ onChange={(value) => {
+ if (value !== undefined) {
+ localValue.set(value.trim());
+ }
+ }}
+ onItemSelect={(item) => {
+ localValue.set(item.value.trim());
+ localValue.flush();
+ }}
+ getDescription={(item) => {
+ const preview = getTimeZonePreview({
+ item,
+ date,
+ locale,
+ dateStyle,
+ timeStyle,
+ format,
+ });
+ return (
+ <Box css={{ width: theme.spacing[28] }}>
+ <Text>{preview ?? "Select or type an IANA timezone."}</Text>
+ </Box>
+ );
+ }}
+ />
+ )}
+ />
</ResponsiveLayout>
);
};
diff --git a/apps/builder/app/builder/features/settings-panel/controls/url.tsx b/apps/builder/app/builder/features/settings-panel/controls/url.tsx
index 02c33c7fac..15f8e5c576 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/url.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/url.tsx
@@ -29,26 +29,24 @@ import {
type Page,
} from "@webstudio-is/sdk";
import { $instances, $pages, $props } from "~/shared/sync/data-stores";
-import {
- BindingControl,
- BindingPopover,
-} from "~/builder/shared/binding-popover";
import { validatePrimitiveValue } from "@webstudio-is/project-build/runtime";
import { useDraftValue } from "~/builder/shared/use-draft-value";
+import {
+ BindableExpressionControl,
+ updateBindableValue,
+} from "~/builder/shared/bindable-expression";
import { getPageDisplayName } from "~/builder/features/pages/page-utils";
import {
type ControlProps,
VerticalLayout,
Label,
- updateExpressionValue,
- $selectedInstanceScope,
- useBindingState,
humanizeAttribute,
type PropValue,
} from "../shared";
import { SelectAsset } from "./select-asset";
import { createRootFolder } from "@webstudio-is/project-build";
import { PropertyLabel } from "../property-label";
+import { useBindableControl } from "./use-bindable-control";
type UrlControlProps = ControlProps<"url">;
@@ -110,11 +108,11 @@ const addHttpsIfMissing = (url: string) => {
const BaseUrl = ({ readOnly, prop, value, onChange, id }: BaseControlProps) => {
const localValue = useDraftValue(value, (value) => {
- if (prop?.type === "expression") {
- updateExpressionValue(prop.value, value);
- } else {
- onChange({ type: "string", value });
- }
+ updateBindableValue({
+ expression: prop?.type === "expression" ? prop.value : undefined,
+ value,
+ onChangeValue: (value) => onChange({ type: "string", value }),
+ });
});
useEffect(() => {
@@ -156,11 +154,12 @@ const BasePhone = ({
const localValue = useDraftValue(
value.startsWith("tel:") ? value.slice(4) : "",
(value) => {
- if (prop?.type === "expression") {
- updateExpressionValue(prop.value, `tel:${value}`);
- } else {
- onChange({ type: "string", value: `tel:${value}` });
- }
+ const nextValue = `tel:${value}`;
+ updateBindableValue({
+ expression: prop?.type === "expression" ? prop.value : undefined,
+ value: nextValue,
+ onChangeValue: (value) => onChange({ type: "string", value }),
+ });
}
);
@@ -234,11 +233,11 @@ const BaseEmail = ({
}: BaseControlProps) => {
const localValue = useDraftValue(propToEmail(value), ({ email, subject }) => {
const value = emailToProp({ email, subject });
- if (prop?.type === "expression") {
- updateExpressionValue(prop.value, value);
- } else {
- onChange({ type: "string", value });
- }
+ updateBindableValue({
+ expression: prop?.type === "expression" ? prop.value : undefined,
+ value,
+ onChangeValue: (value) => onChange({ type: "string", value }),
+ });
});
return (
@@ -483,14 +482,14 @@ export const UrlInput = ({
value,
readOnly = false,
onChange,
- suffix,
+ renderControl,
}: {
instanceId: string;
prop: UrlInputProp;
value: string;
readOnly?: boolean;
onChange: (value: UrlInputValue) => void;
- suffix?: ReactNode;
+ renderControl?: (control: ReactNode) => ReactNode;
}) => {
const { value: mode, set: setMode } = useDraftValue<Mode>(
propToMode(prop, value),
@@ -537,14 +536,7 @@ export const UrlInput = ({
))}
</ToggleGroup>
</Flex>
- {suffix === undefined ? (
- control
- ) : (
- <BindingControl>
- {control}
- {suffix}
- </BindingControl>
- )}
+ {renderControl?.(control) ?? control}
</>
);
};
@@ -559,12 +551,10 @@ export const UrlControl = ({
}: UrlControlProps) => {
const value = String(computedValue ?? "");
const label = humanizeAttribute(meta.label || propName);
- const { scope, aliases } = useStore($selectedInstanceScope);
- const expression =
- prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
- const { overwritable, variant } = useBindingState(
- prop?.type === "expression" ? prop.value : undefined
- );
+ const binding = useBindableControl({
+ boundExpression: prop?.type === "expression" ? prop.value : undefined,
+ fallbackExpression: JSON.stringify(computedValue),
+ });
return (
<VerticalLayout label={<PropertyLabel name={propName} />}>
@@ -579,23 +569,23 @@ export const UrlControl = ({
: undefined
}
value={value}
- readOnly={overwritable === false}
+ readOnly={binding.bindingState.overwritable === false}
onChange={onChange}
- suffix={
- <BindingPopover
- scope={scope}
- aliases={aliases}
+ renderControl={(control) => (
+ <BindableExpressionControl
+ {...binding}
+ value={value}
validate={(value) => validatePrimitiveValue(value, label)}
- variant={variant}
- value={expression}
- onChange={(newExpression) =>
- onChange({ type: "expression", value: newExpression })
+ onChangeValue={(value) => onChange({ type: "string", value })}
+ onChangeExpression={(value) =>
+ onChange({ type: "expression", value })
}
- onRemove={(evaluatedValue) =>
- onChange({ type: "string", value: String(evaluatedValue) })
+ onRemove={(value) =>
+ onChange({ type: "string", value: String(value) })
}
+ renderControl={() => control}
/>
- }
+ )}
/>
</VerticalLayout>
);
diff --git a/apps/builder/app/builder/features/settings-panel/controls/use-bindable-control.ts b/apps/builder/app/builder/features/settings-panel/controls/use-bindable-control.ts
new file mode 100644
index 0000000000..20d9b5406c
--- /dev/null
+++ b/apps/builder/app/builder/features/settings-panel/controls/use-bindable-control.ts
@@ -0,0 +1,17 @@
+import { useStore } from "@nanostores/react";
+import { useBindingState } from "~/builder/shared/bindable-expression";
+import { $selectedInstanceScope } from "../shared";
+
+export const useBindableControl = ({
+ boundExpression,
+ fallbackExpression,
+}: {
+ boundExpression?: string;
+ fallbackExpression: string;
+}) => {
+ const { scope, aliases } = useStore($selectedInstanceScope);
+ const bindingState = useBindingState(boundExpression);
+ const bound = boundExpression !== undefined;
+ const expression = boundExpression ?? fallbackExpression;
+ return { expression, bound, scope, aliases, bindingState };
+};
diff --git a/apps/builder/app/builder/features/settings-panel/controls/use-string-options.ts b/apps/builder/app/builder/features/settings-panel/controls/use-string-options.ts
new file mode 100644
index 0000000000..31bdcbdd71
--- /dev/null
+++ b/apps/builder/app/builder/features/settings-panel/controls/use-string-options.ts
@@ -0,0 +1,53 @@
+import { humanizeAttribute, type ControlProps } from "../shared";
+import { useBindableControl } from "./use-bindable-control";
+
+export const useStringOptions = ({
+ meta,
+ prop,
+ propName,
+ computedValue,
+ onChange,
+ allowEmptyValue = false,
+}: Omit<ControlProps<"radio" | "inline-radio" | "select">, "instanceId"> & {
+ allowEmptyValue?: boolean;
+}) => {
+ const value = computedValue === undefined ? undefined : String(computedValue);
+ const options =
+ value === undefined ||
+ (allowEmptyValue && value.length === 0) ||
+ meta.options.includes(value)
+ ? meta.options
+ : [value, ...meta.options];
+ const label = humanizeAttribute(meta.label || propName);
+ const binding = useBindableControl({
+ boundExpression: prop?.type === "expression" ? prop.value : undefined,
+ fallbackExpression: JSON.stringify(computedValue),
+ });
+
+ return {
+ value,
+ options,
+ overwritable: binding.bindingState.overwritable,
+ binding: {
+ ...binding,
+ value,
+ validate: (value: unknown) => {
+ if (
+ value !== undefined &&
+ meta.options.includes(String(value)) === false
+ ) {
+ const formatter = new Intl.ListFormat(undefined, {
+ type: "disjunction",
+ });
+ return `${label} expects one of ${formatter.format(meta.options)}`;
+ }
+ },
+ onChangeValue: (value: string | undefined) =>
+ onChange({ type: "string", value: value ?? "" }),
+ onChangeExpression: (value: string) =>
+ onChange({ type: "expression", value }),
+ onRemove: (value: unknown) =>
+ onChange({ type: "string", value: String(value) }),
+ },
+ };
+};
diff --git a/apps/builder/app/builder/features/settings-panel/request-error-diagnostics.test.ts b/apps/builder/app/builder/features/settings-panel/request-error-diagnostics.test.ts
new file mode 100644
index 0000000000..e101d7216e
--- /dev/null
+++ b/apps/builder/app/builder/features/settings-panel/request-error-diagnostics.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, test } from "vitest";
+import { getRequestErrorDiagnostics } from "./request-error-diagnostics";
+
+describe("request error diagnostics", () => {
+ test("extracts HTTP and structured API error information", () => {
+ expect(
+ getRequestErrorDiagnostics({
+ ok: false,
+ status: 400,
+ statusText: "",
+ data: {
+ ok: false,
+ error: {
+ code: "CONTENT_NOT_TEXT",
+ message: "Selected binary asset cannot be embedded as text",
+ retryable: false,
+ details: { assetId: "asset", mimeType: "image/png" },
+ },
+ },
+ })
+ ).toEqual({
+ status: 400,
+ statusText: undefined,
+ code: "CONTENT_NOT_TEXT",
+ message: "Selected binary asset cannot be embedded as text",
+ retryable: false,
+ details: { assetId: "asset", mimeType: "image/png" },
+ });
+ });
+
+ test("describes transport failures without a structured error", () => {
+ expect(
+ getRequestErrorDiagnostics({ ok: false, status: 502, data: "failure" })
+ ).toMatchObject({ status: 502, message: "Request failed with status 502" });
+ expect(
+ getRequestErrorDiagnostics({ ok: true, status: 200, data: {} })
+ ).toBeUndefined();
+ });
+});
diff --git a/apps/builder/app/builder/features/settings-panel/request-error-diagnostics.tsx b/apps/builder/app/builder/features/settings-panel/request-error-diagnostics.tsx
new file mode 100644
index 0000000000..66280b7667
--- /dev/null
+++ b/apps/builder/app/builder/features/settings-panel/request-error-diagnostics.tsx
@@ -0,0 +1,104 @@
+import { PanelBanner, Text } from "@webstudio-is/design-system";
+import {
+ RequestDiagnosticsContent,
+ RequestDiagnosticsRow,
+ RequestDiagnosticsTable,
+} from "./request-inspector";
+
+type RequestErrorDiagnosticsValue = {
+ status?: number;
+ statusText?: string;
+ code?: string;
+ message: string;
+ retryable?: boolean;
+ details?: Record<string, unknown>;
+};
+
+const asRecord = (value: unknown): Record<string, unknown> | undefined =>
+ typeof value === "object" && value !== null && Array.isArray(value) === false
+ ? (value as Record<string, unknown>)
+ : undefined;
+
+export const getRequestErrorDiagnostics = (
+ value: unknown
+): RequestErrorDiagnosticsValue | undefined => {
+ const response = asRecord(value);
+ if (response === undefined) {
+ return;
+ }
+ const status =
+ typeof response.status === "number" ? response.status : undefined;
+ const statusText =
+ typeof response.statusText === "string" && response.statusText !== ""
+ ? response.statusText
+ : undefined;
+ const payload = asRecord(response.data);
+ const error = asRecord(payload?.error);
+ const failed =
+ response.ok === false || (status !== undefined && status >= 400);
+ if (error === undefined && failed === false) {
+ return;
+ }
+ const code = typeof error?.code === "string" ? error.code : undefined;
+ const details = asRecord(error?.details);
+ const errorMessage =
+ typeof error?.message === "string" && error.message !== ""
+ ? error.message
+ : undefined;
+ const message =
+ errorMessage ??
+ statusText ??
+ (status === undefined
+ ? "Request failed"
+ : `Request failed with status ${status}`);
+ return {
+ status,
+ statusText,
+ code,
+ message,
+ ...(typeof error?.retryable === "boolean"
+ ? { retryable: error.retryable }
+ : {}),
+ ...(details === undefined ? {} : { details }),
+ };
+};
+
+const formatDetail = (value: unknown) =>
+ typeof value === "string" ? value : JSON.stringify(value);
+
+export const RequestErrorDiagnostics = ({
+ value,
+}: {
+ value: RequestErrorDiagnosticsValue;
+}) => (
+ <RequestDiagnosticsContent>
+ <PanelBanner variant="error">
+ <Text>{value.message}</Text>
+ </PanelBanner>
+ <RequestDiagnosticsTable>
+ {value.status !== undefined && (
+ <RequestDiagnosticsRow
+ label="HTTP status"
+ value={`${value.status}${value.statusText === undefined ? "" : ` ${value.statusText}`}`}
+ />
+ )}
+ {value.code !== undefined && (
+ <RequestDiagnosticsRow label="Error code" value={value.code} />
+ )}
+ <RequestDiagnosticsRow label="Message" value={value.message} />
+ {value.retryable !== undefined && (
+ <RequestDiagnosticsRow
+ label="Retryable"
+ value={value.retryable ? "Yes" : "No"}
+ />
+ )}
+ {Object.entries(value.details ?? {}).map(([key, detail]) => (
+ <RequestDiagnosticsRow
+ key={key}
+ label={`Details · ${key}`}
+ value={formatDetail(detail)}
+ />
+ ))}
+ </RequestDiagnosticsTable>
+ </RequestDiagnosticsContent>
+);
diff --git a/apps/builder/app/builder/features/settings-panel/request-inspector.test.tsx b/apps/builder/app/builder/features/settings-panel/request-inspector.test.tsx
new file mode 100644
index 0000000000..0c6c54c223
--- /dev/null
+++ b/apps/builder/app/builder/features/settings-panel/request-inspector.test.tsx
@@ -0,0 +1,58 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { act } from "react-dom/test-utils";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, expect, test } from "vitest";
+import { RequestInspector } from "./request-inspector";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+let root: Root | undefined;
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = undefined;
+ document.body.innerHTML = "";
+});
+
+const renderInspector = (query: boolean) => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ act(() => {
+ root?.render(
+ <RequestInspector
+ queryContainerRef={query ? () => {} : undefined}
+ preview={<div>Preview content</div>}
+ diagnostics={<div>Diagnostics content</div>}
+ />
+ );
+ });
+ return container;
+};
+
+test("places an available query editor in the first selected tab", () => {
+ const container = renderInspector(true);
+ const tabs = Array.from(container.querySelectorAll('[role="tab"]'));
+
+ expect(tabs.map(({ textContent }) => textContent)).toEqual([
+ "Query",
+ "Preview",
+ "Diagnostics",
+ ]);
+ expect(tabs[0].getAttribute("data-state")).toBe("active");
+});
+
+test("keeps preview first when no query editor is available", () => {
+ const container = renderInspector(false);
+ const tabs = Array.from(container.querySelectorAll('[role="tab"]'));
+
+ expect(tabs.map(({ textContent }) => textContent)).toEqual([
+ "Preview",
+ "Diagnostics",
+ ]);
+ expect(tabs[0].getAttribute("data-state")).toBe("active");
+});
diff --git a/apps/builder/app/builder/features/settings-panel/request-inspector.tsx b/apps/builder/app/builder/features/settings-panel/request-inspector.tsx
new file mode 100644
index 0000000000..aebda5b22a
--- /dev/null
+++ b/apps/builder/app/builder/features/settings-panel/request-inspector.tsx
@@ -0,0 +1,134 @@
+import type { ComponentProps, ReactNode, Ref } from "react";
+import {
+ Flex,
+ Grid,
+ PanelTabs,
+ PanelTabsContent,
+ PanelTabsList,
+ PanelTabsTrigger,
+ ScrollAreaNative,
+ Text,
+ Tooltip,
+ theme,
+} from "@webstudio-is/design-system";
+import { InfoCircleIcon } from "@webstudio-is/icons";
+
+export const RequestDiagnosticsContent = ({
+ children,
+}: {
+ children: ReactNode;
+}) => (
+ <ScrollAreaNative css={{ height: "100%", overflow: "auto" }}>
+ <Flex direction="column" gap={3} css={{ padding: theme.panel.padding }}>
+ {children}
+ </Flex>
+ </ScrollAreaNative>
+);
+
+export const RequestDiagnosticsTable = ({
+ children,
+}: {
+ children: ReactNode;
+}) => (
+ <Grid
+ css={{
+ border: `1px solid ${theme.colors.borderMain}`,
+ borderRadius: theme.borderRadius[4],
+ overflow: "hidden",
+ }}
+ >
+ {children}
+ </Grid>
+);
+
+export const RequestDiagnosticsRow = ({
+ label,
+ value,
+ description,
+ valueColor,
+}: {
+ label: string;
+ value: ReactNode;
+ description?: ReactNode;
+ valueColor?: ComponentProps<typeof Text>["color"];
+}) => (
+ <Grid
+ columns={2}
+ gap={2}
+ css={{
+ padding: theme.spacing[5],
+ borderBottom: `1px solid ${theme.colors.borderMain}`,
+ "&:last-child": { borderBottom: 0 },
+ }}
+ >
+ <Flex align="center" gap={1}>
+ <Text color="moreSubtle">{label}</Text>
+ {description !== undefined && (
+ <Tooltip variant="wrapped" content={description}>
+ <InfoCircleIcon tabIndex={0} />
+ </Tooltip>
+ )}
+ </Flex>
+ <Text
+ color={valueColor}
+ userSelect="text"
+ css={{ fontVariantNumeric: "tabular-nums" }}
+ >
+ {value}
+ </Text>
+ </Grid>
+);
+
+export const RequestInspector = ({
+ queryContainerRef,
+ preview,
+ diagnostics,
+}: {
+ queryContainerRef?: Ref<HTMLDivElement>;
+ preview: ReactNode;
+ diagnostics?: ReactNode;
+}) => (
+ <PanelTabs
+ key={queryContainerRef === undefined ? "preview" : "query"}
+ defaultValue={queryContainerRef === undefined ? "preview" : "query"}
+ css={{ height: "100%", minWidth: 0, overflow: "hidden" }}
+ >
+ <PanelTabsList
+ aria-label="Request details"
+ css={{
+ flexShrink: 0,
+ borderBottom: `1px solid ${theme.colors.borderMain}`,
+ }}
+ >
+ {queryContainerRef !== undefined && (
+ <PanelTabsTrigger value="query">Query</PanelTabsTrigger>
+ )}
+ <PanelTabsTrigger value="preview">Preview</PanelTabsTrigger>
+ <PanelTabsTrigger value="diagnostics">Diagnostics</PanelTabsTrigger>
+ </PanelTabsList>
+ {queryContainerRef !== undefined && (
+ <PanelTabsContent
+ value="query"
+ css={{ flex: 1, position: "relative", overflow: "hidden" }}
+ >
+ <div ref={queryContainerRef} style={{ height: "100%" }} />
+ </PanelTabsContent>
+ )}
+ <PanelTabsContent
+ value="preview"
+ css={{ flex: 1, position: "relative", overflow: "hidden" }}
+ >
+ {preview}
+ </PanelTabsContent>
+ <PanelTabsContent
+ value="diagnostics"
+ css={{ flex: 1, position: "relative", overflow: "hidden" }}
+ >
+ {diagnostics ?? (
+ <Flex align="center" justify="center" css={{ height: "100%" }}>
+ <Text color="moreSubtle">No diagnostics available</Text>
+ </Flex>
+ )}
+ </PanelTabsContent>
+ </PanelTabs>
+);
diff --git a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
index 0adc756f62..34a990c65e 100644
--- a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
@@ -2,6 +2,8 @@ import { z } from "zod";
import { computed } from "nanostores";
import {
forwardRef,
+ lazy,
+ Suspense,
useEffect,
useId,
useImperativeHandle,
@@ -11,6 +13,10 @@ import {
} from "react";
import { useStore } from "@nanostores/react";
import {
+ encodeDataVariableId,
+ isAssetsResource as isAssetsResourceRecord,
+ SYSTEM_VARIABLE_ID,
+ systemParameter,
type DataSources,
type Resource,
type DataSource,
@@ -18,13 +24,10 @@ import {
type PageTemplate,
} from "@webstudio-is/sdk";
import {
- encodeDataVariableId,
generateObjectExpression,
isLiteralExpression,
- parseObjectExpression,
- SYSTEM_VARIABLE_ID,
- systemParameter,
-} from "@webstudio-is/sdk";
+ parseExpressionObject,
+} from "@webstudio-is/expression";
import {
serializeValue,
sitemapResourceUrl,
@@ -38,6 +41,7 @@ import {
InputErrorsTooltip,
InputField,
Label,
+ ProChip,
Select,
SmallIconButton,
Text,
@@ -47,35 +51,38 @@ import {
} from "@webstudio-is/design-system";
import { TrashIcon, InfoCircleIcon, PlusIcon } from "@webstudio-is/icons";
import { humanizeString } from "~/shared/string-utils";
-import { $variableValuesByInstanceSelector } from "~/shared/nano-states";
-import { $dataSources } from "~/shared/sync/data-stores";
-import { $resources } from "~/shared/sync/data-stores";
import {
- BindingControl,
- BindingPopover,
- evaluateExpressionWithinScope,
-} from "~/builder/shared/binding-popover";
+ $permissions,
+ $selectedInstance,
+ $selectedInstancePathWithRoot,
+ $selectedPage,
+ $variableValuesByInstanceSelector,
+ getInstanceKey,
+} from "~/shared/nano-states";
+import { $dataSources, $resources } from "~/shared/sync/data-stores";
+import { evaluateExpressionWithinScope } from "~/builder/shared/binding-popover";
+import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
import { ExpressionEditor } from "~/builder/shared/expression-editor";
import {
EditorDialog,
EditorDialogButton,
EditorDialogControl,
} from "~/shared/code-editor-base";
-import {
- $selectedInstance,
- $selectedInstancePathWithRoot,
- $selectedPage,
- getInstanceKey,
-} from "~/shared/nano-states";
-import type { InstancePath } from "@webstudio-is/project-build/runtime";
import { executeRuntimeMutation } from "~/shared/instance-utils/data";
import {
createResourceFieldsFromFormData,
validateResourceBodyExpression,
validateResourceUrlExpression,
+ type InstancePath,
type ResourceBodyInputType,
} from "@webstudio-is/project-build/runtime";
import { parseCurl, type CurlRequest } from "./curl";
+import { CenteredPanelMessage, Row } from "./shared";
+const AssetQueryForm = lazy(() =>
+ import("./asset-query-form").then(({ AssetQueryForm }) => ({
+ default: AssetQueryForm,
+ }))
+);
export const UrlField = ({
scope,
@@ -118,59 +125,59 @@ export const UrlField = ({
</Tooltip>
</Label>
<input type="hidden" readOnly={true} name="url" value={value} />
- <BindingControl>
- <InputErrorsTooltip errors={error ? [error] : undefined}>
- <TextArea
- ref={ref}
- name="url-validator"
- id={urlId}
- rows={1}
- grow={true}
- // expressions with variables cannot be edited
- disabled={isLiteralExpression(value) === false}
- color={error ? "error" : undefined}
- value={String(evaluateExpressionWithinScope(value, scope))}
- onChange={(value) => {
- const curl = parseCurl(value);
- if (curl) {
- onCurlPaste(curl);
- return;
- }
- try {
- const url = new URL(value);
- if (url.searchParams.size > 0) {
- const searchParams: Resource["searchParams"] = [];
- for (const [name, value] of url.searchParams) {
- searchParams.push({ name, value: JSON.stringify(value) });
- }
- // remove all search params from url
- url.search = "";
- // update text value as string literal
- onChange(JSON.stringify(url.href), searchParams);
+ <BindableExpressionControl
+ expression={value}
+ value={String(evaluateExpressionWithinScope(value, scope))}
+ bound={isLiteralExpression(value) === false}
+ allowBindingOverwrite={false}
+ scope={scope}
+ aliases={aliases}
+ onChangeValue={(value) => onChange(JSON.stringify(value))}
+ onChangeExpression={onChange}
+ onRemove={(value) => onChange(JSON.stringify(value))}
+ renderControl={({ value, readOnly, onChangeValue }) => (
+ <InputErrorsTooltip errors={error ? [error] : undefined}>
+ <TextArea
+ ref={ref}
+ name="url-validator"
+ id={urlId}
+ rows={1}
+ grow={true}
+ disabled={readOnly}
+ color={error ? "error" : undefined}
+ value={value}
+ onChange={(value) => {
+ const curl = parseCurl(value);
+ if (curl) {
+ onCurlPaste(curl);
return;
}
- } catch {
- // serialize without changes when url is invalid
+ try {
+ const url = new URL(value);
+ if (url.searchParams.size > 0) {
+ const searchParams: Resource["searchParams"] = [];
+ for (const [name, value] of url.searchParams) {
+ searchParams.push({ name, value: JSON.stringify(value) });
+ }
+ // remove all search params from url
+ url.search = "";
+ // update text value as string literal
+ onChange(JSON.stringify(url.href), searchParams);
+ return;
+ }
+ } catch {
+ // serialize without changes when url is invalid
+ }
+ onChangeValue(value);
+ }}
+ onBlur={(event) => event.currentTarget.checkValidity()}
+ onInvalid={(event) =>
+ setError(event.currentTarget.validationMessage)
}
- onChange(JSON.stringify(value));
- }}
- onBlur={(event) => event.currentTarget.checkValidity()}
- onInvalid={(event) =>
- setError(event.currentTarget.validationMessage)
- }
- />
- </InputErrorsTooltip>
- <BindingPopover
- scope={scope}
- aliases={aliases}
- variant={isLiteralExpression(value) ? "default" : "bound"}
- value={value}
- onChange={onChange}
- onRemove={(evaluatedValue) =>
- onChange(JSON.stringify(evaluatedValue))
- }
- />
- </BindingControl>
+ />
+ </InputErrorsTooltip>
+ )}
+ />
</Grid>
);
};
@@ -196,9 +203,12 @@ export const MethodField = ({
);
};
-const SearchParamPair = ({
+type ExpressionPair = Resource["headers"][number];
+
+const ExpressionNameValuePair = ({
aliases,
scope,
+ kind,
name,
value,
onChange,
@@ -206,15 +216,14 @@ const SearchParamPair = ({
}: {
aliases: Map<string, string>;
scope: Record<string, unknown>;
+ kind: "header" | "search param";
name: string;
value: string;
onChange: (name: string, value: string) => void;
onDelete: () => void;
}) => {
const evaluatedValue = evaluateExpressionWithinScope(value, scope);
- // expressions with variables or objects cannot be edited from input
- const isValueUnboundString =
- isLiteralExpression(value) && typeof evaluatedValue === "string";
+ const isValueString = typeof evaluatedValue === "string";
return (
<Grid
gap={2}
@@ -225,35 +234,42 @@ const SearchParamPair = ({
// autofocus only new fields
autoFocus={name === ""}
placeholder="Name"
- name="search-param-name"
+ name={kind === "header" ? "header-name" : "search-param-name"}
value={name}
onChange={(event) => onChange(event.target.value, value)}
/>
- <input type="hidden" name="search-param-value" value={value} />
- <BindingControl>
- <InputField
- placeholder="Value"
- name="search-param-value-literal"
- disabled={!isValueUnboundString}
- value={serializeValue(evaluatedValue)}
- // update text value as string literal
- onChange={(event) =>
- onChange(name, JSON.stringify(event.target.value))
- }
- />
- <BindingPopover
- scope={scope}
- aliases={aliases}
- variant={isLiteralExpression(value) ? "default" : "bound"}
- value={value}
- onChange={(newValue) => onChange(name, newValue)}
- onRemove={(evaluatedValue) =>
- onChange(name, JSON.stringify(evaluatedValue))
- }
- />
- </BindingControl>
+ <input
+ type="hidden"
+ readOnly={true}
+ name={kind === "header" ? "header-value" : "search-param-value"}
+ value={value}
+ />
+ <BindableExpressionControl
+ expression={value}
+ value={serializeValue(evaluatedValue)}
+ bound={isLiteralExpression(value) === false}
+ allowBindingOverwrite={false}
+ scope={scope}
+ aliases={aliases}
+ onChangeValue={(value) => onChange(name, JSON.stringify(value))}
+ onChangeExpression={(value) => onChange(name, value)}
+ onRemove={(value) => onChange(name, JSON.stringify(value))}
+ renderControl={({ value, readOnly, onChangeValue }) => (
+ <InputField
+ placeholder="Value"
+ name={
+ kind === "header"
+ ? "header-value-validator"
+ : "search-param-value-literal"
+ }
+ disabled={readOnly || !isValueString}
+ value={value}
+ onChange={(event) => onChangeValue(event.target.value)}
+ />
+ )}
+ />
<SmallIconButton
- aria-label="Delete search param"
+ aria-label={`Delete ${kind}`}
variant="destructive"
icon={<TrashIcon />}
onClick={onDelete}
@@ -262,57 +278,53 @@ const SearchParamPair = ({
);
};
-export const SearchParams = ({
+const ExpressionPairs = ({
scope,
aliases,
- searchParams,
+ kind,
+ values,
onChange,
}: {
scope: Record<string, unknown>;
aliases: Map<string, string>;
- searchParams: NonNullable<Resource["searchParams"]>;
- onChange: (searchParams: NonNullable<Resource["searchParams"]>) => void;
+ kind: "header" | "search param";
+ values: ExpressionPair[];
+ onChange: (values: ExpressionPair[]) => void;
}) => {
+ const label = kind === "header" ? "Headers" : "Search params";
return (
<Grid gap={1}>
<Flex justify="between" align="center">
- <Label>Search params</Label>
+ <Label>{label}</Label>
<SmallIconButton
- aria-label="Add another search param"
+ aria-label={`Add another ${kind}`}
icon={<PlusIcon />}
- onClick={() => {
- // use empty string expression as default
- const newSearchParams = [
- ...searchParams,
- { name: "", value: `""` },
- ];
- onChange(newSearchParams);
- }}
+ // Use an empty string expression as the default value.
+ onClick={() => onChange([...values, { name: "", value: `""` }])}
/>
</Flex>
<Grid gap={2}>
- {searchParams.map((searchParam, index) => (
- <SearchParamPair
+ {values.map((item, index) => (
+ <ExpressionNameValuePair
key={index}
scope={scope}
aliases={aliases}
- name={searchParam.name}
- value={searchParam.value}
+ kind={kind}
+ name={item.name}
+ value={item.value}
onChange={(name, value) => {
- const newSearchParams = [...searchParams];
- newSearchParams[index] = { name, value };
- onChange(newSearchParams);
- }}
- onDelete={() => {
- const newSearchParams = [...searchParams];
- newSearchParams.splice(index, 1);
- onChange(newSearchParams);
+ const next = [...values];
+ next[index] = { name, value };
+ onChange(next);
}}
+ onDelete={() =>
+ onChange(values.filter((_, position) => position !== index))
+ }
/>
))}
- {searchParams.length === 0 && (
+ {values.length === 0 && (
<Text color="subtle" align="center">
- No search params
+ No {label.toLowerCase()}
</Text>
)}
</Grid>
@@ -320,126 +332,25 @@ export const SearchParams = ({
);
};
-const HeaderPair = ({
- aliases,
- scope,
- name,
- value,
- onChange,
- onDelete,
+export const SearchParams = ({
+ searchParams,
+ ...props
}: {
- aliases: Map<string, string>;
scope: Record<string, unknown>;
- name: string;
- value: string;
- onChange: (name: string, value: string) => void;
- onDelete: () => void;
-}) => {
- const evaluatedValue = evaluateExpressionWithinScope(value, scope);
- // expressions with variables or objects cannot be edited from input
- const isValueUnboundString =
- isLiteralExpression(value) && typeof evaluatedValue === "string";
- return (
- <Grid
- gap={2}
- align="center"
- css={{ gridTemplateColumns: `120px 1fr min-content` }}
- >
- <InputField
- // autofocus only new fields
- autoFocus={name === ""}
- placeholder="Name"
- name="header-name"
- value={name}
- onChange={(event) => onChange(event.target.value, value)}
- />
- <input hidden={true} readOnly={true} name="header-value" value={value} />
- <BindingControl>
- <InputField
- placeholder="Value"
- name="header-value-validator"
- disabled={!isValueUnboundString}
- value={serializeValue(evaluatedValue)}
- // update text value as string literal
- onChange={(event) =>
- onChange(name, JSON.stringify(event.target.value))
- }
- />
- <BindingPopover
- scope={scope}
- aliases={aliases}
- variant={isLiteralExpression(value) ? "default" : "bound"}
- value={value}
- onChange={(newValue) => onChange(name, newValue)}
- onRemove={(evaluatedValue) =>
- onChange(name, JSON.stringify(evaluatedValue))
- }
- />
- </BindingControl>
- <SmallIconButton
- aria-label="Delete header"
- variant="destructive"
- icon={<TrashIcon />}
- onClick={onDelete}
- />
- </Grid>
- );
-};
+ aliases: Map<string, string>;
+ searchParams: NonNullable<Resource["searchParams"]>;
+ onChange: (searchParams: NonNullable<Resource["searchParams"]>) => void;
+}) => <ExpressionPairs {...props} kind="search param" values={searchParams} />;
export const Headers = ({
- scope,
- aliases,
headers,
- onChange,
+ ...props
}: {
- scope: Record<string, unknown>;
aliases: Map<string, string>;
+ scope: Record<string, unknown>;
headers: Resource["headers"];
onChange: (headers: Resource["headers"]) => void;
-}) => {
- return (
- <Grid gap={1}>
- <Flex justify="between" align="center">
- <Label>Headers</Label>
- <SmallIconButton
- aria-label="Add another search param"
- icon={<PlusIcon />}
- onClick={() => {
- // use empty string expression as default
- const newHeaders = [...headers, { name: "", value: `""` }];
- onChange(newHeaders);
- }}
- />
- </Flex>
- <Grid gap={2}>
- {headers.map((header, index) => (
- <HeaderPair
- key={index}
- scope={scope}
- aliases={aliases}
- name={header.name}
- value={header.value}
- onChange={(name, value) => {
- const newHeaders = [...headers];
- newHeaders[index] = { name, value };
- onChange(newHeaders);
- }}
- onDelete={() => {
- const newHeaders = [...headers];
- newHeaders.splice(index, 1);
- onChange(newHeaders);
- }}
- />
- ))}
- {headers.length === 0 && (
- <Text color="subtle" align="center">
- No headers
- </Text>
- )}
- </Grid>
- </Grid>
- );
-};
+}) => <ExpressionPairs {...props} kind="header" values={headers} />;
const CacheMaxAge = ({
value,
@@ -597,7 +508,7 @@ export const useResourceScope = ({ variable }: { variable?: DataSource }) => {
};
type PanelApi = {
- save: (formData: FormData) => void;
+ save: (formData: FormData) => void | false;
};
type BodyType = ResourceBodyInputType;
@@ -643,6 +554,16 @@ const BodyField = ({
typeof evaluatedValue === "object" && evaluatedValue !== null;
onChange(newBody, isBodyObject ? "json" : bodyType);
};
+ const displayedValue =
+ bodyType === "json"
+ ? isBodyLiteral
+ ? value
+ : (JSON.stringify(
+ evaluateExpressionWithinScope(value, scope),
+ null,
+ 2
+ ) ?? "")
+ : String(evaluateExpressionWithinScope(value, scope) ?? "");
return (
<Grid gap={1}>
@@ -678,57 +599,54 @@ const BodyField = ({
setBodyError(event.currentTarget.validationMessage)
}
/>
- <BindingControl>
- <InputErrorsTooltip errors={bodyError ? [bodyError] : undefined}>
- {bodyType === "json" ? (
- // wrap with div to position error tooltip
- <div>
- <ExpressionEditor
+ <BindableExpressionControl
+ expression={value}
+ value={displayedValue}
+ bound={isBodyLiteral === false}
+ allowBindingOverwrite={false}
+ scope={scope}
+ aliases={aliases}
+ parseValue={(value) =>
+ bodyType === "json" ? evaluateExpressionWithinScope(value, {}) : value
+ }
+ onChangeValue={(value) =>
+ updateBody(bodyType === "json" ? value : JSON.stringify(value))
+ }
+ onChangeExpression={(value) => {
+ updateBody(value);
+ setIsBodyLiteral(isLiteralExpression(value));
+ }}
+ onRemove={(value) => {
+ updateBody(JSON.stringify(value));
+ setIsBodyLiteral(true);
+ }}
+ renderControl={({ value, readOnly, onChangeValue }) => (
+ <InputErrorsTooltip errors={bodyError ? [bodyError] : undefined}>
+ {bodyType === "json" ? (
+ // wrap with div to position error tooltip
+ <div>
+ <ExpressionEditor
+ color={bodyError ? "error" : undefined}
+ readOnly={readOnly}
+ value={value}
+ onChange={onChangeValue}
+ onChangeComplete={() => bodyRef.current?.checkValidity()}
+ />
+ </div>
+ ) : (
+ <TextArea
+ autoGrow={true}
+ maxRows={10}
+ disabled={readOnly}
color={bodyError ? "error" : undefined}
- // expressions with variables cannot be edited
- readOnly={isBodyLiteral === false}
- value={
- isBodyLiteral
- ? value
- : (JSON.stringify(
- evaluateExpressionWithinScope(value, scope),
- null,
- 2
- ) ?? "")
- }
- onChange={updateBody}
- onChangeComplete={() => bodyRef.current?.checkValidity()}
+ value={value}
+ onChange={onChangeValue}
+ onBlur={() => bodyRef.current?.checkValidity()}
/>
- </div>
- ) : (
- <TextArea
- autoGrow={true}
- maxRows={10}
- // expressions with variables cannot be edited
- disabled={isBodyLiteral === false}
- color={bodyError ? "error" : undefined}
- value={String(evaluateExpressionWithinScope(value, scope) ?? "")}
- // update text value as string literal
- onChange={(newValue) => updateBody(JSON.stringify(newValue))}
- onBlur={() => bodyRef.current?.checkValidity()}
- />
- )}
- </InputErrorsTooltip>
- <BindingPopover
- scope={scope}
- aliases={aliases}
- variant={isBodyLiteral ? "default" : "bound"}
- value={value}
- onChange={(value) => {
- updateBody(value);
- setIsBodyLiteral(isLiteralExpression(value));
- }}
- onRemove={(evaluatedValue) => {
- updateBody(JSON.stringify(evaluatedValue));
- setIsBodyLiteral(true);
- }}
- />
- </BindingControl>
+ )}
+ </InputErrorsTooltip>
+ )}
+ />
</Grid>
);
};
@@ -821,87 +739,99 @@ export const ResourceForm = forwardRef<
return (
<>
- <MethodField value={method} onChange={setMethod} />
- <UrlField
- scope={scope}
- aliases={aliases}
- value={url}
- onChange={(urlExpression, searchParams) => {
- setUrl(urlExpression);
- if (searchParams) {
- setSearchParams((prev) => [...prev, ...searchParams]);
- }
- }}
- onCurlPaste={(curl) => {
- // update all feilds when curl is paste into url field
- setMethod(curl.method);
- setUrl(JSON.stringify(curl.url));
- setSearchParams(
- (curl.searchParams ?? []).map((header) => ({
- name: header.name,
- value: JSON.stringify(header.value),
- }))
- );
- const parsedHeaders = parseHeaders(
- curl.headers.map((header) => ({
- name: header.name,
- value: JSON.stringify(header.value),
- }))
- );
- setMaxAge(parsedHeaders.maxAge);
- setHeaders(parsedHeaders.headers);
- setBodyType(parsedHeaders.bodyType);
- setBody(JSON.stringify(curl.body));
- }}
- />
- <SearchParams
- scope={scope}
- aliases={aliases}
- searchParams={searchParams}
- onChange={setSearchParams}
- />
- <CacheMaxAge
- value={maxAge}
- onChange={(newMaxAge) => {
- setMaxAge(newMaxAge);
- // reset header
- setHeaders((headers) =>
- headers.filter(({ name }) => !isCacheControl(name))
- );
- }}
- />
- <Headers
- scope={scope}
- aliases={aliases}
- headers={headers}
- onChange={(newHeaders) => {
- // reset dedicated fields
- if (newHeaders.some(({ name }) => isCacheControl(name))) {
- setMaxAge(undefined);
- }
- if (newHeaders.some(({ name }) => isContentType(name))) {
- setBodyType(undefined);
- }
- setHeaders(newHeaders);
- }}
- />
- {method !== "get" && (
- <BodyField
+ <Row>
+ <MethodField value={method} onChange={setMethod} />
+ </Row>
+ <Row>
+ <UrlField
scope={scope}
aliases={aliases}
- value={body ?? ""}
- bodyType={bodyType}
- onChange={(newBody, newBodyType) => {
- setBodyType(newBodyType);
+ value={url}
+ onChange={(urlExpression, searchParams) => {
+ setUrl(urlExpression);
+ if (searchParams) {
+ setSearchParams((prev) => [...prev, ...searchParams]);
+ }
+ }}
+ onCurlPaste={(curl) => {
+ // update all feilds when curl is paste into url field
+ setMethod(curl.method);
+ setUrl(JSON.stringify(curl.url));
+ setSearchParams(
+ (curl.searchParams ?? []).map((header) => ({
+ name: header.name,
+ value: JSON.stringify(header.value),
+ }))
+ );
+ const parsedHeaders = parseHeaders(
+ curl.headers.map((header) => ({
+ name: header.name,
+ value: JSON.stringify(header.value),
+ }))
+ );
+ setMaxAge(parsedHeaders.maxAge);
+ setHeaders(parsedHeaders.headers);
+ setBodyType(parsedHeaders.bodyType);
+ setBody(JSON.stringify(curl.body));
+ }}
+ />
+ </Row>
+ <Row>
+ <SearchParams
+ scope={scope}
+ aliases={aliases}
+ searchParams={searchParams}
+ onChange={setSearchParams}
+ />
+ </Row>
+ <Row>
+ <CacheMaxAge
+ value={maxAge}
+ onChange={(newMaxAge) => {
+ setMaxAge(newMaxAge);
// reset header
- if (newBodyType) {
- setHeaders((headers) =>
- headers.filter(({ name }) => !isContentType(name))
- );
+ setHeaders((headers) =>
+ headers.filter(({ name }) => !isCacheControl(name))
+ );
+ }}
+ />
+ </Row>
+ <Row>
+ <Headers
+ scope={scope}
+ aliases={aliases}
+ headers={headers}
+ onChange={(newHeaders) => {
+ // reset dedicated fields
+ if (newHeaders.some(({ name }) => isCacheControl(name))) {
+ setMaxAge(undefined);
+ }
+ if (newHeaders.some(({ name }) => isContentType(name))) {
+ setBodyType(undefined);
}
- setBody(newBody);
+ setHeaders(newHeaders);
}}
/>
+ </Row>
+ {method !== "get" && (
+ <Row>
+ <BodyField
+ scope={scope}
+ aliases={aliases}
+ value={body ?? ""}
+ bodyType={bodyType}
+ onChange={(newBody, newBodyType) => {
+ setBodyType(newBodyType);
+ // reset header
+ if (newBodyType) {
+ setHeaders((headers) =>
+ headers.filter(({ name }) => !isContentType(name))
+ );
+ }
+ setBody(newBody);
+ }}
+ />
+ </Row>
)}
</>
);
@@ -910,15 +840,29 @@ ResourceForm.displayName = "ResourceForm";
export const SystemResourceForm = forwardRef<
undefined | PanelApi,
- { variable?: DataSource }
->(({ variable }, ref) => {
+ {
+ variable?: DataSource;
+ querySourceContainer?: Element | null;
+ onQueryActiveChange?: (active: boolean) => void;
+ }
+>(({ variable, querySourceContainer, onQueryActiveChange }, ref) => {
+ const { scope, aliases } = useResourceScope({ variable });
const resources = useStore($resources);
+ const { allowDynamicData } = useStore($permissions);
const resource =
variable?.type === "resource"
? resources.get(variable.resourceId)
: undefined;
+ const isStoredAssetQuery =
+ resource !== undefined && isAssetsResourceRecord(resource);
+ const assetsLocalResource = {
+ label: "Assets",
+ value: JSON.stringify(assetsResourceUrl),
+ description:
+ "Loads all project assets by default, with optional filters, sorting, pagination, and file content.",
+ };
const localResources = [
{
label: "Sitemap",
@@ -926,29 +870,35 @@ export const SystemResourceForm = forwardRef<
description: "Resource that loads the sitemap data of the current site.",
},
{
- label: "Current Date",
+ label: "Current date",
value: JSON.stringify(currentDateResourceUrl),
description:
"Provides current date information (year, month, day) normalized to midnight UTC. Time components are set to 00:00:00 to prevent React hydration errors.",
},
- {
- label: "Assets",
- value: JSON.stringify(assetsResourceUrl),
- description:
- "Resource that loads the list of assets of the current project.",
- },
+ assetsLocalResource,
];
const [localResource, setLocalResource] = useState(() => {
+ if (isStoredAssetQuery) {
+ return assetsLocalResource;
+ }
return (
localResources.find(
(localResource) => localResource.value === resource?.url
) ?? localResources[0]
);
});
-
+ const isAssetsResource =
+ localResource.value === JSON.stringify(assetsResourceUrl);
+ useEffect(() => {
+ onQueryActiveChange?.(isAssetsResource);
+ return () => onQueryActiveChange?.(false);
+ }, [isAssetsResource, onQueryActiveChange]);
useImperativeHandle(ref, () => ({
save: (formData) => {
+ if (formData.get("asset-query-valid") === "false") {
+ return false;
+ }
// preserve existing instance scope when edit
const scopeInstanceId =
variable?.scopeInstanceId ?? $selectedInstance.get()?.id;
@@ -976,25 +926,51 @@ export const SystemResourceForm = forwardRef<
return (
<>
- <input type="hidden" name="method" value="get" />
+ <input
+ type="hidden"
+ name="method"
+ value={isAssetsResource ? "post" : "get"}
+ />
<input type="hidden" name="url" value={localResource.value} />
- <Flex direction="column" css={{ gap: theme.spacing[3] }}>
- <Label htmlFor={resourceId}>Resource</Label>
- <Select
- options={localResources}
- getLabel={(option) => option.label}
- getValue={(option) => option.value}
- getDescription={(option) => {
- return (
- <Box css={{ width: theme.spacing[25] }}>
- {option?.description}
- </Box>
- );
- }}
- value={localResource}
- onChange={setLocalResource}
- />
- </Flex>
+ <Row>
+ <Grid gap={1}>
+ <Label htmlFor={resourceId}>Resource</Label>
+ <Select
+ options={localResources}
+ getLabel={(option) => (
+ <Flex direction="row" gap="2" align="center">
+ {option.label}
+ {option.value === assetsLocalResource.value &&
+ allowDynamicData === false && <ProChip>Pro</ProChip>}
+ </Flex>
+ )}
+ getValue={(option) => option.value}
+ getDescription={(option) => {
+ return (
+ <Box css={{ width: theme.spacing[25] }}>
+ {option?.description}
+ </Box>
+ );
+ }}
+ value={localResource}
+ onChange={setLocalResource}
+ />
+ </Grid>
+ </Row>
+ {isAssetsResource && (
+ <Suspense
+ fallback={
+ <CenteredPanelMessage>Loading query editor…</CenteredPanelMessage>
+ }
+ >
+ <AssetQueryForm
+ resource={resource}
+ scope={scope}
+ aliases={aliases}
+ sourceContainer={querySourceContainer}
+ />
+ </Suspense>
+ )}
</>
);
});
@@ -1022,8 +998,8 @@ export const GraphqlResourceForm = forwardRef<
const [maxAge, setMaxAge] = useState(parsedHeaders.maxAge);
const [headers, setHeaders] = useState(parsedHeaders.headers);
- const [bodyExpressions] = useState(() =>
- parseObjectExpression(resource?.body ?? "")
+ const [bodyExpressions] = useState(
+ () => parseExpressionObject(resource?.body ?? "") ?? new Map()
);
const queryId = useId();
const [query, setQuery] = useState(
@@ -1098,129 +1074,147 @@ export const GraphqlResourceForm = forwardRef<
)}
/>
- <UrlField
- scope={scope}
- aliases={aliases}
- value={url}
- onChange={setUrl}
- onCurlPaste={(curl) => {
- // update all feilds when curl is paste into url field
- setUrl(JSON.stringify(curl.url));
- const parsedHeaders = parseHeaders(
- curl.headers.map((header) => ({
- name: header.name,
- value: JSON.stringify(header.value),
- }))
- );
- setMaxAge(parsedHeaders.maxAge);
- setHeaders(parsedHeaders.headers);
- const body = zGraphqlBody.safeParse(curl.body);
- if (body.success) {
- setQuery(body.data.query);
- setVariables(JSON.stringify(body.data.variables, null, 2));
- }
- }}
- />
+ <Row>
+ <UrlField
+ scope={scope}
+ aliases={aliases}
+ value={url}
+ onChange={setUrl}
+ onCurlPaste={(curl) => {
+ // update all feilds when curl is paste into url field
+ setUrl(JSON.stringify(curl.url));
+ const parsedHeaders = parseHeaders(
+ curl.headers.map((header) => ({
+ name: header.name,
+ value: JSON.stringify(header.value),
+ }))
+ );
+ setMaxAge(parsedHeaders.maxAge);
+ setHeaders(parsedHeaders.headers);
+ const body = zGraphqlBody.safeParse(curl.body);
+ if (body.success) {
+ setQuery(body.data.query);
+ setVariables(JSON.stringify(body.data.variables, null, 2));
+ }
+ }}
+ />
+ </Row>
- <Grid gap={1}>
- <Label htmlFor={queryId}>Query</Label>
- <EditorDialogControl>
- <TextArea
- name="query"
- id={queryId}
- rows={3}
- maxRows={10}
- autoGrow={true}
- value={query}
- onChange={setQuery}
- />
- <EditorDialog
- title="GraphQL Query"
- content={<TextArea grow={true} value={query} onChange={setQuery} />}
- >
- <EditorDialogButton />
- </EditorDialog>
- </EditorDialogControl>
- </Grid>
+ <Row>
+ <Grid gap={1}>
+ <Label htmlFor={queryId}>Query</Label>
+ <EditorDialogControl>
+ <TextArea
+ name="query"
+ id={queryId}
+ rows={3}
+ maxRows={10}
+ autoGrow={true}
+ value={query}
+ onChange={setQuery}
+ />
+ <EditorDialog
+ title="GraphQL Query"
+ content={
+ <TextArea grow={true} value={query} onChange={setQuery} />
+ }
+ >
+ <EditorDialogButton />
+ </EditorDialog>
+ </EditorDialogControl>
+ </Grid>
+ </Row>
- <Grid gap={1}>
- <Label>GraphQL variables</Label>
- {/* use invisible text input to reflect expression editor in form
+ <Row>
+ <Grid gap={1}>
+ <Label>GraphQL variables</Label>
+ {/* use invisible text input to reflect expression editor in form
type=hidden does not emit invalid event */}
- <input
- ref={variablesRef}
- style={{ display: "none" }}
- type="text"
- name="variables"
- data-color={variablesError ? "error" : undefined}
- value={variables}
- onChange={() => {}}
- onInvalid={(event) =>
- setVariablesError(event.currentTarget.validationMessage)
- }
- />
- <BindingControl>
- <InputErrorsTooltip
- errors={variablesError ? [variablesError] : undefined}
- >
- {/* wrap with div to position error tooltip */}
- <div>
- <ExpressionEditor
- color={variablesError ? "error" : undefined}
- readOnly={isVariablesLiteral === false}
- value={
- isVariablesLiteral
- ? variables
- : (JSON.stringify(
- evaluateExpressionWithinScope(variables, scope),
- null,
- 2
- ) ?? "")
- }
- onChange={setVariables}
- onChangeComplete={() => variablesRef.current?.checkValidity()}
- />
- </div>
- </InputErrorsTooltip>
- <BindingPopover
+ <input
+ ref={variablesRef}
+ style={{ display: "none" }}
+ type="text"
+ name="variables"
+ data-color={variablesError ? "error" : undefined}
+ value={variables}
+ onChange={() => {}}
+ onInvalid={(event) =>
+ setVariablesError(event.currentTarget.validationMessage)
+ }
+ />
+ <BindableExpressionControl
+ expression={variables}
+ value={
+ isVariablesLiteral
+ ? variables
+ : (JSON.stringify(
+ evaluateExpressionWithinScope(variables, scope),
+ null,
+ 2
+ ) ?? "")
+ }
+ bound={isVariablesLiteral === false}
+ allowBindingOverwrite={false}
scope={scope}
aliases={aliases}
- variant={isVariablesLiteral ? "default" : "bound"}
- value={variables}
- onChange={(value) => {
+ parseValue={(value) => evaluateExpressionWithinScope(value, {})}
+ onChangeValue={setVariables}
+ onChangeExpression={(value) => {
setVariables(value);
setIsVariablesLiteral(isLiteralExpression(value));
}}
- onRemove={(evaluatedValue) => {
- setVariables(JSON.stringify(evaluatedValue));
+ onRemove={(value) => {
+ setVariables(JSON.stringify(value));
setIsVariablesLiteral(true);
}}
+ renderControl={({ value, readOnly, onChangeValue }) => (
+ <InputErrorsTooltip
+ errors={variablesError ? [variablesError] : undefined}
+ >
+ {/* wrap with div to position error tooltip */}
+ <div>
+ <ExpressionEditor
+ color={variablesError ? "error" : undefined}
+ readOnly={readOnly}
+ value={value}
+ onChange={onChangeValue}
+ onChangeComplete={() =>
+ variablesRef.current?.checkValidity()
+ }
+ />
+ </div>
+ </InputErrorsTooltip>
+ )}
/>
- </BindingControl>
- </Grid>
+ </Grid>
+ </Row>
- <CacheMaxAge
- value={maxAge}
- onChange={(newMaxAge) => {
- setMaxAge(newMaxAge);
- setHeaders((headers) =>
- headers.filter(({ name }) => !isCacheControl(name))
- );
- }}
- />
+ <Row>
+ <CacheMaxAge
+ value={maxAge}
+ onChange={(newMaxAge) => {
+ setMaxAge(newMaxAge);
+ setHeaders((headers) =>
+ headers.filter(({ name }) => !isCacheControl(name))
+ );
+ }}
+ />
+ </Row>
- <Headers
- scope={scope}
- aliases={aliases}
- headers={headers}
- onChange={(newHeaders) => {
- // reset dedicated fields
- if (newHeaders.some(({ name }) => isCacheControl(name))) {
- setMaxAge(undefined);
- }
- setHeaders(newHeaders);
- }}
- />
+ <Row>
+ <Headers
+ scope={scope}
+ aliases={aliases}
+ headers={headers}
+ onChange={(newHeaders) => {
+ // reset dedicated fields
+ if (newHeaders.some(({ name }) => isCacheControl(name))) {
+ setMaxAge(undefined);
+ }
+ setHeaders(newHeaders);
+ }}
+ />
+ </Row>
</>
);
});
diff --git a/apps/builder/app/builder/features/settings-panel/shared.tsx b/apps/builder/app/builder/features/settings-panel/shared.tsx
index d8a1033ac7..94c601a0b6 100644
--- a/apps/builder/app/builder/features/settings-panel/shared.tsx
+++ b/apps/builder/app/builder/features/settings-panel/shared.tsx
@@ -1,11 +1,9 @@
-import { atom, computed, type ReadableAtom } from "nanostores";
-import { useStore } from "@nanostores/react";
+import { computed } from "nanostores";
import {
type ComponentPropsWithoutRef,
type ReactNode,
useRef,
useState,
- useMemo,
type ComponentProps,
} from "react";
import {
@@ -20,7 +18,6 @@ import {
} from "@webstudio-is/react-sdk";
import { showAttributeMeta } from "@webstudio-is/project-build/runtime";
import {
- decodeDataSourceVariable,
encodeDataSourceVariable,
SYSTEM_VARIABLE_ID,
systemParameter,
@@ -40,12 +37,10 @@ import {
rawTheme,
} from "@webstudio-is/design-system";
import {
- $dataSourceVariables,
$registeredComponentMetas,
$variableValuesByInstanceSelector,
} from "~/shared/nano-states";
import { $dataSources } from "~/shared/sync/data-stores";
-import type { BindingVariant } from "~/builder/shared/binding-popover";
import { humanizeString } from "~/shared/string-utils";
import {
$selectedInstance,
@@ -243,6 +238,26 @@ export const Row = ({
</Flex>
);
+export const CenteredPanelMessage = ({
+ children,
+ color = "subtle",
+}: {
+ children: ReactNode;
+ color?: ComponentProps<typeof Text>["color"];
+}) => (
+ <Row
+ css={{
+ alignItems: "center",
+ justifyContent: "center",
+ flexGrow: 1,
+ minHeight: 100,
+ textAlign: "center",
+ }}
+ >
+ <Text color={color}>{children}</Text>
+ </Row>
+);
+
export const $selectedInstanceScope = computed(
[
$selectedInstanceKeyWithRoot,
@@ -274,61 +289,6 @@ export const $selectedInstanceScope = computed(
}
);
-export const updateExpressionValue = (expression: string, value: unknown) => {
- const dataSources = $dataSources.get();
- // when expression contains only reference to variable update that variable
- // extract id without parsing expression
- const potentialVariableId = decodeDataSourceVariable(expression);
- if (
- potentialVariableId !== undefined &&
- dataSources.has(potentialVariableId)
- ) {
- const dataSourceId = potentialVariableId;
- const dataSourceVariables = new Map($dataSourceVariables.get());
- dataSourceVariables.set(dataSourceId, value);
- $dataSourceVariables.set(dataSourceVariables);
- }
-};
-
-type BindingState = {
- overwritable: boolean;
- variant: BindingVariant;
-};
-
-export const useBindingState = (expression: undefined | string) => {
- const $bindingState = useMemo((): ReadableAtom<BindingState> => {
- if (expression === undefined) {
- // value is not bound to expression and can be updated
- return atom({ overwritable: true, variant: "default" });
- }
- // try to extract variable id from expression
- const potentialVariableId = decodeDataSourceVariable(expression);
- if (potentialVariableId === undefined) {
- // expression is complex and cannot be updated
- return atom({ overwritable: false, variant: "bound" });
- }
- return computed(
- [$dataSources, $dataSourceVariables],
- (dataSources, dataSourceVariables): BindingState => {
- const dataSource = dataSources.get(potentialVariableId);
- // resources and parameters cannot be updated
- if (dataSource?.type !== "variable") {
- return { overwritable: false, variant: "bound" };
- }
- const variableId = potentialVariableId;
- return {
- overwritable: true,
- variant:
- dataSourceVariables.get(variableId) === undefined
- ? "bound"
- : "overwritten",
- };
- }
- );
- }, [expression]);
- return useStore($bindingState);
-};
-
export const humanizeAttribute = (string: string) => {
if (string.includes("-")) {
return string;
diff --git a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
index 691e83ce87..36ae031298 100644
--- a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
@@ -35,6 +35,7 @@ import {
ProChip,
ScrollArea,
Select,
+ SplitView,
Switch,
Text,
TextArea,
@@ -72,11 +73,10 @@ import {
createDataVariableValueFromInput,
createResourceValueFromFormData,
findUnsetVariableNames,
- parseDataVariableJsonExpression,
validateDataVariableJsonValue,
validateDataVariableNumberValue,
- validateDataVariableStringArrayValue,
} from "@webstudio-is/project-build/runtime";
+import { parseJsonExpression } from "@webstudio-is/expression";
import { validateDataVariableName } from "~/builder/shared/data-variable-utils";
import {
GraphqlResourceForm,
@@ -87,11 +87,20 @@ import {
import { generateCurl } from "./curl";
import {
$hasPendingResources,
+ $resourceDiagnosticsCache,
$resourcesCache,
computeResourceRequest,
getResourceKey,
invalidateResource,
} from "~/shared/resources";
+import { Row } from "./shared";
+import type { AssetQueryPreviewDiagnostics } from "@webstudio-is/content-engine";
+import { RequestInspector } from "./request-inspector";
+import { ContentDatabaseDiagnostics } from "./content-database-diagnostics";
+import {
+ getRequestErrorDiagnostics,
+ RequestErrorDiagnostics,
+} from "./request-error-diagnostics";
const NameField = ({
variable,
@@ -179,7 +188,6 @@ type VariableType =
| "string"
| "number"
| "boolean"
- | "string[]"
| "json"
| "resource"
| "graphql-resource"
@@ -214,11 +222,6 @@ const TypeField = ({
label: "Boolean",
description: "A boolean is a true/false switch.",
},
- {
- value: "string[]",
- label: "String Array",
- description: "A list of text values.",
- },
{
value: "json",
label: "JSON",
@@ -250,11 +253,11 @@ const TypeField = ({
value: "system-resource",
label: (
<Flex direction="row" gap="2" align="center">
- System Resource
+ System resource
{allowDynamicData === false && <ProChip>Pro</ProChip>}
</Flex>
),
- description: "A System Resource is a configuration for Webstudio data.",
+ description: "A system resource is a configuration for Webstudio data.",
},
];
const options = new Map(optionsList.map((option) => [option.value, option]));
@@ -282,7 +285,7 @@ const TypeField = ({
};
type PanelApi = {
- save: (formData: FormData) => void;
+ save: (formData: FormData) => void | false;
};
const ParameterForm = forwardRef<
@@ -312,7 +315,7 @@ ParameterForm.displayName = "ParameterForm";
type ValueVariableType = Extract<
VariableType,
- "string" | "number" | "boolean" | "string[]" | "json"
+ "string" | "number" | "boolean" | "json"
>;
const saveVariable = (
@@ -528,51 +531,6 @@ const JsonForm = forwardRef<
});
JsonForm.displayName = "JsonForm";
-const StringArrayForm = forwardRef<
- undefined | PanelApi,
- {
- variable?: DataSource;
- value: unknown;
- onChange: (value: unknown) => void;
- }
->(({ variable, value: unknownValue, onChange }, ref) => {
- const value = typeof unknownValue === "string" ? unknownValue : "[]";
- const [valueError, setValueError] = useState("");
- const valueRef = useRef<HTMLInputElement>(null);
- useEffect(() => {
- valueRef.current?.setCustomValidity(
- validateDataVariableStringArrayValue(value)
- );
- setValueError("");
- }, [value]);
- useValuePanelRef({ ref, variable, type: "string[]" });
- return (
- <>
- <input
- ref={valueRef}
- style={{ display: "none" }}
- name="value"
- data-color={valueError ? "error" : undefined}
- value={value}
- onChange={() => {}}
- onInvalid={(event) =>
- setValueError(event.currentTarget.validationMessage)
- }
- />
- <Flex direction="column" css={{ gap: theme.spacing[3] }}>
- <Label>Value</Label>
- <ExpressionEditor
- color={valueError ? "error" : undefined}
- value={value}
- onChange={onChange}
- onChangeComplete={() => valueRef.current?.checkValidity()}
- />
- </Flex>
- </>
- );
-});
-StringArrayForm.displayName = "StringArrayForm";
-
const VariablePanelForm = forwardRef<
undefined | PanelApi,
{
@@ -581,10 +539,20 @@ const VariablePanelForm = forwardRef<
onVariableTypeChange: (variableType: VariableType) => void;
value: unknown;
onValueChange: (value: unknown) => void;
+ querySourceContainer: Element | null;
+ onQueryActiveChange: (active: boolean) => void;
}
>(
(
- { variable, variableType, onVariableTypeChange, value, onValueChange },
+ {
+ variable,
+ variableType,
+ onVariableTypeChange,
+ value,
+ onValueChange,
+ querySourceContainer,
+ onQueryActiveChange,
+ },
ref
) => {
const { allowDynamicData } = useStore($permissions);
@@ -615,56 +583,63 @@ const VariablePanelForm = forwardRef<
direction="column"
css={{
overflow: "hidden",
- padding: theme.panel.padding,
+ paddingBlock: theme.panel.paddingBlock,
gap: theme.spacing[7],
}}
>
- <NameField variable={variable} defaultValue={variable?.name ?? ""} />
+ <Row>
+ <NameField
+ variable={variable}
+ defaultValue={variable?.name ?? ""}
+ />
+ </Row>
{variableType !== "parameter" && (
- <TypeField value={variableType} onChange={onVariableTypeChange} />
+ <Row>
+ <TypeField value={variableType} onChange={onVariableTypeChange} />
+ </Row>
)}
{variableType === "parameter" && (
<ParameterForm ref={ref} variable={variable} />
)}
{variableType === "string" && (
- <StringForm
- ref={ref}
- variable={variable}
- value={value}
- onChange={onValueChange}
- />
+ <Row>
+ <StringForm
+ ref={ref}
+ variable={variable}
+ value={value}
+ onChange={onValueChange}
+ />
+ </Row>
)}
{variableType === "number" && (
- <NumberForm
- ref={ref}
- variable={variable}
- value={value}
- onChange={onValueChange}
- />
+ <Row>
+ <NumberForm
+ ref={ref}
+ variable={variable}
+ value={value}
+ onChange={onValueChange}
+ />
+ </Row>
)}
{variableType === "boolean" && (
- <BooleanForm
- ref={ref}
- variable={variable}
- value={value}
- onChange={onValueChange}
- />
+ <Row>
+ <BooleanForm
+ ref={ref}
+ variable={variable}
+ value={value}
+ onChange={onValueChange}
+ />
+ </Row>
)}
{variableType === "json" && (
- <JsonForm
- ref={ref}
- variable={variable}
- value={value}
- onChange={onValueChange}
- />
- )}
- {variableType === "string[]" && (
- <StringArrayForm
- ref={ref}
- variable={variable}
- value={value}
- onChange={onValueChange}
- />
+ <Row>
+ <JsonForm
+ ref={ref}
+ variable={variable}
+ value={value}
+ onChange={onValueChange}
+ />
+ </Row>
)}
{variableType === "resource" && (
<ResourceForm ref={ref} variable={variable} />
@@ -673,7 +648,12 @@ const VariablePanelForm = forwardRef<
<GraphqlResourceForm ref={ref} variable={variable} />
)}
{variableType === "system-resource" && (
- <SystemResourceForm ref={ref} variable={variable} />
+ <SystemResourceForm
+ ref={ref}
+ variable={variable}
+ querySourceContainer={querySourceContainer}
+ onQueryActiveChange={onQueryActiveChange}
+ />
)}
</Flex>
</>
@@ -694,11 +674,15 @@ const VariablePreview = ({
variableType,
variableValue,
onLoadData,
+ queryActive,
+ queryContainerRef,
}: {
variable?: DataSource;
variableType: VariableType;
variableValue: unknown;
onLoadData: () => void;
+ queryActive: boolean;
+ queryContainerRef: (element: HTMLDivElement | null) => void;
}) => {
const isResource =
variableType === "resource" ||
@@ -708,12 +692,14 @@ const VariablePreview = ({
const resources = useStore($resources);
const variableValues = useStore($instanceVariableValues);
const resourcesCache = useStore($resourcesCache);
+ const resourceDiagnosticsCache = useStore($resourceDiagnosticsCache);
const resourceScope = useResourceScope({ variable });
let computedValue: unknown;
+ let resourceDiagnostics: AssetQueryPreviewDiagnostics | undefined;
if (variableType === "string" || variableType === "boolean") {
computedValue = variableValue;
} else if (variableType === "json") {
- computedValue = parseDataVariableJsonExpression(String(variableValue));
+ computedValue = parseJsonExpression(String(variableValue));
} else if (variableType === "number") {
computedValue = Number(variableValue);
if (Number.isNaN(computedValue)) {
@@ -734,12 +720,15 @@ const VariablePreview = ({
}
}
if (parsedResourceRequest) {
- computedValue = resourcesCache.get(getResourceKey(parsedResourceRequest));
+ const resourceKey = getResourceKey(parsedResourceRequest);
+ computedValue = resourcesCache.get(resourceKey);
+ resourceDiagnostics = resourceDiagnosticsCache.get(resourceKey);
}
}
const extensions = useMemo(() => [javascript({}), foldGutterExtension], []);
const editorProps = {
readOnly: true,
+ chromeless: true,
extensions,
// compute value as json lazily only when dialog is open
// by spliting into separate component which is invoked
@@ -748,7 +737,7 @@ const VariablePreview = ({
onChange: () => {},
onChangeComplete: () => {},
};
- return (
+ const preview = (
<Grid
align="stretch"
css={{
@@ -756,6 +745,7 @@ const VariablePreview = ({
overflow: "hidden",
boxSizing: "content-box",
position: "relative",
+ gridTemplateRows: "minmax(0, 1fr)",
}}
>
<EditorContent {...editorProps} />
@@ -777,6 +767,23 @@ const VariablePreview = ({
)}
</Grid>
);
+ if (isResource === false) {
+ return preview;
+ }
+ const requestErrorDiagnostics = getRequestErrorDiagnostics(computedValue);
+ return (
+ <RequestInspector
+ queryContainerRef={queryActive ? queryContainerRef : undefined}
+ preview={preview}
+ diagnostics={
+ requestErrorDiagnostics !== undefined ? (
+ <RequestErrorDiagnostics value={requestErrorDiagnostics} />
+ ) : resourceDiagnostics !== undefined ? (
+ <ContentDatabaseDiagnostics value={resourceDiagnostics} />
+ ) : undefined
+ }
+ />
+ );
};
const VariablePopoverContent = ({
@@ -790,13 +797,17 @@ const VariablePopoverContent = ({
}) => {
const hasPendingResources = useStore($hasPendingResources);
const panelRef = useRef<undefined | PanelApi>(undefined);
+ const [queryActive, setQueryActive] = useState(false);
+ const [querySourceContainer, setQuerySourceContainer] =
+ useState<HTMLDivElement | null>(null);
+ const queryContainerRef = useCallback(
+ (element: HTMLDivElement | null) => setQuerySourceContainer(element),
+ []
+ );
const isSystemVariable = variable?.id === SYSTEM_VARIABLE_ID;
const [value, setValue] = useState<unknown>(() => {
if (variable?.type === "variable") {
- if (
- variable.value.type === "json" ||
- variable.value.type === "string[]"
- ) {
+ if (variable.value.type === "json") {
return formatValue(variable.value.value);
}
return variable.value.value;
@@ -820,12 +831,7 @@ const VariablePopoverContent = ({
}
if (variable?.type === "variable") {
const type = variable.value.type;
- if (
- type === "string" ||
- type === "number" ||
- type === "boolean" ||
- type === "string[]"
- ) {
+ if (type === "string" || type === "number" || type === "boolean") {
return type;
}
return "json";
@@ -849,9 +855,6 @@ const VariablePopoverContent = ({
// empty string gives an error
return prev || "{}";
}
- if (variableType === "string[]") {
- return "[]";
- }
return prev;
});
};
@@ -887,69 +890,76 @@ const VariablePopoverContent = ({
return (
<>
- <Grid
- css={{
- height: "100%",
- gridTemplateColumns: "320px 1fr",
- }}
- >
- <ScrollArea
- // flex fixes content overflowing artificial scroll area
- css={{ display: "flex", flexDirection: "column" }}
- >
- <form
- ref={formRef}
- noValidate={true}
- // exclude from the flow
- style={{ display: "contents" }}
- onSubmit={(event) => {
- event.preventDefault();
- if (isSystemVariable) {
- return;
- }
- const nameElement =
- event.currentTarget.elements.namedItem("name");
- // make sure only name is valid and allow to save everything else
- // to avoid loosing complex configuration when closed accidentally
- if (
- nameElement instanceof HTMLInputElement &&
- nameElement.checkValidity()
- ) {
- const formData = new FormData(event.currentTarget);
- panelRef.current?.save(formData);
- // close popover whenever new variable is created
- // to prevent creating duplicated variable
- if (variable === undefined) {
- onClose();
- }
- }
- }}
+ <SplitView
+ defaultSize={{ value: 320, unit: "px" }}
+ minimumStartSize={240}
+ minimumEndSize={240}
+ separatorLabel="Resize variable configuration"
+ start={
+ <ScrollArea
+ // flex fixes content overflowing artificial scroll area
+ css={{ display: "flex", flexDirection: "column" }}
>
- {/* submit is not triggered when press enter on input without submit button */}
- <button hidden></button>
- <fieldset
+ <form
+ ref={formRef}
+ noValidate={true}
+ // exclude from the flow
style={{ display: "contents" }}
- // forbid editing system variable
- disabled={isSystemVariable}
+ onSubmit={(event) => {
+ event.preventDefault();
+ if (isSystemVariable) {
+ return;
+ }
+ const nameElement =
+ event.currentTarget.elements.namedItem("name");
+ // make sure only name is valid and allow to save everything else
+ // to avoid loosing complex configuration when closed accidentally
+ if (
+ nameElement instanceof HTMLInputElement &&
+ nameElement.checkValidity()
+ ) {
+ const formData = new FormData(event.currentTarget);
+ const saved = panelRef.current?.save(formData);
+ // close popover whenever new variable is created
+ // to prevent creating duplicated variable
+ if (variable === undefined && saved !== false) {
+ onClose();
+ }
+ }
+ }}
>
- <VariablePanelForm
- ref={panelRef}
- variable={variable}
- variableType={variableType}
- onVariableTypeChange={updateVariableType}
- value={value}
- onValueChange={setValue}
- />
- </fieldset>
- </form>
- </ScrollArea>
- <VariablePreview
- variable={variable}
- variableType={variableType}
- variableValue={value}
- onLoadData={reloadData}
- />
- </Grid>
+ {/* submit is not triggered when press enter on input without submit button */}
+ <button hidden></button>
+ <fieldset
+ style={{ display: "contents" }}
+ // forbid editing system variable
+ disabled={isSystemVariable}
+ >
+ <VariablePanelForm
+ ref={panelRef}
+ variable={variable}
+ variableType={variableType}
+ onVariableTypeChange={updateVariableType}
+ value={value}
+ onValueChange={setValue}
+ querySourceContainer={querySourceContainer}
+ onQueryActiveChange={setQueryActive}
+ />
+ </fieldset>
+ </form>
+ </ScrollArea>
+ }
+ end={
+ <VariablePreview
+ variable={variable}
+ variableType={variableType}
+ variableValue={value}
+ onLoadData={reloadData}
+ queryActive={queryActive}
+ queryContainerRef={queryContainerRef}
+ />
+ }
+ />
<DialogTitle
maximizable
@@ -1028,6 +1038,7 @@ export const VariablePopoverTrigger = ({
return (
<FloatingPanel
maximizable
+ resize="both"
placement="center"
width={740}
height={480}
diff --git a/apps/builder/app/builder/features/text-file-editor/markdown-preview.test.tsx b/apps/builder/app/builder/features/text-file-editor/markdown-preview.test.tsx
index f0291cf2cf..479117280d 100644
--- a/apps/builder/app/builder/features/text-file-editor/markdown-preview.test.tsx
+++ b/apps/builder/app/builder/features/text-file-editor/markdown-preview.test.tsx
@@ -1,9 +1,8 @@
import { expect, test } from "vitest";
import type { Asset } from "@webstudio-is/sdk";
import { __testing__ } from "./markdown-preview";
-import { renderMarkdown } from "./text-file-utils";
-const { resolveAssetReferences } = __testing__;
+const { renderMarkdownPreview } = __testing__;
const image: Asset = {
id: "image-id",
@@ -16,11 +15,23 @@ const image: Asset = {
createdAt: "2026-01-01T00:00:00.000Z",
};
-test("resolves asset IDs in Markdown images and links", () => {
- const html = resolveAssetReferences({
- html: renderMarkdown(
- "![Local image](image-id)\n\n[Download image](image-id)\n\n![Remote image](https://example.com/image.png)"
- ),
+const markdown: Asset = {
+ id: "markdown-id",
+ projectId: "project-id",
+ type: "file",
+ name: "post.md",
+ format: "md",
+ size: 1,
+ meta: {},
+ createdAt: "2026-01-01T00:00:00.000Z",
+};
+
+test("resolves asset IDs and relative paths in Markdown images and links", () => {
+ const html = renderMarkdownPreview({
+ markdown:
+ "![Local image](image-id)\n\n[Relative image](./image.png)\n\n[Download image](image-id)\n\n![Remote image](https://example.com/image.png)",
+ sourceAsset: markdown,
+ folders: new Map(),
assetContainers: [{ status: "uploaded", asset: image }],
origin: "https://builder.example",
});
@@ -35,8 +46,10 @@ test("resolves asset IDs in Markdown images and links", () => {
});
test("uses an object URL while an inserted image is uploading", () => {
- const html = resolveAssetReferences({
- html: renderMarkdown("![Uploading](image-id)"),
+ const html = renderMarkdownPreview({
+ markdown: "![Uploading](image-id)",
+ sourceAsset: markdown,
+ folders: new Map(),
assetContainers: [
{
status: "uploading",
diff --git a/apps/builder/app/builder/features/text-file-editor/markdown-preview.tsx b/apps/builder/app/builder/features/text-file-editor/markdown-preview.tsx
index 3dece892ed..7fefea6008 100644
--- a/apps/builder/app/builder/features/text-file-editor/markdown-preview.tsx
+++ b/apps/builder/app/builder/features/text-file-editor/markdown-preview.tsx
@@ -1,15 +1,16 @@
-import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { useMemo, type ReactNode } from "react";
+import { css, SplitView, theme } from "@webstudio-is/design-system";
+import { renderMarkdownHtml } from "@webstudio-is/sdk-components-react/markdown";
+import { discoverNamedMarkdownAssetReferenceRanges } from "@webstudio-is/content-engine/markdown-assets";
+import { rewriteMarkdownAssetReferenceRanges } from "@webstudio-is/content-engine/markdown-references";
import {
- Box,
- css,
- numericScrubControl,
- theme,
-} from "@webstudio-is/design-system";
+ createAssetFolderHierarchy,
+ formatAssetName,
+ getAssetUrl,
+ type Asset,
+ type AssetFolders,
+} from "@webstudio-is/sdk";
import type { AssetContainer } from "~/builder/shared/assets";
-import { getAssetUrl } from "~/builder/shared/assets/asset-utils";
-import { renderMarkdown } from "./text-file-utils";
-
-const minimumPaneWidth = 160;
const previewStyle = css({
minWidth: 0,
@@ -68,45 +69,31 @@ const previewStyle = css({
"& a": { color: theme.colors.foregroundPrimary },
});
-const splitHandleStyle = css({
- position: "relative",
- width: 5,
- height: "100%",
- cursor: "col-resize",
- touchAction: "none",
- outline: "none",
- "&::before": {
- position: "absolute",
- content: '""',
- top: 0,
- bottom: 0,
- left: 2,
- width: 1,
- background: theme.colors.backgroundPrimaryLight,
- },
- "&:hover::before, &:focus-visible::before": {
- left: 1,
- width: 3,
- },
-});
-
-const clampRatio = (ratio: number) => Math.min(0.8, Math.max(0.2, ratio));
-
-const resolveAssetReferences = ({
- html,
+const renderMarkdownPreview = ({
+ markdown,
+ sourceAsset,
+ folders,
assetContainers,
origin,
}: {
- html: string;
+ markdown: string;
+ sourceAsset: Asset;
+ folders: AssetFolders;
assetContainers: AssetContainer[];
origin: string;
}) => {
- if (typeof DOMParser === "undefined") {
- return html;
- }
-
- const document = new DOMParser().parseFromString(html, "text/html");
- const urls = new Map(
+ const hierarchy = createAssetFolderHierarchy(folders);
+ const getNamedAsset = (asset: AssetContainer["asset"]) => ({
+ id: asset.id,
+ name: formatAssetName(asset),
+ folderNames: hierarchy.getPath(asset.folderId).map(({ name }) => name),
+ });
+ const references = discoverNamedMarkdownAssetReferenceRanges({
+ markdown,
+ source: getNamedAsset(sourceAsset),
+ assets: assetContainers.map(({ asset }) => getNamedAsset(asset)),
+ });
+ const assetUrls = Object.fromEntries(
assetContainers.map((container) => [
container.asset.id,
container.status === "uploading"
@@ -114,128 +101,57 @@ const resolveAssetReferences = ({
: getAssetUrl(container.asset, origin).href,
])
);
- for (const image of document.querySelectorAll("img[src]")) {
- const url = urls.get(image.getAttribute("src") ?? "");
- if (url !== undefined) {
- image.setAttribute("src", url);
- }
- }
- for (const link of document.querySelectorAll("a[href]")) {
- const url = urls.get(link.getAttribute("href") ?? "");
- if (url !== undefined) {
- link.setAttribute("href", url);
- }
- }
- return document.body.innerHTML;
+ return renderMarkdownHtml(
+ rewriteMarkdownAssetReferenceRanges({ markdown, references, assetUrls }),
+ { allowBlobImages: true }
+ );
};
-export const __testing__ = { resolveAssetReferences };
+export const __testing__ = { renderMarkdownPreview };
export const MarkdownSplitView = ({
open,
source,
+ sourceAsset,
+ folders,
assetContainers,
children,
}: {
open: boolean;
source: string;
+ sourceAsset: Asset;
+ folders: AssetFolders;
assetContainers: AssetContainer[];
children: ReactNode;
}) => {
- const containerRef = useRef<HTMLDivElement>(null);
- const handleRef = useRef<HTMLDivElement>(null);
- const ratioRef = useRef(0.5);
- const [ratio, setRatio] = useState(ratioRef.current);
const html = useMemo(() => {
if (open === false) {
return "";
}
- return resolveAssetReferences({
- html: renderMarkdown(source),
+ return renderMarkdownPreview({
+ markdown: source,
+ sourceAsset,
+ folders,
assetContainers,
origin: window.location.origin,
});
- }, [assetContainers, open, source]);
-
- const updateRatio = (nextRatio: number) => {
- ratioRef.current = clampRatio(nextRatio);
- setRatio(ratioRef.current);
- };
-
- useEffect(() => {
- const handle = handleRef.current;
- if (handle === null) {
- return;
- }
-
- return numericScrubControl(handle, {
- getInitialValue: () => {
- const width = containerRef.current?.getBoundingClientRect().width ?? 0;
- return width * ratioRef.current;
- },
- getValue: (state, movement) => {
- const width = containerRef.current?.getBoundingClientRect().width ?? 0;
- const paneWidth = Math.min(minimumPaneWidth, width / 2);
- return Math.min(
- width - paneWidth,
- Math.max(paneWidth, state.value + movement)
- );
- },
- onValueInput: (event) => {
- const width = containerRef.current?.getBoundingClientRect().width ?? 0;
- if (width > 0) {
- updateRatio(event.value / width);
- }
- },
- });
- }, []);
+ }, [assetContainers, folders, open, source, sourceAsset]);
return (
- <Box
- ref={containerRef}
- css={{
- display: "grid",
- height: "100%",
- minHeight: 0,
- }}
- style={{
- gridTemplateColumns: open
- ? `minmax(0, ${ratio}fr) 5px minmax(0, ${1 - ratio}fr)`
- : "minmax(0, 1fr)",
- }}
- >
- <Box css={{ minWidth: 0, minHeight: 0, overflow: "hidden" }}>
- {children}
- </Box>
- <div
- ref={handleRef}
- className={splitHandleStyle()}
- hidden={open === false}
- role="separator"
- aria-label="Resize Markdown preview"
- aria-orientation="vertical"
- aria-valuemin={20}
- aria-valuemax={80}
- aria-valuenow={Math.round(ratio * 100)}
- tabIndex={0}
- onKeyDown={(event) => {
- if (event.key === "ArrowLeft") {
- event.preventDefault();
- updateRatio(ratioRef.current - 0.05);
- }
- if (event.key === "ArrowRight") {
- event.preventDefault();
- updateRatio(ratioRef.current + 0.05);
- }
- }}
- />
- <div
- className={previewStyle()}
- hidden={open === false}
- role="region"
- aria-label="Markdown preview"
- dangerouslySetInnerHTML={{ __html: html }}
- />
- </Box>
+ <SplitView
+ defaultSize={{ value: 50, unit: "%" }}
+ start={children}
+ end={
+ open ? (
+ <div
+ className={previewStyle()}
+ role="region"
+ aria-label="Markdown preview"
+ dangerouslySetInnerHTML={{ __html: html }}
+ />
+ ) : undefined
+ }
+ separatorLabel="Resize Markdown preview"
+ />
);
};
diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx b/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx
index f5ecbcbd5b..6ca711a08a 100644
--- a/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx
+++ b/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx
@@ -39,13 +39,17 @@ import {
TextStrikethroughIcon,
} from "@webstudio-is/icons";
import { formatAssetName } from "@webstudio-is/project-build/runtime";
-import { getPagePath, type Asset } from "@webstudio-is/sdk";
+import { getAssetUrl, getPagePath, type Asset } from "@webstudio-is/sdk";
import { CodeEditor } from "~/shared/code-editor";
import { EditorDialog, type EditorApi } from "~/shared/code-editor-base";
-import { $assets, $pages, $props } from "~/shared/sync/data-stores";
+import {
+ $assetFolders,
+ $assets,
+ $pages,
+ $props,
+} from "~/shared/sync/data-stores";
import { $authPermit } from "~/shared/nano-states";
import { AssetManager } from "~/builder/shared/asset-manager";
-import { getAssetUrl } from "~/builder/shared/assets/asset-utils";
import {
AssetUpload,
updateAssetContent,
@@ -423,6 +427,7 @@ export const TextFileEditor = ({
onOpenChange: (open: boolean) => void;
}) => {
const assets = useStore($assets);
+ const assetFolders = useStore($assetFolders);
const asset = assets.get(assetId);
const { assetContainers } = useAssets();
const canEdit = useStore($authPermit) !== "view";
@@ -517,7 +522,7 @@ export const TextFileEditor = ({
languageExtensions={getTextFileEditorExtensions(asset)}
size="full"
expandable={false}
- showBorder={false}
+ chromeless
readOnly={canEdit === false}
onChange={(content) => {
setState({ status: "loaded", content });
@@ -575,6 +580,8 @@ export const TextFileEditor = ({
<MarkdownSplitView
open={previewOpen}
source={state.content}
+ sourceAsset={asset}
+ folders={assetFolders}
assetContainers={assetContainers}
>
{editor}
diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts b/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts
index 43f4ba828e..b82b78268b 100644
--- a/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts
+++ b/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts
@@ -7,7 +7,6 @@ import {
import {
getTextFileEditorExtensions,
isMarkdownAsset,
- renderMarkdown,
} from "./text-file-utils";
describe("text file assets", () => {
@@ -46,14 +45,4 @@ describe("text file assets", () => {
expect(isMarkdownAsset({ format: "MD" })).toBe(true);
expect(isMarkdownAsset({ format: "txt" })).toBe(false);
});
-
- test("renders a safe GFM preview", () => {
- const html = renderMarkdown(
- "~~done~~\n\n| A | B |\n| - | - |\n| 1 | 2 |\n\n<script>alert(1)</script>\n\n[unsafe](javascript:alert(1))"
- );
- expect(html).toContain("<del>done</del>");
- expect(html).toContain("<table>");
- expect(html).toContain("&lt;script&gt;alert(1)&lt;/script&gt;");
- expect(html).not.toContain('href="javascript:');
- });
});
diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts b/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts
index b12b1710a7..f1551de101 100644
--- a/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts
+++ b/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts
@@ -3,8 +3,6 @@ import { css } from "@codemirror/lang-css";
import { html } from "@codemirror/lang-html";
import { javascript } from "@codemirror/lang-javascript";
import { markdown } from "@codemirror/lang-markdown";
-import { micromark } from "micromark";
-import { gfm, gfmHtml } from "micromark-extension-gfm";
import {
getAssetTextEditorLanguage,
type Asset,
@@ -33,9 +31,3 @@ export const getTextFileEditorExtensions = (
export const isMarkdownAsset = (asset: Pick<Asset, "format">) =>
getAssetTextEditorLanguage(asset) === "markdown";
-
-export const renderMarkdown = (source: string) =>
- micromark(source, {
- extensions: [gfm()],
- htmlExtensions: [gfmHtml()],
- });
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-folder-breadcrumbs.test.tsx b/apps/builder/app/builder/shared/asset-manager/asset-folder-breadcrumbs.test.tsx
new file mode 100644
index 0000000000..bc5da692c6
--- /dev/null
+++ b/apps/builder/app/builder/shared/asset-manager/asset-folder-breadcrumbs.test.tsx
@@ -0,0 +1,96 @@
+import { act } from "react-dom/test-utils";
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
+import { TooltipProvider } from "@webstudio-is/design-system";
+import { createAssetFolderHierarchy } from "@webstudio-is/sdk";
+import {
+ createAssetFolderFixture,
+ createAssetFoldersFixture,
+} from "@webstudio-is/sdk/testing";
+import { AssetFolderBreadcrumbs } from "./asset-folder-breadcrumbs";
+import { createAssetManagerTestRenderer } from "./test-utils";
+
+const renderer = createAssetManagerTestRenderer();
+const writeText = vi.fn();
+
+beforeEach(() => {
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ value: { writeText },
+ });
+ Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {
+ configurable: true,
+ value: vi.fn(),
+ });
+});
+
+afterEach(() => {
+ renderer.cleanup();
+ writeText.mockReset();
+ vi.unstubAllGlobals();
+});
+
+const parent = createAssetFolderFixture({ id: "parent", name: "Documents" });
+const child = createAssetFolderFixture({
+ id: "child",
+ parentId: parent.id,
+ name: "Articles",
+});
+const hierarchy = createAssetFolderHierarchy(
+ createAssetFoldersFixture(parent, child)
+);
+
+const renderBreadcrumbs = (
+ selectedItem:
+ | { type: "folder"; id: string }
+ | { type: "asset"; folderId: string; name: string }
+) =>
+ renderer.render(
+ <TooltipProvider>
+ <AssetFolderBreadcrumbs
+ hierarchy={hierarchy}
+ folderId={parent.id}
+ selectedItem={selectedItem}
+ onChange={vi.fn()}
+ />
+ </TooltipProvider>
+ );
+
+const copyPath = () => {
+ act(() => {
+ document
+ .querySelector<HTMLButtonElement>('[aria-label="Copy path"]')
+ ?.click();
+ });
+};
+
+test("shows and copies the selected folder path", () => {
+ renderBreadcrumbs({ type: "folder", id: child.id });
+
+ expect(document.body.textContent).toContain("RootDocumentsArticles");
+ copyPath();
+ expect(writeText).toHaveBeenCalledWith("Root / Documents / Articles");
+});
+
+test("shows and copies the selected asset path", () => {
+ renderBreadcrumbs({
+ type: "asset",
+ folderId: child.id,
+ name: "welcome.md",
+ });
+
+ expect(document.body.textContent).toContain(
+ "RootDocumentsArticleswelcome.md"
+ );
+ copyPath();
+ expect(writeText).toHaveBeenCalledWith(
+ "Root / Documents / Articles / welcome.md"
+ );
+});
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-folder-breadcrumbs.tsx b/apps/builder/app/builder/shared/asset-manager/asset-folder-breadcrumbs.tsx
index cd71ae6987..cdbc324f1b 100644
--- a/apps/builder/app/builder/shared/asset-manager/asset-folder-breadcrumbs.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/asset-folder-breadcrumbs.tsx
@@ -5,13 +5,24 @@ import {
Flex,
ScrollAreaNative,
Separator,
+ SmallIconButton,
Text,
theme,
} from "@webstudio-is/design-system";
import type { AssetFolderHierarchy } from "@webstudio-is/sdk";
-import { ChevronRightIcon } from "@webstudio-is/icons";
+import { ChevronRightIcon, CopyIcon } from "@webstudio-is/icons";
import { useEffect, useRef, type ReactElement } from "react";
+import { CopyToClipboard } from "~/shared/copy-to-clipboard";
import { AssetManagerItemContextMenuContent } from "./asset-manager-item-menu";
+import { formatAssetFolderPath } from "./asset-folder-utils";
+
+type SelectedItem =
+ | { type: "folder"; id: string }
+ | {
+ type: "asset";
+ folderId: string | undefined;
+ name: string;
+ };
const PasteTarget = ({
children,
@@ -40,86 +51,157 @@ const PasteTarget = ({
export const AssetFolderBreadcrumbs = ({
hierarchy,
folderId,
+ selectedItem,
onChange,
canPaste,
onPaste,
}: {
hierarchy: AssetFolderHierarchy;
folderId: string | undefined;
+ selectedItem?: SelectedItem;
onChange: (folderId: string | undefined) => void;
canPaste?: (folderId: string | undefined) => boolean;
onPaste?: (folderId: string | undefined) => void;
}) => {
- const path = hierarchy.getPath(folderId);
- const currentFolderRef = useRef<HTMLButtonElement>(null);
+ const pathFolderId =
+ selectedItem?.type === "folder"
+ ? selectedItem.id
+ : (selectedItem?.folderId ?? folderId);
+ const path = hierarchy.getPath(pathFolderId);
+ const folderPath = formatAssetFolderPath(hierarchy, pathFolderId);
+ const copyPath =
+ selectedItem?.type === "asset"
+ ? `${folderPath} / ${selectedItem.name}`
+ : folderPath;
+ const currentPathRef = useRef<HTMLElement | null>(null);
useEffect(() => {
- currentFolderRef.current?.scrollIntoView({
+ currentPathRef.current?.scrollIntoView({
block: "nearest",
inline: "nearest",
});
- }, [folderId]);
+ }, [folderId, selectedItem]);
return (
<>
<Separator />
- <ScrollAreaNative
+ <Flex
+ align="center"
+ data-asset-folder-breadcrumbs=""
css={{
width: "100%",
- overflowX: "auto",
- overflowY: "hidden",
- scrollbarWidth: "none",
- "&::-webkit-scrollbar": { display: "none" },
flexShrink: 0,
marginBottom: `calc(-1 * ${theme.panel.paddingBlock})`,
+ "& [data-copy-asset-path]": { visibility: "hidden" },
+ "&:hover [data-copy-asset-path], &:focus-within [data-copy-asset-path]":
+ { visibility: "visible" },
}}
- aria-label="Asset folder path"
>
- <Flex
- align="center"
- gap={1}
+ <ScrollAreaNative
css={{
- minWidth: "max-content",
- minHeight: theme.spacing[12],
- paddingInline: theme.spacing[2],
- paddingBlock: theme.spacing[2],
+ minWidth: 0,
+ flexGrow: 1,
+ overflowX: "auto",
+ overflowY: "hidden",
+ scrollbarWidth: "none",
+ "&::-webkit-scrollbar": { display: "none" },
}}
+ aria-label="Asset path"
>
- <PasteTarget
- folderId={undefined}
- canPaste={canPaste}
- onPaste={onPaste}
+ <Flex
+ align="center"
+ gap={1}
+ css={{
+ minWidth: "max-content",
+ minHeight: theme.spacing[12],
+ paddingInline: theme.spacing[2],
+ paddingBlock: theme.spacing[2],
+ }}
>
- <Button
- ref={folderId === undefined ? currentFolderRef : undefined}
- color="ghost"
- aria-current={folderId === undefined ? "location" : undefined}
- onClick={() => onChange(undefined)}
+ <PasteTarget
+ folderId={undefined}
+ canPaste={canPaste}
+ onPaste={onPaste}
>
- <Text css={{ minWidth: "3ch" }}>Root</Text>
- </Button>
- </PasteTarget>
- {path.map((folder) => (
- <Flex key={folder.id} align="center" shrink={false}>
- <ChevronRightIcon size={12} />
- <PasteTarget
- folderId={folder.id}
- canPaste={canPaste}
- onPaste={onPaste}
+ <Button
+ ref={(element) => {
+ if (pathFolderId === undefined) {
+ currentPathRef.current = element;
+ }
+ }}
+ color="ghost"
+ aria-current={
+ pathFolderId === undefined && selectedItem === undefined
+ ? "location"
+ : undefined
+ }
+ onClick={() => onChange(undefined)}
>
- <Button
- ref={folder.id === folderId ? currentFolderRef : undefined}
- color="ghost"
- aria-current={folder.id === folderId ? "location" : undefined}
- onClick={() => onChange(folder.id)}
+ <Text css={{ minWidth: "3ch" }}>Root</Text>
+ </Button>
+ </PasteTarget>
+ {path.map((folder) => (
+ <Flex key={folder.id} align="center" shrink={false}>
+ <ChevronRightIcon size={12} />
+ <PasteTarget
+ folderId={folder.id}
+ canPaste={canPaste}
+ onPaste={onPaste}
+ >
+ <Button
+ ref={(element) => {
+ if (
+ folder.id === pathFolderId &&
+ selectedItem?.type !== "asset"
+ ) {
+ currentPathRef.current = element;
+ }
+ }}
+ color="ghost"
+ aria-current={
+ folder.id === pathFolderId &&
+ selectedItem?.type !== "asset"
+ ? "location"
+ : undefined
+ }
+ onClick={() => onChange(folder.id)}
+ >
+ <Text truncate css={{ minWidth: "3ch", maxWidth: 160 }}>
+ {folder.name}
+ </Text>
+ </Button>
+ </PasteTarget>
+ </Flex>
+ ))}
+ {selectedItem?.type === "asset" && (
+ <Flex align="center" shrink={false}>
+ <ChevronRightIcon size={12} />
+ <Text
+ ref={(element) => {
+ currentPathRef.current = element;
+ }}
+ aria-current="location"
+ truncate
+ css={{
+ minWidth: "3ch",
+ maxWidth: 160,
+ paddingInline: theme.spacing[3],
+ }}
>
- <Text truncate css={{ minWidth: "3ch", maxWidth: 160 }}>
- {folder.name}
- </Text>
- </Button>
- </PasteTarget>
- </Flex>
- ))}
+ {selectedItem.name}
+ </Text>
+ </Flex>
+ )}
+ </Flex>
+ </ScrollAreaNative>
+ <Flex
+ data-copy-asset-path=""
+ shrink={false}
+ css={{ paddingInline: theme.spacing[2] }}
+ >
+ <CopyToClipboard text={copyPath} copyText="Copy path">
+ <SmallIconButton aria-label="Copy path" icon={<CopyIcon />} />
+ </CopyToClipboard>
</Flex>
- </ScrollAreaNative>
+ </Flex>
</>
);
};
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.test.tsx b/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.test.tsx
index e082d53dae..74aa613bbb 100644
--- a/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.test.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.test.tsx
@@ -1,5 +1,7 @@
+import type { ReactNode } from "react";
import { act } from "react-dom/test-utils";
import { afterEach, beforeEach, expect, test, vi } from "vitest";
+import { TooltipProvider } from "@webstudio-is/design-system";
import { $assetFolders } from "~/shared/sync/data-stores";
import {
AssetFolderSettingsDialog,
@@ -13,6 +15,8 @@ import {
import { createAssetManagerTestRenderer } from "./test-utils";
const renderer = createAssetManagerTestRenderer();
+const render = (children: ReactNode) =>
+ renderer.render(<TooltipProvider>{children}</TooltipProvider>);
beforeEach(() => {
vi.stubGlobal(
@@ -44,7 +48,7 @@ test("Escape closes folder settings without closing the assets panel", () => {
const onPanelClose = vi.fn();
const onSettingsOpenChange = vi.fn();
- renderer.render(
+ render(
<div
onKeyDown={(event) => {
if (event.key === "Escape") {
@@ -82,7 +86,7 @@ test.each([
});
$assetFolders.set(createAssetFoldersFixture(folder));
- renderer.render(
+ render(
<AssetFolderSettingsDialog
folder={folder}
open
@@ -95,8 +99,32 @@ test.each([
}
);
+test("shows the folder name and ID in settings", () => {
+ const folder = createAssetFolderFixture({
+ id: "folder-id",
+ name: "Documents",
+ });
+ $assetFolders.set(createAssetFoldersFixture(folder));
+
+ render(
+ <AssetFolderSettingsDialog folder={folder} open onOpenChange={vi.fn()} />
+ );
+
+ expect(
+ document.querySelector('label[for="asset-folder-name-folder-id"]')
+ ?.textContent
+ ).toBe("Name");
+ expect(
+ document.querySelector<HTMLInputElement>("#asset-folder-id-folder-id")
+ ?.value
+ ).toBe(folder.id);
+ expect(
+ document.querySelector('[aria-label="Copy folder ID"]')
+ ).toBeInstanceOf(HTMLButtonElement);
+});
+
test("focuses the folder name while the rightmost Create action is disabled", () => {
- renderer.render(
+ render(
<CreateAssetFolderDialog
open
onOpenChange={vi.fn()}
@@ -123,7 +151,7 @@ test("moves items to the selected folder from the folder-only dialog", () => {
const onMove = vi.fn();
const onClose = vi.fn();
- renderer.render(
+ render(
<MoveAssetManagerItemsDialog
initialFolderId={destination.id}
canMove={() => true}
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.tsx b/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.tsx
index 013f1e7cb7..91c0bf04d0 100644
--- a/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.tsx
@@ -16,6 +16,7 @@ import {
Grid,
InputField,
Label,
+ SmallIconButton,
Text,
theme,
} from "@webstudio-is/design-system";
@@ -23,9 +24,10 @@ import {
createAssetFolderHierarchy,
type AssetFolder,
} from "@webstudio-is/sdk";
-import { TrashIcon } from "@webstudio-is/icons";
+import { CopyIcon, TrashIcon } from "@webstudio-is/icons";
import { $assetFolders } from "~/shared/sync/data-stores";
import { executeRuntimeMutation } from "~/shared/instance-utils/data";
+import { CopyToClipboard } from "~/shared/copy-to-clipboard";
import { AssetFolderSelector } from "./asset-folder-selector";
type AssetFolderFormValues = {
@@ -54,6 +56,7 @@ const AssetFolderForm = ({
initialName,
initialParentId,
excludedFolderId,
+ folderId,
autoFocusSubmit = false,
submitLabel,
secondaryAction,
@@ -64,6 +67,7 @@ const AssetFolderForm = ({
initialName: string;
initialParentId: string | undefined;
excludedFolderId?: string;
+ folderId?: string;
autoFocusSubmit?: boolean;
submitLabel: string;
secondaryAction?: ReactNode;
@@ -106,7 +110,7 @@ const AssetFolderForm = ({
return (
<Grid gap={3} css={{ padding: theme.panel.padding }}>
<Grid gap={1}>
- <Label htmlFor={id}>Folder</Label>
+ <Label htmlFor={id}>Name</Label>
<InputField
id={id}
autoFocus={autoFocusSubmit === false}
@@ -131,6 +135,26 @@ const AssetFolderForm = ({
excludedFolderIds={excludedFolderIds}
rootLabel="Parent folder"
/>
+ {folderId !== undefined && (
+ <Grid gap={1}>
+ <Label htmlFor={`asset-folder-id-${folderId}`}>ID</Label>
+ <InputField
+ id={`asset-folder-id-${folderId}`}
+ readOnly
+ value={folderId}
+ suffix={
+ <Flex justify="center" css={{ paddingInline: theme.spacing[2] }}>
+ <CopyToClipboard text={folderId}>
+ <SmallIconButton
+ aria-label="Copy folder ID"
+ icon={<CopyIcon />}
+ />
+ </CopyToClipboard>
+ </Flex>
+ }
+ />
+ </Grid>
+ )}
<Flex justify="end" gap={2}>
{secondaryAction}
<Button
@@ -260,6 +284,7 @@ export const AssetFolderSettingsDialog = ({
initialName={folder.name}
initialParentId={folder.parentId}
excludedFolderId={folder.id}
+ folderId={folder.id}
autoFocusSubmit
submitLabel="Save"
onSubmit={save}
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager.test.tsx b/apps/builder/app/builder/shared/asset-manager/asset-manager.test.tsx
index 6d300e7ae1..8ec5b4500c 100644
--- a/apps/builder/app/builder/shared/asset-manager/asset-manager.test.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager.test.tsx
@@ -217,6 +217,26 @@ const createAsset = (id: string): Asset => ({
});
describe("Asset Manager multiselect interactions", () => {
+ test("keeps the selected asset in the path while focusing the copy action", () => {
+ const asset = createAsset("asset");
+ act(() => $assets.set(new Map([[asset.id, asset]])));
+ const container = renderManager();
+ const assetButton = getOptions(container).at(-1)!.button;
+ const path = container.querySelector<HTMLElement>(
+ '[aria-label="Asset path"]'
+ )!;
+
+ act(() => assetButton.focus());
+ expect(path.textContent).toContain("Rootasset.png");
+
+ act(() =>
+ container
+ .querySelector<HTMLButtonElement>('[aria-label="Copy path"]')
+ ?.focus()
+ );
+ expect(path.textContent).toContain("Rootasset.png");
+ });
+
test("marquee-selects every thumbnail intersecting the pointer rectangle", () => {
const container = renderManager();
const options = getOptions(container);
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager.tsx b/apps/builder/app/builder/shared/asset-manager/asset-manager.tsx
index 838431db33..c71cdcffe7 100644
--- a/apps/builder/app/builder/shared/asset-manager/asset-manager.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager.tsx
@@ -32,6 +32,7 @@ import {
acceptToMimePatterns,
createAssetFolderHierarchy,
doesAssetMatchMimePatterns,
+ formatAssetName,
type Asset,
type AllowedFileExtension,
} from "@webstudio-is/sdk";
@@ -422,11 +423,6 @@ export const AssetManager = ({
const handleFocusChange = (item: AssetManagerSelection, focused: boolean) => {
if (focused) {
setSelection(item);
- } else if (
- forcedSelection === undefined &&
- isSameAssetManagerSelection(selection, item)
- ) {
- setSelection(undefined);
}
};
@@ -559,6 +555,32 @@ export const AssetManager = ({
[assetContainers]
);
+ const selectedBreadcrumbItem = useMemo(() => {
+ if (selection === undefined || forcedSelection !== undefined) {
+ return;
+ }
+ if (selection.type === "folder") {
+ return folders.has(selection.id) ? selection : undefined;
+ }
+ const asset = compatibleContainers.find(
+ ({ asset }) => asset.id === selection.id
+ )?.asset;
+ if (asset === undefined) {
+ return;
+ }
+ return {
+ type: "asset" as const,
+ folderId: folderHierarchy.resolveFolderId(asset.folderId),
+ name: formatAssetName(asset),
+ };
+ }, [
+ compatibleContainers,
+ folderHierarchy,
+ folders,
+ forcedSelection,
+ selection,
+ ]);
+
const normalizeItems = useCallback(
(items: readonly AssetManagerSelection[]) =>
normalizeAssetManagerItems({
@@ -953,6 +975,7 @@ export const AssetManager = ({
<AssetFolderBreadcrumbs
hierarchy={folderHierarchy}
folderId={currentFolderId}
+ selectedItem={selectedBreadcrumbItem}
onChange={setCurrentFolderId}
canPaste={
canManageFolders ? canPasteAssetManagerClipboard : undefined
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-settings.test.tsx b/apps/builder/app/builder/shared/asset-manager/asset-settings.test.tsx
index 6518358621..51b4978468 100644
--- a/apps/builder/app/builder/shared/asset-manager/asset-settings.test.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/asset-settings.test.tsx
@@ -92,6 +92,9 @@ test("uses an auto-growing textarea for the asset description", () => {
expect(document.body.textContent).toContain("Last modified");
expect(document.body.textContent).toContain("Jan 15, 2026");
expect(document.body.textContent).toContain("Feb 15, 2026");
+ expect(
+ Array.from(document.querySelectorAll("label"), (label) => label.textContent)
+ ).toEqual(["Name", "Folder", "Description", "ID"]);
});
test("closes asset settings before replacing an asset", () => {
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-settings.tsx b/apps/builder/app/builder/shared/asset-manager/asset-settings.tsx
index d50a33b639..2af2844982 100644
--- a/apps/builder/app/builder/shared/asset-manager/asset-settings.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/asset-settings.tsx
@@ -4,7 +4,7 @@ import { useDebouncedCallback } from "use-debounce";
import prettyBytes from "pretty-bytes";
import { computed } from "nanostores";
import { useStore } from "@nanostores/react";
-import { getMimeTypeByExtension } from "@webstudio-is/sdk";
+import { getAssetUrl, getMimeTypeByExtension } from "@webstudio-is/sdk";
import type { Asset, Instance } from "@webstudio-is/sdk";
import {
Box,
@@ -74,7 +74,6 @@ import {
} from "@webstudio-is/project-build/runtime";
import { AssetFolderSelector } from "./asset-folder-selector";
import { moveAssetManagerItems } from "./asset-manager-operations";
-import { getAssetUrl } from "~/builder/shared/assets/asset-utils";
import { getFormattedAspectRatio } from "./utils";
import { CopyToClipboard } from "~/shared/copy-to-clipboard";
import {
@@ -478,6 +477,16 @@ const AssetSettingsContent = ({
</InputErrorsTooltip>
</Grid>
+ <Grid css={{ padding: theme.panel.padding, gap: 4 }}>
+ <AssetFolderSelector
+ value={asset.folderId}
+ onChange={moveToFolder}
+ rootLabel="Folder"
+ disabled={authPermit === "view"}
+ deferChangesUntilBlur
+ />
+ </Grid>
+
<Grid css={{ padding: theme.panel.padding, gap: 4 }}>
<Label
htmlFor="asset-manager-description"
@@ -503,16 +512,6 @@ const AssetSettingsContent = ({
/>
</Grid>
- <Grid css={{ padding: theme.panel.padding, gap: 4 }}>
- <AssetFolderSelector
- value={asset.folderId}
- onChange={moveToFolder}
- rootLabel="Folder"
- disabled={authPermit === "view"}
- deferChangesUntilBlur
- />
- </Grid>
-
<Grid css={{ padding: theme.panel.padding, gap: 4 }}>
<Label htmlFor="asset-manager-id">ID</Label>
<InputField
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.tsx b/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.tsx
index df3d629343..6da6c456b8 100644
--- a/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.tsx
@@ -18,6 +18,7 @@ import {
FILE_EXTENSIONS_BY_CATEGORY,
IMAGE_MIME_TYPES,
detectAssetType,
+ getAssetUrl,
isResizableImageFileName,
} from "@webstudio-is/sdk";
import type { MimeCategory } from "@webstudio-is/sdk";
@@ -25,7 +26,6 @@ import { draggable } from "@atlaskit/pragmatic-drag-and-drop/element/adapter";
import { $authPermit, $permissions } from "~/shared/nano-states";
import { replaceAsset } from "~/builder/shared/assets";
import { validateFiles } from "~/builder/shared/assets/asset-upload";
-import { getAssetUrl } from "~/builder/shared/assets/asset-utils";
import { createAssetManagerClipboardActions } from "./asset-manager-clipboard";
import { setAssetManagerDragPreview } from "./asset-manager-drag-preview";
import { type AssetManagerItemActions } from "./asset-manager-item-menu";
diff --git a/apps/builder/app/builder/shared/assets/asset-utils.ts b/apps/builder/app/builder/shared/assets/asset-utils.ts
index 333895604b..953a79e81c 100644
--- a/apps/builder/app/builder/shared/assets/asset-utils.ts
+++ b/apps/builder/app/builder/shared/assets/asset-utils.ts
@@ -10,12 +10,9 @@ import {
getFileExtension,
IMAGE_EXTENSIONS,
detectAssetType,
- getAssetUrl,
+ getAssetContentHash,
} from "@webstudio-is/sdk";
import type { UploadingFileData } from "~/shared/nano-states";
-import { getContentHash } from "@webstudio-is/asset-uploader";
-
-export { getAssetUrl };
export const getImageNameAndType = (fileName: string) => {
const extractedExt = getFileExtension(fileName)?.toLowerCase();
@@ -58,7 +55,7 @@ const extractImageNameAndMimeTypeFromUrl = (url: URL) => {
export const getSha256Hash = async (data: string) => {
const encoder = new TextEncoder();
- return getContentHash(encoder.encode(data));
+ return getAssetContentHash(encoder.encode(data));
};
const readFileAsArrayBuffer = (file: File): Promise<ArrayBuffer> =>
@@ -71,7 +68,7 @@ const readFileAsArrayBuffer = (file: File): Promise<ArrayBuffer> =>
export const getSha256HashOfFile = async (file: File) => {
const arrayBuffer = await readFileAsArrayBuffer(file);
- return getContentHash(arrayBuffer);
+ return getAssetContentHash(arrayBuffer);
};
export const getFileUploadFingerprint = async (
diff --git a/apps/builder/app/builder/shared/assets/types.ts b/apps/builder/app/builder/shared/assets/types.ts
index 019d691ec6..ef5bd0f462 100644
--- a/apps/builder/app/builder/shared/assets/types.ts
+++ b/apps/builder/app/builder/shared/assets/types.ts
@@ -20,10 +20,3 @@ export type UploadingAssetContainer = {
* Assets that can be shown in the UI
*/
export type AssetContainer = UploadedAssetContainer | UploadingAssetContainer;
-
-export type AssetActionResponse = {
- uploadedAssets?: Array<Asset>;
- deduplicated?: boolean;
- deletedAssets?: Array<Asset>;
- errors?: string;
-};
diff --git a/apps/builder/app/builder/shared/assets/upload-assets.tsx b/apps/builder/app/builder/shared/assets/upload-assets.tsx
index 1a177935e4..e197e9ad3d 100644
--- a/apps/builder/app/builder/shared/assets/upload-assets.tsx
+++ b/apps/builder/app/builder/shared/assets/upload-assets.tsx
@@ -1,13 +1,14 @@
import warnOnce from "warn-once";
import invariant from "tiny-invariant";
import { getFileNameParts, type Asset } from "@webstudio-is/sdk";
+import { assetsUploadsApiUrl } from "@webstudio-is/sdk/runtime";
+import type { AssetUploadResult } from "@webstudio-is/protocol/asset-resource-api";
import type { AssetType, UploadTicket } from "@webstudio-is/asset-uploader";
import { Box, toast, css, theme } from "@webstudio-is/design-system";
import { sanitizeS3Key } from "@webstudio-is/asset-uploader";
import { Image, wsImageLoader } from "@webstudio-is/image";
-import { restAssetsUploadPath, restAssetsPath } from "~/shared/router-utils";
+import { restAssetsUploadPath } from "~/shared/router-utils";
import { fetch } from "~/shared/fetch.client";
-import type { AssetActionResponse } from "~/builder/shared/assets";
import {
$authToken,
$uploadingFilesDataStore,
@@ -27,6 +28,8 @@ import {
getSha256HashOfFile,
} from "./asset-utils";
+type AssetActionResponse = AssetUploadResult | { errors: string };
+
const safeDeleteAssets = (assetIds: Asset["id"][], projectId: string) => {
const currentProjectId = $project.get()?.id;
@@ -235,7 +238,7 @@ const submitAssetUpload = async ({
authToken: undefined | string;
uploadName: string;
fileOrUrl: File | URL;
- onCompleted: (data: AssetActionResponse) => void;
+ onCompleted: (data: AssetUploadResult) => void;
onError: (error: string) => void;
request?: typeof fetch;
}) => {
@@ -321,7 +324,7 @@ const createUploadTicket = async ({
const authHeaders = createAssetUploadHeaders(authToken);
- const metaResponse = await request(restAssetsPath(), {
+ const metaResponse = await request(assetsUploadsApiUrl, {
method: "POST",
body: metaFormData,
headers: authHeaders,
@@ -338,16 +341,16 @@ const createUploadTicket = async ({
const handleAfterSubmit = (
assetId: string,
- data: AssetActionResponse,
+ data: AssetUploadResult,
projectId: string,
folderId?: string
) => {
warnOnce(
- data.uploadedAssets?.length !== 1,
+ data.uploadedAssets.length !== 1,
"Expected exactly 1 uploaded asset"
);
- const uploadedAsset = data.uploadedAssets?.[0];
+ const uploadedAsset = data.uploadedAssets[0];
if (uploadedAsset === undefined) {
warnOnce(true, "An uploaded asset is undefined");
diff --git a/apps/builder/app/builder/shared/bindable-expression.test.tsx b/apps/builder/app/builder/shared/bindable-expression.test.tsx
new file mode 100644
index 0000000000..f5f0ea1b23
--- /dev/null
+++ b/apps/builder/app/builder/shared/bindable-expression.test.tsx
@@ -0,0 +1,159 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { act } from "react-dom/test-utils";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, expect, test, vi } from "vitest";
+import { encodeDataSourceVariable, type DataSource } from "@webstudio-is/sdk";
+import { $dataSourceVariables } from "~/shared/nano-states";
+import { $dataSources } from "~/shared/sync/data-stores";
+import { BindableExpressionControl } from "./bindable-expression";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+let root: Root | undefined;
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = undefined;
+ document.body.innerHTML = "";
+ $dataSources.set(new Map());
+ $dataSourceVariables.set(new Map());
+});
+
+const renderControl = ({
+ expression,
+ bound,
+ allowBindingOverwrite,
+ parseValue,
+ onChangeValue,
+}: {
+ expression: string;
+ bound: boolean;
+ allowBindingOverwrite?: boolean;
+ parseValue?: (value: string) => unknown;
+ onChangeValue: (value: string) => void;
+}) => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ act(() => {
+ root?.render(
+ <BindableExpressionControl
+ expression={expression}
+ value="displayed"
+ bound={bound}
+ showBinding={false}
+ allowBindingOverwrite={allowBindingOverwrite}
+ parseValue={parseValue}
+ scope={{}}
+ aliases={new Map()}
+ onChangeValue={onChangeValue}
+ onChangeExpression={() => {}}
+ onRemove={() => {}}
+ renderControl={({ value, readOnly, onChangeValue }) => (
+ <button
+ type="button"
+ disabled={readOnly}
+ onClick={() => onChangeValue("changed")}
+ >
+ {value}
+ </button>
+ )}
+ />
+ );
+ });
+ return container.querySelector("button") as HTMLButtonElement;
+};
+
+test("updates a directly bound variable without replacing its expression", () => {
+ const variable: DataSource = {
+ type: "variable",
+ id: "variable-id",
+ name: "Variable",
+ value: { type: "string", value: "initial" },
+ };
+ $dataSources.set(new Map([[variable.id, variable]]));
+ const onChangeValue = vi.fn();
+ const button = renderControl({
+ expression: encodeDataSourceVariable(variable.id),
+ bound: true,
+ onChangeValue,
+ });
+
+ act(() => button.click());
+
+ expect($dataSourceVariables.get().get(variable.id)).toBe("changed");
+ expect(onChangeValue).not.toHaveBeenCalled();
+});
+
+test("passes literal input changes to its consumer", () => {
+ const onChangeValue = vi.fn();
+ const button = renderControl({
+ expression: '"displayed"',
+ bound: false,
+ onChangeValue,
+ });
+
+ act(() => button.click());
+
+ expect(onChangeValue).toHaveBeenCalledExactlyOnceWith("changed");
+});
+
+test("parses bound values before updating the variable", () => {
+ const variable: DataSource = {
+ type: "variable",
+ id: "variable-id",
+ name: "Variable",
+ value: { type: "string", value: "initial" },
+ };
+ $dataSources.set(new Map([[variable.id, variable]]));
+ const parseValue = vi.fn((value: string) => ({ value }));
+ const button = renderControl({
+ expression: encodeDataSourceVariable(variable.id),
+ bound: true,
+ parseValue,
+ onChangeValue: () => {},
+ });
+
+ act(() => button.click());
+
+ expect(parseValue).toHaveBeenCalledExactlyOnceWith("changed");
+ expect($dataSourceVariables.get().get(variable.id)).toEqual({
+ value: "changed",
+ });
+});
+
+test("does not parse literal input", () => {
+ const parseValue = vi.fn((value: string) => ({ value }));
+ const onChangeValue = vi.fn();
+ const literalButton = renderControl({
+ expression: '"displayed"',
+ bound: false,
+ parseValue,
+ onChangeValue,
+ });
+ act(() => literalButton.click());
+ expect(parseValue).not.toHaveBeenCalled();
+ expect(onChangeValue).toHaveBeenCalledExactlyOnceWith("changed");
+});
+
+test("can keep directly bound values read-only", () => {
+ const variable: DataSource = {
+ type: "variable",
+ id: "variable-id",
+ name: "Variable",
+ value: { type: "string", value: "initial" },
+ };
+ $dataSources.set(new Map([[variable.id, variable]]));
+ const button = renderControl({
+ expression: encodeDataSourceVariable(variable.id),
+ bound: true,
+ allowBindingOverwrite: false,
+ onChangeValue: () => {},
+ });
+
+ expect(button.disabled).toBe(true);
+});
diff --git a/apps/builder/app/builder/shared/bindable-expression.tsx b/apps/builder/app/builder/shared/bindable-expression.tsx
new file mode 100644
index 0000000000..ee8e8851e9
--- /dev/null
+++ b/apps/builder/app/builder/shared/bindable-expression.tsx
@@ -0,0 +1,175 @@
+import { useMemo, type ReactNode } from "react";
+import { useStore } from "@nanostores/react";
+import { atom, computed, type ReadableAtom } from "nanostores";
+import { decodeDataSourceVariable } from "@webstudio-is/sdk";
+import { $dataSourceVariables } from "~/shared/nano-states";
+import { $dataSources } from "~/shared/sync/data-stores";
+import {
+ BindingControl,
+ BindingPopover,
+ type BindingVariant,
+} from "./binding-popover";
+
+export type BindingState = {
+ overwritable: boolean;
+ variant: BindingVariant;
+};
+
+const updateExpressionValue = (expression: string, value: unknown) => {
+ const potentialVariableId = decodeDataSourceVariable(expression);
+ if (
+ potentialVariableId === undefined ||
+ $dataSources.get().has(potentialVariableId) === false
+ ) {
+ return;
+ }
+ const dataSourceVariables = new Map($dataSourceVariables.get());
+ dataSourceVariables.set(potentialVariableId, value);
+ $dataSourceVariables.set(dataSourceVariables);
+};
+
+export const updateBindableValue = <Value,>({
+ expression,
+ value,
+ expressionValue = value,
+ onChangeValue,
+}: {
+ expression: string | undefined;
+ value: Value;
+ expressionValue?: unknown;
+ onChangeValue: (value: Value) => void;
+}) => {
+ if (expression !== undefined) {
+ updateExpressionValue(expression, expressionValue);
+ return;
+ }
+ onChangeValue(value);
+};
+
+export const useBindingState = (expression: string | undefined) => {
+ const $bindingState = useMemo((): ReadableAtom<BindingState> => {
+ if (expression === undefined) {
+ return atom({ overwritable: true, variant: "default" });
+ }
+ const potentialVariableId = decodeDataSourceVariable(expression);
+ if (potentialVariableId === undefined) {
+ return atom({ overwritable: false, variant: "bound" });
+ }
+ return computed(
+ [$dataSources, $dataSourceVariables],
+ (dataSources, dataSourceVariables): BindingState => {
+ const dataSource = dataSources.get(potentialVariableId);
+ if (dataSource?.type !== "variable") {
+ return { overwritable: false, variant: "bound" };
+ }
+ return {
+ overwritable: true,
+ variant:
+ dataSourceVariables.get(potentialVariableId) === undefined
+ ? "bound"
+ : "overwritten",
+ };
+ }
+ );
+ }, [expression]);
+ return useStore($bindingState);
+};
+
+export const BindableExpressionControl = <Value,>({
+ expression,
+ value,
+ bound,
+ scope,
+ aliases,
+ validate,
+ showBinding = true,
+ allowBindingOverwrite = true,
+ renderControl,
+ parseValue = (value) => value,
+ onChangeValue,
+ onChangeExpression,
+ onRemove,
+ bindingState,
+}: {
+ expression: string;
+ value: Value;
+ bound: boolean;
+ scope: Record<string, unknown>;
+ aliases: Map<string, string>;
+ validate?: (value: unknown) => string | undefined;
+ showBinding?: boolean;
+ allowBindingOverwrite?: boolean;
+ renderControl: (props: {
+ value: Value;
+ readOnly: boolean;
+ onChangeValue: (value: Value) => void;
+ }) => ReactNode;
+ parseValue?: (value: Value) => unknown;
+ onChangeValue: (value: Value) => void;
+ onChangeExpression: (expression: string) => void;
+ onRemove: (evaluatedValue: unknown) => void;
+ bindingState?: BindingState;
+}) => {
+ if (bindingState === undefined) {
+ return (
+ <BindableExpressionControlWithState
+ expression={expression}
+ value={value}
+ bound={bound}
+ scope={scope}
+ aliases={aliases}
+ validate={validate}
+ showBinding={showBinding}
+ allowBindingOverwrite={allowBindingOverwrite}
+ renderControl={renderControl}
+ parseValue={parseValue}
+ onChangeValue={onChangeValue}
+ onChangeExpression={onChangeExpression}
+ onRemove={onRemove}
+ />
+ );
+ }
+
+ const { overwritable, variant } = bindingState;
+ const readOnly =
+ overwritable === false || (bound && allowBindingOverwrite === false);
+ return (
+ <BindingControl>
+ {renderControl({
+ value,
+ readOnly,
+ onChangeValue: (nextValue) => {
+ updateBindableValue({
+ expression: bound ? expression : undefined,
+ value: nextValue,
+ expressionValue: bound ? parseValue(nextValue) : nextValue,
+ onChangeValue,
+ });
+ },
+ })}
+ {showBinding && (
+ <BindingPopover
+ scope={scope}
+ aliases={aliases}
+ validate={validate}
+ variant={variant}
+ value={expression}
+ onChange={onChangeExpression}
+ onRemove={onRemove}
+ />
+ )}
+ </BindingControl>
+ );
+};
+
+const BindableExpressionControlWithState = <Value,>(
+ props: Omit<
+ Parameters<typeof BindableExpressionControl<Value>>[0],
+ "bindingState"
+ >
+) => {
+ const bindingState = useBindingState(
+ props.bound ? props.expression : undefined
+ );
+ return <BindableExpressionControl {...props} bindingState={bindingState} />;
+};
diff --git a/apps/builder/app/builder/shared/binding-popover.tsx b/apps/builder/app/builder/shared/binding-popover.tsx
index 339cde2ca9..6f4e49e967 100644
--- a/apps/builder/app/builder/shared/binding-popover.tsx
+++ b/apps/builder/app/builder/shared/binding-popover.tsx
@@ -32,10 +32,8 @@ import {
Tooltip,
theme,
} from "@webstudio-is/design-system";
-import {
- decodeDataSourceVariable,
- getExpressionIdentifiers,
-} from "@webstudio-is/sdk";
+import { getExpressionIdentifiers } from "@webstudio-is/expression";
+import { decodeDataSourceVariable } from "@webstudio-is/sdk";
import { getExpressionErrorMessages } from "@webstudio-is/project-build/runtime";
import { $dataSourceVariables, $isDesignMode } from "~/shared/nano-states";
import {
@@ -358,6 +356,7 @@ export const BindingPopover = ({
return (
<FloatingPanel
placement="left-start"
+ anchor="trigger"
open={isOpen}
onOpenChange={(newOpen) => {
// handle special case for popover close
diff --git a/apps/builder/app/builder/shared/expression-editor.test.ts b/apps/builder/app/builder/shared/expression-editor.test.ts
index 5d843def78..414fd01cfe 100644
--- a/apps/builder/app/builder/shared/expression-editor.test.ts
+++ b/apps/builder/app/builder/shared/expression-editor.test.ts
@@ -2,7 +2,10 @@ import { describe, test, expect } from "vitest";
import { CompletionContext } from "@codemirror/autocomplete";
import { EditorState } from "@codemirror/state";
import { javascript } from "@codemirror/lang-javascript";
-import { allowedArrayMethods, allowedStringMethods } from "@webstudio-is/sdk";
+import {
+ allowedArrayMethods,
+ allowedStringMethods,
+} from "@webstudio-is/expression";
import {
completionPath,
formatValue,
diff --git a/apps/builder/app/builder/shared/expression-editor.tsx b/apps/builder/app/builder/shared/expression-editor.tsx
index fd6f8671b9..338c06428d 100644
--- a/apps/builder/app/builder/shared/expression-editor.tsx
+++ b/apps/builder/app/builder/shared/expression-editor.tsx
@@ -28,18 +28,19 @@ import {
import { javascript } from "@codemirror/lang-javascript";
import { textVariants, css, rawTheme } from "@webstudio-is/design-system";
import {
- decodeDataVariableId,
lintExpression,
allowedStringMethods,
allowedArrayMethods,
getExpressionValueKind,
-} from "@webstudio-is/sdk";
+} from "@webstudio-is/expression";
+import { decodeDataVariableId } from "@webstudio-is/sdk";
import {
EditorContent,
EditorDialog,
EditorDialogButton,
EditorDialogControl,
type EditorApi,
+ getCodeEditorCssVars,
normalizeEditorValue,
} from "~/shared/code-editor-base";
import {
@@ -519,9 +520,20 @@ const emptyScope: Scope = {};
const emptyAliases: Aliases = new Map();
const wrapperStyle = css({
- // 1 line is 16px
- // set and max 20 lines
- "--ws-code-editor-max-height": "320px",
+ variants: {
+ size: {
+ default: {
+ // 1 line is 16px; show at most 20 lines.
+ "--ws-code-editor-max-height": "320px",
+ },
+ full: {
+ ...getCodeEditorCssVars({ minHeight: "100%", maxHeight: "100%" }),
+ height: "100%",
+ "& > div, & .cm-editor, & .cm-scroller": { height: "100%" },
+ },
+ },
+ },
+ defaultVariants: { size: "default" },
});
const linterTooltipTheme = EditorView.theme({
@@ -556,16 +568,20 @@ const expressionLinter = linter((view) => {
});
export const ExpressionEditor = ({
+ "aria-label": ariaLabel,
editorApiRef,
scope = emptyScope,
aliases = emptyAliases,
color,
+ size,
+ chromeless = false,
autoFocus = false,
readOnly = false,
value,
onChange,
onChangeComplete,
}: {
+ "aria-label"?: string;
editorApiRef?: RefObject<undefined | EditorApi>;
/**
* object with variables and their data to autocomplete
@@ -576,6 +592,8 @@ export const ExpressionEditor = ({
*/
aliases?: Aliases;
color?: "error";
+ size?: "default" | "full";
+ chromeless?: boolean;
autoFocus?: boolean;
readOnly?: boolean;
value?: string;
@@ -663,9 +681,11 @@ export const ExpressionEditor = ({
const content = (
<EditorContent
+ aria-label={ariaLabel}
editorApiRef={editorApiRef}
extensions={extensions}
invalid={color === "error"}
+ chromeless={chromeless}
readOnly={readOnly}
autoFocus={autoFocus}
value={expressionWithUnsetVariables}
@@ -686,8 +706,12 @@ export const ExpressionEditor = ({
/>
);
+ if (chromeless) {
+ return <div className={wrapperStyle({ size })}>{content}</div>;
+ }
+
return (
- <div className={wrapperStyle.toString()}>
+ <div className={wrapperStyle({ size })}>
<EditorDialogControl>
{content}
<EditorDialog title="Expression Editor" content={content}>
diff --git a/apps/builder/app/builder/shared/query-builder.test.tsx b/apps/builder/app/builder/shared/query-builder.test.tsx
new file mode 100644
index 0000000000..4d8e00908f
--- /dev/null
+++ b/apps/builder/app/builder/shared/query-builder.test.tsx
@@ -0,0 +1,141 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { act } from "react-dom/test-utils";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, expect, test } from "vitest";
+import type { QueryDefinition } from "@webstudio-is/query-builder";
+import { BindableQueryBuilder } from "./query-builder";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const scope = {
+ $ws$system: {
+ pathname: "/blog/article",
+ page: 20,
+ },
+};
+const aliases = new Map([["$ws$system", "system"]]);
+let root: Root | undefined;
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = undefined;
+ document.body.innerHTML = "";
+});
+
+const renderQueryBuilder = <Query extends Record<string, unknown>>({
+ value,
+ capabilities,
+}: {
+ value: Query;
+ capabilities: QueryDefinition<string, string>;
+}) => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ act(() => {
+ root?.render(
+ <BindableQueryBuilder
+ value={value}
+ capabilities={capabilities}
+ scope={scope}
+ aliases={aliases}
+ onChange={() => {}}
+ />
+ );
+ });
+ return container;
+};
+
+test("shows public variable names without changing the stored expression", () => {
+ const value = {
+ where: {
+ all: [
+ {
+ field: ["path"],
+ operator: "eq",
+ value: "$ws$system.pathname",
+ },
+ ],
+ },
+ };
+ const capabilities = {
+ version: 1,
+ fields: [{ path: ["path"], label: "Path", types: ["string"] }],
+ operators: [
+ {
+ value: "eq",
+ label: "Equals",
+ types: ["string"],
+ input: { control: "expression", defaultValue: '""' },
+ },
+ ],
+ source: {
+ fieldPathSchema: {
+ type: "array",
+ items: { type: "string" },
+ minItems: 1,
+ },
+ controls: [
+ {
+ type: "filter",
+ key: "where",
+ label: "Filters",
+ defaultValue: { all: [] },
+ combinators: ["all"],
+ limits: { conditions: 8, depth: 3 },
+ defaultCondition: { field: ["path"], operator: "eq" },
+ },
+ ],
+ },
+ } as const satisfies QueryDefinition<string, string>;
+
+ const container = renderQueryBuilder({ value, capabilities });
+ const editor = container.querySelector(".cm-content");
+ const source = Array.from(container.querySelectorAll(".cm-content")).at(-1);
+
+ expect(editor?.textContent).toBe('"/blog/article"');
+ expect(source?.textContent).toContain("system.pathname");
+ expect(source?.textContent).not.toContain("$ws$system.pathname");
+ expect(value.where.all[0].value).toBe("$ws$system.pathname");
+});
+
+test("shows an evaluated value for a bound number input", () => {
+ const capabilities = {
+ version: 1,
+ fields: [],
+ operators: [],
+ source: {
+ fieldPathSchema: {
+ type: "array",
+ items: { type: "string" },
+ minItems: 1,
+ },
+ controls: [
+ {
+ type: "expression",
+ key: "limit",
+ label: "Limit",
+ defaultValue: "20",
+ input: "number",
+ integer: true,
+ },
+ ],
+ },
+ } as const satisfies QueryDefinition<string, string>;
+
+ const container = renderQueryBuilder({
+ value: { limit: "$ws$system.page" },
+ capabilities,
+ });
+ const input = container.querySelector<HTMLInputElement>(
+ 'input[aria-label="Limit"]'
+ );
+
+ expect(input?.value).toBe("20");
+ expect(input?.step).toBe("1");
+ expect(input?.disabled).toBe(true);
+});
diff --git a/apps/builder/app/builder/shared/query-builder.tsx b/apps/builder/app/builder/shared/query-builder.tsx
new file mode 100644
index 0000000000..44a6cbfd55
--- /dev/null
+++ b/apps/builder/app/builder/shared/query-builder.tsx
@@ -0,0 +1,180 @@
+import { isLiteralExpression } from "@webstudio-is/expression";
+import { Grid, InputField } from "@webstudio-is/design-system";
+import { createPortal } from "react-dom";
+import {
+ StructuredQueryBuilder,
+ type QueryValueEditorProps,
+} from "@webstudio-is/query-builder-react";
+import type { QueryDefinition } from "@webstudio-is/query-builder";
+import { evaluateExpressionWithinScope } from "./binding-popover";
+import { BindableExpressionControl } from "./bindable-expression";
+import { ExpressionEditor, formatValue } from "./expression-editor";
+
+const BoundExpression = ({
+ "aria-label": label,
+ value,
+ scope,
+ aliases,
+ onChange,
+ input,
+ min,
+ max,
+ exclusiveMin,
+ exclusiveMax,
+ integer,
+}: QueryValueEditorProps & {
+ scope: Record<string, unknown>;
+ aliases: Map<string, string>;
+}) => {
+ const bound = isLiteralExpression(value) === false;
+ const evaluatedValue = evaluateExpressionWithinScope(value, scope);
+
+ if (input === "number") {
+ const number = Number(evaluatedValue);
+ const displayedValue = Number.isNaN(number) ? "" : String(number);
+ return (
+ <BindableExpressionControl
+ expression={value}
+ value={displayedValue}
+ bound={bound}
+ scope={scope}
+ aliases={aliases}
+ validate={(value) => {
+ if (value !== undefined && typeof value !== "number") {
+ return `${label} expects a number value`;
+ }
+ if (typeof value !== "number") {
+ return;
+ }
+ if (integer && Number.isInteger(value) === false) {
+ return `${label} expects an integer value`;
+ }
+ if (
+ min !== undefined &&
+ (exclusiveMin ? value <= min : value < min)
+ ) {
+ return `${label} expects a value ${exclusiveMin ? "greater than" : "greater than or equal to"} ${min}`;
+ }
+ if (
+ max !== undefined &&
+ (exclusiveMax ? value >= max : value > max)
+ ) {
+ return `${label} expects a value ${exclusiveMax ? "less than" : "less than or equal to"} ${max}`;
+ }
+ }}
+ parseValue={Number}
+ onChangeValue={onChange}
+ onChangeExpression={onChange}
+ onRemove={(value) => onChange(String(Number(value) || 0))}
+ renderControl={({ value, readOnly, onChangeValue }) => (
+ <InputField
+ aria-label={label}
+ type="number"
+ min={min}
+ max={max}
+ step={integer === true ? 1 : "any"}
+ disabled={readOnly}
+ value={value}
+ onChange={(event) => onChangeValue(event.target.value)}
+ />
+ )}
+ />
+ );
+ }
+
+ const displayedValue = bound ? formatValue(evaluatedValue) : value;
+ return (
+ <BindableExpressionControl
+ expression={value}
+ value={displayedValue}
+ bound={bound}
+ scope={scope}
+ aliases={aliases}
+ parseValue={(value) => evaluateExpressionWithinScope(value, {})}
+ onChangeValue={onChange}
+ onChangeExpression={onChange}
+ onRemove={(value) => onChange(JSON.stringify(value) ?? "undefined")}
+ renderControl={({ value, readOnly, onChangeValue }) => {
+ const updateValue = (nextValue: string) => {
+ if (bound && isLiteralExpression(nextValue) === false) {
+ return;
+ }
+ onChangeValue(nextValue);
+ };
+ return (
+ <div>
+ <ExpressionEditor
+ aria-label={label}
+ readOnly={readOnly}
+ value={value}
+ onChange={updateValue}
+ onChangeComplete={updateValue}
+ />
+ </div>
+ );
+ }}
+ />
+ );
+};
+
+export const BindableQueryBuilder = <
+ FieldType extends string,
+ Operator extends string,
+ Query extends Record<string, unknown>,
+>({
+ value,
+ capabilities,
+ scope,
+ aliases,
+ sourceContainer,
+ sectionPaddingInline,
+ onChange,
+}: {
+ value: Query;
+ capabilities: QueryDefinition<FieldType, Operator>;
+ scope: Record<string, unknown>;
+ aliases: Map<string, string>;
+ sourceContainer?: Element | null;
+ sectionPaddingInline?: string;
+ onChange: (value: Query) => void;
+}) => (
+ <StructuredQueryBuilder<FieldType, Operator, Query>
+ value={value}
+ capabilities={capabilities}
+ sectionPaddingInline={sectionPaddingInline}
+ editors={{
+ expression: (props) => (
+ <BoundExpression {...props} scope={scope} aliases={aliases} />
+ ),
+ source: (props) => (
+ <ExpressionEditor
+ {...props}
+ scope={scope}
+ aliases={aliases}
+ size={sourceContainer === undefined ? "default" : "full"}
+ chromeless={sourceContainer !== undefined}
+ />
+ ),
+ }}
+ renderSource={
+ sourceContainer === undefined
+ ? undefined
+ : (source) =>
+ sourceContainer === null
+ ? null
+ : createPortal(
+ <Grid
+ css={{
+ height: "100%",
+ minHeight: 0,
+ gridTemplateRows: "minmax(0, 1fr) auto",
+ }}
+ >
+ {source}
+ </Grid>,
+ sourceContainer
+ )
+ }
+ onChange={onChange}
+ />
+);
diff --git a/apps/builder/app/routes/rest.assets.$assetId.content.tsx b/apps/builder/app/routes/rest.assets.$assetId.content.tsx
index 1967c5244e..72d141923b 100644
--- a/apps/builder/app/routes/rest.assets.$assetId.content.tsx
+++ b/apps/builder/app/routes/rest.assets.$assetId.content.tsx
@@ -1,66 +1,54 @@
import { json, type ActionFunctionArgs } from "@remix-run/server-runtime";
-import {
- AssetRevisionConflictError,
- updateAssetContent,
-} from "@webstudio-is/asset-uploader/index.server";
-import type { Asset } from "@webstudio-is/sdk";
-import { createAssetClient } from "~/shared/asset-client";
-import { createContext } from "~/shared/context.server";
+import { assetResourceApiOperations } from "@webstudio-is/protocol/asset-resource-api";
import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
-import { checkCsrf } from "~/services/csrf-session.server";
-import { parseError } from "~/shared/error/error-parse";
import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";
+import { createAssetContentLoader } from "~/services/asset-rest-route-handlers.server";
+import { ensureApiCsrf } from "~/services/api-auth.server";
+import {
+ assetRestErrorResponse,
+ assetRestMethodNotAllowed,
+ createAssetRestRepository,
+ parseAssetRestFilename,
+ parseAssetRestIdentifier,
+ requireAssetRestBody,
+} from "~/services/asset-rest.server";
-export type AssetContentActionResponse = { asset: Asset } | { errors: string };
+export const loader = createAssetContentLoader();
export const action = async ({ request, params }: ActionFunctionArgs) => {
preventCrossOriginCookie(request);
- if (request.headers.has("x-auth-token") === false) {
- await checkCsrf(request);
+ if (
+ request.method.toLowerCase() !==
+ assetResourceApiOperations.replaceAssetContent.method
+ ) {
+ return assetRestMethodNotAllowed([
+ assetResourceApiOperations.replaceAssetContent,
+ ]);
}
+ await ensureApiCsrf(request);
try {
- if (request.method !== "PUT" || request.body === null) {
- return json(
- { errors: "Method not allowed" } satisfies AssetContentActionResponse,
- { status: 405, headers: privateNoStoreResponseHeaders }
- );
- }
- if (params.assetId === undefined) {
- throw new Error("Asset id is required");
- }
+ const assetId = parseAssetRestIdentifier(params.assetId);
const url = new URL(request.url);
- const projectId = url.searchParams.get("projectId");
- const expectedName = url.searchParams.get("expectedName");
- if (projectId === null || expectedName === null) {
- throw new Error("Project id and expected asset name are required");
- }
-
- const context = await createContext(request);
- const asset = await updateAssetContent(
- {
- assetId: params.assetId,
- projectId,
- expectedName,
- data: request.body,
- },
- createAssetClient(),
- context
+ const expectedName = parseAssetRestFilename(
+ url.searchParams.get("expectedName")
);
- return json({ asset } satisfies AssetContentActionResponse, {
- headers: privateNoStoreResponseHeaders,
+
+ const asset = await (
+ await createAssetRestRepository(request, "edit")
+ ).updateContent({
+ assetId,
+ expectedName,
+ data: requireAssetRestBody(request),
});
- } catch (error) {
- console.error(error);
return json(
+ { asset },
{
- errors: parseError(error).message,
- } satisfies AssetContentActionResponse,
- {
- status: error instanceof AssetRevisionConflictError ? 409 : 400,
headers: privateNoStoreResponseHeaders,
}
);
+ } catch (error) {
+ return assetRestErrorResponse(error);
}
};
diff --git a/apps/builder/app/routes/rest.assets.$assetId.tsx b/apps/builder/app/routes/rest.assets.$assetId.tsx
new file mode 100644
index 0000000000..627afc7cf5
--- /dev/null
+++ b/apps/builder/app/routes/rest.assets.$assetId.tsx
@@ -0,0 +1,29 @@
+import { json, type LoaderFunctionArgs } from "@remix-run/server-runtime";
+import { assetResourceApiOperations } from "@webstudio-is/protocol/asset-resource-api";
+import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";
+import { createAssetAction } from "~/services/asset-rest-route-handlers.server";
+import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
+import {
+ assetRestErrorResponse,
+ assetRestMethodNotAllowed,
+ createAssetRestRepository,
+ parseAssetRestIdentifier,
+} from "~/services/asset-rest.server";
+
+export const action = createAssetAction();
+
+export const loader = async ({ request, params }: LoaderFunctionArgs) => {
+ preventCrossOriginCookie(request);
+ if (
+ request.method.toLowerCase() !== assetResourceApiOperations.getAsset.method
+ ) {
+ return assetRestMethodNotAllowed([assetResourceApiOperations.getAsset]);
+ }
+ try {
+ const assetId = parseAssetRestIdentifier(params.assetId);
+ const asset = await (await createAssetRestRepository(request)).get(assetId);
+ return json({ asset }, { headers: privateNoStoreResponseHeaders });
+ } catch (error) {
+ return assetRestErrorResponse(error);
+ }
+};
diff --git a/apps/builder/app/routes/rest.assets.field-catalog.ts b/apps/builder/app/routes/rest.assets.field-catalog.ts
new file mode 100644
index 0000000000..0b881b3f10
--- /dev/null
+++ b/apps/builder/app/routes/rest.assets.field-catalog.ts
@@ -0,0 +1,5 @@
+import { createAssetDescriptionLoader } from "~/shared/$resources/assets-description.server";
+
+export const loader = createAssetDescriptionLoader({
+ createValue: (catalog) => catalog,
+});
diff --git a/apps/builder/app/routes/rest.assets.folders.$folderId.tsx b/apps/builder/app/routes/rest.assets.folders.$folderId.tsx
new file mode 100644
index 0000000000..d8a454d852
--- /dev/null
+++ b/apps/builder/app/routes/rest.assets.folders.$folderId.tsx
@@ -0,0 +1,73 @@
+import {
+ json,
+ type ActionFunctionArgs,
+ type LoaderFunctionArgs,
+} from "@remix-run/server-runtime";
+import {
+ assetFolderUpdateRequest,
+ assetResourceApiOperations,
+} from "@webstudio-is/protocol/asset-resource-api";
+import { ensureApiCsrf } from "~/services/api-auth.server";
+import {
+ assetRestErrorResponse,
+ assetRestMethodNotAllowed,
+ createAssetRestRepository,
+ parseAssetRestIdentifier,
+ readAssetRestJson,
+} from "~/services/asset-rest.server";
+import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";
+import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
+
+export const loader = async ({ request, params }: LoaderFunctionArgs) => {
+ preventCrossOriginCookie(request);
+ if (
+ request.method.toLowerCase() !==
+ assetResourceApiOperations.getAssetFolder.method
+ ) {
+ return assetRestMethodNotAllowed([
+ assetResourceApiOperations.getAssetFolder,
+ ]);
+ }
+ try {
+ const folderId = parseAssetRestIdentifier(params.folderId);
+ const folder = await (
+ await createAssetRestRepository(request, "view")
+ ).getFolder(folderId);
+ return json({ folder }, { headers: privateNoStoreResponseHeaders });
+ } catch (error) {
+ return assetRestErrorResponse(error);
+ }
+};
+
+export const action = async ({ request, params }: ActionFunctionArgs) => {
+ preventCrossOriginCookie(request);
+ const method = request.method.toLowerCase();
+ if (
+ method !== assetResourceApiOperations.updateAssetFolder.method &&
+ method !== assetResourceApiOperations.deleteAssetFolder.method
+ ) {
+ return assetRestMethodNotAllowed([
+ assetResourceApiOperations.updateAssetFolder,
+ assetResourceApiOperations.deleteAssetFolder,
+ ]);
+ }
+ await ensureApiCsrf(request);
+ try {
+ const folderId = parseAssetRestIdentifier(params.folderId);
+ const repository = await createAssetRestRepository(request, "edit");
+ if (method === assetResourceApiOperations.updateAssetFolder.method) {
+ const folder = await repository.updateFolder(
+ folderId,
+ assetFolderUpdateRequest.parse(await readAssetRestJson(request))
+ );
+ return json({ folder }, { headers: privateNoStoreResponseHeaders });
+ }
+ await repository.deleteFolder(folderId);
+ return new Response(null, {
+ status: 204,
+ headers: privateNoStoreResponseHeaders,
+ });
+ } catch (error) {
+ return assetRestErrorResponse(error);
+ }
+};
diff --git a/apps/builder/app/routes/rest.assets.folders.tsx b/apps/builder/app/routes/rest.assets.folders.tsx
new file mode 100644
index 0000000000..875bbafe76
--- /dev/null
+++ b/apps/builder/app/routes/rest.assets.folders.tsx
@@ -0,0 +1,64 @@
+import {
+ json,
+ type ActionFunctionArgs,
+ type LoaderFunctionArgs,
+} from "@remix-run/server-runtime";
+import {
+ assetFolderCreateRequest,
+ assetResourceApiOperations,
+} from "@webstudio-is/protocol/asset-resource-api";
+import { ensureApiCsrf } from "~/services/api-auth.server";
+import {
+ assetRestErrorResponse,
+ assetRestMethodNotAllowed,
+ createAssetRestRepository,
+ readAssetRestJson,
+} from "~/services/asset-rest.server";
+import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";
+import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
+
+export const loader = async ({ request }: LoaderFunctionArgs) => {
+ preventCrossOriginCookie(request);
+ if (
+ request.method.toLowerCase() !==
+ assetResourceApiOperations.listAssetFolders.method
+ ) {
+ return assetRestMethodNotAllowed([
+ assetResourceApiOperations.listAssetFolders,
+ ]);
+ }
+ try {
+ const folders = await (
+ await createAssetRestRepository(request, "view")
+ ).listFolders();
+ return json({ folders }, { headers: privateNoStoreResponseHeaders });
+ } catch (error) {
+ return assetRestErrorResponse(error);
+ }
+};
+
+export const action = async ({ request }: ActionFunctionArgs) => {
+ preventCrossOriginCookie(request);
+ if (
+ request.method.toLowerCase() !==
+ assetResourceApiOperations.createAssetFolder.method
+ ) {
+ return assetRestMethodNotAllowed([
+ assetResourceApiOperations.createAssetFolder,
+ ]);
+ }
+ await ensureApiCsrf(request);
+ try {
+ const folder = await (
+ await createAssetRestRepository(request, "edit")
+ ).createFolder(
+ assetFolderCreateRequest.parse(await readAssetRestJson(request))
+ );
+ return json(
+ { folder },
+ { status: 201, headers: privateNoStoreResponseHeaders }
+ );
+ } catch (error) {
+ return assetRestErrorResponse(error);
+ }
+};
diff --git a/apps/builder/app/routes/rest.assets.index.refresh.ts b/apps/builder/app/routes/rest.assets.index.refresh.ts
new file mode 100644
index 0000000000..c639cf2d40
--- /dev/null
+++ b/apps/builder/app/routes/rest.assets.index.refresh.ts
@@ -0,0 +1,3 @@
+import { createAssetIndexRefreshAction } from "~/services/asset-rest-route-handlers.server";
+
+export const action = createAssetIndexRefreshAction();
diff --git a/apps/builder/app/routes/rest.assets.openapi[.]json.ts b/apps/builder/app/routes/rest.assets.openapi[.]json.ts
new file mode 100644
index 0000000000..51517155ed
--- /dev/null
+++ b/apps/builder/app/routes/rest.assets.openapi[.]json.ts
@@ -0,0 +1,13 @@
+import { createAssetResourceOpenApi } from "@webstudio-is/protocol/asset-resource-api";
+import { createStaticAssetDescriptionLoader } from "~/shared/$resources/assets-description.server";
+import { builderSessionCookieName } from "~/services/builder-session.server";
+import { assetsQuerySchemaApiUrl } from "@webstudio-is/sdk/runtime";
+
+export const loader = createStaticAssetDescriptionLoader({
+ createValue: ({ projectId }) =>
+ createAssetResourceOpenApi({
+ builderSessionCookieName,
+ querySchemaReference: `${assetsQuerySchemaApiUrl}?projectId=${encodeURIComponent(projectId)}`,
+ }),
+ contentType: "application/vnd.oai.openapi+json;version=3.1",
+});
diff --git a/apps/builder/app/routes/rest.assets.query-schema[.]json.ts b/apps/builder/app/routes/rest.assets.query-schema[.]json.ts
new file mode 100644
index 0000000000..780088e485
--- /dev/null
+++ b/apps/builder/app/routes/rest.assets.query-schema[.]json.ts
@@ -0,0 +1,7 @@
+import { createAssetQueryJsonSchema } from "@webstudio-is/protocol/asset-resource-api";
+import { createAssetDescriptionLoader } from "~/shared/$resources/assets-description.server";
+
+export const loader = createAssetDescriptionLoader({
+ createValue: (catalog) => createAssetQueryJsonSchema({ catalog }),
+ contentType: "application/schema+json",
+});
diff --git a/apps/builder/app/routes/rest.assets.query.ts b/apps/builder/app/routes/rest.assets.query.ts
new file mode 100644
index 0000000000..752f6e44bf
--- /dev/null
+++ b/apps/builder/app/routes/rest.assets.query.ts
@@ -0,0 +1,14 @@
+import type { ActionFunctionArgs } from "@remix-run/server-runtime";
+import { assetResourceApiOperations } from "@webstudio-is/protocol/asset-resource-api";
+import { executeAssetQuery } from "../shared/$resources/assets-query.server";
+import { assetRestMethodNotAllowed } from "~/services/asset-rest.server";
+
+export const action = async ({ request }: ActionFunctionArgs) => {
+ if (
+ request.method.toLowerCase() !==
+ assetResourceApiOperations.queryAssets.method
+ ) {
+ return assetRestMethodNotAllowed([assetResourceApiOperations.queryAssets]);
+ }
+ return await executeAssetQuery({ request, resourceRequest: request });
+};
diff --git a/apps/builder/app/routes/rest.assets.tsx b/apps/builder/app/routes/rest.assets.tsx
index 6d02b5b8cf..b05afc69bd 100644
--- a/apps/builder/app/routes/rest.assets.tsx
+++ b/apps/builder/app/routes/rest.assets.tsx
@@ -1,72 +1,27 @@
-import { json, type ActionFunctionArgs } from "@remix-run/server-runtime";
+import { json, type LoaderFunctionArgs } from "@remix-run/server-runtime";
+import { assetResourceApiOperations } from "@webstudio-is/protocol/asset-resource-api";
+import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";
import {
- createUploadTicket,
- isContentHash,
-} from "@webstudio-is/asset-uploader/index.server";
-import isValidFilename from "valid-filename";
-import { createContext } from "~/shared/context.server";
+ assetRestErrorResponse,
+ assetRestMethodNotAllowed,
+ createAssetRestRepository,
+} from "~/services/asset-rest.server";
import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
-import { checkCsrf } from "~/services/csrf-session.server";
-import { parseError } from "~/shared/error/error-parse";
-import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";
-export const loader = async () => {
- return json(
- { errors: "Method not allowed" },
- { status: 405, headers: privateNoStoreResponseHeaders }
- );
-};
-
-export const action = async (props: ActionFunctionArgs) => {
+export const loader = async ({ request }: LoaderFunctionArgs) => {
+ preventCrossOriginCookie(request);
+ if (
+ request.method.toLowerCase() !==
+ assetResourceApiOperations.listAssets.method
+ ) {
+ return assetRestMethodNotAllowed([assetResourceApiOperations.listAssets]);
+ }
try {
- preventCrossOriginCookie(props.request);
- await checkCsrf(props.request);
-
- const { request } = props;
-
- const context = await createContext(request);
-
- if (request.method === "POST") {
- const formData = await request.formData();
- const projectId = formData.get("projectId");
- const type = formData.get("type");
- const filename = formData.get("filename");
- const displayFilename = formData.get("displayFilename");
- const contentHash = formData.get("contentHash");
- if (
- typeof projectId !== "string" ||
- typeof type !== "string" ||
- typeof filename !== "string" ||
- (contentHash !== null && isContentHash(contentHash) === false) ||
- (displayFilename !== null &&
- (typeof displayFilename !== "string" ||
- isValidFilename(displayFilename) === false))
- ) {
- throw Error("Project id, type or filename are invalid");
- }
- const ticket = await createUploadTicket(
- {
- projectId,
- type,
- filename,
- displayFilename: displayFilename ?? undefined,
- contentHash: contentHash ?? undefined,
- },
- context
- );
- return json(ticket, { headers: privateNoStoreResponseHeaders });
- }
-
- return json(
- { errors: "Method not allowed" },
- { status: 405, headers: privateNoStoreResponseHeaders }
- );
+ const assets = await (
+ await createAssetRestRepository(request, "view")
+ ).list();
+ return json({ assets }, { headers: privateNoStoreResponseHeaders });
} catch (error) {
- console.error(error);
-
- return json(
- { errors: parseError(error).message },
- { headers: privateNoStoreResponseHeaders }
- );
+ return assetRestErrorResponse(error);
}
};
diff --git a/apps/builder/app/routes/rest.assets.uploads.tsx b/apps/builder/app/routes/rest.assets.uploads.tsx
new file mode 100644
index 0000000000..fc5a82f109
--- /dev/null
+++ b/apps/builder/app/routes/rest.assets.uploads.tsx
@@ -0,0 +1,71 @@
+import { json, type ActionFunctionArgs } from "@remix-run/server-runtime";
+import isValidFilename from "valid-filename";
+import {
+ assetResourceApiOperations,
+ assetUploadReservationRequest,
+} from "@webstudio-is/protocol/asset-resource-api";
+import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
+import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";
+import { ensureApiCsrf } from "~/services/api-auth.server";
+import {
+ AssetRestRequestError,
+ assetRestErrorResponse,
+ assetRestMethodNotAllowed,
+ createAssetRestRepositoryForProject,
+ readAssetRestFormData,
+ readAssetRestJson,
+} from "~/services/asset-rest.server";
+
+// Keep upload commands under an explicit collection so read-only Assets API
+// operations can use stable names without colliding with uploaded filenames.
+
+export const loader = async () => {
+ return assetRestMethodNotAllowed([
+ assetResourceApiOperations.reserveAssetUpload,
+ ]);
+};
+
+export const action = async (props: ActionFunctionArgs) => {
+ const { request } = props;
+ preventCrossOriginCookie(request);
+ if (
+ request.method.toLowerCase() !==
+ assetResourceApiOperations.reserveAssetUpload.method
+ ) {
+ return assetRestMethodNotAllowed([
+ assetResourceApiOperations.reserveAssetUpload,
+ ]);
+ }
+ await ensureApiCsrf(request);
+ try {
+ const contentType = request.headers.get("content-type") ?? "";
+ const rawInput = contentType.includes("application/json")
+ ? await readAssetRestJson(request)
+ : Object.fromEntries(await readAssetRestFormData(request));
+ const input = assetUploadReservationRequest.parse(rawInput);
+ if (
+ input.displayFilename !== undefined &&
+ isValidFilename(input.displayFilename) === false
+ ) {
+ throw new AssetRestRequestError(
+ "Project id, type or filename are invalid"
+ );
+ }
+ const repository = await createAssetRestRepositoryForProject(
+ request,
+ input.projectId,
+ "edit"
+ );
+ const ticket = await repository.createUploadTicket({
+ type: input.type,
+ filename: input.filename,
+ displayFilename: input.displayFilename,
+ description: input.description,
+ folderId: input.folderId,
+ contentHash: input.contentHash,
+ });
+ return json(ticket, { headers: privateNoStoreResponseHeaders });
+ } catch (error) {
+ return assetRestErrorResponse(error);
+ }
+};
diff --git a/apps/builder/app/routes/rest.assets.uploads_.$name.tsx b/apps/builder/app/routes/rest.assets.uploads_.$name.tsx
new file mode 100644
index 0000000000..53e82d0ce6
--- /dev/null
+++ b/apps/builder/app/routes/rest.assets.uploads_.$name.tsx
@@ -0,0 +1,186 @@
+import { json, type ActionFunctionArgs } from "@remix-run/server-runtime";
+import { arrayBuffer } from "node:stream/consumers";
+import {
+ createSizeLimiter,
+ assetDataOverride,
+ PostgresAssetRepository,
+} from "@webstudio-is/asset-uploader/server";
+import { isAssetFileName } from "@webstudio-is/protocol";
+import {
+ assetResourceApiOperations,
+ type AssetUploadResult,
+} from "@webstudio-is/protocol/asset-resource-api";
+import { getAssetContentHash, type Asset } from "@webstudio-is/sdk";
+import {
+ createAssetClient,
+ getMaxAssetUploadSize,
+} from "~/shared/asset-client";
+import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
+import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";
+import { ensureApiCsrf } from "~/services/api-auth.server";
+import { createContext } from "~/shared/context.server";
+import {
+ AssetRestRequestError,
+ assetRestErrorResponse,
+ assetRestMethodNotAllowed,
+ createAssetRestRepositoryForProject,
+ parseAssetRestDescription,
+ parseAssetRestFilename,
+ parseAssetRestIdentifier,
+ parseAssetRestMetadataHeader,
+ requireAssetRestBody,
+} from "~/services/asset-rest.server";
+import {
+ getAssetInfoFallback,
+ getBrowserAssetFormat,
+ parseAssetType,
+} from "@webstudio-is/project-build/runtime";
+import { getBrowserUploadBody } from "~/services/asset-upload.server";
+
+// The explicit uploads segment prevents asset names such as `query` from
+// shadowing the read-only Assets API.
+
+const assetUploadResponse = ({
+ asset,
+ deduplicated,
+}: {
+ asset: Asset;
+ deduplicated: boolean;
+}) => {
+ return json(
+ {
+ uploadedAssets: [asset],
+ deduplicated,
+ } satisfies AssetUploadResult,
+ {
+ headers: privateNoStoreResponseHeaders,
+ }
+ );
+};
+
+const createRequestBody = (data: Uint8Array) =>
+ new Blob([data as Uint8Array<ArrayBuffer>]).stream();
+
+const readRequestBody = async (
+ body: ReadableStream<Uint8Array>,
+ name: string
+) =>
+ new Uint8Array(
+ await arrayBuffer(
+ createSizeLimiter(
+ getMaxAssetUploadSize(),
+ name
+ )(body as unknown as AsyncIterable<Uint8Array>)
+ )
+ );
+
+export const action = async (props: ActionFunctionArgs) => {
+ preventCrossOriginCookie(props.request);
+
+ const { request, params } = props;
+ if (
+ request.method.toLowerCase() !==
+ assetResourceApiOperations.uploadAssetContent.method
+ ) {
+ return assetRestMethodNotAllowed([
+ assetResourceApiOperations.uploadAssetContent,
+ ]);
+ }
+
+ const url = new URL(request.url);
+ const projectId = url.searchParams.get("projectId");
+ const folderIdValue = url.searchParams.get("folderId");
+ const rawAssetMeta = request.headers.get("x-webstudio-asset-meta");
+ const rawAssetType = url.searchParams.get("type");
+ const isApiUpload = projectId !== null || rawAssetType !== null;
+
+ await ensureApiCsrf(request);
+
+ try {
+ if (params.name === undefined) {
+ throw new AssetRestRequestError("Asset name is required");
+ }
+ const requestBody = requireAssetRestBody(request);
+
+ const assetType = parseAssetType(rawAssetType);
+
+ if (isApiUpload) {
+ const filename = parseAssetRestFilename(params.name);
+ if (isAssetFileName(filename) === false) {
+ throw new AssetRestRequestError("Asset name is invalid");
+ }
+ const parsedProjectId = parseAssetRestIdentifier(projectId);
+ const folderId =
+ folderIdValue === null
+ ? undefined
+ : parseAssetRestIdentifier(folderIdValue);
+ const description = parseAssetRestDescription(
+ request.headers.get("x-webstudio-asset-description")
+ );
+ if (assetType === undefined) {
+ throw new AssetRestRequestError("Asset type is invalid");
+ }
+ const assetInfoFallback = getAssetInfoFallback({
+ format:
+ assetType === "image"
+ ? (url.searchParams.get("format") ?? undefined)
+ : undefined,
+ searchParams: url.searchParams,
+ });
+ const assetInfoOverride = assetDataOverride.parse({
+ format: url.searchParams.get("format") ?? undefined,
+ meta: parseAssetRestMetadataHeader(rawAssetMeta),
+ });
+
+ const repository = await createAssetRestRepositoryForProject(
+ request,
+ parsedProjectId,
+ "edit"
+ );
+ const data = await readRequestBody(requestBody, params.name);
+ const force = url.searchParams.get("force") === "true";
+ const ticket = await repository.createUploadTicket({
+ type: assetType,
+ filename,
+ description,
+ folderId,
+ contentHash: force ? undefined : await getAssetContentHash(data),
+ });
+ if (ticket.deduplicated) {
+ return assetUploadResponse({ asset: ticket.asset, deduplicated: true });
+ }
+ const asset = await repository.completeUpload({
+ name: ticket.name,
+ data: createRequestBody(data),
+ assetInfoFallback,
+ assetDataOverride: assetInfoOverride,
+ assetId: ticket.assetId,
+ });
+ return assetUploadResponse({ asset, deduplicated: false });
+ }
+
+ const contentType = request.headers.get("Content-Type");
+ const body = await getBrowserUploadBody(request, contentType);
+ const format = getBrowserAssetFormat({ contentType, name: params.name });
+ const assetInfoFallback = getAssetInfoFallback({
+ format,
+ searchParams: url.searchParams,
+ });
+
+ const context = await createContext(request);
+ const assetClient = createAssetClient();
+ const repository = await PostgresAssetRepository.forUpload({
+ name: params.name,
+ context,
+ assetStore: assetClient,
+ });
+ const asset = await repository.completeUpload({
+ name: params.name,
+ data: body,
+ assetInfoFallback,
+ });
+ return assetUploadResponse({ asset, deduplicated: false });
+ } catch (error) {
+ return assetRestErrorResponse(error);
+ }
+};
diff --git a/apps/builder/app/routes/rest.assets_.$name.tsx b/apps/builder/app/routes/rest.assets_.$name.tsx
deleted file mode 100644
index a9c2c9a742..0000000000
--- a/apps/builder/app/routes/rest.assets_.$name.tsx
+++ /dev/null
@@ -1,222 +0,0 @@
-import { json, type ActionFunctionArgs } from "@remix-run/server-runtime";
-import { arrayBuffer } from "node:stream/consumers";
-import {
- createUploadTicket,
- createSizeLimiter,
- assetDataOverride,
- getContentHash,
- uploadFile,
- type UploadErrorCleanup,
-} from "@webstudio-is/asset-uploader/index.server";
-import { isAssetFileName } from "@webstudio-is/protocol";
-import type { Asset } from "@webstudio-is/sdk";
-import type { AssetActionResponse } from "~/builder/shared/assets";
-import {
- createAssetClient,
- getMaxAssetUploadSize,
-} from "~/shared/asset-client";
-import { createContext } from "~/shared/context.server";
-import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
-import { checkCsrf } from "~/services/csrf-session.server";
-import { parseError } from "~/shared/error/error-parse";
-import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";
-import { assertApiProjectPermit } from "~/services/api-permits.server";
-import {
- getAssetInfoFallback,
- getBrowserAssetFormat,
- parseAssetType,
- type AssetInfoFallback,
-} from "@webstudio-is/project-build/runtime";
-import { getBrowserUploadBody } from "~/services/asset-upload.server";
-
-const createAssetUploadResponse = async ({
- body,
- context,
- name,
- assetInfoFallback,
- assetInfoOverride,
- onUploadError,
-}: {
- body: ReadableStream<Uint8Array>;
- context: Awaited<ReturnType<typeof createContext>>;
- name: string;
- assetInfoFallback: AssetInfoFallback;
- assetInfoOverride?: {
- format?: string;
- meta?: Record<string, unknown>;
- };
- onUploadError?: UploadErrorCleanup;
-}) => {
- const asset = await uploadFile(
- name,
- body,
- createAssetClient(),
- context,
- assetInfoFallback,
- assetInfoOverride,
- onUploadError
- );
- return json(
- {
- uploadedAssets: [asset],
- deduplicated: false,
- } satisfies AssetActionResponse,
- {
- headers: privateNoStoreResponseHeaders,
- }
- );
-};
-
-const createDeduplicatedAssetResponse = (asset: Asset) => {
- return json(
- {
- uploadedAssets: [asset],
- deduplicated: true,
- } satisfies AssetActionResponse,
- {
- headers: privateNoStoreResponseHeaders,
- }
- );
-};
-
-const createRequestBody = (data: Uint8Array) =>
- new Blob([data as Uint8Array<ArrayBuffer>]).stream();
-
-const readRequestBody = async (
- body: ReadableStream<Uint8Array>,
- name: string
-) =>
- new Uint8Array(
- await arrayBuffer(
- createSizeLimiter(
- getMaxAssetUploadSize(),
- name
- )(body as unknown as AsyncIterable<Uint8Array>)
- )
- );
-
-const createApiUploadErrorCleanup =
- (assetId: string, projectId: string): UploadErrorCleanup =>
- async (name, context) => {
- const deleteAsset = await context.postgrest.client
- .from("Asset")
- .delete()
- .eq("id", assetId)
- .eq("projectId", projectId);
- if (deleteAsset.error) {
- throw deleteAsset.error;
- }
- const deleteFile = await context.postgrest.client
- .from("File")
- .delete()
- .eq("name", name);
- if (deleteFile.error) {
- throw deleteFile.error;
- }
- };
-
-export const action = async (props: ActionFunctionArgs) => {
- preventCrossOriginCookie(props.request);
-
- const { request, params } = props;
-
- if (params.name === undefined) {
- throw new Error("Name is undefined");
- }
-
- const url = new URL(request.url);
- const projectId = url.searchParams.get("projectId");
- const folderId = url.searchParams.get("folderId") ?? undefined;
- const description =
- request.headers.get("x-webstudio-asset-description") ?? undefined;
- const rawAssetMeta = request.headers.get("x-webstudio-asset-meta");
- const rawAssetType = url.searchParams.get("type");
- const isApiUpload = projectId !== null || rawAssetType !== null;
-
- if (isApiUpload === false) {
- await checkCsrf(request);
- }
-
- try {
- if (request.method !== "POST" || request.body === null) {
- return json(
- { errors: "Method not allowed" } satisfies AssetActionResponse,
- { status: 405, headers: privateNoStoreResponseHeaders }
- );
- }
-
- const assetType = parseAssetType(rawAssetType);
-
- if (isApiUpload) {
- if (isAssetFileName(params.name) === false) {
- throw new Error("Asset name is invalid");
- }
- if (projectId === null) {
- throw new Error("Project id is required");
- }
- if (assetType === undefined) {
- throw new Error("Asset type is invalid");
- }
- const assetInfoFallback = getAssetInfoFallback({
- format:
- assetType === "image"
- ? (url.searchParams.get("format") ?? undefined)
- : undefined,
- searchParams: url.searchParams,
- });
- const assetInfoOverride = assetDataOverride.parse({
- format: url.searchParams.get("format") ?? undefined,
- meta: rawAssetMeta === null ? undefined : JSON.parse(rawAssetMeta),
- });
-
- const context = await createContext(request);
- await assertApiProjectPermit(context, projectId, "build");
- const data = await readRequestBody(request.body, params.name);
- const force = url.searchParams.get("force") === "true";
- const ticket = await createUploadTicket(
- {
- projectId,
- type: assetType,
- filename: params.name,
- description,
- folderId,
- contentHash: force ? undefined : await getContentHash(data),
- },
- context
- );
- if (ticket.deduplicated) {
- return createDeduplicatedAssetResponse(ticket.asset);
- }
- return await createAssetUploadResponse({
- body: createRequestBody(data),
- context,
- name: ticket.name,
- assetInfoFallback,
- assetInfoOverride,
- onUploadError: createApiUploadErrorCleanup(ticket.assetId, projectId),
- });
- }
-
- const contentType = request.headers.get("Content-Type");
- const body = await getBrowserUploadBody(request, contentType);
- const format = getBrowserAssetFormat({ contentType, name: params.name });
- const assetInfoFallback = getAssetInfoFallback({
- format,
- searchParams: url.searchParams,
- });
-
- const context = await createContext(request);
- return await createAssetUploadResponse({
- body,
- context,
- name: params.name,
- assetInfoFallback,
- });
- } catch (error) {
- console.error(error);
- return json(
- { errors: parseError(error).message } satisfies AssetActionResponse,
- { headers: privateNoStoreResponseHeaders }
- );
- }
-};
diff --git a/apps/builder/app/routes/rest.resources-loader.ts b/apps/builder/app/routes/rest.resources-loader.ts
index 1d35d0bf49..9b444f39a0 100644
--- a/apps/builder/app/routes/rest.resources-loader.ts
+++ b/apps/builder/app/routes/rest.resources-loader.ts
@@ -2,9 +2,12 @@ import { z } from "zod";
import { type ActionFunctionArgs, data, json } from "@remix-run/server-runtime";
import { type ResourceRequest, resourceRequest } from "@webstudio-is/sdk";
import { isLocalResource, loadResource } from "@webstudio-is/sdk/runtime";
+import { parseBuilderUrl } from "@webstudio-is/protocol";
import { loader as siteMapLoader } from "../shared/$resources/sitemap.xml.server";
import { loader as currentDateLoader } from "../shared/$resources/current-date.server";
-import { loader as assetsLoader } from "../shared/$resources/assets.server";
+import { loader as assetsFieldCatalogLoader } from "./rest.assets.field-catalog";
+import { executeAssetQuery } from "../shared/$resources/assets-query.server";
+import { loader as assetsOpenApiLoader } from "./rest.assets.openapi[.]json";
import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
import { checkCsrf } from "~/services/csrf-session.server";
import { getResourceKey } from "~/shared/resources";
@@ -29,13 +32,23 @@ export const action = async ({ request }: ActionFunctionArgs) => {
}
if (isLocalResource(input, "assets")) {
- return assetsLoader({ request });
+ const resourceRequest = new Request(new URL(input, request.url), init);
+ return executeAssetQuery({ request, resourceRequest });
+ }
+
+ if (isLocalResource(input, "assets/field-catalog")) {
+ return assetsFieldCatalogLoader({ request });
+ }
+
+ if (isLocalResource(input, "assets/openapi.json")) {
+ return assetsOpenApiLoader({ request });
}
return fetch(input, init);
};
const requestJson = await request.json();
+ const { sourceOrigin } = parseBuilderUrl(request.url);
const requestList = z.array(z.unknown()).safeParse(requestJson);
if (requestList.success === false) {
@@ -62,7 +75,7 @@ export const action = async ({ request }: ActionFunctionArgs) => {
}
return [
getResourceKey(resource.data),
- await loadResource(customFetch, resource.data),
+ await loadResource(customFetch, resource.data, sourceOrigin),
];
})
);
diff --git a/apps/builder/app/routes/trpc.$.ts b/apps/builder/app/routes/trpc.$.ts
index 0fb8ab7f4c..9bcbd1f73b 100644
--- a/apps/builder/app/routes/trpc.$.ts
+++ b/apps/builder/app/routes/trpc.$.ts
@@ -3,27 +3,17 @@ import type { ActionFunctionArgs } from "@remix-run/server-runtime";
import { createContext, isServiceAuthorization } from "~/shared/context.server";
import { appRouter } from "~/services/trcp-router.server";
import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
-import { checkCsrf } from "~/services/csrf-session.server";
import { getTrpcResponseMeta } from "~/services/trpc-response-meta.server";
-import { isCliApiRequest } from "~/services/trpc-request.server";
+import { ensureApiCsrf } from "~/services/api-auth.server";
const isServiceRequest = (request: Request) => {
return isServiceAuthorization(request.headers.get("Authorization"));
};
-const isAuthTokenRequest = (request: Request) => {
- return request.headers.has("x-auth-token");
-};
-
export const action = async ({ request }: ActionFunctionArgs) => {
- if (
- isServiceRequest(request) === false &&
- isCliApiRequest(request) === false
- ) {
+ if (isServiceRequest(request) === false) {
preventCrossOriginCookie(request);
- if (isAuthTokenRequest(request) === false) {
- await checkCsrf(request);
- }
+ await ensureApiCsrf(request);
}
// https://trpc.io/docs/server/adapters/fetch
diff --git a/apps/builder/app/services/api-auth.server.test.ts b/apps/builder/app/services/api-auth.server.test.ts
new file mode 100644
index 0000000000..88a13d5028
--- /dev/null
+++ b/apps/builder/app/services/api-auth.server.test.ts
@@ -0,0 +1,195 @@
+import { expect, test, vi } from "vitest";
+import { TRPCError } from "@trpc/server";
+import { AuthorizationError } from "@webstudio-is/trpc-interface/index.server";
+import {
+ authorizeApiProject,
+ ensureApiCsrf,
+ getApiAuthorizationFailure,
+ requiresApiCsrf,
+} from "./api-auth.server";
+
+test.each([
+ [
+ new TRPCError({ code: "UNAUTHORIZED", message: "login required" }),
+ { status: 401, code: "UNAUTHORIZED", message: "login required" },
+ ],
+ [
+ new TRPCError({ code: "FORBIDDEN", message: "denied" }),
+ { status: 403, code: "FORBIDDEN", message: "denied" },
+ ],
+ [
+ new AuthorizationError("project denied"),
+ { status: 403, code: "FORBIDDEN", message: "project denied" },
+ ],
+ [
+ new Response("CSRF failed", { status: 403 }),
+ { status: 403, code: "FORBIDDEN", message: "Forbidden" },
+ ],
+])("classifies API authorization failures", (error, expected) => {
+ expect(getApiAuthorizationFailure(error)).toEqual(expected);
+});
+
+test("does not classify unrelated failures as authorization failures", () => {
+ expect(
+ getApiAuthorizationFailure(new Error("database failed"))
+ ).toBeUndefined();
+});
+
+test("requires CSRF for cookie-authenticated API requests", () => {
+ expect(requiresApiCsrf(new Request("https://example.com/rest/assets"))).toBe(
+ true
+ );
+});
+
+test("uses explicit token authentication without cookie CSRF", () => {
+ expect(
+ requiresApiCsrf(
+ new Request("https://example.com/rest/assets", {
+ headers: { "x-auth-token": "share-token" },
+ })
+ )
+ ).toBe(false);
+});
+
+test("requires CSRF for Builder share-token requests", () => {
+ expect(
+ requiresApiCsrf(
+ new Request("https://example.com/rest/assets", {
+ headers: {
+ "x-auth-token": "share-token",
+ "x-webstudio-client": "browser",
+ },
+ })
+ )
+ ).toBe(true);
+});
+
+test("requires API enablement for explicit API tokens", async () => {
+ const context = { authorization: { type: "token" } } as never;
+ const dependencies = {
+ createContext: vi.fn().mockResolvedValue(context),
+ assertApiProjectPermit: vi.fn().mockResolvedValue(undefined),
+ hasProjectPermit: vi.fn().mockResolvedValue(true),
+ ensureApiCsrf: vi.fn(),
+ };
+
+ await expect(
+ authorizeApiProject(
+ new Request("https://example.com/rest/assets"),
+ "project-1",
+ "view",
+ dependencies
+ )
+ ).resolves.toBe(context);
+ expect(dependencies.assertApiProjectPermit).toHaveBeenCalledWith(
+ context,
+ "project-1",
+ "view"
+ );
+ expect(dependencies.hasProjectPermit).not.toHaveBeenCalled();
+});
+
+test("checks project permits for cookie-authenticated requests", async () => {
+ const context = { authorization: { type: "user" } } as never;
+ const dependencies = {
+ createContext: vi.fn().mockResolvedValue(context),
+ assertApiProjectPermit: vi.fn(),
+ hasProjectPermit: vi.fn().mockResolvedValue(true),
+ ensureApiCsrf: vi.fn(),
+ };
+
+ await authorizeApiProject(
+ new Request("https://example.com/rest/assets"),
+ "project-1",
+ "build",
+ dependencies
+ );
+ expect(dependencies.assertApiProjectPermit).toHaveBeenCalledWith(
+ context,
+ "project-1",
+ "build"
+ );
+ expect(dependencies.hasProjectPermit).not.toHaveBeenCalled();
+});
+
+test("keeps Builder share-token requests on project authorization", async () => {
+ const context = { authorization: { type: "token" } } as never;
+ const dependencies = {
+ createContext: vi.fn().mockResolvedValue(context),
+ assertApiProjectPermit: vi.fn(),
+ hasProjectPermit: vi.fn().mockResolvedValue(true),
+ ensureApiCsrf: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await authorizeApiProject(
+ new Request("https://example.com/rest/assets", {
+ headers: { "x-webstudio-client": "browser", "x-auth-token": "token" },
+ }),
+ "project-1",
+ "build",
+ dependencies
+ );
+ expect(dependencies.assertApiProjectPermit).not.toHaveBeenCalled();
+ expect(dependencies.hasProjectPermit).toHaveBeenCalledWith(
+ { projectId: "project-1", permit: "build" },
+ context
+ );
+ expect(dependencies.ensureApiCsrf).toHaveBeenCalledOnce();
+});
+
+test("rejects Builder share tokens for a different project", async () => {
+ const context = { authorization: { type: "token" } } as never;
+ const dependencies = {
+ createContext: vi.fn().mockResolvedValue(context),
+ assertApiProjectPermit: vi.fn(),
+ hasProjectPermit: vi.fn().mockResolvedValue(false),
+ ensureApiCsrf: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await expect(
+ authorizeApiProject(
+ new Request("https://example.com/rest/assets", {
+ headers: { "x-webstudio-client": "browser", "x-auth-token": "token" },
+ }),
+ "other-project",
+ "view",
+ dependencies
+ )
+ ).rejects.toThrow("You don't have access to this project");
+ expect(dependencies.assertApiProjectPermit).not.toHaveBeenCalled();
+});
+
+test("does not trust the Builder client marker without valid CSRF", async () => {
+ const context = { authorization: { type: "token" } } as never;
+ const csrfError = new Response("Forbidden", { status: 403 });
+ const dependencies = {
+ createContext: vi.fn().mockResolvedValue(context),
+ assertApiProjectPermit: vi.fn(),
+ hasProjectPermit: vi.fn().mockResolvedValue(true),
+ ensureApiCsrf: vi.fn().mockRejectedValue(csrfError),
+ };
+
+ await expect(
+ authorizeApiProject(
+ new Request("https://example.com/rest/assets", {
+ headers: { "x-webstudio-client": "browser", "x-auth-token": "token" },
+ }),
+ "project-1",
+ "view",
+ dependencies
+ )
+ ).rejects.toBe(csrfError);
+ expect(dependencies.assertApiProjectPermit).not.toHaveBeenCalled();
+});
+
+test("validates CSRF only once for one request", async () => {
+ const request = new Request("https://example.com/rest/assets", {
+ headers: { "x-webstudio-client": "browser" },
+ });
+ const validate = vi.fn().mockResolvedValue(undefined);
+
+ await ensureApiCsrf(request, validate);
+ await ensureApiCsrf(request, validate);
+
+ expect(validate).toHaveBeenCalledOnce();
+});
diff --git a/apps/builder/app/services/api-auth.server.ts b/apps/builder/app/services/api-auth.server.ts
new file mode 100644
index 0000000000..3fead4ed9b
--- /dev/null
+++ b/apps/builder/app/services/api-auth.server.ts
@@ -0,0 +1,110 @@
+import { TRPCError } from "@trpc/server";
+import {
+ AuthorizationError,
+ authorizeProject,
+ type ProjectPermit,
+} from "@webstudio-is/trpc-interface/index.server";
+import { apiClientHeader } from "@webstudio-is/trpc-interface/api-compatibility";
+import { createContext } from "~/shared/context.server";
+import { assertApiProjectPermit } from "./api-permits.server";
+import { checkCsrf } from "./csrf-session.server";
+
+/**
+ * Authorize one project-scoped API request. Explicit API tokens are subject to
+ * public API enablement and token permits. Browser sessions and Builder share
+ * links retain the repository's normal project authorization.
+ */
+export const authorizeApiProject = async (
+ request: Request,
+ projectId: string,
+ permit: ProjectPermit,
+ dependencies = {
+ createContext,
+ assertApiProjectPermit,
+ hasProjectPermit: authorizeProject.hasProjectPermit,
+ ensureApiCsrf,
+ }
+) => {
+ const context = await dependencies.createContext(request);
+ if (
+ context.authorization.type === "token" &&
+ request.headers.get(apiClientHeader) === "browser"
+ ) {
+ await dependencies.ensureApiCsrf(request);
+ if (
+ (await dependencies.hasProjectPermit({ projectId, permit }, context)) ===
+ false
+ ) {
+ throw new AuthorizationError("You don't have access to this project");
+ }
+ return context;
+ }
+ if (
+ context.authorization.type === "token" ||
+ context.authorization.type === "user"
+ ) {
+ await dependencies.assertApiProjectPermit(context, projectId, permit);
+ }
+ return context;
+};
+
+/**
+ * Requests without an explicit API token require CSRF validation at API
+ * transports that can mutate. Builder share-token requests identify themselves
+ * as browser traffic and remain CSRF-protected.
+ */
+export const requiresApiCsrf = (request: Request) =>
+ request.headers.get(apiClientHeader) === "browser" ||
+ request.headers.has("x-auth-token") === false;
+
+const csrfValidatedRequests = new WeakSet<Request>();
+
+/** Validate one request at most once across its transport and authorization. */
+export const ensureApiCsrf = async (
+ request: Request,
+ validate: typeof checkCsrf = checkCsrf
+) => {
+ if (
+ requiresApiCsrf(request) === false ||
+ csrfValidatedRequests.has(request)
+ ) {
+ return;
+ }
+ await validate(request);
+ csrfValidatedRequests.add(request);
+};
+
+export const getApiAuthorizationFailure = (error: unknown) => {
+ if (
+ error instanceof Response &&
+ (error.status === 401 || error.status === 403)
+ ) {
+ return {
+ status: error.status,
+ code:
+ error.status === 401
+ ? ("UNAUTHORIZED" as const)
+ : ("FORBIDDEN" as const),
+ message:
+ error.statusText ||
+ (error.status === 401 ? "Authentication required" : "Forbidden"),
+ };
+ }
+ if (error instanceof TRPCError && error.code === "UNAUTHORIZED") {
+ return {
+ status: 401 as const,
+ code: "UNAUTHORIZED" as const,
+ message: error.message,
+ };
+ }
+ if (
+ (error instanceof TRPCError && error.code === "FORBIDDEN") ||
+ error instanceof AuthorizationError
+ ) {
+ return {
+ status: 403 as const,
+ code: "FORBIDDEN" as const,
+ message: error.message,
+ };
+ }
+};
diff --git a/apps/builder/app/services/api-permits.server.ts b/apps/builder/app/services/api-permits.server.ts
index f6dcb47f2d..d697273c55 100644
--- a/apps/builder/app/services/api-permits.server.ts
+++ b/apps/builder/app/services/api-permits.server.ts
@@ -46,36 +46,56 @@ export const assertApiTokenPermit = async (ctx: AppContext) => {
return { token, permits };
};
-export const assertApiProjectPermit = async (
+const assertProjectPermit = async (
ctx: AppContext,
projectId: string,
permit: ProjectApiPermit
) => {
- const { token, permits } = await assertApiTokenPermit(ctx);
- if (token.projectId !== projectId) {
+ const allowed = await authorizeProject.hasProjectPermit(
+ { projectId, permit },
+ ctx
+ );
+ if (allowed === false) {
throw new TRPCError({
code: "FORBIDDEN",
- message: "Authorization token is not valid for project",
+ message: "You don't have access to this project",
});
}
+};
+
+export const assertApiProjectPermit = async (
+ ctx: AppContext,
+ projectId: string,
+ permit: ProjectApiPermit
+) => {
+ if (ctx.authorization.type === "user") {
+ await assertProjectPermit(ctx, projectId, permit);
+ const permits: ProjectApiPermit[] = [permit];
+ if (
+ permit === "edit" &&
+ (await authorizeProject.hasProjectPermit(
+ { projectId, permit: "build" },
+ ctx
+ ))
+ ) {
+ permits.push("build");
+ }
+ return { type: "user" as const, permits };
+ }
- if (permits.includes(permit) === false) {
+ const tokenAuth = await assertApiTokenPermit(ctx);
+ if (tokenAuth.token.projectId !== projectId) {
throw new TRPCError({
code: "FORBIDDEN",
- message: `Authorization token does not have ${permit} permission`,
+ message: "Authorization token is not valid for project",
});
}
-
- const canUseProject = await authorizeProject.hasProjectPermit(
- { projectId, permit },
- ctx
- );
- if (canUseProject === false) {
+ if (tokenAuth.permits.includes(permit) === false) {
throw new TRPCError({
code: "FORBIDDEN",
- message: "You don't have access to this project",
+ message: `Authorization token does not have ${permit} permission`,
});
}
-
- return { token, permits };
+ await assertProjectPermit(ctx, projectId, permit);
+ return { type: "token" as const, ...tokenAuth };
};
diff --git a/apps/builder/app/services/api-router.server.test.ts b/apps/builder/app/services/api-router.server.test.ts
index 4861d1838e..f2e004c385 100644
--- a/apps/builder/app/services/api-router.server.test.ts
+++ b/apps/builder/app/services/api-router.server.test.ts
@@ -18,7 +18,8 @@ import {
} from "@webstudio-is/trpc-interface/index.server";
import { db as authDb } from "@webstudio-is/authorization-token/index.server";
import { blockComponent } from "@webstudio-is/sdk";
-import * as assetUploader from "@webstudio-is/asset-uploader/index.server";
+import { AssetIndexRevisionError } from "@webstudio-is/content-engine";
+import * as assetUploader from "@webstudio-is/asset-uploader/server";
import { apiRouter, __testing__ } from "./api-router.server";
import {
getApiRouterProcedures,
@@ -74,6 +75,115 @@ const createCaller = (context: AppContext) =>
apiRouter.createCaller(context) as ApiRouterCaller & RuntimeApiCaller;
describe("api router build operation adapters", () => {
+ test("exposes query validation and persisted asset query reads to API clients", async () => {
+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(createToken());
+ vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);
+ vi.spyOn(assetUploader, "previewAssetResourceQuery").mockResolvedValue({
+ data: {
+ items: [{ id: "post" }],
+ totalCount: 1,
+ hasMore: false,
+ },
+ __diagnostics__: {
+ scope: "query-preview",
+ usedBytes: 100,
+ maxBytes: 512_000,
+ unboundedBytes: 100,
+ includedDocumentCount: 1,
+ omittedDocumentCount: 0,
+ truncated: false,
+ },
+ } as never);
+ vi.spyOn(assetUploader, "loadBuilderAssetFieldCatalog").mockResolvedValue({
+ format: "webstudio-builder-asset-field-catalog",
+ version: 1,
+ canonicalRevision: `sha256:${"a".repeat(64)}`,
+ documentCount: 1,
+ fields: {
+ "properties.slug": {
+ types: ["string"],
+ occurrences: 1,
+ queryPath: ["properties", "slug"],
+ },
+ },
+ });
+ const caller = createCaller(createContext(true));
+
+ await expect(
+ caller.assetQueries.validate({
+ projectId: "project-1",
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "post",
+ },
+ ],
+ },
+ limit: 1,
+ },
+ })
+ ).resolves.toMatchObject({
+ valid: true,
+ referencedFieldPaths: expect.arrayContaining([["properties", "slug"]]),
+ filterCount: 1,
+ });
+ await expect(
+ caller.assetQueries.validate({
+ projectId: "project-1",
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "missing"],
+ operator: "exists",
+ value: true,
+ },
+ ],
+ },
+ },
+ })
+ ).resolves.toMatchObject({
+ valid: true,
+ warnings: ["Asset field properties.missing is not currently observed"],
+ });
+ await expect(
+ caller.assetQueries.preview({
+ projectId: "project-1",
+ query: { limit: 10 },
+ })
+ ).resolves.toMatchObject({
+ data: {
+ items: [{ id: "post" }],
+ totalCount: 1,
+ },
+ __diagnostics__: { scope: "query-preview", truncated: false },
+ });
+ expect(assetUploader.previewAssetResourceQuery).toHaveBeenCalledWith(
+ expect.objectContaining({ contentDatabaseMaxBytes: 512_000 })
+ );
+ vi.mocked(assetUploader.previewAssetResourceQuery).mockRejectedValueOnce(
+ new AssetIndexRevisionError()
+ );
+ await expect(
+ caller.assetQueries.preview({
+ projectId: "project-1",
+ query: { limit: 10 },
+ indexRevision: `sha256:${"0".repeat(64)}`,
+ })
+ ).rejects.toMatchObject({
+ code: "CONFLICT",
+ cause: { webstudioCode: "STALE_INDEX" },
+ });
+ await expect(
+ caller.assetQueries.fieldCatalog({ projectId: "project-1" })
+ ).resolves.toMatchObject({
+ fields: { "properties.slug": { types: ["string"] } },
+ });
+ });
+
test("allows CLI clients to refresh pages without project settings", async () => {
const build = {
id: "build-1",
@@ -258,7 +368,9 @@ describe("api router permits", () => {
).toEqual(["view", "edit", "build", "admin", "api"]);
});
- test("requires token auth for project-scoped api procedures", async () => {
+ test("accepts cookie auth for project-scoped api procedures", async () => {
+ vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);
+
await expect(
assertApiProjectPermit(
createContext(true, {
@@ -270,12 +382,50 @@ describe("api router permits", () => {
"project-1",
"view"
)
- ).rejects.toMatchObject({
- code: "FORBIDDEN",
- message: "Builder API requires an API token",
+ ).resolves.toEqual({
+ type: "user",
+ permits: ["view"],
});
});
+ test("rejects cookie auth without the requested project permit", async () => {
+ vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(false);
+
+ await expect(
+ assertApiProjectPermit(
+ createContext(true, {
+ type: "user",
+ userId: "user-1",
+ sessionCreatedAt: 0,
+ isLoggedInToBuilder: async () => true,
+ }),
+ "project-1",
+ "edit"
+ )
+ ).rejects.toThrow("You don't have access to this project");
+ });
+
+ test("preserves content-only permissions for cookie-authenticated editors", async () => {
+ const hasProjectPermit = vi
+ .spyOn(authorizeProject, "hasProjectPermit")
+ .mockImplementation(async ({ permit }) => permit === "edit");
+ const context = createContext(true, {
+ type: "user",
+ userId: "user-1",
+ sessionCreatedAt: 0,
+ isLoggedInToBuilder: async () => true,
+ });
+
+ await expect(
+ assertApiProjectPermit(context, "project-1", "edit")
+ ).resolves.toEqual({ type: "user", permits: ["edit"] });
+
+ hasProjectPermit.mockResolvedValue(true);
+ await expect(
+ assertApiProjectPermit(context, "project-1", "edit")
+ ).resolves.toEqual({ type: "user", permits: ["edit", "build"] });
+ });
+
test("rejects tokens from another project", async () => {
vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(
createToken({ projectId: "project-2" })
@@ -436,6 +586,7 @@ describe("api router permits", () => {
await expect(
assertApiProjectPermit(createContext(true), "project-1", "edit")
).resolves.toEqual({
+ type: "token",
token,
permits: ["view", "edit", "api"],
});
@@ -444,9 +595,18 @@ describe("api router permits", () => {
test("requires publish permission for api publish domains", () => {
const project = { domain: "project.wstd.dev" };
+ expect(() =>
+ assertApiPublishDomains({
+ auth: { type: "user", permits: ["edit"] },
+ domains: ["custom.example.com"],
+ project,
+ })
+ ).not.toThrow();
+
expect(() =>
assertApiPublishDomains({
auth: {
+ type: "token",
token: createToken({ relation: "editors", canPublish: false }),
permits: ["view", "edit", "api"],
},
@@ -458,6 +618,7 @@ describe("api router permits", () => {
expect(() =>
assertApiPublishDomains({
auth: {
+ type: "token",
token: createToken({ relation: "editors", canPublish: true }),
permits: ["view", "edit", "api"],
},
@@ -469,6 +630,7 @@ describe("api router permits", () => {
expect(() =>
assertApiPublishDomains({
auth: {
+ type: "token",
token: createToken({ relation: "builders", canPublish: false }),
permits: ["view", "edit", "build", "api"],
},
@@ -480,6 +642,7 @@ describe("api router permits", () => {
expect(() =>
assertApiPublishDomains({
auth: {
+ type: "token",
token: createToken({ relation: "builders", canPublish: false }),
permits: ["view", "edit", "build", "api"],
},
@@ -491,6 +654,7 @@ describe("api router permits", () => {
expect(() =>
assertApiPublishDomains({
auth: {
+ type: "token",
token: createToken({
relation: "administrators",
canPublish: true,
@@ -536,10 +700,12 @@ describe("api router permits", () => {
marketplaceProduct: {},
} as unknown as CompactBuild;
const editorAuth = {
+ type: "token",
token: createToken({ relation: "editors" }),
permits: ["view", "edit", "api"],
} satisfies Awaited<ReturnType<typeof assertApiProjectPermit>>;
const builderAuth = {
+ type: "token",
token: createToken({ relation: "builders" }),
permits: ["view", "edit", "build", "api"],
} satisfies Awaited<ReturnType<typeof assertApiProjectPermit>>;
@@ -660,7 +826,9 @@ describe("api router permits", () => {
projectId: "project-1",
clientVersion: 3,
}),
- expect.anything()
+ expect.objectContaining({
+ authorization: expect.objectContaining({ type: "token" }),
+ })
);
});
diff --git a/apps/builder/app/services/api-router.server.ts b/apps/builder/app/services/api-router.server.ts
index 3eb9c703a3..e8b2db8e26 100644
--- a/apps/builder/app/services/api-router.server.ts
+++ b/apps/builder/app/services/api-router.server.ts
@@ -28,9 +28,17 @@ import {
paginatedOutputInputSchema,
} from "@webstudio-is/project-build/runtime";
import {
+ getAssetResourceQueryError,
+ assetQueryRequest,
+ getAssetQueryWhereMetrics,
+ validateAssetQueryAgainstCatalog,
+} from "@webstudio-is/content-engine";
+import {
+ loadBuilderAssetFieldCatalog,
loadAssetDataByProject,
loadAssetFoldersByProject,
-} from "@webstudio-is/asset-uploader/index.server";
+ previewAssetResourceQuery,
+} from "@webstudio-is/asset-uploader/server";
import { buildPatchTransaction } from "@webstudio-is/protocol/schema";
import {
publicApiContractVersion,
@@ -72,6 +80,8 @@ import {
executeApiRuntimeMutation,
executeApiRuntimeOperation,
} from "./api-runtime.server";
+import { createAssetClient } from "../shared/asset-client";
+import { getContentDatabaseMaxBytes } from "./content-database.server";
const assertApiPublishDomains = ({
auth,
@@ -82,6 +92,9 @@ const assertApiPublishDomains = ({
domains: string[];
project: { domain: string };
}) => {
+ if (auth.type === "user") {
+ return;
+ }
const { token } = auth;
if (token.canPublish === true) {
return;
@@ -100,6 +113,24 @@ const assertApiPublishDomains = ({
const projectIdInput = z.object({ projectId: z.string() });
+const assetQueryInput = projectIdInput.extend(assetQueryRequest.shape);
+const assetQueryValidationInput = projectIdInput.extend({
+ query: assetQueryRequest.shape.query,
+});
+const throwAssetQueryApiError = (error: unknown): never => {
+ const queryError = getAssetResourceQueryError(error);
+ if (queryError !== undefined) {
+ return throwApiError(
+ queryError.status === 409 ? "CONFLICT" : "BAD_REQUEST",
+ queryError.message,
+ {
+ webstudioCode: queryError.code,
+ }
+ );
+ }
+ throw error;
+};
+
const paginatedProjectInput = projectIdInput.extend(
paginatedOutputInputSchema.shape
);
@@ -691,6 +722,76 @@ export const apiRouter = router({
...runtimeOperationRouters,
+ assetQueries: router({
+ validate: projectQuery(
+ assetQueryValidationInput,
+ "view",
+ async ({ ctx, input }) => {
+ try {
+ const catalog = await loadBuilderAssetFieldCatalog({
+ projectId: input.projectId,
+ context: ctx,
+ assetClient: createAssetClient(),
+ });
+ const validated = validateAssetQueryAgainstCatalog({
+ query: input.query,
+ catalog,
+ });
+ return {
+ valid: true as const,
+ referencedFieldPaths: validated.referencedFieldPaths,
+ filterCount: getAssetQueryWhereMetrics(validated.query.where)
+ .filters,
+ sortCount: validated.query.sort.length,
+ warnings: validated.warnings,
+ };
+ } catch (error) {
+ return throwAssetQueryApiError(error);
+ }
+ },
+ {
+ command: "validate-asset-query",
+ client: "validateAssetQuery",
+ }
+ ),
+ preview: projectQuery(
+ assetQueryInput,
+ "view",
+ async ({ ctx, input }) => {
+ try {
+ const { projectId, ...request } = input;
+ return await previewAssetResourceQuery({
+ projectId,
+ request,
+ context: ctx,
+ assetClient: createAssetClient(),
+ contentDatabaseMaxBytes: getContentDatabaseMaxBytes(),
+ });
+ } catch (error) {
+ return throwAssetQueryApiError(error);
+ }
+ },
+ {
+ command: "preview-asset-query",
+ client: "previewAssetQuery",
+ }
+ ),
+ fieldCatalog: projectQuery(
+ projectIdInput,
+ "view",
+ async ({ ctx, input }) =>
+ await loadBuilderAssetFieldCatalog({
+ projectId: input.projectId,
+ context: ctx,
+ assetClient: createAssetClient(),
+ }),
+ {
+ command: "get-asset-field-catalog",
+ client: "getAssetFieldCatalog",
+ }
+ ),
+ }),
+
publish: router({
list: projectQuery(
paginatedProjectInput,
diff --git a/apps/builder/app/services/asset-rest-content.server.test.ts b/apps/builder/app/services/asset-rest-content.server.test.ts
new file mode 100644
index 0000000000..cd28a87f6d
--- /dev/null
+++ b/apps/builder/app/services/asset-rest-content.server.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, test, vi } from "vitest";
+import type { Asset } from "@webstudio-is/sdk";
+import {
+ createAssetContentLoader,
+ parseRequestRange,
+} from "./asset-rest-route-handlers.server";
+
+const asset: Asset = {
+ id: "asset-1",
+ projectId: "project-1",
+ name: "post.md",
+ type: "file",
+ format: "md",
+ size: 10,
+ description: null,
+ createdAt: "2026-07-25T00:00:00.000Z",
+ meta: {},
+};
+
+describe("Assets REST content download", () => {
+ test("parses one standard byte range", () => {
+ expect(parseRequestRange("bytes=2-5", 10)).toEqual({
+ offset: 2,
+ length: 4,
+ });
+ expect(() => parseRequestRange("bytes=0-1,4-5", 10)).toThrow(
+ "single valid byte range"
+ );
+ expect(() => parseRequestRange("items=0-1", 10)).toThrow(
+ "single valid byte range"
+ );
+ });
+
+ test("streams an authorized partial response", async () => {
+ const readContent = vi.fn(async () => ({
+ asset,
+ data: {
+ async *[Symbol.asyncIterator]() {
+ yield new TextEncoder().encode("post");
+ },
+ },
+ contentLength: 4,
+ }));
+ const dependencies = {
+ preventCrossOriginCookie: vi.fn(),
+ createRepository: vi.fn(async () => ({
+ get: vi.fn(async () => asset),
+ readContent,
+ })) as never,
+ };
+ const response = await createAssetContentLoader(dependencies)({
+ request: new Request(
+ "https://webstudio.is/rest/assets/asset-1/content?projectId=project-1",
+ { headers: { range: "bytes=2-5", "x-auth-token": "token" } }
+ ),
+ params: { assetId: "asset-1" },
+ } as never);
+
+ expect(response.status).toBe(206);
+ expect(response.headers.get("content-range")).toBe("bytes 2-5/10");
+ expect(response.headers.get("content-length")).toBe("4");
+ expect(await response.text()).toBe("post");
+ expect(readContent).toHaveBeenCalledWith({
+ assetId: "asset-1",
+ range: { offset: 2, length: 4 },
+ asset,
+ });
+ });
+});
diff --git a/apps/builder/app/services/asset-rest-index.server.test.ts b/apps/builder/app/services/asset-rest-index.server.test.ts
new file mode 100644
index 0000000000..068944bf90
--- /dev/null
+++ b/apps/builder/app/services/asset-rest-index.server.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, test, vi } from "vitest";
+import { createAssetIndexRefreshAction } from "./asset-rest-route-handlers.server";
+
+const call = (
+ action: ReturnType<typeof createAssetIndexRefreshAction>,
+ headers?: HeadersInit
+) =>
+ action({
+ request: new Request(
+ "https://webstudio.is/rest/assets/index/refresh?projectId=project-1",
+ { method: "POST", headers }
+ ),
+ params: {},
+ } as never);
+
+const createDependencies = (issues: Array<Record<string, string>> = []) => ({
+ preventCrossOriginCookie: vi.fn(),
+ ensureApiCsrf: vi.fn(),
+ createRepository: vi.fn(async () => ({
+ synchronize: vi.fn(async () => ({
+ scanned: 1,
+ indexed: issues.length === 0 ? 1 : 0,
+ metadataUpdated: 0,
+ unchanged: 0,
+ removed: 0,
+ skipped: issues.length,
+ inconsistent: 0,
+ issues,
+ })),
+ })) as never,
+});
+
+describe("Assets index repair", () => {
+ test("repairs metadata and protects cookie mutations with CSRF", async () => {
+ const dependencies = createDependencies();
+ const response = await call(createAssetIndexRefreshAction(dependencies));
+
+ expect(response.status).toBe(200);
+ expect(dependencies.ensureApiCsrf).toHaveBeenCalledOnce();
+ expect(dependencies.createRepository).toHaveBeenCalledWith(
+ expect.any(Request),
+ "edit"
+ );
+ expect(await response.json()).toMatchObject({ indexed: 1 });
+ });
+
+ test("reports incomplete repair and accepts project-token authentication", async () => {
+ const dependencies = createDependencies([
+ {
+ assetId: "asset-1",
+ storageName: "post.md",
+ revision: "revision-1",
+ message: "Object is unavailable",
+ },
+ ]);
+ const response = await call(createAssetIndexRefreshAction(dependencies), {
+ "x-auth-token": "share-token",
+ });
+
+ expect(response.status).toBe(503);
+ expect(dependencies.ensureApiCsrf).toHaveBeenCalledOnce();
+ expect(await response.json()).toMatchObject({
+ issues: [expect.objectContaining({ assetId: "asset-1" })],
+ });
+ });
+});
diff --git a/apps/builder/app/services/asset-rest-item.server.test.ts b/apps/builder/app/services/asset-rest-item.server.test.ts
new file mode 100644
index 0000000000..ed4de295a2
--- /dev/null
+++ b/apps/builder/app/services/asset-rest-item.server.test.ts
@@ -0,0 +1,220 @@
+import { describe, expect, test, vi } from "vitest";
+import type { Asset } from "@webstudio-is/sdk";
+import { assetResourceLimits } from "@webstudio-is/sdk/asset-resource-limits";
+import { AuthorizationError } from "@webstudio-is/trpc-interface/index.server";
+import { AssetRepositoryNotFoundError } from "@webstudio-is/asset-uploader/server";
+import { createAssetAction } from "./asset-rest-route-handlers.server";
+
+const asset: Asset = {
+ id: "asset-1",
+ projectId: "project-1",
+ name: "post.md",
+ filename: "Post",
+ description: null,
+ type: "file",
+ format: "md",
+ size: 10,
+ createdAt: "2026-07-25T00:00:00.000Z",
+ meta: {},
+};
+
+const createDependencies = () => {
+ const updateMetadata = vi.fn().mockResolvedValue(asset);
+ const deleteAsset = vi.fn().mockResolvedValue(undefined);
+ const createRepository = vi.fn(async () => ({
+ updateMetadata,
+ delete: deleteAsset,
+ }));
+ return {
+ updateMetadata,
+ deleteAsset,
+ createRepository,
+ dependencies: {
+ preventCrossOriginCookie: vi.fn(),
+ ensureApiCsrf: vi.fn(),
+ createRepository: createRepository as never,
+ } satisfies Parameters<typeof createAssetAction>[0],
+ };
+};
+
+const callAction = (
+ action: ReturnType<typeof createAssetAction>,
+ request: Request
+) => action({ request, params: { assetId: "asset-1" } } as never);
+
+describe("mutable Assets REST route", () => {
+ test("rejects unsupported methods before authorization", async () => {
+ const { dependencies, createRepository } = createDependencies();
+ const response = await callAction(
+ createAssetAction(dependencies),
+ new Request(
+ "https://webstudio.is/rest/assets/asset-1?projectId=project-1",
+ { method: "POST" }
+ )
+ );
+
+ expect(response.status).toBe(405);
+ expect(response.headers.get("allow")).toBe("PATCH, DELETE");
+ expect(dependencies.ensureApiCsrf).not.toHaveBeenCalled();
+ expect(createRepository).not.toHaveBeenCalled();
+ });
+
+ test("updates metadata through the repository with browser CSRF protection", async () => {
+ const { dependencies, updateMetadata } = createDependencies();
+ const action = createAssetAction(dependencies);
+ const response = await callAction(
+ action,
+ new Request(
+ "https://webstudio.is/rest/assets/asset-1?projectId=project-1",
+ {
+ method: "PATCH",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ filename: "Post", folderId: null }),
+ }
+ )
+ );
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ asset });
+ expect(dependencies.ensureApiCsrf).toHaveBeenCalledOnce();
+ expect(updateMetadata).toHaveBeenCalledWith("asset-1", {
+ filename: "Post",
+ folderId: null,
+ });
+ });
+
+ test("returns the same metadata contract for project-token authentication", async () => {
+ const { dependencies, createRepository, updateMetadata } =
+ createDependencies();
+ const response = await callAction(
+ createAssetAction(dependencies),
+ new Request(
+ "https://webstudio.is/rest/assets/asset-1?projectId=project-1",
+ {
+ method: "PATCH",
+ headers: {
+ "content-type": "application/json",
+ "x-auth-token": "token",
+ },
+ body: JSON.stringify({ filename: "Post", folderId: null }),
+ }
+ )
+ );
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ asset });
+ expect(dependencies.ensureApiCsrf).toHaveBeenCalledOnce();
+ expect(createRepository).toHaveBeenCalledWith(expect.any(Request), "edit");
+ expect(updateMetadata).toHaveBeenCalledWith("asset-1", {
+ filename: "Post",
+ folderId: null,
+ });
+ });
+
+ test("deletes through the repository and accepts token-authenticated requests", async () => {
+ const { dependencies, deleteAsset } = createDependencies();
+ const action = createAssetAction(dependencies);
+ const response = await callAction(
+ action,
+ new Request(
+ "https://webstudio.is/rest/assets/asset-1?projectId=project-1",
+ {
+ method: "DELETE",
+ headers: { "x-auth-token": "token" },
+ }
+ )
+ );
+
+ expect(response.status).toBe(204);
+ expect(dependencies.ensureApiCsrf).toHaveBeenCalledOnce();
+ expect(deleteAsset).toHaveBeenCalledWith(["asset-1"]);
+ });
+
+ test("returns a forbidden response for repository authorization failures", async () => {
+ const { dependencies, createRepository } = createDependencies();
+ createRepository.mockRejectedValue(
+ new AuthorizationError("You don't have access") as never
+ );
+ const report = vi.spyOn(console, "error").mockImplementation(() => {});
+ const response = await callAction(
+ createAssetAction(dependencies),
+ new Request(
+ "https://webstudio.is/rest/assets/asset-1?projectId=project-1",
+ {
+ method: "PATCH",
+ headers: {
+ "content-type": "application/json",
+ "x-auth-token": "token",
+ },
+ body: JSON.stringify({ description: "Updated" }),
+ }
+ )
+ );
+
+ expect(response.status).toBe(403);
+ expect(await response.json()).toEqual({
+ errors: "You don't have access",
+ });
+ report.mockRestore();
+ });
+
+ test.each([
+ ["PATCH", "updateMetadata"],
+ ["DELETE", "deleteAsset"],
+ ] as const)(
+ "returns not found when %s targets a missing asset",
+ async (method, operation) => {
+ const dependencies = createDependencies();
+ dependencies[operation].mockRejectedValue(
+ new AssetRepositoryNotFoundError("Asset not found")
+ );
+ const requestInit: RequestInit = {
+ method,
+ headers: { "x-auth-token": "token" },
+ };
+ if (method === "PATCH") {
+ requestInit.headers = {
+ ...requestInit.headers,
+ "content-type": "application/json",
+ };
+ requestInit.body = JSON.stringify({ description: "Missing" });
+ }
+
+ const response = await callAction(
+ createAssetAction(dependencies.dependencies),
+ new Request(
+ "https://webstudio.is/rest/assets/missing?projectId=project-1",
+ requestInit
+ )
+ );
+
+ expect(response.status).toBe(404);
+ expect(await response.json()).toEqual({ errors: "Asset not found" });
+ }
+ );
+
+ test("rejects oversized JSON before calling the repository", async () => {
+ const { dependencies, updateMetadata } = createDependencies();
+ const response = await callAction(
+ createAssetAction(dependencies),
+ new Request(
+ "https://webstudio.is/rest/assets/asset-1?projectId=project-1",
+ {
+ method: "PATCH",
+ headers: {
+ "content-type": "application/json",
+ "x-auth-token": "token",
+ },
+ body: JSON.stringify({
+ description: "x".repeat(
+ assetResourceLimits.restMutationRequestBytes
+ ),
+ }),
+ }
+ )
+ );
+
+ expect(response.status).toBe(413);
+ expect(updateMetadata).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/builder/app/services/asset-rest-route-handlers.server.ts b/apps/builder/app/services/asset-rest-route-handlers.server.ts
new file mode 100644
index 0000000000..8b0f98031d
--- /dev/null
+++ b/apps/builder/app/services/asset-rest-route-handlers.server.ts
@@ -0,0 +1,175 @@
+import {
+ json,
+ type ActionFunctionArgs,
+ type LoaderFunctionArgs,
+} from "@remix-run/server-runtime";
+import { Readable } from "node:stream";
+import parseRange from "range-parser";
+import { getAssetMime } from "@webstudio-is/sdk";
+import {
+ assetMetadataUpdate,
+ assetResourceApiOperations,
+} from "@webstudio-is/protocol/asset-resource-api";
+import { privateNoStoreResponseHeaders } from "./cache-control.server";
+import { ensureApiCsrf } from "./api-auth.server";
+import {
+ AssetRestRangeError,
+ assetRestErrorResponse,
+ assetRestMethodNotAllowed,
+ createAssetRestRepository,
+ parseAssetRestIdentifier,
+ readAssetRestJson,
+} from "./asset-rest.server";
+import { preventCrossOriginCookie } from "./no-cross-origin-cookie";
+
+export const parseRequestRange = (value: string | null, size: number) => {
+ if (value === null) {
+ return;
+ }
+ const parsed = parseRange(size, value, { combine: true });
+ if (
+ typeof parsed === "number" ||
+ parsed.type !== "bytes" ||
+ parsed.length !== 1
+ ) {
+ throw new AssetRestRangeError("A single valid byte range is required");
+ }
+ const [{ start, end }] = parsed;
+ return { offset: start, length: end - start + 1 };
+};
+
+type AssetContentLoaderDependencies = {
+ preventCrossOriginCookie: typeof preventCrossOriginCookie;
+ createRepository: typeof createAssetRestRepository;
+};
+
+const defaultAssetContentLoaderDependencies: AssetContentLoaderDependencies = {
+ preventCrossOriginCookie,
+ createRepository: createAssetRestRepository,
+};
+
+export const createAssetContentLoader =
+ (
+ dependencies: AssetContentLoaderDependencies = defaultAssetContentLoaderDependencies
+ ) =>
+ async ({ request, params }: LoaderFunctionArgs) => {
+ dependencies.preventCrossOriginCookie(request);
+ if (
+ request.method.toLowerCase() !==
+ assetResourceApiOperations.downloadAssetContent.method
+ ) {
+ return assetRestMethodNotAllowed([
+ assetResourceApiOperations.downloadAssetContent,
+ ]);
+ }
+ try {
+ const assetId = parseAssetRestIdentifier(params.assetId);
+ const repository = await dependencies.createRepository(request, "view");
+ const asset = await repository.get(assetId);
+ const range = parseRequestRange(request.headers.get("range"), asset.size);
+ const content = await repository.readContent({ assetId, range, asset });
+ const headers = new Headers(privateNoStoreResponseHeaders);
+ headers.set(
+ "content-type",
+ getAssetMime(asset) ?? "application/octet-stream"
+ );
+ headers.set("accept-ranges", "bytes");
+ headers.set(
+ "content-length",
+ String(content.contentLength ?? range?.length ?? asset.size)
+ );
+ if (range !== undefined) {
+ headers.set(
+ "content-range",
+ `bytes ${range.offset}-${range.offset + range.length - 1}/${asset.size}`
+ );
+ }
+ return new Response(
+ Readable.toWeb(Readable.from(content.data)) as ReadableStream,
+ { status: range === undefined ? 200 : 206, headers }
+ );
+ } catch (error) {
+ return assetRestErrorResponse(error);
+ }
+ };
+
+type AssetActionDependencies = {
+ preventCrossOriginCookie: typeof preventCrossOriginCookie;
+ ensureApiCsrf: typeof ensureApiCsrf;
+ createRepository: typeof createAssetRestRepository;
+};
+
+const defaultAssetActionDependencies: AssetActionDependencies = {
+ preventCrossOriginCookie,
+ ensureApiCsrf,
+ createRepository: createAssetRestRepository,
+};
+
+export const createAssetAction =
+ (dependencies: AssetActionDependencies = defaultAssetActionDependencies) =>
+ async ({ request, params }: ActionFunctionArgs) => {
+ dependencies.preventCrossOriginCookie(request);
+ const method = request.method.toLowerCase();
+ if (
+ method !== assetResourceApiOperations.updateAsset.method &&
+ method !== assetResourceApiOperations.deleteAsset.method
+ ) {
+ return assetRestMethodNotAllowed([
+ assetResourceApiOperations.updateAsset,
+ assetResourceApiOperations.deleteAsset,
+ ]);
+ }
+ await dependencies.ensureApiCsrf(request);
+
+ try {
+ const assetId = parseAssetRestIdentifier(params.assetId);
+ const repository = await dependencies.createRepository(request, "edit");
+
+ if (method === assetResourceApiOperations.updateAsset.method) {
+ const asset = await repository.updateMetadata(
+ assetId,
+ assetMetadataUpdate.parse(await readAssetRestJson(request))
+ );
+ return json({ asset }, { headers: privateNoStoreResponseHeaders });
+ }
+ await repository.delete([assetId]);
+ return new Response(null, {
+ status: 204,
+ headers: privateNoStoreResponseHeaders,
+ });
+ } catch (error) {
+ return assetRestErrorResponse(error);
+ }
+ };
+
+const defaultAssetIndexRefreshDependencies = {
+ preventCrossOriginCookie,
+ ensureApiCsrf,
+ createRepository: createAssetRestRepository,
+};
+
+export const createAssetIndexRefreshAction =
+ (dependencies = defaultAssetIndexRefreshDependencies) =>
+ async ({ request }: ActionFunctionArgs) => {
+ dependencies.preventCrossOriginCookie(request);
+ if (
+ request.method.toLowerCase() !==
+ assetResourceApiOperations.refreshAssetIndex.method
+ ) {
+ return assetRestMethodNotAllowed([
+ assetResourceApiOperations.refreshAssetIndex,
+ ]);
+ }
+ await dependencies.ensureApiCsrf(request);
+ try {
+ const result = await (
+ await dependencies.createRepository(request, "edit")
+ ).synchronize();
+ return json(result, {
+ status: result.issues.length === 0 ? 200 : 503,
+ headers: privateNoStoreResponseHeaders,
+ });
+ } catch (error) {
+ return assetRestErrorResponse(error);
+ }
+ };
diff --git a/apps/builder/app/services/asset-rest.server.test.ts b/apps/builder/app/services/asset-rest.server.test.ts
new file mode 100644
index 0000000000..3e25acb09e
--- /dev/null
+++ b/apps/builder/app/services/asset-rest.server.test.ts
@@ -0,0 +1,203 @@
+import { describe, expect, test, vi } from "vitest";
+import { TRPCError } from "@trpc/server";
+import {
+ AssetRepositoryConflictError,
+ AssetRepositoryNotFoundError,
+} from "@webstudio-is/asset-uploader/server";
+import { assetFolders } from "@webstudio-is/sdk";
+import { assetResourceLimits } from "@webstudio-is/sdk/asset-resource-limits";
+import { assetResourceApiOperations } from "@webstudio-is/protocol/asset-resource-api";
+import { AuthorizationError } from "@webstudio-is/trpc-interface/index.server";
+import {
+ AssetRestRangeError,
+ AssetRestPayloadTooLargeError,
+ AssetRestRequestError,
+ assetRestErrorResponse,
+ assetRestMethodNotAllowed,
+ parseAssetRestDescription,
+ parseAssetRestMetadataHeader,
+ readAssetRestFormData,
+ readAssetRestJson,
+ requireAssetRestBody,
+} from "./asset-rest.server";
+import { AssetUploadSizeLimitError } from "@webstudio-is/asset-uploader/server";
+
+describe("Assets REST responses", () => {
+ test.each([
+ [new AssetRestRequestError("bad request"), 400],
+ [new AuthorizationError("forbidden"), 403],
+ [new TRPCError({ code: "UNAUTHORIZED" }), 401],
+ [new TRPCError({ code: "FORBIDDEN" }), 403],
+ [new AssetRepositoryNotFoundError("missing"), 404],
+ [new AssetRepositoryConflictError("conflict"), 409],
+ [new AssetRestRangeError("bad range"), 416],
+ [new AssetRestPayloadTooLargeError("too large"), 413],
+ [new AssetUploadSizeLimitError("post.md", 10), 413],
+ ])("maps domain errors to HTTP status", async (error, status) => {
+ const response = assetRestErrorResponse(error);
+ expect(response.status).toBe(status);
+ expect(await response.json()).toEqual({ errors: error.message });
+ });
+
+ test("maps duplicate sibling folders to conflict", () => {
+ const error = assetFolders.safeParse(
+ new Map([
+ [
+ "one",
+ {
+ id: "one",
+ projectId: "project-1",
+ name: "Blog",
+ createdAt: "2026-07-25T00:00:00.000Z",
+ },
+ ],
+ [
+ "two",
+ {
+ id: "two",
+ projectId: "project-1",
+ name: "Blog",
+ createdAt: "2026-07-25T00:00:00.000Z",
+ },
+ ],
+ ])
+ ).error;
+ expect(error).toBeDefined();
+ expect(assetRestErrorResponse(error).status).toBe(409);
+ });
+
+ test("does not swallow CSRF responses and advertises allowed methods", () => {
+ const csrf = new Response("Forbidden", { status: 403 });
+ expect(assetRestErrorResponse(csrf)).toBe(csrf);
+ const response = assetRestMethodNotAllowed([
+ assetResourceApiOperations.getAsset,
+ assetResourceApiOperations.updateAsset,
+ ]);
+ expect(response.status).toBe(405);
+ expect(response.headers.get("allow")).toBe("GET, PATCH");
+ });
+
+ test("does not expose unexpected internal errors", async () => {
+ const report = vi.spyOn(console, "error").mockImplementation(() => {});
+ const response = assetRestErrorResponse(new Error("database password"));
+ expect(response.status).toBe(500);
+ expect(await response.json()).toEqual({
+ errors: "Internal Assets API error",
+ });
+ report.mockRestore();
+ });
+
+ test("bounds mutation bodies before parsing JSON", async () => {
+ await expect(
+ readAssetRestJson(
+ new Request("https://example.com/rest/assets", {
+ method: "PATCH",
+ headers: {
+ "content-type": "application/json",
+ "content-length": String(
+ assetResourceLimits.restMutationRequestBytes + 1
+ ),
+ },
+ body: "{}",
+ })
+ )
+ ).rejects.toBeInstanceOf(AssetRestPayloadTooLargeError);
+
+ await expect(
+ readAssetRestJson(
+ new Request("https://example.com/rest/assets", {
+ method: "PATCH",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ description: "x".repeat(
+ assetResourceLimits.restMutationRequestBytes
+ ),
+ }),
+ })
+ )
+ ).rejects.toBeInstanceOf(AssetRestPayloadTooLargeError);
+ });
+
+ test("rejects malformed UTF-8 in JSON bodies", async () => {
+ const prefix = new TextEncoder().encode('{"description":"');
+ const suffix = new TextEncoder().encode('"}');
+ const body = new Uint8Array(prefix.byteLength + 1 + suffix.byteLength);
+ body.set(prefix);
+ body[prefix.byteLength] = 0xff;
+ body.set(suffix, prefix.byteLength + 1);
+
+ await expect(
+ readAssetRestJson(
+ new Request("https://example.com/rest/assets", {
+ method: "PATCH",
+ body,
+ })
+ )
+ ).rejects.toBeInstanceOf(AssetRestRequestError);
+ });
+
+ test("distinguishes a missing content body from an unsupported method", () => {
+ expect(() =>
+ requireAssetRestBody(
+ new Request("https://example.com/rest/assets/asset/content", {
+ method: "POST",
+ })
+ )
+ ).toThrow(AssetRestRequestError);
+ expect(
+ requireAssetRestBody(
+ new Request("https://example.com/rest/assets/asset/content", {
+ method: "POST",
+ body: "content",
+ })
+ )
+ ).toBeInstanceOf(ReadableStream);
+ });
+
+ test("bounds upload metadata carried in headers", () => {
+ expect(() =>
+ parseAssetRestDescription(
+ "x".repeat(assetResourceLimits.assetDescriptionCharacters + 1)
+ )
+ ).toThrow(AssetRestRequestError);
+ expect(() =>
+ parseAssetRestMetadataHeader(
+ "x".repeat(assetResourceLimits.restMutationRequestBytes + 1)
+ )
+ ).toThrow(AssetRestPayloadTooLargeError);
+ expect(() => parseAssetRestMetadataHeader("{")).toThrow(
+ AssetRestRequestError
+ );
+ });
+
+ test("parses bounded multipart forms and rejects oversized forms", async () => {
+ const form = new FormData();
+ form.set("projectId", "project-1");
+ form.set("filename", "post.md");
+ const parsed = await readAssetRestFormData(
+ new Request("https://example.com/rest/assets/uploads", {
+ method: "POST",
+ body: form,
+ })
+ );
+ expect(Object.fromEntries(parsed)).toEqual({
+ projectId: "project-1",
+ filename: "post.md",
+ });
+
+ await expect(
+ readAssetRestFormData(
+ new Request("https://example.com/rest/assets/uploads", {
+ method: "POST",
+ headers: {
+ "content-type": "multipart/form-data; boundary=test",
+ "content-length": String(
+ assetResourceLimits.restMutationRequestBytes + 1
+ ),
+ },
+ body: "--test--",
+ })
+ )
+ ).rejects.toBeInstanceOf(AssetRestPayloadTooLargeError);
+ });
+});
diff --git a/apps/builder/app/services/asset-rest.server.ts b/apps/builder/app/services/asset-rest.server.ts
new file mode 100644
index 0000000000..c7c4b99d8d
--- /dev/null
+++ b/apps/builder/app/services/asset-rest.server.ts
@@ -0,0 +1,245 @@
+import { json } from "@remix-run/server-runtime";
+import {
+ readBoundedRequestBytes,
+ RequestByteLimitError,
+} from "@webstudio-is/content-engine";
+import { decodeUtf8 } from "@webstudio-is/content-engine/compiler";
+import {
+ AssetRepositoryConflictError,
+ AssetRepositoryNotFoundError,
+ AssetRevisionConflictError,
+ AssetUploadSizeLimitError,
+ PostgresAssetRepository,
+} from "@webstudio-is/asset-uploader/server";
+import type { ProjectPermit } from "@webstudio-is/trpc-interface/index.server";
+import { assetFolderIssue } from "@webstudio-is/sdk";
+import { assetResourceLimits } from "@webstudio-is/sdk/asset-resource-limits";
+import { parseBuilderUrl } from "@webstudio-is/protocol";
+import { ZodError } from "zod";
+import { createAssetClient } from "~/shared/asset-client";
+import { parseError } from "~/shared/error/error-parse";
+import { privateNoStoreResponseHeaders } from "./cache-control.server";
+import {
+ authorizeApiProject,
+ getApiAuthorizationFailure,
+} from "./api-auth.server";
+
+export class AssetRestRequestError extends Error {}
+export class AssetRestRangeError extends Error {}
+export class AssetRestPayloadTooLargeError extends Error {}
+
+export const requireAssetRestBody = (request: Request) => {
+ if (request.body === null) {
+ throw new AssetRestRequestError("Asset content is required");
+ }
+ return request.body;
+};
+
+const readAssetRestBody = async (request: Request) => {
+ try {
+ return await readBoundedRequestBytes(
+ request,
+ assetResourceLimits.restMutationRequestBytes
+ );
+ } catch (error) {
+ if (error instanceof RequestByteLimitError) {
+ throw new AssetRestPayloadTooLargeError(
+ "Assets API request exceeds the byte limit",
+ { cause: error }
+ );
+ }
+ throw error;
+ }
+};
+
+export const readAssetRestJson = async (request: Request) => {
+ const bytes = await readAssetRestBody(request);
+ try {
+ return JSON.parse(decodeUtf8(bytes)) as unknown;
+ } catch (error) {
+ throw new AssetRestRequestError("Assets API request JSON is invalid", {
+ cause: error,
+ });
+ }
+};
+
+export const readAssetRestFormData = async (request: Request) => {
+ const bytes = await readAssetRestBody(request);
+ try {
+ return await new Request(request.url, {
+ method: request.method,
+ headers: request.headers,
+ body: bytes,
+ }).formData();
+ } catch (error) {
+ throw new AssetRestRequestError("Assets API form data is invalid", {
+ cause: error,
+ });
+ }
+};
+
+const parseRequiredAssetString = ({
+ value,
+ maximumCharacters,
+ name,
+}: {
+ value: string | undefined | null;
+ maximumCharacters: number;
+ name: string;
+}) => {
+ if (
+ value === undefined ||
+ value === null ||
+ value.length === 0 ||
+ value.length > maximumCharacters
+ ) {
+ throw new AssetRestRequestError(`Assets API ${name} is invalid`);
+ }
+ return value;
+};
+
+export const parseAssetRestIdentifier = (value: string | undefined | null) =>
+ parseRequiredAssetString({
+ value,
+ maximumCharacters: assetResourceLimits.assetIdentifierCharacters,
+ name: "identifier",
+ });
+
+export const parseAssetRestFilename = (value: string | undefined | null) =>
+ parseRequiredAssetString({
+ value,
+ maximumCharacters: assetResourceLimits.assetFilenameCharacters,
+ name: "filename",
+ });
+
+export const parseAssetRestDescription = (value: string | undefined | null) => {
+ if (
+ value !== undefined &&
+ value !== null &&
+ value.length > assetResourceLimits.assetDescriptionCharacters
+ ) {
+ throw new AssetRestRequestError("Assets API description is invalid");
+ }
+ return value ?? undefined;
+};
+
+export const parseAssetRestMetadataHeader = (
+ value: string | undefined | null
+) => {
+ if (value === undefined || value === null) {
+ return;
+ }
+ if (
+ new TextEncoder().encode(value).byteLength >
+ assetResourceLimits.restMutationRequestBytes
+ ) {
+ throw new AssetRestPayloadTooLargeError(
+ "Assets API metadata header exceeds the byte limit"
+ );
+ }
+ try {
+ return JSON.parse(value) as unknown;
+ } catch (error) {
+ throw new AssetRestRequestError("Assets API metadata header is invalid", {
+ cause: error,
+ });
+ }
+};
+
+export const getAssetRestProjectId = (request: Request) => {
+ const projectId =
+ parseBuilderUrl(request.url).projectId ??
+ new URL(request.url).searchParams.get("projectId");
+ return parseAssetRestIdentifier(projectId);
+};
+
+export const createAssetRestRepositoryForProject = async (
+ request: Request,
+ projectId: string,
+ permit: ProjectPermit = "view"
+) =>
+ new PostgresAssetRepository({
+ projectId,
+ context: await authorizeApiProject(request, projectId, permit),
+ assetStore: createAssetClient(),
+ });
+
+export const createAssetRestRepository = async (
+ request: Request,
+ permit: ProjectPermit = "view"
+) =>
+ createAssetRestRepositoryForProject(
+ request,
+ getAssetRestProjectId(request),
+ permit
+ );
+
+const getAssetRestErrorStatus = (error: unknown) => {
+ const authorizationFailure = getApiAuthorizationFailure(error);
+ if (authorizationFailure !== undefined) {
+ return authorizationFailure.status;
+ }
+ if (error instanceof AssetRepositoryNotFoundError) {
+ return 404;
+ }
+ if (
+ error instanceof AssetRepositoryConflictError ||
+ error instanceof AssetRevisionConflictError
+ ) {
+ return 409;
+ }
+ if (
+ error instanceof ZodError &&
+ error.issues.some(
+ ({ message }) => message === assetFolderIssue.duplicateName
+ )
+ ) {
+ return 409;
+ }
+ if (error instanceof AssetRestRangeError) {
+ return 416;
+ }
+ if (
+ error instanceof AssetRestPayloadTooLargeError ||
+ error instanceof AssetUploadSizeLimitError
+ ) {
+ return 413;
+ }
+ if (error instanceof AssetRestRequestError || error instanceof ZodError) {
+ return 400;
+ }
+ return 500;
+};
+
+export const assetRestErrorResponse = (error: unknown) => {
+ if (error instanceof Response) {
+ return error;
+ }
+ const status = getAssetRestErrorStatus(error);
+ if (status === 500) {
+ console.error(error);
+ }
+ return json(
+ {
+ errors:
+ status === 500
+ ? "Internal Assets API error"
+ : parseError(error).message,
+ },
+ { status, headers: privateNoStoreResponseHeaders }
+ );
+};
+
+export const assetRestMethodNotAllowed = (
+ allowed: readonly { method: string }[]
+) =>
+ json(
+ { errors: "Method not allowed" },
+ {
+ status: 405,
+ headers: {
+ ...privateNoStoreResponseHeaders,
+ Allow: allowed.map(({ method }) => method.toUpperCase()).join(", "),
+ },
+ }
+ );
diff --git a/apps/builder/app/services/asset-upload.server.test.ts b/apps/builder/app/services/asset-upload.server.test.ts
index 16e6b05a05..162c4b7e5a 100644
--- a/apps/builder/app/services/asset-upload.server.test.ts
+++ b/apps/builder/app/services/asset-upload.server.test.ts
@@ -9,10 +9,13 @@ afterEach(() => {
});
test("keeps raw browser upload request bodies unchanged", async () => {
- const request = new Request("https://webstudio.is/rest/assets/image.png", {
- method: "POST",
- body: "raw file",
- });
+ const request = new Request(
+ "https://webstudio.is/rest/assets/uploads/image.png",
+ {
+ method: "POST",
+ body: "raw file",
+ }
+ );
await expect(
new Response(
@@ -22,11 +25,14 @@ test("keeps raw browser upload request bodies unchanged", async () => {
});
test("keeps browser JSON file uploads as JSON file content", async () => {
- const request = new Request("https://webstudio.is/rest/assets/data.json", {
- method: "POST",
- body: JSON.stringify({ value: 1 }),
- headers: { "Content-Type": "application/json" },
- });
+ const request = new Request(
+ "https://webstudio.is/rest/assets/uploads/data.json",
+ {
+ method: "POST",
+ body: JSON.stringify({ value: 1 }),
+ headers: { "Content-Type": "application/json" },
+ }
+ );
await expect(
new Response(await getBrowserUploadBody(request, "application/json")).text()
@@ -36,11 +42,14 @@ test("keeps browser JSON file uploads as JSON file content", async () => {
test("keeps browser URL image uploads by fetching the remote image body", async () => {
const fetch = vi.fn(async () => new Response("remote image"));
vi.stubGlobal("fetch", fetch);
- const request = new Request("https://webstudio.is/rest/assets/image.png", {
- method: "POST",
- body: JSON.stringify({ url: "https://example.com/image.png" }),
- headers: { "Content-Type": "application/json" },
- });
+ const request = new Request(
+ "https://webstudio.is/rest/assets/uploads/image.png",
+ {
+ method: "POST",
+ body: JSON.stringify({ url: "https://example.com/image.png" }),
+ headers: { "Content-Type": "application/json" },
+ }
+ );
await expect(
new Response(await getBrowserUploadBody(request, "application/json")).text()
@@ -56,11 +65,14 @@ test("reports browser URL image fetch failures", async () => {
"fetch",
vi.fn(async () => new Response("not found", { status: 404 }))
);
- const request = new Request("https://webstudio.is/rest/assets/image.png", {
- method: "POST",
- body: JSON.stringify({ url: "https://example.com/image.png" }),
- headers: { "Content-Type": "application/json" },
- });
+ const request = new Request(
+ "https://webstudio.is/rest/assets/uploads/image.png",
+ {
+ method: "POST",
+ body: JSON.stringify({ url: "https://example.com/image.png" }),
+ headers: { "Content-Type": "application/json" },
+ }
+ );
await expect(
getBrowserUploadBody(request, "application/json")
diff --git a/apps/builder/app/services/build-router.server.test.ts b/apps/builder/app/services/build-router.server.test.ts
index db5c4fd18e..45caa3a0e3 100644
--- a/apps/builder/app/services/build-router.server.test.ts
+++ b/apps/builder/app/services/build-router.server.test.ts
@@ -4,11 +4,17 @@ import { createPublishedProjectBundleFixture } from "@webstudio-is/protocol/fixt
import { buildRouter, __testing__ } from "./build-router.server";
import { authorizeProject } from "@webstudio-is/trpc-interface/index.server";
import { getApiCompatibilityPayload } from "@webstudio-is/trpc-interface/api-compatibility";
+import { createStructuredAssetQueryResourceBody } from "@webstudio-is/sdk";
+import {
+ createAssetIndex,
+ createCanonicalAssetFileEntry,
+} from "@webstudio-is/content-engine/compiler";
const {
assertCliBundleVersion,
createImportProjectBundleHandler,
prepareProjectBundleForClient,
+ getContentDatabasePublishDiagnostics,
} = __testing__;
afterEach(() => {
@@ -75,6 +81,91 @@ describe("build router project bundle compatibility", () => {
});
});
+describe("content database publish diagnostics", () => {
+ test("reports bounded database stats and conservatively affected resources", async () => {
+ const resourceId = "blog-posts";
+ const createEntry = (id: string, bytes: number) =>
+ createCanonicalAssetFileEntry({
+ projectId: "source-project",
+ document: {
+ _id: id,
+ _type: "asset.file",
+ name: `${id}.md`,
+ path: `blog/${id}.md`,
+ key: id,
+ extension: "md",
+ mimeType: "text/markdown",
+ size: bytes,
+ revision: `revision-${id}`,
+ contentRef: `files/${id}.md`,
+ properties: { value: "x".repeat(bytes) },
+ },
+ });
+ const assetIndex = await createAssetIndex({
+ projectId: "source-project",
+ entries: [createEntry("small", 100), createEntry("large", 10_000)],
+ maxBytes: 5_000,
+ });
+ const bundle = createPublishedProjectBundleFixture({
+ build: {
+ props: [
+ [
+ "posts-prop",
+ {
+ id: "posts-prop",
+ instanceId: "collection",
+ name: "data",
+ type: "resource",
+ value: resourceId,
+ },
+ ],
+ ],
+ resources: [
+ [
+ resourceId,
+ {
+ id: resourceId,
+ name: "Blog posts",
+ control: "system",
+ method: "post",
+ url: '"/$resources/assets"',
+ headers: [],
+ body: createStructuredAssetQueryResourceBody({
+ where: { all: [] },
+ sort: [],
+ limit: "pageSize",
+ offset: "0",
+ output: { mode: "base", includeMetadata: true },
+ content: { mode: "none" },
+ }),
+ },
+ ],
+ ],
+ },
+ assetIndex,
+ });
+
+ expect(getContentDatabasePublishDiagnostics(bundle)).toMatchObject({
+ stats: {
+ maxBytes: 5_000,
+ includedDocumentCount: 1,
+ omittedDocumentCount: 1,
+ truncated: true,
+ },
+ potentiallyAffectedResources: [{ id: resourceId, name: "Blog posts" }],
+ hasDynamicValues: true,
+ });
+ });
+
+ test("does nothing when the build has no content query", () => {
+ expect(
+ getContentDatabasePublishDiagnostics(
+ createPublishedProjectBundleFixture()
+ )
+ ).toBeUndefined();
+ });
+});
+
describe("build router jsx fragment conversion", () => {
test("converts Webstudio JSX through the shared runtime converter", async () => {
vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);
diff --git a/apps/builder/app/services/build-router.server.ts b/apps/builder/app/services/build-router.server.ts
index c533467373..e7ee007553 100644
--- a/apps/builder/app/services/build-router.server.ts
+++ b/apps/builder/app/services/build-router.server.ts
@@ -22,7 +22,12 @@ import type { BuildPatchTransaction } from "@webstudio-is/project/index.server";
import { loadDevBuildByProjectId } from "@webstudio-is/project-build/server";
import { parseWebstudioJsxFragment } from "@webstudio-is/project-build/transfer/server";
import { serializePages } from "@webstudio-is/project-migrations/pages";
-import { loadAssetDataByProject } from "@webstudio-is/asset-uploader/index.server";
+import { loadAssetDataByProject } from "@webstudio-is/asset-uploader/server";
+import {
+ createContentDatabase,
+ hasDynamicContentCompilationValues,
+} from "@webstudio-is/content-engine";
+import { createReachableAssetContentCompilationPlan } from "@webstudio-is/sdk";
import {
checkProjectBuildPermissionInput,
importProjectBundleInput,
@@ -33,6 +38,7 @@ import { removeAgentInstructionsFromProjectSettings } from "@webstudio-is/projec
import { hydrateRestorePointTransaction } from "@webstudio-is/project-build/project-session";
import {
loadProjectBundleByBuildId,
+ loadProjectBundleByProjectId,
loadPublishedProjectBundleByProjectId,
} from "~/shared/db";
import {
@@ -60,6 +66,36 @@ const buildBundleInput = z.object({
bundleVersion: z.union([z.string(), z.number()]).optional(),
});
+const getContentDatabasePublishDiagnostics = (
+ bundle: z.infer<typeof publishedProjectBundle>
+) => {
+ if (bundle.assetIndex === undefined) {
+ return;
+ }
+ const plan = createReachableAssetContentCompilationPlan({
+ props: bundle.build.props.map(([, prop]) => prop),
+ dataSources: bundle.build.dataSources.map(([, dataSource]) => dataSource),
+ resources: bundle.build.resources.map(([, resource]) => resource),
+ });
+ if (plan === undefined) {
+ return;
+ }
+ const resourceNameById = new Map(
+ bundle.build.resources.map(([, resource]) => [resource.id, resource.name])
+ );
+ const stats = createContentDatabase({
+ artifact: bundle.assetIndex,
+ }).getStats();
+ return {
+ stats,
+ potentiallyAffectedResources: plan.queries.map(({ id }) => ({
+ id,
+ name: resourceNameById.get(id) ?? id,
+ })),
+ hasDynamicValues: hasDynamicContentCompilationValues(plan),
+ };
+};
+
const assertCliBundleVersion = (
ctx: AppContext,
clientBundleVersion: string | number | undefined
@@ -284,6 +320,15 @@ export const buildRouter = router({
);
}),
+ contentDatabasePublishDiagnostics: procedure
+ .input(z.object({ projectId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ await assertProjectBuildPermit({ ctx, projectId: input.projectId });
+ return getContentDatabasePublishDiagnostics(
+ await loadProjectBundleByProjectId(input.projectId, ctx)
+ );
+ }),
+
checkProjectBuildPermission: procedure
.input(checkProjectBuildPermissionInput)
.query(async ({ ctx, input }) => {
@@ -412,4 +457,5 @@ export const __testing__ = {
createImportProjectBundleHandler,
assertCliBundleVersion,
prepareProjectBundleForClient,
+ getContentDatabasePublishDiagnostics,
};
diff --git a/apps/builder/app/services/builder-session.server.ts b/apps/builder/app/services/builder-session.server.ts
index adc21fda1c..ac245bd8ad 100644
--- a/apps/builder/app/services/builder-session.server.ts
+++ b/apps/builder/app/services/builder-session.server.ts
@@ -2,12 +2,14 @@ import { createCookieSessionStorage } from "@remix-run/node";
import env from "~/env/env.server";
import { getSessionCookieNameVersion } from "./auth.server.utils";
+export const builderSessionCookieName = `__Host-_session_builder_session_${getSessionCookieNameVersion()}`;
+
export const builderSessionStorage = createCookieSessionStorage({
cookie: {
// Using the __Host- prefix to prevent a malicious user from setting another person's session cookie
// on all subdomains of apps.webstudio.is, e.g., setting Domain=.apps.webstudio.is.
// For more information, see: https://developer.mozilla.org/en-US/docs/Web/Security/Practical_implementation_guides/Cookies#name
- name: `__Host-_session_builder_session_${getSessionCookieNameVersion()}`,
+ name: builderSessionCookieName,
sameSite: "lax",
path: "/",
httpOnly: true,
diff --git a/apps/builder/app/services/content-database.server.ts b/apps/builder/app/services/content-database.server.ts
new file mode 100644
index 0000000000..bed2abf24c
--- /dev/null
+++ b/apps/builder/app/services/content-database.server.ts
@@ -0,0 +1,4 @@
+import { parseContentDatabaseMaxBytes } from "@webstudio-is/content-engine";
+
+export const getContentDatabaseMaxBytes = () =>
+ parseContentDatabaseMaxBytes(process.env.CONTENT_DATABASE_MAX_BYTES);
diff --git a/apps/builder/app/services/project-import.server.test.ts b/apps/builder/app/services/project-import.server.test.ts
index 4e30e174a4..eb72ebdc9f 100644
--- a/apps/builder/app/services/project-import.server.test.ts
+++ b/apps/builder/app/services/project-import.server.test.ts
@@ -5,7 +5,7 @@ import {
createPublishedProjectBundleFixture,
} from "@webstudio-is/protocol/fixtures";
import { type PublishedProjectBundle } from "@webstudio-is/protocol";
-import { createAssetRows } from "@webstudio-is/asset-uploader/index.server";
+import { createAssetRows } from "@webstudio-is/asset-uploader/server";
import {
__testing__,
importPublishedProjectBundle,
diff --git a/apps/builder/app/services/project-import.server.ts b/apps/builder/app/services/project-import.server.ts
index 562a85a06d..1fb0579261 100644
--- a/apps/builder/app/services/project-import.server.ts
+++ b/apps/builder/app/services/project-import.server.ts
@@ -12,7 +12,7 @@ import {
import {
createAssetFolderRows,
createAssetRows,
-} from "@webstudio-is/asset-uploader/index.server";
+} from "@webstudio-is/asset-uploader/server";
import { loadDevBuildByProjectId } from "@webstudio-is/project-build/server";
import {
migratePages,
@@ -307,7 +307,10 @@ export const importPublishedProjectBundle = async (
ignoreVersionCheck?: boolean;
projectId: string;
},
- dependencies = {
+ dependencies: {
+ hasProjectPermit: typeof authorizeProject.hasProjectPermit;
+ loadDevBuildByProjectId: typeof loadDevBuildByProjectId;
+ } = {
hasProjectPermit: authorizeProject.hasProjectPermit,
loadDevBuildByProjectId,
}
@@ -335,17 +338,15 @@ export const importPublishedProjectBundle = async (
projectId,
});
+ const buildUpdate = createBuildImportUpdate({
+ data,
+ lastTransactionId: crypto.randomUUID(),
+ updatedAt: new Date().toISOString(),
+ version: nextVersion,
+ });
const update = await ctx.postgrest.client
.from("Build")
- .update(
- createBuildImportUpdate({
- data,
- lastTransactionId: crypto.randomUUID(),
- updatedAt: new Date().toISOString(),
- version: nextVersion,
- }),
- { count: "exact" }
- )
+ .update(buildUpdate, { count: "exact" })
.match({
id: build.id,
projectId,
diff --git a/apps/builder/app/services/rest-route-not-found.server.test.ts b/apps/builder/app/services/rest-route-not-found.server.test.ts
new file mode 100644
index 0000000000..9f9a5afc9d
--- /dev/null
+++ b/apps/builder/app/services/rest-route-not-found.server.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, test } from "vitest";
+import {
+ apiClientHeader,
+ getApiCompatibilityPayload,
+} from "@webstudio-is/trpc-interface/api-compatibility";
+import { action } from "../routes/rest.$";
+
+const requestUnknownRoute = async (client: "browser" | "cli") => {
+ const response = await action({
+ request: new Request("https://webstudio.is/rest/assets/unknown.png", {
+ method: "POST",
+ headers: { [apiClientHeader]: client },
+ }),
+ } as never);
+ return { response, body: await response.json() };
+};
+
+describe("unknown REST route", () => {
+ test("asks browser callers to reload", async () => {
+ const { response, body } = await requestUnknownRoute("browser");
+
+ expect(response.status).toBe(426);
+ expect(getApiCompatibilityPayload(body)).toMatchObject({
+ reason: "apiRouteNotFound",
+ target: "browser",
+ action: { type: "reloadBrowser" },
+ });
+ });
+
+ test("asks CLI callers to update", async () => {
+ const { response, body } = await requestUnknownRoute("cli");
+
+ expect(response.status).toBe(426);
+ expect(getApiCompatibilityPayload(body)).toMatchObject({
+ reason: "apiRouteNotFound",
+ target: "cli",
+ action: { type: "updateCli" },
+ });
+ });
+});
diff --git a/apps/builder/app/services/trpc-request.server.test.ts b/apps/builder/app/services/trpc-request.server.test.ts
deleted file mode 100644
index 886bcd2a75..0000000000
--- a/apps/builder/app/services/trpc-request.server.test.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { describe, expect, test } from "vitest";
-import { apiClientHeader } from "@webstudio-is/trpc-interface/api-compatibility";
-import { isCliApiRequest } from "./trpc-request.server";
-
-describe("isCliApiRequest", () => {
- test("accepts CLI API requests", () => {
- const request = new Request("https://webstudio.is/trpc", {
- headers: {
- [apiClientHeader]: "cli",
- },
- });
-
- expect(isCliApiRequest(request)).toBe(true);
- });
-
- test("rejects browser and unknown API requests", () => {
- const browserRequest = new Request("https://webstudio.is/trpc", {
- headers: {
- [apiClientHeader]: "browser",
- },
- });
- const unknownRequest = new Request("https://webstudio.is/trpc");
-
- expect(isCliApiRequest(browserRequest)).toBe(false);
- expect(isCliApiRequest(unknownRequest)).toBe(false);
- });
-});
diff --git a/apps/builder/app/services/trpc-request.server.ts b/apps/builder/app/services/trpc-request.server.ts
deleted file mode 100644
index c3bf36cfbd..0000000000
--- a/apps/builder/app/services/trpc-request.server.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { apiClientHeader } from "@webstudio-is/trpc-interface/api-compatibility";
-
-export const isCliApiRequest = (request: Pick<Request, "headers">) => {
- return request.headers.get(apiClientHeader) === "cli";
-};
diff --git a/apps/builder/app/shared/$resources/assets-description.server.test.ts b/apps/builder/app/shared/$resources/assets-description.server.test.ts
new file mode 100644
index 0000000000..0ab942e0b2
--- /dev/null
+++ b/apps/builder/app/shared/$resources/assets-description.server.test.ts
@@ -0,0 +1,183 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { TRPCError } from "@trpc/server";
+import { AuthorizationError } from "@webstudio-is/trpc-interface/index.server";
+import { defaultAssetResourceOutputSelection } from "@webstudio-is/content-engine";
+import { loadOpenApiQueryDefinition } from "@webstudio-is/query-builder";
+import { loader as openApiLoader } from "../../routes/rest.assets.openapi[.]json";
+import { loader as querySchemaLoader } from "../../routes/rest.assets.query-schema[.]json";
+import { builderSessionCookieName } from "~/services/builder-session.server";
+
+const projectId = "090e6e14-ae50-4b2e-bd22-71733cec05bb";
+const assetClient = { readFile: vi.fn() };
+const dependencies = {
+ authorizeApiProject: vi.fn(),
+ createAssetClient: vi.fn(() => assetClient),
+ loadBuilderAssetFieldCatalog: vi.fn(),
+ preventCrossOriginCookie: vi.fn(),
+};
+const catalog = {
+ format: "webstudio-builder-asset-field-catalog" as const,
+ version: 1 as const,
+ canonicalRevision: `sha256:${"a".repeat(64)}`,
+ documentCount: 1,
+ fields: {
+ slug: {
+ queryPath: ["properties", "slug"],
+ types: ["string" as const],
+ occurrences: 1,
+ },
+ },
+};
+
+const request = (path: string, hostname = `p-${projectId}.localhost`) =>
+ new Request(`https://${hostname}${path}`);
+
+describe("asset API descriptions", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ dependencies.authorizeApiProject.mockResolvedValue({} as never);
+ dependencies.loadBuilderAssetFieldCatalog.mockResolvedValue(catalog);
+ });
+
+ test("serves project-specific OpenAPI without storage configuration", async () => {
+ const openApiRequest = request("/$resources/assets/openapi.json");
+ const response = await openApiLoader(
+ { request: openApiRequest },
+ dependencies
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get("content-type")).toBe(
+ "application/vnd.oai.openapi+json;version=3.1"
+ );
+ const document = await response.json();
+ expect(document).toMatchObject({
+ openapi: "3.1.1",
+ paths: {
+ "/rest/assets/query": {
+ post: { operationId: "queryAssets" },
+ },
+ },
+ components: {
+ securitySchemes: {
+ builderSession: { name: builderSessionCookieName },
+ },
+ },
+ });
+ const definition = await loadOpenApiQueryDefinition({
+ document,
+ documentUrl: openApiRequest.url,
+ operationId: "queryAssets",
+ loadReference: async (url) => {
+ const schemaResponse = await querySchemaLoader(
+ { request: new Request(url) },
+ dependencies
+ );
+ expect(schemaResponse.status).toBe(200);
+ return await schemaResponse.json();
+ },
+ });
+ expect(definition.fields).toContainEqual(
+ expect.objectContaining({
+ path: ["properties", "slug"],
+ label: "properties / slug",
+ operators: expect.arrayContaining(["eq", "contains"]),
+ })
+ );
+ expect(definition.source.controls).toContainEqual(
+ expect.objectContaining({
+ type: "variant",
+ key: "output",
+ defaultValue: defaultAssetResourceOutputSelection,
+ config: expect.objectContaining({
+ selection: {
+ label: "Output",
+ emptyOption: "base",
+ baseline: { key: "includeMetadata", label: "File metadata" },
+ },
+ options: expect.arrayContaining([
+ expect.objectContaining({
+ value: "all",
+ label: "All content fields",
+ }),
+ ]),
+ }),
+ })
+ );
+ expect(dependencies.authorizeApiProject).toHaveBeenCalledWith(
+ expect.any(Request),
+ projectId,
+ "view"
+ );
+ expect(dependencies.loadBuilderAssetFieldCatalog).toHaveBeenCalledTimes(1);
+ expect(dependencies.loadBuilderAssetFieldCatalog).toHaveBeenLastCalledWith({
+ projectId,
+ context: expect.anything(),
+ assetClient,
+ });
+ });
+
+ test("requires a project outside Builder", async () => {
+ const response = await openApiLoader(
+ {
+ request: request("/$resources/assets/openapi.json", "example.com"),
+ },
+ dependencies
+ );
+
+ expect(response.status).toBe(400);
+ expect(dependencies.loadBuilderAssetFieldCatalog).not.toHaveBeenCalled();
+ });
+
+ test("serves token-authenticated REST descriptions with a project query", async () => {
+ const directRequest = request(
+ `/rest/assets/openapi.json?projectId=${projectId}`,
+ "api.example"
+ );
+ const response = await openApiLoader(
+ { request: directRequest },
+ dependencies
+ );
+
+ expect(response.status).toBe(200);
+ expect(dependencies.authorizeApiProject).toHaveBeenCalledWith(
+ directRequest,
+ projectId,
+ "view"
+ );
+ });
+
+ test("does not expose descriptions without project authorization", async () => {
+ dependencies.authorizeApiProject.mockRejectedValue(
+ new AuthorizationError("denied")
+ );
+
+ const response = await openApiLoader(
+ { request: request("/$resources/assets/openapi.json") },
+ dependencies
+ );
+
+ expect(response.status).toBe(403);
+ await expect(response.json()).resolves.toMatchObject({
+ ok: false,
+ error: { code: "FORBIDDEN", retryable: false },
+ });
+ });
+
+ test("preserves authentication failures in description responses", async () => {
+ dependencies.authorizeApiProject.mockRejectedValueOnce(
+ new TRPCError({ code: "UNAUTHORIZED", message: "token required" })
+ );
+
+ const response = await openApiLoader(
+ { request: request("/$resources/assets/openapi.json") },
+ dependencies
+ );
+
+ expect(response.status).toBe(401);
+ await expect(response.json()).resolves.toMatchObject({
+ ok: false,
+ error: { code: "UNAUTHORIZED", retryable: false },
+ });
+ });
+});
diff --git a/apps/builder/app/shared/$resources/assets-description.server.ts b/apps/builder/app/shared/$resources/assets-description.server.ts
new file mode 100644
index 0000000000..1bc6d47da7
--- /dev/null
+++ b/apps/builder/app/shared/$resources/assets-description.server.ts
@@ -0,0 +1,119 @@
+import { loadBuilderAssetFieldCatalog } from "@webstudio-is/asset-uploader/server";
+import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";
+import {
+ authorizeApiProject,
+ getApiAuthorizationFailure,
+} from "~/services/api-auth.server";
+import { getAssetRestProjectId } from "~/services/asset-rest.server";
+import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
+import { createAssetClient } from "../asset-client";
+import { createAssetResourceFailureResponse } from "./assets-response.server";
+
+type AssetDescriptionDependencies = {
+ authorizeApiProject: typeof authorizeApiProject;
+ createAssetClient: () => Pick<
+ ReturnType<typeof createAssetClient>,
+ "readFile"
+ >;
+ loadBuilderAssetFieldCatalog: typeof loadBuilderAssetFieldCatalog;
+ preventCrossOriginCookie: typeof preventCrossOriginCookie;
+};
+
+const defaultDependencies: AssetDescriptionDependencies = {
+ authorizeApiProject,
+ createAssetClient,
+ loadBuilderAssetFieldCatalog,
+ preventCrossOriginCookie,
+};
+
+type AssetDescriptionContext = {
+ projectId: string;
+ loadFieldCatalog: () => ReturnType<typeof loadBuilderAssetFieldCatalog>;
+};
+
+const createAssetDescriptionLoaderCore =
+ <Value>({
+ createValue,
+ contentType,
+ }: {
+ createValue: (context: AssetDescriptionContext) => Value | Promise<Value>;
+ contentType?: string;
+ }) =>
+ async (
+ { request }: { request: Request },
+ dependencies: AssetDescriptionDependencies = defaultDependencies
+ ) => {
+ dependencies.preventCrossOriginCookie(request);
+ let projectId: string;
+ try {
+ projectId = getAssetRestProjectId(request);
+ } catch {
+ return createAssetResourceFailureResponse({
+ code: "INVALID_REQUEST",
+ message: "Project ID is required to describe project assets",
+ status: 400,
+ });
+ }
+
+ try {
+ const authorization = await dependencies.authorizeApiProject(
+ request,
+ projectId,
+ "view"
+ );
+ const value = await createValue({
+ projectId,
+ loadFieldCatalog: () =>
+ dependencies.loadBuilderAssetFieldCatalog({
+ projectId,
+ context: authorization,
+ assetClient: dependencies.createAssetClient(),
+ }),
+ });
+ return new Response(JSON.stringify(value), {
+ headers: {
+ ...privateNoStoreResponseHeaders,
+ "content-type": contentType ?? "application/json; charset=utf-8",
+ },
+ });
+ } catch (error) {
+ const authorizationFailure = getApiAuthorizationFailure(error);
+ if (authorizationFailure !== undefined) {
+ return createAssetResourceFailureResponse(authorizationFailure);
+ }
+ return createAssetResourceFailureResponse({
+ code: "INTERNAL_ERROR",
+ message: "Project asset API description failed",
+ status: 500,
+ retryable: true,
+ });
+ }
+ };
+
+export const createAssetDescriptionLoader = <Value>({
+ createValue,
+ contentType,
+}: {
+ createValue: (
+ catalog: Awaited<ReturnType<typeof loadBuilderAssetFieldCatalog>>,
+ context: { projectId: string }
+ ) => Value;
+ contentType?: string;
+}) =>
+ createAssetDescriptionLoaderCore({
+ contentType,
+ createValue: async ({ projectId, loadFieldCatalog }) =>
+ createValue(await loadFieldCatalog(), { projectId }),
+ });
+
+export const createStaticAssetDescriptionLoader = <Value>({
+ createValue,
+ contentType,
+}: {
+ createValue: (context: { projectId: string }) => Value;
+ contentType?: string;
+}) =>
+ createAssetDescriptionLoaderCore({
+ contentType,
+ createValue: ({ projectId }) => createValue({ projectId }),
+ });
diff --git a/apps/builder/app/shared/$resources/assets-field-catalog.server.test.ts b/apps/builder/app/shared/$resources/assets-field-catalog.server.test.ts
new file mode 100644
index 0000000000..bd2d74a7e0
--- /dev/null
+++ b/apps/builder/app/shared/$resources/assets-field-catalog.server.test.ts
@@ -0,0 +1,77 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { AuthorizationError } from "@webstudio-is/trpc-interface/index.server";
+import { loader } from "../../routes/rest.assets.field-catalog";
+
+const projectId = "090e6e14-ae50-4b2e-bd22-71733cec05bb";
+const assetClient = { readFile: vi.fn() };
+const dependencies = {
+ authorizeApiProject: vi.fn(),
+ createAssetClient: vi.fn(() => assetClient),
+ loadBuilderAssetFieldCatalog: vi.fn(),
+ preventCrossOriginCookie: vi.fn(),
+};
+const catalog = {
+ format: "webstudio-builder-asset-field-catalog" as const,
+ version: 1 as const,
+ canonicalRevision: `sha256:${"a".repeat(64)}`,
+ documentCount: 2,
+ fields: {
+ "properties.title": {
+ types: ["string" as const],
+ occurrences: 2,
+ },
+ },
+};
+
+describe("asset field catalog system resource", () => {
+ beforeEach(() => {
+ dependencies.authorizeApiProject.mockResolvedValue({} as never);
+ dependencies.loadBuilderAssetFieldCatalog.mockResolvedValue(catalog);
+ });
+
+ test("returns the authenticated project's compact field catalog", async () => {
+ const response = await loader(
+ {
+ request: new Request(
+ `https://p-${projectId}.localhost/$resources/assets/field-catalog`
+ ),
+ },
+ dependencies
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get("cache-control")).toContain("private");
+ await expect(response.json()).resolves.toEqual(catalog);
+ expect(dependencies.authorizeApiProject).toHaveBeenCalledWith(
+ expect.any(Request),
+ projectId,
+ "view"
+ );
+ expect(dependencies.loadBuilderAssetFieldCatalog).toHaveBeenCalledWith({
+ projectId,
+ context: expect.anything(),
+ assetClient,
+ });
+ });
+
+ test("returns a structured forbidden response", async () => {
+ dependencies.loadBuilderAssetFieldCatalog.mockRejectedValue(
+ new AuthorizationError("denied")
+ );
+
+ const response = await loader(
+ {
+ request: new Request(
+ `https://p-${projectId}.localhost/$resources/assets/field-catalog`
+ ),
+ },
+ dependencies
+ );
+
+ expect(response.status).toBe(403);
+ await expect(response.json()).resolves.toMatchObject({
+ ok: false,
+ error: { code: "FORBIDDEN", retryable: false },
+ });
+ });
+});
diff --git a/apps/builder/app/shared/$resources/assets-query.server.test.ts b/apps/builder/app/shared/$resources/assets-query.server.test.ts
new file mode 100644
index 0000000000..fe889511cc
--- /dev/null
+++ b/apps/builder/app/shared/$resources/assets-query.server.test.ts
@@ -0,0 +1,219 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { TRPCError } from "@trpc/server";
+import {
+ AssetIndexRevisionError,
+ AssetQueryExecutionError,
+} from "@webstudio-is/content-engine";
+import { AuthorizationError } from "@webstudio-is/trpc-interface/index.server";
+import { executeAssetQuery } from "./assets-query.server";
+
+const projectId = "090e6e14-ae50-4b2e-bd22-71733cec05bb";
+const dependencies = {
+ authorizeApiProject: vi.fn(),
+ createAssetClient: vi.fn(() => ({ readFile: vi.fn() })),
+ previewAssetResourceQuery: vi.fn(),
+ preventCrossOriginCookie: vi.fn(),
+};
+const outerRequest = () =>
+ new Request(`https://p-${projectId}.localhost/rest/resources-loader`);
+const innerRequest = (body: unknown) =>
+ new Request(`https://p-${projectId}.localhost/$resources/assets`, {
+ method: "POST",
+ body: JSON.stringify(body),
+ });
+
+describe("configured Assets system resource", () => {
+ beforeEach(() => {
+ dependencies.authorizeApiProject.mockResolvedValue({} as never);
+ dependencies.previewAssetResourceQuery.mockReset();
+ });
+
+ test("uses the outer authentication context and typed inner request", async () => {
+ const responseBody = {
+ data: {
+ items: [{ id: "post-1" }],
+ totalCount: 1,
+ hasMore: false,
+ },
+ __diagnostics__: {
+ scope: "query-preview",
+ usedBytes: 100,
+ maxBytes: 512_000,
+ unboundedBytes: 100,
+ includedDocumentCount: 1,
+ omittedDocumentCount: 0,
+ truncated: false,
+ },
+ };
+ dependencies.previewAssetResourceQuery.mockResolvedValue(responseBody);
+ const query = {
+ where: {
+ all: [
+ {
+ field: ["properties", "draft"],
+ operator: "ne",
+ value: true,
+ },
+ ],
+ },
+ limit: 20,
+ };
+
+ const response = await executeAssetQuery(
+ { request: outerRequest(), resourceRequest: innerRequest({ query }) },
+ dependencies
+ );
+
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual(responseBody);
+ expect(dependencies.authorizeApiProject).toHaveBeenCalledWith(
+ expect.any(Request),
+ projectId,
+ "view"
+ );
+ expect(dependencies.previewAssetResourceQuery).toHaveBeenCalledWith({
+ projectId,
+ request: {
+ query: expect.objectContaining({
+ ...query,
+ sort: [],
+ offset: 0,
+ content: { mode: "none" },
+ }),
+ },
+ context: expect.anything(),
+ assetClient: expect.objectContaining({ readFile: expect.any(Function) }),
+ contentDatabaseMaxBytes: 512_000,
+ });
+ });
+
+ test("supports the public REST URL with an explicit project", async () => {
+ dependencies.previewAssetResourceQuery.mockResolvedValue({
+ data: { items: [], totalCount: 0, hasMore: false },
+ __diagnostics__: {
+ scope: "query-preview",
+ usedBytes: 100,
+ maxBytes: 512_000,
+ unboundedBytes: 100,
+ includedDocumentCount: 0,
+ omittedDocumentCount: 0,
+ truncated: false,
+ },
+ });
+ const request = new Request(
+ `https://api.example/rest/assets/query?projectId=${projectId}`,
+ { method: "POST", body: JSON.stringify({ query: {} }) }
+ );
+
+ const response = await executeAssetQuery(
+ { request, resourceRequest: request.clone() },
+ dependencies
+ );
+
+ expect(response.status).toBe(200);
+ expect(dependencies.authorizeApiProject).toHaveBeenCalledWith(
+ request,
+ projectId,
+ "view"
+ );
+ });
+
+ test("returns structured invalid-request and forbidden failures", async () => {
+ const invalid = await executeAssetQuery(
+ {
+ request: outerRequest(),
+ resourceRequest: innerRequest({ query: { limit: -1 } }),
+ },
+ dependencies
+ );
+ expect(invalid.status).toBe(400);
+ await expect(invalid.json()).resolves.toMatchObject({
+ ok: false,
+ error: { code: "INVALID_REQUEST" },
+ });
+
+ dependencies.previewAssetResourceQuery.mockRejectedValue(
+ new AuthorizationError("denied")
+ );
+ const forbidden = await executeAssetQuery(
+ { request: outerRequest(), resourceRequest: innerRequest({ query: {} }) },
+ dependencies
+ );
+ expect(forbidden.status).toBe(403);
+ await expect(forbidden.json()).resolves.toMatchObject({
+ ok: false,
+ error: { code: "FORBIDDEN" },
+ });
+ });
+
+ test("preserves authentication and CSRF response statuses", async () => {
+ dependencies.authorizeApiProject.mockRejectedValueOnce(
+ new TRPCError({ code: "UNAUTHORIZED", message: "token required" })
+ );
+ const unauthorized = await executeAssetQuery(
+ { request: outerRequest(), resourceRequest: innerRequest({ query: {} }) },
+ dependencies
+ );
+ expect(unauthorized.status).toBe(401);
+ await expect(unauthorized.json()).resolves.toMatchObject({
+ ok: false,
+ error: { code: "UNAUTHORIZED", retryable: false },
+ });
+
+ dependencies.authorizeApiProject.mockRejectedValueOnce(
+ new Response("CSRF failed", { status: 403 })
+ );
+ const csrf = await executeAssetQuery(
+ { request: outerRequest(), resourceRequest: innerRequest({ query: {} }) },
+ dependencies
+ );
+ expect(csrf.status).toBe(403);
+ await expect(csrf.json()).resolves.toMatchObject({
+ ok: false,
+ error: { code: "FORBIDDEN", retryable: false },
+ });
+ });
+
+ test("rejects malformed JSON and maps execution errors", async () => {
+ const malformed = await executeAssetQuery(
+ {
+ request: outerRequest(),
+ resourceRequest: new Request(
+ `https://p-${projectId}.localhost/$resources/assets`,
+ { method: "POST", body: "{" }
+ ),
+ },
+ dependencies
+ );
+ expect(malformed.status).toBe(400);
+
+ dependencies.previewAssetResourceQuery.mockRejectedValueOnce(
+ new AssetQueryExecutionError("Invalid pagination")
+ );
+ const invalid = await executeAssetQuery(
+ { request: outerRequest(), resourceRequest: innerRequest({ query: {} }) },
+ dependencies
+ );
+ expect(invalid.status).toBe(400);
+ await expect(invalid.json()).resolves.toMatchObject({
+ error: { code: "INVALID_REQUEST" },
+ });
+ });
+
+ test("maps stale revisions to conflict responses", async () => {
+ dependencies.previewAssetResourceQuery.mockRejectedValue(
+ new AssetIndexRevisionError()
+ );
+
+ const response = await executeAssetQuery(
+ { request: outerRequest(), resourceRequest: innerRequest({ query: {} }) },
+ dependencies
+ );
+
+ expect(response.status).toBe(409);
+ await expect(response.json()).resolves.toMatchObject({
+ ok: false,
+ error: { code: "STALE_INDEX", retryable: false },
+ });
+ });
+});
diff --git a/apps/builder/app/shared/$resources/assets-query.server.ts b/apps/builder/app/shared/$resources/assets-query.server.ts
new file mode 100644
index 0000000000..b5b2c3d284
--- /dev/null
+++ b/apps/builder/app/shared/$resources/assets-query.server.ts
@@ -0,0 +1,97 @@
+import { json } from "@remix-run/server-runtime";
+import {
+ getAssetResourceQueryError,
+ readAssetQueryRequest,
+} from "@webstudio-is/content-engine";
+import { previewAssetResourceQuery } from "@webstudio-is/asset-uploader/server";
+import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";
+import {
+ authorizeApiProject,
+ getApiAuthorizationFailure,
+} from "~/services/api-auth.server";
+import { getAssetRestProjectId } from "~/services/asset-rest.server";
+import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
+import { getContentDatabaseMaxBytes } from "~/services/content-database.server";
+import { createAssetClient } from "../asset-client";
+import { createAssetResourceFailureResponse } from "./assets-response.server";
+
+type Dependencies = {
+ authorizeApiProject: typeof authorizeApiProject;
+ createAssetClient: () => Pick<
+ ReturnType<typeof createAssetClient>,
+ "readFile"
+ >;
+ previewAssetResourceQuery: typeof previewAssetResourceQuery;
+ preventCrossOriginCookie: typeof preventCrossOriginCookie;
+};
+
+const defaultDependencies: Dependencies = {
+ authorizeApiProject,
+ createAssetClient,
+ previewAssetResourceQuery,
+ preventCrossOriginCookie,
+};
+
+export const executeAssetQuery = async (
+ {
+ request,
+ resourceRequest,
+ }: {
+ request: Request;
+ resourceRequest: Request;
+ },
+ dependencies = defaultDependencies
+) => {
+ dependencies.preventCrossOriginCookie(request);
+ let projectId: string;
+ try {
+ projectId = getAssetRestProjectId(request);
+ } catch {
+ return createAssetResourceFailureResponse({
+ code: "INVALID_REQUEST",
+ message: "Project ID is required to preview an asset query",
+ status: 400,
+ });
+ }
+
+ let parsed;
+ try {
+ parsed = await readAssetQueryRequest(resourceRequest);
+ } catch {
+ return createAssetResourceFailureResponse({
+ code: "INVALID_REQUEST",
+ message: "Asset query preview requires a JSON request body",
+ status: 400,
+ });
+ }
+ try {
+ const context = await dependencies.authorizeApiProject(
+ request,
+ projectId,
+ "view"
+ );
+ const result = await dependencies.previewAssetResourceQuery({
+ projectId,
+ request: parsed,
+ context,
+ assetClient: dependencies.createAssetClient(),
+ contentDatabaseMaxBytes: getContentDatabaseMaxBytes(),
+ });
+ return json(result, { headers: privateNoStoreResponseHeaders });
+ } catch (error) {
+ const authorizationFailure = getApiAuthorizationFailure(error);
+ if (authorizationFailure !== undefined) {
+ return createAssetResourceFailureResponse(authorizationFailure);
+ }
+ const queryError = getAssetResourceQueryError(error);
+ if (queryError !== undefined) {
+ return createAssetResourceFailureResponse(queryError);
+ }
+ return createAssetResourceFailureResponse({
+ code: "INTERNAL_ERROR",
+ message: "Asset query preview failed",
+ status: 500,
+ retryable: true,
+ });
+ }
+};
diff --git a/apps/builder/app/shared/$resources/assets-response.server.ts b/apps/builder/app/shared/$resources/assets-response.server.ts
new file mode 100644
index 0000000000..ff1f280d71
--- /dev/null
+++ b/apps/builder/app/shared/$resources/assets-response.server.ts
@@ -0,0 +1,19 @@
+import { json } from "@remix-run/server-runtime";
+import {
+ createAssetResourceQueryFailure,
+ type AssetResourceQueryFailure,
+} from "@webstudio-is/content-engine";
+import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";
+
+export const createAssetResourceFailureResponse = ({
+ status,
+ retryable = false,
+ ...error
+}: Omit<AssetResourceQueryFailure["error"], "retryable"> & {
+ status: number;
+ retryable?: boolean;
+}) =>
+ json(createAssetResourceQueryFailure({ ...error, retryable }), {
+ status,
+ headers: privateNoStoreResponseHeaders,
+ });
diff --git a/apps/builder/app/shared/$resources/assets.server.ts b/apps/builder/app/shared/$resources/assets.server.ts
deleted file mode 100644
index bffdd290b2..0000000000
--- a/apps/builder/app/shared/$resources/assets.server.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { json } from "@remix-run/server-runtime";
-import { parseBuilderUrl } from "@webstudio-is/protocol";
-import { loadAssetsByProject } from "@webstudio-is/asset-uploader/index.server";
-import { toRuntimeAsset } from "@webstudio-is/sdk";
-import { isBuilder } from "../router-utils";
-import { createContext } from "../context.server";
-
-/**
- * System Resource that provides the list of assets for the current project.
- * This allows assets to be dynamically referenced in the builder using the expression editor.
- */
-export const loader = async ({ request }: { request: Request }) => {
- if (isBuilder(request) === false) {
- throw new Error(
- "Asset resource loader can only be accessed from the builder interface"
- );
- }
-
- const { projectId } = parseBuilderUrl(request.url);
-
- if (projectId === undefined) {
- throw new Error(
- "Project ID is required to load assets. Ensure the request includes a valid project context."
- );
- }
-
- const context = await createContext(request);
-
- const assets = await loadAssetsByProject(projectId, context);
-
- const requestUrl = new URL(request.url);
- const origin = `${requestUrl.protocol}//${requestUrl.host}`;
-
- // Convert array to object with asset IDs as keys
- // Use /cgi/ endpoint URLs (relative paths)
- const assetsById = Object.fromEntries(
- assets.map((asset) => [asset.id, toRuntimeAsset(asset, origin)])
- );
-
- return json(assetsById);
-};
diff --git a/apps/builder/app/shared/asset-client.ts b/apps/builder/app/shared/asset-client.ts
index c16b020011..da2261dab9 100644
--- a/apps/builder/app/shared/asset-client.ts
+++ b/apps/builder/app/shared/asset-client.ts
@@ -1,9 +1,9 @@
import * as path from "node:path";
import { maxSize } from "@webstudio-is/asset-uploader";
import {
- createFsClient,
- createS3Client,
-} from "@webstudio-is/asset-uploader/index.server";
+ createFsAssetObjectStore,
+ createS3AssetObjectStore,
+} from "@webstudio-is/asset-uploader/server";
import env from "~/env/env.server";
export const fileUploadPath = "public/cgi/asset";
@@ -19,7 +19,7 @@ export const createAssetClient = () => {
env.S3_SECRET_ACCESS_KEY !== undefined &&
env.S3_BUCKET !== undefined
) {
- return createS3Client({
+ return createS3AssetObjectStore({
endpoint: env.S3_ENDPOINT,
region: env.S3_REGION,
accessKeyId: env.S3_ACCESS_KEY_ID,
@@ -29,7 +29,7 @@ export const createAssetClient = () => {
maxUploadSize,
});
} else {
- return createFsClient({
+ return createFsAssetObjectStore({
maxUploadSize,
fileDirectory: path.join(process.cwd(), fileUploadPath),
});
diff --git a/apps/builder/app/shared/code-editor-base.tsx b/apps/builder/app/shared/code-editor-base.tsx
index bde7f64efb..0235d1f3b6 100644
--- a/apps/builder/app/shared/code-editor-base.tsx
+++ b/apps/builder/app/shared/code-editor-base.tsx
@@ -113,7 +113,10 @@ const editorContentStyle = css({
"&:focus-within": {
borderColor: theme.colors.borderFocus,
},
- '&[data-border="hidden"]:not([data-invalid="true"]):is(:hover, :focus-within)':
+ '&[data-chromeless="true"]': {
+ borderRadius: 0,
+ },
+ '&[data-chromeless="true"]:not([data-invalid="true"]):is(:hover, :focus-within)':
{
borderColor: "transparent",
},
@@ -274,7 +277,7 @@ type EditorContentProps = {
autoFocus?: boolean;
invalid?: boolean;
showShortcuts?: boolean;
- showBorder?: boolean;
+ chromeless?: boolean;
value?: string;
onChange: (value: string) => void;
onChangeComplete: (value: string) => void;
@@ -287,7 +290,7 @@ export const EditorContent = ({
autoFocus = false,
invalid = false,
showShortcuts = false,
- showBorder = true,
+ chromeless = false,
value,
onChange,
onChangeComplete,
@@ -474,7 +477,7 @@ export const EditorContent = ({
<div
className={editorContentStyle()}
data-invalid={invalid}
- data-border={showBorder ? undefined : "hidden"}
+ data-chromeless={chromeless ? "true" : undefined}
ref={editorRef}
>
{showShortcuts && (
diff --git a/apps/builder/app/shared/context.server.test.ts b/apps/builder/app/shared/context.server.test.ts
index 170f353f2e..9f403ff6da 100644
--- a/apps/builder/app/shared/context.server.test.ts
+++ b/apps/builder/app/shared/context.server.test.ts
@@ -69,6 +69,7 @@ import { extractAuthFromRequest } from "./context.server";
describe("extractAuthFromRequest", () => {
beforeEach(() => {
+ vi.clearAllMocks();
env.TRPC_SERVER_API_TOKEN = undefined;
authenticator.isAuthenticated.mockResolvedValue(undefined);
builderAuthenticator.isAuthenticated.mockResolvedValue(undefined);
@@ -96,5 +97,30 @@ describe("extractAuthFromRequest", () => {
const auth = await extractAuthFromRequest(request);
expect(auth.isServiceCall).toBe(true);
+ expect(authenticator.isAuthenticated).not.toHaveBeenCalled();
+ });
+
+ test("prefers an explicit token without reading the cookie session", async () => {
+ const request = new Request("https://webstudio.is/trpc", {
+ headers: { "x-auth-token": "project-token" },
+ });
+
+ const auth = await extractAuthFromRequest(request);
+
+ expect(auth.authToken).toBe("project-token");
+ expect(auth.sessionData).toBeUndefined();
+ expect(authenticator.isAuthenticated).not.toHaveBeenCalled();
+ });
+
+ test("reads the cookie session when no explicit credential is available", async () => {
+ const sessionData = { userId: "user-1", createdAt: 1 };
+ authenticator.isAuthenticated.mockResolvedValue(sessionData);
+
+ const auth = await extractAuthFromRequest(
+ new Request("https://webstudio.is/trpc")
+ );
+
+ expect(auth.authToken).toBeUndefined();
+ expect(auth.sessionData).toBe(sessionData);
});
});
diff --git a/apps/builder/app/shared/context.server.ts b/apps/builder/app/shared/context.server.ts
index 74ec42cc75..e3880b47d4 100644
--- a/apps/builder/app/shared/context.server.ts
+++ b/apps/builder/app/shared/context.server.ts
@@ -33,14 +33,20 @@ export const extractAuthFromRequest = async (request: Request) => {
request.headers.get("x-auth-token") ??
undefined;
- const sessionData = isBuilder(request)
- ? await builderAuthenticator.isAuthenticated(request)
- : await authenticator.isAuthenticated(request);
-
const isServiceCall = isServiceAuthorization(
request.headers.get("Authorization")
);
+ // Explicit credentials always win. In particular, an invalid supplied token
+ // must fail during context creation instead of falling back to a potentially
+ // more privileged browser session.
+ const sessionData =
+ authToken === undefined && isServiceCall === false
+ ? isBuilder(request)
+ ? await builderAuthenticator.isAuthenticated(request)
+ : await authenticator.isAuthenticated(request)
+ : undefined;
+
return {
authToken,
isServiceCall,
diff --git a/apps/builder/app/shared/db/canvas.server.ts b/apps/builder/app/shared/db/canvas.server.ts
index 8b66daf2b3..995611a8cb 100644
--- a/apps/builder/app/shared/db/canvas.server.ts
+++ b/apps/builder/app/shared/db/canvas.server.ts
@@ -8,10 +8,15 @@ import {
loadDevBuildByProjectId,
} from "@webstudio-is/project-build/server";
import { collectFontFamiliesFromStyleDecls } from "@webstudio-is/project-build/runtime";
-import { loadAssetDataByProject } from "@webstudio-is/asset-uploader/index.server";
+import {
+ loadAssetDataByProject,
+ PostgresAssetRepository,
+} from "@webstudio-is/asset-uploader/server";
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+import { getContentArtifactRuntimeAssetIds } from "@webstudio-is/content-engine";
import {
findPageByIdOrPath,
+ createReachableAssetContentCompilationPlan,
getAllPages,
getStyleDeclKey,
type Asset,
@@ -20,6 +25,8 @@ import {
import { serializePages } from "@webstudio-is/project-migrations/pages";
import { loadById } from "@webstudio-is/project/index.server";
import { getUserById } from "./user.server";
+import { createAssetClient } from "../asset-client";
+import { getContentDatabaseMaxBytes } from "~/services/content-database.server";
const getPair = <Item extends { id: string }>(item: Item): [string, Item] => [
item.id,
@@ -153,12 +160,69 @@ const addProjectMetadata = async (
? undefined
: await getUserById(context, project.userId);
+ const assetRequirements = createReachableAssetContentCompilationPlan({
+ props: data.build.props.map(([, prop]) => prop),
+ dataSources: data.build.dataSources.map(([, dataSource]) => dataSource),
+ resources: data.build.resources.map(([, resource]) => resource),
+ });
+ let assetIndex: PublishedProjectBundle["assetIndex"];
+ let publishedAssets = data.assets;
+ let publishedAssetFolders = data.assetFolders;
+ if (assetRequirements !== undefined) {
+ const assetClient = createAssetClient();
+ const assetRepository = new PostgresAssetRepository({
+ projectId: project.id,
+ context,
+ assetStore: assetClient,
+ contentDatabaseMaxBytes: getContentDatabaseMaxBytes(),
+ });
+ const retainedFontIds = new Set(
+ data.assets
+ .filter((asset) => asset.type === "font")
+ .map((asset) => asset.id)
+ );
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ const assetDataBefore = await loadAssetDataByProject(project.id, context);
+ const preparedIndex =
+ await assetRepository.prepareIndex(assetRequirements);
+ const assetDataAfter = await loadAssetDataByProject(project.id, context);
+ const assetsStayedStable =
+ JSON.stringify(assetDataBefore) === JSON.stringify(assetDataAfter);
+ if (assetsStayedStable === false) {
+ if (attempt === 0) {
+ continue;
+ }
+ throw new Error("Assets changed while preparing publication; retry");
+ }
+ assetIndex = preparedIndex;
+ const retainedRuntimeAssetIds = new Set(retainedFontIds);
+ for (const assetId of getContentArtifactRuntimeAssetIds({
+ artifact: preparedIndex,
+ includeDocuments: true,
+ })) {
+ retainedRuntimeAssetIds.add(assetId);
+ }
+ publishedAssets = assetDataAfter.assets.filter(
+ (asset) =>
+ asset.type !== "font" || retainedRuntimeAssetIds.has(asset.id)
+ );
+ publishedAssetFolders = assetDataAfter.assetFolders;
+ break;
+ }
+ if (assetIndex === undefined) {
+ throw new Error("Asset index was not prepared");
+ }
+ }
+
return {
...data,
+ assets: publishedAssets,
+ assetFolders: publishedAssetFolders,
bundleVersion,
user: user ? { email: user.email } : undefined,
projectDomain: project.domain,
projectTitle: project.title,
+ assetIndex,
};
};
diff --git a/apps/builder/app/shared/fetch.client.ts b/apps/builder/app/shared/fetch.client.ts
index 68b1445a59..6af82a60ba 100644
--- a/apps/builder/app/shared/fetch.client.ts
+++ b/apps/builder/app/shared/fetch.client.ts
@@ -5,7 +5,7 @@ import {
getApiCompatibilityPayload,
} from "@webstudio-is/trpc-interface/api-compatibility";
import { csrfToken } from "./csrf.client";
-import { $authToken } from "./nano-states";
+import { $authToken } from "./nano-states/misc";
import { publicStaticEnv } from "~/env/env.static";
/**
diff --git a/apps/builder/app/shared/marketplace/db.server.ts b/apps/builder/app/shared/marketplace/db.server.ts
index f0db77d328..85e196ad69 100644
--- a/apps/builder/app/shared/marketplace/db.server.ts
+++ b/apps/builder/app/shared/marketplace/db.server.ts
@@ -4,7 +4,7 @@ import { loadApprovedProdBuildByProjectId } from "@webstudio-is/project-build/se
import { parseConfig } from "@webstudio-is/project-build/persistence";
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
import type { Project } from "@webstudio-is/project";
-import { loadAssetsByProject } from "@webstudio-is/asset-uploader/index.server";
+import { loadAssetsByProject } from "@webstudio-is/asset-uploader/server";
import { serializePages } from "@webstudio-is/project-migrations/pages";
export const getBuildProdData = async (
diff --git a/apps/builder/app/shared/nano-states/props.ts b/apps/builder/app/shared/nano-states/props.ts
index 2dee8a7328..3dfa9e48ef 100644
--- a/apps/builder/app/shared/nano-states/props.ts
+++ b/apps/builder/app/shared/nano-states/props.ts
@@ -9,13 +9,13 @@ import type {
import {
decodeDataSourceVariable,
encodeDataSourceVariable,
- transpileExpression,
collectionComponent,
portalComponent,
ROOT_INSTANCE_ID,
SYSTEM_VARIABLE_ID,
findTreeInstanceIds,
} from "@webstudio-is/sdk";
+import { transpileExpression } from "@webstudio-is/expression";
import {
normalizeProps,
textContentAttribute,
@@ -37,7 +37,7 @@ import {
$resourcesCache,
computeResourceRequest,
getResourceKey,
- preloadResource,
+ preloadResources,
} from "../resources";
export const assetBaseUrl = "/cgi/asset/";
@@ -621,8 +621,6 @@ const $computedResourceRequests = computed(
*/
export const subscribeResources = () => {
return $computedResourceRequests.subscribe((computedResourceRequests) => {
- for (const resourceRequest of computedResourceRequests) {
- preloadResource(resourceRequest);
- }
+ preloadResources(computedResourceRequests);
});
};
diff --git a/apps/builder/app/shared/resource-diagnostics.test.ts b/apps/builder/app/shared/resource-diagnostics.test.ts
new file mode 100644
index 0000000000..41fec6aa9c
--- /dev/null
+++ b/apps/builder/app/shared/resource-diagnostics.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, test } from "vitest";
+import type { ResourceRequest } from "@webstudio-is/sdk";
+import { separateResourceDiagnostics } from "./resource-diagnostics";
+
+const assetsRequest: ResourceRequest = {
+ name: "assets",
+ url: "/$resources/assets",
+ method: "post",
+ searchParams: [],
+ headers: [],
+};
+
+describe("resource diagnostics", () => {
+ test("keeps diagnostics outside of the binding-visible resource value", () => {
+ const separated = separateResourceDiagnostics({
+ request: assetsRequest,
+ result: {
+ ok: true,
+ data: { post: { id: "post" } },
+ meta: { totalCount: 1, hasMore: false },
+ __diagnostics__: {
+ scope: "query-preview",
+ usedBytes: 100,
+ maxBytes: 500,
+ unboundedBytes: 700,
+ includedDocumentCount: 80,
+ omittedDocumentCount: 20,
+ truncated: true,
+ },
+ },
+ });
+
+ expect(separated.result).toEqual({
+ ok: true,
+ data: { post: { id: "post" } },
+ meta: { totalCount: 1, hasMore: false },
+ });
+ expect(separated.result).not.toHaveProperty("__diagnostics__");
+ expect(separated.diagnostics).toMatchObject({
+ includedDocumentCount: 80,
+ omittedDocumentCount: 20,
+ truncated: true,
+ });
+ });
+
+ test("strips malformed diagnostics instead of exposing them", () => {
+ const separated = separateResourceDiagnostics({
+ request: assetsRequest,
+ result: {
+ data: { items: [] },
+ __diagnostics__: { truncated: "yes" },
+ },
+ });
+
+ expect(separated.result).toEqual({ data: { items: [] } });
+ expect(separated.diagnostics).toBeUndefined();
+ });
+
+ test("preserves diagnostics fields returned by ordinary APIs", () => {
+ const result = {
+ data: { items: [] },
+ __diagnostics__: { provider: "example" },
+ };
+ expect(
+ separateResourceDiagnostics({
+ request: { ...assetsRequest, name: "API", url: "/api/items" },
+ result,
+ })
+ ).toEqual({ result, diagnostics: undefined });
+ });
+});
diff --git a/apps/builder/app/shared/resource-diagnostics.ts b/apps/builder/app/shared/resource-diagnostics.ts
new file mode 100644
index 0000000000..c90877a68c
--- /dev/null
+++ b/apps/builder/app/shared/resource-diagnostics.ts
@@ -0,0 +1,28 @@
+import { assetQueryPreviewDiagnostics } from "@webstudio-is/content-engine";
+import type { ResourceRequest } from "@webstudio-is/sdk";
+import { isAssetsResourceRequest } from "@webstudio-is/sdk/runtime";
+
+// Assets diagnostics may be shown by Builder, but must never enter the value
+// exposed to expressions. Ordinary APIs may legitimately use the same field.
+export const separateResourceDiagnostics = ({
+ request,
+ result,
+}: {
+ request?: ResourceRequest;
+ result: unknown;
+}) => {
+ if (
+ request === undefined ||
+ isAssetsResourceRequest(request) === false ||
+ typeof result !== "object" ||
+ result === null ||
+ "__diagnostics__" in result === false
+ ) {
+ return { result, diagnostics: undefined };
+ }
+ const { __diagnostics__, ...resourceResult } = result;
+ return {
+ result: resourceResult,
+ diagnostics: assetQueryPreviewDiagnostics.safeParse(__diagnostics__).data,
+ };
+};
diff --git a/apps/builder/app/shared/resource-utils.test.ts b/apps/builder/app/shared/resource-utils.test.ts
index 95700e57ea..ad5e4b58e6 100644
--- a/apps/builder/app/shared/resource-utils.test.ts
+++ b/apps/builder/app/shared/resource-utils.test.ts
@@ -209,4 +209,31 @@ describe("getResourceKey - pure function tests", () => {
expect(key1).toBe(key2);
expect(key1).toBeTruthy();
});
+
+ test("asset query cache separates structured query inputs", () => {
+ const createRequest = (body: Record<string, unknown>): ResourceRequest => ({
+ name: "assets-query",
+ control: "system",
+ method: "post",
+ url: "/$resources/assets",
+ searchParams: [],
+ headers: [{ name: "content-type", value: "application/json" }],
+ body,
+ });
+ const base = { query: { where: { all: [] }, limit: 20, offset: 0 } };
+ const requests = [
+ base,
+ { query: { ...base.query, limit: 10 } },
+ { query: { ...base.query, offset: 10 } },
+ {
+ query: {
+ ...base.query,
+ sort: [{ field: ["name"], direction: "asc" }],
+ },
+ },
+ ];
+ const keys = requests.map((body) => getResourceKey(createRequest(body)));
+
+ expect(new Set(keys).size).toBe(requests.length);
+ });
});
diff --git a/apps/builder/app/shared/resources.test.ts b/apps/builder/app/shared/resources.test.ts
new file mode 100644
index 0000000000..557cfbcd96
--- /dev/null
+++ b/apps/builder/app/shared/resources.test.ts
@@ -0,0 +1,70 @@
+import { afterEach, expect, test, vi } from "vitest";
+import type { ResourceRequest } from "@webstudio-is/sdk";
+import {
+ __testing__,
+ $hasPendingResources,
+ $resourcesCache,
+ getResourceKey,
+ preloadResources,
+} from "./resources";
+
+const { loadResources } = __testing__;
+
+afterEach(() => {
+ preloadResources([]);
+ vi.useRealTimers();
+});
+
+test("removes obsolete queued requests but keeps cached results", () => {
+ vi.useFakeTimers();
+ const request: ResourceRequest = {
+ name: "Posts",
+ method: "get",
+ url: "https://example.com/posts",
+ searchParams: [],
+ headers: [],
+ };
+ const key = getResourceKey(request);
+
+ preloadResources([request]);
+ $resourcesCache.get().set(key, { stale: true });
+ expect($hasPendingResources.get()).toBe(true);
+
+ preloadResources([]);
+
+ expect($resourcesCache.get().has(key)).toBe(true);
+ expect($hasPendingResources.get()).toBe(false);
+});
+
+test.each([
+ {
+ name: "a rejected request",
+ fetch: async () => {
+ throw new Error("network failure");
+ },
+ },
+ {
+ name: "a non-success response",
+ fetch: async () => new Response(null, { status: 503 }),
+ },
+ {
+ name: "a response missing the dispatched result",
+ fetch: async () => Response.json([]),
+ },
+])("settles pending resources after $name", async ({ fetch }) => {
+ vi.useFakeTimers();
+ const request: ResourceRequest = {
+ name: "Posts",
+ method: "get",
+ url: "https://example.com/posts",
+ searchParams: [],
+ headers: [],
+ };
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+
+ preloadResources([request]);
+ await loadResources(fetch as typeof globalThis.fetch);
+
+ expect($hasPendingResources.get()).toBe(false);
+ error.mockRestore();
+});
diff --git a/apps/builder/app/shared/resources.ts b/apps/builder/app/shared/resources.ts
index b2a6eed53b..9b6db5f9a9 100644
--- a/apps/builder/app/shared/resources.ts
+++ b/apps/builder/app/shared/resources.ts
@@ -1,9 +1,12 @@
import { atom, computed } from "nanostores";
import type { DataSource, Resource, ResourceRequest } from "@webstudio-is/sdk";
+import { isAssetsResourceRequest } from "@webstudio-is/sdk/runtime";
import { restResourcesLoader } from "./router-utils";
import { computeExpression } from "@webstudio-is/project-build/runtime";
import { fetch } from "./fetch.client";
import { getResourceKey } from "./resource-utils";
+import { type AssetQueryPreviewDiagnostics } from "@webstudio-is/content-engine";
+import { separateResourceDiagnostics } from "./resource-diagnostics";
const MAX_PENDING_RESOURCES = 5;
@@ -12,11 +15,15 @@ export { getResourceKey };
const queue = new Map<string, ResourceRequest>();
const pending = new Map<string, ResourceRequest>();
const cache = new Map<string, unknown>();
+const diagnosticsCache = new Map<string, AssetQueryPreviewDiagnostics>();
+const knownRequests = new Map<string, ResourceRequest>();
export const $resourcesCache = atom(cache);
+export const $resourceDiagnosticsCache = atom(diagnosticsCache);
const updateCache = () => {
$resourcesCache.set(new Map(cache));
+ $resourceDiagnosticsCache.set(new Map(diagnosticsCache));
};
const $pendingUpdater = atom({});
@@ -30,29 +37,53 @@ export const $hasPendingResources = computed(
() => queue.size > 0 || pending.size > 0
);
-const loadResources = async () => {
+const loadResources = async (requestFetch: typeof fetch = fetch) => {
const list = Array.from(queue.values()).slice(0, MAX_PENDING_RESOURCES);
+ const dispatched = new Map<string, ResourceRequest>();
for (const resource of list) {
const key = getResourceKey(resource);
queue.delete(key);
pending.set(key, resource);
+ dispatched.set(key, resource);
}
updatePending();
- const response = await fetch(restResourcesLoader(), {
- method: "POST",
- body: JSON.stringify(Array.from(pending.values())),
- });
- if (response.ok) {
+
+ try {
+ const response = await requestFetch(restResourcesLoader(), {
+ method: "POST",
+ body: JSON.stringify(list),
+ });
+ if (response.ok === false) {
+ return;
+ }
const results = new Map<string, unknown>(await response.json());
for (const [key, result] of results) {
- cache.set(key, result);
- pending.delete(key);
+ const request = dispatched.get(key);
+ if (request === undefined || knownRequests.has(key) === false) {
+ continue;
+ }
+ const separated = separateResourceDiagnostics({ request, result });
+ cache.set(key, separated.result);
+ if (separated.diagnostics === undefined) {
+ diagnosticsCache.delete(key);
+ } else {
+ diagnosticsCache.set(key, separated.diagnostics);
+ }
+ }
+ } catch {
+ console.error("Resource batch request failed");
+ } finally {
+ for (const [key, request] of dispatched) {
+ if (pending.get(key) === request) {
+ pending.delete(key);
+ }
}
+ updateCache();
+ updatePending();
+ // Restart loading until the queue is empty. An invalidation may have
+ // queued a fresh request while this batch was pending.
+ scheduleLoading();
}
- updateCache();
- updatePending();
- // restart loading until queue is empty
- scheduleLoading();
};
let timeoutId: undefined | number;
@@ -68,8 +99,9 @@ const scheduleLoading = () => {
timeoutId = window.setTimeout(loadResources, 1000);
};
-export const preloadResource = (resource: ResourceRequest) => {
+const preloadResource = (resource: ResourceRequest) => {
const key = getResourceKey(resource);
+ knownRequests.set(key, resource);
if (queue.has(key) || pending.has(key) || cache.has(key)) {
return;
}
@@ -79,9 +111,27 @@ export const preloadResource = (resource: ResourceRequest) => {
scheduleLoading();
};
+export const preloadResources = (resources: readonly ResourceRequest[]) => {
+ const currentKeys = new Set(resources.map(getResourceKey));
+ let pendingChanged = false;
+ for (const key of knownRequests.keys()) {
+ if (currentKeys.has(key) === false) {
+ knownRequests.delete(key);
+ pendingChanged = queue.delete(key) || pendingChanged;
+ }
+ }
+ if (pendingChanged) {
+ updatePending();
+ }
+ for (const resource of resources) {
+ preloadResource(resource);
+ }
+};
+
export const invalidateResource = (resource: ResourceRequest) => {
const key = getResourceKey(resource);
cache.delete(key);
+ diagnosticsCache.delete(key);
preloadResource(resource);
};
@@ -90,16 +140,19 @@ export const invalidateResource = (resource: ResourceRequest) => {
* Call this when assets are uploaded, deleted, or modified to refresh expressions using assets.
*/
export const invalidateAssets = () => {
- const url = "/$resources/assets";
- // System resources always use GET with no params/headers/body
- const systemResourceRequest: ResourceRequest = {
- name: "assets",
- method: "get",
- url,
- searchParams: [],
- headers: [],
- };
- invalidateResource(systemResourceRequest);
+ for (const [key, request] of knownRequests) {
+ if (isAssetsResourceRequest(request) === false) {
+ continue;
+ }
+ cache.delete(key);
+ diagnosticsCache.delete(key);
+ // Queue another load even when the previous request is still pending. The
+ // pending load may contain the asset state from before this mutation.
+ queue.set(key, request);
+ }
+ updateCache();
+ updatePending();
+ scheduleLoading();
};
export const computeResourceRequest = (
@@ -124,3 +177,5 @@ export const computeResourceRequest = (
}
return request;
};
+
+export const __testing__ = { loadResources };
diff --git a/apps/builder/app/shared/router-utils/path-utils.test.ts b/apps/builder/app/shared/router-utils/path-utils.test.ts
index f69adc1716..9bee1ab2ee 100644
--- a/apps/builder/app/shared/router-utils/path-utils.test.ts
+++ b/apps/builder/app/shared/router-utils/path-utils.test.ts
@@ -1,5 +1,5 @@
import { expect, test } from "vitest";
-import { builderPath, builderUrl } from "./path-utils";
+import { builderPath, builderUrl, restAssetsUploadPath } from "./path-utils";
test("includes an instance deep link in builder paths", () => {
expect(
@@ -23,3 +23,9 @@ test("includes an instance deep link in builder urls", () => {
"https://p-project-id.wstd.dev/?pageId=page-id&instanceId=instance-id"
);
});
+
+test("builds the asset upload item route", () => {
+ expect(restAssetsUploadPath({ name: "query", width: 100, height: 200 })).toBe(
+ "/rest/assets/uploads/query?width=100&height=200"
+ );
+});
diff --git a/apps/builder/app/shared/router-utils/path-utils.ts b/apps/builder/app/shared/router-utils/path-utils.ts
index 0da1acc33c..5efb678526 100644
--- a/apps/builder/app/shared/router-utils/path-utils.ts
+++ b/apps/builder/app/shared/router-utils/path-utils.ts
@@ -1,4 +1,5 @@
import type { AUTH_PROVIDERS } from "~/shared/session";
+import { getAssetUploadApiUrl } from "@webstudio-is/sdk/runtime";
import { getAuthorizationServerOrigin } from "./origins";
import type { BuilderMode } from "../nano-states/misc";
@@ -123,10 +124,6 @@ export const authPath = ({
provider: "google" | "github" | "dev";
}) => `/auth/${provider}`;
-export const restAssetsPath = () => {
- return `/rest/assets`;
-};
-
export const restAssetsUploadPath = ({
name,
width,
@@ -144,11 +141,12 @@ export const restAssetsUploadPath = ({
urlSearchParams.set("height", String(height));
}
- if (urlSearchParams.size > 0) {
- return `/rest/assets/${name}?${urlSearchParams.toString()}`;
+ const query = urlSearchParams.toString();
+ if (query !== "") {
+ return `${getAssetUploadApiUrl(name)}?${query}`;
}
- return `/rest/assets/${name}`;
+ return getAssetUploadApiUrl(name);
};
export const getCanvasUrl = () => {
diff --git a/apps/builder/app/shared/sync/patch/patch-service.server.test.ts b/apps/builder/app/shared/sync/patch/patch-service.server.test.ts
index f86206c3a8..ad7631b3af 100644
--- a/apps/builder/app/shared/sync/patch/patch-service.server.test.ts
+++ b/apps/builder/app/shared/sync/patch/patch-service.server.test.ts
@@ -16,7 +16,6 @@ vi.mock("./patch-auth.server", () => ({
createContentModeCapabilities,
createWriterContext: vi.fn(),
}));
-
import {
applyPatchRequest,
loadAuthorizedPatchState,
@@ -24,6 +23,23 @@ import {
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
import type { NormalizedPatchRequest } from "./patch-normalize.server";
+const applyPatchRequestForTest = (
+ context: AppContext,
+ patch: NormalizedPatchRequest
+) => applyPatchRequest(context, patch);
+
+const configuredResources = JSON.stringify([
+ {
+ id: "posts",
+ name: "Posts",
+ control: "system",
+ method: "post",
+ url: JSON.stringify("/$resources/assets"),
+ headers: [],
+ body: '{ query: { where: { all: [] }, sort: [], limit: 20, offset: 0, content: { mode: "none" } } }',
+ },
+]);
+
const buildRow = {
projectId: "project-1",
version: 3,
@@ -34,6 +50,7 @@ const buildRow = {
styleSourceSelections: JSON.stringify([]),
styles: JSON.stringify([]),
breakpoints: JSON.stringify([]),
+ resources: configuredResources,
};
const createContext = () => {
@@ -97,6 +114,227 @@ describe("applyPatchRequest", () => {
createContentModeCapabilities.mockClear();
});
+ test("applies a combined resource and asset patch without derived work", async () => {
+ const combinedEntry = {
+ ...patch.entries[0],
+ transaction: {
+ id: "tx-combined",
+ payload: [
+ { namespace: "resources", patches: [] },
+ {
+ namespace: "assets",
+ patches: [
+ {
+ op: "add",
+ path: ["asset-1"],
+ value: { id: "asset-1", name: "post.md" },
+ },
+ ],
+ },
+ ],
+ } as never,
+ };
+ authorizePatchEntries.mockResolvedValue({
+ authorized: [{ entry: combinedEntry, context: { writer: 1 } }],
+ rejected: [],
+ });
+ const nextResources = JSON.stringify([
+ {
+ id: "posts",
+ name: "Posts",
+ control: "system",
+ method: "post",
+ url: JSON.stringify("/$resources/assets"),
+ headers: [],
+ body: '{ query: { where: { all: [] }, sort: [], limit: 10, offset: 0, content: { mode: "none" } } }',
+ },
+ ]);
+ patchLoadedBuild.mockImplementation(async ({ build }) => ({
+ status: "ok",
+ version: 4,
+ build: { ...build, version: 4, resources: nextResources },
+ }));
+ await applyPatchRequestForTest(createContext(), {
+ ...patch,
+ entries: [combinedEntry],
+ });
+ });
+
+ test("applies asset-folder patches without derived work", async () => {
+ const folderEntry = {
+ ...patch.entries[0],
+ transaction: {
+ id: "tx-folder",
+ payload: [
+ {
+ namespace: "assetFolders",
+ patches: [
+ { op: "replace", path: ["folder-1", "name"], value: "News" },
+ ],
+ },
+ ],
+ } as never,
+ };
+ authorizePatchEntries.mockResolvedValue({
+ authorized: [{ entry: folderEntry, context: { writer: 1 } }],
+ rejected: [],
+ });
+ patchLoadedBuild.mockImplementation(async ({ build }) => ({
+ status: "ok",
+ version: 4,
+ build: { ...build, version: 4 },
+ }));
+
+ await expect(
+ applyPatchRequestForTest(createContext(), {
+ ...patch,
+ entries: [folderEntry],
+ })
+ ).resolves.toMatchObject({ status: "ok" });
+ });
+
+ test("applies added assets without derived work", async () => {
+ const assetEntry = {
+ ...patch.entries[0],
+ transaction: {
+ id: "tx-asset-add",
+ payload: [
+ {
+ namespace: "assets",
+ patches: [
+ {
+ op: "add",
+ path: ["asset-1"],
+ value: { id: "asset-1", name: "post.md" },
+ },
+ ],
+ },
+ ],
+ } as never,
+ };
+ authorizePatchEntries.mockResolvedValue({
+ authorized: [{ entry: assetEntry, context: { writer: 1 } }],
+ rejected: [],
+ });
+ patchLoadedBuild.mockImplementation(async ({ build }) => ({
+ status: "ok",
+ version: 4,
+ build: { ...build, version: 4 },
+ }));
+
+ await expect(
+ applyPatchRequestForTest(createContext(), {
+ ...patch,
+ entries: [assetEntry],
+ })
+ ).resolves.toMatchObject({ status: "ok" });
+ });
+
+ test("applies a swapped asset revision without derived work", async () => {
+ const assetEntry = {
+ ...patch.entries[0],
+ transaction: {
+ id: "tx-asset-revision",
+ payload: [
+ {
+ namespace: "assets",
+ patches: [
+ {
+ op: "replace",
+ path: ["asset-1", "name"],
+ value: "post-revision.md",
+ },
+ ],
+ },
+ ],
+ } as never,
+ };
+ authorizePatchEntries.mockResolvedValue({
+ authorized: [{ entry: assetEntry, context: { writer: 1 } }],
+ rejected: [],
+ });
+ patchLoadedBuild.mockImplementation(async ({ build }) => ({
+ status: "ok",
+ version: 4,
+ build: { ...build, version: 4 },
+ }));
+
+ await applyPatchRequestForTest(createContext(), {
+ ...patch,
+ entries: [assetEntry],
+ });
+ });
+
+ test("applies standard asset metadata changes without derived work", async () => {
+ const assetEntry = {
+ ...patch.entries[0],
+ transaction: {
+ id: "tx-asset-filename",
+ payload: [
+ {
+ namespace: "assets",
+ patches: [
+ {
+ op: "replace",
+ path: ["asset-1", "filename"],
+ value: "Public post title.md",
+ },
+ ],
+ },
+ ],
+ } as never,
+ };
+ authorizePatchEntries.mockResolvedValue({
+ authorized: [{ entry: assetEntry, context: { writer: 1 } }],
+ rejected: [],
+ });
+ patchLoadedBuild.mockImplementation(async ({ build }) => ({
+ status: "ok",
+ version: 4,
+ build: { ...build, version: 4 },
+ }));
+
+ await applyPatchRequestForTest(createContext(), {
+ ...patch,
+ entries: [assetEntry],
+ });
+ });
+
+ test("applies asset descriptions without derived work", async () => {
+ const assetEntry = {
+ ...patch.entries[0],
+ transaction: {
+ id: "tx-asset-description",
+ payload: [
+ {
+ namespace: "assets",
+ patches: [
+ {
+ op: "replace",
+ path: ["asset-1", "description"],
+ value: "Decorative description",
+ },
+ ],
+ },
+ ],
+ } as never,
+ };
+ authorizePatchEntries.mockResolvedValue({
+ authorized: [{ entry: assetEntry, context: { writer: 1 } }],
+ rejected: [],
+ });
+ patchLoadedBuild.mockImplementation(async ({ build }) => ({
+ status: "ok",
+ version: 4,
+ build: { ...build, version: 4 },
+ }));
+
+ await applyPatchRequestForTest(createContext(), {
+ ...patch,
+ entries: [assetEntry],
+ });
+ });
+
test("returns per-entry partial results while applying authorized entries", async () => {
authorizePatchEntries.mockResolvedValue({
authorized: [{ entry: patch.entries[1], context: { writer: 2 } }],
@@ -115,7 +353,7 @@ describe("applyPatchRequest", () => {
const context = createContext();
- const result = await applyPatchRequest(context, patch);
+ const result = await applyPatchRequestForTest(context, patch);
expect(createContentModeCapabilities).not.toHaveBeenCalled();
expect(context.selectedColumns).toEqual([
@@ -166,7 +404,7 @@ describe("applyPatchRequest", () => {
}));
const context = createContext();
- const result = await applyPatchRequest(context, patch);
+ const result = await applyPatchRequestForTest(context, patch);
expect(createContentModeCapabilities).toHaveBeenCalledWith({
breakpoints: JSON.stringify([]),
@@ -200,7 +438,7 @@ describe("applyPatchRequest", () => {
});
const context = createContext();
- const result = await applyPatchRequest(context, patch);
+ const result = await applyPatchRequestForTest(context, patch);
expect(context.selectedColumns).toEqual(["projectId, version"]);
expect(patchLoadedBuild).not.toHaveBeenCalled();
@@ -218,7 +456,7 @@ describe("applyPatchRequest", () => {
});
});
- test("loads only base patch columns for asset-only patches", async () => {
+ test("does not load resources for an asset-only patch", async () => {
const assetsPatch: NormalizedPatchRequest = {
...patch,
entries: [
@@ -240,7 +478,7 @@ describe("applyPatchRequest", () => {
}));
const context = createContext();
- const result = await applyPatchRequest(context, assetsPatch);
+ const result = await applyPatchRequestForTest(context, assetsPatch);
expect(context.selectedColumns).toEqual([
"projectId, version",
@@ -282,7 +520,7 @@ describe("applyPatchRequest", () => {
}))
.mockResolvedValueOnce({ status: "error", errors: "entry failed" });
- const result = await applyPatchRequest(createContext(), patch);
+ const result = await applyPatchRequestForTest(createContext(), patch);
expect(result).toEqual({
status: "partial",
@@ -319,7 +557,7 @@ describe("applyPatchRequest", () => {
build: { ...build, version: 5 },
}));
- const result = await applyPatchRequest(createContext(), patch);
+ const result = await applyPatchRequestForTest(createContext(), patch);
expect(patchLoadedBuild).toHaveBeenCalledTimes(2);
expect(patchLoadedBuild).toHaveBeenNthCalledWith(
@@ -383,7 +621,10 @@ describe("applyPatchRequest", () => {
build: { ...build, version: 4 },
}));
- const result = await applyPatchRequest(createContext(), duplicatePatch);
+ const result = await applyPatchRequestForTest(
+ createContext(),
+ duplicatePatch
+ );
expect(result).toEqual({
status: "partial",
@@ -418,9 +659,9 @@ describe("applyPatchRequest", () => {
}))
.mockRejectedValueOnce(new Error("PostgREST unavailable"));
- await expect(applyPatchRequest(createContext(), patch)).rejects.toThrow(
- "PostgREST unavailable"
- );
+ await expect(
+ applyPatchRequestForTest(createContext(), patch)
+ ).rejects.toThrow("PostgREST unavailable");
});
});
diff --git a/apps/builder/app/shared/sync/patch/patch-service.server.ts b/apps/builder/app/shared/sync/patch/patch-service.server.ts
index 2c2afdebc1..d554ce4805 100644
--- a/apps/builder/app/shared/sync/patch/patch-service.server.ts
+++ b/apps/builder/app/shared/sync/patch/patch-service.server.ts
@@ -40,8 +40,6 @@ const namespaceBuildColumns = {
breakpoints: ["breakpoints"],
instances: ["instances"],
props: ["props"],
- assets: [],
- assetFolders: [],
styleSourceSelections: ["styleSourceSelections"],
styleSources: ["styleSources"],
styles: ["styles"],
@@ -270,7 +268,6 @@ const applyAuthorizedEntries = async ({
);
if (batchResult.status === "ok") {
- currentBuild = batchResult.build;
return {
status: "ok" as const,
version: batchResult.version,
@@ -338,17 +335,18 @@ export const applyPatchRequest = async (
});
}
);
+ const build =
+ authorized.length === 0
+ ? undefined
+ : await loadBuildForPatch({
+ authorized,
+ context,
+ state,
+ buildId: patch.buildId,
+ });
const applied = await applyAuthorizedEntries({
authorized,
- build:
- authorized.length === 0
- ? undefined
- : await loadBuildForPatch({
- authorized,
- context,
- state,
- buildId: patch.buildId,
- }),
+ build,
patch,
version: authorized.length === 0 ? state.version : patch.clientVersion,
});
diff --git a/apps/builder/dev/backend.sh b/apps/builder/dev/backend.sh
index c65f2f2f3c..1d852a0467 100644
--- a/apps/builder/dev/backend.sh
+++ b/apps/builder/dev/backend.sh
@@ -23,6 +23,9 @@ builder_backend_migrations_fingerprint() {
-mindepth 1 -maxdepth 1 -type d -print
find packages/prisma-client/prisma/migrations \
-type f \( -name migration.sql -o -name migration.ts \) -print
+ printf '%s\n' \
+ apps/builder/dev/backend.sh \
+ apps/builder/docker-compose.yaml
} | LC_ALL=C sort | while IFS= read -r path; do
if [ -f "$path" ]; then
printf '%s ' "$path"
@@ -42,6 +45,10 @@ builder_backend_down() {
builder_compose down "$@"
}
+builder_backend_pull_db() {
+ builder_compose pull --policy missing db
+}
+
builder_backend_start_db() {
builder_compose up -d db
}
@@ -61,7 +68,7 @@ builder_backend_wait_for_postgrest() {
until {
local status
status="$(curl -s -o /dev/null -w "%{http_code}" "$url" || true)"
- [ "$status" -ge 200 ] && [ "$status" -lt 500 ]
+ [ "$status" -ge 200 ] && [ "$status" -lt 300 ]
}; do
if [ "$(date +%s)" -ge "$timeout_at" ]; then
echo "Timed out waiting for PostgREST" >&2
@@ -94,7 +101,7 @@ builder_backend_wait_for_db() {
builder_backend_schema_exists() {
[ "$(
builder_compose exec -T db \
- sh -c 'psql -q -U "$POSTGRES_USER" -d "$POSTGRES_DB" -tAc "SELECT to_regclass('\''public.\"Project\"'\'') IS NOT NULL"'
+ sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" psql -q -U "$POSTGRES_USER" -d "$POSTGRES_DB" -tAc "SELECT to_regclass('\''public.\"Project\"'\'') IS NOT NULL"'
)" = "t" ]
}
@@ -104,7 +111,7 @@ builder_backend_bootstrap_schema_snapshot() {
fi
builder_compose exec -T db \
- sh -c 'psql -q -U "$POSTGRES_USER" -d "$POSTGRES_DB" -v ON_ERROR_STOP=1' \
+ sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" psql -q -U "$POSTGRES_USER" -d "$POSTGRES_DB" -v ON_ERROR_STOP=1' \
<"$SCHEMA_SNAPSHOT" >/dev/null
}
@@ -148,8 +155,11 @@ builder_backend_bootstrap_if_empty() {
builder_backend_write_schema_snapshot() {
mkdir -p "$(dirname "$SCHEMA_SNAPSHOT")"
local temporary_snapshot="${SCHEMA_SNAPSHOT}.tmp.$$"
+ # Supabase initializes auth, storage, extensions, and other service schemas.
+ # Dump only the application-owned public schema so the snapshot can be
+ # restored into a fresh Supabase database without replacing its internals.
if builder_compose exec -T db \
- sh -c 'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" --schema-only --no-owner --no-privileges' \
+ sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" --schema=public --schema-only --clean --if-exists --no-owner --no-privileges' \
>"$temporary_snapshot"; then
mv "$temporary_snapshot" "$SCHEMA_SNAPSHOT"
else
diff --git a/apps/builder/docker-compose.local.yaml b/apps/builder/docker-compose.local.yaml
index 61ea53ff45..e176530e1c 100644
--- a/apps/builder/docker-compose.local.yaml
+++ b/apps/builder/docker-compose.local.yaml
@@ -1,7 +1,9 @@
services:
db:
volumes:
- - db:/var/lib/postgresql/data
+ # Do not mount the previous PostgreSQL 16 volume into Supabase PostgreSQL
+ # 15. Keep the old volume recoverable while initializing compatible data.
+ - supabase-db:/var/lib/postgresql/data
volumes:
- db:
+ supabase-db:
diff --git a/apps/builder/docker-compose.yaml b/apps/builder/docker-compose.yaml
index c5578e7cbb..0ff8e51471 100644
--- a/apps/builder/docker-compose.yaml
+++ b/apps/builder/docker-compose.yaml
@@ -1,9 +1,10 @@
services:
db:
- image: postgres:16
+ image: public.ecr.aws/supabase/postgres:15.8.1.085
environment:
+ # The image initializes its required roles as supabase_admin. Supplying
+ # POSTGRES_USER overrides that bootstrap user and breaks its init scripts.
POSTGRES_DB: ${POSTGRES_DB:?}
- POSTGRES_USER: ${POSTGRES_USER:?}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
ports:
- "${PGPORT:?}:5432"
diff --git a/apps/builder/docs/page-templates-plan.md b/apps/builder/docs/page-templates-plan.md
deleted file mode 100644
index de634904d0..0000000000
--- a/apps/builder/docs/page-templates-plan.md
+++ /dev/null
@@ -1,146 +0,0 @@
-# Page Templates Plan
-
-## Overview
-
-This plan introduces a **Page Templates** feature in two phases. V1 gives designers a way to define reusable page blueprints within a project. V2 extends the content editing experience by giving editors meaningful control over page settings and the ability to create new pages from those same templates.
-
----
-
-## V1 — Designer Page Templates
-
-### Summary
-
-Designers can define reusable, per-project page templates and use them as starting points when creating new pages. This gives design teams a way to enforce consistent structure and content patterns across pages in a project without starting from scratch every time.
-
-### Scope
-
-- **Designers only.** Templates are created, edited, and used exclusively in Design mode.
-- Pages created from a template are **independent copies** — there is no sync or update propagation between a template and the pages derived from it.
-- Templates are **per-project** artifacts — they are never published and do not appear in the site's public routes or sitemap.
-
----
-
-### What Is Built
-
-#### Template Storage
-
-- Templates live in a dedicated collection, separate from regular pages and folders.
-- They carry the same content as a page (name, title, meta, component tree) but intentionally have no page path, folder placement, or publish-related fields — templates are not live routes.
-- The templates collection is optional — existing projects without it load safely, treating the absence as an empty collection. No data migration is required.
-
-#### Data Safety Boundaries
-
-- Templates are fully excluded from sitemap generation, route resolution, and all published site output. Only the builder canvas is aware of them.
-- A clear type distinction between a template and a page is enforced throughout. All lookups that power the published site use this to ensure templates can never leak into public output.
-
-#### Pages Panel UI
-
-- A distinct **Page Templates** section appears in the Pages panel, below the folder tree.
-- The section and all template actions are only visible to designers in Design mode. Content mode users see nothing related to templates.
-- Each template row has two actions:
- - A **create button** (`+`) that opens a creation dialog pre-filled from the template's settings, where the designer confirms or adjusts all page settings before the page is created.
- - A **settings button** (`...`) that opens the template's settings panel.
-- A **New Template** button in the section header opens the new-template creation form.
-
-#### Creating a New Template
-
-- The creation form collects: template name, SEO title, description, exclude-from-search toggle, social image (URL or asset picker), and custom metadata key/value pairs.
-- All expression fields support variable binding via binding popovers — the same capability as regular page settings.
-- On creation, a blank component tree body is initialised as the template's root, ready for the designer to build out on the canvas.
-
-#### Editing Template Settings
-
-- The settings panel is identical in structure to the regular page settings form, minus path and folder fields.
-- Changes are auto-saved continuously with a short debounce; unsaved changes are also flushed immediately when the panel is closed.
-- The settings panel is rendered as read-only in content mode — no editor can accidentally modify a template's settings.
-
-#### Template CRUD
-
-- **Duplicate:** produces a full independent copy of the template's component tree and metadata, with a de-duplicated name.
-- **Delete:** removes the template and cleans up its entire component tree.
-
-#### Canvas Editing of Templates
-
-- Selecting a template loads it on the canvas for full design editing, just like a regular page.
-- The builder's awareness and selection systems are fully template-aware — navigating between templates and regular pages does not corrupt canvas state or selection.
-- Asset usage tracking and asset replacement both correctly account for assets referenced inside templates.
-
-#### Creating a Page from a Template (Core Engine)
-
-- The underlying copy logic performs a full deep-copy of the template's component tree, styles, properties, and data sources — all with fresh, unique identifiers.
-- All variable expressions in the copied metadata (title, description, social image URL, etc.) are correctly rebound to the new page's context, preserving the intended dynamic behaviour.
-- Name and path collisions with existing pages are resolved automatically.
-
-#### Create Page from Template Dialog
-
-- Clicking the create button (`+`) on a template row opens a creation dialog rather than immediately creating a page.
-- The dialog is pre-populated from the template's metadata and derives a unique path from the name automatically.
-- All standard page settings are available for the designer to review or adjust before confirming: name, path, title, description, language, SEO, social image, status, redirect, document type, and custom metadata.
-- The page is only created once the designer confirms, giving them full control over settings upfront.
-
-#### Template Row Context Menu
-
-- Template rows now have a right-click context menu with **Duplicate** and **Delete** actions, matching the behaviour of regular page and folder rows.
-- Duplicate produces a full independent copy of the template (component tree + metadata) with a de-duplicated name and navigates to the new template.
-- Delete shows a confirmation dialog before removing the template and its component tree, and navigates away if the deleted template was the active canvas view.
-
-#### Template Ordering
-
-- Templates can now be drag-and-drop reordered within the Page Templates section using the same sortable-item mechanism as the pages tree.
-- The new order is persisted immediately to the project data.
-
----
-
-### Limitations
-
-#### URL Display When Editing a Template
-
-- When a template is the active canvas view, any part of the UI that displays the current page's URL shows the root URL (`/`) as a placeholder, since templates have no path. This could be confusing.
-
-#### Visual Differentiation
-
-- The "New Template" button in the panel header reuses the same icon as the "New Page" button. Templates and pages are visually indistinguishable in the panel icon set.
-
----
-
-## V2 — Editor Page Creation & Limited Page Settings
-
-### Summary
-
-In the current product, content editors have no ability to modify page settings of any kind. V2 introduces a meaningful, safe subset of page-setting control for editors — both on existing pages and when creating new pages from templates. The guiding principle is that editors can change things that are purely editorial (names, readable text, simple toggles) but cannot touch anything that is dynamic, data-bound, or structural.
-
-### Scope
-
-- **Editors only.** Design mode behaviour is unchanged.
-- Editors gain access to a limited set of page settings on existing pages.
-- Editors gain the ability to create new pages from page templates, with the same limited settings available at creation time.
-- Editors retain their existing content-editing capability on the page canvas.
-
-### Editable Page Settings for Editors
-
-Editors should be able to edit the following page settings, subject to the conditions noted:
-
-| Setting | Editable by Editor? | Condition |
-| ------------------------------------ | ------------------- | -------------------------------------------------------------------------------------------------------------- |
-| Page name | Yes | Always |
-| Page path | Yes | Only if the path is a plain static value — not dynamic (no path parameters) and not using any variable binding |
-| Title | Yes | Only if the title is a plain static value and is not using any variable binding |
-| Search settings (SEO indexing, etc.) | Yes | Only if none of the search setting fields are using variable bindings |
-| Social image settings | Yes | Only if none of the social image fields are using any variable binding |
-| Redirect | No | — |
-| Custom metadata | No | — |
-| Any field with a variable binding | No | Binding presence locks the field for editors regardless of which setting it belongs to |
-
-**Key rule:** if a field has a binding attached, it is read-only for editors. The editor should be able to see the current value but not modify it. This prevents editors from accidentally breaking dynamic behaviour set up by the designer.
-
-### Editor Page Creation from Templates
-
-- Editors should see a **New Page** option that surfaces the project's available page templates.
-- The creation flow mirrors the designer flow, but is scoped to only the settings editors are permitted to set:
- - Page name
- - Page path (static only, following the same binding rule as above)
- - Title (if not bound)
- - Search settings (if not bound)
- - Social image settings (if not bound)
-- After creation, the editor lands on the new page with the template's content already in place and can immediately begin editing content within their existing permissions.
-- Editors cannot create blank pages — template-based creation is the only page creation path available to them. If no templates exist in the project, editors have no page creation option.
diff --git a/apps/builder/docs/test-cases.md b/apps/builder/docs/test-cases.md
deleted file mode 100644
index 15f2d12fa5..0000000000
--- a/apps/builder/docs/test-cases.md
+++ /dev/null
@@ -1,204 +0,0 @@
-1. Instance states
-
- - Hover over an instance, check if its outline is correct
- - Select an instance, check if its outline is correct
-
-1. Create instances by drag&drop
-
- - Drag a component over an instance - check if its outline is correct
- - Drag a Box over a Box, drop it - check if it was inserted in that Box
- - Drag a Box and place it before a Box - check if it was inserted before
- - Drag a Box and place it after a Box - check if it was inserted after
- - Drag a Box exactly between 2 Boxes - check if it was inserted between
- - Drag a Box to the bottom edge - check if parent Box gets outlined and insertion happened after that dragged over Box inside that outlined parent
- - Drag a Box to the top edge - check if parent Box gets outlined and insertion happened before that dragged over Box inside that outlined parent
- - Create a Box with child Boxes, where children are aligned vertically - repeat the tests above with trying to insert inside the new Box
- - Try to drop into a Paragraph - check that it's not allowed, and it drops next to the Paragraph instead
-
-1. Moving instances on canvas by drag&drop
-
- - Do the tests described in "Create instances by drag&drop",
- but instead of moving a component from the panel to the canvas,
- move a component that's already on the canvas
- - Create a Paragraph, and make a word in it Bold
- - drag & drop the Bold component - check that entire Paragraph have been moved
- - Try to drop a Box inside itself - check that it's not allowed, and it drops next to it instead
- - Create a Box that contains another Box, give the parent Box a padding
- - drag the parent Box, and try to put it inside the child Box - check that it's not allowed, and it drops next to the parent Box instead
-
-1. Create instance by clicking on a component
-
- - Make sure no instance is selected (no outline in the canvas)
- - Click on a component in the panel - check that it's inserted at the end of the root instance
- - Select an istance that can accept children (e.g. Box), by clicking on it on the canvas
- - Click on a component in the panel - check that it's inserted at the end of the selected instance
- - Select an instance that cannot accept children (e.g. Heading), but choose one that is not the last child of its parent
- - Click on a component in the panel - check that it's inserted in the parent of the selected instance, and that it's positioned right after the selected instance
-
-1. Styles apply
-
- - Select an instance
- - Change any style
- - See if it is applied
-
-1. Repeated shadow labels
-
- - Select an instance
- - Add at least 3 `box-shadow` layers in the style panel
- - Hide the first layer
- - Check that all `box-shadow` rows keep their full labels and only the hidden row is visually muted
- - Repeat the same flow with at least 3 `text-shadow` layers
- - Check that all `text-shadow` rows keep their full labels after hiding one layer
-
-1. Content editable components
-
- - Add any contenteditable component (heading, paragraph, text ...)
- - Check if you can drag&drop it on the canvas
- - Double click or press enter to enter editing mode
- - Press escape or click away to exit editing mode
- - Selecting with the mouse any char or word shows a menu abov
- e it
- - Selecting with keybord does the same
- - Changing selection using mouse or keyboard moves the menu
- - Menu shows correctly on very left, right, top corners
- - Typing renders typed characters as expected
- - After editing and unfocusing the component content stays the way it was changed
- - After each menu action unfocus component and see that content stays the way it was changed
- - Run every action on first, middle and last word, on first line on second line and on the last line
- - Enter multiline text, unfocus
- - Check every change is also saved when after reloading
- - Enter text and unfocus quickly - changes shouldn't disappear
- - Keep typing text for some time and see in network tab that we send only a few requests, not one for each char
-
-1. Breakpoints
-
- - Clicking on different breakpoints resizes the canvas
- - Click on Edit breakpoints shows you breakpoints editor
- - lets you change the breakpoint min-width value and it gets applied immediately on the canvas and on the width slider constraint
- - adding a new breakpoint adds it, lets you specify the value, works like every other breakpoint
- - Trash icon button shows confirmation dialog and upon confirmation
- - Delete button deletes the corresponding styles of that breakpoint entirely
- - Abort button doesn't delete and returns you to breakpoints editor
- - Done button returns you to breakpoints selector
- - Click anywhere outside of breakpoints closes breakpoints selector
- - Click on the canvas closes breakpoints selector
- - Styles added on each breakpoint are only applied to each breakpoint, verify that by resizing the canvas in preview mode
-
-1. Auth
-
- - Try to access the dashboard when not logged in to make sure you will be redirected to the login page
- - Open the login page when logged in to make sure you are redirected to the dashboard
- - Ensure you can view a built project in an incognito tab
- - Ensure you can view a forked project in an incognito tab
- - Click on dev login, add the first four characters in AUTH_SECRET value in the `.env` value and make sure user is authenticated and redirected to the dashboard
- - Click on dev login and write a wrong value to make sure you get an error message and stay in the login page.
- - Click on login with GitHub and make sure that you are redirected to the dashboard
- - Click on login with Google and make sure that you are redirected to the dashboard
-
-1. Default properties
-
- - Add a Box component to the canvas
- - Open Props panel
- - See the default tag is provided and can be modified
-
-1. Asset manager
-
- - Open assets panel
- - Upload an image
- - Check it loads and shows a progress bar
- - Delete an asset by clicking on the `x` icon and then the delete button in the tooltip
- - Click on an image asset to open asset details
- - Click the replace (reverse) icon button next to the download button
- - Select a new image file from the file picker
- - Check that the asset is replaced and the new image is shown
- - Check that all usages of the old asset (image `src` props, background image styles, favicon, social image) now reference the new file
- - Check that the original asset's filename is preserved on the new asset
- - Verify the replace button is absent for non-image assets (e.g. fonts)
-
-1. Navigator view settings
-
- - Initially navigator always shown
- - Check that `Menu > View > Undock navigator` is checked
- - Click on "Show navigator"
- - Navigator is now not shown
- - New tab was added that lets you open navigator
-
-1. Navigator keyboard interactions
-
- - Move focus to the navigator by clicking on a tree item
- - Check that pressing `arrow up` and `arrow down` changes the selected item
- - Check that you can expand and collapse the selected item using `arrow right`, `arrow left`, and `spacebar`
- - Check that pressing `delete` or `backspace` deletes the selected item
-
-1. Navigator drag&drop
-
- - Drag a tree item and put the cursor between some tree items
- - check that a line appeared between the tree items
- - check that after you drop, the dragged item moves between the tree items
- - Drag a tree item over an empty `Box` item,
- - check that an outline appears around the `Box` item,
- - check that when you drop, the dragged item moves inside the `Box` item
- - Drag a tree item over a non-empty but collapsed `Box` item
- - check that the `Box` item expands automatically when you hold over it
- - check that if you drop before it expands, the dragged item moves inside the `Box`, and becomes the last child
- - Drag a tree item over a `Heading` item, check that it doesn't allow you to drop inside a `Heading`
- - Make some text inside a `Heading` "bold" so that the `Heading` item in the tree gets a child item `Bold Text`
- - check that you cannot drag the `Bold Text` item
- - Start dragging a tree item but do not move the cursor vertically
- - check that by moving horizontally you're able to change how deeply the item is nested inside the tree
- - Drag an item between some tree items
- - check that moving the cursor horizontally allows you to change the depth of the placement indicator line
- - check that after you drop, the dragged item moves to the correct depth
- - Check that after a drag&drop the dragged item is the selected item
-
-1. Flex panel
-
- - Select an instance
- - Select "flexbox" as the selected display option.
- - Check if clicking a flex property icon opens a dropdown.
- - Check if all flexbox states are computable through the icons seletables.
- - Check if all flexbox states are computable through the grid.
- - Check if gap inputs work.
- - Check if tooltips are present on all icons(including gap input icons).
- - Check that tooltips have a first time interaction delay.
-
-1. Creating a new page
-
- - Open the pages panel
- - Click on the "New Page" button in the panel header
- - Enter a page name
- - Enter a page path
- - Click on the "Create" button
- - Check than the page is created and selected as the current page
- - Repeat the proccess and make sure it doens't allow you to create a page with an empty name or a path that's used for another page
-
-1. Deleting a page
-
- - Open the pages panel
- - Make sure you have pages other than the Home page, create one if you don't
- - Click on the menu icon of a page other than the Home page
- - Page settings should open
- - Click on the delete icon in the page settings header
- - Page settings should close
- - Page should disappear from the list
- - If the page was selected, the Home page should become selected instead
- - In the Home page settings, the delete icon should be absent
-
-1. Editing a page
-
- - Open the pages panel
- - Click on the menu icon of a page
- - Page settings should open
- - Change the page name
- - The name should change in the pages list as well (with a small delay)
- - Change the page path
- - Reload browser tab and open the page settings again and make sure your changes are persisted
-
-1. Preview mode
-
- - Enter preview mode from the top bar
- - Press `escape` while focus is outside the canvas
- - Check that preview mode exits and the builder UI is shown
- - Enter preview mode again
- - Press `escape` while interacting with the canvas
- - Check that preview mode stays active and the canvas handles the key press
diff --git a/apps/builder/e2e/db.ts b/apps/builder/e2e/db.ts
index 2cfbb3903d..2c021bcd19 100644
--- a/apps/builder/e2e/db.ts
+++ b/apps/builder/e2e/db.ts
@@ -65,7 +65,7 @@ export const resetDatabase = async () => {
"db",
"sh",
"-c",
- 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -v ON_ERROR_STOP=1 -c "$1"',
+ 'PGPASSWORD="$POSTGRES_PASSWORD" psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -v ON_ERROR_STOP=1 -c "$1"',
"sh",
sql,
],
diff --git a/apps/builder/e2e/flows/assets-panel.ts b/apps/builder/e2e/flows/assets-panel.ts
index 418eccb12a..1c4dd06889 100644
--- a/apps/builder/e2e/flows/assets-panel.ts
+++ b/apps/builder/e2e/flows/assets-panel.ts
@@ -47,7 +47,7 @@ export const createAssetFolder = async ({
await openAddAssetMenu(page);
await page.getByRole("menuitem", { name: "Create folder" }).click();
const dialog = page.getByRole("dialog", { name: "New folder" });
- await dialog.getByLabel("Folder", { exact: true }).fill(name);
+ await dialog.getByLabel("Name", { exact: true }).fill(name);
await Promise.all([
waitForChangeToBeSaved({ page }),
dialog.getByRole("button", { name: "Create folder" }).click(),
diff --git a/apps/builder/e2e/flows/data-variables.ts b/apps/builder/e2e/flows/data-variables.ts
index a33584e48b..93705cdfb2 100644
--- a/apps/builder/e2e/flows/data-variables.ts
+++ b/apps/builder/e2e/flows/data-variables.ts
@@ -140,11 +140,11 @@ export const createSystemResourceVariable = async ({
}: {
page: Page;
name: string;
- resource?: "Sitemap" | "Current Date" | "Assets";
+ resource?: "Sitemap" | "Current date" | "Assets";
}) => {
await openNewVariablePanel({ page });
await fillVariableName({ page, name });
- await selectVariableType({ page, next: "System Resource" });
+ await selectVariableType({ page, next: "System resource" });
if (resource !== "Sitemap") {
await getVariableForm(page)
.getByText("Resource", { exact: true })
diff --git a/apps/builder/e2e/flows/sync-status.ts b/apps/builder/e2e/flows/sync-status.ts
index 93e3c5f01b..bb2301924e 100644
--- a/apps/builder/e2e/flows/sync-status.ts
+++ b/apps/builder/e2e/flows/sync-status.ts
@@ -22,33 +22,6 @@ const getSyncStatusLabel = async (page: Page) =>
(await getSyncStatusDot(page).getAttribute("aria-label")) ??
"Sync status: error";
-const waitForAnySyncStatus = async ({
- page,
- statuses,
- timeout,
-}: {
- page: Page;
- statuses: SyncStatusDotStatus[];
- timeout: number;
-}) => {
- const handle = await page.waitForFunction(
- ({ selector, statuses }) => {
- const dot = document.querySelector<HTMLElement>(selector);
- const status = dot?.dataset.syncStatus;
- if (status === undefined) {
- return false;
- }
- if ((statuses as readonly string[]).includes(status)) {
- return status;
- }
- return false;
- },
- { selector: syncStatusDotSelector, statuses },
- { timeout }
- );
- return (await handle.jsonValue()) as SyncStatusDotStatus;
-};
-
export const waitForSyncStatus = async ({
page,
status,
@@ -72,23 +45,60 @@ export const waitForChangeToBeSaved = async ({
page: Page;
timeout?: number;
}) => {
- const firstStatus = await waitForAnySyncStatus({
- page,
- statuses: ["pending", "error"],
- timeout,
- });
-
- if (firstStatus === "error") {
- throw new Error(
- `Expected change to save, received ${await getSyncStatusLabel(page)}`
- );
- }
-
- const finalStatus = await waitForAnySyncStatus({
- page,
- statuses: ["saved", "idle", "error"],
- timeout,
- });
+ // Saves can pass through `pending` between Playwright polling frames. Observe
+ // old attribute values so a transient pending or error state is not missed.
+ const finalStatus = await page.evaluate(
+ ({ selector, timeout }) =>
+ new Promise<SyncStatusDotStatus>((resolve, reject) => {
+ let sawPending = false;
+ let timeoutId = 0;
+ const observer = new MutationObserver((records) => {
+ const status = document.querySelector<HTMLElement>(selector)?.dataset
+ .syncStatus as SyncStatusDotStatus | undefined;
+ if (
+ status === "pending" ||
+ records.some((record) => record.oldValue === "pending")
+ ) {
+ sawPending = true;
+ }
+ if (
+ status === "error" ||
+ records.some((record) => record.oldValue === "error")
+ ) {
+ window.clearTimeout(timeoutId);
+ observer.disconnect();
+ resolve("error");
+ return;
+ }
+ if (sawPending && (status === "saved" || status === "idle")) {
+ window.clearTimeout(timeoutId);
+ observer.disconnect();
+ resolve(status);
+ }
+ });
+ observer.observe(document, {
+ subtree: true,
+ childList: true,
+ attributes: true,
+ attributeFilter: ["data-sync-status"],
+ attributeOldValue: true,
+ });
+ timeoutId = window.setTimeout(() => {
+ observer.disconnect();
+ reject(new Error("Timed out waiting for a change to be saved"));
+ }, timeout);
+ const initialStatus = document.querySelector<HTMLElement>(selector)
+ ?.dataset.syncStatus as SyncStatusDotStatus | undefined;
+ if (initialStatus === "pending") {
+ sawPending = true;
+ } else if (initialStatus === "error") {
+ window.clearTimeout(timeoutId);
+ observer.disconnect();
+ resolve("error");
+ }
+ }),
+ { selector: syncStatusDotSelector, timeout }
+ );
if (finalStatus === "error") {
throw new Error(
diff --git a/apps/builder/e2e/run-local.sh b/apps/builder/e2e/run-local.sh
index 59d188df0e..de2ed0590d 100644
--- a/apps/builder/e2e/run-local.sh
+++ b/apps/builder/e2e/run-local.sh
@@ -11,7 +11,10 @@ export COMPOSE_PROJECT_NAME="${E2E_COMPOSE_PROJECT_NAME:-builder-e2e}"
export PGPORT="${E2E_PGPORT:-55434}"
export POSTGREST_PORT="${E2E_POSTGREST_PORT:-55435}"
export POSTGRES_DB="${E2E_POSTGRES_DB:-webstudio}"
-export POSTGRES_USER="${E2E_POSTGRES_USER:-postgres}"
+# The Supabase image owns the schema as this required bootstrap role. Callers
+# can still replace migration connections through E2E_DATABASE_URL and
+# E2E_DIRECT_URL.
+export POSTGRES_USER="supabase_admin"
export POSTGRES_PASSWORD="${E2E_POSTGRES_PASSWORD:-pass}"
export DATABASE_URL="${E2E_DATABASE_URL:-postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${PGPORT}/${POSTGRES_DB}?pgbouncer=true}"
export DIRECT_URL="${E2E_DIRECT_URL:-postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${PGPORT}/${POSTGRES_DB}}"
@@ -22,6 +25,7 @@ builder_backend_init
export E2E_DB_BOOTSTRAP="${E2E_DB_BOOTSTRAP:-auto}"
export E2E_GENERATE_PRISMA="${E2E_GENERATE_PRISMA:-auto}"
+export E2E_DOCKER_PULL_TIMEOUT_SECONDS="${E2E_DOCKER_PULL_TIMEOUT_SECONDS:-300}"
export E2E_DOCKER_TIMEOUT_SECONDS="${E2E_DOCKER_TIMEOUT_SECONDS:-60}"
export E2E_MIGRATIONS_TIMEOUT_SECONDS="${E2E_MIGRATIONS_TIMEOUT_SECONDS:-300}"
export E2E_INSTALL_PLAYWRIGHT="${E2E_INSTALL_PLAYWRIGHT:-auto}"
@@ -156,6 +160,9 @@ if [ "$E2E_RUN_TESTS" = "true" ]; then
validate_test_filter
fi
+run_step "pull e2e database image" "$E2E_DOCKER_PULL_TIMEOUT_SECONDS" \
+ builder_backend_pull_db
+
run_step "start e2e database" "$E2E_DOCKER_TIMEOUT_SECONDS" \
builder_backend_start_db
diff --git a/apps/builder/e2e/run.ts b/apps/builder/e2e/run.ts
index 562d3ff2a6..91f15e9009 100644
--- a/apps/builder/e2e/run.ts
+++ b/apps/builder/e2e/run.ts
@@ -45,19 +45,37 @@ for (const module of testModules) {
process.env.NODE_TLS_REJECT_UNAUTHORIZED ??= "0";
-const waitForHttp = async (url: string, timeoutMs: number) => {
+const waitForHttp = async ({
+ url,
+ timeoutMs,
+ isReady = (response) => response.status < 500,
+ consecutiveResponses = 1,
+}: {
+ url: string;
+ timeoutMs: number;
+ isReady?: (response: Response) => boolean;
+ consecutiveResponses?: number;
+}) => {
const startedAt = Date.now();
let lastError: unknown;
+ let readyResponses = 0;
while (Date.now() - startedAt < timeoutMs) {
try {
const response = await fetch(url);
await response.arrayBuffer();
- if (response.status < 500) {
+ if (isReady(response)) {
+ readyResponses += 1;
+ } else {
+ readyResponses = 0;
+ lastError = new Error(`Received HTTP ${response.status}`);
+ }
+ if (readyResponses === consecutiveResponses) {
return;
}
} catch (error) {
lastError = error;
+ readyResponses = 0;
}
await delay(250);
}
@@ -67,31 +85,17 @@ const waitForHttp = async (url: string, timeoutMs: number) => {
const waitForPostgrest = async () => {
const url = new URL("/User?select=*", postgrestUrl);
- const startedAt = Date.now();
- let successfulResponses = 0;
-
- while (Date.now() - startedAt < 30_000) {
- try {
- const response = await fetch(url.href);
- await response.arrayBuffer();
- if (response.status < 500) {
- successfulResponses += 1;
- if (successfulResponses === 3) {
- return;
- }
- }
- } catch {
- successfulResponses = 0;
- }
- await delay(250);
- }
-
- throw new Error(`Timed out waiting for ${url.href}`);
+ await waitForHttp({
+ url: url.href,
+ timeoutMs: 30_000,
+ isReady: (response) => response.ok,
+ consecutiveResponses: 3,
+ });
};
const waitForBuilder = async (child: ChildProcess) => {
await Promise.race([
- waitForHttp(builderUrl, 60_000),
+ waitForHttp({ url: builderUrl, timeoutMs: 60_000 }),
new Promise<never>((_, reject) => {
child.once("exit", (code, signal) => {
reject(
diff --git a/apps/builder/e2e/tests/data-variables-generated.[shard-2].[shard-5].[shard-6].e2e.ts b/apps/builder/e2e/tests/data-variables-generated.[shard-2].[shard-5].[shard-6].e2e.ts
index 6b222e5a46..98840c79b7 100644
--- a/apps/builder/e2e/tests/data-variables-generated.[shard-2].[shard-5].[shard-6].e2e.ts
+++ b/apps/builder/e2e/tests/data-variables-generated.[shard-2].[shard-5].[shard-6].e2e.ts
@@ -167,7 +167,7 @@ test("Generated app renders a Builder-created current-date system resource", asy
await createSystemResourceVariable({
page,
name: resourceName,
- resource: "Current Date",
+ resource: "Current date",
});
await reloadAndSelectContent({
page,
diff --git a/apps/builder/package.json b/apps/builder/package.json
index 6f3eabe9dc..abb0a8b736 100644
--- a/apps/builder/package.json
+++ b/apps/builder/package.json
@@ -67,6 +67,7 @@
"@tus/server": "^2.4.1",
"@unocss/core": "66.6.8",
"@vercel/remix": "2.15.3",
+ "@webstudio-is/content-engine": "workspace:0.0.0-webstudio-version",
"@webstudio-is/asset-uploader": "workspace:*",
"@webstudio-is/authorization-token": "workspace:*",
"@webstudio-is/css-data": "workspace:*",
@@ -74,6 +75,7 @@
"@webstudio-is/dashboard": "workspace:*",
"@webstudio-is/design-system": "workspace:*",
"@webstudio-is/domain": "workspace:*",
+ "@webstudio-is/expression": "workspace:*",
"@webstudio-is/feature-flags": "workspace:*",
"@webstudio-is/fonts": "workspace:*",
"@webstudio-is/html-data": "workspace:*",
@@ -86,6 +88,8 @@
"@webstudio-is/project-build": "workspace:*",
"@webstudio-is/project-migrations": "workspace:*",
"@webstudio-is/protocol": "workspace:*",
+ "@webstudio-is/query-builder": "workspace:*",
+ "@webstudio-is/query-builder-react": "workspace:*",
"@webstudio-is/react-sdk": "workspace:*",
"@webstudio-is/sdk": "workspace:*",
"@webstudio-is/sdk-components-animation": "workspace:*",
@@ -119,6 +123,7 @@
"nanostores": "^0.11.3",
"picocolors": "^1.1.1",
"pretty-bytes": "^6.1.1",
+ "range-parser": "^1.2.1",
"react": "18.3.0-canary-14898b6a9-20240318",
"react-dom": "18.3.0-canary-14898b6a9-20240318",
"react-error-boundary": "^5.0.0",
@@ -146,6 +151,7 @@
"@types/express": "^4.17.21",
"@types/react": "^18.2.70",
"@types/react-dom": "^18.2.25",
+ "@types/range-parser": "^1.2.7",
"@unocss/preset-wind4": "^66.6.8",
"@vitest/coverage-v8": "3.1.2",
"@webstudio-is/tsconfig": "workspace:*",
diff --git a/apps/builder/vite.config.ts b/apps/builder/vite.config.ts
index e3d15c24bc..9ccafc5486 100644
--- a/apps/builder/vite.config.ts
+++ b/apps/builder/vite.config.ts
@@ -130,6 +130,11 @@ export default defineConfig(({ mode }) => {
define: {
"process.env.NODE_ENV": JSON.stringify(mode),
},
+ build: {
+ commonjsOptions: {
+ esmExternals: true,
+ },
+ },
server: {
// Service-to-service OAuth token call requires a specified host for the wstd.dev domain
host: "wstd.dev",
diff --git a/fixtures/react-router-cloudflare/.webstudio/data.json b/fixtures/react-router-cloudflare/.webstudio/data.json
index 3e8cfd588f..78421acad5 100644
--- a/fixtures/react-router-cloudflare/.webstudio/data.json
+++ b/fixtures/react-router-cloudflare/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1l6lbch",
+ "bundleVersion": "bundle-1ikf7r3",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/react-router-cloudflare/app/__generated__/$resources.asset-query-manifest.ts b/fixtures/react-router-cloudflare/app/__generated__/$resources.asset-query-manifest.ts
new file mode 100644
index 0000000000..de56e5d216
--- /dev/null
+++ b/fixtures/react-router-cloudflare/app/__generated__/$resources.asset-query-manifest.ts
@@ -0,0 +1,2 @@
+export const assetQueryDeploymentId = "f565d527-32e7-4731-bc71-aca9e9574587";
+export const assetQueryDatabase = undefined;
diff --git a/fixtures/react-router-cloudflare/app/__generated__/$resources.asset-query-runtime.ts b/fixtures/react-router-cloudflare/app/__generated__/$resources.asset-query-runtime.ts
new file mode 100644
index 0000000000..4e56ef157a
--- /dev/null
+++ b/fixtures/react-router-cloudflare/app/__generated__/$resources.asset-query-runtime.ts
@@ -0,0 +1,5 @@
+export const createGeneratedAssetResourceFetch = async ({ fallback }: {
+ request: Request;
+ context: unknown;
+ fallback: typeof fetch;
+ }): Promise<typeof fetch> => fallback;
diff --git a/fixtures/react-router-cloudflare/app/__generated__/$resources.assets.ts b/fixtures/react-router-cloudflare/app/__generated__/$resources.assets.ts
index 6274fdf61e..2a5c535b6a 100644
--- a/fixtures/react-router-cloudflare/app/__generated__/$resources.assets.ts
+++ b/fixtures/react-router-cloudflare/app/__generated__/$resources.assets.ts
@@ -1,12 +1,14 @@
-export const assets = {
+
+ export const assets = {
"1d8bf4398f643f5333d415091507d778aaed62f28883642636cbed0be156a0ee": {
- url: "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
- width: 14,
- height: 16,
- },
- d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd: {
- url: "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
- width: 820,
- height: 985,
+ "url": "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
+ "width": 14,
+ "height": 16
},
+ "d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd": {
+ "url": "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
+ "width": 820,
+ "height": 985
+ }
};
+
\ No newline at end of file
diff --git a/fixtures/react-router-cloudflare/app/__generated__/$resources.redirects.ts b/fixtures/react-router-cloudflare/app/__generated__/$resources.redirects.ts
index a3ee44bd02..5872ee0507 100644
--- a/fixtures/react-router-cloudflare/app/__generated__/$resources.redirects.ts
+++ b/fixtures/react-router-cloudflare/app/__generated__/$resources.redirects.ts
@@ -1 +1,3 @@
-export const redirects = [];
+
+ export const redirects = [];
+
\ No newline at end of file
diff --git a/fixtures/react-router-cloudflare/app/__generated__/$resources.sitemap.xml.ts b/fixtures/react-router-cloudflare/app/__generated__/$resources.sitemap.xml.ts
index 181eac4621..5cb5b92832 100644
--- a/fixtures/react-router-cloudflare/app/__generated__/$resources.sitemap.xml.ts
+++ b/fixtures/react-router-cloudflare/app/__generated__/$resources.sitemap.xml.ts
@@ -1,6 +1,8 @@
-export const sitemap = [
+
+ export const sitemap = [
{
- path: "/",
- lastModified: "2025-01-04",
- },
+ "path": "/",
+ "lastModified": "2025-01-04"
+ }
];
+
\ No newline at end of file
diff --git a/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.server.tsx b/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.server.tsx
index 7742cba561..023be09459 100644
--- a/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.server.tsx
+++ b/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: 200,
redirect: "",
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.tsx b/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.tsx
index e73e1bd0f1..0c656158e7 100644
--- a/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.tsx
+++ b/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.tsx
@@ -1,44 +1,47 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import { Body as Body } from "@webstudio-is/sdk-components-react-router";
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body } from "@webstudio-is/sdk-components-react-router";
import { Heading as Heading } from "@webstudio-is/sdk-components-react/components";
-export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
-export const projectDomain = "cli-basic-test-d0osr";
+ export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
+
+
+
+ export const projectDomain = "cli-basic-test-d0osr";
+
+ export const lastPublished = "2025-01-04T11:01:50.091Z";
+
+ export const siteName = "";
-export const lastPublished = "2025-01-04T11:01:50.091Z";
+ export const breakpoints = [{"id":"rKj-wYctg3-GnqL3WHN9I"},{"id":"yH9RXhqCyeaVkrOt8MzLc","maxWidth":991},{"id":"8nSCZbeS002IVwkTdoIes","maxWidth":767},{"id":"7gBD25KrrbBdJYNDlhPz7","maxWidth":479}];
-export const siteName = "";
+ export const favIconAsset: string | undefined =
+ "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg";
-export const breakpoints = [
- { id: "rKj-wYctg3-GnqL3WHN9I" },
- { id: "yH9RXhqCyeaVkrOt8MzLc", maxWidth: 991 },
- { id: "8nSCZbeS002IVwkTdoIes", maxWidth: 767 },
- { id: "7gBD25KrrbBdJYNDlhPz7", maxWidth: 479 },
-];
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
-export const favIconAsset: string | undefined =
- "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg";
+ export const pageBackgroundImageAssets: string[] =
+ []
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
+
-export const pageBackgroundImageAssets: string[] = [];
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body`}>
+<Heading
+className={`w-heading`}>
+{"Another page"}
+</Heading>
+</Body>
+}
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body`}>
- <Heading className={`w-heading`}>{"Another page"}</Heading>
- </Body>
- );
-};
-export { Page };
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsx b/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsx
index 43532c4748..3896f613db 100644
--- a/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsx
+++ b/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: undefined,
redirect: undefined,
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/react-router-cloudflare/app/__generated__/_index.tsx b/fixtures/react-router-cloudflare/app/__generated__/_index.tsx
index 3064b027a9..ac16a8975d 100644
--- a/fixtures/react-router-cloudflare/app/__generated__/_index.tsx
+++ b/fixtures/react-router-cloudflare/app/__generated__/_index.tsx
@@ -1,73 +1,70 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import {
- Body as Body,
- Link as Link,
-} from "@webstudio-is/sdk-components-react-router";
-import {
- Heading as Heading,
- Text as Text,
- Image as Image,
-} from "@webstudio-is/sdk-components-react/components";
-
-export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
-
-export const projectVersion = 43;
-
-export const projectDomain = "cli-basic-test-d0osr";
-
-export const lastPublished = "2025-01-04T11:01:50.091Z";
-
-export const siteName = "";
-
-export const breakpoints = [
- { id: "rKj-wYctg3-GnqL3WHN9I" },
- { id: "yH9RXhqCyeaVkrOt8MzLc", maxWidth: 991 },
- { id: "8nSCZbeS002IVwkTdoIes", maxWidth: 767 },
- { id: "7gBD25KrrbBdJYNDlhPz7", maxWidth: 479 },
-];
-
-export const favIconAsset: string | undefined =
- "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg";
-
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
-
-export const pageBackgroundImageAssets: string[] = [];
-
-export const CustomCode = () => {
- return <></>;
-};
-
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body c1jaw2zx cbipm55 ctniqj4 ctgx88l`}>
- <Heading className={`w-heading`}>{"Simple Project to test CLI"}</Heading>
- <Text className={`w-text cn3rfux`}>
- {"Please don't change directly in the fixture"}
- </Text>
- <Link href={"/another-page"} className={`w-link`}>
- {"Test another page link"}
- </Link>
- <Image
- src={"/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg"}
- width={14}
- height={16}
- className={`w-image c161qeci`}
- />
- <Image
- src={"https://picsum.photos/id/237/100/100.jpg?blur=4&grayscale"}
- className={`w-image`}
- />
- </Body>
- );
-};
-
-export { Page };
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body, Link as Link } from "@webstudio-is/sdk-components-react-router";
+import { Heading as Heading, Text as Text, Image as Image } from "@webstudio-is/sdk-components-react/components";
+
+
+ export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
+
+ export const projectVersion = 43;
+
+ export const projectDomain = "cli-basic-test-d0osr";
+
+ export const lastPublished = "2025-01-04T11:01:50.091Z";
+
+ export const siteName = "";
+
+ export const breakpoints = [{"id":"rKj-wYctg3-GnqL3WHN9I"},{"id":"yH9RXhqCyeaVkrOt8MzLc","maxWidth":991},{"id":"8nSCZbeS002IVwkTdoIes","maxWidth":767},{"id":"7gBD25KrrbBdJYNDlhPz7","maxWidth":479}];
+
+ export const favIconAsset: string | undefined =
+ "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg";
+
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
+
+ export const pageBackgroundImageAssets: string[] =
+ []
+
+
+
+
+ export const CustomCode = () => {
+ return (<></>);
+ }
+
+
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body c1jaw2zx cbipm55 ctniqj4 ctgx88l`}>
+<Heading
+className={`w-heading`}>
+{"Simple Project to test CLI"}
+</Heading>
+<Text
+className={`w-text cn3rfux`}>
+{"Please don't change directly in the fixture"}
+</Text>
+<Link
+href={"/another-page"}
+className={`w-link`}>
+{"Test another page link"}
+</Link>
+<Image
+src={"/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg"}
+width={14}
+height={16}
+className={`w-image c161qeci`} />
+<Image
+src={"https://picsum.photos/id/237/100/100.jpg?blur=4&grayscale"}
+className={`w-image`} />
+</Body>
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/react-router-cloudflare/app/__generated__/index.css b/fixtures/react-router-cloudflare/app/__generated__/index.css
index bae88880bc..8df45a0874 100644
--- a/fixtures/react-router-cloudflare/app/__generated__/index.css
+++ b/fixtures/react-router-cloudflare/app/__generated__/index.css
@@ -8,49 +8,49 @@
font-size: 16px;
line-height: 1.2;
white-space: pre-wrap;
- white-space-collapse: preserve;
+ white-space-collapse: preserve
}
body.w-body {
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
- margin: 0;
+ margin: 0
}
h1.w-heading {
- box-sizing: border-box;
+ box-sizing: border-box
}
div.w-text {
box-sizing: border-box;
- min-height: 1em;
+ min-height: 1em
}
a.w-link {
box-sizing: border-box;
- display: inline-block;
+ display: inline-block
}
img.w-image {
box-sizing: border-box;
max-width: 100%;
display: block;
- height: auto;
+ height: auto
}
}
@media all {
.c1jaw2zx {
- display: flex;
+ display: flex
}
.cbipm55 {
- align-items: center;
+ align-items: center
}
.ctniqj4 {
- justify-content: center;
+ justify-content: center
}
.ctgx88l {
- flex-direction: column;
+ flex-direction: column
}
.cn3rfux {
- margin-bottom: 1em;
+ margin-bottom: 1em
}
.c161qeci {
- width: 400px;
+ width: 400px
}
-}
+}
\ No newline at end of file
diff --git a/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx b/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx
index b4af7cc103..ab5d17cf89 100644
--- a/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx
+++ b/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/react-router-cloudflare/app/routes/_index.tsx b/fixtures/react-router-cloudflare/app/routes/_index.tsx
index 867d53e46b..d8fe87ddaa 100644
--- a/fixtures/react-router-cloudflare/app/routes/_index.tsx
+++ b/fixtures/react-router-cloudflare/app/routes/_index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/react-router-docker/.webstudio/data.json b/fixtures/react-router-docker/.webstudio/data.json
index 3e8cfd588f..78421acad5 100644
--- a/fixtures/react-router-docker/.webstudio/data.json
+++ b/fixtures/react-router-docker/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1l6lbch",
+ "bundleVersion": "bundle-1ikf7r3",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/react-router-docker/app/__generated__/$resources.asset-query-manifest.ts b/fixtures/react-router-docker/app/__generated__/$resources.asset-query-manifest.ts
new file mode 100644
index 0000000000..de56e5d216
--- /dev/null
+++ b/fixtures/react-router-docker/app/__generated__/$resources.asset-query-manifest.ts
@@ -0,0 +1,2 @@
+export const assetQueryDeploymentId = "f565d527-32e7-4731-bc71-aca9e9574587";
+export const assetQueryDatabase = undefined;
diff --git a/fixtures/react-router-docker/app/__generated__/$resources.asset-query-runtime.ts b/fixtures/react-router-docker/app/__generated__/$resources.asset-query-runtime.ts
new file mode 100644
index 0000000000..4e56ef157a
--- /dev/null
+++ b/fixtures/react-router-docker/app/__generated__/$resources.asset-query-runtime.ts
@@ -0,0 +1,5 @@
+export const createGeneratedAssetResourceFetch = async ({ fallback }: {
+ request: Request;
+ context: unknown;
+ fallback: typeof fetch;
+ }): Promise<typeof fetch> => fallback;
diff --git a/fixtures/react-router-docker/app/__generated__/$resources.assets.ts b/fixtures/react-router-docker/app/__generated__/$resources.assets.ts
index 6274fdf61e..2a5c535b6a 100644
--- a/fixtures/react-router-docker/app/__generated__/$resources.assets.ts
+++ b/fixtures/react-router-docker/app/__generated__/$resources.assets.ts
@@ -1,12 +1,14 @@
-export const assets = {
+
+ export const assets = {
"1d8bf4398f643f5333d415091507d778aaed62f28883642636cbed0be156a0ee": {
- url: "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
- width: 14,
- height: 16,
- },
- d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd: {
- url: "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
- width: 820,
- height: 985,
+ "url": "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
+ "width": 14,
+ "height": 16
},
+ "d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd": {
+ "url": "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
+ "width": 820,
+ "height": 985
+ }
};
+
\ No newline at end of file
diff --git a/fixtures/react-router-docker/app/__generated__/$resources.redirects.ts b/fixtures/react-router-docker/app/__generated__/$resources.redirects.ts
index a3ee44bd02..5872ee0507 100644
--- a/fixtures/react-router-docker/app/__generated__/$resources.redirects.ts
+++ b/fixtures/react-router-docker/app/__generated__/$resources.redirects.ts
@@ -1 +1,3 @@
-export const redirects = [];
+
+ export const redirects = [];
+
\ No newline at end of file
diff --git a/fixtures/react-router-docker/app/__generated__/$resources.sitemap.xml.ts b/fixtures/react-router-docker/app/__generated__/$resources.sitemap.xml.ts
index 181eac4621..5cb5b92832 100644
--- a/fixtures/react-router-docker/app/__generated__/$resources.sitemap.xml.ts
+++ b/fixtures/react-router-docker/app/__generated__/$resources.sitemap.xml.ts
@@ -1,6 +1,8 @@
-export const sitemap = [
+
+ export const sitemap = [
{
- path: "/",
- lastModified: "2025-01-04",
- },
+ "path": "/",
+ "lastModified": "2025-01-04"
+ }
];
+
\ No newline at end of file
diff --git a/fixtures/react-router-docker/app/__generated__/[another-page]._index.server.tsx b/fixtures/react-router-docker/app/__generated__/[another-page]._index.server.tsx
index 7742cba561..023be09459 100644
--- a/fixtures/react-router-docker/app/__generated__/[another-page]._index.server.tsx
+++ b/fixtures/react-router-docker/app/__generated__/[another-page]._index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: 200,
redirect: "",
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/react-router-docker/app/__generated__/[another-page]._index.tsx b/fixtures/react-router-docker/app/__generated__/[another-page]._index.tsx
index e73e1bd0f1..0c656158e7 100644
--- a/fixtures/react-router-docker/app/__generated__/[another-page]._index.tsx
+++ b/fixtures/react-router-docker/app/__generated__/[another-page]._index.tsx
@@ -1,44 +1,47 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import { Body as Body } from "@webstudio-is/sdk-components-react-router";
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body } from "@webstudio-is/sdk-components-react-router";
import { Heading as Heading } from "@webstudio-is/sdk-components-react/components";
-export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
-export const projectDomain = "cli-basic-test-d0osr";
+ export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
+
+
+
+ export const projectDomain = "cli-basic-test-d0osr";
+
+ export const lastPublished = "2025-01-04T11:01:50.091Z";
+
+ export const siteName = "";
-export const lastPublished = "2025-01-04T11:01:50.091Z";
+ export const breakpoints = [{"id":"rKj-wYctg3-GnqL3WHN9I"},{"id":"yH9RXhqCyeaVkrOt8MzLc","maxWidth":991},{"id":"8nSCZbeS002IVwkTdoIes","maxWidth":767},{"id":"7gBD25KrrbBdJYNDlhPz7","maxWidth":479}];
-export const siteName = "";
+ export const favIconAsset: string | undefined =
+ "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg";
-export const breakpoints = [
- { id: "rKj-wYctg3-GnqL3WHN9I" },
- { id: "yH9RXhqCyeaVkrOt8MzLc", maxWidth: 991 },
- { id: "8nSCZbeS002IVwkTdoIes", maxWidth: 767 },
- { id: "7gBD25KrrbBdJYNDlhPz7", maxWidth: 479 },
-];
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
-export const favIconAsset: string | undefined =
- "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg";
+ export const pageBackgroundImageAssets: string[] =
+ []
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
+
-export const pageBackgroundImageAssets: string[] = [];
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body`}>
+<Heading
+className={`w-heading`}>
+{"Another page"}
+</Heading>
+</Body>
+}
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body`}>
- <Heading className={`w-heading`}>{"Another page"}</Heading>
- </Body>
- );
-};
-export { Page };
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/react-router-docker/app/__generated__/_index.server.tsx b/fixtures/react-router-docker/app/__generated__/_index.server.tsx
index 43532c4748..3896f613db 100644
--- a/fixtures/react-router-docker/app/__generated__/_index.server.tsx
+++ b/fixtures/react-router-docker/app/__generated__/_index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: undefined,
redirect: undefined,
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/react-router-docker/app/__generated__/_index.tsx b/fixtures/react-router-docker/app/__generated__/_index.tsx
index 3064b027a9..ac16a8975d 100644
--- a/fixtures/react-router-docker/app/__generated__/_index.tsx
+++ b/fixtures/react-router-docker/app/__generated__/_index.tsx
@@ -1,73 +1,70 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import {
- Body as Body,
- Link as Link,
-} from "@webstudio-is/sdk-components-react-router";
-import {
- Heading as Heading,
- Text as Text,
- Image as Image,
-} from "@webstudio-is/sdk-components-react/components";
-
-export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
-
-export const projectVersion = 43;
-
-export const projectDomain = "cli-basic-test-d0osr";
-
-export const lastPublished = "2025-01-04T11:01:50.091Z";
-
-export const siteName = "";
-
-export const breakpoints = [
- { id: "rKj-wYctg3-GnqL3WHN9I" },
- { id: "yH9RXhqCyeaVkrOt8MzLc", maxWidth: 991 },
- { id: "8nSCZbeS002IVwkTdoIes", maxWidth: 767 },
- { id: "7gBD25KrrbBdJYNDlhPz7", maxWidth: 479 },
-];
-
-export const favIconAsset: string | undefined =
- "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg";
-
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
-
-export const pageBackgroundImageAssets: string[] = [];
-
-export const CustomCode = () => {
- return <></>;
-};
-
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body c1jaw2zx cbipm55 ctniqj4 ctgx88l`}>
- <Heading className={`w-heading`}>{"Simple Project to test CLI"}</Heading>
- <Text className={`w-text cn3rfux`}>
- {"Please don't change directly in the fixture"}
- </Text>
- <Link href={"/another-page"} className={`w-link`}>
- {"Test another page link"}
- </Link>
- <Image
- src={"/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg"}
- width={14}
- height={16}
- className={`w-image c161qeci`}
- />
- <Image
- src={"https://picsum.photos/id/237/100/100.jpg?blur=4&grayscale"}
- className={`w-image`}
- />
- </Body>
- );
-};
-
-export { Page };
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body, Link as Link } from "@webstudio-is/sdk-components-react-router";
+import { Heading as Heading, Text as Text, Image as Image } from "@webstudio-is/sdk-components-react/components";
+
+
+ export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
+
+ export const projectVersion = 43;
+
+ export const projectDomain = "cli-basic-test-d0osr";
+
+ export const lastPublished = "2025-01-04T11:01:50.091Z";
+
+ export const siteName = "";
+
+ export const breakpoints = [{"id":"rKj-wYctg3-GnqL3WHN9I"},{"id":"yH9RXhqCyeaVkrOt8MzLc","maxWidth":991},{"id":"8nSCZbeS002IVwkTdoIes","maxWidth":767},{"id":"7gBD25KrrbBdJYNDlhPz7","maxWidth":479}];
+
+ export const favIconAsset: string | undefined =
+ "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg";
+
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
+
+ export const pageBackgroundImageAssets: string[] =
+ []
+
+
+
+
+ export const CustomCode = () => {
+ return (<></>);
+ }
+
+
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body c1jaw2zx cbipm55 ctniqj4 ctgx88l`}>
+<Heading
+className={`w-heading`}>
+{"Simple Project to test CLI"}
+</Heading>
+<Text
+className={`w-text cn3rfux`}>
+{"Please don't change directly in the fixture"}
+</Text>
+<Link
+href={"/another-page"}
+className={`w-link`}>
+{"Test another page link"}
+</Link>
+<Image
+src={"/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg"}
+width={14}
+height={16}
+className={`w-image c161qeci`} />
+<Image
+src={"https://picsum.photos/id/237/100/100.jpg?blur=4&grayscale"}
+className={`w-image`} />
+</Body>
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/react-router-docker/app/__generated__/index.css b/fixtures/react-router-docker/app/__generated__/index.css
index bae88880bc..8df45a0874 100644
--- a/fixtures/react-router-docker/app/__generated__/index.css
+++ b/fixtures/react-router-docker/app/__generated__/index.css
@@ -8,49 +8,49 @@
font-size: 16px;
line-height: 1.2;
white-space: pre-wrap;
- white-space-collapse: preserve;
+ white-space-collapse: preserve
}
body.w-body {
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
- margin: 0;
+ margin: 0
}
h1.w-heading {
- box-sizing: border-box;
+ box-sizing: border-box
}
div.w-text {
box-sizing: border-box;
- min-height: 1em;
+ min-height: 1em
}
a.w-link {
box-sizing: border-box;
- display: inline-block;
+ display: inline-block
}
img.w-image {
box-sizing: border-box;
max-width: 100%;
display: block;
- height: auto;
+ height: auto
}
}
@media all {
.c1jaw2zx {
- display: flex;
+ display: flex
}
.cbipm55 {
- align-items: center;
+ align-items: center
}
.ctniqj4 {
- justify-content: center;
+ justify-content: center
}
.ctgx88l {
- flex-direction: column;
+ flex-direction: column
}
.cn3rfux {
- margin-bottom: 1em;
+ margin-bottom: 1em
}
.c161qeci {
- width: 400px;
+ width: 400px
}
-}
+}
\ No newline at end of file
diff --git a/fixtures/react-router-docker/app/routes/[another-page]._index.tsx b/fixtures/react-router-docker/app/routes/[another-page]._index.tsx
index b4af7cc103..ab5d17cf89 100644
--- a/fixtures/react-router-docker/app/routes/[another-page]._index.tsx
+++ b/fixtures/react-router-docker/app/routes/[another-page]._index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/react-router-docker/app/routes/_index.tsx b/fixtures/react-router-docker/app/routes/_index.tsx
index 867d53e46b..d8fe87ddaa 100644
--- a/fixtures/react-router-docker/app/routes/_index.tsx
+++ b/fixtures/react-router-docker/app/routes/_index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/react-router-netlify/.webstudio/data.json b/fixtures/react-router-netlify/.webstudio/data.json
index 3e8cfd588f..78421acad5 100644
--- a/fixtures/react-router-netlify/.webstudio/data.json
+++ b/fixtures/react-router-netlify/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1l6lbch",
+ "bundleVersion": "bundle-1ikf7r3",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/react-router-netlify/app/__generated__/$resources.asset-query-manifest.ts b/fixtures/react-router-netlify/app/__generated__/$resources.asset-query-manifest.ts
new file mode 100644
index 0000000000..de56e5d216
--- /dev/null
+++ b/fixtures/react-router-netlify/app/__generated__/$resources.asset-query-manifest.ts
@@ -0,0 +1,2 @@
+export const assetQueryDeploymentId = "f565d527-32e7-4731-bc71-aca9e9574587";
+export const assetQueryDatabase = undefined;
diff --git a/fixtures/react-router-netlify/app/__generated__/$resources.asset-query-runtime.ts b/fixtures/react-router-netlify/app/__generated__/$resources.asset-query-runtime.ts
new file mode 100644
index 0000000000..4e56ef157a
--- /dev/null
+++ b/fixtures/react-router-netlify/app/__generated__/$resources.asset-query-runtime.ts
@@ -0,0 +1,5 @@
+export const createGeneratedAssetResourceFetch = async ({ fallback }: {
+ request: Request;
+ context: unknown;
+ fallback: typeof fetch;
+ }): Promise<typeof fetch> => fallback;
diff --git a/fixtures/react-router-netlify/app/__generated__/$resources.assets.ts b/fixtures/react-router-netlify/app/__generated__/$resources.assets.ts
index 6274fdf61e..2a5c535b6a 100644
--- a/fixtures/react-router-netlify/app/__generated__/$resources.assets.ts
+++ b/fixtures/react-router-netlify/app/__generated__/$resources.assets.ts
@@ -1,12 +1,14 @@
-export const assets = {
+
+ export const assets = {
"1d8bf4398f643f5333d415091507d778aaed62f28883642636cbed0be156a0ee": {
- url: "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
- width: 14,
- height: 16,
- },
- d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd: {
- url: "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
- width: 820,
- height: 985,
+ "url": "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
+ "width": 14,
+ "height": 16
},
+ "d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd": {
+ "url": "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
+ "width": 820,
+ "height": 985
+ }
};
+
\ No newline at end of file
diff --git a/fixtures/react-router-netlify/app/__generated__/$resources.redirects.ts b/fixtures/react-router-netlify/app/__generated__/$resources.redirects.ts
index a3ee44bd02..5872ee0507 100644
--- a/fixtures/react-router-netlify/app/__generated__/$resources.redirects.ts
+++ b/fixtures/react-router-netlify/app/__generated__/$resources.redirects.ts
@@ -1 +1,3 @@
-export const redirects = [];
+
+ export const redirects = [];
+
\ No newline at end of file
diff --git a/fixtures/react-router-netlify/app/__generated__/$resources.sitemap.xml.ts b/fixtures/react-router-netlify/app/__generated__/$resources.sitemap.xml.ts
index 181eac4621..5cb5b92832 100644
--- a/fixtures/react-router-netlify/app/__generated__/$resources.sitemap.xml.ts
+++ b/fixtures/react-router-netlify/app/__generated__/$resources.sitemap.xml.ts
@@ -1,6 +1,8 @@
-export const sitemap = [
+
+ export const sitemap = [
{
- path: "/",
- lastModified: "2025-01-04",
- },
+ "path": "/",
+ "lastModified": "2025-01-04"
+ }
];
+
\ No newline at end of file
diff --git a/fixtures/react-router-netlify/app/__generated__/[another-page]._index.server.tsx b/fixtures/react-router-netlify/app/__generated__/[another-page]._index.server.tsx
index 7742cba561..023be09459 100644
--- a/fixtures/react-router-netlify/app/__generated__/[another-page]._index.server.tsx
+++ b/fixtures/react-router-netlify/app/__generated__/[another-page]._index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: 200,
redirect: "",
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/react-router-netlify/app/__generated__/[another-page]._index.tsx b/fixtures/react-router-netlify/app/__generated__/[another-page]._index.tsx
index e73e1bd0f1..0c656158e7 100644
--- a/fixtures/react-router-netlify/app/__generated__/[another-page]._index.tsx
+++ b/fixtures/react-router-netlify/app/__generated__/[another-page]._index.tsx
@@ -1,44 +1,47 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import { Body as Body } from "@webstudio-is/sdk-components-react-router";
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body } from "@webstudio-is/sdk-components-react-router";
import { Heading as Heading } from "@webstudio-is/sdk-components-react/components";
-export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
-export const projectDomain = "cli-basic-test-d0osr";
+ export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
+
+
+
+ export const projectDomain = "cli-basic-test-d0osr";
+
+ export const lastPublished = "2025-01-04T11:01:50.091Z";
+
+ export const siteName = "";
-export const lastPublished = "2025-01-04T11:01:50.091Z";
+ export const breakpoints = [{"id":"rKj-wYctg3-GnqL3WHN9I"},{"id":"yH9RXhqCyeaVkrOt8MzLc","maxWidth":991},{"id":"8nSCZbeS002IVwkTdoIes","maxWidth":767},{"id":"7gBD25KrrbBdJYNDlhPz7","maxWidth":479}];
-export const siteName = "";
+ export const favIconAsset: string | undefined =
+ "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg";
-export const breakpoints = [
- { id: "rKj-wYctg3-GnqL3WHN9I" },
- { id: "yH9RXhqCyeaVkrOt8MzLc", maxWidth: 991 },
- { id: "8nSCZbeS002IVwkTdoIes", maxWidth: 767 },
- { id: "7gBD25KrrbBdJYNDlhPz7", maxWidth: 479 },
-];
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
-export const favIconAsset: string | undefined =
- "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg";
+ export const pageBackgroundImageAssets: string[] =
+ []
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
+
-export const pageBackgroundImageAssets: string[] = [];
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body`}>
+<Heading
+className={`w-heading`}>
+{"Another page"}
+</Heading>
+</Body>
+}
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body`}>
- <Heading className={`w-heading`}>{"Another page"}</Heading>
- </Body>
- );
-};
-export { Page };
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/react-router-netlify/app/__generated__/_index.server.tsx b/fixtures/react-router-netlify/app/__generated__/_index.server.tsx
index 43532c4748..3896f613db 100644
--- a/fixtures/react-router-netlify/app/__generated__/_index.server.tsx
+++ b/fixtures/react-router-netlify/app/__generated__/_index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: undefined,
redirect: undefined,
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/react-router-netlify/app/__generated__/_index.tsx b/fixtures/react-router-netlify/app/__generated__/_index.tsx
index 3064b027a9..ac16a8975d 100644
--- a/fixtures/react-router-netlify/app/__generated__/_index.tsx
+++ b/fixtures/react-router-netlify/app/__generated__/_index.tsx
@@ -1,73 +1,70 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import {
- Body as Body,
- Link as Link,
-} from "@webstudio-is/sdk-components-react-router";
-import {
- Heading as Heading,
- Text as Text,
- Image as Image,
-} from "@webstudio-is/sdk-components-react/components";
-
-export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
-
-export const projectVersion = 43;
-
-export const projectDomain = "cli-basic-test-d0osr";
-
-export const lastPublished = "2025-01-04T11:01:50.091Z";
-
-export const siteName = "";
-
-export const breakpoints = [
- { id: "rKj-wYctg3-GnqL3WHN9I" },
- { id: "yH9RXhqCyeaVkrOt8MzLc", maxWidth: 991 },
- { id: "8nSCZbeS002IVwkTdoIes", maxWidth: 767 },
- { id: "7gBD25KrrbBdJYNDlhPz7", maxWidth: 479 },
-];
-
-export const favIconAsset: string | undefined =
- "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg";
-
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
-
-export const pageBackgroundImageAssets: string[] = [];
-
-export const CustomCode = () => {
- return <></>;
-};
-
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body c1jaw2zx cbipm55 ctniqj4 ctgx88l`}>
- <Heading className={`w-heading`}>{"Simple Project to test CLI"}</Heading>
- <Text className={`w-text cn3rfux`}>
- {"Please don't change directly in the fixture"}
- </Text>
- <Link href={"/another-page"} className={`w-link`}>
- {"Test another page link"}
- </Link>
- <Image
- src={"/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg"}
- width={14}
- height={16}
- className={`w-image c161qeci`}
- />
- <Image
- src={"https://picsum.photos/id/237/100/100.jpg?blur=4&grayscale"}
- className={`w-image`}
- />
- </Body>
- );
-};
-
-export { Page };
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body, Link as Link } from "@webstudio-is/sdk-components-react-router";
+import { Heading as Heading, Text as Text, Image as Image } from "@webstudio-is/sdk-components-react/components";
+
+
+ export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
+
+ export const projectVersion = 43;
+
+ export const projectDomain = "cli-basic-test-d0osr";
+
+ export const lastPublished = "2025-01-04T11:01:50.091Z";
+
+ export const siteName = "";
+
+ export const breakpoints = [{"id":"rKj-wYctg3-GnqL3WHN9I"},{"id":"yH9RXhqCyeaVkrOt8MzLc","maxWidth":991},{"id":"8nSCZbeS002IVwkTdoIes","maxWidth":767},{"id":"7gBD25KrrbBdJYNDlhPz7","maxWidth":479}];
+
+ export const favIconAsset: string | undefined =
+ "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg";
+
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
+
+ export const pageBackgroundImageAssets: string[] =
+ []
+
+
+
+
+ export const CustomCode = () => {
+ return (<></>);
+ }
+
+
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body c1jaw2zx cbipm55 ctniqj4 ctgx88l`}>
+<Heading
+className={`w-heading`}>
+{"Simple Project to test CLI"}
+</Heading>
+<Text
+className={`w-text cn3rfux`}>
+{"Please don't change directly in the fixture"}
+</Text>
+<Link
+href={"/another-page"}
+className={`w-link`}>
+{"Test another page link"}
+</Link>
+<Image
+src={"/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg"}
+width={14}
+height={16}
+className={`w-image c161qeci`} />
+<Image
+src={"https://picsum.photos/id/237/100/100.jpg?blur=4&grayscale"}
+className={`w-image`} />
+</Body>
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/react-router-netlify/app/__generated__/index.css b/fixtures/react-router-netlify/app/__generated__/index.css
index bae88880bc..8df45a0874 100644
--- a/fixtures/react-router-netlify/app/__generated__/index.css
+++ b/fixtures/react-router-netlify/app/__generated__/index.css
@@ -8,49 +8,49 @@
font-size: 16px;
line-height: 1.2;
white-space: pre-wrap;
- white-space-collapse: preserve;
+ white-space-collapse: preserve
}
body.w-body {
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
- margin: 0;
+ margin: 0
}
h1.w-heading {
- box-sizing: border-box;
+ box-sizing: border-box
}
div.w-text {
box-sizing: border-box;
- min-height: 1em;
+ min-height: 1em
}
a.w-link {
box-sizing: border-box;
- display: inline-block;
+ display: inline-block
}
img.w-image {
box-sizing: border-box;
max-width: 100%;
display: block;
- height: auto;
+ height: auto
}
}
@media all {
.c1jaw2zx {
- display: flex;
+ display: flex
}
.cbipm55 {
- align-items: center;
+ align-items: center
}
.ctniqj4 {
- justify-content: center;
+ justify-content: center
}
.ctgx88l {
- flex-direction: column;
+ flex-direction: column
}
.cn3rfux {
- margin-bottom: 1em;
+ margin-bottom: 1em
}
.c161qeci {
- width: 400px;
+ width: 400px
}
-}
+}
\ No newline at end of file
diff --git a/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx b/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx
index b4af7cc103..ab5d17cf89 100644
--- a/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx
+++ b/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/react-router-netlify/app/routes/_index.tsx b/fixtures/react-router-netlify/app/routes/_index.tsx
index 867d53e46b..d8fe87ddaa 100644
--- a/fixtures/react-router-netlify/app/routes/_index.tsx
+++ b/fixtures/react-router-netlify/app/routes/_index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/react-router-vercel/.webstudio/data.json b/fixtures/react-router-vercel/.webstudio/data.json
index 3e8cfd588f..78421acad5 100644
--- a/fixtures/react-router-vercel/.webstudio/data.json
+++ b/fixtures/react-router-vercel/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1l6lbch",
+ "bundleVersion": "bundle-1ikf7r3",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/react-router-vercel/app/__generated__/$resources.asset-query-manifest.ts b/fixtures/react-router-vercel/app/__generated__/$resources.asset-query-manifest.ts
new file mode 100644
index 0000000000..de56e5d216
--- /dev/null
+++ b/fixtures/react-router-vercel/app/__generated__/$resources.asset-query-manifest.ts
@@ -0,0 +1,2 @@
+export const assetQueryDeploymentId = "f565d527-32e7-4731-bc71-aca9e9574587";
+export const assetQueryDatabase = undefined;
diff --git a/fixtures/react-router-vercel/app/__generated__/$resources.asset-query-runtime.ts b/fixtures/react-router-vercel/app/__generated__/$resources.asset-query-runtime.ts
new file mode 100644
index 0000000000..4e56ef157a
--- /dev/null
+++ b/fixtures/react-router-vercel/app/__generated__/$resources.asset-query-runtime.ts
@@ -0,0 +1,5 @@
+export const createGeneratedAssetResourceFetch = async ({ fallback }: {
+ request: Request;
+ context: unknown;
+ fallback: typeof fetch;
+ }): Promise<typeof fetch> => fallback;
diff --git a/fixtures/react-router-vercel/app/__generated__/$resources.assets.ts b/fixtures/react-router-vercel/app/__generated__/$resources.assets.ts
index 6274fdf61e..2a5c535b6a 100644
--- a/fixtures/react-router-vercel/app/__generated__/$resources.assets.ts
+++ b/fixtures/react-router-vercel/app/__generated__/$resources.assets.ts
@@ -1,12 +1,14 @@
-export const assets = {
+
+ export const assets = {
"1d8bf4398f643f5333d415091507d778aaed62f28883642636cbed0be156a0ee": {
- url: "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
- width: 14,
- height: 16,
- },
- d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd: {
- url: "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
- width: 820,
- height: 985,
+ "url": "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
+ "width": 14,
+ "height": 16
},
+ "d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd": {
+ "url": "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
+ "width": 820,
+ "height": 985
+ }
};
+
\ No newline at end of file
diff --git a/fixtures/react-router-vercel/app/__generated__/$resources.redirects.ts b/fixtures/react-router-vercel/app/__generated__/$resources.redirects.ts
index a3ee44bd02..5872ee0507 100644
--- a/fixtures/react-router-vercel/app/__generated__/$resources.redirects.ts
+++ b/fixtures/react-router-vercel/app/__generated__/$resources.redirects.ts
@@ -1 +1,3 @@
-export const redirects = [];
+
+ export const redirects = [];
+
\ No newline at end of file
diff --git a/fixtures/react-router-vercel/app/__generated__/$resources.sitemap.xml.ts b/fixtures/react-router-vercel/app/__generated__/$resources.sitemap.xml.ts
index 181eac4621..5cb5b92832 100644
--- a/fixtures/react-router-vercel/app/__generated__/$resources.sitemap.xml.ts
+++ b/fixtures/react-router-vercel/app/__generated__/$resources.sitemap.xml.ts
@@ -1,6 +1,8 @@
-export const sitemap = [
+
+ export const sitemap = [
{
- path: "/",
- lastModified: "2025-01-04",
- },
+ "path": "/",
+ "lastModified": "2025-01-04"
+ }
];
+
\ No newline at end of file
diff --git a/fixtures/react-router-vercel/app/__generated__/[another-page]._index.server.tsx b/fixtures/react-router-vercel/app/__generated__/[another-page]._index.server.tsx
index 7742cba561..023be09459 100644
--- a/fixtures/react-router-vercel/app/__generated__/[another-page]._index.server.tsx
+++ b/fixtures/react-router-vercel/app/__generated__/[another-page]._index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: 200,
redirect: "",
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/react-router-vercel/app/__generated__/[another-page]._index.tsx b/fixtures/react-router-vercel/app/__generated__/[another-page]._index.tsx
index e73e1bd0f1..0c656158e7 100644
--- a/fixtures/react-router-vercel/app/__generated__/[another-page]._index.tsx
+++ b/fixtures/react-router-vercel/app/__generated__/[another-page]._index.tsx
@@ -1,44 +1,47 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import { Body as Body } from "@webstudio-is/sdk-components-react-router";
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body } from "@webstudio-is/sdk-components-react-router";
import { Heading as Heading } from "@webstudio-is/sdk-components-react/components";
-export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
-export const projectDomain = "cli-basic-test-d0osr";
+ export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
+
+
+
+ export const projectDomain = "cli-basic-test-d0osr";
+
+ export const lastPublished = "2025-01-04T11:01:50.091Z";
+
+ export const siteName = "";
-export const lastPublished = "2025-01-04T11:01:50.091Z";
+ export const breakpoints = [{"id":"rKj-wYctg3-GnqL3WHN9I"},{"id":"yH9RXhqCyeaVkrOt8MzLc","maxWidth":991},{"id":"8nSCZbeS002IVwkTdoIes","maxWidth":767},{"id":"7gBD25KrrbBdJYNDlhPz7","maxWidth":479}];
-export const siteName = "";
+ export const favIconAsset: string | undefined =
+ "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg";
-export const breakpoints = [
- { id: "rKj-wYctg3-GnqL3WHN9I" },
- { id: "yH9RXhqCyeaVkrOt8MzLc", maxWidth: 991 },
- { id: "8nSCZbeS002IVwkTdoIes", maxWidth: 767 },
- { id: "7gBD25KrrbBdJYNDlhPz7", maxWidth: 479 },
-];
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
-export const favIconAsset: string | undefined =
- "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg";
+ export const pageBackgroundImageAssets: string[] =
+ []
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
+
-export const pageBackgroundImageAssets: string[] = [];
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body`}>
+<Heading
+className={`w-heading`}>
+{"Another page"}
+</Heading>
+</Body>
+}
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body`}>
- <Heading className={`w-heading`}>{"Another page"}</Heading>
- </Body>
- );
-};
-export { Page };
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/react-router-vercel/app/__generated__/_index.server.tsx b/fixtures/react-router-vercel/app/__generated__/_index.server.tsx
index 43532c4748..3896f613db 100644
--- a/fixtures/react-router-vercel/app/__generated__/_index.server.tsx
+++ b/fixtures/react-router-vercel/app/__generated__/_index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: undefined,
redirect: undefined,
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/react-router-vercel/app/__generated__/_index.tsx b/fixtures/react-router-vercel/app/__generated__/_index.tsx
index 3064b027a9..ac16a8975d 100644
--- a/fixtures/react-router-vercel/app/__generated__/_index.tsx
+++ b/fixtures/react-router-vercel/app/__generated__/_index.tsx
@@ -1,73 +1,70 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import {
- Body as Body,
- Link as Link,
-} from "@webstudio-is/sdk-components-react-router";
-import {
- Heading as Heading,
- Text as Text,
- Image as Image,
-} from "@webstudio-is/sdk-components-react/components";
-
-export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
-
-export const projectVersion = 43;
-
-export const projectDomain = "cli-basic-test-d0osr";
-
-export const lastPublished = "2025-01-04T11:01:50.091Z";
-
-export const siteName = "";
-
-export const breakpoints = [
- { id: "rKj-wYctg3-GnqL3WHN9I" },
- { id: "yH9RXhqCyeaVkrOt8MzLc", maxWidth: 991 },
- { id: "8nSCZbeS002IVwkTdoIes", maxWidth: 767 },
- { id: "7gBD25KrrbBdJYNDlhPz7", maxWidth: 479 },
-];
-
-export const favIconAsset: string | undefined =
- "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg";
-
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
-
-export const pageBackgroundImageAssets: string[] = [];
-
-export const CustomCode = () => {
- return <></>;
-};
-
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body c1jaw2zx cbipm55 ctniqj4 ctgx88l`}>
- <Heading className={`w-heading`}>{"Simple Project to test CLI"}</Heading>
- <Text className={`w-text cn3rfux`}>
- {"Please don't change directly in the fixture"}
- </Text>
- <Link href={"/another-page"} className={`w-link`}>
- {"Test another page link"}
- </Link>
- <Image
- src={"/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg"}
- width={14}
- height={16}
- className={`w-image c161qeci`}
- />
- <Image
- src={"https://picsum.photos/id/237/100/100.jpg?blur=4&grayscale"}
- className={`w-image`}
- />
- </Body>
- );
-};
-
-export { Page };
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body, Link as Link } from "@webstudio-is/sdk-components-react-router";
+import { Heading as Heading, Text as Text, Image as Image } from "@webstudio-is/sdk-components-react/components";
+
+
+ export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
+
+ export const projectVersion = 43;
+
+ export const projectDomain = "cli-basic-test-d0osr";
+
+ export const lastPublished = "2025-01-04T11:01:50.091Z";
+
+ export const siteName = "";
+
+ export const breakpoints = [{"id":"rKj-wYctg3-GnqL3WHN9I"},{"id":"yH9RXhqCyeaVkrOt8MzLc","maxWidth":991},{"id":"8nSCZbeS002IVwkTdoIes","maxWidth":767},{"id":"7gBD25KrrbBdJYNDlhPz7","maxWidth":479}];
+
+ export const favIconAsset: string | undefined =
+ "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg";
+
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
+
+ export const pageBackgroundImageAssets: string[] =
+ []
+
+
+
+
+ export const CustomCode = () => {
+ return (<></>);
+ }
+
+
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body c1jaw2zx cbipm55 ctniqj4 ctgx88l`}>
+<Heading
+className={`w-heading`}>
+{"Simple Project to test CLI"}
+</Heading>
+<Text
+className={`w-text cn3rfux`}>
+{"Please don't change directly in the fixture"}
+</Text>
+<Link
+href={"/another-page"}
+className={`w-link`}>
+{"Test another page link"}
+</Link>
+<Image
+src={"/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg"}
+width={14}
+height={16}
+className={`w-image c161qeci`} />
+<Image
+src={"https://picsum.photos/id/237/100/100.jpg?blur=4&grayscale"}
+className={`w-image`} />
+</Body>
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/react-router-vercel/app/__generated__/index.css b/fixtures/react-router-vercel/app/__generated__/index.css
index bae88880bc..8df45a0874 100644
--- a/fixtures/react-router-vercel/app/__generated__/index.css
+++ b/fixtures/react-router-vercel/app/__generated__/index.css
@@ -8,49 +8,49 @@
font-size: 16px;
line-height: 1.2;
white-space: pre-wrap;
- white-space-collapse: preserve;
+ white-space-collapse: preserve
}
body.w-body {
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
- margin: 0;
+ margin: 0
}
h1.w-heading {
- box-sizing: border-box;
+ box-sizing: border-box
}
div.w-text {
box-sizing: border-box;
- min-height: 1em;
+ min-height: 1em
}
a.w-link {
box-sizing: border-box;
- display: inline-block;
+ display: inline-block
}
img.w-image {
box-sizing: border-box;
max-width: 100%;
display: block;
- height: auto;
+ height: auto
}
}
@media all {
.c1jaw2zx {
- display: flex;
+ display: flex
}
.cbipm55 {
- align-items: center;
+ align-items: center
}
.ctniqj4 {
- justify-content: center;
+ justify-content: center
}
.ctgx88l {
- flex-direction: column;
+ flex-direction: column
}
.cn3rfux {
- margin-bottom: 1em;
+ margin-bottom: 1em
}
.c161qeci {
- width: 400px;
+ width: 400px
}
-}
+}
\ No newline at end of file
diff --git a/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx b/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx
index b4af7cc103..ab5d17cf89 100644
--- a/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx
+++ b/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/react-router-vercel/app/routes/_index.tsx b/fixtures/react-router-vercel/app/routes/_index.tsx
index 867d53e46b..d8fe87ddaa 100644
--- a/fixtures/react-router-vercel/app/routes/_index.tsx
+++ b/fixtures/react-router-vercel/app/routes/_index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/ssg-cloudflare-pages/.webstudio/data.json b/fixtures/ssg-cloudflare-pages/.webstudio/data.json
index 3bcf267907..c87376c6d0 100644
--- a/fixtures/ssg-cloudflare-pages/.webstudio/data.json
+++ b/fixtures/ssg-cloudflare-pages/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1l6lbch",
+ "bundleVersion": "bundle-1ikf7r3",
"build": {
"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.asset-query-manifest.ts b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.asset-query-manifest.ts
new file mode 100644
index 0000000000..3ca2291fd2
--- /dev/null
+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.asset-query-manifest.ts
@@ -0,0 +1,2 @@
+export const assetQueryDeploymentId = "a2e8de30-03d5-4514-a3a6-406b3266a3af";
+export const assetQueryDatabase = undefined;
diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.asset-query-runtime.ts b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.asset-query-runtime.ts
new file mode 100644
index 0000000000..4e56ef157a
--- /dev/null
+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.asset-query-runtime.ts
@@ -0,0 +1,5 @@
+export const createGeneratedAssetResourceFetch = async ({ fallback }: {
+ request: Request;
+ context: unknown;
+ fallback: typeof fetch;
+ }): Promise<typeof fetch> => fallback;
diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.assets.ts b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.assets.ts
index 6274fdf61e..2a5c535b6a 100644
--- a/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.assets.ts
+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.assets.ts
@@ -1,12 +1,14 @@
-export const assets = {
+
+ export const assets = {
"1d8bf4398f643f5333d415091507d778aaed62f28883642636cbed0be156a0ee": {
- url: "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
- width: 14,
- height: 16,
- },
- d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd: {
- url: "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
- width: 820,
- height: 985,
+ "url": "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
+ "width": 14,
+ "height": 16
},
+ "d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd": {
+ "url": "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
+ "width": 820,
+ "height": 985
+ }
};
+
\ No newline at end of file
diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.redirects.ts b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.redirects.ts
index a3ee44bd02..5872ee0507 100644
--- a/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.redirects.ts
+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.redirects.ts
@@ -1 +1,3 @@
-export const redirects = [];
+
+ export const redirects = [];
+
\ No newline at end of file
diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.sitemap.xml.ts b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.sitemap.xml.ts
index 9b3f4dfa6d..2853d60abb 100644
--- a/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.sitemap.xml.ts
+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.sitemap.xml.ts
@@ -1,6 +1,8 @@
-export const sitemap = [
+
+ export const sitemap = [
{
- path: "/",
- lastModified: "2024-07-29",
- },
+ "path": "/",
+ "lastModified": "2024-07-29"
+ }
];
+
\ No newline at end of file
diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.server.tsx b/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.server.tsx
index 7742cba561..023be09459 100644
--- a/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.server.tsx
+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: 200,
redirect: "",
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.tsx b/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.tsx
index 035cbcadbd..52f066251c 100644
--- a/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.tsx
+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.tsx
@@ -1,45 +1,46 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import {
- Body as Body,
- Heading as Heading,
-} from "@webstudio-is/sdk-components-react/components";
-export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body, Heading as Heading } from "@webstudio-is/sdk-components-react/components";
-export const projectDomain = "cli-basic-test-d0osr";
-export const lastPublished = "2024-07-29T12:50:07.515Z";
+ export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
-export const siteName = "";
+
-export const breakpoints = [
- { id: "rKj-wYctg3-GnqL3WHN9I" },
- { id: "yH9RXhqCyeaVkrOt8MzLc", maxWidth: 991 },
- { id: "8nSCZbeS002IVwkTdoIes", maxWidth: 767 },
- { id: "7gBD25KrrbBdJYNDlhPz7", maxWidth: 479 },
-];
+ export const projectDomain = "cli-basic-test-d0osr";
-export const favIconAsset: string | undefined = undefined;
+ export const lastPublished = "2024-07-29T12:50:07.515Z";
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
+ export const siteName = "";
-export const pageBackgroundImageAssets: string[] = [];
+ export const breakpoints = [{"id":"rKj-wYctg3-GnqL3WHN9I"},{"id":"yH9RXhqCyeaVkrOt8MzLc","maxWidth":991},{"id":"8nSCZbeS002IVwkTdoIes","maxWidth":767},{"id":"7gBD25KrrbBdJYNDlhPz7","maxWidth":479}];
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body`}>
- <Heading className={`w-heading`}>{"Another page"}</Heading>
- </Body>
- );
-};
+ export const favIconAsset: string | undefined =
+ undefined;
-export { Page };
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
+
+ export const pageBackgroundImageAssets: string[] =
+ []
+
+
+
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body`}>
+<Heading
+className={`w-heading`}>
+{"Another page"}
+</Heading>
+</Body>
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsx b/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsx
index 43532c4748..3896f613db 100644
--- a/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsx
+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: undefined,
redirect: undefined,
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/_index.tsx b/fixtures/ssg-cloudflare-pages/app/__generated__/_index.tsx
index fe06a3d837..1cfe1a8dd7 100644
--- a/fixtures/ssg-cloudflare-pages/app/__generated__/_index.tsx
+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/_index.tsx
@@ -1,70 +1,69 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import {
- Body as Body,
- Heading as Heading,
- Text as Text,
- Link as Link,
- Image as Image,
-} from "@webstudio-is/sdk-components-react/components";
-
-export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
-
-export const projectVersion = 38;
-
-export const projectDomain = "cli-basic-test-d0osr";
-
-export const lastPublished = "2024-07-29T12:50:07.515Z";
-
-export const siteName = "";
-
-export const breakpoints = [
- { id: "rKj-wYctg3-GnqL3WHN9I" },
- { id: "yH9RXhqCyeaVkrOt8MzLc", maxWidth: 991 },
- { id: "8nSCZbeS002IVwkTdoIes", maxWidth: 767 },
- { id: "7gBD25KrrbBdJYNDlhPz7", maxWidth: 479 },
-];
-
-export const favIconAsset: string | undefined = undefined;
-
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
-
-export const pageBackgroundImageAssets: string[] = [];
-
-export const CustomCode = () => {
- return <></>;
-};
-
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body c1jaw2zx cbipm55 ctniqj4 ctgx88l`}>
- <Heading className={`w-heading`}>{"Simple Project to test CLI"}</Heading>
- <Text className={`w-text cn3rfux`}>
- {"Please don't change directly in the fixture"}
- </Text>
- <Link href={"/another-page"} className={`w-link`}>
- {"Test another page link"}
- </Link>
- <Image
- src={"/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg"}
- width={14}
- height={16}
- className={`w-image c161qeci`}
- />
- <Image
- src={"https://picsum.photos/id/237/100/100.jpg?blur=4&grayscale"}
- className={`w-image`}
- />
- </Body>
- );
-};
-
-export { Page };
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body, Heading as Heading, Text as Text, Link as Link, Image as Image } from "@webstudio-is/sdk-components-react/components";
+
+
+ export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
+
+ export const projectVersion = 38;
+
+ export const projectDomain = "cli-basic-test-d0osr";
+
+ export const lastPublished = "2024-07-29T12:50:07.515Z";
+
+ export const siteName = "";
+
+ export const breakpoints = [{"id":"rKj-wYctg3-GnqL3WHN9I"},{"id":"yH9RXhqCyeaVkrOt8MzLc","maxWidth":991},{"id":"8nSCZbeS002IVwkTdoIes","maxWidth":767},{"id":"7gBD25KrrbBdJYNDlhPz7","maxWidth":479}];
+
+ export const favIconAsset: string | undefined =
+ undefined;
+
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
+
+ export const pageBackgroundImageAssets: string[] =
+ []
+
+
+
+
+ export const CustomCode = () => {
+ return (<></>);
+ }
+
+
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body c1jaw2zx cbipm55 ctniqj4 ctgx88l`}>
+<Heading
+className={`w-heading`}>
+{"Simple Project to test CLI"}
+</Heading>
+<Text
+className={`w-text cn3rfux`}>
+{"Please don't change directly in the fixture"}
+</Text>
+<Link
+href={"/another-page"}
+className={`w-link`}>
+{"Test another page link"}
+</Link>
+<Image
+src={"/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg"}
+width={14}
+height={16}
+className={`w-image c161qeci`} />
+<Image
+src={"https://picsum.photos/id/237/100/100.jpg?blur=4&grayscale"}
+className={`w-image`} />
+</Body>
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/index.css b/fixtures/ssg-cloudflare-pages/app/__generated__/index.css
index bae88880bc..8df45a0874 100644
--- a/fixtures/ssg-cloudflare-pages/app/__generated__/index.css
+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/index.css
@@ -8,49 +8,49 @@
font-size: 16px;
line-height: 1.2;
white-space: pre-wrap;
- white-space-collapse: preserve;
+ white-space-collapse: preserve
}
body.w-body {
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
- margin: 0;
+ margin: 0
}
h1.w-heading {
- box-sizing: border-box;
+ box-sizing: border-box
}
div.w-text {
box-sizing: border-box;
- min-height: 1em;
+ min-height: 1em
}
a.w-link {
box-sizing: border-box;
- display: inline-block;
+ display: inline-block
}
img.w-image {
box-sizing: border-box;
max-width: 100%;
display: block;
- height: auto;
+ height: auto
}
}
@media all {
.c1jaw2zx {
- display: flex;
+ display: flex
}
.cbipm55 {
- align-items: center;
+ align-items: center
}
.ctniqj4 {
- justify-content: center;
+ justify-content: center
}
.ctgx88l {
- flex-direction: column;
+ flex-direction: column
}
.cn3rfux {
- margin-bottom: 1em;
+ margin-bottom: 1em
}
.c161qeci {
- width: 400px;
+ width: 400px
}
-}
+}
\ No newline at end of file
diff --git a/fixtures/ssg-cloudflare-pages/app/asset-resource-fetch.ts b/fixtures/ssg-cloudflare-pages/app/asset-resource-fetch.ts
new file mode 100644
index 0000000000..fda7a44b64
--- /dev/null
+++ b/fixtures/ssg-cloudflare-pages/app/asset-resource-fetch.ts
@@ -0,0 +1,4 @@
+export const createSsgAssetResourceFetch =
+ (_options: unknown) =>
+ async (_input: RequestInfo | URL, _init?: RequestInit) =>
+ undefined;
diff --git a/fixtures/ssg-cloudflare-pages/pages/another-page/+data.ts b/fixtures/ssg-cloudflare-pages/pages/another-page/+data.ts
index 35c8bd18f6..a6b39df159 100644
--- a/fixtures/ssg-cloudflare-pages/pages/another-page/+data.ts
+++ b/fixtures/ssg-cloudflare-pages/pages/another-page/+data.ts
@@ -5,8 +5,26 @@ import {
getResources,
} from "../../app/__generated__/[another-page]._index.server";
import { assets } from "../../app/__generated__/$resources.assets";
+import {
+ assetQueryDeploymentId,
+ assetQueryDatabase,
+} from "../../app/__generated__/$resources.asset-query-manifest";
+import { createSsgAssetResourceFetch } from "../../app/asset-resource-fetch";
+
+const fetchAssetResource =
+ assetQueryDatabase === undefined
+ ? undefined
+ : createSsgAssetResourceFetch({
+ deploymentId: assetQueryDeploymentId,
+ artifact: assetQueryDatabase,
+ runtimeAssets: assets,
+ });
-const customFetch: typeof fetch = (input, init) => {
+const customFetch: typeof fetch = async (input, init) => {
+ const assetResourceResponse = await fetchAssetResource?.(input, init);
+ if (assetResourceResponse !== undefined) {
+ return assetResourceResponse;
+ }
if (typeof input !== "string") {
return fetch(input, init);
}
@@ -26,13 +44,7 @@ const customFetch: typeof fetch = (input, init) => {
};
const response = new Response(JSON.stringify(data));
response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
+ return response;
}
return fetch(input, init);
@@ -55,7 +67,8 @@ export const data = async (pageContext: PageContextServer) => {
const resources = await loadResources(
customFetch,
- getResources({ system }).data
+ getResources({ system }).data,
+ url
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/ssg-cloudflare-pages/pages/index/+data.ts b/fixtures/ssg-cloudflare-pages/pages/index/+data.ts
index 8f86daf8a5..41189eeabd 100644
--- a/fixtures/ssg-cloudflare-pages/pages/index/+data.ts
+++ b/fixtures/ssg-cloudflare-pages/pages/index/+data.ts
@@ -5,8 +5,26 @@ import {
getResources,
} from "../../app/__generated__/_index.server";
import { assets } from "../../app/__generated__/$resources.assets";
+import {
+ assetQueryDeploymentId,
+ assetQueryDatabase,
+} from "../../app/__generated__/$resources.asset-query-manifest";
+import { createSsgAssetResourceFetch } from "../../app/asset-resource-fetch";
+
+const fetchAssetResource =
+ assetQueryDatabase === undefined
+ ? undefined
+ : createSsgAssetResourceFetch({
+ deploymentId: assetQueryDeploymentId,
+ artifact: assetQueryDatabase,
+ runtimeAssets: assets,
+ });
-const customFetch: typeof fetch = (input, init) => {
+const customFetch: typeof fetch = async (input, init) => {
+ const assetResourceResponse = await fetchAssetResource?.(input, init);
+ if (assetResourceResponse !== undefined) {
+ return assetResourceResponse;
+ }
if (typeof input !== "string") {
return fetch(input, init);
}
@@ -26,13 +44,7 @@ const customFetch: typeof fetch = (input, init) => {
};
const response = new Response(JSON.stringify(data));
response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
+ return response;
}
return fetch(input, init);
@@ -55,7 +67,8 @@ export const data = async (pageContext: PageContextServer) => {
const resources = await loadResources(
customFetch,
- getResources({ system }).data
+ getResources({ system }).data,
+ url
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/ssg-cloudflare-pages/vite.config.ts b/fixtures/ssg-cloudflare-pages/vite.config.ts
index 8e2bf4e3d6..83d1624d67 100644
--- a/fixtures/ssg-cloudflare-pages/vite.config.ts
+++ b/fixtures/ssg-cloudflare-pages/vite.config.ts
@@ -2,14 +2,17 @@ import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import vike from "vike/plugin";
+const sourceConditions =
+ process.env.WEBSTUDIO_LOCAL_CLI_BOOTSTRAPPED === "1" ? ["webstudio"] : [];
+
export default defineConfig({
plugins: [react(), vike()],
resolve: {
- conditions: ["browser", "development|production"],
+ conditions: [...sourceConditions, "browser", "development|production"],
},
ssr: {
resolve: {
- conditions: ["node", "development|production"],
+ conditions: [...sourceConditions, "node", "development|production"],
},
},
});
diff --git a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json b/fixtures/ssg-netlify-by-project-id/.webstudio/data.json
index 8c72f92e80..54c301798f 100644
--- a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json
+++ b/fixtures/ssg-netlify-by-project-id/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1l6lbch",
+ "bundleVersion": "bundle-1ikf7r3",
"build": {
"id": "8f0fdff2-e76b-4f86-9203-ea7df5f1143c",
"projectId": "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e",
diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.asset-query-manifest.ts b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.asset-query-manifest.ts
new file mode 100644
index 0000000000..b68197d7f6
--- /dev/null
+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.asset-query-manifest.ts
@@ -0,0 +1,2 @@
+export const assetQueryDeploymentId = "8f0fdff2-e76b-4f86-9203-ea7df5f1143c";
+export const assetQueryDatabase = undefined;
diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.asset-query-runtime.ts b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.asset-query-runtime.ts
new file mode 100644
index 0000000000..4e56ef157a
--- /dev/null
+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.asset-query-runtime.ts
@@ -0,0 +1,5 @@
+export const createGeneratedAssetResourceFetch = async ({ fallback }: {
+ request: Request;
+ context: unknown;
+ fallback: typeof fetch;
+ }): Promise<typeof fetch> => fallback;
diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.assets.ts b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.assets.ts
index def0dafa8f..803ae11d57 100644
--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.assets.ts
+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.assets.ts
@@ -1 +1,3 @@
-export const assets = {};
+
+ export const assets = {};
+
\ No newline at end of file
diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.redirects.ts b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.redirects.ts
index a3ee44bd02..5872ee0507 100644
--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.redirects.ts
+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.redirects.ts
@@ -1 +1,3 @@
-export const redirects = [];
+
+ export const redirects = [];
+
\ No newline at end of file
diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.sitemap.xml.ts b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.sitemap.xml.ts
index e54947f47b..ae27edefca 100644
--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.sitemap.xml.ts
+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.sitemap.xml.ts
@@ -1,6 +1,8 @@
-export const sitemap = [
+
+ export const sitemap = [
{
- path: "/",
- lastModified: "2026-01-04",
- },
+ "path": "/",
+ "lastModified": "2026-01-04"
+ }
];
+
\ No newline at end of file
diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsx
index 3235fdf5fa..de8b65606e 100644
--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsx
+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: 302,
redirect: "/",
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.tsx
index 8e97d940d0..badabac03c 100644
--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.tsx
+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.tsx
@@ -1,37 +1,40 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-export const projectId = "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e";
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+
-export const projectDomain = "fixture-client-do-not-touch-wsmel";
+ export const projectId = "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e";
-export const lastPublished = "2026-01-04T10:46:48.415Z";
+
-export const siteName = undefined;
+ export const projectDomain = "fixture-client-do-not-touch-wsmel";
-export const breakpoints = [
- { id: "pTyOZEX5PG52onfyt3-Vg" },
- { id: "GzBytedsc258Pp7rh1hiD", maxWidth: 991 },
- { id: "ugRM71O_Lm78kMKjkrtyz", maxWidth: 767 },
- { id: "NKdYAYw-oxmW8laNbpiwK", maxWidth: 479 },
-];
+ export const lastPublished = "2026-01-04T10:46:48.415Z";
-export const favIconAsset: string | undefined = undefined;
+ export const siteName = undefined;
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
+ export const breakpoints = [{"id":"pTyOZEX5PG52onfyt3-Vg"},{"id":"GzBytedsc258Pp7rh1hiD","maxWidth":991},{"id":"ugRM71O_Lm78kMKjkrtyz","maxWidth":767},{"id":"NKdYAYw-oxmW8laNbpiwK","maxWidth":479}];
-export const pageBackgroundImageAssets: string[] = [];
+ export const favIconAsset: string | undefined =
+ undefined;
-const Page = (_props: { system: any }) => {
- return <body className={`w-element`} />;
-};
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
-export { Page };
+ export const pageBackgroundImageAssets: string[] =
+ []
+
+
+
+ const Page = (_props: { system: any; }) => {
+return <body
+className={`w-element`} />
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx
index 43532c4748..3896f613db 100644
--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx
+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: undefined,
redirect: undefined,
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.tsx
index 658c1bb7b2..6697abdec4 100644
--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.tsx
+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.tsx
@@ -1,51 +1,52 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import {
- Body as Body,
- Heading as Heading,
-} from "@webstudio-is/sdk-components-react/components";
-export const projectId = "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e";
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body, Heading as Heading } from "@webstudio-is/sdk-components-react/components";
-export const projectVersion = 7;
-export const projectDomain = "fixture-client-do-not-touch-wsmel";
+ export const projectId = "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e";
-export const lastPublished = "2026-01-04T10:46:48.415Z";
+ export const projectVersion = 7;
-export const siteName = undefined;
+ export const projectDomain = "fixture-client-do-not-touch-wsmel";
-export const breakpoints = [
- { id: "pTyOZEX5PG52onfyt3-Vg" },
- { id: "GzBytedsc258Pp7rh1hiD", maxWidth: 991 },
- { id: "ugRM71O_Lm78kMKjkrtyz", maxWidth: 767 },
- { id: "NKdYAYw-oxmW8laNbpiwK", maxWidth: 479 },
-];
+ export const lastPublished = "2026-01-04T10:46:48.415Z";
-export const favIconAsset: string | undefined = undefined;
+ export const siteName = undefined;
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
+ export const breakpoints = [{"id":"pTyOZEX5PG52onfyt3-Vg"},{"id":"GzBytedsc258Pp7rh1hiD","maxWidth":991},{"id":"ugRM71O_Lm78kMKjkrtyz","maxWidth":767},{"id":"NKdYAYw-oxmW8laNbpiwK","maxWidth":479}];
-export const pageBackgroundImageAssets: string[] = [];
+ export const favIconAsset: string | undefined =
+ undefined;
-export const CustomCode = () => {
- return <></>;
-};
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body`}>
- <Heading className={`w-heading`}>{"FIXTURE-CLIENT-DO-NOT-TOUCH"}</Heading>
- </Body>
- );
-};
+ export const pageBackgroundImageAssets: string[] =
+ []
-export { Page };
+
+
+
+ export const CustomCode = () => {
+ return (<></>);
+ }
+
+
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body`}>
+<Heading
+className={`w-heading`}>
+{"FIXTURE-CLIENT-DO-NOT-TOUCH"}
+</Heading>
+</Body>
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/index.css b/fixtures/ssg-netlify-by-project-id/app/__generated__/index.css
index cd9e1ffa2b..e60fc5b600 100644
--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/index.css
+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/index.css
@@ -8,21 +8,21 @@
font-size: 16px;
line-height: 1.2;
white-space: pre-wrap;
- white-space-collapse: preserve;
+ white-space-collapse: preserve
}
body.w-element {
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
- margin: 0;
+ margin: 0
}
body.w-body {
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
- margin: 0;
+ margin: 0
}
h1.w-heading {
- box-sizing: border-box;
+ box-sizing: border-box
}
}
diff --git a/fixtures/ssg-netlify-by-project-id/app/asset-resource-fetch.ts b/fixtures/ssg-netlify-by-project-id/app/asset-resource-fetch.ts
new file mode 100644
index 0000000000..fda7a44b64
--- /dev/null
+++ b/fixtures/ssg-netlify-by-project-id/app/asset-resource-fetch.ts
@@ -0,0 +1,4 @@
+export const createSsgAssetResourceFetch =
+ (_options: unknown) =>
+ async (_input: RequestInfo | URL, _init?: RequestInit) =>
+ undefined;
diff --git a/fixtures/ssg-netlify-by-project-id/pages/index/+data.ts b/fixtures/ssg-netlify-by-project-id/pages/index/+data.ts
index 8f86daf8a5..41189eeabd 100644
--- a/fixtures/ssg-netlify-by-project-id/pages/index/+data.ts
+++ b/fixtures/ssg-netlify-by-project-id/pages/index/+data.ts
@@ -5,8 +5,26 @@ import {
getResources,
} from "../../app/__generated__/_index.server";
import { assets } from "../../app/__generated__/$resources.assets";
+import {
+ assetQueryDeploymentId,
+ assetQueryDatabase,
+} from "../../app/__generated__/$resources.asset-query-manifest";
+import { createSsgAssetResourceFetch } from "../../app/asset-resource-fetch";
+
+const fetchAssetResource =
+ assetQueryDatabase === undefined
+ ? undefined
+ : createSsgAssetResourceFetch({
+ deploymentId: assetQueryDeploymentId,
+ artifact: assetQueryDatabase,
+ runtimeAssets: assets,
+ });
-const customFetch: typeof fetch = (input, init) => {
+const customFetch: typeof fetch = async (input, init) => {
+ const assetResourceResponse = await fetchAssetResource?.(input, init);
+ if (assetResourceResponse !== undefined) {
+ return assetResourceResponse;
+ }
if (typeof input !== "string") {
return fetch(input, init);
}
@@ -26,13 +44,7 @@ const customFetch: typeof fetch = (input, init) => {
};
const response = new Response(JSON.stringify(data));
response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
+ return response;
}
return fetch(input, init);
@@ -55,7 +67,8 @@ export const data = async (pageContext: PageContextServer) => {
const resources = await loadResources(
customFetch,
- getResources({ system }).data
+ getResources({ system }).data,
+ url
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/ssg-netlify-by-project-id/pages/redirect/+data.ts b/fixtures/ssg-netlify-by-project-id/pages/redirect/+data.ts
index 31c7efd090..8b9723c4ea 100644
--- a/fixtures/ssg-netlify-by-project-id/pages/redirect/+data.ts
+++ b/fixtures/ssg-netlify-by-project-id/pages/redirect/+data.ts
@@ -5,8 +5,26 @@ import {
getResources,
} from "../../app/__generated__/[redirect]._index.server";
import { assets } from "../../app/__generated__/$resources.assets";
+import {
+ assetQueryDeploymentId,
+ assetQueryDatabase,
+} from "../../app/__generated__/$resources.asset-query-manifest";
+import { createSsgAssetResourceFetch } from "../../app/asset-resource-fetch";
+
+const fetchAssetResource =
+ assetQueryDatabase === undefined
+ ? undefined
+ : createSsgAssetResourceFetch({
+ deploymentId: assetQueryDeploymentId,
+ artifact: assetQueryDatabase,
+ runtimeAssets: assets,
+ });
-const customFetch: typeof fetch = (input, init) => {
+const customFetch: typeof fetch = async (input, init) => {
+ const assetResourceResponse = await fetchAssetResource?.(input, init);
+ if (assetResourceResponse !== undefined) {
+ return assetResourceResponse;
+ }
if (typeof input !== "string") {
return fetch(input, init);
}
@@ -26,13 +44,7 @@ const customFetch: typeof fetch = (input, init) => {
};
const response = new Response(JSON.stringify(data));
response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
+ return response;
}
return fetch(input, init);
@@ -55,7 +67,8 @@ export const data = async (pageContext: PageContextServer) => {
const resources = await loadResources(
customFetch,
- getResources({ system }).data
+ getResources({ system }).data,
+ url
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/ssg-netlify-by-project-id/vite.config.ts b/fixtures/ssg-netlify-by-project-id/vite.config.ts
index 8e2bf4e3d6..83d1624d67 100644
--- a/fixtures/ssg-netlify-by-project-id/vite.config.ts
+++ b/fixtures/ssg-netlify-by-project-id/vite.config.ts
@@ -2,14 +2,17 @@ import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import vike from "vike/plugin";
+const sourceConditions =
+ process.env.WEBSTUDIO_LOCAL_CLI_BOOTSTRAPPED === "1" ? ["webstudio"] : [];
+
export default defineConfig({
plugins: [react(), vike()],
resolve: {
- conditions: ["browser", "development|production"],
+ conditions: [...sourceConditions, "browser", "development|production"],
},
ssr: {
resolve: {
- conditions: ["node", "development|production"],
+ conditions: [...sourceConditions, "node", "development|production"],
},
},
});
diff --git a/fixtures/webstudio-cloudflare-template/.webstudio/data.json b/fixtures/webstudio-cloudflare-template/.webstudio/data.json
index 3bcf267907..c87376c6d0 100644
--- a/fixtures/webstudio-cloudflare-template/.webstudio/data.json
+++ b/fixtures/webstudio-cloudflare-template/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1l6lbch",
+ "bundleVersion": "bundle-1ikf7r3",
"build": {
"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.asset-query-manifest.ts b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.asset-query-manifest.ts
new file mode 100644
index 0000000000..3ca2291fd2
--- /dev/null
+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.asset-query-manifest.ts
@@ -0,0 +1,2 @@
+export const assetQueryDeploymentId = "a2e8de30-03d5-4514-a3a6-406b3266a3af";
+export const assetQueryDatabase = undefined;
diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.asset-query-runtime.ts b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.asset-query-runtime.ts
new file mode 100644
index 0000000000..4e56ef157a
--- /dev/null
+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.asset-query-runtime.ts
@@ -0,0 +1,5 @@
+export const createGeneratedAssetResourceFetch = async ({ fallback }: {
+ request: Request;
+ context: unknown;
+ fallback: typeof fetch;
+ }): Promise<typeof fetch> => fallback;
diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.assets.ts b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.assets.ts
index 6274fdf61e..2a5c535b6a 100644
--- a/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.assets.ts
+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.assets.ts
@@ -1,12 +1,14 @@
-export const assets = {
+
+ export const assets = {
"1d8bf4398f643f5333d415091507d778aaed62f28883642636cbed0be156a0ee": {
- url: "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
- width: 14,
- height: 16,
- },
- d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd: {
- url: "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
- width: 820,
- height: 985,
+ "url": "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
+ "width": 14,
+ "height": 16
},
+ "d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd": {
+ "url": "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
+ "width": 820,
+ "height": 985
+ }
};
+
\ No newline at end of file
diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.redirects.ts b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.redirects.ts
index a3ee44bd02..5872ee0507 100644
--- a/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.redirects.ts
+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.redirects.ts
@@ -1 +1,3 @@
-export const redirects = [];
+
+ export const redirects = [];
+
\ No newline at end of file
diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.sitemap.xml.ts b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.sitemap.xml.ts
index 9b3f4dfa6d..2853d60abb 100644
--- a/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.sitemap.xml.ts
+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.sitemap.xml.ts
@@ -1,6 +1,8 @@
-export const sitemap = [
+
+ export const sitemap = [
{
- path: "/",
- lastModified: "2024-07-29",
- },
+ "path": "/",
+ "lastModified": "2024-07-29"
+ }
];
+
\ No newline at end of file
diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.server.tsx b/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.server.tsx
index 7742cba561..023be09459 100644
--- a/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.server.tsx
+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: 200,
redirect: "",
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.tsx b/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.tsx
index 7fe6f98117..7b9d957316 100644
--- a/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.tsx
+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.tsx
@@ -1,43 +1,47 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import { Body as Body } from "@webstudio-is/sdk-components-react-remix";
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body } from "@webstudio-is/sdk-components-react-remix";
import { Heading as Heading } from "@webstudio-is/sdk-components-react/components";
-export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
-export const projectDomain = "cli-basic-test-d0osr";
+ export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
+
+
+
+ export const projectDomain = "cli-basic-test-d0osr";
+
+ export const lastPublished = "2024-07-29T12:50:07.515Z";
+
+ export const siteName = "";
-export const lastPublished = "2024-07-29T12:50:07.515Z";
+ export const breakpoints = [{"id":"rKj-wYctg3-GnqL3WHN9I"},{"id":"yH9RXhqCyeaVkrOt8MzLc","maxWidth":991},{"id":"8nSCZbeS002IVwkTdoIes","maxWidth":767},{"id":"7gBD25KrrbBdJYNDlhPz7","maxWidth":479}];
-export const siteName = "";
+ export const favIconAsset: string | undefined =
+ undefined;
-export const breakpoints = [
- { id: "rKj-wYctg3-GnqL3WHN9I" },
- { id: "yH9RXhqCyeaVkrOt8MzLc", maxWidth: 991 },
- { id: "8nSCZbeS002IVwkTdoIes", maxWidth: 767 },
- { id: "7gBD25KrrbBdJYNDlhPz7", maxWidth: 479 },
-];
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
-export const favIconAsset: string | undefined = undefined;
+ export const pageBackgroundImageAssets: string[] =
+ []
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
+
-export const pageBackgroundImageAssets: string[] = [];
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body`}>
+<Heading
+className={`w-heading`}>
+{"Another page"}
+</Heading>
+</Body>
+}
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body`}>
- <Heading className={`w-heading`}>{"Another page"}</Heading>
- </Body>
- );
-};
-export { Page };
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsx b/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsx
index 43532c4748..3896f613db 100644
--- a/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsx
+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: undefined,
redirect: undefined,
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/_index.tsx b/fixtures/webstudio-cloudflare-template/app/__generated__/_index.tsx
index 3457077bd5..5df9cd5d7d 100644
--- a/fixtures/webstudio-cloudflare-template/app/__generated__/_index.tsx
+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/_index.tsx
@@ -1,72 +1,70 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import {
- Body as Body,
- Link as Link,
-} from "@webstudio-is/sdk-components-react-remix";
-import {
- Heading as Heading,
- Text as Text,
- Image as Image,
-} from "@webstudio-is/sdk-components-react/components";
-
-export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
-
-export const projectVersion = 38;
-
-export const projectDomain = "cli-basic-test-d0osr";
-
-export const lastPublished = "2024-07-29T12:50:07.515Z";
-
-export const siteName = "";
-
-export const breakpoints = [
- { id: "rKj-wYctg3-GnqL3WHN9I" },
- { id: "yH9RXhqCyeaVkrOt8MzLc", maxWidth: 991 },
- { id: "8nSCZbeS002IVwkTdoIes", maxWidth: 767 },
- { id: "7gBD25KrrbBdJYNDlhPz7", maxWidth: 479 },
-];
-
-export const favIconAsset: string | undefined = undefined;
-
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
-
-export const pageBackgroundImageAssets: string[] = [];
-
-export const CustomCode = () => {
- return <></>;
-};
-
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body c1jaw2zx cbipm55 ctniqj4 ctgx88l`}>
- <Heading className={`w-heading`}>{"Simple Project to test CLI"}</Heading>
- <Text className={`w-text cn3rfux`}>
- {"Please don't change directly in the fixture"}
- </Text>
- <Link href={"/another-page"} className={`w-link`}>
- {"Test another page link"}
- </Link>
- <Image
- src={"/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg"}
- width={14}
- height={16}
- className={`w-image c161qeci`}
- />
- <Image
- src={"https://picsum.photos/id/237/100/100.jpg?blur=4&grayscale"}
- className={`w-image`}
- />
- </Body>
- );
-};
-
-export { Page };
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body, Link as Link } from "@webstudio-is/sdk-components-react-remix";
+import { Heading as Heading, Text as Text, Image as Image } from "@webstudio-is/sdk-components-react/components";
+
+
+ export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";
+
+ export const projectVersion = 38;
+
+ export const projectDomain = "cli-basic-test-d0osr";
+
+ export const lastPublished = "2024-07-29T12:50:07.515Z";
+
+ export const siteName = "";
+
+ export const breakpoints = [{"id":"rKj-wYctg3-GnqL3WHN9I"},{"id":"yH9RXhqCyeaVkrOt8MzLc","maxWidth":991},{"id":"8nSCZbeS002IVwkTdoIes","maxWidth":767},{"id":"7gBD25KrrbBdJYNDlhPz7","maxWidth":479}];
+
+ export const favIconAsset: string | undefined =
+ undefined;
+
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
+
+ export const pageBackgroundImageAssets: string[] =
+ []
+
+
+
+
+ export const CustomCode = () => {
+ return (<></>);
+ }
+
+
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body c1jaw2zx cbipm55 ctniqj4 ctgx88l`}>
+<Heading
+className={`w-heading`}>
+{"Simple Project to test CLI"}
+</Heading>
+<Text
+className={`w-text cn3rfux`}>
+{"Please don't change directly in the fixture"}
+</Text>
+<Link
+href={"/another-page"}
+className={`w-link`}>
+{"Test another page link"}
+</Link>
+<Image
+src={"/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg"}
+width={14}
+height={16}
+className={`w-image c161qeci`} />
+<Image
+src={"https://picsum.photos/id/237/100/100.jpg?blur=4&grayscale"}
+className={`w-image`} />
+</Body>
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/index.css b/fixtures/webstudio-cloudflare-template/app/__generated__/index.css
index bae88880bc..8df45a0874 100644
--- a/fixtures/webstudio-cloudflare-template/app/__generated__/index.css
+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/index.css
@@ -8,49 +8,49 @@
font-size: 16px;
line-height: 1.2;
white-space: pre-wrap;
- white-space-collapse: preserve;
+ white-space-collapse: preserve
}
body.w-body {
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
- margin: 0;
+ margin: 0
}
h1.w-heading {
- box-sizing: border-box;
+ box-sizing: border-box
}
div.w-text {
box-sizing: border-box;
- min-height: 1em;
+ min-height: 1em
}
a.w-link {
box-sizing: border-box;
- display: inline-block;
+ display: inline-block
}
img.w-image {
box-sizing: border-box;
max-width: 100%;
display: block;
- height: auto;
+ height: auto
}
}
@media all {
.c1jaw2zx {
- display: flex;
+ display: flex
}
.cbipm55 {
- align-items: center;
+ align-items: center
}
.ctniqj4 {
- justify-content: center;
+ justify-content: center
}
.ctgx88l {
- flex-direction: column;
+ flex-direction: column
}
.cn3rfux {
- margin-bottom: 1em;
+ margin-bottom: 1em
}
.c161qeci {
- width: 400px;
+ width: 400px
}
-}
+}
\ No newline at end of file
diff --git a/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx b/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx
index a0ca5169c7..bff4144f99 100644
--- a/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx
+++ b/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx
@@ -44,8 +44,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -95,12 +95,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -123,9 +117,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx b/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx
index cb5d8b908e..eb8edabb69 100644
--- a/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx
+++ b/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx
@@ -44,8 +44,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -95,12 +95,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -123,9 +117,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/webstudio-features/.webstudio/data.json b/fixtures/webstudio-features/.webstudio/data.json
index 9355144767..df1140ae07 100644
--- a/fixtures/webstudio-features/.webstudio/data.json
+++ b/fixtures/webstudio-features/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1l6lbch",
+ "bundleVersion": "bundle-1ikf7r3",
"build": {
"id": "1b66ee06-8ea5-4420-9a0e-e0d3a67aca32",
"projectId": "cddc1d44-af37-4cb6-a430-d300cf6f932d",
@@ -6873,10 +6873,16 @@
"id": "oIYuHoIwG7GM5J9cCSsai",
"name": "assets",
"control": "system",
- "method": "get",
+ "method": "post",
"url": "\"/$resources/assets\"",
"searchParams": [],
- "headers": []
+ "headers": [
+ {
+ "name": "Content-Type",
+ "value": "\"application/json\""
+ }
+ ],
+ "body": "{\n query: ({\n output: {\n mode: \"fields\",\n includeMetadata: false,\n fields: [[\"url\"], [\"width\"], [\"height\"]],\n },\n content: {\n mode: \"none\",\n },\n where: {\n all: [],\n },\n sort: [],\n limit: 1000,\n offset: 0,\n }),\n}"
}
]
],
@@ -7232,6 +7238,21 @@
"meta": {},
"type": "file"
},
+ {
+ "id": "42e55b0464790758b9352d675cf28fadfcf8a3259fc1e890100617d3e731be88",
+ "projectId": "cddc1d44-af37-4cb6-a430-d300cf6f932d",
+ "size": 377924,
+ "name": "cabinsketch-bold_TLCbytfxf8ENHwZ6ze3Jj.ttf",
+ "createdAt": "2026-01-14T01:10:46.647+00:00",
+ "updatedAt": "2026-01-14T01:10:46.647+00:00",
+ "format": "ttf",
+ "meta": {
+ "family": "CabinSketch",
+ "style": "normal",
+ "weight": 700
+ },
+ "type": "font"
+ },
{
"id": "4afe692f78ec0530e355a551a3860302c4478037db7b25a3bdae82c32c78634d",
"projectId": "cddc1d44-af37-4cb6-a430-d300cf6f932d",
@@ -7303,5 +7324,49 @@
},
"projectDomain": "webstudio-fixture-project-a-0su3o",
"projectTitle": "webstudio-fixture-project-a",
+ "assetIndex": {
+ "format": "webstudio-content-database",
+ "version": 1,
+ "assetRevision": "sha256:55e51683a123fa9724ffe8c4e71de1e342708975690008480005002d2c1e739e",
+ "documents": [
+ {
+ "_id": "2b151fc7b4b0324e6ab78c40f72c7f59273f81fb1be3d08b3f9976428601b95e"
+ },
+ {
+ "_id": "42e55b0464790758b9352d675cf28fadfcf8a3259fc1e890100617d3e731be88"
+ },
+ {
+ "_id": "4afe692f78ec0530e355a551a3860302c4478037db7b25a3bdae82c32c78634d"
+ },
+ {
+ "_id": "7cf5892080fa66b5e6175ffd2d27c304ee6b09ce1f21847a95000225ad1afa59"
+ },
+ {
+ "_id": "9a8bc926-7804-4d3f-af81-69196b1d2ed8"
+ },
+ {
+ "_id": "cbf6b1b052e52b256cef54a032a546bf43bf3f5441be4d1c5eeaabce26903d78"
+ },
+ {
+ "_id": "cd939c56-bcdd-4e64-bd9c-567a9bccd3da"
+ }
+ ],
+ "fieldCatalog": {
+ "format": "webstudio-builder-asset-field-catalog",
+ "version": 1,
+ "canonicalRevision": "sha256:55e51683a123fa9724ffe8c4e71de1e342708975690008480005002d2c1e739e",
+ "documentCount": 7,
+ "fields": {}
+ },
+ "database": {
+ "maxBytes": 512000,
+ "unboundedBytes": 1023,
+ "sourceDocumentCount": 7
+ },
+ "integrity": {
+ "algorithm": "sha256",
+ "checksum": "sha256:8ec5939a945f85326475b8351e5a343e82b9c6971c490550a9e2dd4079503225"
+ }
+ },
"origin": "https://main.development.webstudio.is"
}
diff --git a/fixtures/webstudio-features/app/__generated__/$resources.asset-query-manifest.ts b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-manifest.ts
new file mode 100644
index 0000000000..1f405c174c
--- /dev/null
+++ b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-manifest.ts
@@ -0,0 +1,2 @@
+export const assetQueryDeploymentId = "1b66ee06-8ea5-4420-9a0e-e0d3a67aca32";
+export const assetQueryDatabase = {"assetRevision":"sha256:55e51683a123fa9724ffe8c4e71de1e342708975690008480005002d2c1e739e","database":{"maxBytes":512000,"sourceDocumentCount":7,"unboundedBytes":1023},"documents":[{"_id":"2b151fc7b4b0324e6ab78c40f72c7f59273f81fb1be3d08b3f9976428601b95e"},{"_id":"42e55b0464790758b9352d675cf28fadfcf8a3259fc1e890100617d3e731be88"},{"_id":"4afe692f78ec0530e355a551a3860302c4478037db7b25a3bdae82c32c78634d"},{"_id":"7cf5892080fa66b5e6175ffd2d27c304ee6b09ce1f21847a95000225ad1afa59"},{"_id":"9a8bc926-7804-4d3f-af81-69196b1d2ed8"},{"_id":"cbf6b1b052e52b256cef54a032a546bf43bf3f5441be4d1c5eeaabce26903d78"},{"_id":"cd939c56-bcdd-4e64-bd9c-567a9bccd3da"}],"fieldCatalog":{"canonicalRevision":"sha256:55e51683a123fa9724ffe8c4e71de1e342708975690008480005002d2c1e739e","documentCount":7,"fields":{},"format":"webstudio-builder-asset-field-catalog","version":1},"format":"webstudio-content-database","integrity":{"algorithm":"sha256","checksum":"sha256:8ec5939a945f85326475b8351e5a343e82b9c6971c490550a9e2dd4079503225"},"version":1};
diff --git a/fixtures/webstudio-features/app/__generated__/$resources.asset-query-runtime.ts b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-runtime.ts
new file mode 100644
index 0000000000..9a63651a7c
--- /dev/null
+++ b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-runtime.ts
@@ -0,0 +1,17 @@
+import { createGeneratedAssetResourceRuntime } from "./$resources.asset-query-vendor.js";
+import { assetQueryDatabase } from "./$resources.asset-query-manifest";
+
+const deploymentId = "1b66ee06-8ea5-4420-9a0e-e0d3a67aca32";
+const runtimeAssets = {"2b151fc7b4b0324e6ab78c40f72c7f59273f81fb1be3d08b3f9976428601b95e":{"url":"/assets/e-mail-39993_vrxyjxQv3j67Krs62Vz7Y.mp3"},"42e55b0464790758b9352d675cf28fadfcf8a3259fc1e890100617d3e731be88":{"url":"/assets/cabinsketch-bold_TLCbytfxf8ENHwZ6ze3Jj.ttf","family":"CabinSketch","style":"normal","weight":700},"4afe692f78ec0530e355a551a3860302c4478037db7b25a3bdae82c32c78634d":{"url":"/assets/webm-example_2r_6VmRBjhAy3ldaqz0gk.webm"},"7cf5892080fa66b5e6175ffd2d27c304ee6b09ce1f21847a95000225ad1afa59":{"url":"/assets/cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png","width":790,"height":786},"9a8bc926-7804-4d3f-af81-69196b1d2ed8":{"url":"/assets/small-avif-kitty_FnabJsioMWpBtXZSGf4DR.webp","width":100,"height":100},"cbf6b1b052e52b256cef54a032a546bf43bf3f5441be4d1c5eeaabce26903d78":{"url":"/assets/video_QamtUWsD-ShifhzZLoNIv_ald_1xtyEb3uHhFb7nCQa.mp4"},"cd939c56-bcdd-4e64-bd9c-567a9bccd3da":{"url":"/assets/_937084ed-a798-49fe-8664-df93a2af605e_uiBk3o6UWdqolyakMvQJ9.jpeg","width":1024,"height":1024}};
+const createRuntimeFetch = createGeneratedAssetResourceRuntime({
+ deploymentId,
+ artifact: assetQueryDatabase,
+ runtimeAssets,
+});
+
+export const createGeneratedAssetResourceFetch = ({ request, fallback }: {
+ request: Request;
+ context: unknown;
+ fallback: typeof fetch;
+ }) =>
+ createRuntimeFetch({ request, fallback });
diff --git a/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js
new file mode 100644
index 0000000000..483f4533b7
--- /dev/null
+++ b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js
@@ -0,0 +1,64 @@
+var Li=Object.defineProperty;var Mi=(e,t)=>{for(var r in t)Li(e,r,{get:t[r],enumerable:!0})};var tr;function l(e,t,r){function n(c,a){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:a,constr:i,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,a);let u=i.prototype,f=Object.keys(u);for(let p=0;p<f.length;p++){let m=f[p];m in c||(c[m]=u[m].bind(c))}}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function i(c){var a;let u=r?.Parent?new s:this;n(u,c),(a=u._zod).deferred??(a.deferred=[]);for(let f of u._zod.deferred)f();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}var Ru=Symbol("zod_brand"),Q=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},le=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(tr=globalThis).__zod_globalConfig??(tr.__zod_globalConfig={});var pe=globalThis.__zod_globalConfig;function M(e){return e&&Object.assign(pe,e),pe}var x={};Mi(x,{BIGINT_FORMAT_RANGES:()=>ir,Class:()=>ct,NUMBER_FORMAT_RANGES:()=>ft,aborted:()=>X,allowsEval:()=>lt,assert:()=>qi,assertEqual:()=>Ui,assertIs:()=>Qi,assertNever:()=>Ji,assertNotEqual:()=>Bi,assignProp:()=>G,base64ToUint8Array:()=>ar,base64urlToUint8Array:()=>pc,cached:()=>fe,captureStackTrace:()=>Fe,cleanEnum:()=>lc,cleanRegex:()=>ve,clone:()=>U,cloneDef:()=>Gi,createTransparentProxy:()=>tc,defineLazy:()=>_,esc:()=>De,escapeRegex:()=>q,explicitlyAborted:()=>mt,extend:()=>oc,finalizeIssue:()=>j,floatSafeRemainder:()=>at,getElementAtPath:()=>Ki,getEnumValues:()=>be,getLengthableOrigin:()=>ze,getParsedType:()=>ec,getSizableOrigin:()=>cr,hexToUint8Array:()=>fc,isObject:()=>re,isPlainObject:()=>K,issue:()=>me,joinValues:()=>Vi,jsonStringifyReplacer:()=>de,merge:()=>ic,mergeDefs:()=>J,normalizeParams:()=>h,nullish:()=>we,numKeys:()=>Hi,objectClone:()=>Wi,omit:()=>nc,optionalKeys:()=>dt,parsedType:()=>uc,partial:()=>cc,pick:()=>rc,prefixIssues:()=>V,primitiveTypes:()=>or,promiseAllObject:()=>Xi,propertyKeyTypes:()=>pt,randomString:()=>Yi,required:()=>ac,safeExtend:()=>sc,shallowClone:()=>nr,slugify:()=>ut,stringifyPrimitive:()=>sr,uint8ArrayToBase64:()=>ur,uint8ArrayToBase64url:()=>dc,uint8ArrayToHex:()=>mc,unwrapMessage:()=>xe});function Ui(e){return e}function Bi(e){return e}function Qi(e){}function Ji(e){throw new Error("Unexpected value in exhaustive check")}function qi(e){}function be(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function Vi(e,t="|"){return e.map(r=>sr(r)).join(t)}function de(e,t){return typeof t=="bigint"?t.toString():t}function fe(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function we(e){return e==null}function ve(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function at(e,t){let r=e/t,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<o?0:r-n}var rr=Symbol("evaluating");function _(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==rr)return n===void 0&&(n=rr,n=r()),n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Wi(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function G(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function J(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function Gi(e){return J(e._zod.def)}function Ki(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function Xi(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<t.length;s++)o[t[s]]=n[s];return o})}function Yi(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function De(e){return JSON.stringify(e)}function ut(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Fe="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function re(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var lt=fe(()=>{if(pe.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function K(e){if(re(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(re(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function nr(e){return K(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function Hi(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var ec=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},pt=new Set(["string","number","symbol"]),or=new Set(["string","number","bigint","boolean","symbol","undefined"]);function q(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function U(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function h(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function tc(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,s){return t??(t=e()),Reflect.set(t,n,o,s)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function sr(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function dt(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var ft={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},ir={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function rc(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=J(e._zod.def,{get shape(){let i={};for(let c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(i[c]=r.shape[c])}return G(this,"shape",i),i},checks:[]});return U(e,s)}function nc(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=J(e._zod.def,{get shape(){let i={...e._zod.def.shape};for(let c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete i[c]}return G(this,"shape",i),i},checks:[]});return U(e,s)}function oc(e,t){if(!K(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let s=e._zod.def.shape;for(let i in t)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=J(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return G(this,"shape",s),s}});return U(e,o)}function sc(e,t){if(!K(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=J(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return G(this,"shape",n),n}});return U(e,r)}function ic(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=J(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return G(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return U(e,r)}function cc(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let i=J(t._zod.def,{get shape(){let c=t._zod.def.shape,a={...c};if(r)for(let u in r){if(!(u in c))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(a[u]=e?new e({type:"optional",innerType:c[u]}):c[u])}else for(let u in c)a[u]=e?new e({type:"optional",innerType:c[u]}):c[u];return G(this,"shape",a),a},checks:[]});return U(t,i)}function ac(e,t,r){let n=J(t._zod.def,{get shape(){let o=t._zod.def.shape,s={...o};if(r)for(let i in r){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(s[i]=new e({type:"nonoptional",innerType:o[i]}))}else for(let i in o)s[i]=new e({type:"nonoptional",innerType:o[i]});return G(this,"shape",s),s}});return U(t,n)}function X(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function mt(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function V(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function xe(e){return typeof e=="string"?e:e?.message}function j(e,t,r){let n=e.message?e.message:xe(e.inst?._zod.def?.error?.(e))??xe(t?.error?.(e))??xe(r.customError?.(e))??xe(r.localeError?.(e))??"Invalid input",{inst:o,continue:s,input:i,...c}=e;return c.path??(c.path=[]),c.message=n,t?.reportInput&&(c.input=i),c}function cr(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function ze(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function uc(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function me(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function lc(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function ar(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function ur(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function pc(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return ar(t+r)}function dc(e){return ur(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function fc(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=Number.parseInt(t.slice(n,n+2),16);return r}function mc(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var ct=class{constructor(...t){}};var lr=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,de,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},je=l("$ZodError",lr),ht=l("$ZodError",lr,{Parent:Error});function pr(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function dr(e,t=r=>r.message){let r={_errors:[]},n=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(c=>n({issues:c},[...s,...i.path]));else if(i.code==="invalid_key")n({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")n({issues:i.issues},[...s,...i.path]);else{let c=[...s,...i.path];if(c.length===0)r._errors.push(t(i));else{let a=r,u=0;for(;u<c.length;){let f=c[u];u===c.length-1?(a[f]=a[f]||{_errors:[]},a[f]._errors.push(t(i))):a[f]=a[f]||{_errors:[]},a=a[f],u++}}}};return n(e),r}var Le=e=>(t,r,n,o)=>{let s=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Q;if(i.issues.length){let c=new(o?.Err??e)(i.issues.map(a=>j(a,s,M())));throw Fe(c,o?.callee),c}return i.value};var Me=e=>async(t,r,n,o)=>{let s=n?{...n,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let c=new(o?.Err??e)(i.issues.map(a=>j(a,s,M())));throw Fe(c,o?.callee),c}return i.value};var $e=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Q;return s.issues.length?{success:!1,error:new(e??je)(s.issues.map(i=>j(i,o,M())))}:{success:!0,data:s.value}},fr=$e(ht),ke=e=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(i=>j(i,o,M())))}:{success:!0,data:s.value}},mr=ke(ht),hr=e=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Le(e)(t,r,o)};var yr=e=>(t,r,n)=>Le(e)(t,r,n);var gr=e=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Me(e)(t,r,o)};var _r=e=>async(t,r,n)=>Me(e)(t,r,n);var xr=e=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return $e(e)(t,r,o)};var br=e=>(t,r,n)=>$e(e)(t,r,n);var wr=e=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return ke(e)(t,r,o)};var vr=e=>async(t,r,n)=>ke(e)(t,r,n);var zr=/^[cC][0-9a-z]{6,}$/,$r=/^[0-9a-z]+$/,kr=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ar=/^[0-9a-vA-V]{20}$/,Zr=/^[A-Za-z0-9]{27}$/,Sr=/^[a-zA-Z0-9_-]{21}$/,Er=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Rr=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,yt=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;var Pr=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var yc="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Or(){return new RegExp(yc,"u")}var Ir=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Tr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var Cr=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Nr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Dr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,gt=/^[A-Za-z0-9_-]*$/;var Fr=/^https?$/,jr=/^\+[1-9]\d{6,14}$/,Lr="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Mr=new RegExp(`^${Lr}$`);function Ur(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Br(e){return new RegExp(`^${Ur(e)}$`)}function Qr(e){let t=Ur({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Lr}T(?:${n})$`)}var Jr=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var qr=/^-?\d+$/,_t=/^-?\d+(?:\.\d+)?$/,Vr=/^(?:true|false)$/i,Wr=/^null$/i;var Gr=/^[^A-Z]*$/,Kr=/^[^a-z]*$/;var I=l("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Xr={number:"number",bigint:"bigint",object:"date"},xt=l("$ZodCheckLessThan",(e,t)=>{I.init(e,t);let r=Xr[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),bt=l("$ZodCheckGreaterThan",(e,t)=>{I.init(e,t);let r=Xr[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Yr=l("$ZodCheckMultipleOf",(e,t)=>{I.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):at(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Hr=l("$ZodCheckNumberFormat",(e,t)=>{I.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,s]=ft[t.format];e._zod.onattach.push(i=>{let c=i._zod.bag;c.format=t.format,c.minimum=o,c.maximum=s,r&&(c.pattern=qr)}),e._zod.check=i=>{let c=i.value;if(r){if(!Number.isInteger(c)){i.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?i.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):i.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}c<o&&i.issues.push({origin:"number",input:c,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),c>s&&i.issues.push({origin:"number",input:c,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var en=l("$ZodCheckMaxLength",(e,t)=>{var r;I.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!we(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;if(o.length<=t.maximum)return;let i=ze(o);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),tn=l("$ZodCheckMinLength",(e,t)=>{var r;I.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!we(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let i=ze(o);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),rn=l("$ZodCheckLengthEquals",(e,t)=>{var r;I.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!we(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,s=o.length;if(s===t.length)return;let i=ze(o),c=s>t.length;n.issues.push({origin:i,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ae=l("$ZodCheckStringFormat",(e,t)=>{var r,n;I.init(e,t),e._zod.onattach.push(o=>{let s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),nn=l("$ZodCheckRegex",(e,t)=>{Ae.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),on=l("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Gr),Ae.init(e,t)}),sn=l("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Kr),Ae.init(e,t)}),cn=l("$ZodCheckIncludes",(e,t)=>{I.init(e,t);let r=q(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),an=l("$ZodCheckStartsWith",(e,t)=>{I.init(e,t);let r=new RegExp(`^${q(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),un=l("$ZodCheckEndsWith",(e,t)=>{I.init(e,t);let r=new RegExp(`.*${q(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var ln=l("$ZodCheckOverwrite",(e,t)=>{I.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Be=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
+`).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let t=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,o.join(`
+`))}};var dn={major:4,minor:4,patch:3};var z=l("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=dn;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(i,c,a)=>{let u=X(i),f;for(let p of c){if(p._zod.def.when){if(mt(i)||!p._zod.def.when(i))continue}else if(u)continue;let m=i.issues.length,d=p._zod.check(i);if(d instanceof Promise&&a?.async===!1)throw new Q;if(f||d instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await d,i.issues.length!==m&&(u||(u=X(i,m)))});else{if(i.issues.length===m)continue;u||(u=X(i,m))}}return f?f.then(()=>i):i},s=(i,c,a)=>{if(X(i))return i.aborted=!0,i;let u=o(c,n,a);if(u instanceof Promise){if(a.async===!1)throw new Q;return u.then(f=>e._zod.parse(f,a))}return e._zod.parse(u,a)};e._zod.run=(i,c)=>{if(c.skipChecks)return e._zod.parse(i,c);if(c.direction==="backward"){let u=e._zod.parse({value:i.value,issues:[]},{...c,skipChecks:!0});return u instanceof Promise?u.then(f=>s(f,i,c)):s(u,i,c)}let a=e._zod.parse(i,c);if(a instanceof Promise){if(c.async===!1)throw new Q;return a.then(u=>o(u,n,c))}return o(a,n,c)}}_(e,"~standard",()=>({validate:o=>{try{let s=fr(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return mr(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),qe=l("$ZodString",(e,t)=>{z.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Jr(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),$=l("$ZodStringFormat",(e,t)=>{Ae.init(e,t),qe.init(e,t)}),wn=l("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Rr),$.init(e,t)}),vn=l("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=yt(n))}else t.pattern??(t.pattern=yt());$.init(e,t)}),zn=l("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Pr),$.init(e,t)}),$n=l("$ZodURL",(e,t)=>{$.init(e,t),e._zod.check=r=>{try{let n=r.value.trim();if(!t.normalize&&t.protocol?.source===Fr.source&&!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}let o=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=o.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),kn=l("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Or()),$.init(e,t)}),An=l("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Sr),$.init(e,t)}),Zn=l("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=zr),$.init(e,t)}),Sn=l("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=$r),$.init(e,t)}),En=l("$ZodULID",(e,t)=>{t.pattern??(t.pattern=kr),$.init(e,t)}),Rn=l("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Ar),$.init(e,t)}),Pn=l("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Zr),$.init(e,t)}),On=l("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Qr(t)),$.init(e,t)}),In=l("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Mr),$.init(e,t)}),Tn=l("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Br(t)),$.init(e,t)}),Cn=l("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Er),$.init(e,t)}),Nn=l("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ir),$.init(e,t),e._zod.bag.format="ipv4"}),Dn=l("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Tr),$.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}});var Fn=l("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Cr),$.init(e,t)}),jn=l("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Nr),$.init(e,t),e._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,s]=n;if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Ln(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Mn=l("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Dr),$.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{Ln(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function gc(e){if(!gt.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Ln(r)}var Un=l("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=gt),$.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{gc(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Bn=l("$ZodE164",(e,t)=>{t.pattern??(t.pattern=jr),$.init(e,t)});function _c(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}var Qn=l("$ZodJWT",(e,t)=>{$.init(e,t),e._zod.check=r=>{_c(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var vt=l("$ZodNumber",(e,t)=>{z.init(e,t),e._zod.pattern=e._zod.bag.pattern??_t,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),Jn=l("$ZodNumberFormat",(e,t)=>{Hr.init(e,t),vt.init(e,t)}),qn=l("$ZodBoolean",(e,t)=>{z.init(e,t),e._zod.pattern=Vr,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}});var Vn=l("$ZodNull",(e,t)=>{z.init(e,t),e._zod.pattern=Wr,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}});var Wn=l("$ZodUnknown",(e,t)=>{z.init(e,t),e._zod.parse=r=>r}),Gn=l("$ZodNever",(e,t)=>{z.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function fn(e,t,r){e.issues.length&&t.issues.push(...V(r,e.issues)),t.value[r]=e.value}var Kn=l("$ZodArray",(e,t)=>{z.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let c=o[i],a=t.element._zod.run({value:c,issues:[]},n);a instanceof Promise?s.push(a.then(u=>fn(u,r,i))):fn(a,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function Je(e,t,r,n,o,s){let i=r in n;if(e.issues.length){if(o&&s&&!i)return;t.issues.push(...V(r,e.issues))}if(!i&&!o){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?i&&(t.value[r]=void 0):t.value[r]=e.value}function Xn(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=dt(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function Yn(e,t,r,n,o,s){let i=[],c=o.keySet,a=o.catchall._zod,u=a.def.type,f=a.optin==="optional",p=a.optout==="optional";for(let m in t){if(m==="__proto__"||c.has(m))continue;if(u==="never"){i.push(m);continue}let d=a.run({value:t[m],issues:[]},n);d instanceof Promise?e.push(d.then(y=>Je(y,r,m,t,f,p))):Je(d,r,m,t,f,p)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:s}),e.length?Promise.all(e).then(()=>r):r}var xc=l("$ZodObject",(e,t)=>{if(z.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let c=t.shape;Object.defineProperty(t,"shape",{get:()=>{let a={...c};return Object.defineProperty(t,"shape",{value:a}),a}})}let n=fe(()=>Xn(t));_(e._zod,"propValues",()=>{let c=t.shape,a={};for(let u in c){let f=c[u]._zod;if(f.values){a[u]??(a[u]=new Set);for(let p of f.values)a[u].add(p)}}return a});let o=re,s=t.catchall,i;e._zod.parse=(c,a)=>{i??(i=n.value);let u=c.value;if(!o(u))return c.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),c;c.value={};let f=[],p=i.shape;for(let m of i.keys){let d=p[m],y=d._zod.optin==="optional",P=d._zod.optout==="optional",w=d._zod.run({value:u[m],issues:[]},a);w instanceof Promise?f.push(w.then(F=>Je(F,c,m,u,y,P))):Je(w,c,m,u,y,P)}return s?Yn(f,u,c,a,n.value,e):f.length?Promise.all(f).then(()=>c):c}}),Hn=l("$ZodObjectJIT",(e,t)=>{xc.init(e,t);let r=e._zod.parse,n=fe(()=>Xn(t)),o=m=>{let d=new Be(["shape","payload","ctx"]),y=n.value,P=B=>{let Z=De(B);return`shape[${Z}]._zod.run({ value: input[${Z}], issues: [] }, ctx)`};d.write("const input = payload.value;");let w=Object.create(null),F=0;for(let B of y.keys)w[B]=`key_${F++}`;d.write("const newResult = {};");for(let B of y.keys){let Z=w[B],O=De(B),Ht=m[B],er=Ht?._zod?.optin==="optional",ji=Ht?._zod?.optout==="optional";d.write(`const ${Z} = ${P(B)};`),er&&ji?d.write(`
+ if (${Z}.issues.length) {
+ if (${O} in input) {
+ payload.issues = payload.issues.concat(${Z}.issues.map(iss => ({
+ ...iss,
+ path: iss.path ? [${O}, ...iss.path] : [${O}]
+ })));
+ }
+ }
+
+ if (${Z}.value === undefined) {
+ if (${O} in input) {
+ newResult[${O}] = undefined;
+ }
+ } else {
+ newResult[${O}] = ${Z}.value;
+ }
+
+ `):er?d.write(`
+ if (${Z}.issues.length) {
+ payload.issues = payload.issues.concat(${Z}.issues.map(iss => ({
+ ...iss,
+ path: iss.path ? [${O}, ...iss.path] : [${O}]
+ })));
+ }
+
+ if (${Z}.value === undefined) {
+ if (${O} in input) {
+ newResult[${O}] = undefined;
+ }
+ } else {
+ newResult[${O}] = ${Z}.value;
+ }
+
+ `):d.write(`
+ const ${Z}_present = ${O} in input;
+ if (${Z}.issues.length) {
+ payload.issues = payload.issues.concat(${Z}.issues.map(iss => ({
+ ...iss,
+ path: iss.path ? [${O}, ...iss.path] : [${O}]
+ })));
+ }
+ if (!${Z}_present && !${Z}.issues.length) {
+ payload.issues.push({
+ code: "invalid_type",
+ expected: "nonoptional",
+ input: undefined,
+ path: [${O}]
+ });
+ }
+
+ if (${Z}_present) {
+ if (${Z}.value === undefined) {
+ newResult[${O}] = undefined;
+ } else {
+ newResult[${O}] = ${Z}.value;
+ }
+ }
+
+ `)}d.write("payload.value = newResult;"),d.write("return payload;");let Fi=d.compile();return(B,Z)=>Fi(m,B,Z)},s,i=re,c=!pe.jitless,u=c&&lt.value,f=t.catchall,p;e._zod.parse=(m,d)=>{p??(p=n.value);let y=m.value;return i(y)?c&&u&&d?.async===!1&&d.jitless!==!0?(s||(s=o(t.shape)),m=s(m,d),f?Yn([],y,m,d,p,e):m):r(m,d):(m.issues.push({expected:"object",code:"invalid_type",input:y,inst:e}),m)}});function mn(e,t,r,n){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let o=e.filter(s=>!X(s));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(s=>s.issues.map(i=>j(i,n,M())))}),t)}var zt=l("$ZodUnion",(e,t)=>{z.init(e,t),_(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),_(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),_(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),_(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){let n=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${n.map(o=>ve(o.source)).join("|")})$`)}});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,o)=>{if(r)return r(n,o);let s=!1,i=[];for(let c of t.options){let a=c._zod.run({value:n.value,issues:[]},o);if(a instanceof Promise)i.push(a),s=!0;else{if(a.issues.length===0)return a;i.push(a)}}return s?Promise.all(i).then(c=>mn(c,n,e,o)):mn(i,n,e,o)}});var eo=l("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,zt.init(e,t);let r=e._zod.parse;_(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[c,a]of Object.entries(i)){o[c]||(o[c]=new Set);for(let u of a)o[c].add(u)}}return o});let n=fe(()=>{let o=t.options,s=new Map;for(let i of o){let c=i._zod.propValues?.[t.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let a of c){if(s.has(a))throw new Error(`Duplicate discriminator value "${String(a)}"`);s.set(a,i)}}return s});e._zod.parse=(o,s)=>{let i=o.value;if(!re(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;let c=n.value.get(i?.[t.discriminator]);return c?c._zod.run(o,s):t.unionFallback||s.direction==="backward"?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()),input:i,path:[t.discriminator],inst:e}),o)}}),to=l("$ZodIntersection",(e,t)=>{z.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,s=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([a,u])=>hn(r,a,u)):hn(r,s,i)}});function wt(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(K(e)&&K(t)){let r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),o={...e,...t};for(let s of n){let i=wt(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 r=[];for(let n=0;n<e.length;n++){let o=e[n],s=t[n],i=wt(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function hn(e,t,r){let n=new Map,o;for(let c of t.issues)if(c.code==="unrecognized_keys"){o??(o=c);for(let a of c.keys)n.has(a)||n.set(a,{}),n.get(a).l=!0}else e.issues.push(c);for(let c of r.issues)if(c.code==="unrecognized_keys")for(let a of c.keys)n.has(a)||n.set(a,{}),n.get(a).r=!0;else e.issues.push(c);let s=[...n].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(s.length&&o&&e.issues.push({...o,keys:s}),X(e))return e;let i=wt(t.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}var ro=l("$ZodRecord",(e,t)=>{z.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!K(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let s=[],i=t.keyType._zod.values;if(i){r.value={};let c=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){c.add(typeof u=="number"?u.toString():u);let f=t.keyType._zod.run({value:u,issues:[]},n);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(f.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map(d=>j(d,n,M())),input:u,path:[u],inst:e});continue}let p=f.value,m=t.valueType._zod.run({value:o[u],issues:[]},n);m instanceof Promise?s.push(m.then(d=>{d.issues.length&&r.issues.push(...V(u,d.issues)),r.value[p]=d.value})):(m.issues.length&&r.issues.push(...V(u,m.issues)),r.value[p]=m.value)}let a;for(let u in o)c.has(u)||(a=a??[],a.push(u));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{r.value={};for(let c of Reflect.ownKeys(o)){if(c==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,c))continue;let a=t.keyType._zod.run({value:c,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof c=="string"&&_t.test(c)&&a.issues.length){let p=t.keyType._zod.run({value:Number(c),issues:[]},n);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");p.issues.length===0&&(a=p)}if(a.issues.length){t.mode==="loose"?r.value[c]=o[c]:r.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(p=>j(p,n,M())),input:c,path:[c],inst:e});continue}let f=t.valueType._zod.run({value:o[c],issues:[]},n);f instanceof Promise?s.push(f.then(p=>{p.issues.length&&r.issues.push(...V(c,p.issues)),r.value[a.value]=p.value})):(f.issues.length&&r.issues.push(...V(c,f.issues)),r.value[a.value]=f.value)}}return s.length?Promise.all(s).then(()=>r):r}});var no=l("$ZodEnum",(e,t)=>{z.init(e,t);let r=be(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(o=>pt.has(typeof o)).map(o=>typeof o=="string"?q(o):o.toString()).join("|")})$`),e._zod.parse=(o,s)=>{let i=o.value;return n.has(i)||o.issues.push({code:"invalid_value",values:r,input:i,inst:e}),o}}),oo=l("$ZodLiteral",(e,t)=>{if(z.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?q(n):n?q(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,o)=>{let s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),n}});var so=l("$ZodTransform",(e,t)=>{z.init(e,t),e._zod.optin="optional",e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new le(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r.fallback=!0,r));if(o instanceof Promise)throw new Q;return r.value=o,r.fallback=!0,r}});function yn(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var $t=l("$ZodOptional",(e,t)=>{z.init(e,t),e._zod.optin="optional",e._zod.optout="optional",_(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),_(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${ve(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){let o=r.value,s=t.innerType._zod.run(r,n);return s instanceof Promise?s.then(i=>yn(i,o)):yn(s,o)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),io=l("$ZodExactOptional",(e,t)=>{$t.init(e,t),_(e._zod,"values",()=>t.innerType._zod.values),_(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),co=l("$ZodNullable",(e,t)=>{z.init(e,t),_(e._zod,"optin",()=>t.innerType._zod.optin),_(e._zod,"optout",()=>t.innerType._zod.optout),_(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${ve(r.source)}|null)$`):void 0}),_(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),ao=l("$ZodDefault",(e,t)=>{z.init(e,t),e._zod.optin="optional",_(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>gn(s,t)):gn(o,t)}});function gn(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var uo=l("$ZodPrefault",(e,t)=>{z.init(e,t),e._zod.optin="optional",_(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),lo=l("$ZodNonOptional",(e,t)=>{z.init(e,t),_(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>_n(s,e)):_n(o,e)}});function _n(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 po=l("$ZodCatch",(e,t)=>{z.init(e,t),e._zod.optin="optional",_(e._zod,"optout",()=>t.innerType._zod.optout),_(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(i=>j(i,n,M()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>j(s,n,M()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var fo=l("$ZodPipe",(e,t)=>{z.init(e,t),_(e._zod,"values",()=>t.in._zod.values),_(e._zod,"optin",()=>t.in._zod.optin),_(e._zod,"optout",()=>t.out._zod.optout),_(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=t.out._zod.run(r,n);return s instanceof Promise?s.then(i=>Qe(i,t.in,n)):Qe(s,t.in,n)}let o=t.in._zod.run(r,n);return o instanceof Promise?o.then(s=>Qe(s,t.out,n)):Qe(o,t.out,n)}});function Qe(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}var mo=l("$ZodReadonly",(e,t)=>{z.init(e,t),_(e._zod,"propValues",()=>t.innerType._zod.propValues),_(e._zod,"values",()=>t.innerType._zod.values),_(e._zod,"optin",()=>t.innerType?._zod?.optin),_(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(xn):xn(o)}});function xn(e){return e.value=Object.freeze(e.value),e}var ho=l("$ZodLazy",(e,t)=>{z.init(e,t),_(e._zod,"innerType",()=>{let r=t;return r._cachedInner||(r._cachedInner=t.getter()),r._cachedInner}),_(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),_(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),_(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),_(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),yo=l("$ZodCustom",(e,t)=>{I.init(e,t),z.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>bn(s,r,n,e));bn(o,r,n,e)}});function bn(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(me(o))}}var go,Vu=Symbol("ZodOutput"),Wu=Symbol("ZodInput"),kt=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let n=r[0];return this._map.set(t,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let o={...n,...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 bc(){return new kt}(go=globalThis).__zod_globalRegistry??(go.__zod_globalRegistry=bc());var ne=globalThis.__zod_globalRegistry;function _o(e,t){return new e({type:"string",...h(t)})}function xo(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...h(t)})}function At(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...h(t)})}function bo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...h(t)})}function wo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...h(t)})}function vo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...h(t)})}function zo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...h(t)})}function $o(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...h(t)})}function ko(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...h(t)})}function Ao(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...h(t)})}function Zo(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...h(t)})}function So(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...h(t)})}function Eo(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...h(t)})}function Ro(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...h(t)})}function Po(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...h(t)})}function Oo(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...h(t)})}function Io(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...h(t)})}function To(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...h(t)})}function Co(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...h(t)})}function No(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...h(t)})}function Do(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...h(t)})}function Fo(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...h(t)})}function jo(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...h(t)})}function Lo(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...h(t)})}function Mo(e,t){return new e({type:"string",format:"date",check:"string_format",...h(t)})}function Uo(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...h(t)})}function Bo(e,t){return new e({type:"string",format:"duration",check:"string_format",...h(t)})}function Qo(e,t){return new e({type:"number",checks:[],...h(t)})}function Jo(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...h(t)})}function qo(e,t){return new e({type:"boolean",...h(t)})}function Vo(e,t){return new e({type:"null",...h(t)})}function Wo(e){return new e({type:"unknown"})}function Go(e,t){return new e({type:"never",...h(t)})}function Ve(e,t){return new xt({check:"less_than",...h(t),value:e,inclusive:!1})}function Ze(e,t){return new xt({check:"less_than",...h(t),value:e,inclusive:!0})}function We(e,t){return new bt({check:"greater_than",...h(t),value:e,inclusive:!1})}function Se(e,t){return new bt({check:"greater_than",...h(t),value:e,inclusive:!0})}function Ge(e,t){return new Yr({check:"multiple_of",...h(t),value:e})}function Ke(e,t){return new en({check:"max_length",...h(t),maximum:e})}function he(e,t){return new tn({check:"min_length",...h(t),minimum:e})}function Xe(e,t){return new rn({check:"length_equals",...h(t),length:e})}function Zt(e,t){return new nn({check:"string_format",format:"regex",...h(t),pattern:e})}function St(e){return new on({check:"string_format",format:"lowercase",...h(e)})}function Et(e){return new sn({check:"string_format",format:"uppercase",...h(e)})}function Rt(e,t){return new cn({check:"string_format",format:"includes",...h(t),includes:e})}function Pt(e,t){return new an({check:"string_format",format:"starts_with",...h(t),prefix:e})}function Ot(e,t){return new un({check:"string_format",format:"ends_with",...h(t),suffix:e})}function Y(e){return new ln({check:"overwrite",tx:e})}function It(e){return Y(t=>t.normalize(e))}function Tt(){return Y(e=>e.trim())}function Ct(){return Y(e=>e.toLowerCase())}function Nt(){return Y(e=>e.toUpperCase())}function Dt(){return Y(e=>ut(e))}function Ko(e,t,r){return new e({type:"array",element:t,...h(r)})}function Xo(e,t,r){return new e({type:"custom",check:"custom",fn:t,...h(r)})}function Yo(e,t){let r=wc(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(me(o,n.value,r._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(me(s))}},e(n.value,n)),t);return r}function wc(e,t){let r=new I({check:"custom",...h(t)});return r._zod.check=e,r}function Ft(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??ne,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 S(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s=t.seen.get(e);if(s)return s.count++,r.schemaPath.includes(e)&&(s.cycle=r.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i);let c=e._zod.toJSONSchema?.();if(c)i.schema=c;else{let f={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,f);else{let m=i.schema,d=t.processors[o.type];if(!d)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);d(e,t,m,f)}let p=e._zod.parent;p&&(i.ref||(i.ref=p),S(p,t,f),t.seen.get(p).isParent=!0)}let a=t.metadataRegistry.get(e);return a&&Object.assign(i.schema,a),t.io==="input"&&T(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&"_prefault"in i.schema&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function jt(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let i of e.seen.entries()){let c=e.metadataRegistry.get(i[0])?.id;if(c){let a=n.get(c);if(a&&a!==i[0])throw new Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(c,i[0])}}let o=i=>{let c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(i[0])?.id,m=e.external.uri??(y=>y);if(p)return{ref:m(p)};let d=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=d,{defId:d,ref:`${m("__shared")}#/${c}/${d}`}}if(i[1]===r)return{ref:"#"};let u=`#/${c}/`,f=i[1].schema.id??`__schema${e.counter++}`;return{defId:f,ref:u+f}},s=i=>{if(i[1].schema.$ref)return;let c=i[1],{ref:a,defId:u}=o(i);c.def={...c.schema},u&&(c.defId=u);let f=c.schema;for(let p in f)delete f[p];f.$ref=a};if(e.cycles==="throw")for(let i of e.seen.entries()){let c=i[1];if(c.cycle)throw new Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
+
+Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let c=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(c.cycle){s(i);continue}if(c.count>1&&e.reused==="ref"){s(i);continue}}}function Lt(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=c=>{let a=e.seen.get(c);if(a.ref===null)return;let u=a.def??a.schema,f={...u},p=a.ref;if(a.ref=null,p){n(p);let d=e.seen.get(p),y=d.schema;if(y.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(y)):Object.assign(u,y),Object.assign(u,f),c._zod.parent===p)for(let w in u)w==="$ref"||w==="allOf"||w in f||delete u[w];if(y.$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]}let m=c._zod.parent;if(m&&m!==p){n(m);let d=e.seen.get(m);if(d?.schema.$ref&&(u.$ref=d.schema.$ref,d.def))for(let y in u)y==="$ref"||y==="allOf"||y in d.def&&JSON.stringify(u[y])===JSON.stringify(d.def[y])&&delete u[y]}e.override({zodSchema:c,jsonSchema:u,path:a.path??[]})};for(let c of[...e.seen.entries()].reverse())n(c[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 c=e.external.registry.get(t)?.id;if(!c)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(c)}Object.assign(o,r.def??r.schema);let s=e.metadataRegistry.get(t)?.id;s!==void 0&&o.id===s&&delete o.id;let i=e.external?.defs??{};for(let c of e.seen.entries()){let a=c[1];a.def&&a.defId&&(a.def.id===a.defId&&delete a.def.id,i[a.defId]=a.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let c=JSON.parse(JSON.stringify(o));return Object.defineProperty(c,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ee(t,"input",e.processors),output:Ee(t,"output",e.processors)}},enumerable:!1,writable:!1}),c}catch{throw new Error("Error converting schema to JSON.")}}function T(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return T(n.element,r);if(n.type==="set")return T(n.valueType,r);if(n.type==="lazy")return T(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return T(n.innerType,r);if(n.type==="intersection")return T(n.left,r)||T(n.right,r);if(n.type==="record"||n.type==="map")return T(n.keyType,r)||T(n.valueType,r);if(n.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:T(n.in,r)||T(n.out,r);if(n.type==="object"){for(let o in n.shape)if(T(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(T(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(T(o,r))return!0;return!!(n.rest&&T(n.rest,r))}return!1}var Ho=(e,t={})=>r=>{let n=Ft({...r,processors:t});return S(e,n),jt(n,e),Lt(n,e)},Ee=(e,t,r={})=>n=>{let{libraryOptions:o,target:s}=n??{},i=Ft({...o??{},target:s,io:t,processors:r});return S(e,i),jt(i,e),Lt(i,e)};var vc={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},es=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:i,format:c,patterns:a,contentEncoding:u}=e._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),c&&(o.format=vc[c]??c,o.format===""&&delete o.format,c==="time"&&delete o.format),u&&(o.contentEncoding=u),a&&a.size>0){let f=[...a];f.length===1?o.pattern=f[0].source:f.length>1&&(o.allOf=[...f.map(p=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},ts=(e,t,r,n)=>{let o=r,{minimum:s,maximum:i,format:c,multipleOf:a,exclusiveMaximum:u,exclusiveMinimum:f}=e._zod.bag;typeof c=="string"&&c.includes("int")?o.type="integer":o.type="number";let p=typeof f=="number"&&f>=(s??Number.NEGATIVE_INFINITY),m=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),d=t.target==="draft-04"||t.target==="openapi-3.0";p?d?(o.minimum=f,o.exclusiveMinimum=!0):o.exclusiveMinimum=f:typeof s=="number"&&(o.minimum=s),m?d?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof a=="number"&&(o.multipleOf=a)},rs=(e,t,r,n)=>{r.type="boolean"};var ns=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var os=(e,t,r,n)=>{r.not={}};var ss=(e,t,r,n)=>{};var is=(e,t,r,n)=>{let o=e._zod.def,s=be(o.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},cs=(e,t,r,n)=>{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];r.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[i]:r.const=i}else s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),s.every(i=>typeof i=="boolean")&&(r.type="boolean"),s.every(i=>i===null)&&(r.type="null"),r.enum=s};var as=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var us=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var ls=(e,t,r,n)=>{let o=r,s=e._zod.def,{minimum:i,maximum:c}=e._zod.bag;typeof i=="number"&&(o.minItems=i),typeof c=="number"&&(o.maxItems=c),o.type="array",o.items=S(s.element,t,{...n,path:[...n.path,"items"]})},ps=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="object",o.properties={};let i=s.shape;for(let u in i)o.properties[u]=S(i[u],t,{...n,path:[...n.path,"properties",u]});let c=new Set(Object.keys(i)),a=new Set([...c].filter(u=>{let f=s.shape[u]._zod;return t.io==="input"?f.optin===void 0:f.optout===void 0}));a.size>0&&(o.required=Array.from(a)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=S(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},ds=(e,t,r,n)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((c,a)=>S(c,t,{...n,path:[...n.path,s?"oneOf":"anyOf",a]}));s?r.oneOf=i:r.anyOf=i},fs=(e,t,r,n)=>{let o=e._zod.def,s=S(o.left,t,{...n,path:[...n.path,"allOf",0]}),i=S(o.right,t,{...n,path:[...n.path,"allOf",1]}),c=u=>"allOf"in u&&Object.keys(u).length===1,a=[...c(s)?s.allOf:[s],...c(i)?i.allOf:[i]];r.allOf=a};var ms=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="object";let i=s.keyType,a=i._zod.bag?.patterns;if(s.mode==="loose"&&a&&a.size>0){let f=S(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let p of a)o.patternProperties[p.source]=f}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=S(s.keyType,t,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=S(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]});let u=i._zod.values;if(u){let f=[...u].filter(p=>typeof p=="string"||typeof p=="number");f.length>0&&(o.required=f)}},hs=(e,t,r,n)=>{let o=e._zod.def,s=S(o.innerType,t,n),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=o.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},ys=(e,t,r,n)=>{let o=e._zod.def;S(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},gs=(e,t,r,n)=>{let o=e._zod.def;S(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},_s=(e,t,r,n)=>{let o=e._zod.def;S(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},xs=(e,t,r,n)=>{let o=e._zod.def;S(o.innerType,t,n);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")}r.default=i},bs=(e,t,r,n)=>{let o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?o.out:o.in:o.out;S(i,t,n);let c=t.seen.get(e);c.ref=i},ws=(e,t,r,n)=>{let o=e._zod.def;S(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.readOnly=!0};var Mt=(e,t,r,n)=>{let o=e._zod.def;S(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},vs=(e,t,r,n)=>{let o=e._zod.innerType;S(o,t,n);let s=t.seen.get(e);s.ref=o};var Ec=l("ZodISODateTime",(e,t)=>{On.init(e,t),A.init(e,t)});function zs(e){return Lo(Ec,e)}var Rc=l("ZodISODate",(e,t)=>{In.init(e,t),A.init(e,t)});function $s(e){return Mo(Rc,e)}var Pc=l("ZodISOTime",(e,t)=>{Tn.init(e,t),A.init(e,t)});function ks(e){return Uo(Pc,e)}var Oc=l("ZodISODuration",(e,t)=>{Cn.init(e,t),A.init(e,t)});function As(e){return Bo(Oc,e)}var Cc=(e,t)=>{je.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>dr(e,r)},flatten:{value:r=>pr(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,de,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,de,2)}},isEmpty:{get(){return e.issues.length===0}}})};var D=l("ZodError",Cc,{Parent:Error});var Zs=Le(D),Ss=Me(D),Es=$e(D),Rs=ke(D),Ps=hr(D),Os=yr(D),Is=gr(D),Ts=_r(D),Cs=xr(D),Ns=br(D),Ds=wr(D),Fs=vr(D);var js=new WeakMap;function Re(e,t,r){let n=Object.getPrototypeOf(e),o=js.get(n);if(o||(o=new Set,js.set(n,o)),!o.has(t)){o.add(t);for(let s in r){let i=r[s];Object.defineProperty(n,s,{configurable:!0,enumerable:!1,get(){let c=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:c}),c},set(c){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:c})}})}}}var k=l("ZodType",(e,t)=>(z.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ee(e,"input"),output:Ee(e,"output")}}),e.toJSONSchema=Ho(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,n)=>Zs(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Es(e,r,n),e.parseAsync=async(r,n)=>Ss(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Rs(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>Ps(e,r,n),e.decode=(r,n)=>Os(e,r,n),e.encodeAsync=async(r,n)=>Is(e,r,n),e.decodeAsync=async(r,n)=>Ts(e,r,n),e.safeEncode=(r,n)=>Cs(e,r,n),e.safeDecode=(r,n)=>Ns(e,r,n),e.safeEncodeAsync=async(r,n)=>Ds(e,r,n),e.safeDecodeAsync=async(r,n)=>Fs(e,r,n),Re(e,"ZodType",{check(...r){let n=this.def;return this.clone(x.mergeDefs(n,{checks:[...n.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return U(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(Ea(r,n))},superRefine(r,n){return this.check(Ra(r,n))},overwrite(r){return this.check(Y(r))},optional(){return Qs(this)},exactOptional(){return ha(this)},nullable(){return Js(this)},nullish(){return Qs(Js(this))},nonoptional(r){return wa(this,r)},array(){return N(this)},or(r){return et([this,r])},and(r){return la(this,r)},transform(r){return qs(this,fa(r))},default(r){return _a(this,r)},prefault(r){return ba(this,r)},catch(r){return za(this,r)},pipe(r){return qs(this,r)},readonly(){return Aa(this)},describe(r){let n=this.clone();return ne.add(n,{description:r}),n},meta(...r){if(r.length===0)return ne.get(this);let n=this.clone();return ne.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){return ne.get(e)?.description},configurable:!0}),e)),Vs=l("_ZodString",(e,t)=>{qe.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,o,s)=>es(e,n,o,s);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,Re(e,"_ZodString",{regex(...n){return this.check(Zt(...n))},includes(...n){return this.check(Rt(...n))},startsWith(...n){return this.check(Pt(...n))},endsWith(...n){return this.check(Ot(...n))},min(...n){return this.check(he(...n))},max(...n){return this.check(Ke(...n))},length(...n){return this.check(Xe(...n))},nonempty(...n){return this.check(he(1,...n))},lowercase(n){return this.check(St(n))},uppercase(n){return this.check(Et(n))},trim(){return this.check(Tt())},normalize(...n){return this.check(It(...n))},toLowerCase(){return this.check(Ct())},toUpperCase(){return this.check(Nt())},slugify(){return this.check(Dt())}})}),Dc=l("ZodString",(e,t)=>{qe.init(e,t),Vs.init(e,t),e.email=r=>e.check(xo(Fc,r)),e.url=r=>e.check($o(jc,r)),e.jwt=r=>e.check(jo(ea,r)),e.emoji=r=>e.check(ko(Lc,r)),e.guid=r=>e.check(At(Ls,r)),e.uuid=r=>e.check(bo(He,r)),e.uuidv4=r=>e.check(wo(He,r)),e.uuidv6=r=>e.check(vo(He,r)),e.uuidv7=r=>e.check(zo(He,r)),e.nanoid=r=>e.check(Ao(Mc,r)),e.guid=r=>e.check(At(Ls,r)),e.cuid=r=>e.check(Zo(Uc,r)),e.cuid2=r=>e.check(So(Bc,r)),e.ulid=r=>e.check(Eo(Qc,r)),e.base64=r=>e.check(No(Xc,r)),e.base64url=r=>e.check(Do(Yc,r)),e.xid=r=>e.check(Ro(Jc,r)),e.ksuid=r=>e.check(Po(qc,r)),e.ipv4=r=>e.check(Oo(Vc,r)),e.ipv6=r=>e.check(Io(Wc,r)),e.cidrv4=r=>e.check(To(Gc,r)),e.cidrv6=r=>e.check(Co(Kc,r)),e.e164=r=>e.check(Fo(Hc,r)),e.datetime=r=>e.check(zs(r)),e.date=r=>e.check($s(r)),e.time=r=>e.check(ks(r)),e.duration=r=>e.check(As(r))});function g(e){return _o(Dc,e)}var A=l("ZodStringFormat",(e,t)=>{$.init(e,t),Vs.init(e,t)}),Fc=l("ZodEmail",(e,t)=>{zn.init(e,t),A.init(e,t)});var Ls=l("ZodGUID",(e,t)=>{wn.init(e,t),A.init(e,t)});var He=l("ZodUUID",(e,t)=>{vn.init(e,t),A.init(e,t)});var jc=l("ZodURL",(e,t)=>{$n.init(e,t),A.init(e,t)});var Lc=l("ZodEmoji",(e,t)=>{kn.init(e,t),A.init(e,t)});var Mc=l("ZodNanoID",(e,t)=>{An.init(e,t),A.init(e,t)});var Uc=l("ZodCUID",(e,t)=>{Zn.init(e,t),A.init(e,t)});var Bc=l("ZodCUID2",(e,t)=>{Sn.init(e,t),A.init(e,t)});var Qc=l("ZodULID",(e,t)=>{En.init(e,t),A.init(e,t)});var Jc=l("ZodXID",(e,t)=>{Rn.init(e,t),A.init(e,t)});var qc=l("ZodKSUID",(e,t)=>{Pn.init(e,t),A.init(e,t)});var Vc=l("ZodIPv4",(e,t)=>{Nn.init(e,t),A.init(e,t)});var Wc=l("ZodIPv6",(e,t)=>{Dn.init(e,t),A.init(e,t)});var Gc=l("ZodCIDRv4",(e,t)=>{Fn.init(e,t),A.init(e,t)});var Kc=l("ZodCIDRv6",(e,t)=>{jn.init(e,t),A.init(e,t)});var Xc=l("ZodBase64",(e,t)=>{Mn.init(e,t),A.init(e,t)});var Yc=l("ZodBase64URL",(e,t)=>{Un.init(e,t),A.init(e,t)});var Hc=l("ZodE164",(e,t)=>{Bn.init(e,t),A.init(e,t)});var ea=l("ZodJWT",(e,t)=>{Qn.init(e,t),A.init(e,t)});var Ws=l("ZodNumber",(e,t)=>{vt.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,o,s)=>ts(e,n,o,s),Re(e,"ZodNumber",{gt(n,o){return this.check(We(n,o))},gte(n,o){return this.check(Se(n,o))},min(n,o){return this.check(Se(n,o))},lt(n,o){return this.check(Ve(n,o))},lte(n,o){return this.check(Ze(n,o))},max(n,o){return this.check(Ze(n,o))},int(n){return this.check(Ms(n))},safe(n){return this.check(Ms(n))},positive(n){return this.check(We(0,n))},nonnegative(n){return this.check(Se(0,n))},negative(n){return this.check(Ve(0,n))},nonpositive(n){return this.check(Ze(0,n))},multipleOf(n,o){return this.check(Ge(n,o))},step(n,o){return this.check(Ge(n,o))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function v(e){return Qo(Ws,e)}var ta=l("ZodNumberFormat",(e,t)=>{Jn.init(e,t),Ws.init(e,t)});function Ms(e){return Jo(ta,e)}var ra=l("ZodBoolean",(e,t)=>{qn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>rs(e,r,n,o)});function oe(e){return qo(ra,e)}var na=l("ZodNull",(e,t)=>{Vn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ns(e,r,n,o)});function oa(e){return Vo(na,e)}var sa=l("ZodUnknown",(e,t)=>{Wn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ss(e,r,n,o)});function Us(){return Wo(sa)}var ia=l("ZodNever",(e,t)=>{Gn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>os(e,r,n,o)});function Gs(e){return Go(ia,e)}var ca=l("ZodArray",(e,t)=>{Kn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ls(e,r,n,o),e.element=t.element,Re(e,"ZodArray",{min(r,n){return this.check(he(r,n))},nonempty(r){return this.check(he(1,r))},max(r,n){return this.check(Ke(r,n))},length(r,n){return this.check(Xe(r,n))},unwrap(){return this.element}})});function N(e,t){return Ko(ca,e,t)}var Ks=l("ZodObject",(e,t)=>{Hn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ps(e,r,n,o),x.defineLazy(e,"shape",()=>t.shape),Re(e,"ZodObject",{keyof(){return H(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:Us()})},loose(){return this.clone({...this._zod.def,catchall:Us()})},strict(){return this.clone({...this._zod.def,catchall:Gs()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return x.extend(this,r)},safeExtend(r){return x.safeExtend(this,r)},merge(r){return x.merge(this,r)},pick(r){return x.pick(this,r)},omit(r){return x.omit(this,r)},partial(...r){return x.partial(Ys,this,r[0])},required(...r){return x.required(Hs,this,r[0])}})});function L(e,t){let r={type:"object",shape:e??{},...x.normalizeParams(t)};return new Ks(r)}function E(e,t){return new Ks({type:"object",shape:e,catchall:Gs(),...x.normalizeParams(t)})}var Xs=l("ZodUnion",(e,t)=>{zt.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ds(e,r,n,o),e.options=t.options});function et(e,t){return new Xs({type:"union",options:e,...x.normalizeParams(t)})}var aa=l("ZodDiscriminatedUnion",(e,t)=>{Xs.init(e,t),eo.init(e,t)});function tt(e,t,r){return new aa({type:"union",options:t,discriminator:e,...x.normalizeParams(r)})}var ua=l("ZodIntersection",(e,t)=>{to.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>fs(e,r,n,o)});function la(e,t){return new ua({type:"intersection",left:e,right:t})}var Bs=l("ZodRecord",(e,t)=>{ro.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ms(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType});function se(e,t,r){return!t||!t._zod?new Bs({type:"record",keyType:g(),valueType:e,...x.normalizeParams(t)}):new Bs({type:"record",keyType:e,valueType:t,...x.normalizeParams(r)})}var Ut=l("ZodEnum",(e,t)=>{no.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,o,s)=>is(e,n,o,s),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Ut({...t,checks:[],...x.normalizeParams(o),entries:s})},e.exclude=(n,o)=>{let s={...t.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Ut({...t,checks:[],...x.normalizeParams(o),entries:s})}});function H(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Ut({type:"enum",entries:r,...x.normalizeParams(t)})}var pa=l("ZodLiteral",(e,t)=>{oo.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cs(e,r,n,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 R(e,t){return new pa({type:"literal",values:Array.isArray(e)?e:[e],...x.normalizeParams(t)})}var da=l("ZodTransform",(e,t)=>{so.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>us(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new le(e.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(x.issue(s,r.value,t));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),r.issues.push(x.issue(i))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r.fallback=!0,r)):(r.value=o,r.fallback=!0,r)}});function fa(e){return new da({type:"transform",transform:e})}var Ys=l("ZodOptional",(e,t)=>{$t.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Mt(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Qs(e){return new Ys({type:"optional",innerType:e})}var ma=l("ZodExactOptional",(e,t)=>{io.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Mt(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function ha(e){return new ma({type:"optional",innerType:e})}var ya=l("ZodNullable",(e,t)=>{co.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>hs(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Js(e){return new ya({type:"nullable",innerType:e})}var ga=l("ZodDefault",(e,t)=>{ao.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>gs(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function _a(e,t){return new ga({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():x.shallowClone(t)}})}var xa=l("ZodPrefault",(e,t)=>{uo.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>_s(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function ba(e,t){return new xa({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():x.shallowClone(t)}})}var Hs=l("ZodNonOptional",(e,t)=>{lo.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ys(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function wa(e,t){return new Hs({type:"nonoptional",innerType:e,...x.normalizeParams(t)})}var va=l("ZodCatch",(e,t)=>{po.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>xs(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function za(e,t){return new va({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var $a=l("ZodPipe",(e,t)=>{fo.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>bs(e,r,n,o),e.in=t.in,e.out=t.out});function qs(e,t){return new $a({type:"pipe",in:e,out:t})}var ka=l("ZodReadonly",(e,t)=>{mo.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ws(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Aa(e){return new ka({type:"readonly",innerType:e})}var Za=l("ZodLazy",(e,t)=>{ho.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>vs(e,r,n,o),e.unwrap=()=>e._zod.def.getter()});function Bt(e){return new Za({type:"lazy",getter:e})}var Sa=l("ZodCustom",(e,t)=>{yo.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>as(e,r,n,o)});function Ea(e,t={}){return Xo(Sa,e,t)}function Ra(e,t){return Yo(e,t)}function Pe(e){let t=Bt(()=>et([g(e),v(),oe(),oa(),N(t),se(g(),t)]));return t}var ei=e=>"field"in e?[e]:("all"in e?e.all:e.any).flatMap(ei),ti=e=>ei(e);var rt=(e,t)=>{if("field"in e)return t(e);let r="all"in e?e.all:e.any,n=!1;if("all"in e){for(let o of r){let s=rt(o,t);if(s===!1)return!1;n||=s===void 0}return n?void 0:!0}for(let o of r){let s=rt(o,t);if(s===!0)return!0;n||=s===void 0}return n?void 0:!1},ri=e=>JSON.stringify(e),Qt=e=>{if("field"in e)return{conditions:1,depth:0};let t="all"in e?e.all:e.any,r=0,n=1;for(let o of t){let s=Qt(o);r+=s.conditions,n=Math.max(n,s.depth+1)}return{conditions:r,depth:n}},ni=(e,t={})=>{let r=o=>{let s=N(o),i=t.maximumChildren===void 0?s:s.max(t.maximumChildren);return et([e,E({all:i}),E({any:i})])},n=Bt(()=>r(n));return t.maximumConditions===void 0&&t.maximumDepth===void 0?n:n.superRefine((o,s)=>{let{conditions:i,depth:c}=Qt(o);t.maximumConditions!==void 0&&i>t.maximumConditions&&s.addIssue({code:"custom",message:t.maximumConditionsMessage??"Query exceeds the condition limit"}),t.maximumDepth!==void 0&&c>t.maximumDepth&&s.addIssue({code:"custom",message:t.maximumDepthMessage??"Query exceeds the nesting limit"})})};var b={requestBytes:524288,filterCount:32,filterDepth:8,sortCount:8,outputFieldCount:256,fieldPathDepth:9,defaultResultCount:20,resultCount:1e3,resultBytes:16777216,candidateDocuments:1e3,databaseBytes:512e3,frontmatterBytes:65536,frontmatterDepth:8,frontmatterFields:256,frontmatterStringBytes:16384,jsonBytes:1048576,jsonDepth:8,jsonFields:256,jsonStringBytes:16384,indexedPropertiesBytes:65536,excerptBytes:2048,hydratedFileBytes:1048576,hydratedTotalBytes:2097152,hydratedFileCount:20,hydratedRangeBytes:262144,concurrentContentReads:8};var Pa=g().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"}),oi=E({_id:g().min(1),_type:R("asset.file"),name:g().min(1),description:g().optional(),path:Pa,key:g(),folderId:g().min(1).optional(),extension:g().regex(/^[a-z0-9]*$/),mimeType:g().min(1),size:v().int().nonnegative(),createdAt:g().datetime().optional(),revision:g().min(1),contentRef:g().min(1),properties:se(g(),Pe()),excerpt:g().optional(),metadataError:E({code:g().min(1),message:g().min(1)}).optional()}),Oa=oi.partial().required({_id:!0}),Ia=H(["null","boolean","number","string","object","array"]),Ta=L({format:R("webstudio-builder-asset-field-catalog"),version:R(1),canonicalRevision:g().regex(/^sha256:[a-f0-9]{64}$/),documentCount:v().int().nonnegative(),fields:se(g().min(1),L({queryPath:N(g().min(1)).min(1).max(b.fieldPathDepth).optional(),types:N(Ia).min(1),occurrences:v().int().positive(),optional:R(!0).optional(),mixed:R(!0).optional()}))}).superRefine((e,t)=>{for(let[r,n]of Object.entries(e.fields)){let o=[...new Set(n.types)].sort();JSON.stringify(n.types)!==JSON.stringify(o)&&t.addIssue({code:"custom",path:["fields",r,"types"],message:"Observed field types must be unique and sorted"}),n.occurrences>e.documentCount&&t.addIssue({code:"custom",path:["fields",r,"occurrences"],message:"Field occurrences cannot exceed the document count"});let s=n.occurrences<e.documentCount;n.optional===!0!==s&&t.addIssue({code:"custom",path:["fields",r,"optional"],message:"Field optionality must match its occurrence count"});let i=o.length>1;n.mixed===!0!==i&&t.addIssue({code:"custom",path:["fields",r,"mixed"],message:"Mixed status must match the observed types"})}}),qt=g().regex(/^sha256:[a-f0-9]{64}$/),si=E({format:R("webstudio-content-database"),version:R(1),assetRevision:qt,documents:N(Oa),contents:se(g().min(1),g()).optional(),assetReferences:se(g().min(1),N(E({start:v().int().nonnegative(),end:v().int().positive(),assetId:g().min(1),suffix:g().min(1).optional()}).refine(({start:e,end:t})=>t>e,{message:"Markdown asset reference range must not be empty"}))).optional(),fieldCatalog:Ta,database:E({maxBytes:v().int().positive(),unboundedBytes:v().int().nonnegative(),sourceDocumentCount:v().int().nonnegative()}).optional(),integrity:E({algorithm:R("sha256"),checksum:qt})}).superRefine((e,t)=>{e.documents.length>b.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"});let r;for(let[o,s]of e.documents.entries())r!==void 0&&s._id<=r&&t.addIssue({code:"custom",path:["documents",o,"_id"],message:"Asset index documents must have unique sorted IDs"}),r=s._id;let n=new Set(e.documents.flatMap(({contentRef:o})=>o===void 0?[]:[o]));for(let o of Object.keys(e.contents??{}))n.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??{}))n.has(o)===!1&&t.addIssue({code:"custom",path:["assetReferences",o],message:"Asset references must belong to an indexed document"})}),Ca=tt("mode",[L({mode:R("none")}),L({mode:R("full"),maxBytes:v().int().positive().max(b.hydratedFileBytes).optional()}),L({mode:R("range"),offset:v().int().nonnegative(),length:v().int().positive().max(b.hydratedRangeBytes)}),L({mode:R("markdown-body"),maxBytes:v().int().positive().max(b.hydratedFileBytes).optional()})]),Vt={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"]},ii=Object.keys(Vt),ci=["url","width","height"],Wt=e=>ci.includes(e),ai=ii.filter(e=>Wt(e)===!1&&e!=="excerpt"),ui=ai.filter(e=>e!=="id"),li=e=>ai.includes(e),Na=H(ii),Oe=N(g().min(1)).min(1).max(b.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||Na.safeParse(e[0]).success===!1)&&t.addIssue({code:"custom",message:"Asset query field path is unsupported"})}),Jt=oe().default(!0),Da=tt("mode",[E({mode:R("all"),includeMetadata:Jt}),E({mode:R("base"),includeMetadata:Jt}),E({mode:R("fields"),includeMetadata:Jt,fields:N(Oe).max(b.outputFieldCount).refine(e=>new Set(e.map(ri)).size===e.length,{error:"Selected output fields must be unique"})})]),Fa={mode:"fields",includeMetadata:!1,fields:ci.map(e=>[e])},pi=["eq","ne","contains","startsWith","endsWith","gt","gte","lt","lte"],Dp=[...pi,"in","exists","isEmpty"],ja=E({field:Oe,operator:H(pi),value:Pe()}),La=E({field:Oe,operator:R("in"),value:N(Pe()).max(b.resultCount)}),Ma=E({field:Oe,operator:H(["exists","isEmpty"]),value:oe()}),Ua=tt("operator",[ja,La,Ma]),Ba=ni(Ua,{maximumChildren:b.filterCount,maximumConditions:b.filterCount,maximumDepth:b.filterDepth,maximumConditionsMessage:"Asset query exceeds the filter limit",maximumDepthMessage:"Asset query exceeds the filter nesting limit"});var Qa=Ba,di=e=>{let t=new Set(["eq","ne","in","exists"]);return e.some(r=>r==="string"||r==="array")&&t.add("contains"),e.includes("string")&&(t.add("startsWith"),t.add("endsWith")),e.some(r=>r==="string"||r==="number")&&(t.add("gt"),t.add("gte"),t.add("lt"),t.add("lte")),e.some(r=>r==="string"||r==="array"||r==="object")&&t.add("isEmpty"),[...t]},Ja=E({field:Oe,direction:H(["asc","desc"])}),qa=({output:e,content:t})=>e.includeMetadata||e.mode==="all"||e.mode==="fields"&&e.fields.length>0||t.mode!=="none",Gt=E({where:Qa.default({all:[]}),sort:N(Ja).max(b.sortCount).default([]),limit:v().int().nonnegative().max(b.resultCount).default(b.defaultResultCount),offset:v().int().nonnegative().max(b.candidateDocuments).default(0),output:Da.default(Fa),content:Ca.default({mode:"none"})}).refine(qa,{error:"Select at least one asset query output"}),fi=E({query:Gt,indexRevision:g().min(1).max(255).optional()}),Va=L({_id:g().min(1),revision:g().min(1),contentRef:g().min(1),encoding:R("utf-8"),text:g(),range:L({offset:v().int().nonnegative(),length:v().int().nonnegative(),total:v().int().nonnegative()}).optional()}),Wa=Va.omit({_id:!0,revision:!0,contentRef:!0}),Ga=oi.omit({_id:!0,_type:!0,contentRef:!0}).partial().extend({id:g().min(1),url:g().min(1).optional(),width:v().positive().optional(),height:v().positive().optional(),content:Wa.optional()}).refine(e=>e.width===void 0==(e.height===void 0),{error:"Asset dimensions must include both width and height"}),Ka=E({format:R("webstudio-content-database"),version:R(1),revision:qt,usedBytes:v().int().nonnegative(),maxBytes:v().int().positive(),unboundedBytes:v().int().nonnegative(),includedDocumentCount:v().int().nonnegative(),omittedDocumentCount:v().int().nonnegative(),truncated:oe()}),Xa=Ka.pick({usedBytes:!0,maxBytes:!0,unboundedBytes:!0,includedDocumentCount:!0,omittedDocumentCount:!0,truncated:!0}).extend({scope:R("query-preview")}),Ya=E({items:N(Ga),totalCount:v().int().nonnegative(),hasMore:oe()}),Fp=E({data:Ya,__diagnostics__:Xa}),Ha=H(["INVALID_REQUEST","REQUEST_CANCELLED","UNAUTHORIZED","FORBIDDEN","STALE_INDEX","CONTENT_IDENTITY_REQUIRED","CONTENT_NOT_TEXT","CONTENT_DECODING_FAILED","CONTENT_LIMIT_EXCEEDED","INTERNAL_ERROR"]),eu=L({ok:R(!1),error:L({code:Ha,message:g().min(1),retryable:oe(),details:se(g(),Pe()).optional()}),meta:L({queryHash:g().min(1).optional(),indexRevision:g().min(1).optional(),assetRevision:g().min(1).optional()}).optional()}),mi=({code:e,message:t,retryable:r=!1,details:n})=>eu.parse({ok:!1,error:{code:e,message:t,retryable:r,details:n}});function ie(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 n=ie(e.toJSON(),t);return t.delete(e),n}if(t.has(e))throw new Error("Circular reference detected");t.add(e);let r;if(Array.isArray(e))r=`[${e.map(o=>ie(o===void 0||typeof o=="symbol"?null:o,t)).join(",")}]`;else{let n=[];for(let o of Object.keys(e).sort())e[o]===void 0||typeof e[o]=="symbol"||n.push(`${ie(o)}:${ie(e[o],t)}`);r=`{${n.join(",")}}`}return t.delete(e),r}var tu=new TextEncoder,ye=e=>tu.encode(e),ee=e=>ye(e).byteLength,ce=class extends Error{constructor(){super("Byte stream exceeds the configured limit"),this.name="ByteLimitExceededError"}},ru=(e,t)=>{let r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.byteLength;return r},nu=e=>typeof e=="string"?{async*[Symbol.asyncIterator](){yield ye(e)}}:e instanceof Uint8Array?{async*[Symbol.asyncIterator](){yield e}}:e,ou=async(e,t)=>{let r=[],n=0;for await(let o of nu(e)){let s=t-n;if(s<=0)break;let i=o.subarray(0,s);if(r.push(i),n+=i.byteLength,n===t)break}return ru(r,n)},nt=async(e,t)=>{let r=await ou(e,t+1);if(r.byteLength>t)throw new ce;return r},ae=e=>new TextDecoder("utf-8",{fatal:!0}).decode(e),hi=e=>e.charCodeAt(0)===65279?e.slice(1):e;var yi=e=>{for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(t+1>=e.length||n<56320||n>57343)throw new Error("JSON strings cannot contain lone Unicode surrogates");t+=1;continue}if(r>=56320&&r<=57343)throw new Error("JSON strings cannot contain lone Unicode surrogates")}},Kt=(e,t)=>{if(e===null||typeof e=="boolean")return e;if(typeof e=="string")return yi(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 r=[];for(let n=0;n<e.length;n+=1){if(Object.hasOwn(e,n)===!1)throw new Error("JSON arrays cannot be sparse");let o=e[n];if(o===void 0)throw new Error("JSON arrays cannot contain undefined values");r.push(Kt(o,t))}if(Object.keys(e).length!==e.length)throw new Error("JSON arrays cannot contain named properties");return r}finally{t.delete(e)}}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==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 n={};try{for(let[o,s]of Object.entries(e))yi(o),s!==void 0&&Object.defineProperty(n,o,{value:Kt(s,t),enumerable:!0,configurable:!0,writable:!0})}finally{t.delete(e)}return n}throw new Error("Value cannot be represented as JSON")},su=e=>Kt(e,new Set),te=e=>{let t=ie(su(e));if(t===void 0)throw new Error("Value cannot be represented as canonical JSON");return t},Ie=(e,t)=>e<t?-1:e>t?1:0,gi=async e=>{let t=typeof e=="string"?ye(e):e,r=await globalThis.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r),n=>n.toString(16).padStart(2,"0")).join("")};var _i=e=>te(si.parse(e)),xi=e=>[...new Set(Object.values(e.assetReferences??{}).flat().map(({assetId:t})=>t))].sort();var ue=class extends Error{code;constructor(t,r){super(r),this.name="MarkdownMetadataError",this.code=t}};var Te=new Uint8Array([239,187,191]),Kp=Te.byteLength+10,iu=(e,t,r=0)=>e.byteLength-r<t.byteLength?!1:t.every((n,o)=>e[r+o]===n),bi=(e,t)=>{let r=0;if(iu(e,Te))r=Te.byteLength;else if(e.byteLength<Te.byteLength&&Te.slice(0,e.byteLength).every((s,i)=>s===e[i]))return t?null:void 0;if(e.byteLength<r+4)return t?null:void 0;if(e[r]!==45||e[r+1]!==45||e[r+2]!==45)return null;let n=r+3;if(e[n]===10)n+=1;else if(e[n]===13){if(e.byteLength===n+1)return t?null:void 0;if(e[n+1]!==10)return null;n+=2}else return null;let o=n;for(let s=n;s<=e.byteLength;s+=1){let i=s===e.byteLength;if(i===!1&&e[s]!==10)continue;if(i&&t===!1)return;let c=s;if(c>o&&e[c-1]===13&&(c-=1),c-o===3&&(e[o]===45&&e[o+1]===45&&e[o+2]===45||e[o]===46&&e[o+1]===46&&e[o+2]===46))return{yamlStart:n,yamlEnd:o,blockEnd:i?s:s+1};o=s+1}};var wi=async(e,t=b.hydratedFileBytes)=>{if(Number.isInteger(t)===!1||t<=0||t>b.hydratedFileBytes)throw new ue("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown body byte limit is outside the supported range");let r;try{r=await nt(e,t)}catch(c){throw c instanceof ce?new ue("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown content exceeds the byte limit"):c}let n;try{n=ae(r)}catch{throw new ue("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}let s=bi(r,!0)?.blockEnd??0,i;try{i=s===0?hi(n):ae(r.subarray(s))}catch{throw new ue("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}return{body:i,bodyBytes:ee(i),sourceBytes:r.byteLength}};var vi=async(e,t,r)=>{if(Number.isSafeInteger(t)===!1||t<=0)throw new Error("Concurrency must be a positive safe integer");let n=0,o=new Array(e.length),s=async()=>{for(;n<e.length;){let u=n;n+=1,o[u]=await r(e[u])}},i=Array.from({length:Math.min(t,e.length)},s),a=(await Promise.allSettled(i)).find(u=>u.status==="rejected");if(a!==void 0)throw a.reason;return o};var cu=(e,t)=>{if(t===void 0||t.length===0)return e;let r=new URL("https://content.webstudio.invalid/__assets__/"),n=new URL(e,r),o=new URL(t,r);for(let[c,a]of o.searchParams)n.searchParams.append(c,a);if(o.hash!==""&&(n.hash=o.hash),URL.canParse(e))return n.href;if(e.startsWith("//"))return`//${n.host}${n.pathname}${n.search}${n.hash}`;if(e.startsWith("/"))return`${n.pathname}${n.search}${n.hash}`;let s=r.pathname;return`${n.pathname.startsWith(s)?n.pathname.slice(s.length):n.pathname}${n.search}${n.hash}`},zi=({markdown:e,references:t,assetUrls:r})=>{let n=e.length,o=e;for(let s of[...t].sort((i,c)=>c.start-i.start)){if(s.start<0||s.end<=s.start||s.end>e.length||s.end>n)throw new Error("Markdown asset reference range is invalid");n=s.start;let i=r[s.assetId];if(i===void 0)continue;let c=cu(i,s.suffix);o=`${o.slice(0,s.start)}${c}${o.slice(s.end)}`}return o};var C=class extends Error{code;details;constructor({code:t,message:r,details:n}){super(r),this.name="AssetResourceHydrationError",this.code=t,this.details=n}},au=e=>{if(e===null)return[];let t=Array.isArray(e)?e:[e],r=new Map;for(let n of t){if(typeof n!="object"||n===null||!("_id"in n)||typeof n._id!="string"||!("revision"in n)||typeof n.revision!="string"||!("contentRef"in n)||typeof n.contentRef!="string")throw new C({code:"CONTENT_IDENTITY_REQUIRED",message:"Hydrated query results must retain _id, revision, and contentRef"});let o=r.get(n._id);if(o!==void 0&&(o.revision!==n.revision||o.contentRef!==n.contentRef))throw new C({code:"CONTENT_IDENTITY_REQUIRED",message:"A selected asset ID has conflicting content identity",details:{assetId:n._id}});r.set(n._id,{_id:n._id,revision:n.revision,contentRef:n.contentRef})}return Array.from(r.values())},uu=e=>typeof e.mimeType=="string"&&(e.mimeType.startsWith("text/")||["application/json","application/javascript","application/xml","image/svg+xml"].includes(e.mimeType)),lu=async({read:e,contentRef:t,range:r,maximumBytes:n})=>{if(n===0)return new Uint8Array;let o=await e(t,r);try{return await nt(o.data,n)}catch(s){throw s instanceof ce?new C({code:"CONTENT_LIMIT_EXCEEDED",message:"Asset storage returned more content than requested"}):s}},pu=e=>{try{return ae(e)}catch{throw new C({code:"CONTENT_DECODING_FAILED",message:"Selected asset content is not valid UTF-8"})}},du=(e,t)=>{if(t.mode==="range")return Math.max(0,Math.min(t.length,e.size-t.offset));let r=t.maxBytes??b.hydratedFileBytes;if(e.size>r)throw new C({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected asset exceeds the per-file content limit",details:{assetId:e._id,assetBytes:e.size,fileByteLimit:r}});return e.size},$i=async({result:e,documents:t,options:r,read:n,assetReferences:o,assetUrls:s})=>{if(r.mode==="none")return{content:{},hydratedFileCount:0,hydratedBytes:0};let i=au(e);if(i.length>b.hydratedFileCount)throw new C({code:"CONTENT_LIMIT_EXCEEDED",message:"Too many selected assets requested content hydration",details:{fileCount:i.length,fileCountLimit:b.hydratedFileCount}});let c=new Map(t.map(p=>[p._id,p])),a=i.map(p=>{let m=c.get(p._id);if(m===void 0||m.revision!==p.revision||m.contentRef!==p.contentRef||typeof m.size!="number"||typeof m.mimeType!="string")throw new C({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset content identity is stale or unavailable",details:{assetId:p._id}});let d={...m,size:m.size,mimeType:m.mimeType};if(uu(d)===!1)throw new C({code:"CONTENT_NOT_TEXT",message:"Selected binary asset cannot be embedded as text",details:{assetId:p._id,mimeType:d.mimeType}});return{identity:p,document:d,readLength:du(d,r)}}),u=a.reduce((p,m)=>p+m.readLength,0);if(u>b.hydratedTotalBytes)throw new C({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected assets exceed the total hydrated-content limit",details:{totalReadBytes:u,totalByteLimit:b.hydratedTotalBytes}});let f=await vi(a,b.concurrentContentReads,async p=>{let m=r.mode==="range"?{offset:r.offset,length:p.readLength}:p.readLength===0?void 0:{offset:0,length:p.readLength},d=await lu({read:n,contentRef:p.identity.contentRef,range:m,maximumBytes:p.readLength});if(d.byteLength!==p.readLength)throw new C({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset bytes do not match canonical metadata",details:{assetId:p.identity._id}});let y;if(r.mode==="markdown-body")try{y=(await wi(d,p.readLength||1)).body;let w=o?.[p.identity.contentRef];w!==void 0&&s!==void 0&&(y=zi({markdown:y,references:w,assetUrls:s}))}catch{throw new C({code:"CONTENT_DECODING_FAILED",message:"Selected Markdown body could not be decoded",details:{assetId:p.identity._id}})}else y=pu(d);let P=ee(y);return{id:p.identity._id,returnedBytes:P,content:{...p.identity,encoding:"utf-8",text:y,...r.mode==="range"?{range:{offset:r.offset,length:d.byteLength,total:p.document.size}}:{}}}});return{content:Object.fromEntries(f.map(({id:p,content:m})=>[p,m])),hydratedFileCount:a.length,hydratedBytes:f.reduce((p,{returnedBytes:m})=>p+m,0)}};var dd=g().datetime({offset:!0}).transform(e=>new Date(e).toISOString());var fu=/^[A-Za-z_][A-Za-z0-9_]*$/,ki=(e,t)=>fu.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`;var Ai=({document:e,includes:t})=>{let r={};for(let n of ui){let o=e[n];o!==void 0&&t(n)&&(r[n]=o)}return r},Zi=({source:e,target:t,path:r})=>{let[n,...o]=r;if(n===void 0||Object.hasOwn(e,n)===!1)return;let s=e[n];if(o.length===0){Object.defineProperty(t,n,{value:s,enumerable:!0,configurable:!0,writable:!0});return}if(typeof s!="object"||s===null||Array.isArray(s))return;let i={};if(Zi({source:s,target:i,path:o}),Object.keys(i).length===0)return;let c=t[n];Object.defineProperty(t,n,{value:{...typeof c=="object"&&c!==null&&Array.isArray(c)===!1?c:{},...i},enumerable:!0,configurable:!0,writable:!0})},Si=({properties:e,fields:t})=>{let r={};for(let n of t)n[0]==="properties"&&Zi({source:e,target:r,path:n.slice(1)});return r};var W=class extends Error{constructor(t,r){super(t,r),this.name="AssetQueryExecutionError"}},_e=class extends Error{constructor(){super("The requested asset index revision is stale"),this.name="AssetIndexRevisionError"}},Ei=e=>{if(e[0]!=="properties")return e[0];let t="properties";for(let r of e.slice(1))t=ki(t,r);return t},Ri=({filter:e,fieldTypes:t})=>di(t).includes(e.operator),Pi=(e,t)=>Object.hasOwn(e.fields,t)?e.fields[t]:void 0,mu=({query:e,catalog:t})=>{let r=Gt.parse(e),n=new Map,o=[];for(let s of ti(r.where)){let i=Ei(s.field);if(n.set(i,s.field),s.field[0]==="properties"){let c=Pi(t,i);c===void 0?o.push(`Asset field ${i} is not currently observed`):Ri({filter:s,fieldTypes:c.types})===!1&&o.push(`Operator ${s.operator} is not compatible with the currently observed types of ${i}`)}else if(Ri({filter:s,fieldTypes:Vt[s.field[0]]})===!1)throw new W(`Operator ${s.operator} is incompatible with ${i}`)}for(let s of r.sort){let i=Ei(s.field);if(n.set(i,s.field),s.field[0]==="properties"){let c=Pi(t,i);c===void 0?o.push(`Asset field ${i} is not currently observed`):c.types.some(a=>a==="object"||a==="array")&&o.push(`Asset field ${i} currently includes structured values that use deterministic JSON sort order`)}}return{query:r,referencedFieldPaths:[...n.values()],warnings:[...new Set(o)]}},Xt=(e,t,r)=>{let n=t[0]==="id"?e._id:Wt(t[0])?r?.[t[0]]:e[t[0]];for(let o of t.slice(1)){if(typeof n!="object"||n===null||Object.hasOwn(n,o)===!1)return;n=n[o]}return n},ot=(e,t)=>e===void 0||t===void 0?e===t:te(e)===te(t),hu=e=>typeof e=="string"||Array.isArray(e)?e.length===0:typeof e=="object"&&e!==null&&Object.keys(e).length===0,yu=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e-t;if(typeof e=="string"&&typeof t=="string")return Ie(e,t)},gu=(e,t,r)=>{let n=Xt(e,t.field,r);if(t.operator==="exists")return n!=null===t.value;if(t.operator==="isEmpty")return hu(n)===t.value;if(t.operator==="eq")return ot(n,t.value);if(t.operator==="ne")return ot(n,t.value)===!1;if(t.operator==="in")return t.value.some(s=>ot(n,s));if(t.operator==="contains")return typeof n=="string"&&typeof t.value=="string"?n.includes(t.value):Array.isArray(n)&&n.some(s=>ot(s,t.value));if(t.operator==="startsWith")return typeof n=="string"&&typeof t.value=="string"&&n.startsWith(t.value);if(t.operator==="endsWith")return typeof n=="string"&&typeof t.value=="string"&&n.endsWith(t.value);let o=yu(n,t.value);return o===void 0?!1:t.operator==="gt"?o>0:t.operator==="gte"?o>=0:t.operator==="lt"?o<0:o<=0},_u=(e,t,r)=>rt(t,n=>gu(e,n,r))===!0,xu=(e,t)=>{let r=e==null,n=t==null;return r||n?r===n?0:r?1:-1:typeof e=="number"&&typeof t=="number"?e-t:(typeof e=="string"||typeof e=="boolean")&&(typeof t=="string"||typeof t=="boolean")?Ie(String(e),String(t)):Ie(te(e),te(t))},bu=({left:e,right:t,sort:r,runtimeAssets:n})=>{for(let o of r){let s=xu(Xt(e,o.field,n?.[e._id]),Xt(t,o.field,n?.[t._id]));if(s!==0)return o.direction==="asc"?s:-s}return Ie(e._id,t._id)};var wu=(e,t)=>{if(e.properties===void 0)return;if(t.mode==="all")return Object.keys(e.properties).length===0?void 0:e.properties;if(t.mode!=="fields"||t.fields.some(n=>n[0]==="properties")===!1)return;let r=Si({properties:e.properties,fields:t.fields});return Object.keys(r).length===0?void 0:r},ge=(e,t)=>e.includeMetadata&&li(t)||e.mode==="fields"&&e.fields.some(r=>r.length===1&&r[0]===t),vu=e=>e.mode==="all"||e.mode==="fields"&&e.fields.some(t=>t.length===1&&t[0]==="excerpt"),zu=(e,t,r)=>{if(ge(t,"url")&&r===void 0)throw new Error(`Asset URL is unavailable for ${e._id}`);let n=wu(e,t),o=r?.width!==void 0&&r.height!==void 0;return{...r!==void 0&&ge(t,"url")?{url:r.url}:{},...o&&ge(t,"width")?{width:r.width}:{},...o&&ge(t,"height")?{height:r.height}:{},...Ai({document:e,includes:s=>ge(t,s)}),...n===void 0?{}:{properties:n},...e.excerpt===void 0||vu(t)===!1?{}:{excerpt:e.excerpt},...e.metadataError===void 0||t.includeMetadata===!1?{}:{metadataError:e.metadataError}}},$u=e=>{if(ee(te(e))>b.resultBytes)throw new W("Asset query result exceeds the byte limit")},Oi=async({query:e,catalog:t,documents:r,read:n,runtimeAssets:o,assetReferences:s})=>{let{query:i}=mu({query:e,catalog:t});if(r.length>b.candidateDocuments)throw new W("Asset query document limit was exceeded");let c=r.flatMap(d=>{let y=o?.[d._id];if(_u(d,i.where,y)===!1)return[];let P=zu(d,i.output,y);return i.content.mode==="none"&&Object.keys(P).length===0&&ge(i.output,"id")===!1?[]:[{document:d,item:{id:d._id,...P}}]}),u=[...c].sort((d,y)=>bu({left:d.document,right:y.document,sort:i.sort,runtimeAssets:o})).slice(i.offset,i.offset+i.limit),f=u.map(({document:d})=>d),p=u.map(({item:d})=>d);if(i.content.mode!=="none"){let d=i.content;if(n===void 0)throw new W("Asset content reader is unavailable");let y=await $i({result:f,documents:f,options:d,read:n,assetReferences:s,assetUrls:s===void 0?void 0:Object.fromEntries(Object.entries(o??{}).map(([P,w])=>[P,w.url]))});p=f.map((P,w)=>{let F=y.content[P._id];if(F===void 0)throw new W("Selected asset content could not be read");return{...p[w],content:{encoding:F.encoding,text:F.text,...F.range===void 0?{}:{range:F.range}}}})}let m={items:p,totalCount:c.length,hasMore:i.offset+u.length<c.length};return $u(m),m};var Yt=({artifact:e,readContent:t})=>{let r=e.documents.length,o=(e.database?.sourceDocumentCount??r)-r,s=ee(_i(e)),i={format:e.format,version:e.version,revision:e.integrity.checksum,usedBytes:s,maxBytes:e.database?.maxBytes??Number.MAX_SAFE_INTEGER,unboundedBytes:e.database?.unboundedBytes??s,includedDocumentCount:r,omittedDocumentCount:o,truncated:o>0};return{query:async(c,a,u)=>{if(c.indexRevision!==void 0&&c.indexRevision!==e.integrity.checksum)throw new _e;let f=async(m,d)=>{let y=e.contents?.[m];if(y===void 0){let F=a??t;if(F===void 0)throw new Error("Content is not embedded in this database");return await F(m,d)}let P=ye(y),w=d===void 0?P:P.slice(d.offset,d.offset+d.length);return{data:async function*(){yield w}(),contentLength:w.byteLength}};return await Oi({query:c.query,catalog:e.fieldCatalog,documents:e.documents,read:f,runtimeAssets:u,assetReferences:e.assetReferences})},getFieldCatalog:()=>e.fieldCatalog,getStats:()=>i}};var st=class extends Error{constructor(t,r){super(t,r),this.name="AssetQueryRequestError"}},Ce=class extends Error{},ku=async(e,t)=>{if(Number.isSafeInteger(t)===!1||t<0)throw new TypeError("Request byte limit must be a non-negative integer");let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new Ce("Request exceeds the byte limit");let n=e.body?.getReader(),o=[],s=0;if(n!==void 0)for(;;){let{done:a,value:u}=await n.read();if(a)break;if(s+=u.byteLength,s>t){try{await n.cancel()}catch{}throw new Ce("Request exceeds the byte limit")}o.push(u)}let i=new Uint8Array(s),c=0;for(let a of o)i.set(a,c),c+=a.byteLength;return i},Ii=async e=>{let t;try{t=await ku(e,b.requestBytes)}catch(r){throw r instanceof Ce?new st("Asset query request exceeds the byte limit",{cause:r}):r}try{return fi.parse(JSON.parse(ae(t)))}catch(r){throw new st("Asset query request is invalid",{cause:r})}};var Ti=e=>{if(e instanceof _e)return{code:"STALE_INDEX",message:e.message,retryable:!1,status:409};if(e instanceof W)return{code:"INVALID_REQUEST",message:e.message,retryable:!1,status:400};if(e instanceof C)return{code:e.code,message:e.message,retryable:!1,details:e.details,status:400}};var Au="/$resources/assets",Ci=(e,t=200)=>new Response(JSON.stringify(e),{status:t,headers:{"content-type":"application/json; charset=utf-8"}}),Ne=({code:e,message:t,status:r,retryable:n=!1,details:o})=>Ci(mi({code:e,message:t,retryable:n,details:o}),r),Zu=(e,t,r)=>typeof e=="string"||e instanceof URL?new Request(new URL(e,t),r):new Request(e,r),Su=async({deploymentId:e,artifact:t,request:r})=>{let n=await r.clone().text(),o=r.headers.get("cache-control"),s=await gi(JSON.stringify([e,t.integrity.checksum,n,o])),i=new URL(r.url);return i.searchParams.set("ws-asset-resource",s),new Request(i,{method:"GET"})},Ud=({deploymentId:e,artifact:t,runtimeAssets:r,cache:n,baseUrl:o})=>(Ni({artifact:t,runtimeAssets:r}),Di({deploymentId:e,artifact:t,runtimeAssets:r,cache:n,baseUrl:o,database:Yt({artifact:t})})),Ni=({artifact:e,runtimeAssets:t})=>{let r=xi(e).find(n=>t[n]===void 0);if(r!==void 0)throw new Error(`Published referenced asset URL is unavailable for ${r}`)},Di=({deploymentId:e,artifact:t,runtimeAssets:r,cache:n,baseUrl:o,database:s})=>{let i=new URL(o).origin;return async(c,a)=>{let u=Zu(c,o,a),f=new URL(u.url);if(f.origin!==i||f.pathname!==Au||u.method.toUpperCase()!=="POST")return;let p;try{p=await Ii(u.clone())}catch{return Ne({code:"INVALID_REQUEST",message:"Asset resource request is invalid",status:400})}let m=n===void 0||u.headers.has("cache-control")===!1?void 0:await Su({deploymentId:e,artifact:t,request:u});if(m!==void 0&&n!==void 0){let d=await n.match(m).catch(()=>{});if(d!==void 0)return new Response(d.body,d)}try{if(u.signal.aborted)return Ne({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let d=Ci(await s.query(p,void 0,r));return m!==void 0&&n!==void 0&&u.signal.aborted===!1&&(d.headers.set("cache-control",u.headers.get("cache-control")),await n.put(m,d.clone()).catch(()=>{})),d}catch(d){if(u.signal.aborted)return Ne({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let y=Ti(d);return Ne(y!==void 0?y:{code:"INTERNAL_ERROR",message:"Published asset query failed",status:500,retryable:!0})}}},Bd=({deploymentId:e,artifact:t,runtimeAssets:r})=>{let n=globalThis.caches,o,s=()=>(o??=n.open(`webstudio-assets-${e}`),o),i=n===void 0?void 0:{match:async a=>(await s()).match(a),put:async(a,u)=>(await s()).put(a,u)};Ni({artifact:t,runtimeAssets:r});let c=Yt({artifact:t});return async({request:a,fallback:u})=>{let f=new URL(a.url).origin,p=Di({deploymentId:e,artifact:t,runtimeAssets:r,cache:i,baseUrl:f,database:c});return async(m,d)=>await p(m,d)??u(m,d)}};export{Bd as createGeneratedAssetResourceRuntime,Ud as createPublishedAssetResourceFetch};
diff --git a/fixtures/webstudio-features/app/__generated__/$resources.assets.ts b/fixtures/webstudio-features/app/__generated__/$resources.assets.ts
index 4905f46368..82986429f6 100644
--- a/fixtures/webstudio-features/app/__generated__/$resources.assets.ts
+++ b/fixtures/webstudio-features/app/__generated__/$resources.assets.ts
@@ -1,26 +1,34 @@
-export const assets = {
+
+ export const assets = {
"2b151fc7b4b0324e6ab78c40f72c7f59273f81fb1be3d08b3f9976428601b95e": {
- url: "/assets/e-mail-39993_vrxyjxQv3j67Krs62Vz7Y.mp3",
+ "url": "/assets/e-mail-39993_vrxyjxQv3j67Krs62Vz7Y.mp3"
+ },
+ "42e55b0464790758b9352d675cf28fadfcf8a3259fc1e890100617d3e731be88": {
+ "url": "/assets/cabinsketch-bold_TLCbytfxf8ENHwZ6ze3Jj.ttf",
+ "family": "CabinSketch",
+ "style": "normal",
+ "weight": 700
},
"4afe692f78ec0530e355a551a3860302c4478037db7b25a3bdae82c32c78634d": {
- url: "/assets/webm-example_2r_6VmRBjhAy3ldaqz0gk.webm",
+ "url": "/assets/webm-example_2r_6VmRBjhAy3ldaqz0gk.webm"
},
"7cf5892080fa66b5e6175ffd2d27c304ee6b09ce1f21847a95000225ad1afa59": {
- url: "/assets/cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png",
- width: 790,
- height: 786,
+ "url": "/assets/cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png",
+ "width": 790,
+ "height": 786
},
"9a8bc926-7804-4d3f-af81-69196b1d2ed8": {
- url: "/assets/small-avif-kitty_FnabJsioMWpBtXZSGf4DR.webp",
- width: 100,
- height: 100,
+ "url": "/assets/small-avif-kitty_FnabJsioMWpBtXZSGf4DR.webp",
+ "width": 100,
+ "height": 100
},
- cbf6b1b052e52b256cef54a032a546bf43bf3f5441be4d1c5eeaabce26903d78: {
- url: "/assets/video_QamtUWsD-ShifhzZLoNIv_ald_1xtyEb3uHhFb7nCQa.mp4",
+ "cbf6b1b052e52b256cef54a032a546bf43bf3f5441be4d1c5eeaabce26903d78": {
+ "url": "/assets/video_QamtUWsD-ShifhzZLoNIv_ald_1xtyEb3uHhFb7nCQa.mp4"
},
"cd939c56-bcdd-4e64-bd9c-567a9bccd3da": {
- url: "/assets/_937084ed-a798-49fe-8664-df93a2af605e_uiBk3o6UWdqolyakMvQJ9.jpeg",
- width: 1024,
- height: 1024,
- },
+ "url": "/assets/_937084ed-a798-49fe-8664-df93a2af605e_uiBk3o6UWdqolyakMvQJ9.jpeg",
+ "width": 1024,
+ "height": 1024
+ }
};
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/$resources.redirects.ts b/fixtures/webstudio-features/app/__generated__/$resources.redirects.ts
index a3ee44bd02..5872ee0507 100644
--- a/fixtures/webstudio-features/app/__generated__/$resources.redirects.ts
+++ b/fixtures/webstudio-features/app/__generated__/$resources.redirects.ts
@@ -1 +1,3 @@
-export const redirects = [];
+
+ export const redirects = [];
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/$resources.sitemap.xml.ts b/fixtures/webstudio-features/app/__generated__/$resources.sitemap.xml.ts
index 72fdad78cc..34362a7e93 100644
--- a/fixtures/webstudio-features/app/__generated__/$resources.sitemap.xml.ts
+++ b/fixtures/webstudio-features/app/__generated__/$resources.sitemap.xml.ts
@@ -1,26 +1,28 @@
-export const sitemap = [
+
+ export const sitemap = [
{
- path: "/",
- lastModified: "2026-01-15",
+ "path": "/",
+ "lastModified": "2026-01-15"
},
{
- path: "/_route_with_symbols_",
- lastModified: "2026-01-15",
+ "path": "/_route_with_symbols_",
+ "lastModified": "2026-01-15"
},
{
- path: "/form",
- lastModified: "2026-01-15",
+ "path": "/form",
+ "lastModified": "2026-01-15"
},
{
- path: "/heading-with-id",
- lastModified: "2026-01-15",
+ "path": "/heading-with-id",
+ "lastModified": "2026-01-15"
},
{
- path: "/resources",
- lastModified: "2026-01-15",
+ "path": "/resources",
+ "lastModified": "2026-01-15"
},
{
- path: "/nested/nested-page",
- lastModified: "2026-01-15",
- },
+ "path": "/nested/nested-page",
+ "lastModified": "2026-01-15"
+ }
];
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.server.tsx
index ad45acbd8c..908255b01e 100644
--- a/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: undefined,
redirect: undefined,
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.tsx b/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.tsx
index 76c965230b..2e8b9e82d2 100644
--- a/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.tsx
@@ -1,46 +1,46 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import { Body as Body } from "@webstudio-is/sdk-components-react-router";
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body } from "@webstudio-is/sdk-components-react-router";
import { Image as Image } from "@webstudio-is/sdk-components-react/components";
-export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
-export const projectDomain = "webstudio-fixture-project-a-0su3o";
+ export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
+
+
+
+ export const projectDomain = "webstudio-fixture-project-a-0su3o";
+
+ export const lastPublished = "2026-01-15T16:19:55.574Z";
+
+ export const siteName = "KittyGuardedZone";
-export const lastPublished = "2026-01-15T16:19:55.574Z";
+ export const breakpoints = [{"id":"UoTkWyaFuTYJihS3MFYK5"},{"id":"ZMaWCtWpH-ao0e_kgIHqR","minWidth":372},{"id":"Z8WjyXWkCrr35PXgjHdpY","minWidth":472}];
-export const siteName = "KittyGuardedZone";
+ export const favIconAsset: string | undefined =
+ "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
-export const breakpoints = [
- { id: "UoTkWyaFuTYJihS3MFYK5" },
- { id: "ZMaWCtWpH-ao0e_kgIHqR", minWidth: 372 },
- { id: "Z8WjyXWkCrr35PXgjHdpY", minWidth: 472 },
-];
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
-export const favIconAsset: string | undefined =
- "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
+ export const pageBackgroundImageAssets: string[] =
+ []
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
+
-export const pageBackgroundImageAssets: string[] = [];
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body`}>
+<Image
+src={"/assets/small-avif-kitty_FnabJsioMWpBtXZSGf4DR.webp"}
+className={`w-image c1czoo99`} />
+</Body>
+}
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body`}>
- <Image
- src={"/assets/small-avif-kitty_FnabJsioMWpBtXZSGf4DR.webp"}
- className={`w-image c1czoo99`}
- />
- </Body>
- );
-};
-export { Page };
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsx
index 05e54798db..8fd5e5c714 100644
--- a/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: 200,
redirect: "",
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[animations]._index.tsx b/fixtures/webstudio-features/app/__generated__/[animations]._index.tsx
index e8bf1bf492..f18c07c9e1 100644
--- a/fixtures/webstudio-features/app/__generated__/[animations]._index.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[animations]._index.tsx
@@ -1,310 +1,106 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import { Body as Body } from "@webstudio-is/sdk-components-react-router";
-import {
- Box as Box,
- Heading as Heading,
-} from "@webstudio-is/sdk-components-react/components";
-import {
- AnimateChildren as AnimateChildren,
- AnimateText as AnimateText,
-} from "@webstudio-is/sdk-components-animation";
-export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body } from "@webstudio-is/sdk-components-react-router";
+import { Box as Box, Heading as Heading } from "@webstudio-is/sdk-components-react/components";
+import { AnimateChildren as AnimateChildren, AnimateText as AnimateText } from "@webstudio-is/sdk-components-animation";
-export const projectDomain = "webstudio-fixture-project-a-0su3o";
-export const lastPublished = "2026-01-15T16:19:55.574Z";
+ export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
-export const siteName = "KittyGuardedZone";
+
-export const breakpoints = [
- { id: "UoTkWyaFuTYJihS3MFYK5" },
- { id: "ZMaWCtWpH-ao0e_kgIHqR", minWidth: 372 },
- { id: "Z8WjyXWkCrr35PXgjHdpY", minWidth: 472 },
-];
+ export const projectDomain = "webstudio-fixture-project-a-0su3o";
-export const favIconAsset: string | undefined =
- "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
+ export const lastPublished = "2026-01-15T16:19:55.574Z";
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
+ export const siteName = "KittyGuardedZone";
-export const pageBackgroundImageAssets: string[] = [];
+ export const breakpoints = [{"id":"UoTkWyaFuTYJihS3MFYK5"},{"id":"ZMaWCtWpH-ao0e_kgIHqR","minWidth":372},{"id":"Z8WjyXWkCrr35PXgjHdpY","minWidth":472}];
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body c1jgcte3 cncutr5 c1ywt30e cqvurle`}>
- <Box className={`w-box c1m04i8w c13v7j50 cpjvam0 cqkqnmd`}>
- <Heading className={`w-heading`}>{"ANIMATIONS"}</Heading>
- </Box>
- <Box className={`w-box c1y8ynw5 c2gdfrb c1yk3skc c16asro7 c1pt69cw`}>
- <Box className={`w-box`}>
- <AnimateChildren
- action={{
- type: "view",
- animations: [
- {
- name: "Fade In",
- description: "Fade in the element as it scrolls into view.",
- keyframes: [
- {
- offset: 0,
- styles: {
- opacity: { type: "unit", unit: "number", value: 0 },
- },
- },
- ],
- timing: {
- easing: "linear",
- fill: "backwards",
- rangeStart: [
- "entry",
- { type: "unit", value: 0, unit: "%" },
- ],
- rangeEnd: [
- "entry",
- { type: "unit", value: 100, unit: "%" },
- ],
- },
- },
- {
- name: "Fade Out",
- description:
- "Fade out the element as it scrolls out of view.",
- keyframes: [
- {
- offset: 1,
- styles: {
- opacity: { type: "unit", unit: "number", value: 0 },
- },
- },
- ],
- timing: {
- easing: "linear",
- fill: "forwards",
- rangeStart: ["exit", { type: "unit", value: 0, unit: "%" }],
- rangeEnd: ["exit", { type: "unit", value: 100, unit: "%" }],
- },
- },
- {
- name: "Parallax In",
- description:
- "Parallax the element as it scrolls out of view.",
- keyframes: [
- {
- offset: 0,
- styles: {
- translate: {
- type: "tuple",
- value: [
- { type: "unit", unit: "number", value: 0 },
- { type: "unit", unit: "px", value: 100 },
- ],
- },
- },
- },
- ],
- timing: {
- easing: "linear",
- fill: "backwards",
- rangeStart: [
- "cover",
- { type: "unit", value: 0, unit: "%" },
- ],
- rangeEnd: ["cover", { type: "unit", value: 50, unit: "%" }],
- },
- },
- {
- name: "Parallax Out",
- description:
- "Parallax the element as it scrolls out of view.",
- keyframes: [
- {
- offset: 1,
- styles: {
- translate: {
- type: "tuple",
- value: [
- { type: "unit", unit: "number", value: 0 },
- { type: "unit", unit: "px", value: -100 },
- ],
- },
- },
- },
- ],
- timing: {
- easing: "linear",
- fill: "forwards",
- rangeStart: [
- "cover",
- { type: "unit", value: 50, unit: "%" },
- ],
- rangeEnd: [
- "cover",
- { type: "unit", value: 100, unit: "%" },
- ],
- },
- },
- ],
- isPinned: false,
- }}
- >
- <Heading className={`w-heading c1pdroxx cudat22`}>
- {"ANIMATED CHILD 0"}
- </Heading>
- <Heading className={`w-heading`}>{"ANIMATED CHILD 1"}</Heading>
- </AnimateChildren>
- </Box>
- <Box className={`w-box`}>
- {
- "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed tellus at nisi feugiat accumsan. Aliquam tristique vitae augue eget lacinia. "
- }
- </Box>
- </Box>
- <Box className={`w-box cq3mp4w`} />
- <Box className={`w-box c1y8ynw5 c2gdfrb c1yk3skc`}>
- <Box className={`w-box`}>
- <AnimateChildren
- action={{
- type: "view",
- animations: [
- {
- name: "Fade In",
- description: "Fade in the element as it scrolls into view.",
- keyframes: [
- {
- offset: 0,
- styles: {
- opacity: { type: "unit", unit: "number", value: 0 },
- },
- },
- ],
- timing: {
- easing: "linear",
- fill: "backwards",
- rangeStart: [
- "entry",
- { type: "unit", value: 0, unit: "%" },
- ],
- rangeEnd: [
- "entry",
- { type: "unit", value: 100, unit: "%" },
- ],
- },
- },
- {
- name: "Fade Out",
- description:
- "Fade out the element as it scrolls out of view.",
- keyframes: [
- {
- offset: 1,
- styles: {
- opacity: { type: "unit", unit: "number", value: 0 },
- },
- },
- ],
- timing: {
- easing: "linear",
- fill: "forwards",
- rangeStart: ["exit", { type: "unit", value: 0, unit: "%" }],
- rangeEnd: ["exit", { type: "unit", value: 100, unit: "%" }],
- },
- },
- {
- name: "Parallax In",
- description:
- "Parallax the element as it scrolls out of view.",
- keyframes: [
- {
- offset: 0,
- styles: {
- translate: {
- type: "tuple",
- value: [
- { type: "unit", unit: "number", value: 0 },
- { type: "unit", unit: "px", value: 100 },
- ],
- },
- },
- },
- ],
- timing: {
- easing: "linear",
- fill: "backwards",
- rangeStart: [
- "cover",
- { type: "unit", value: 0, unit: "%" },
- ],
- rangeEnd: ["cover", { type: "unit", value: 50, unit: "%" }],
- },
- },
- {
- name: "Parallax Out",
- description:
- "Parallax the element as it scrolls out of view.",
- keyframes: [
- {
- offset: 1,
- styles: {
- translate: {
- type: "tuple",
- value: [
- { type: "unit", unit: "number", value: 0 },
- { type: "unit", unit: "px", value: -100 },
- ],
- },
- },
- },
- ],
- timing: {
- easing: "linear",
- fill: "forwards",
- rangeStart: [
- "cover",
- { type: "unit", value: 50, unit: "%" },
- ],
- rangeEnd: [
- "cover",
- { type: "unit", value: 100, unit: "%" },
- ],
- },
- },
- ],
- isPinned: false,
- }}
- >
- <AnimateText slidingWindow={20} className={`w-text-animation`}>
- <Heading className={`w-heading c1pdroxx`}>
- {"ANIMATED CHILD 1"}
- </Heading>
- <Box className={`w-box`}>
- {
- "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed tellus at nisi feugiat accumsan. Aliquam tristique vitae augue eget lacinia. "
- }
- </Box>
- </AnimateText>
- </AnimateChildren>
- </Box>
- <Box className={`w-box`}>
- {
- "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed tellus at nisi feugiat accumsan. Aliquam tristique vitae augue eget lacinia. "
- }
- </Box>
- </Box>
- <Box className={`w-box c1m04i8w c13v7j50 cpjvam0 cqkqnmd`}>
- <Heading className={`w-heading`}>{"THE END"}</Heading>
- </Box>
- </Body>
- );
-};
+ export const favIconAsset: string | undefined =
+ "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
-export { Page };
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
+
+ export const pageBackgroundImageAssets: string[] =
+ []
+
+
+
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body c1jgcte3 cncutr5 c1ywt30e cqvurle`}>
+<Box
+className={`w-box c1m04i8w c13v7j50 cpjvam0 cqkqnmd`}>
+<Heading
+className={`w-heading`}>
+{"ANIMATIONS"}
+</Heading>
+</Box>
+<Box
+className={`w-box c1y8ynw5 c2gdfrb c1yk3skc c16asro7 c1pt69cw`}>
+<Box
+className={`w-box`}>
+<AnimateChildren
+action={{"type":"view","animations":[{"name":"Fade In","description":"Fade in the element as it scrolls into view.","keyframes":[{"offset":0,"styles":{"opacity":{"type":"unit","unit":"number","value":0}}}],"timing":{"easing":"linear","fill":"backwards","rangeStart":["entry",{"type":"unit","value":0,"unit":"%"}],"rangeEnd":["entry",{"type":"unit","value":100,"unit":"%"}]}},{"name":"Fade Out","description":"Fade out the element as it scrolls out of view.","keyframes":[{"offset":1,"styles":{"opacity":{"type":"unit","unit":"number","value":0}}}],"timing":{"easing":"linear","fill":"forwards","rangeStart":["exit",{"type":"unit","value":0,"unit":"%"}],"rangeEnd":["exit",{"type":"unit","value":100,"unit":"%"}]}},{"name":"Parallax In","description":"Parallax the element as it scrolls out of view.","keyframes":[{"offset":0,"styles":{"translate":{"type":"tuple","value":[{"type":"unit","unit":"number","value":0},{"type":"unit","unit":"px","value":100}]}}}],"timing":{"easing":"linear","fill":"backwards","rangeStart":["cover",{"type":"unit","value":0,"unit":"%"}],"rangeEnd":["cover",{"type":"unit","value":50,"unit":"%"}]}},{"name":"Parallax Out","description":"Parallax the element as it scrolls out of view.","keyframes":[{"offset":1,"styles":{"translate":{"type":"tuple","value":[{"type":"unit","unit":"number","value":0},{"type":"unit","unit":"px","value":-100}]}}}],"timing":{"easing":"linear","fill":"forwards","rangeStart":["cover",{"type":"unit","value":50,"unit":"%"}],"rangeEnd":["cover",{"type":"unit","value":100,"unit":"%"}]}}],"isPinned":false}}>
+<Heading
+className={`w-heading c1pdroxx cudat22`}>
+{"ANIMATED CHILD 0"}
+</Heading>
+<Heading
+className={`w-heading`}>
+{"ANIMATED CHILD 1"}
+</Heading>
+</AnimateChildren>
+</Box>
+<Box
+className={`w-box`}>
+{"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed tellus at nisi feugiat accumsan. Aliquam tristique vitae augue eget lacinia. "}
+</Box>
+</Box>
+<Box
+className={`w-box cq3mp4w`} />
+<Box
+className={`w-box c1y8ynw5 c2gdfrb c1yk3skc`}>
+<Box
+className={`w-box`}>
+<AnimateChildren
+action={{"type":"view","animations":[{"name":"Fade In","description":"Fade in the element as it scrolls into view.","keyframes":[{"offset":0,"styles":{"opacity":{"type":"unit","unit":"number","value":0}}}],"timing":{"easing":"linear","fill":"backwards","rangeStart":["entry",{"type":"unit","value":0,"unit":"%"}],"rangeEnd":["entry",{"type":"unit","value":100,"unit":"%"}]}},{"name":"Fade Out","description":"Fade out the element as it scrolls out of view.","keyframes":[{"offset":1,"styles":{"opacity":{"type":"unit","unit":"number","value":0}}}],"timing":{"easing":"linear","fill":"forwards","rangeStart":["exit",{"type":"unit","value":0,"unit":"%"}],"rangeEnd":["exit",{"type":"unit","value":100,"unit":"%"}]}},{"name":"Parallax In","description":"Parallax the element as it scrolls out of view.","keyframes":[{"offset":0,"styles":{"translate":{"type":"tuple","value":[{"type":"unit","unit":"number","value":0},{"type":"unit","unit":"px","value":100}]}}}],"timing":{"easing":"linear","fill":"backwards","rangeStart":["cover",{"type":"unit","value":0,"unit":"%"}],"rangeEnd":["cover",{"type":"unit","value":50,"unit":"%"}]}},{"name":"Parallax Out","description":"Parallax the element as it scrolls out of view.","keyframes":[{"offset":1,"styles":{"translate":{"type":"tuple","value":[{"type":"unit","unit":"number","value":0},{"type":"unit","unit":"px","value":-100}]}}}],"timing":{"easing":"linear","fill":"forwards","rangeStart":["cover",{"type":"unit","value":50,"unit":"%"}],"rangeEnd":["cover",{"type":"unit","value":100,"unit":"%"}]}}],"isPinned":false}}>
+<AnimateText
+slidingWindow={20}
+className={`w-text-animation`}>
+<Heading
+className={`w-heading c1pdroxx`}>
+{"ANIMATED CHILD 1"}
+</Heading>
+<Box
+className={`w-box`}>
+{"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed tellus at nisi feugiat accumsan. Aliquam tristique vitae augue eget lacinia. "}
+</Box>
+</AnimateText>
+</AnimateChildren>
+</Box>
+<Box
+className={`w-box`}>
+{"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed tellus at nisi feugiat accumsan. Aliquam tristique vitae augue eget lacinia. "}
+</Box>
+</Box>
+<Box
+className={`w-box c1m04i8w c13v7j50 cpjvam0 cqkqnmd`}>
+<Heading
+className={`w-heading`}>
+{"THE END"}
+</Heading>
+</Box>
+</Body>
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx
index e3b773ec19..36b49b0dbb 100644
--- a/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx
@@ -1,23 +1,49 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
const assets_1: ResourceRequest = {
name: "assets",
control: "system",
url: "/$resources/assets",
- searchParams: [],
- method: "get",
- headers: [],
- };
- const _data = new Map<string, ResourceRequest>([["assets_1", assets_1]]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ searchParams: [
+ ],
+ method: "post",
+ headers: [
+ { name: "Content-Type", value: "application/json" },
+ ],
+ body: {
+ query: ({
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["url"], ["width"], ["height"]],
+ },
+ content: {
+ mode: "none",
+ },
+ where: {
+ all: [],
+ },
+ sort: [],
+ limit: 1000,
+ offset: 0,
+ }),
+},
+ }
+ const _data = new Map<string, ResourceRequest>([
+ ["assets_1", assets_1],
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -34,13 +60,17 @@ export const getPageMeta = ({
status: undefined,
redirect: "",
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[assets1]._index.tsx b/fixtures/webstudio-features/app/__generated__/[assets1]._index.tsx
index 5fa87bb0c1..65f940626c 100644
--- a/fixtures/webstudio-features/app/__generated__/[assets1]._index.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[assets1]._index.tsx
@@ -1,60 +1,51 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import { Body as Body } from "@webstudio-is/sdk-components-react-router";
-
-export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
-
-export const projectDomain = "webstudio-fixture-project-a-0su3o";
-
-export const lastPublished = "2026-01-15T16:19:55.574Z";
-
-export const siteName = "KittyGuardedZone";
-
-export const breakpoints = [
- { id: "UoTkWyaFuTYJihS3MFYK5" },
- { id: "ZMaWCtWpH-ao0e_kgIHqR", minWidth: 372 },
- { id: "Z8WjyXWkCrr35PXgjHdpY", minWidth: 472 },
-];
-
-export const favIconAsset: string | undefined =
- "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
-
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
-
-export const pageBackgroundImageAssets: string[] = [];
-
-const Page = (_props: { system: any }) => {
- let assets = useResource("assets_1");
- return (
- <Body className={`w-element`}>
- <audio
- controls={true}
- src={
- assets?.data?.[
- "2b151fc7b4b0324e6ab78c40f72c7f59273f81fb1be3d08b3f9976428601b95e"
- ]?.url
- }
- className={`w-element`}
- />
- <video
- controls={true}
- src={
- assets?.data?.[
- "4afe692f78ec0530e355a551a3860302c4478037db7b25a3bdae82c32c78634d"
- ]?.url
- }
- className={`w-element`}
- />
- </Body>
- );
-};
-
-export { Page };
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body } from "@webstudio-is/sdk-components-react-router";
+
+
+ export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
+
+
+
+ export const projectDomain = "webstudio-fixture-project-a-0su3o";
+
+ export const lastPublished = "2026-01-15T16:19:55.574Z";
+
+ export const siteName = "KittyGuardedZone";
+
+ export const breakpoints = [{"id":"UoTkWyaFuTYJihS3MFYK5"},{"id":"ZMaWCtWpH-ao0e_kgIHqR","minWidth":372},{"id":"Z8WjyXWkCrr35PXgjHdpY","minWidth":472}];
+
+ export const favIconAsset: string | undefined =
+ "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
+
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
+
+ export const pageBackgroundImageAssets: string[] =
+ []
+
+
+
+ const Page = (_props: { system: any; }) => {
+let assets = useResource("assets_1")
+return <Body
+className={`w-element`}>
+<audio
+controls={true}
+src={assets?.data?.['2b151fc7b4b0324e6ab78c40f72c7f59273f81fb1be3d08b3f9976428601b95e']?.url}
+className={`w-element`} />
+<video
+controls={true}
+src={assets?.data?.['4afe692f78ec0530e355a551a3860302c4478037db7b25a3bdae82c32c78634d']?.url}
+className={`w-element`} />
+</Body>
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsx
index 05e54798db..8fd5e5c714 100644
--- a/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: 200,
redirect: "",
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[class-names]._index.tsx b/fixtures/webstudio-features/app/__generated__/[class-names]._index.tsx
index 8f78d80e38..3bc2fc12fe 100644
--- a/fixtures/webstudio-features/app/__generated__/[class-names]._index.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[class-names]._index.tsx
@@ -1,48 +1,49 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import { Body as Body } from "@webstudio-is/sdk-components-react-router";
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body } from "@webstudio-is/sdk-components-react-router";
import { Box as Box } from "@webstudio-is/sdk-components-react/components";
-export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
-export const projectDomain = "webstudio-fixture-project-a-0su3o";
+ export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
+
+
+
+ export const projectDomain = "webstudio-fixture-project-a-0su3o";
+
+ export const lastPublished = "2026-01-15T16:19:55.574Z";
+
+ export const siteName = "KittyGuardedZone";
-export const lastPublished = "2026-01-15T16:19:55.574Z";
+ export const breakpoints = [{"id":"UoTkWyaFuTYJihS3MFYK5"},{"id":"ZMaWCtWpH-ao0e_kgIHqR","minWidth":372},{"id":"Z8WjyXWkCrr35PXgjHdpY","minWidth":472}];
-export const siteName = "KittyGuardedZone";
+ export const favIconAsset: string | undefined =
+ "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
-export const breakpoints = [
- { id: "UoTkWyaFuTYJihS3MFYK5" },
- { id: "ZMaWCtWpH-ao0e_kgIHqR", minWidth: 372 },
- { id: "Z8WjyXWkCrr35PXgjHdpY", minWidth: 472 },
-];
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
-export const favIconAsset: string | undefined =
- "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
+ export const pageBackgroundImageAssets: string[] =
+ []
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
+
-export const pageBackgroundImageAssets: string[] = [];
+ const Page = (_props: { system: any; }) => {
+let [classVar, set$classVar] = useVariableState<any>("varClass")
+return <Body
+className={`w-body`}>
+<Box
+id={"\"broken'with`symbols"}
+className={`w-box cm16yxw ${"custom-class \"broken 'with `symbols"}`} />
+<Box
+className={`w-box ctm310 ${`${classVar} class_3`}`} />
+</Body>
+}
-const Page = (_props: { system: any }) => {
- let [classVar, set$classVar] = useVariableState<any>("varClass");
- return (
- <Body className={`w-body`}>
- <Box
- id={"\"broken'with`symbols"}
- className={`w-box cm16yxw ${"custom-class \"broken 'with `symbols"}`}
- />
- <Box className={`w-box ctm310 ${`${classVar} class_3`}`} />
- </Body>
- );
-};
-export { Page };
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsx
index 05e54798db..8fd5e5c714 100644
--- a/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: 200,
redirect: "",
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[content-block]._index.tsx b/fixtures/webstudio-features/app/__generated__/[content-block]._index.tsx
index 517cf20c97..3835827f57 100644
--- a/fixtures/webstudio-features/app/__generated__/[content-block]._index.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[content-block]._index.tsx
@@ -1,66 +1,87 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import { Body as Body } from "@webstudio-is/sdk-components-react-router";
-import {
- Box as Box,
- Heading as Heading,
- Paragraph as Paragraph,
-} from "@webstudio-is/sdk-components-react/components";
-
-export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
-
-export const projectDomain = "webstudio-fixture-project-a-0su3o";
-
-export const lastPublished = "2026-01-15T16:19:55.574Z";
-
-export const siteName = "KittyGuardedZone";
-
-export const breakpoints = [
- { id: "UoTkWyaFuTYJihS3MFYK5" },
- { id: "ZMaWCtWpH-ao0e_kgIHqR", minWidth: 372 },
- { id: "Z8WjyXWkCrr35PXgjHdpY", minWidth: 472 },
-];
-
-export const favIconAsset: string | undefined =
- "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
-
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
-
-export const pageBackgroundImageAssets: string[] = [];
-
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body`}>
- <Box className={`w-box c620822`}>
- <Heading className={`w-heading cc5h0no`}>
- {"Content Block With Templates And Content"}
- </Heading>
- <Heading className={`w-heading`}>{"H1"}</Heading>
- <Paragraph className={`w-paragraph`}>{"Paragraph"}</Paragraph>
- </Box>
- <Box className={`w-box ch21dzk`}>
- <Heading className={`w-heading cc5h0no`}>
- {"Content Block With Templates Only"}
- </Heading>
- </Box>
- <Box className={`w-box c44hi06`}>
- <Heading className={`w-heading cc5h0no`}>{"With Content Only"}</Heading>
- <Heading className={`w-heading`}>{"H1"}</Heading>
- <Paragraph className={`w-paragraph`}>{"Paragraph"}</Paragraph>
- </Box>
- <Box className={`w-box cno1tjk`}>
- <Heading className={`w-heading cc5h0no`}>{"Empty"}</Heading>
- </Box>
- </Body>
- );
-};
-
-export { Page };
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body } from "@webstudio-is/sdk-components-react-router";
+import { Box as Box, Heading as Heading, Paragraph as Paragraph } from "@webstudio-is/sdk-components-react/components";
+
+
+ export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
+
+
+
+ export const projectDomain = "webstudio-fixture-project-a-0su3o";
+
+ export const lastPublished = "2026-01-15T16:19:55.574Z";
+
+ export const siteName = "KittyGuardedZone";
+
+ export const breakpoints = [{"id":"UoTkWyaFuTYJihS3MFYK5"},{"id":"ZMaWCtWpH-ao0e_kgIHqR","minWidth":372},{"id":"Z8WjyXWkCrr35PXgjHdpY","minWidth":472}];
+
+ export const favIconAsset: string | undefined =
+ "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
+
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
+
+ export const pageBackgroundImageAssets: string[] =
+ []
+
+
+
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body`}>
+<Box
+className={`w-box c620822`}>
+<Heading
+className={`w-heading cc5h0no`}>
+{"Content Block With Templates And Content"}
+</Heading>
+<Heading
+className={`w-heading`}>
+{"H1"}
+</Heading>
+<Paragraph
+className={`w-paragraph`}>
+{"Paragraph"}
+</Paragraph>
+</Box>
+<Box
+className={`w-box ch21dzk`}>
+<Heading
+className={`w-heading cc5h0no`}>
+{"Content Block With Templates Only"}
+</Heading>
+</Box>
+<Box
+className={`w-box c44hi06`}>
+<Heading
+className={`w-heading cc5h0no`}>
+{"With Content Only"}
+</Heading>
+<Heading
+className={`w-heading`}>
+{"H1"}
+</Heading>
+<Paragraph
+className={`w-paragraph`}>
+{"Paragraph"}
+</Paragraph>
+</Box>
+<Box
+className={`w-box cno1tjk`}>
+<Heading
+className={`w-heading cc5h0no`}>
+{"Empty"}
+</Heading>
+</Box>
+</Body>
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsx
index ae4185ddcc..07a3cfbb2a 100644
--- a/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: undefined,
redirect: "",
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[duration]._index.tsx b/fixtures/webstudio-features/app/__generated__/[duration]._index.tsx
index 296330ad3e..6407e8b742 100644
--- a/fixtures/webstudio-features/app/__generated__/[duration]._index.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[duration]._index.tsx
@@ -1,95 +1,63 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import { Body as Body } from "@webstudio-is/sdk-components-react-router";
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body } from "@webstudio-is/sdk-components-react-router";
import { AnimateChildren as AnimateChildren } from "@webstudio-is/sdk-components-animation";
import { Heading as Heading } from "@webstudio-is/sdk-components-react/components";
-export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
-
-export const projectDomain = "webstudio-fixture-project-a-0su3o";
-
-export const lastPublished = "2026-01-15T16:19:55.574Z";
-
-export const siteName = "KittyGuardedZone";
-
-export const breakpoints = [
- { id: "UoTkWyaFuTYJihS3MFYK5" },
- { id: "ZMaWCtWpH-ao0e_kgIHqR", minWidth: 372 },
- { id: "Z8WjyXWkCrr35PXgjHdpY", minWidth: 472 },
-];
-
-export const favIconAsset: string | undefined =
- "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
-
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
-
-export const pageBackgroundImageAssets: string[] = [];
-
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body`}>
- <AnimateChildren
- action={{
- type: "view",
- animations: [
- {
- name: "Parent",
- description: "Parallax the element as it scrolls into the view.",
- keyframes: [
- {
- offset: 0,
- styles: {
- translate: {
- type: "tuple",
- value: [
- { type: "unit", unit: "number", value: 0 },
- { type: "unit", unit: "px", value: 100 },
- ],
- },
- },
- },
- ],
- timing: {
- easing: "linear",
- fill: "backwards",
- duration: { type: "unit", value: 302, unit: "ms" },
- rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],
- rangeEnd: ["cover", { type: "unit", value: 50, unit: "%" }],
- },
- },
- ],
- insetStart: { type: "keyword", value: "auto" },
- insetEnd: { type: "keyword", value: "auto" },
- isPinned: true,
- debug: false,
- }}
- >
- <Heading className={`w-heading cjib6ds`}>
- {"HELLO WORLD"}
- {""}
- <br />
- {""}
- {"GOOD"}
- {""}
- <br />
- {""}
- {"BAD"}
- {""}
- <br />
- {""}
- {"UGLY"}
- </Heading>
- </AnimateChildren>
- </Body>
- );
-};
-
-export { Page };
+
+ export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
+
+
+
+ export const projectDomain = "webstudio-fixture-project-a-0su3o";
+
+ export const lastPublished = "2026-01-15T16:19:55.574Z";
+
+ export const siteName = "KittyGuardedZone";
+
+ export const breakpoints = [{"id":"UoTkWyaFuTYJihS3MFYK5"},{"id":"ZMaWCtWpH-ao0e_kgIHqR","minWidth":372},{"id":"Z8WjyXWkCrr35PXgjHdpY","minWidth":472}];
+
+ export const favIconAsset: string | undefined =
+ "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
+
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
+
+ export const pageBackgroundImageAssets: string[] =
+ []
+
+
+
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body`}>
+<AnimateChildren
+action={{"type":"view","animations":[{"name":"Parent","description":"Parallax the element as it scrolls into the view.","keyframes":[{"offset":0,"styles":{"translate":{"type":"tuple","value":[{"type":"unit","unit":"number","value":0},{"type":"unit","unit":"px","value":100}]}}}],"timing":{"easing":"linear","fill":"backwards","duration":{"type":"unit","value":302,"unit":"ms"},"rangeStart":["cover",{"type":"unit","value":0,"unit":"%"}],"rangeEnd":["cover",{"type":"unit","value":50,"unit":"%"}]}}],"insetStart":{"type":"keyword","value":"auto"},"insetEnd":{"type":"keyword","value":"auto"},"isPinned":true,"debug":false}}>
+<Heading
+className={`w-heading cjib6ds`}>
+{"HELLO WORLD"}
+{""}
+<br />
+{""}
+{"GOOD"}
+{""}
+<br />
+{""}
+{"BAD"}
+{""}
+<br />
+{""}
+{"UGLY"}
+</Heading>
+</AnimateChildren>
+</Body>
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx
index 6f1c7f0b95..07695cd8b1 100644
--- a/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx
@@ -1,24 +1,29 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
const jsonResourceVariable_1: ResourceRequest = {
name: "jsonResourceVariable",
url: "https://httpbin.org/get?hello=world",
- searchParams: [],
+ searchParams: [
+ ],
method: "get",
- headers: [],
- };
+ headers: [
+ ],
+ }
const _data = new Map<string, ResourceRequest>([
["jsonResourceVariable_1", jsonResourceVariable_1],
- ]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -35,13 +40,17 @@ export const getPageMeta = ({
status: 200,
redirect: "",
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[expressions]._index.tsx b/fixtures/webstudio-features/app/__generated__/[expressions]._index.tsx
index abc83242ec..b76c1319dc 100644
--- a/fixtures/webstudio-features/app/__generated__/[expressions]._index.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[expressions]._index.tsx
@@ -1,64 +1,63 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import { Body as Body } from "@webstudio-is/sdk-components-react-router";
-import {
- Heading as Heading,
- HtmlEmbed as HtmlEmbed,
- Box as Box,
-} from "@webstudio-is/sdk-components-react/components";
-
-export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
-
-export const projectDomain = "webstudio-fixture-project-a-0su3o";
-
-export const lastPublished = "2026-01-15T16:19:55.574Z";
-
-export const siteName = "KittyGuardedZone";
-
-export const breakpoints = [
- { id: "UoTkWyaFuTYJihS3MFYK5" },
- { id: "ZMaWCtWpH-ao0e_kgIHqR", minWidth: 372 },
- { id: "Z8WjyXWkCrr35PXgjHdpY", minWidth: 472 },
-];
-
-export const favIconAsset: string | undefined =
- "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
-
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
-
-export const pageBackgroundImageAssets: string[] = [];
-
-const Page = (_props: { system: any }) => {
- let jsonResourceVariable = useResource("jsonResourceVariable_1");
- let [jsonVar, set$jsonVar] = useVariableState<any>({ hello: "world" });
- let [globalVariable, set$globalVariable] =
- useVariableState<any>("globalValue");
- return (
- <Body className={`w-body`}>
- <Heading className={`w-heading`}>
- {renderText(`${jsonResourceVariable?.data?.args}`)}
- </Heading>
- <HtmlEmbed
- code={`<script>
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body } from "@webstudio-is/sdk-components-react-router";
+import { Heading as Heading, HtmlEmbed as HtmlEmbed, Box as Box } from "@webstudio-is/sdk-components-react/components";
+
+
+ export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
+
+
+
+ export const projectDomain = "webstudio-fixture-project-a-0su3o";
+
+ export const lastPublished = "2026-01-15T16:19:55.574Z";
+
+ export const siteName = "KittyGuardedZone";
+
+ export const breakpoints = [{"id":"UoTkWyaFuTYJihS3MFYK5"},{"id":"ZMaWCtWpH-ao0e_kgIHqR","minWidth":372},{"id":"Z8WjyXWkCrr35PXgjHdpY","minWidth":472}];
+
+ export const favIconAsset: string | undefined =
+ "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
+
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
+
+ export const pageBackgroundImageAssets: string[] =
+ []
+
+
+
+ const Page = (_props: { system: any; }) => {
+let jsonResourceVariable = useResource("jsonResourceVariable_1")
+let [jsonVar, set$jsonVar] = useVariableState<any>({"hello":"world"})
+let [globalVariable, set$globalVariable] = useVariableState<any>("globalValue")
+return <Body
+className={`w-body`}>
+<Heading
+className={`w-heading`}>
+{renderText(`${jsonResourceVariable?.data?.args}`)}
+</Heading>
+<HtmlEmbed
+code={`<script>
const a = ${jsonResourceVariable?.data?.args}
const b = ${jsonVar}
console.log(a, b);
</script>`}
- className={`w-html-embed`}
- />
- <Box className={`w-box`}>{renderText(globalVariable)}</Box>
- </Body>
- );
-};
-
-export { Page };
+className={`w-html-embed`} />
+<Box
+className={`w-box`}>
+{renderText(globalVariable)}
+</Box>
+</Body>
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx
index ec5f112308..4c3f3c98ae 100644
--- a/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx
@@ -1,22 +1,30 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
const action: ResourceRequest = {
name: "action",
url: "/custom",
- searchParams: [],
+ searchParams: [
+ ],
method: "get",
- headers: [{ name: "Content-Type", value: "application/json" }],
- };
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([["action", action]]);
- return { data: _data, action: _action };
-};
+ headers: [
+ { name: "Content-Type", value: "application/json" },
+ ],
+ }
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ["action", action],
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -33,13 +41,17 @@ export const getPageMeta = ({
status: undefined,
redirect: undefined,
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[form]._index.tsx b/fixtures/webstudio-features/app/__generated__/[form]._index.tsx
index e4ab56e099..fc34548291 100644
--- a/fixtures/webstudio-features/app/__generated__/[form]._index.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[form]._index.tsx
@@ -1,108 +1,142 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import {
- Body as Body,
- Form as Form,
-} from "@webstudio-is/sdk-components-react-router";
-import {
- Box as Box,
- Label as Label,
- Input as Input,
- Button as Button,
- Heading as Heading,
-} from "@webstudio-is/sdk-components-react/components";
-
-export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
-
-export const projectDomain = "webstudio-fixture-project-a-0su3o";
-
-export const lastPublished = "2026-01-15T16:19:55.574Z";
-
-export const siteName = "KittyGuardedZone";
-
-export const breakpoints = [
- { id: "UoTkWyaFuTYJihS3MFYK5" },
- { id: "ZMaWCtWpH-ao0e_kgIHqR", minWidth: 372 },
- { id: "Z8WjyXWkCrr35PXgjHdpY", minWidth: 472 },
-];
-
-export const favIconAsset: string | undefined =
- "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
-
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
-
-export const pageBackgroundImageAssets: string[] = [];
-
-const Page = (_props: { system: any }) => {
- let [formState, set$formState] = useVariableState<any>("initial");
- let [formState_1, set$formState_1] = useVariableState<any>("initial");
- return (
- <Body className={`w-body`}>
- <Form
- state={formState}
- onStateChange={(state: any) => {
- formState = state;
- set$formState(formState);
- }}
- className={`w-webhook-form`}
- >
- {(formState === "initial" || formState === "error") && (
- <Box className={`w-box`}>
- <Heading tag={"h3"} className={`w-heading`}>
- {"Default form"}
- </Heading>
- <Label className={`w-input-label`}>{"Name"}</Label>
- <Input name={"name"} className={`w-text-input`} />
- <Label className={`w-input-label`}>{"Email"}</Label>
- <Input name={"email"} className={`w-text-input`} />
- <Button className={`w-button`}>{"Submit"}</Button>
- </Box>
- )}
- {formState === "success" && (
- <Box className={`w-box`}>{"Thank you for getting in touch!"}</Box>
- )}
- {formState === "error" && (
- <Box className={`w-box`}>{"Sorry, something went wrong."}</Box>
- )}
- </Form>
- <Form
- state={formState_1}
- onStateChange={(state: any) => {
- formState_1 = state;
- set$formState_1(formState_1);
- }}
- action={"action"}
- className={`w-webhook-form`}
- >
- {(formState_1 === "initial" || formState_1 === "error") && (
- <Box className={`w-box`}>
- <Heading tag={"h3"} className={`w-heading`}>
- {"Form with custom action and method"}
- </Heading>
- <Label className={`w-input-label`}>{"Name"}</Label>
- <Input name={"name"} className={`w-text-input`} />
- <Label className={`w-input-label`}>{"Email"}</Label>
- <Input name={"email"} className={`w-text-input`} />
- <Button className={`w-button`}>{"Submit"}</Button>
- </Box>
- )}
- {formState_1 === "success" && (
- <Box className={`w-box`}>{"Thank you for getting in touch!"}</Box>
- )}
- {formState_1 === "error" && (
- <Box className={`w-box`}>{"Sorry, something went wrong."}</Box>
- )}
- </Form>
- </Body>
- );
-};
-
-export { Page };
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body, Form as Form } from "@webstudio-is/sdk-components-react-router";
+import { Box as Box, Label as Label, Input as Input, Button as Button, Heading as Heading } from "@webstudio-is/sdk-components-react/components";
+
+
+ export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
+
+
+
+ export const projectDomain = "webstudio-fixture-project-a-0su3o";
+
+ export const lastPublished = "2026-01-15T16:19:55.574Z";
+
+ export const siteName = "KittyGuardedZone";
+
+ export const breakpoints = [{"id":"UoTkWyaFuTYJihS3MFYK5"},{"id":"ZMaWCtWpH-ao0e_kgIHqR","minWidth":372},{"id":"Z8WjyXWkCrr35PXgjHdpY","minWidth":472}];
+
+ export const favIconAsset: string | undefined =
+ "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
+
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
+
+ export const pageBackgroundImageAssets: string[] =
+ []
+
+
+
+ const Page = (_props: { system: any; }) => {
+let [formState, set$formState] = useVariableState<any>("initial")
+let [formState_1, set$formState_1] = useVariableState<any>("initial")
+return <Body
+className={`w-body`}>
+<Form
+state={formState}
+onStateChange={(state: any) => {
+formState = state
+set$formState(formState)
+}}
+className={`w-webhook-form`}>
+{(formState === 'initial' || formState === 'error') &&
+<Box
+className={`w-box`}>
+<Heading
+tag={"h3"}
+className={`w-heading`}>
+{"Default form"}
+</Heading>
+<Label
+className={`w-input-label`}>
+{"Name"}
+</Label>
+<Input
+name={"name"}
+className={`w-text-input`} />
+<Label
+className={`w-input-label`}>
+{"Email"}
+</Label>
+<Input
+name={"email"}
+className={`w-text-input`} />
+<Button
+className={`w-button`}>
+{"Submit"}
+</Button>
+</Box>
+}
+{(formState === 'success') &&
+<Box
+className={`w-box`}>
+{"Thank you for getting in touch!"}
+</Box>
+}
+{(formState === 'error') &&
+<Box
+className={`w-box`}>
+{"Sorry, something went wrong."}
+</Box>
+}
+</Form>
+<Form
+state={formState_1}
+onStateChange={(state: any) => {
+formState_1 = state
+set$formState_1(formState_1)
+}}
+action={"action"}
+className={`w-webhook-form`}>
+{(formState_1 === 'initial' || formState_1 === 'error') &&
+<Box
+className={`w-box`}>
+<Heading
+tag={"h3"}
+className={`w-heading`}>
+{"Form with custom action and method"}
+</Heading>
+<Label
+className={`w-input-label`}>
+{"Name"}
+</Label>
+<Input
+name={"name"}
+className={`w-text-input`} />
+<Label
+className={`w-input-label`}>
+{"Email"}
+</Label>
+<Input
+name={"email"}
+className={`w-text-input`} />
+<Button
+className={`w-button`}>
+{"Submit"}
+</Button>
+</Box>
+}
+{(formState_1 === 'success') &&
+<Box
+className={`w-box`}>
+{"Thank you for getting in touch!"}
+</Box>
+}
+{(formState_1 === 'error') &&
+<Box
+className={`w-box`}>
+{"Sorry, something went wrong."}
+</Box>
+}
+</Form>
+</Body>
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsx
index 05e54798db..8fd5e5c714 100644
--- a/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: 200,
redirect: "",
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[head-tag]._index.tsx b/fixtures/webstudio-features/app/__generated__/[head-tag]._index.tsx
index 7e16a1ce03..fcf9f3ade6 100644
--- a/fixtures/webstudio-features/app/__generated__/[head-tag]._index.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[head-tag]._index.tsx
@@ -1,65 +1,69 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import {
- Body as Body,
- Link as Link,
-} from "@webstudio-is/sdk-components-react-router";
-import {
- HeadSlot as HeadSlot,
- HeadLink as HeadLink,
- HeadMeta as HeadMeta,
- Heading as Heading,
- HeadTitle as HeadTitle,
-} from "@webstudio-is/sdk-components-react/components";
-
-export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
-
-export const projectDomain = "webstudio-fixture-project-a-0su3o";
-
-export const lastPublished = "2026-01-15T16:19:55.574Z";
-
-export const siteName = "KittyGuardedZone";
-
-export const breakpoints = [
- { id: "UoTkWyaFuTYJihS3MFYK5" },
- { id: "ZMaWCtWpH-ao0e_kgIHqR", minWidth: 372 },
- { id: "Z8WjyXWkCrr35PXgjHdpY", minWidth: 472 },
-];
-
-export const favIconAsset: string | undefined =
- "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
-
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
-
-export const pageBackgroundImageAssets: string[] = [];
-
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body`}>
- <HeadSlot>
- <HeadTitle>{"Head Slot Title"}</HeadTitle>
- <HeadLink rel={"help"} href={"/help-head-slot"} />
- <HeadMeta name={"keywords"} content={"Head Slot Content"} />
- <HeadMeta content={"Head Slot Content"} property={"og:title"} />
- <HeadLink
- rel={"canonical"}
- href={"https://overwritten.slot/head-slot-tag"}
- />
- </HeadSlot>
- <Heading className={`w-heading`}>{"Test Head Slot"}</Heading>
- <Link href={"/"} className={`w-link`}>
- {"Go Home"}
- </Link>
- </Body>
- );
-};
-
-export { Page };
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body, Link as Link } from "@webstudio-is/sdk-components-react-router";
+import { HeadSlot as HeadSlot, HeadLink as HeadLink, HeadMeta as HeadMeta, Heading as Heading, HeadTitle as HeadTitle } from "@webstudio-is/sdk-components-react/components";
+
+
+ export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
+
+
+
+ export const projectDomain = "webstudio-fixture-project-a-0su3o";
+
+ export const lastPublished = "2026-01-15T16:19:55.574Z";
+
+ export const siteName = "KittyGuardedZone";
+
+ export const breakpoints = [{"id":"UoTkWyaFuTYJihS3MFYK5"},{"id":"ZMaWCtWpH-ao0e_kgIHqR","minWidth":372},{"id":"Z8WjyXWkCrr35PXgjHdpY","minWidth":472}];
+
+ export const favIconAsset: string | undefined =
+ "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
+
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
+
+ export const pageBackgroundImageAssets: string[] =
+ []
+
+
+
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body`}>
+<HeadSlot>
+<HeadTitle>
+{"Head Slot Title"}
+</HeadTitle>
+<HeadLink
+rel={"help"}
+href={"/help-head-slot"} />
+<HeadMeta
+name={"keywords"}
+content={"Head Slot Content"} />
+<HeadMeta
+content={"Head Slot Content"}
+property={"og:title"} />
+<HeadLink
+rel={"canonical"}
+href={"https://overwritten.slot/head-slot-tag"} />
+</HeadSlot>
+<Heading
+className={`w-heading`}>
+{"Test Head Slot"}
+</Heading>
+<Link
+href={"/"}
+className={`w-link`}>
+{"Go Home"}
+</Link>
+</Body>
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.server.tsx
index 1848504e3c..52fd99106b 100644
--- a/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: undefined,
redirect: undefined,
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.tsx b/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.tsx
index 88060d4a60..e4824a2966 100644
--- a/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.tsx
@@ -1,45 +1,48 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import { Body as Body } from "@webstudio-is/sdk-components-react-router";
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body } from "@webstudio-is/sdk-components-react-router";
import { Heading as Heading } from "@webstudio-is/sdk-components-react/components";
-export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
-export const projectDomain = "webstudio-fixture-project-a-0su3o";
+ export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
+
+
+
+ export const projectDomain = "webstudio-fixture-project-a-0su3o";
+
+ export const lastPublished = "2026-01-15T16:19:55.574Z";
+
+ export const siteName = "KittyGuardedZone";
-export const lastPublished = "2026-01-15T16:19:55.574Z";
+ export const breakpoints = [{"id":"UoTkWyaFuTYJihS3MFYK5"},{"id":"ZMaWCtWpH-ao0e_kgIHqR","minWidth":372},{"id":"Z8WjyXWkCrr35PXgjHdpY","minWidth":472}];
-export const siteName = "KittyGuardedZone";
+ export const favIconAsset: string | undefined =
+ "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
-export const breakpoints = [
- { id: "UoTkWyaFuTYJihS3MFYK5" },
- { id: "ZMaWCtWpH-ao0e_kgIHqR", minWidth: 372 },
- { id: "Z8WjyXWkCrr35PXgjHdpY", minWidth: 472 },
-];
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
-export const favIconAsset: string | undefined =
- "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
+ export const pageBackgroundImageAssets: string[] =
+ []
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
+
-export const pageBackgroundImageAssets: string[] = [];
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body`}>
+<Heading
+id={"my-heading"}
+className={`w-heading`}>
+{"Heading you can edit"}
+</Heading>
+</Body>
+}
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body`}>
- <Heading id={"my-heading"} className={`w-heading`}>
- {"Heading you can edit"}
- </Heading>
- </Body>
- );
-};
-export { Page };
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.server.tsx
index cf3eda55f3..aaaee6f246 100644
--- a/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: undefined,
redirect: undefined,
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.tsx b/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.tsx
index 80108f70a1..53d91ce4f1 100644
--- a/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.tsx
@@ -1,43 +1,47 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import { Body as Body } from "@webstudio-is/sdk-components-react-router";
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body } from "@webstudio-is/sdk-components-react-router";
import { Heading as Heading } from "@webstudio-is/sdk-components-react/components";
-export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
-export const projectDomain = "webstudio-fixture-project-a-0su3o";
+ export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
+
+
+
+ export const projectDomain = "webstudio-fixture-project-a-0su3o";
+
+ export const lastPublished = "2026-01-15T16:19:55.574Z";
+
+ export const siteName = "KittyGuardedZone";
-export const lastPublished = "2026-01-15T16:19:55.574Z";
+ export const breakpoints = [{"id":"UoTkWyaFuTYJihS3MFYK5"},{"id":"ZMaWCtWpH-ao0e_kgIHqR","minWidth":372},{"id":"Z8WjyXWkCrr35PXgjHdpY","minWidth":472}];
-export const siteName = "KittyGuardedZone";
+ export const favIconAsset: string | undefined =
+ "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
-export const breakpoints = [
- { id: "UoTkWyaFuTYJihS3MFYK5" },
- { id: "ZMaWCtWpH-ao0e_kgIHqR", minWidth: 372 },
- { id: "Z8WjyXWkCrr35PXgjHdpY", minWidth: 472 },
-];
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
-export const favIconAsset: string | undefined =
- "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
+ export const pageBackgroundImageAssets: string[] =
+ []
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
+
-export const pageBackgroundImageAssets: string[] = [];
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body`}>
+<Heading
+className={`w-heading`}>
+{"Nested page"}
+</Heading>
+</Body>
+}
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body`}>
- <Heading className={`w-heading`}>{"Nested page"}</Heading>
- </Body>
- );
-};
-export { Page };
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsx
index 467a91ce19..49d91d7a44 100644
--- a/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -18,8 +22,7 @@ export const getPageMeta = ({
}): PageMeta => {
return {
title: "Radix Revelations: Unraveling the Feline Mystique",
- description:
- "Delve deep into the radix roots of feline behaviors. At KittyNoTouchy, we dissect the core essence, or 'radix', of what makes cats the enigmatic creatures they are. Join us as we explore the radix of their instincts, habits, and quirks.",
+ description: "Delve deep into the radix roots of feline behaviors. At KittyNoTouchy, we dissect the core essence, or 'radix', of what makes cats the enigmatic creatures they are. Join us as we explore the radix of their instincts, habits, and quirks.",
excludePageFromSearch: true,
language: undefined,
socialImageAssetName: undefined,
@@ -27,13 +30,17 @@ export const getPageMeta = ({
status: undefined,
redirect: undefined,
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[radix]._index.tsx b/fixtures/webstudio-features/app/__generated__/[radix]._index.tsx
index 492ddd59a4..907fe214a8 100644
--- a/fixtures/webstudio-features/app/__generated__/[radix]._index.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[radix]._index.tsx
@@ -1,140 +1,126 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import { Body as Body } from "@webstudio-is/sdk-components-react-router";
-import {
- Accordion as Accordion,
- AccordionItem as AccordionItem,
- AccordionHeader as AccordionHeader,
- AccordionTrigger as AccordionTrigger,
- AccordionContent as AccordionContent,
-} from "@webstudio-is/sdk-components-react-radix";
-import {
- Text as Text,
- Box as Box,
- HtmlEmbed as HtmlEmbed,
-} from "@webstudio-is/sdk-components-react/components";
-
-export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
-
-export const projectDomain = "webstudio-fixture-project-a-0su3o";
-
-export const lastPublished = "2026-01-15T16:19:55.574Z";
-
-export const siteName = "KittyGuardedZone";
-
-export const breakpoints = [
- { id: "UoTkWyaFuTYJihS3MFYK5" },
- { id: "ZMaWCtWpH-ao0e_kgIHqR", minWidth: 372 },
- { id: "Z8WjyXWkCrr35PXgjHdpY", minWidth: 472 },
-];
-
-export const favIconAsset: string | undefined =
- "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
-
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
-
-export const pageBackgroundImageAssets: string[] = [];
-
-const Page = (_props: { system: any }) => {
- let [accordionValue, set$accordionValue] = useVariableState<any>("0");
- return (
- <Body className={`w-body`}>
- <Accordion
- collapsible={true}
- value={accordionValue}
- onValueChange={(value: any) => {
- accordionValue = value;
- set$accordionValue(accordionValue);
- }}
- className={`w-accordion`}
- >
- <AccordionItem data-ws-index="0" className={`w-item c6gjj8k`}>
- <AccordionHeader className={`w-item-header c13v7j50`}>
- <AccordionTrigger
- className={`w-item-trigger c13v7j50 c1qxdkbn chhejm9 c13bviim cpjvam0 c1tw5o2 cqw88jp c44srea c14kxsax cg783j6 c1ad236a c1s4llbc`}
- >
- <Text className={`w-text`}>{"Is it accessible?"}</Text>
- <Box
- className={`w-box c14hansb c6d2sb5 cwwiftc c16vb2zi c1hl6g8z c1xm49r0 c1vri55v`}
- >
- <HtmlEmbed
- code={
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor" width="100%" height="100%" style="display: block;"><path d="M4.04 6.284a.65.65 0 0 1 .92.001L8 9.335l3.04-3.05a.65.65 0 1 1 .921.918l-3.5 3.512a.65.65 0 0 1-.921 0L4.039 7.203a.65.65 0 0 1 .001-.92Z"/></svg>'
- }
- className={`w-html-embed`}
- />
- </Box>
- </AccordionTrigger>
- </AccordionHeader>
- <AccordionContent
- className={`w-item-content c1j0j9ep c1gl2i2 c44srea c1xcxvc0 c12ct49k`}
- >
- {"Yes. It adheres to the WAI-ARIA design pattern."}
- </AccordionContent>
- </AccordionItem>
- <AccordionItem data-ws-index="1" className={`w-item c6gjj8k`}>
- <AccordionHeader className={`w-item-header c13v7j50`}>
- <AccordionTrigger
- className={`w-item-trigger c13v7j50 c1qxdkbn chhejm9 c13bviim cpjvam0 c1tw5o2 cqw88jp c44srea c14kxsax cg783j6 c1ad236a c1s4llbc`}
- >
- <Text className={`w-text`}>{"Is it styled?"}</Text>
- <Box
- className={`w-box c14hansb c6d2sb5 cwwiftc c16vb2zi c1hl6g8z c1xm49r0 c1vri55v`}
- >
- <HtmlEmbed
- code={
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor" width="100%" height="100%" style="display: block;"><path d="M4.04 6.284a.65.65 0 0 1 .92.001L8 9.335l3.04-3.05a.65.65 0 1 1 .921.918l-3.5 3.512a.65.65 0 0 1-.921 0L4.039 7.203a.65.65 0 0 1 .001-.92Z"/></svg>'
- }
- className={`w-html-embed`}
- />
- </Box>
- </AccordionTrigger>
- </AccordionHeader>
- <AccordionContent
- className={`w-item-content c1j0j9ep c1gl2i2 c44srea c1xcxvc0 c12ct49k`}
- >
- {
- "Yes. It comes with default styles that matches the other components' aesthetic."
- }
- </AccordionContent>
- </AccordionItem>
- <AccordionItem data-ws-index="2" className={`w-item c6gjj8k`}>
- <AccordionHeader className={`w-item-header c13v7j50`}>
- <AccordionTrigger
- className={`w-item-trigger c13v7j50 c1qxdkbn chhejm9 c13bviim cpjvam0 c1tw5o2 cqw88jp c44srea c14kxsax cg783j6 c1ad236a c1s4llbc`}
- >
- <Text className={`w-text`}>{"Is it animated?"}</Text>
- <Box
- className={`w-box c14hansb c6d2sb5 cwwiftc c16vb2zi c1hl6g8z c1xm49r0 c1vri55v`}
- >
- <HtmlEmbed
- code={
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor" width="100%" height="100%" style="display: block;"><path d="M4.04 6.284a.65.65 0 0 1 .92.001L8 9.335l3.04-3.05a.65.65 0 1 1 .921.918l-3.5 3.512a.65.65 0 0 1-.921 0L4.039 7.203a.65.65 0 0 1 .001-.92Z"/></svg>'
- }
- className={`w-html-embed`}
- />
- </Box>
- </AccordionTrigger>
- </AccordionHeader>
- <AccordionContent
- className={`w-item-content c1j0j9ep c1gl2i2 c44srea c1xcxvc0 c12ct49k`}
- >
- {
- "Yes. It's animated by default, but you can disable it if you prefer."
- }
- </AccordionContent>
- </AccordionItem>
- </Accordion>
- </Body>
- );
-};
-
-export { Page };
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body } from "@webstudio-is/sdk-components-react-router";
+import { Accordion as Accordion, AccordionItem as AccordionItem, AccordionHeader as AccordionHeader, AccordionTrigger as AccordionTrigger, AccordionContent as AccordionContent } from "@webstudio-is/sdk-components-react-radix";
+import { Text as Text, Box as Box, HtmlEmbed as HtmlEmbed } from "@webstudio-is/sdk-components-react/components";
+
+
+ export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
+
+
+
+ export const projectDomain = "webstudio-fixture-project-a-0su3o";
+
+ export const lastPublished = "2026-01-15T16:19:55.574Z";
+
+ export const siteName = "KittyGuardedZone";
+
+ export const breakpoints = [{"id":"UoTkWyaFuTYJihS3MFYK5"},{"id":"ZMaWCtWpH-ao0e_kgIHqR","minWidth":372},{"id":"Z8WjyXWkCrr35PXgjHdpY","minWidth":472}];
+
+ export const favIconAsset: string | undefined =
+ "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
+
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
+
+ export const pageBackgroundImageAssets: string[] =
+ []
+
+
+
+ const Page = (_props: { system: any; }) => {
+let [accordionValue, set$accordionValue] = useVariableState<any>("0")
+return <Body
+className={`w-body`}>
+<Accordion
+collapsible={true}
+value={accordionValue}
+onValueChange={(value: any) => {
+accordionValue = value
+set$accordionValue(accordionValue)
+}}
+className={`w-accordion`}>
+<AccordionItem
+data-ws-index="0"
+className={`w-item c6gjj8k`}>
+<AccordionHeader
+className={`w-item-header c13v7j50`}>
+<AccordionTrigger
+className={`w-item-trigger c13v7j50 c1qxdkbn chhejm9 c13bviim cpjvam0 c1tw5o2 cqw88jp c44srea c14kxsax cg783j6 c1ad236a c1s4llbc`}>
+<Text
+className={`w-text`}>
+{"Is it accessible?"}
+</Text>
+<Box
+className={`w-box c14hansb c6d2sb5 cwwiftc c16vb2zi c1hl6g8z c1xm49r0 c1vri55v`}>
+<HtmlEmbed
+code={"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 16 16\" fill=\"currentColor\" width=\"100%\" height=\"100%\" style=\"display: block;\"><path d=\"M4.04 6.284a.65.65 0 0 1 .92.001L8 9.335l3.04-3.05a.65.65 0 1 1 .921.918l-3.5 3.512a.65.65 0 0 1-.921 0L4.039 7.203a.65.65 0 0 1 .001-.92Z\"/></svg>"}
+className={`w-html-embed`} />
+</Box>
+</AccordionTrigger>
+</AccordionHeader>
+<AccordionContent
+className={`w-item-content c1j0j9ep c1gl2i2 c44srea c1xcxvc0 c12ct49k`}>
+{"Yes. It adheres to the WAI-ARIA design pattern."}
+</AccordionContent>
+</AccordionItem>
+<AccordionItem
+data-ws-index="1"
+className={`w-item c6gjj8k`}>
+<AccordionHeader
+className={`w-item-header c13v7j50`}>
+<AccordionTrigger
+className={`w-item-trigger c13v7j50 c1qxdkbn chhejm9 c13bviim cpjvam0 c1tw5o2 cqw88jp c44srea c14kxsax cg783j6 c1ad236a c1s4llbc`}>
+<Text
+className={`w-text`}>
+{"Is it styled?"}
+</Text>
+<Box
+className={`w-box c14hansb c6d2sb5 cwwiftc c16vb2zi c1hl6g8z c1xm49r0 c1vri55v`}>
+<HtmlEmbed
+code={"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 16 16\" fill=\"currentColor\" width=\"100%\" height=\"100%\" style=\"display: block;\"><path d=\"M4.04 6.284a.65.65 0 0 1 .92.001L8 9.335l3.04-3.05a.65.65 0 1 1 .921.918l-3.5 3.512a.65.65 0 0 1-.921 0L4.039 7.203a.65.65 0 0 1 .001-.92Z\"/></svg>"}
+className={`w-html-embed`} />
+</Box>
+</AccordionTrigger>
+</AccordionHeader>
+<AccordionContent
+className={`w-item-content c1j0j9ep c1gl2i2 c44srea c1xcxvc0 c12ct49k`}>
+{"Yes. It comes with default styles that matches the other components' aesthetic."}
+</AccordionContent>
+</AccordionItem>
+<AccordionItem
+data-ws-index="2"
+className={`w-item c6gjj8k`}>
+<AccordionHeader
+className={`w-item-header c13v7j50`}>
+<AccordionTrigger
+className={`w-item-trigger c13v7j50 c1qxdkbn chhejm9 c13bviim cpjvam0 c1tw5o2 cqw88jp c44srea c14kxsax cg783j6 c1ad236a c1s4llbc`}>
+<Text
+className={`w-text`}>
+{"Is it animated?"}
+</Text>
+<Box
+className={`w-box c14hansb c6d2sb5 cwwiftc c16vb2zi c1hl6g8z c1xm49r0 c1vri55v`}>
+<HtmlEmbed
+code={"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 16 16\" fill=\"currentColor\" width=\"100%\" height=\"100%\" style=\"display: block;\"><path d=\"M4.04 6.284a.65.65 0 0 1 .92.001L8 9.335l3.04-3.05a.65.65 0 1 1 .921.918l-3.5 3.512a.65.65 0 0 1-.921 0L4.039 7.203a.65.65 0 0 1 .001-.92Z\"/></svg>"}
+className={`w-html-embed`} />
+</Box>
+</AccordionTrigger>
+</AccordionHeader>
+<AccordionContent
+className={`w-item-content c1j0j9ep c1gl2i2 c44srea c1xcxvc0 c12ct49k`}>
+{"Yes. It's animated by default, but you can disable it if you prefer."}
+</AccordionContent>
+</AccordionItem>
+</Accordion>
+</Body>
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx
index 7895fa75aa..0058dccf45 100644
--- a/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx
@@ -1,22 +1,29 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
const list_1: ResourceRequest = {
name: "list",
url: "https://gist.githubusercontent.com/TrySound/56507c301ec85669db5f1541406a9259/raw/a49548730ab592c86b9e7781f5b29beec4765494/collection.json",
- searchParams: [],
+ searchParams: [
+ ],
method: "get",
- headers: [],
- };
- const _data = new Map<string, ResourceRequest>([["list_1", list_1]]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ headers: [
+ ],
+ }
+ const _data = new Map<string, ResourceRequest>([
+ ["list_1", list_1],
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -33,13 +40,17 @@ export const getPageMeta = ({
status: undefined,
redirect: undefined,
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[resources]._index.tsx b/fixtures/webstudio-features/app/__generated__/[resources]._index.tsx
index 50b6f08353..8b6343810e 100644
--- a/fixtures/webstudio-features/app/__generated__/[resources]._index.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[resources]._index.tsx
@@ -1,62 +1,61 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import { Body as Body } from "@webstudio-is/sdk-components-react-router";
-import {
- Box as Box,
- HtmlEmbed as HtmlEmbed,
-} from "@webstudio-is/sdk-components-react/components";
-export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body } from "@webstudio-is/sdk-components-react-router";
+import { Box as Box, HtmlEmbed as HtmlEmbed } from "@webstudio-is/sdk-components-react/components";
-export const projectDomain = "webstudio-fixture-project-a-0su3o";
-export const lastPublished = "2026-01-15T16:19:55.574Z";
+ export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
-export const siteName = "KittyGuardedZone";
+
-export const breakpoints = [
- { id: "UoTkWyaFuTYJihS3MFYK5" },
- { id: "ZMaWCtWpH-ao0e_kgIHqR", minWidth: 372 },
- { id: "Z8WjyXWkCrr35PXgjHdpY", minWidth: 472 },
-];
+ export const projectDomain = "webstudio-fixture-project-a-0su3o";
-export const favIconAsset: string | undefined =
- "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
+ export const lastPublished = "2026-01-15T16:19:55.574Z";
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
+ export const siteName = "KittyGuardedZone";
-export const pageBackgroundImageAssets: string[] = [];
+ export const breakpoints = [{"id":"UoTkWyaFuTYJihS3MFYK5"},{"id":"ZMaWCtWpH-ao0e_kgIHqR","minWidth":372},{"id":"Z8WjyXWkCrr35PXgjHdpY","minWidth":472}];
-const Page = (_props: { system: any }) => {
- let list = useResource("list_1");
+ export const favIconAsset: string | undefined =
+ "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
+
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
+
+ export const pageBackgroundImageAssets: string[] =
+ []
+
+
+
+ const Page = (_props: { system: any; }) => {
+let list = useResource("list_1")
+return <Body
+className={`w-body`}>
+{Object.entries(
+ // @ts-ignore
+ list?.data ?? {}
+).map(([_key, collectionItem]: any) => {
+ const index = Array.isArray(list?.data) ? Number(_key) : _key;
return (
- <Body className={`w-body`}>
- {Object.entries(
- // @ts-ignore
- list?.data ?? {}
- ).map(([_key, collectionItem]: any) => {
- const index = Array.isArray(list?.data) ? Number(_key) : _key;
- return (
- <Fragment key={index}>
- <Box className={`w-box`}>
- <HtmlEmbed
- code={collectionItem?.name}
- className={`w-html-embed`}
- />
- </Box>
- </Fragment>
- );
- })}
- </Body>
- );
-};
-
-export { Page };
+<Fragment key={index}>
+<Box
+className={`w-box`}>
+<HtmlEmbed
+code={collectionItem?.name}
+className={`w-html-embed`} />
+</Box>
+</Fragment>
+)
+})
+}
+</Body>
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsx
index 05e54798db..8fd5e5c714 100644
--- a/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: 200,
redirect: "",
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.tsx b/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.tsx
index d36f971ec3..b71dfb1783 100644
--- a/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.tsx
@@ -1,105 +1,115 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import {
- XmlNode as XmlNode,
- XmlTime as XmlTime,
-} from "@webstudio-is/sdk-components-react/components";
-export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { XmlNode as XmlNode, XmlTime as XmlTime } from "@webstudio-is/sdk-components-react/components";
-export const projectDomain = "webstudio-fixture-project-a-0su3o";
-export const lastPublished = "2026-01-15T16:19:55.574Z";
+ export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
-export const siteName = "KittyGuardedZone";
+
-export const breakpoints = [
- { id: "UoTkWyaFuTYJihS3MFYK5" },
- { id: "ZMaWCtWpH-ao0e_kgIHqR", minWidth: 372 },
- { id: "Z8WjyXWkCrr35PXgjHdpY", minWidth: 472 },
-];
+ export const projectDomain = "webstudio-fixture-project-a-0su3o";
-export const favIconAsset: string | undefined =
- "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
+ export const lastPublished = "2026-01-15T16:19:55.574Z";
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
+ export const siteName = "KittyGuardedZone";
-export const pageBackgroundImageAssets: string[] = [];
+ export const breakpoints = [{"id":"UoTkWyaFuTYJihS3MFYK5"},{"id":"ZMaWCtWpH-ao0e_kgIHqR","minWidth":372},{"id":"Z8WjyXWkCrr35PXgjHdpY","minWidth":472}];
-const Page = (_props: { system: any }) => {
- const system = _props.system;
+ export const favIconAsset: string | undefined =
+ "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
+
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
+
+ export const pageBackgroundImageAssets: string[] =
+ []
+
+
+
+ const Page = (_props: { system: any; }) => {
+const system = _props.system;
+return <XmlNode
+tag={"urlset"}
+xmlns={"http://www.sitemaps.org/schemas/sitemap/0.9"}
+xmlns:xhtml={"http://www.w3.org/TR/xhtml11/xhtml11_schema.html"}>
+{Object.entries(
+ // @ts-ignore
+ [
+ {
+ "path": "/",
+ "lastModified": "2024-05-07"
+ },
+ {
+ "path": "/olegs-test",
+ "lastModified": "2024-05-07"
+ }
+]
+).map(([_key, url]: any) => {
+ const index = Array.isArray([
+ {
+ "path": "/",
+ "lastModified": "2024-05-07"
+ },
+ {
+ "path": "/olegs-test",
+ "lastModified": "2024-05-07"
+ }
+]) ? Number(_key) : _key;
return (
- <XmlNode
- tag={"urlset"}
- xmlns={"http://www.sitemaps.org/schemas/sitemap/0.9"}
- xmlns:xhtml={"http://www.w3.org/TR/xhtml11/xhtml11_schema.html"}
- >
- {Object.entries(
- // @ts-ignore
- [
- {
- path: "/",
- lastModified: "2024-05-07",
- },
- {
- path: "/olegs-test",
- lastModified: "2024-05-07",
- },
- ]
- ).map(([_key, url]: any) => {
- const index = Array.isArray([
- {
- path: "/",
- lastModified: "2024-05-07",
- },
- {
- path: "/olegs-test",
- lastModified: "2024-05-07",
- },
- ])
- ? Number(_key)
- : _key;
- return (
- <Fragment key={index}>
- <XmlNode tag={"url"}>
- <XmlNode tag={"loc"}>
- {renderText(`${system?.origin ?? "${ORIGIN}"}${url?.path}`)}
- </XmlNode>
- <XmlNode tag={"lastmod"}>{renderText(url?.lastModified)}</XmlNode>
- <XmlNode
- tag={"xhtml:link"}
- rel={"alternate"}
- hreflang={"en"}
- href={`${system?.origin ?? "${ORIGIN}"}${url?.path}en`}
- />
- </XmlNode>
- </Fragment>
- );
- })}
- <XmlNode tag={"url"}>
- <XmlNode tag={"loc"}>{"custom-hand-made-location"}</XmlNode>
- <XmlNode tag={"lastmod"}>
- <XmlTime datetime={"1733402818245"} />
- </XmlNode>
- <XmlNode
- tag={"xhtml:link"}
- rel={"alternate"}
- hreflang={"en"}
- href={"custom-en-location"}
- />
- <XmlNode tag={"title"}>{"Hello"}</XmlNode>
- <XmlNode tag={"link"}>{"https://webstudio.is"}</XmlNode>
- </XmlNode>
- </XmlNode>
- );
-};
-
-export { Page };
+<Fragment key={index}>
+<XmlNode
+tag={"url"}>
+<XmlNode
+tag={"loc"}>
+{renderText(`${system?.origin ?? '${ORIGIN}'}${url?.path}`)}
+</XmlNode>
+<XmlNode
+tag={"lastmod"}>
+{renderText(url?.lastModified)}
+</XmlNode>
+<XmlNode
+tag={"xhtml:link"}
+rel={"alternate"}
+hreflang={"en"}
+href={`${system?.origin ?? '${ORIGIN}'}${url?.path}en`} />
+</XmlNode>
+</Fragment>
+)
+})
+}
+<XmlNode
+tag={"url"}>
+<XmlNode
+tag={"loc"}>
+{"custom-hand-made-location"}
+</XmlNode>
+<XmlNode
+tag={"lastmod"}>
+<XmlTime
+datetime={"1733402818245"} />
+</XmlNode>
+<XmlNode
+tag={"xhtml:link"}
+rel={"alternate"}
+hreflang={"en"}
+href={"custom-en-location"} />
+<XmlNode
+tag={"title"}>
+{"Hello"}
+</XmlNode>
+<XmlNode
+tag={"link"}>
+{"https://webstudio.is"}
+</XmlNode>
+</XmlNode>
+</XmlNode>
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsx
index ae4185ddcc..07a3cfbb2a 100644
--- a/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -26,13 +30,17 @@ export const getPageMeta = ({
status: undefined,
redirect: "",
content: undefined,
- custom: [],
+ custom: [
+ ],
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[text-duration]._index.tsx b/fixtures/webstudio-features/app/__generated__/[text-duration]._index.tsx
index 060de920d3..2850be8ebc 100644
--- a/fixtures/webstudio-features/app/__generated__/[text-duration]._index.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[text-duration]._index.tsx
@@ -1,117 +1,66 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import { Body as Body } from "@webstudio-is/sdk-components-react-router";
-import {
- AnimateChildren as AnimateChildren,
- AnimateText as AnimateText,
-} from "@webstudio-is/sdk-components-animation";
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body } from "@webstudio-is/sdk-components-react-router";
+import { AnimateChildren as AnimateChildren, AnimateText as AnimateText } from "@webstudio-is/sdk-components-animation";
import { Heading as Heading } from "@webstudio-is/sdk-components-react/components";
-export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
-
-export const projectDomain = "webstudio-fixture-project-a-0su3o";
-
-export const lastPublished = "2026-01-15T16:19:55.574Z";
-
-export const siteName = "KittyGuardedZone";
-
-export const breakpoints = [
- { id: "UoTkWyaFuTYJihS3MFYK5" },
- { id: "ZMaWCtWpH-ao0e_kgIHqR", minWidth: 372 },
- { id: "Z8WjyXWkCrr35PXgjHdpY", minWidth: 472 },
-];
-
-export const favIconAsset: string | undefined =
- "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
-
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
-
-export const pageBackgroundImageAssets: string[] = [];
-
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body`}>
- <AnimateChildren
- action={{
- type: "view",
- animations: [
- {
- name: "Parent",
- description: "Parallax the element as it scrolls into the view.",
- keyframes: [
- {
- offset: 0,
- styles: {
- translate: {
- type: "tuple",
- value: [
- { type: "unit", unit: "number", value: 0 },
- { type: "unit", unit: "px", value: 200 },
- ],
- },
- },
- },
- ],
- timing: {
- easing: "linear",
- fill: "backwards",
- duration: { type: "unit", value: 600, unit: "ms" },
- rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],
- rangeEnd: ["cover", { type: "unit", value: 50, unit: "%" }],
- },
- },
- {
- name: "Parallax In",
- description: "Parallax the element as it scrolls into the view.",
- keyframes: [
- {
- offset: 0,
- styles: { opacity: { type: "unit", unit: "%", value: 0 } },
- },
- ],
- timing: {
- easing: "linear",
- fill: "backwards",
- duration: { type: "unit", value: 600, unit: "ms" },
- rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],
- rangeEnd: ["cover", { type: "unit", value: 50, unit: "%" }],
- },
- },
- ],
- insetStart: { type: "keyword", value: "auto" },
- insetEnd: { type: "keyword", value: "auto" },
- isPinned: true,
- debug: false,
- }}
- >
- <AnimateText className={`w-text-animation`}>
- <Heading className={`w-heading cjib6ds`}>
- {"HELLO WORLD"}
- {""}
- <br />
- {""}
- {"GOOD"}
- {""}
- <br />
- {""}
- {"BAD"}
- {""}
- <br />
- {""}
- {"UGLY"}
- </Heading>
- </AnimateText>
- </AnimateChildren>
- </Body>
- );
-};
-
-export { Page };
+
+ export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
+
+
+
+ export const projectDomain = "webstudio-fixture-project-a-0su3o";
+
+ export const lastPublished = "2026-01-15T16:19:55.574Z";
+
+ export const siteName = "KittyGuardedZone";
+
+ export const breakpoints = [{"id":"UoTkWyaFuTYJihS3MFYK5"},{"id":"ZMaWCtWpH-ao0e_kgIHqR","minWidth":372},{"id":"Z8WjyXWkCrr35PXgjHdpY","minWidth":472}];
+
+ export const favIconAsset: string | undefined =
+ "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
+
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
+
+ export const pageBackgroundImageAssets: string[] =
+ []
+
+
+
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body`}>
+<AnimateChildren
+action={{"type":"view","animations":[{"name":"Parent","description":"Parallax the element as it scrolls into the view.","keyframes":[{"offset":0,"styles":{"translate":{"type":"tuple","value":[{"type":"unit","unit":"number","value":0},{"type":"unit","unit":"px","value":200}]}}}],"timing":{"easing":"linear","fill":"backwards","duration":{"type":"unit","value":600,"unit":"ms"},"rangeStart":["cover",{"type":"unit","value":0,"unit":"%"}],"rangeEnd":["cover",{"type":"unit","value":50,"unit":"%"}]}},{"name":"Parallax In","description":"Parallax the element as it scrolls into the view.","keyframes":[{"offset":0,"styles":{"opacity":{"type":"unit","unit":"%","value":0}}}],"timing":{"easing":"linear","fill":"backwards","duration":{"type":"unit","value":600,"unit":"ms"},"rangeStart":["cover",{"type":"unit","value":0,"unit":"%"}],"rangeEnd":["cover",{"type":"unit","value":50,"unit":"%"}]}}],"insetStart":{"type":"keyword","value":"auto"},"insetEnd":{"type":"keyword","value":"auto"},"isPinned":true,"debug":false}}>
+<AnimateText
+className={`w-text-animation`}>
+<Heading
+className={`w-heading cjib6ds`}>
+{"HELLO WORLD"}
+{""}
+<br />
+{""}
+{"GOOD"}
+{""}
+<br />
+{""}
+{"BAD"}
+{""}
+<br />
+{""}
+{"UGLY"}
+</Heading>
+</AnimateText>
+</AnimateChildren>
+</Body>
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/_index.server.tsx b/fixtures/webstudio-features/app/__generated__/_index.server.tsx
index 6f3569767f..1b005258f3 100644
--- a/fixtures/webstudio-features/app/__generated__/_index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/_index.server.tsx
@@ -1,15 +1,19 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
+ /* This is a auto generated file for building the project */
-import type { PageMeta } from "@webstudio-is/sdk";
-import type { System, ResourceRequest } from "@webstudio-is/sdk";
+
+ import type { PageMeta } from "@webstudio-is/sdk";
+ import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
- const _data = new Map<string, ResourceRequest>([]);
- const _action = new Map<string, ResourceRequest>([]);
- return { data: _data, action: _action };
-};
+ const _data = new Map<string, ResourceRequest>([
+ ])
+ const _action = new Map<string, ResourceRequest>([
+ ])
+ return { data: _data, action: _action }
+}
+
-export const getPageMeta = ({
+ export const getPageMeta = ({
system,
resources,
}: {
@@ -18,12 +22,10 @@ export const getPageMeta = ({
}): PageMeta => {
return {
title: "The Ultimate Cat Protection Zone",
- description:
- "Dive into the world of felines and discover why some whiskers are best left untouched. From intriguing cat behaviors to protective measures, \nKittyGuardedZone is your go-to hub for all things 'hands-off' in the cat realm.",
+ description: "Dive into the world of felines and discover why some whiskers are best left untouched. From intriguing cat behaviors to protective measures, \nKittyGuardedZone is your go-to hub for all things 'hands-off' in the cat realm.",
excludePageFromSearch: undefined,
language: undefined,
- socialImageAssetName:
- "_937084ed-a798-49fe-8664-df93a2af605e_uiBk3o6UWdqolyakMvQJ9.jpeg",
+ socialImageAssetName: "_937084ed-a798-49fe-8664-df93a2af605e_uiBk3o6UWdqolyakMvQJ9.jpeg",
socialImageUrl: undefined,
status: undefined,
redirect: undefined,
@@ -37,9 +39,12 @@ export const getPageMeta = ({
};
};
-type Params = Record<string, string | undefined>;
+
+ type Params = Record<string, string | undefined>;
export const getRemixParams = ({ ...params }: Params): Params => {
- return params;
-};
+ return params
+}
+
-export const contactEmail = "[email protected]";
+ export const contactEmail = "[email protected]";
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/_index.tsx b/fixtures/webstudio-features/app/__generated__/_index.tsx
index 532391737a..1d6e16c615 100644
--- a/fixtures/webstudio-features/app/__generated__/_index.tsx
+++ b/fixtures/webstudio-features/app/__generated__/_index.tsx
@@ -1,120 +1,115 @@
/* eslint-disable */
-/* This is a auto generated file for building the project */
-
-import { Fragment, useState } from "react";
-import {
- renderText,
- useResource,
- useVariableState,
-} from "@webstudio-is/react-sdk/runtime";
-import {
- Body as Body,
- Link as Link,
- Link as Link_1,
-} from "@webstudio-is/sdk-components-react-router";
-import {
- Heading as Heading,
- Box as Box,
- Paragraph as Paragraph,
- Image as Image,
- Text as Text,
-} from "@webstudio-is/sdk-components-react/components";
-
-export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
-
-export const projectVersion = 634;
-
-export const projectDomain = "webstudio-fixture-project-a-0su3o";
-
-export const lastPublished = "2026-01-15T16:19:55.574Z";
-
-export const siteName = "KittyGuardedZone";
-
-export const breakpoints = [
- { id: "UoTkWyaFuTYJihS3MFYK5" },
- { id: "ZMaWCtWpH-ao0e_kgIHqR", minWidth: 372 },
- { id: "Z8WjyXWkCrr35PXgjHdpY", minWidth: 472 },
-];
-
-export const favIconAsset: string | undefined =
- "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
-
-// Font assets on current page (can be preloaded)
-export const pageFontAssets: string[] = [];
-
-export const pageBackgroundImageAssets: string[] = [];
-
-const Script = ({ children, ...props }: Record<string, string | boolean>) => {
- if (children == null) {
- return <script {...props} />;
- }
-
- return <script {...props} dangerouslySetInnerHTML={{ __html: children }} />;
-};
-const Style = ({ children, ...props }: Record<string, string | boolean>) => {
- if (children == null) {
- return <style {...props} />;
- }
-
- return <style {...props} dangerouslySetInnerHTML={{ __html: children }} />;
-};
-
-export const CustomCode = () => {
- return (
- <>
- <Script>{"console.log('KittyGuardedZone')"}</Script>
- </>
- );
-};
-
-const Page = (_props: { system: any }) => {
- return (
- <Body className={`w-body cielobv`}>
- <Heading className={`w-heading ceva767`}>
- {"DO NOT TOUCH THIS PROJECT, IT'S USED FOR FIXTURES"}
- </Heading>
- <Box className={`w-box c13v7j50 cqkqnmd cv6wa71`}>
- <Box className={`w-box c1t3ybra c1qxdkbn c1ogzcge cv3kvac`}>
- <Heading className={`w-heading`}>{"Heading"}</Heading>
- <Paragraph className={`w-paragraph`}>
- {
- "a little kitten painted in black and white gouache with a thick brush"
- }
- </Paragraph>
- <Link_1 href={"https://github.com/"} className={`w-element ch2exr5`}>
- {"Click here to adore more kittens"}
- </Link_1>
- <Text tag={"span"} className={`w-text`}>
- {" or "}
- </Text>
- <Link
- href={"/assets/small-avif-kitty_FnabJsioMWpBtXZSGf4DR.webp"}
- className={`w-link`}
- >
- {"go download this little kitten"}
- </Link>
- <Box className={`w-box`} />
- <Link href={"/_route_with_symbols_"} className={`w-link ch2exr5`}>
- {"Symbols in path"}
- </Link>
- <Link
- href={"/heading-with-id#my-heading"}
- className={`w-link ch2exr5`}
- >
- {"Link to instance"}
- </Link>
- </Box>
- <Box className={`w-box c1t3ybra c1qxdkbn c1ogzcge cv3kvac`}>
- <Image
- src={
- "/assets/_937084ed-a798-49fe-8664-df93a2af605e_uiBk3o6UWdqolyakMvQJ9.jpeg"
+ /* This is a auto generated file for building the project */
+
+
+ import { Fragment, useState } from "react";
+ import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
+ import { Body as Body, Link as Link, Link as Link_1 } from "@webstudio-is/sdk-components-react-router";
+import { Heading as Heading, Box as Box, Paragraph as Paragraph, Image as Image, Text as Text } from "@webstudio-is/sdk-components-react/components";
+
+
+ export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";
+
+ export const projectVersion = 634;
+
+ export const projectDomain = "webstudio-fixture-project-a-0su3o";
+
+ export const lastPublished = "2026-01-15T16:19:55.574Z";
+
+ export const siteName = "KittyGuardedZone";
+
+ export const breakpoints = [{"id":"UoTkWyaFuTYJihS3MFYK5"},{"id":"ZMaWCtWpH-ao0e_kgIHqR","minWidth":372},{"id":"Z8WjyXWkCrr35PXgjHdpY","minWidth":472}];
+
+ export const favIconAsset: string | undefined =
+ "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png";
+
+ // Font assets on current page (can be preloaded)
+ export const pageFontAssets: string[] =
+ []
+
+ export const pageBackgroundImageAssets: string[] =
+ []
+
+
+
+ const Script = ({children, ...props}: Record<string, string | boolean>) => {
+ if (children == null) {
+ return <script {...props} />;
+ }
+
+ return <script {...props} dangerouslySetInnerHTML={{__html: children}} />;
+ };
+ const Style = ({children, ...props}: Record<string, string | boolean>) => {
+ if (children == null) {
+ return <style {...props} />;
+ }
+
+ return <style {...props} dangerouslySetInnerHTML={{__html: children}} />;
+ };
+
+
+ export const CustomCode = () => {
+ return (<><Script>{"console.log('KittyGuardedZone')"}</Script></>);
}
- className={`w-image c1czoo99`}
- />
- </Box>
- </Box>
- </Body>
- );
-};
-
-export { Page };
+
+
+ const Page = (_props: { system: any; }) => {
+return <Body
+className={`w-body cielobv`}>
+<Heading
+className={`w-heading ceva767`}>
+{"DO NOT TOUCH THIS PROJECT, IT'S USED FOR FIXTURES"}
+</Heading>
+<Box
+className={`w-box c13v7j50 cqkqnmd cv6wa71`}>
+<Box
+className={`w-box c1t3ybra c1qxdkbn c1ogzcge cv3kvac`}>
+<Heading
+className={`w-heading`}>
+{"Heading"}
+</Heading>
+<Paragraph
+className={`w-paragraph`}>
+{"a little kitten painted in black and white gouache with a thick brush"}
+</Paragraph>
+<Link_1
+href={"https://github.com/"}
+className={`w-element ch2exr5`}>
+{"Click here to adore more kittens"}
+</Link_1>
+<Text
+tag={"span"}
+className={`w-text`}>
+{" or "}
+</Text>
+<Link
+href={"/assets/small-avif-kitty_FnabJsioMWpBtXZSGf4DR.webp"}
+className={`w-link`}>
+{"go download this little kitten"}
+</Link>
+<Box
+className={`w-box`} />
+<Link
+href={"/_route_with_symbols_"}
+className={`w-link ch2exr5`}>
+{"Symbols in path"}
+</Link>
+<Link
+href={"/heading-with-id#my-heading"}
+className={`w-link ch2exr5`}>
+{"Link to instance"}
+</Link>
+</Box>
+<Box
+className={`w-box c1t3ybra c1qxdkbn c1ogzcge cv3kvac`}>
+<Image
+src={"/assets/_937084ed-a798-49fe-8664-df93a2af605e_uiBk3o6UWdqolyakMvQJ9.jpeg"}
+className={`w-image c1czoo99`} />
+</Box>
+</Box>
+</Body>
+}
+
+
+ export { Page }
+
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/index.css b/fixtures/webstudio-features/app/__generated__/index.css
index 9590a0d588..887854a06c 100644
--- a/fixtures/webstudio-features/app/__generated__/index.css
+++ b/fixtures/webstudio-features/app/__generated__/index.css
@@ -1,4 +1,6 @@
-@layer presets {
+@font-face {
+ font-family: CabinSketch; font-style: normal; font-weight: 700; font-display: swap; src: url("/assets/cabinsketch-bold_TLCbytfxf8ENHwZ6ze3Jj.ttf") format("truetype");
+}@layer presets {
:root {
display: grid;
min-height: 100%;
@@ -8,59 +10,59 @@
font-size: 16px;
line-height: 1.2;
white-space: pre-wrap;
- white-space-collapse: preserve;
+ white-space-collapse: preserve
}
a.w-element {
- box-sizing: border-box;
+ box-sizing: border-box
}
body.w-element {
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
- margin: 0;
+ margin: 0
}
body.w-body {
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
- margin: 0;
+ margin: 0
}
h1.w-heading {
- box-sizing: border-box;
+ box-sizing: border-box
}
h3.w-heading {
- box-sizing: border-box;
+ box-sizing: border-box
}
div.w-box {
- box-sizing: border-box;
+ box-sizing: border-box
}
p.w-paragraph {
- box-sizing: border-box;
+ box-sizing: border-box
}
img.w-image {
box-sizing: border-box;
max-width: 100%;
display: block;
- height: auto;
+ height: auto
}
a.w-link {
box-sizing: border-box;
- display: inline-block;
+ display: inline-block
}
div.w-text {
box-sizing: border-box;
- min-height: 1em;
+ min-height: 1em
}
div.w-accordion {
- box-sizing: border-box;
+ box-sizing: border-box
}
div.w-item {
- box-sizing: border-box;
+ box-sizing: border-box
}
h3.w-item-header {
box-sizing: border-box;
margin-top: 0px;
- margin-bottom: 0px;
+ margin-bottom: 0px
}
button.w-item-trigger {
font-family: inherit;
@@ -72,22 +74,22 @@
background-image: none;
border: 0px solid rgb(226 232 240 / 1);
margin: 0;
- padding: 0px;
+ padding: 0px
}
div.w-html-embed {
display: contents;
white-space: normal;
- white-space-collapse: collapse;
+ white-space-collapse: collapse
}
div.w-item-content {
- box-sizing: border-box;
+ box-sizing: border-box
}
form.w-webhook-form {
- box-sizing: border-box;
+ box-sizing: border-box
}
label.w-input-label {
box-sizing: border-box;
- display: block;
+ display: block
}
input.w-text-input {
font-family: inherit;
@@ -99,7 +101,7 @@
border-bottom-style: solid;
border-left-style: solid;
display: block;
- margin: 0;
+ margin: 0
}
button.w-button {
font-family: inherit;
@@ -111,181 +113,181 @@
border-bottom-style: solid;
border-left-style: solid;
text-transform: none;
- margin: 0;
+ margin: 0
}
div.w-text-animation {
- box-sizing: border-box;
+ box-sizing: border-box
}
}
@media all {
.ceva767 {
- font-size: 4em;
+ font-size: 4em
}
.c13v7j50 {
- display: flex;
+ display: flex
}
.cqkqnmd {
- justify-content: center;
+ justify-content: center
}
.cv6wa71 {
- align-items: start;
+ align-items: start
}
.c1t3ybra {
- min-width: 0px;
+ min-width: 0px
}
.c1qxdkbn {
- flex-grow: 1;
+ flex-grow: 1
}
.c1ogzcge {
- flex-shrink: 0;
+ flex-shrink: 0
}
.cv3kvac {
- flex-basis: 0px;
+ flex-basis: 0px
}
.c1czoo99 {
- aspect-ratio: 1;
+ aspect-ratio: 1
}
.cielobv {
- padding: 16px;
+ padding: 16px
}
.c6gjj8k {
- border-bottom: 1px solid rgb(226 232 240 / 1);
+ border-bottom: 1px solid rgb(226 232 240 / 1)
}
.chhejm9 {
- flex-shrink: 1;
+ flex-shrink: 1
}
.c13bviim {
- flex-basis: 0%;
+ flex-basis: 0%
}
.cpjvam0 {
- align-items: center;
+ align-items: center
}
.c1tw5o2 {
- justify-content: space-between;
+ justify-content: space-between
}
.cqw88jp {
- padding-top: 1rem;
+ padding-top: 1rem
}
.c44srea {
- padding-bottom: 1rem;
+ padding-bottom: 1rem
}
.c14kxsax {
- font-weight: 500;
+ font-weight: 500
}
.cg783j6 {
- --accordion-trigger-icon-transform: 0deg;
+ --accordion-trigger-icon-transform: 0deg
}
.c1ad236a:hover {
- text-decoration-line: underline;
+ text-decoration-line: underline
}
- .c1s4llbc[data-state="open"] {
- --accordion-trigger-icon-transform: 180deg;
+ .c1s4llbc[data-state=open] {
+ --accordion-trigger-icon-transform: 180deg
}
.c14hansb {
- rotate: var(--accordion-trigger-icon-transform);
+ rotate: var(--accordion-trigger-icon-transform)
}
.c6d2sb5 {
- height: 1rem;
+ height: 1rem
}
.cwwiftc {
- width: 1rem;
+ width: 1rem
}
.c16vb2zi {
- flex-grow: 0;
+ flex-grow: 0
}
.c1hl6g8z {
- transition-property: all;
+ transition-property: all
}
.c1xm49r0 {
- transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
+ transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1)
}
.c1vri55v {
- transition-duration: 200ms;
+ transition-duration: 200ms
}
.c1j0j9ep {
- font-size: 0.875rem;
+ font-size: 0.875rem
}
.c1gl2i2 {
- line-height: 1.25rem;
+ line-height: 1.25rem
}
.c1xcxvc0 {
- overflow-x: hidden;
+ overflow-x: hidden
}
.c12ct49k {
- overflow-y: hidden;
+ overflow-y: hidden
}
.ch2exr5 {
- display: block;
+ display: block
}
.cm16yxw {
- width: 300px;
+ width: 300px
}
.ctm310 {
- margin-top: 12px;
+ margin-top: 12px
}
.c1jumvji {
- margin-top: 1em;
+ margin-top: 1em
}
.cvdtpev {
- margin-bottom: 0em;
+ margin-bottom: 0em
}
.cc5h0no {
- font-size: 1em;
+ font-size: 1em
}
.c620822 {
- background-color: rgb(251 247 3 / 1);
+ background-color: rgb(251 247 3 / 1)
}
.ch21dzk {
- background-color: rgb(89 250 2 / 1);
+ background-color: rgb(89 250 2 / 1)
}
.c44hi06 {
- background-color: rgb(2 250 168 / 1);
+ background-color: rgb(2 250 168 / 1)
}
.cno1tjk {
- background-color: rgb(2 139 250 / 1);
+ background-color: rgb(2 139 250 / 1)
}
.c1m04i8w {
- height: 100dvh;
+ height: 100dvh
}
.cjib6ds {
- text-align: center;
+ text-align: center
}
}
@media all and (min-width: 472px) {
.c1jgcte3 {
- max-width: 900px;
+ max-width: 900px
}
.cncutr5 {
- width: 100%;
+ width: 100%
}
.c1ywt30e {
- min-width: 0px;
+ min-width: 0px
}
.cqvurle {
- justify-self: center;
+ justify-self: center
}
.c1y8ynw5 {
- display: grid;
+ display: grid
}
.c2gdfrb {
- grid-auto-flow: column;
+ grid-auto-flow: column
}
.c1yk3skc {
- grid-auto-columns: 1fr;
+ grid-auto-columns: 1fr
}
.c16asro7 {
- align-items: start;
+ align-items: start
}
.c1pt69cw {
- align-content: start;
+ align-content: start
}
.cq3mp4w {
- height: 40dvh;
+ height: 40dvh
}
.c1pdroxx {
- margin-top: 0em;
+ margin-top: 0em
}
.cudat22 {
- margin-bottom: 0em;
+ margin-bottom: 0em
}
-}
+}
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx b/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx
index a23fe4a9fa..14e31beba9 100644
--- a/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/webstudio-features/app/routes/[animations]._index.tsx b/fixtures/webstudio-features/app/routes/[animations]._index.tsx
index ac5591b6e9..c148140643 100644
--- a/fixtures/webstudio-features/app/routes/[animations]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[animations]._index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/webstudio-features/app/routes/[assets1]._index.tsx b/fixtures/webstudio-features/app/routes/[assets1]._index.tsx
index 357aadb289..8d4dc03b5c 100644
--- a/fixtures/webstudio-features/app/routes/[assets1]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[assets1]._index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/webstudio-features/app/routes/[class-names]._index.tsx b/fixtures/webstudio-features/app/routes/[class-names]._index.tsx
index b56fc4e83f..45945d1444 100644
--- a/fixtures/webstudio-features/app/routes/[class-names]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[class-names]._index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/webstudio-features/app/routes/[content-block]._index.tsx b/fixtures/webstudio-features/app/routes/[content-block]._index.tsx
index 9888b1b046..26f1edfbd9 100644
--- a/fixtures/webstudio-features/app/routes/[content-block]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[content-block]._index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/webstudio-features/app/routes/[duration]._index.tsx b/fixtures/webstudio-features/app/routes/[duration]._index.tsx
index be87b8ace5..5960aa5eea 100644
--- a/fixtures/webstudio-features/app/routes/[duration]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[duration]._index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/webstudio-features/app/routes/[expressions]._index.tsx b/fixtures/webstudio-features/app/routes/[expressions]._index.tsx
index e32498f9d7..0719819103 100644
--- a/fixtures/webstudio-features/app/routes/[expressions]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[expressions]._index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/webstudio-features/app/routes/[form]._index.tsx b/fixtures/webstudio-features/app/routes/[form]._index.tsx
index 16684fdc4f..af34978760 100644
--- a/fixtures/webstudio-features/app/routes/[form]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[form]._index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx b/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx
index f2c9620fff..353d2435ff 100644
--- a/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx b/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx
index cc76334f28..7babde7a97 100644
--- a/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx b/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx
index e747d8b617..6c3f7cb0be 100644
--- a/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/webstudio-features/app/routes/[radix]._index.tsx b/fixtures/webstudio-features/app/routes/[radix]._index.tsx
index f4070bb89e..0204454424 100644
--- a/fixtures/webstudio-features/app/routes/[radix]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[radix]._index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/webstudio-features/app/routes/[resources]._index.tsx b/fixtures/webstudio-features/app/routes/[resources]._index.tsx
index 31d4962a81..dd03504701 100644
--- a/fixtures/webstudio-features/app/routes/[resources]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[resources]._index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx b/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx
index 14ef8fba33..7f252952d7 100644
--- a/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx
@@ -18,8 +18,8 @@ import {
} from "../__generated__/[sitemap.xml]._index.server";
import { assetBaseUrl, imageLoader } from "../constants.mjs";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -69,12 +69,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return fetch(input, init);
};
@@ -98,9 +92,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx b/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx
index d842f7f7d8..89b4a62206 100644
--- a/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/webstudio-features/app/routes/_index.tsx b/fixtures/webstudio-features/app/routes/_index.tsx
index 867d53e46b..d8fe87ddaa 100644
--- a/fixtures/webstudio-features/app/routes/_index.tsx
+++ b/fixtures/webstudio-features/app/routes/_index.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "../constants.mjs";
import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
-import { assets } from "../__generated__/$resources.assets";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
+import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/fixtures/webstudio-features/public/assets/cabinsketch-bold_TLCbytfxf8ENHwZ6ze3Jj.ttf b/fixtures/webstudio-features/public/assets/cabinsketch-bold_TLCbytfxf8ENHwZ6ze3Jj.ttf
new file mode 100644
index 0000000000..9b988a4534
Binary files /dev/null and b/fixtures/webstudio-features/public/assets/cabinsketch-bold_TLCbytfxf8ENHwZ6ze3Jj.ttf differ
diff --git a/packages/asset-uploader/package.json b/packages/asset-uploader/package.json
index cc67a9d7bc..41dde00db9 100644
--- a/packages/asset-uploader/package.json
+++ b/packages/asset-uploader/package.json
@@ -12,6 +12,7 @@
"dependencies": {
"@aws-crypto/sha256-js": "^5.2.0",
"@smithy/signature-v4": "^5.1.3",
+ "@webstudio-is/content-engine": "workspace:*",
"@webstudio-is/fonts": "workspace:*",
"@webstudio-is/postgrest": "workspace:*",
"@webstudio-is/sdk": "workspace:*",
@@ -33,8 +34,8 @@
".": {
"webstudio": "./src/index.ts"
},
- "./index.server": {
- "webstudio": "./src/index.server.ts"
+ "./server": {
+ "webstudio": "./src/server.ts"
},
"./patch-assets-core.server": {
"webstudio": "./src/asset-patch-core.ts",
diff --git a/packages/asset-uploader/src/asset-mutation-types.ts b/packages/asset-uploader/src/asset-mutation-types.ts
new file mode 100644
index 0000000000..a2acff783e
--- /dev/null
+++ b/packages/asset-uploader/src/asset-mutation-types.ts
@@ -0,0 +1,11 @@
+/** Storage-layer commands after transport validation has completed. */
+export type AssetMetadataUpdate = {
+ filename?: string | null;
+ description?: string | null;
+ folderId?: string | null;
+};
+
+export type AssetFolderUpdate = {
+ name?: string;
+ parentId?: string | null;
+};
diff --git a/packages/asset-uploader/src/asset-patch-core.ts b/packages/asset-uploader/src/asset-patch-core.ts
index 6d892ea4f9..f5d64a91cc 100644
--- a/packages/asset-uploader/src/asset-patch-core.ts
+++ b/packages/asset-uploader/src/asset-patch-core.ts
@@ -8,6 +8,8 @@ import {
type Patch,
} from "./patch-utils";
import { swapAssetFileWithClient } from "./revision";
+import type { AssetMetadataUpdate } from "./asset-mutation-types";
+import { AssetRepositoryNotFoundError } from "./asset-repository-errors";
const serializeAssetMeta = (meta: Asset["meta"]) => JSON.stringify(meta);
@@ -23,9 +25,10 @@ export const createAssetRows = (assets: Iterable<Asset>, projectId: string) =>
export const loadAssetsByProjectWithClient = async (
projectId: string,
- client: Client
+ client: Client,
+ assetIds?: string[]
): Promise<Asset[]> => {
- const assets = await client
+ let query = client
.from("Asset")
// use inner to filter out assets without file
// when file is not uploaded
@@ -40,7 +43,14 @@ export const loadAssetsByProjectWithClient = async (
`
)
.eq("projectId", projectId)
- .eq("file.status", "UPLOADED")
+ .eq("file.status", "UPLOADED");
+ if (assetIds !== undefined) {
+ if (assetIds.length === 0) {
+ return [];
+ }
+ query = query.in("id", assetIds);
+ }
+ const assets = await query
// always sort by primary key to get stable list
// required to not break fixtures
.order("id");
@@ -94,7 +104,7 @@ export const deleteAssetsWithClient = async (
assertPostgrestSuccess(assets);
if ((assets.data ?? []).length === 0) {
- throw new Error("Assets not found");
+ throw new AssetRepositoryNotFoundError("Assets not found");
}
const previewUpdate = await client
@@ -130,11 +140,79 @@ export const deleteAssetsWithClient = async (
}
};
+export const updateAssetMetadataWithClient = async (
+ {
+ projectId,
+ assetId,
+ values,
+ }: {
+ projectId: string;
+ assetId: Asset["id"];
+ values: AssetMetadataUpdate;
+ },
+ client: Client
+): Promise<Asset> => {
+ await persistAssetMetadataWithClient({ projectId, assetId, values }, client);
+
+ const [asset] = await loadAssetsByProjectWithClient(projectId, client, [
+ assetId,
+ ]);
+ if (asset === undefined) {
+ throw new AssetRepositoryNotFoundError("Asset not found");
+ }
+ return asset;
+};
+
+const persistAssetMetadataWithClient = async (
+ {
+ projectId,
+ assetId,
+ values,
+ }: {
+ projectId: string;
+ assetId: Asset["id"];
+ values: AssetMetadataUpdate;
+ },
+ client: Client
+) => {
+ const update: {
+ filename?: string | null;
+ description?: string | null;
+ folderId?: string | null;
+ } = {};
+ if (Object.hasOwn(values, "filename")) {
+ update.filename = values.filename ?? null;
+ }
+ if (Object.hasOwn(values, "description")) {
+ update.description = values.description ?? null;
+ }
+ if (Object.hasOwn(values, "folderId")) {
+ update.folderId = values.folderId ?? null;
+ }
+ const result = await client
+ .from("Asset")
+ .update(update)
+ .eq("id", assetId)
+ .eq("projectId", projectId)
+ .select("id")
+ .maybeSingle();
+ assertPostgrestSuccess(result);
+ if (result.data?.id !== assetId) {
+ throw new AssetRepositoryNotFoundError("Asset not found");
+ }
+};
+
/**
* Persists asset additions, deletions, metadata updates, and file revisions.
*/
export const patchAssetsWithClient = async (
- { projectId, client }: { projectId: string; client: Client },
+ {
+ projectId,
+ client,
+ }: {
+ projectId: string;
+ client: Client;
+ },
patches: Array<Patch>
): Promise<void> => {
const assetsList = await loadAssetsByProjectWithClient(projectId, client);
@@ -145,6 +223,11 @@ export const patchAssetsWithClient = async (
const patchedAssets = applyValidatedMapPatches(assetsMap, patches, (value) =>
assets.parse(value)
);
+ for (const asset of patchedAssets.values()) {
+ if (asset.projectId !== projectId) {
+ throw new Error(`Asset ${asset.id} belongs to another project`);
+ }
+ }
const {
added,
updated,
@@ -185,25 +268,14 @@ export const patchAssetsWithClient = async (
previous.folderId !== asset.folderId
) {
const { filename, description, folderId } = asset;
- const updatedAsset = await client
- .from("Asset")
- .update({
- filename: filename ?? null,
- description: description ?? null,
- folderId: folderId ?? null,
- })
- .eq("id", asset.id)
- .eq("projectId", asset.projectId)
- .select("filename, description, folderId")
- .single();
- assertPostgrestSuccess(updatedAsset);
- if (
- updatedAsset.data?.filename !== (filename ?? null) ||
- updatedAsset.data?.description !== (description ?? null) ||
- (updatedAsset.data?.folderId ?? null) !== (folderId ?? null)
- ) {
- throw new Error(`Asset update was not persisted for ${asset.id}`);
- }
+ await persistAssetMetadataWithClient(
+ {
+ projectId,
+ assetId: asset.id,
+ values: { filename, description, folderId },
+ },
+ client
+ );
}
if (serializeAssetMeta(previous.meta) !== serializeAssetMeta(asset.meta)) {
const meta = serializeAssetMeta(asset.meta);
@@ -221,7 +293,6 @@ export const patchAssetsWithClient = async (
}
}
}
-
const addedAssets: Asset[] = added;
if (addedAssets.length !== 0) {
const files = await client
@@ -234,6 +305,14 @@ export const patchAssetsWithClient = async (
assertPostgrestSuccess(files);
const fileNames = new Set(files.data?.map((file) => file.name));
+ const missingFile = addedAssets.find(
+ (asset) => fileNames.has(asset.name) === false
+ );
+ if (missingFile !== undefined) {
+ throw new AssetRepositoryNotFoundError(
+ `Asset file not found for ${missingFile.id}`
+ );
+ }
// restore file when undo is triggered
const restoredFiles = await client
@@ -242,14 +321,9 @@ export const patchAssetsWithClient = async (
.in("name", Array.from(fileNames));
assertPostgrestSuccess(restoredFiles);
- const insertedAssets = await client.from("Asset").insert(
- createAssetRows(
- // Make sure the corresponding file exists before creating an asset
- // that references it.
- addedAssets.filter((asset) => fileNames.has(asset.name)),
- projectId
- )
- );
+ const insertedAssets = await client
+ .from("Asset")
+ .insert(createAssetRows(addedAssets, projectId));
assertPostgrestSuccess(insertedAssets);
}
};
diff --git a/packages/asset-uploader/src/asset-repository-errors.ts b/packages/asset-uploader/src/asset-repository-errors.ts
new file mode 100644
index 0000000000..9543c32df8
--- /dev/null
+++ b/packages/asset-uploader/src/asset-repository-errors.ts
@@ -0,0 +1,3 @@
+export class AssetRepositoryNotFoundError extends Error {}
+
+export class AssetRepositoryConflictError extends Error {}
diff --git a/packages/asset-uploader/src/asset-repository.test.ts b/packages/asset-uploader/src/asset-repository.test.ts
new file mode 100644
index 0000000000..eea29f0cbf
--- /dev/null
+++ b/packages/asset-uploader/src/asset-repository.test.ts
@@ -0,0 +1,1356 @@
+import { describe, expect, test, vi } from "vitest";
+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+import type { AssetObjectStore } from "./client";
+import { createUploadTicket, uploadFile } from "./upload";
+import {
+ loadCanonicalAssetBaseEntries,
+ synchronizeCanonicalAssets,
+} from "./canonical-metadata-backfill";
+import { loadCanonicalAssetFileEntries } from "./canonical-metadata-persistence";
+import {
+ createContentCompilationPlan,
+ createLiteralContentCompilationQuery,
+ assetQuery,
+ type AssetQueryInput,
+ type AssetFileDocument,
+} from "@webstudio-is/content-engine";
+import {
+ createAssetIndex,
+ type CanonicalAssetFileEntry,
+} from "@webstudio-is/content-engine/compiler";
+import { createPublishedAssetResourceFetch } from "@webstudio-is/content-engine/runtime";
+import {
+ AssetIndexPreparationError,
+ PostgresAssetRepository,
+} from "./asset-repository";
+import { createContentCompilationCache } from "./content-compilation-cache";
+import {
+ deleteAssetsWithClient,
+ loadAssetsByProjectWithClient,
+ updateAssetMetadataWithClient,
+} from "./asset-patch-core";
+import { updateAssetContent } from "./revision";
+import {
+ deleteAssetFoldersWithClient,
+ loadAssetFoldersByProjectWithClient,
+ upsertAssetFolderWithClient,
+} from "./folder-persistence";
+
+const context = {
+ postgrest: { client: {} },
+} as unknown as AppContext;
+const assetClient: AssetObjectStore = {
+ readFile: vi.fn(),
+ uploadFile: vi.fn(),
+};
+
+const createCompilationPlan = (query: AssetQueryInput) => {
+ const plan = createContentCompilationPlan([
+ createLiteralContentCompilationQuery({
+ id: "resource",
+ query: assetQuery.parse(query),
+ }),
+ ]);
+ if (plan === undefined) {
+ throw new Error("Expected a content compilation plan");
+ }
+ return plan;
+};
+
+const createDependencies = () => ({
+ hasProjectPermit: vi.fn().mockResolvedValue(true),
+ createUploadTicket: vi.fn<typeof createUploadTicket>(),
+ uploadFile: vi.fn<typeof uploadFile>(),
+ updateAssetContent: vi.fn<typeof updateAssetContent>(),
+ deleteAssetsWithClient: vi.fn<typeof deleteAssetsWithClient>(),
+ synchronizeCanonicalAssets: vi
+ .fn<typeof synchronizeCanonicalAssets>()
+ .mockResolvedValue({
+ scanned: 0,
+ indexed: 0,
+ metadataUpdated: 0,
+ unchanged: 0,
+ removed: 0,
+ skipped: 0,
+ inconsistent: 0,
+ issues: [],
+ }),
+ loadCanonicalAssetBaseEntries: vi
+ .fn<typeof loadCanonicalAssetBaseEntries>()
+ .mockResolvedValue([]),
+ loadCanonicalAssetFileEntries: vi.fn<typeof loadCanonicalAssetFileEntries>(),
+ createAssetIndex: vi.fn<typeof createAssetIndex>(),
+ updateAssetMetadataWithClient: vi.fn<typeof updateAssetMetadataWithClient>(),
+ loadAssetsByProjectWithClient: vi
+ .fn<typeof loadAssetsByProjectWithClient>()
+ .mockResolvedValue([]),
+ loadAssetFoldersByProjectWithClient:
+ vi.fn<typeof loadAssetFoldersByProjectWithClient>(),
+ upsertAssetFolderWithClient: vi.fn<typeof upsertAssetFolderWithClient>(),
+ deleteAssetFoldersWithClient: vi.fn<typeof deleteAssetFoldersWithClient>(),
+ createId: vi.fn(() => "folder-1"),
+ now: vi.fn(() => new Date("2026-07-25T00:00:00.000Z")),
+});
+
+describe("PostgresAssetRepository", () => {
+ test("lists, gets, and range-reads assets through the authorized object store", async () => {
+ const dependencies = createDependencies();
+ const asset = {
+ id: "asset-1",
+ projectId: "project-1",
+ name: "post.md",
+ type: "file" as const,
+ format: "md",
+ size: 10,
+ description: null,
+ createdAt: "2026-07-25T00:00:00.000Z",
+ meta: {},
+ };
+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([asset]);
+ const readFile = vi.fn(async () => ({
+ data: new Blob(["post"]).stream() as unknown as AsyncIterable<Uint8Array>,
+ contentLength: 4,
+ }));
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: { ...assetClient, readFile },
+ dependencies,
+ });
+
+ await expect(repository.list()).resolves.toEqual([asset]);
+ await expect(repository.get("asset-1")).resolves.toEqual(asset);
+ await expect(
+ repository.readContent({
+ assetId: "asset-1",
+ range: { offset: 2, length: 4 },
+ })
+ ).resolves.toMatchObject({ asset, contentLength: 4 });
+ expect(dependencies.loadAssetsByProjectWithClient).toHaveBeenNthCalledWith(
+ 1,
+ "project-1",
+ context.postgrest.client
+ );
+ expect(dependencies.loadAssetsByProjectWithClient).toHaveBeenNthCalledWith(
+ 2,
+ "project-1",
+ context.postgrest.client,
+ ["asset-1"]
+ );
+ expect(dependencies.loadAssetsByProjectWithClient).toHaveBeenNthCalledWith(
+ 3,
+ "project-1",
+ context.postgrest.client,
+ ["asset-1"]
+ );
+ expect(dependencies.hasProjectPermit).toHaveBeenCalledWith(
+ { projectId: "project-1", permit: "view" },
+ context
+ );
+ expect(readFile).toHaveBeenCalledWith("post.md", {
+ offset: 2,
+ length: 4,
+ });
+ });
+
+ test("creates, moves, and deletes empty folders through the repository", async () => {
+ const dependencies = createDependencies();
+ const root = {
+ id: "root",
+ projectId: "project-1",
+ name: "Root",
+ createdAt: "2026-07-24T00:00:00.000Z",
+ };
+ const created = {
+ id: "folder-1",
+ projectId: "project-1",
+ name: "Blog",
+ parentId: "root",
+ createdAt: "2026-07-25T00:00:00.000Z",
+ };
+ dependencies.upsertAssetFolderWithClient
+ .mockResolvedValueOnce(created)
+ .mockResolvedValueOnce({ ...created, name: "Articles" });
+ dependencies.loadAssetFoldersByProjectWithClient
+ .mockResolvedValueOnce([root, created])
+ .mockResolvedValueOnce([root, { ...created, name: "Articles" }]);
+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([]);
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: assetClient,
+ dependencies,
+ });
+
+ await expect(
+ repository.createFolder({ name: "Blog", parentId: "root" })
+ ).resolves.toEqual(created);
+ await expect(
+ repository.updateFolder("folder-1", { name: "Articles" })
+ ).resolves.toMatchObject({ name: "Articles" });
+ await expect(repository.deleteFolder("folder-1")).resolves.toBeUndefined();
+ expect(dependencies.deleteAssetFoldersWithClient).toHaveBeenCalledWith(
+ { projectId: "project-1", ids: ["folder-1"] },
+ context.postgrest.client
+ );
+ });
+
+ test("lists and gets folders with view authorization", async () => {
+ const dependencies = createDependencies();
+ const folder = {
+ id: "blog",
+ projectId: "project-1",
+ name: "Blog",
+ createdAt: "2026-07-25T00:00:00.000Z",
+ };
+ dependencies.loadAssetFoldersByProjectWithClient.mockImplementation(
+ async (_projectId, _client, folderIds) =>
+ folderIds?.includes(folder.id) === false ? [] : [folder]
+ );
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: assetClient,
+ dependencies,
+ });
+
+ await expect(repository.listFolders()).resolves.toEqual([folder]);
+ await expect(repository.getFolder("blog")).resolves.toEqual(folder);
+ await expect(repository.getFolder("missing")).rejects.toThrow(
+ "Asset folder not found"
+ );
+ expect(dependencies.hasProjectPermit).toHaveBeenCalledWith(
+ { projectId: "project-1", permit: "view" },
+ context
+ );
+ });
+
+ test("rejects deleting a non-empty folder", async () => {
+ const dependencies = createDependencies();
+ dependencies.loadAssetFoldersByProjectWithClient.mockResolvedValue([
+ {
+ id: "folder-1",
+ projectId: "project-1",
+ name: "Blog",
+ createdAt: "2026-07-25T00:00:00.000Z",
+ },
+ ]);
+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([
+ {
+ id: "asset-1",
+ projectId: "project-1",
+ name: "post.md",
+ folderId: "folder-1",
+ type: "file",
+ format: "md",
+ size: 10,
+ description: null,
+ createdAt: "2026-07-25T00:00:00.000Z",
+ meta: {},
+ },
+ ]);
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: assetClient,
+ dependencies,
+ });
+
+ await expect(repository.deleteFolder("folder-1")).rejects.toThrow(
+ "must be empty"
+ );
+ expect(dependencies.deleteAssetFoldersWithClient).not.toHaveBeenCalled();
+ });
+
+ test("does not parse a complete asset restored by upload deduplication", async () => {
+ const dependencies = createDependencies();
+ dependencies.createUploadTicket.mockResolvedValue({
+ assetId: "asset-1",
+ name: "post.md",
+ deduplicated: true,
+ asset: {
+ id: "asset-1",
+ projectId: "project-1",
+ name: "post.md",
+ type: "file",
+ format: "raw",
+ size: 12,
+ createdAt: "2026-07-24T00:00:00.000Z",
+ meta: {},
+ },
+ });
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: assetClient,
+ dependencies,
+ });
+
+ const ticket = await repository.createUploadTicket({
+ type: "file",
+ filename: "post.md",
+ contentHash: "hash",
+ });
+
+ expect(ticket.deduplicated).toBe(true);
+ expect(dependencies.createUploadTicket).toHaveBeenCalledWith(
+ {
+ projectId: "project-1",
+ type: "file",
+ filename: "post.md",
+ contentHash: "hash",
+ },
+ context,
+ undefined
+ );
+ });
+
+ test("does not index an incomplete upload reservation", async () => {
+ const dependencies = createDependencies();
+ dependencies.createUploadTicket.mockResolvedValue({
+ assetId: "asset-1",
+ name: "post.md",
+ deduplicated: false,
+ });
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: assetClient,
+ dependencies,
+ });
+
+ await repository.createUploadTicket({
+ type: "file",
+ filename: "post.md",
+ });
+ });
+
+ test("authorizes upload completion independently of its reserved name", async () => {
+ const dependencies = createDependencies();
+ dependencies.hasProjectPermit.mockResolvedValue(false);
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: assetClient,
+ dependencies,
+ });
+
+ await expect(
+ repository.completeUpload({
+ name: "reserved.md",
+ data: new Blob(["post"]).stream(),
+ assetInfoFallback: undefined,
+ })
+ ).rejects.toThrow("access to edit");
+ expect(dependencies.uploadFile).not.toHaveBeenCalled();
+ });
+
+ test("does not read or parse stored content during ordinary mutations", async () => {
+ const dependencies = createDependencies();
+ const asset = {
+ id: "asset-1",
+ projectId: "project-1",
+ name: "post.md",
+ type: "file" as const,
+ format: "md",
+ size: 10,
+ description: null,
+ createdAt: "2026-07-25T00:00:00.000Z",
+ meta: {},
+ };
+ dependencies.createUploadTicket.mockResolvedValue({
+ assetId: asset.id,
+ name: asset.name,
+ deduplicated: true,
+ asset,
+ });
+ dependencies.uploadFile.mockResolvedValue(asset);
+ dependencies.updateAssetContent.mockResolvedValue(asset);
+ dependencies.updateAssetMetadataWithClient.mockResolvedValue(asset);
+ const readFile = vi.fn<AssetObjectStore["readFile"]>();
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: { readFile, uploadFile: vi.fn() },
+ dependencies,
+ });
+
+ await repository.createUploadTicket({ type: "file", filename: "post.md" });
+ await repository.completeUpload({
+ name: "post.md",
+ data: new Blob(["post"]).stream(),
+ assetInfoFallback: undefined,
+ });
+ await repository.updateContent({
+ assetId: asset.id,
+ expectedName: asset.name,
+ data: new Blob(["updated"]).stream(),
+ });
+ await repository.updateMetadata(asset.id, { filename: "Post" });
+ await repository.delete([asset.id]);
+
+ expect(readFile).not.toHaveBeenCalled();
+ expect(dependencies.synchronizeCanonicalAssets).not.toHaveBeenCalled();
+ });
+
+ test("authorizes public read and trusted maintenance operations", async () => {
+ const dependencies = createDependencies();
+ dependencies.hasProjectPermit.mockResolvedValue(false);
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: assetClient,
+ dependencies,
+ });
+
+ await expect(
+ repository.query({
+ query: {
+ where: { all: [] },
+ output: { mode: "base", includeMetadata: true },
+ },
+ })
+ ).rejects.toThrow("access to view");
+ await expect(repository.synchronize()).rejects.toThrow("access to edit");
+ await expect(repository.prepareIndex()).rejects.toThrow("access to view");
+ expect(dependencies.loadAssetsByProjectWithClient).not.toHaveBeenCalled();
+ expect(dependencies.loadCanonicalAssetFileEntries).not.toHaveBeenCalled();
+ expect(dependencies.synchronizeCanonicalAssets).not.toHaveBeenCalled();
+ });
+
+ test("allows the publisher service to prepare an index without granting asset edits", async () => {
+ const dependencies = createDependencies();
+ dependencies.hasProjectPermit.mockResolvedValue(false);
+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue([]);
+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);
+ const serviceContext = {
+ ...context,
+ authorization: { type: "service", isServiceCall: true },
+ } as AppContext;
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context: serviceContext,
+ assetStore: assetClient,
+ dependencies,
+ });
+
+ await expect(repository.prepareIndex()).resolves.toMatchObject({
+ documents: [],
+ });
+ await expect(repository.synchronize()).rejects.toThrow("access to edit");
+ expect(dependencies.hasProjectPermit).toHaveBeenCalledOnce();
+ expect(dependencies.hasProjectPermit).toHaveBeenCalledWith(
+ { projectId: "project-1", permit: "edit" },
+ serviceContext
+ );
+ });
+
+ test("repairs canonical metadata before creating an index", async () => {
+ const dependencies = createDependencies();
+ const entries = [
+ {
+ projectId: "project-1",
+ assetId: "asset-1",
+ revision: `sha256:${"a".repeat(64)}`,
+ document: {
+ _id: "asset-1",
+ _type: "asset.file" as const,
+ name: "post.md",
+ path: "post.md",
+ key: "post.md",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 10,
+ revision: `sha256:${"a".repeat(64)}`,
+ contentRef: "assets/post.md",
+ properties: {},
+ },
+ },
+ ];
+ const index = { integrity: { checksum: `sha256:${"b".repeat(64)}` } };
+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue(entries);
+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue(entries);
+ dependencies.createAssetIndex.mockResolvedValue(index as never);
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: assetClient,
+ dependencies,
+ });
+
+ await expect(repository.prepareIndex()).resolves.toBe(index);
+ expect(dependencies.hasProjectPermit).toHaveBeenCalledWith(
+ { projectId: "project-1", permit: "view" },
+ context
+ );
+ expect(dependencies.synchronizeCanonicalAssets).toHaveBeenCalledWith({
+ client: context.postgrest.client,
+ assetClient,
+ projectId: "project-1",
+ });
+ expect(dependencies.loadCanonicalAssetFileEntries).toHaveBeenCalledWith({
+ client: context.postgrest.client,
+ projectId: "project-1",
+ });
+ expect(dependencies.createAssetIndex).toHaveBeenCalledWith({
+ projectId: "project-1",
+ entries,
+ assetReferences: {},
+ maxBytes: 500 * 1024,
+ });
+ });
+
+ test.each([
+ {
+ name: "replacement",
+ update: (entry: CanonicalAssetFileEntry) => ({
+ ...entry,
+ revision: "revision-replaced",
+ document: {
+ ...entry.document,
+ revision: "revision-replaced",
+ contentRef: "assets/post-replaced.md",
+ },
+ }),
+ expectedPath: "post.md",
+ },
+ {
+ name: "deletion",
+ update: () => undefined,
+ expectedPath: undefined,
+ },
+ {
+ name: "folder movement",
+ update: (entry: CanonicalAssetFileEntry) => ({
+ ...entry,
+ document: { ...entry.document, path: "archive/post.md" },
+ }),
+ expectedPath: "archive/post.md",
+ },
+ ])(
+ "retries a snapshot after asset $name",
+ async ({ update, expectedPath }) => {
+ const dependencies = createDependencies();
+ const initial = {
+ projectId: "project-1",
+ assetId: "asset-1",
+ revision: "revision-1",
+ document: {
+ _id: "asset-1",
+ _type: "asset.file" as const,
+ name: "post.md",
+ path: "post.md",
+ key: "post",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 10,
+ revision: "revision-1",
+ contentRef: "assets/post.md",
+ properties: {},
+ },
+ };
+ const updated = update(initial);
+ const current = updated === undefined ? [] : [updated];
+ dependencies.loadCanonicalAssetBaseEntries
+ .mockResolvedValueOnce([initial])
+ .mockResolvedValueOnce(current)
+ .mockResolvedValueOnce(current)
+ .mockResolvedValueOnce(current);
+ dependencies.loadCanonicalAssetFileEntries
+ .mockResolvedValueOnce([initial])
+ .mockResolvedValueOnce(current);
+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: assetClient,
+ dependencies,
+ });
+
+ const index = await repository.prepareIndex();
+
+ expect(index.documents[0]?.path).toBe(expectedPath);
+ expect(dependencies.loadCanonicalAssetBaseEntries).toHaveBeenCalledTimes(
+ 4
+ );
+ expect(dependencies.loadCanonicalAssetFileEntries).toHaveBeenCalledTimes(
+ 2
+ );
+ expect(dependencies.createAssetIndex).toHaveBeenCalledOnce();
+ }
+ );
+
+ test("creates a base-only index without synchronizing or reading content", async () => {
+ const dependencies = createDependencies();
+ const entries = [
+ {
+ projectId: "project-1",
+ assetId: "asset-1",
+ revision: "revision-1",
+ document: {
+ _id: "asset-1",
+ _type: "asset.file" as const,
+ name: "post.md",
+ path: "post.md",
+ key: "post",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 10,
+ revision: "revision-1",
+ contentRef: "post.md",
+ properties: {},
+ },
+ },
+ ];
+ const index = { integrity: { checksum: `sha256:${"b".repeat(64)}` } };
+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue(entries);
+ dependencies.createAssetIndex.mockResolvedValue(index as never);
+ const readFile = vi.fn();
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: { readFile, uploadFile: vi.fn() },
+ dependencies,
+ });
+
+ await expect(
+ repository.prepareIndex(
+ createCompilationPlan({
+ where: { all: [] },
+ output: { mode: "base", includeMetadata: true },
+ })
+ )
+ ).resolves.toBe(index);
+
+ expect(dependencies.synchronizeCanonicalAssets).not.toHaveBeenCalled();
+ expect(dependencies.loadCanonicalAssetFileEntries).not.toHaveBeenCalled();
+ expect(dependencies.loadCanonicalAssetBaseEntries).toHaveBeenCalledWith({
+ client: context.postgrest.client,
+ projectId: "project-1",
+ });
+ expect(readFile).not.toHaveBeenCalled();
+ });
+
+ test("discovers fields without preparing excerpts or file bodies", async () => {
+ const dependencies = createDependencies();
+ const entry = {
+ projectId: "project-1",
+ assetId: "asset-1",
+ revision: "revision-1",
+ document: {
+ _id: "asset-1",
+ _type: "asset.file" as const,
+ name: "post.md",
+ path: "post.md",
+ key: "post",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 10,
+ revision: "revision-1",
+ contentRef: "post.md",
+ properties: { title: "Post" },
+ },
+ };
+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([
+ { ...entry, document: { ...entry.document, properties: {} } },
+ ]);
+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue([entry]);
+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);
+ const readFile = vi.fn();
+ const assetStore = { readFile };
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore,
+ dependencies,
+ contentDatabaseMaxBytes: 1,
+ });
+
+ await expect(repository.readFieldCatalog()).resolves.toMatchObject({
+ fields: { "properties.title": expect.any(Object) },
+ });
+ expect(dependencies.synchronizeCanonicalAssets).toHaveBeenCalledWith({
+ client: context.postgrest.client,
+ assetClient: assetStore,
+ projectId: "project-1",
+ assetIds: ["asset-1"],
+ requirements: { structuredProperties: true, excerpt: false },
+ });
+ expect(dependencies.createAssetIndex).not.toHaveBeenCalled();
+ expect(readFile).not.toHaveBeenCalled();
+ });
+
+ test("coalesces and reuses compilation by source revision and plan", async () => {
+ const dependencies = createDependencies();
+ const entry = {
+ projectId: "project-1",
+ assetId: "asset-1",
+ revision: "revision-1",
+ document: {
+ _id: "asset-1",
+ _type: "asset.file" as const,
+ name: "post.md",
+ path: "post.md",
+ key: "post",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 10,
+ revision: "revision-1",
+ contentRef: "post.md",
+ properties: { title: "Post" },
+ },
+ };
+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([entry]);
+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue([entry]);
+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: assetClient,
+ dependencies,
+ compilationCache: createContentCompilationCache(),
+ });
+
+ const [first, second] = await Promise.all([
+ repository.prepareIndex(),
+ repository.prepareIndex(),
+ ]);
+ const third = await repository.prepareIndex();
+
+ expect(first).toBe(second);
+ expect(second).toBe(third);
+ expect(dependencies.createAssetIndex).toHaveBeenCalledOnce();
+ expect(dependencies.synchronizeCanonicalAssets).toHaveBeenCalledOnce();
+ expect(dependencies.loadCanonicalAssetFileEntries).toHaveBeenCalledOnce();
+
+ const updatedEntry = {
+ ...entry,
+ revision: "revision-2",
+ document: {
+ ...entry.document,
+ revision: "revision-2",
+ contentRef: "post-revision-2.md",
+ },
+ };
+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([
+ updatedEntry,
+ ]);
+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue([
+ updatedEntry,
+ ]);
+
+ const updated = await repository.prepareIndex();
+
+ expect(updated).not.toBe(first);
+ expect(dependencies.createAssetIndex).toHaveBeenCalledTimes(2);
+ });
+
+ test("keeps only required properties and excerpts in a prepared index", async () => {
+ const dependencies = createDependencies();
+ const entries = [
+ {
+ projectId: "project-1",
+ assetId: "asset-1",
+ revision: "revision-1",
+ document: {
+ _id: "asset-1",
+ _type: "asset.file" as const,
+ name: "post.md",
+ path: "post.md",
+ key: "post",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 10,
+ revision: "revision-1",
+ contentRef: "post.md",
+ properties: { title: "Post", draft: true },
+ excerpt: "Excerpt",
+ },
+ },
+ ];
+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue(
+ entries.map((entry) => ({
+ ...entry,
+ document: { ...entry.document, properties: {}, excerpt: undefined },
+ }))
+ );
+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue(entries);
+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);
+ const uploadFile = vi.fn<AssetObjectStore["uploadFile"]>();
+ const assetStore = { ...assetClient, uploadFile };
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore,
+ dependencies,
+ });
+
+ const index = await repository.prepareIndex(
+ createCompilationPlan({
+ where: { all: [] },
+ output: {
+ mode: "fields",
+ fields: [["properties", "title"]],
+ },
+ })
+ );
+
+ expect(index.documents[0].properties).toEqual({ title: "Post" });
+ expect(index.documents[0]).not.toHaveProperty("excerpt");
+ expect(dependencies.synchronizeCanonicalAssets).toHaveBeenCalledWith({
+ client: context.postgrest.client,
+ assetClient: assetStore,
+ projectId: "project-1",
+ assetIds: ["asset-1"],
+ requirements: { structuredProperties: true, excerpt: false },
+ });
+ expect(uploadFile).not.toHaveBeenCalled();
+ });
+
+ test("prepares only files that can be used by configured queries", async () => {
+ const dependencies = createDependencies();
+ const createEntry = ({
+ id,
+ extension,
+ properties,
+ }: {
+ id: string;
+ extension: "md" | "json";
+ properties: AssetFileDocument["properties"];
+ }) => ({
+ projectId: "project-1",
+ assetId: id,
+ revision: `revision-${id}`,
+ document: {
+ _id: id,
+ _type: "asset.file" as const,
+ name: `${id}.${extension}`,
+ path: `content/${id}.${extension}`,
+ key: id,
+ extension,
+ mimeType: extension === "md" ? "text/markdown" : "application/json",
+ size: 10,
+ revision: `revision-${id}`,
+ contentRef: `${id}.${extension}`,
+ properties,
+ },
+ });
+ const entries = [
+ createEntry({
+ id: "published",
+ extension: "md",
+ properties: { draft: false },
+ }),
+ createEntry({
+ id: "draft",
+ extension: "md",
+ properties: { draft: true },
+ }),
+ createEntry({
+ id: "data",
+ extension: "json",
+ properties: { draft: false },
+ }),
+ ];
+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue(
+ entries.map((entry) => ({
+ ...entry,
+ document: { ...entry.document, properties: {} },
+ }))
+ );
+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue(entries);
+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: assetClient,
+ dependencies,
+ });
+
+ const index = await repository.prepareIndex(
+ createCompilationPlan({
+ where: {
+ all: [
+ { field: ["extension"], operator: "eq", value: "md" },
+ {
+ field: ["properties", "draft"],
+ operator: "ne",
+ value: true,
+ },
+ ],
+ },
+ output: { mode: "base", includeMetadata: true },
+ })
+ );
+
+ expect(dependencies.synchronizeCanonicalAssets).toHaveBeenCalledWith({
+ client: context.postgrest.client,
+ assetClient,
+ projectId: "project-1",
+ assetIds: ["published", "draft"],
+ requirements: { structuredProperties: true, excerpt: false },
+ });
+ expect(dependencies.loadCanonicalAssetFileEntries).toHaveBeenCalledWith({
+ client: context.postgrest.client,
+ projectId: "project-1",
+ assetIds: ["published", "draft"],
+ });
+ expect(index.documents.map(({ _id }) => _id)).toEqual(["published"]);
+ });
+
+ test("keeps matching metadata for totals while embedding only the selected content window", async () => {
+ const dependencies = createDependencies();
+ const entries = ["alpha", "beta"].map((id) => ({
+ projectId: "project-1",
+ assetId: id,
+ revision: `revision-${id}`,
+ document: {
+ _id: id,
+ _type: "asset.file" as const,
+ name: `${id}.md`,
+ path: `blog/${id}.md`,
+ key: id,
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 4,
+ revision: `revision-${id}`,
+ contentRef: `${id}.md`,
+ properties: {},
+ },
+ }));
+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue(entries);
+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue(entries);
+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);
+ const readFile = vi.fn().mockResolvedValue({
+ data: new Blob(["Post"]).stream(),
+ contentLength: 4,
+ });
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: { readFile },
+ dependencies,
+ });
+
+ const index = await repository.prepareIndex(
+ createCompilationPlan({
+ where: { all: [] },
+ sort: [{ field: ["id"], direction: "asc" }],
+ limit: 1,
+ content: { mode: "full" },
+ })
+ );
+
+ expect(index.documents.map(({ _id }) => _id)).toEqual(["alpha", "beta"]);
+ expect(index.contents).toEqual({ "alpha.md": "Post" });
+ expect(readFile).toHaveBeenCalledOnce();
+ expect(dependencies.synchronizeCanonicalAssets).not.toHaveBeenCalled();
+ expect(dependencies.loadCanonicalAssetFileEntries).not.toHaveBeenCalled();
+ });
+
+ test("fails publication when selected text content cannot be embedded", async () => {
+ const dependencies = createDependencies();
+ const entry = {
+ projectId: "project-1",
+ assetId: "post",
+ revision: "revision-post",
+ document: {
+ _id: "post",
+ _type: "asset.file" as const,
+ name: "post.md",
+ path: "blog/post.md",
+ key: "post",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 1,
+ revision: "revision-post",
+ contentRef: "post.md",
+ properties: {},
+ },
+ };
+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([entry]);
+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue([entry]);
+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: {
+ readFile: vi.fn().mockResolvedValue({
+ data: new Blob([new Uint8Array([0xff])]).stream(),
+ contentLength: 1,
+ }),
+ },
+ dependencies,
+ });
+
+ await expect(
+ repository.prepareIndex(
+ createCompilationPlan({
+ where: { all: [] },
+ sort: [],
+ limit: 1,
+ content: { mode: "full" },
+ })
+ )
+ ).rejects.toMatchObject({
+ name: "AssetIndexPreparationError",
+ issues: [
+ expect.objectContaining({
+ assetId: "post",
+ message: "Selected asset content is not valid UTF-8",
+ }),
+ ],
+ });
+ });
+
+ test("fails strict index preparation with per-asset diagnostics", async () => {
+ const dependencies = createDependencies();
+ const issues = [
+ {
+ assetId: "broken",
+ storageName: "broken.md",
+ revision: "file:broken.md:now:4",
+ message: "Object is missing",
+ },
+ ];
+ dependencies.synchronizeCanonicalAssets.mockResolvedValue({
+ scanned: 1,
+ indexed: 0,
+ metadataUpdated: 0,
+ unchanged: 0,
+ removed: 0,
+ skipped: 0,
+ inconsistent: 0,
+ issues,
+ });
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: assetClient,
+ dependencies,
+ });
+
+ await expect(repository.prepareIndex()).rejects.toMatchObject({
+ name: "AssetIndexPreparationError",
+ issues,
+ } satisfies Partial<AssetIndexPreparationError>);
+ expect(dependencies.loadCanonicalAssetFileEntries).not.toHaveBeenCalled();
+ });
+
+ test("keeps healthy indexed assets readable when another asset is broken", async () => {
+ const dependencies = createDependencies();
+ dependencies.synchronizeCanonicalAssets.mockResolvedValue({
+ scanned: 2,
+ indexed: 0,
+ metadataUpdated: 0,
+ unchanged: 1,
+ removed: 1,
+ skipped: 1,
+ inconsistent: 0,
+ issues: [
+ {
+ assetId: "broken",
+ storageName: "broken.md",
+ revision: "revision-broken",
+ message: "Object is missing",
+ },
+ ],
+ });
+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([]);
+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue([]);
+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: assetClient,
+ dependencies,
+ });
+
+ await expect(
+ repository.query({
+ query: {
+ where: { all: [] },
+ output: { mode: "base", includeMetadata: true },
+ },
+ })
+ ).resolves.toMatchObject({ data: { items: [] } });
+ });
+
+ test("updates metadata without eagerly maintaining query fields", async () => {
+ const dependencies = createDependencies();
+ const updatedAsset = {
+ id: "asset-1",
+ projectId: "project-1",
+ name: "post.md",
+ filename: "Published post",
+ description: "Description",
+ folderId: "blog",
+ type: "file" as const,
+ format: "md",
+ size: 10,
+ createdAt: "2026-07-25T00:00:00.000Z",
+ meta: {},
+ };
+ dependencies.updateAssetMetadataWithClient.mockResolvedValue(updatedAsset);
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: assetClient,
+ dependencies,
+ });
+
+ await expect(
+ repository.updateMetadata("asset-1", {
+ filename: "Published post",
+ description: "Description",
+ folderId: "blog",
+ })
+ ).resolves.toBe(updatedAsset);
+ expect(dependencies.hasProjectPermit).toHaveBeenCalledWith(
+ { projectId: "project-1", permit: "edit" },
+ context
+ );
+ expect(dependencies.updateAssetMetadataWithClient).toHaveBeenCalledWith(
+ {
+ projectId: "project-1",
+ assetId: "asset-1",
+ values: {
+ filename: "Published post",
+ description: "Description",
+ folderId: "blog",
+ },
+ },
+ context.postgrest.client
+ );
+ });
+
+ test("does not reindex changed content during the mutation", async () => {
+ const dependencies = createDependencies();
+ const updatedAsset = {
+ id: "asset-1",
+ projectId: "project-1",
+ name: "post.md",
+ type: "file" as const,
+ format: "md",
+ size: 12,
+ description: null,
+ createdAt: "2026-07-25T00:00:00.000Z",
+ meta: {},
+ };
+ dependencies.updateAssetContent.mockResolvedValue(updatedAsset);
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: assetClient,
+ dependencies,
+ });
+
+ await expect(
+ repository.updateContent({
+ assetId: "asset-1",
+ expectedName: "post.md",
+ data: new Blob(["updated post"]).stream(),
+ })
+ ).resolves.toBe(updatedAsset);
+ });
+
+ test("does not rebuild the derived index while deleting assets", async () => {
+ const dependencies = createDependencies();
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: assetClient,
+ dependencies,
+ });
+
+ await repository.delete(["asset-1", "asset-2"]);
+
+ expect(dependencies.deleteAssetsWithClient).toHaveBeenCalledWith(
+ { projectId: "project-1", ids: ["asset-1", "asset-2"] },
+ context.postgrest.client
+ );
+ expect(dependencies.synchronizeCanonicalAssets).not.toHaveBeenCalled();
+ });
+
+ test("lazily indexes an uploaded Markdown document on its first query", async () => {
+ const dependencies = createDependencies();
+ const revision = `sha256:${"a".repeat(64)}`;
+ const uploadedAsset = {
+ id: "asset-1",
+ projectId: "project-1",
+ name: "post.md",
+ type: "file" as const,
+ format: "md",
+ size: 10,
+ description: null,
+ createdAt: "2026-07-25T00:00:00.000Z",
+ meta: {},
+ };
+ dependencies.uploadFile.mockResolvedValue(uploadedAsset);
+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([
+ uploadedAsset,
+ ]);
+ const entry = {
+ projectId: "project-1",
+ assetId: "asset-1",
+ revision,
+ document: {
+ _id: "asset-1",
+ _type: "asset.file" as const,
+ name: "post.md",
+ path: "post.md",
+ key: "post.md",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 10,
+ revision,
+ contentRef: "post.md",
+ properties: { title: "New post" },
+ },
+ };
+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([
+ { ...entry, document: { ...entry.document, properties: {} } },
+ ]);
+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue([entry]);
+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: assetClient,
+ dependencies,
+ });
+
+ await repository.completeUpload({
+ name: "post.md",
+ data: new Blob(["post"]).stream(),
+ assetInfoFallback: undefined,
+ });
+ const result = await repository.query({
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "title"],
+ operator: "eq",
+ value: "New post",
+ },
+ ],
+ },
+ output: { mode: "base", includeMetadata: true },
+ },
+ });
+
+ expect(dependencies.synchronizeCanonicalAssets).toHaveBeenCalledWith({
+ client: context.postgrest.client,
+ assetClient,
+ projectId: "project-1",
+ assetIds: ["asset-1"],
+ requirements: { structuredProperties: true, excerpt: false },
+ });
+ expect(result.data.items).toEqual([
+ expect.objectContaining({
+ id: "asset-1",
+ }),
+ ]);
+ expect(result.__diagnostics__).toMatchObject({
+ scope: "query-preview",
+ includedDocumentCount: 1,
+ omittedDocumentCount: 0,
+ truncated: false,
+ });
+ expect(dependencies.loadAssetsByProjectWithClient).not.toHaveBeenCalled();
+
+ const urlResult = await repository.query({
+ query: {
+ where: { all: [] },
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["url"]],
+ },
+ },
+ });
+ expect(urlResult.data.items).toEqual([
+ { id: "asset-1", url: "/cgi/asset/post.md?format=raw" },
+ ]);
+ expect(dependencies.loadAssetsByProjectWithClient).toHaveBeenCalledWith(
+ "project-1",
+ context.postgrest.client,
+ ["asset-1"]
+ );
+ dependencies.loadAssetsByProjectWithClient.mockClear();
+
+ const idOnlyResult = await repository.query({
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "title"],
+ operator: "eq",
+ value: "New post",
+ },
+ ],
+ },
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["id"]],
+ },
+ },
+ });
+ expect(idOnlyResult.__diagnostics__.usedBytes).toBeLessThan(
+ result.__diagnostics__.usedBytes
+ );
+ expect(dependencies.loadAssetsByProjectWithClient).not.toHaveBeenCalled();
+
+ vi.mocked(assetClient.readFile).mockResolvedValue({
+ data: new Blob(["# New post"]).stream(),
+ contentLength: 10,
+ });
+ const publishedIndex = await repository.prepareIndex(
+ createCompilationPlan({
+ where: {
+ all: [
+ {
+ field: ["properties", "title"],
+ operator: "eq",
+ value: "New post",
+ },
+ ],
+ },
+ content: { mode: "full" },
+ })
+ );
+ const publishedFetch = createPublishedAssetResourceFetch({
+ baseUrl: "https://blog.example",
+ deploymentId: "deployment-1",
+ artifact: publishedIndex,
+ runtimeAssets: { "asset-1": { url: "/assets/post.md" } },
+ });
+ const publishedResponse = await publishedFetch("/$resources/assets", {
+ method: "POST",
+ body: JSON.stringify({
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "title"],
+ operator: "eq",
+ value: "New post",
+ },
+ ],
+ },
+ content: { mode: "full" },
+ },
+ }),
+ });
+ expect(await publishedResponse?.json()).toMatchObject({
+ items: [
+ {
+ id: "asset-1",
+ content: { text: "# New post" },
+ },
+ ],
+ });
+ });
+});
diff --git a/packages/asset-uploader/src/asset-repository.ts b/packages/asset-uploader/src/asset-repository.ts
new file mode 100644
index 0000000000..f64b0a86cf
--- /dev/null
+++ b/packages/asset-uploader/src/asset-repository.ts
@@ -0,0 +1,766 @@
+import {
+ assetQuery,
+ contentEngineLimits,
+ createContentCompilationPlan,
+ createContentFieldCatalogCompilationPlan,
+ createLiteralContentCompilationQuery,
+ getContentArtifactRuntimeAssetIds,
+ isContentDocumentCandidate,
+ prepareContentCompilerEntries,
+ requiresRuntimeDocumentData,
+ requiresStructuredProperties,
+ type AssetQueryRequestInput,
+ type AssetQueryPreviewResult,
+ type BuilderAssetFieldCatalog,
+ type ContentCompilationPlan,
+} from "@webstudio-is/content-engine";
+import {
+ createAssetIndex,
+ createAssetFieldCatalog,
+ createContentSourceFile,
+ computeCanonicalAssetRevision,
+ decodeUtf8,
+ materializeContentSource,
+ materializeContentSnapshot,
+ ContentSourceChangedError,
+ readBoundedBytes,
+ toBuilderAssetFieldCatalog,
+ type ContentSource,
+} from "@webstudio-is/content-engine/compiler";
+import {
+ toRuntimeAsset,
+ type Asset,
+ type AssetFolder,
+} from "@webstudio-is/sdk";
+import type {
+ AssetFolderUpdate,
+ AssetMetadataUpdate,
+} from "./asset-mutation-types";
+import {
+ authorizeProject,
+ AuthorizationError,
+ type AppContext,
+} from "@webstudio-is/trpc-interface/index.server";
+import type { AssetDataOverride } from "./utils/get-asset-data";
+import type {
+ AssetReadRange,
+ AssetInfoFallback,
+ AssetObjectReader,
+ AssetObjectStore,
+ AssetObjectWriter,
+} from "./client";
+import { nanoid } from "nanoid";
+import {
+ createUploadTicket,
+ uploadFile,
+ type CreateUploadTicketInput,
+} from "./upload";
+import { updateAssetContent } from "./revision";
+import {
+ deleteAssetsWithClient,
+ updateAssetMetadataWithClient,
+ loadAssetsByProjectWithClient,
+} from "./asset-patch-core";
+import type { UploadTicket } from "./types";
+import {
+ loadCanonicalAssetBaseEntries,
+ synchronizeCanonicalAssets,
+} from "./canonical-metadata-backfill";
+import { loadCanonicalAssetFileEntries } from "./canonical-metadata-persistence";
+import {
+ deleteAssetFoldersWithClient,
+ loadAssetFoldersByProjectWithClient,
+ upsertAssetFolderWithClient,
+} from "./folder-persistence";
+import {
+ createContentCompilationCacheKey,
+ getContentDatabaseForArtifact,
+ sharedContentCompilationCache,
+ type ContentCompilationCache,
+} from "./content-compilation-cache";
+import {
+ AssetRepositoryConflictError,
+ AssetRepositoryNotFoundError,
+} from "./asset-repository-errors";
+
+type CreateId = () => Asset["id"];
+type RepositoryObjectStore = AssetObjectReader & Partial<AssetObjectWriter>;
+
+const defaultDependencies = {
+ hasProjectPermit: authorizeProject.hasProjectPermit,
+ createUploadTicket,
+ uploadFile,
+ updateAssetContent,
+ deleteAssetsWithClient,
+ updateAssetMetadataWithClient,
+ loadAssetsByProjectWithClient,
+ loadAssetFoldersByProjectWithClient,
+ upsertAssetFolderWithClient,
+ deleteAssetFoldersWithClient,
+ createId: (): string => nanoid(),
+ now: () => new Date(),
+ loadCanonicalAssetBaseEntries,
+ synchronizeCanonicalAssets,
+ loadCanonicalAssetFileEntries,
+ createAssetIndex,
+};
+
+type AssetRepositoryDependencies = typeof defaultDependencies;
+
+export class AssetIndexPreparationError extends Error {
+ readonly issues: Awaited<
+ ReturnType<typeof synchronizeCanonicalAssets>
+ >["issues"];
+
+ constructor(
+ issues: Awaited<ReturnType<typeof synchronizeCanonicalAssets>>["issues"]
+ ) {
+ super(
+ `Asset index preparation failed for ${issues.length} asset${issues.length === 1 ? "" : "s"}: ${issues.map(({ assetId, storageName, message }) => `${assetId} (${storageName}): ${message}`).join("; ")}`
+ );
+ this.name = "AssetIndexPreparationError";
+ this.issues = issues;
+ }
+}
+
+export type AssetContentRead = {
+ asset: Asset;
+ data: AsyncIterable<Uint8Array>;
+ contentLength?: number;
+};
+
+export interface AssetRepository {
+ list(): Promise<Asset[]>;
+ get(assetId: Asset["id"]): Promise<Asset>;
+ readContent(input: {
+ assetId: Asset["id"];
+ range?: AssetReadRange;
+ asset?: Asset;
+ }): Promise<AssetContentRead>;
+ createUploadTicket(
+ input: Omit<CreateUploadTicketInput, "projectId">,
+ createId?: CreateId
+ ): Promise<UploadTicket>;
+ completeUpload(input: {
+ name: string;
+ data: ReadableStream<Uint8Array>;
+ assetInfoFallback: AssetInfoFallback | undefined;
+ assetDataOverride?: AssetDataOverride;
+ assetId?: Asset["id"];
+ }): Promise<Asset>;
+ updateContent(input: {
+ assetId: Asset["id"];
+ expectedName: string;
+ data: ReadableStream<Uint8Array>;
+ }): Promise<Asset>;
+ updateMetadata(
+ assetId: Asset["id"],
+ values: AssetMetadataUpdate
+ ): Promise<Asset>;
+ delete(ids: Asset["id"][]): Promise<void>;
+ listFolders(): Promise<AssetFolder[]>;
+ getFolder(folderId: string): Promise<AssetFolder>;
+ createFolder(input: {
+ name: string;
+ parentId?: string;
+ }): Promise<AssetFolder>;
+ updateFolder(
+ folderId: string,
+ values: AssetFolderUpdate
+ ): Promise<AssetFolder>;
+ deleteFolder(folderId: string): Promise<void>;
+ readFieldCatalog(): Promise<BuilderAssetFieldCatalog>;
+ query(request: AssetQueryRequestInput): Promise<AssetQueryPreviewResult>;
+}
+
+/**
+ * Hosted Assets repository. PostgreSQL owns logical records and canonical
+ * metadata; the injected object store owns file bytes. Published runtimes use
+ * a separate storage-neutral index/query repository.
+ *
+ * Public mutations update only logical records and object bytes. Query reads
+ * and publication lazily reconcile derived metadata so projects that do not
+ * use configured Assets queries never open or parse stored file contents.
+ */
+export class PostgresAssetRepository implements AssetRepository {
+ private readonly projectId: string;
+ private readonly context: AppContext;
+ private readonly assetStore: RepositoryObjectStore;
+ private readonly dependencies: AssetRepositoryDependencies;
+ private readonly contentDatabaseMaxBytes: number;
+ private readonly compilationCache: ContentCompilationCache | undefined;
+
+ constructor({
+ projectId,
+ context,
+ assetStore,
+ dependencies,
+ contentDatabaseMaxBytes = contentEngineLimits.databaseBytes,
+ compilationCache,
+ }: {
+ projectId: string;
+ context: AppContext;
+ assetStore: RepositoryObjectStore;
+ dependencies?: Partial<AssetRepositoryDependencies>;
+ contentDatabaseMaxBytes?: number;
+ compilationCache?: ContentCompilationCache;
+ }) {
+ this.projectId = projectId;
+ this.context = context;
+ this.assetStore = assetStore;
+ this.dependencies = { ...defaultDependencies, ...dependencies };
+ this.contentDatabaseMaxBytes = contentDatabaseMaxBytes;
+ this.compilationCache =
+ compilationCache ??
+ (dependencies === undefined ? sharedContentCompilationCache : undefined);
+ }
+
+ static async forUpload({
+ name,
+ context,
+ assetStore,
+ }: {
+ name: string;
+ context: AppContext;
+ assetStore: AssetObjectStore;
+ }) {
+ const file = await context.postgrest.client
+ .from("File")
+ .select("uploaderProjectId")
+ .eq("name", name)
+ .single();
+ if (file.error || typeof file.data?.uploaderProjectId !== "string") {
+ throw new Error(
+ file.error?.message ?? "File uploader project is missing"
+ );
+ }
+ return new PostgresAssetRepository({
+ projectId: file.data.uploaderProjectId,
+ context,
+ assetStore,
+ });
+ }
+
+ private async assertPermit(
+ permit: "view" | "edit" | "build",
+ action: string
+ ) {
+ const permitted = await this.dependencies.hasProjectPermit(
+ { projectId: this.projectId, permit },
+ this.context
+ );
+ if (permitted === false) {
+ throw new AuthorizationError(`You don't have access to ${action}`);
+ }
+ }
+
+ private async assertCanEdit() {
+ await this.assertPermit("edit", "edit this project assets");
+ }
+
+ private async assertCanView() {
+ await this.assertPermit("view", "view this project assets");
+ }
+
+ private async assertCanBuild() {
+ // Index preparation only reads asset data and produces a derived artifact.
+ // Callers that perform an actual build or publish enforce the stronger
+ // build permit before invoking this method.
+ if (this.context.authorization?.type === "service") {
+ return;
+ }
+ await this.assertCanView();
+ }
+
+ private getWritableStore(): AssetObjectStore {
+ if (this.assetStore.uploadFile === undefined) {
+ throw new Error("Asset object storage is read-only");
+ }
+ return this.assetStore as AssetObjectStore;
+ }
+
+ private getUploadErrorCleanup(assetId: Asset["id"] | undefined) {
+ if (assetId === undefined) {
+ return;
+ }
+ return async (name: string) => {
+ const deletedAsset = await this.context.postgrest.client
+ .from("Asset")
+ .delete()
+ .eq("id", assetId)
+ .eq("projectId", this.projectId);
+ if (deletedAsset.error) {
+ throw deletedAsset.error;
+ }
+ const deletedFile = await this.context.postgrest.client
+ .from("File")
+ .delete()
+ .eq("name", name);
+ if (deletedFile.error) {
+ throw deletedFile.error;
+ }
+ };
+ }
+
+ async list() {
+ await this.assertCanView();
+ return await this.dependencies.loadAssetsByProjectWithClient(
+ this.projectId,
+ this.context.postgrest.client
+ );
+ }
+
+ async get(assetId: Asset["id"]) {
+ await this.assertCanView();
+ const [asset] = await this.dependencies.loadAssetsByProjectWithClient(
+ this.projectId,
+ this.context.postgrest.client,
+ [assetId]
+ );
+ if (asset === undefined) {
+ throw new AssetRepositoryNotFoundError("Asset not found");
+ }
+ return asset;
+ }
+
+ async readContent({
+ assetId,
+ range,
+ asset: knownAsset,
+ }: Parameters<AssetRepository["readContent"]>[0]) {
+ if (knownAsset !== undefined && knownAsset.id !== assetId) {
+ throw new Error("Known asset does not match requested asset id");
+ }
+ if (knownAsset !== undefined) {
+ await this.assertCanView();
+ }
+ const asset = knownAsset ?? (await this.get(assetId));
+ const content = await this.assetStore.readFile(asset.name, range);
+ return { asset, ...content };
+ }
+
+ async createUploadTicket(
+ input: Omit<CreateUploadTicketInput, "projectId">,
+ createId?: CreateId
+ ) {
+ await this.assertCanEdit();
+ const ticket = await this.dependencies.createUploadTicket(
+ { ...input, projectId: this.projectId },
+ this.context,
+ createId
+ );
+ return ticket;
+ }
+
+ async completeUpload({
+ name,
+ data,
+ assetInfoFallback,
+ assetDataOverride,
+ assetId,
+ }: Parameters<AssetRepository["completeUpload"]>[0]) {
+ // Reserved upload names are not authorization credentials. Recheck the
+ // derived owning project when the second upload step writes file content.
+ await this.assertCanEdit();
+ const asset = await this.dependencies.uploadFile(
+ name,
+ data,
+ this.getWritableStore(),
+ this.context,
+ assetInfoFallback,
+ assetDataOverride,
+ this.getUploadErrorCleanup(assetId)
+ );
+ return asset;
+ }
+
+ async updateContent({
+ assetId,
+ expectedName,
+ data,
+ }: Parameters<AssetRepository["updateContent"]>[0]) {
+ await this.assertCanEdit();
+ const asset = await this.dependencies.updateAssetContent(
+ {
+ assetId,
+ projectId: this.projectId,
+ expectedName,
+ data,
+ },
+ this.getWritableStore(),
+ this.context
+ );
+ return asset;
+ }
+
+ async updateMetadata(assetId: Asset["id"], values: AssetMetadataUpdate) {
+ await this.assertCanEdit();
+ const asset = await this.dependencies.updateAssetMetadataWithClient(
+ { projectId: this.projectId, assetId, values },
+ this.context.postgrest.client
+ );
+
+ return asset;
+ }
+
+ async delete(ids: Asset["id"][]) {
+ await this.assertCanEdit();
+ await this.dependencies.deleteAssetsWithClient(
+ { projectId: this.projectId, ids },
+ this.context.postgrest.client
+ );
+ }
+
+ async listFolders() {
+ await this.assertCanView();
+ return await this.dependencies.loadAssetFoldersByProjectWithClient(
+ this.projectId,
+ this.context.postgrest.client
+ );
+ }
+
+ async getFolder(folderId: string) {
+ await this.assertCanView();
+ const [folder] =
+ await this.dependencies.loadAssetFoldersByProjectWithClient(
+ this.projectId,
+ this.context.postgrest.client,
+ [folderId]
+ );
+ if (folder === undefined) {
+ throw new AssetRepositoryNotFoundError("Asset folder not found");
+ }
+ return folder;
+ }
+
+ async createFolder({ name, parentId }: { name: string; parentId?: string }) {
+ await this.assertCanEdit();
+ return await this.dependencies.upsertAssetFolderWithClient(
+ {
+ projectId: this.projectId,
+ folder: {
+ id: this.dependencies.createId(),
+ projectId: this.projectId,
+ name,
+ parentId,
+ createdAt: this.dependencies.now().toISOString(),
+ },
+ },
+ this.context.postgrest.client
+ );
+ }
+
+ async updateFolder(folderId: string, values: AssetFolderUpdate) {
+ await this.assertCanEdit();
+ const folder = (
+ await this.dependencies.loadAssetFoldersByProjectWithClient(
+ this.projectId,
+ this.context.postgrest.client
+ )
+ ).find(({ id }) => id === folderId);
+ if (folder === undefined) {
+ throw new AssetRepositoryNotFoundError("Asset folder not found");
+ }
+ const updated = await this.dependencies.upsertAssetFolderWithClient(
+ {
+ projectId: this.projectId,
+ folder: {
+ ...folder,
+ ...(values.name === undefined ? {} : { name: values.name }),
+ parentId:
+ values.parentId === null
+ ? undefined
+ : (values.parentId ?? folder.parentId),
+ },
+ },
+ this.context.postgrest.client
+ );
+ return updated;
+ }
+
+ async deleteFolder(folderId: string) {
+ await this.assertCanEdit();
+ const [folders, assets] = await Promise.all([
+ this.dependencies.loadAssetFoldersByProjectWithClient(
+ this.projectId,
+ this.context.postgrest.client
+ ),
+ this.dependencies.loadAssetsByProjectWithClient(
+ this.projectId,
+ this.context.postgrest.client
+ ),
+ ]);
+ if (folders.some(({ id }) => id === folderId) === false) {
+ throw new AssetRepositoryNotFoundError("Asset folder not found");
+ }
+ if (
+ folders.some(({ parentId }) => parentId === folderId) ||
+ assets.some(({ folderId: assetFolderId }) => assetFolderId === folderId)
+ ) {
+ throw new AssetRepositoryConflictError(
+ "Asset folder must be empty before it can be deleted"
+ );
+ }
+ await this.dependencies.deleteAssetFoldersWithClient(
+ { projectId: this.projectId, ids: [folderId] },
+ this.context.postgrest.client
+ );
+ }
+
+ async synchronize() {
+ await this.assertCanEdit();
+ return await this.synchronizeTrusted();
+ }
+
+ private async synchronizeTrusted(
+ requirements?: ContentCompilationPlan,
+ assetIds?: string[]
+ ) {
+ return await this.dependencies.synchronizeCanonicalAssets({
+ client: this.context.postgrest.client,
+ assetClient: this.assetStore,
+ projectId: this.projectId,
+ assetIds,
+ ...(requirements === undefined
+ ? {}
+ : {
+ requirements: {
+ structuredProperties: requiresStructuredProperties(requirements),
+ excerpt: requirements.excerpt,
+ },
+ }),
+ });
+ }
+
+ async prepareIndex(requirements?: ContentCompilationPlan) {
+ await this.assertCanBuild();
+ return await this.prepareIndexAfterAuthorization(requirements, true);
+ }
+
+ private async prepareIndexAfterAuthorization(
+ requirements: ContentCompilationPlan | undefined,
+ strict: boolean
+ ) {
+ const source = this.createContentSource(strict);
+ const compile = async (
+ entries: Parameters<typeof createAssetIndex>[0]["entries"],
+ assetReferences: Parameters<typeof createAssetIndex>[0]["assetReferences"]
+ ) =>
+ await this.dependencies.createAssetIndex({
+ projectId: this.projectId,
+ entries,
+ assetReferences,
+ maxBytes: this.contentDatabaseMaxBytes,
+ ...(requirements === undefined ? {} : { plan: requirements }),
+ });
+ if (this.compilationCache === undefined) {
+ const { entries, assetReferences } = await materializeContentSource({
+ source,
+ plan: requirements,
+ maximumContentBytes: this.contentDatabaseMaxBytes,
+ });
+ return await compile(entries, assetReferences);
+ }
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ const snapshot = await source.openSnapshot();
+ const key = createContentCompilationCacheKey({
+ projectId: this.projectId,
+ sourceRevision: snapshot.revision,
+ plan: requirements,
+ strict,
+ maxBytes: this.contentDatabaseMaxBytes,
+ });
+ try {
+ return await this.compilationCache.getOrCreate(key, async () => {
+ const { entries, assetReferences } = await materializeContentSnapshot(
+ {
+ snapshot,
+ plan: requirements,
+ maximumContentBytes: this.contentDatabaseMaxBytes,
+ }
+ );
+ return await compile(entries, assetReferences);
+ });
+ } catch (error) {
+ if (error instanceof ContentSourceChangedError === false) {
+ throw error;
+ }
+ }
+ }
+ throw new ContentSourceChangedError();
+ }
+
+ private createContentSource(strict: boolean): ContentSource {
+ const loadBaseEntries = () =>
+ this.dependencies.loadCanonicalAssetBaseEntries({
+ client: this.context.postgrest.client,
+ projectId: this.projectId,
+ });
+ return {
+ openSnapshot: async () => {
+ const baseEntries = await loadBaseEntries();
+ const revision = await computeCanonicalAssetRevision(baseEntries);
+ return {
+ revision,
+ files: baseEntries.map(createContentSourceFile),
+ loadEntries: (plan, options) =>
+ this.loadCompilerEntries({
+ baseEntries,
+ requirements: plan,
+ strict,
+ maximumContentBytes: options?.maximumContentBytes,
+ }),
+ isCurrent: async () =>
+ (await computeCanonicalAssetRevision(await loadBaseEntries())) ===
+ revision,
+ };
+ },
+ };
+ }
+
+ private async loadCompilerEntries({
+ baseEntries,
+ requirements,
+ strict,
+ maximumContentBytes,
+ }: {
+ baseEntries: Awaited<ReturnType<typeof loadCanonicalAssetBaseEntries>>;
+ requirements?: ContentCompilationPlan;
+ strict: boolean;
+ maximumContentBytes?: number;
+ }) {
+ const candidateBaseEntries =
+ requirements === undefined
+ ? baseEntries
+ : baseEntries.filter(({ document }) =>
+ isContentDocumentCandidate({
+ document,
+ plan: requirements,
+ available: "base",
+ })
+ );
+ const candidateAssetIds =
+ requirements === undefined
+ ? undefined
+ : candidateBaseEntries.map(({ assetId }) => assetId);
+ let entries = candidateBaseEntries;
+ if (
+ requirements === undefined ||
+ requiresStructuredProperties(requirements) ||
+ requirements.excerpt
+ ) {
+ const result = await this.synchronizeTrusted(
+ requirements,
+ candidateAssetIds
+ );
+ if (strict && result.issues.length > 0) {
+ throw new AssetIndexPreparationError(result.issues);
+ }
+ entries = await this.dependencies.loadCanonicalAssetFileEntries({
+ client: this.context.postgrest.client,
+ projectId: this.projectId,
+ assetIds: candidateAssetIds,
+ });
+ }
+ return await prepareContentCompilerEntries({
+ entries,
+ plan: requirements,
+ loadContent: async (entry) => {
+ const response = await this.assetStore.readFile(
+ entry.document.contentRef,
+ { offset: 0, length: entry.document.size }
+ );
+ const bytes = await readBoundedBytes(
+ response.data,
+ entry.document.size
+ );
+ if (bytes.byteLength !== entry.document.size) {
+ throw new Error("Asset content does not match its canonical size");
+ }
+ let content: string;
+ try {
+ content = decodeUtf8(bytes);
+ } catch {
+ if (strict) {
+ throw new AssetIndexPreparationError([
+ {
+ assetId: entry.assetId,
+ storageName: entry.document.contentRef,
+ revision: entry.revision,
+ message: "Selected asset content is not valid UTF-8",
+ },
+ ]);
+ }
+ return;
+ }
+ return content;
+ },
+ maximumContentBytes,
+ });
+ }
+
+ async readFieldCatalog() {
+ await this.assertCanView();
+ const { entries } = await materializeContentSource({
+ source: this.createContentSource(false),
+ plan: createContentFieldCatalogCompilationPlan(),
+ });
+ return toBuilderAssetFieldCatalog(await createAssetFieldCatalog(entries));
+ }
+
+ async query(
+ request: AssetQueryRequestInput
+ ): Promise<AssetQueryPreviewResult> {
+ await this.assertCanView();
+ const query = assetQuery.parse(request.query);
+ const plan = createContentCompilationPlan([
+ createLiteralContentCompilationQuery({ id: "preview", query }),
+ ]);
+ const index = await this.prepareIndexAfterAuthorization(plan, false);
+ const database = getContentDatabaseForArtifact(index);
+ const runtimeAssetIds = getContentArtifactRuntimeAssetIds({
+ artifact: index,
+ includeDocuments: plan !== undefined && requiresRuntimeDocumentData(plan),
+ });
+ const runtimeAssets =
+ runtimeAssetIds.length > 0
+ ? Object.fromEntries(
+ (
+ await this.dependencies.loadAssetsByProjectWithClient(
+ this.projectId,
+ this.context.postgrest.client,
+ runtimeAssetIds
+ )
+ ).map((asset) => [
+ asset.id,
+ toRuntimeAsset(asset, "https://webstudio.local"),
+ ])
+ )
+ : undefined;
+ const data = await database.query(
+ request,
+ this.assetStore.readFile,
+ runtimeAssets
+ );
+ const {
+ usedBytes,
+ maxBytes,
+ unboundedBytes,
+ includedDocumentCount,
+ omittedDocumentCount,
+ truncated,
+ } = database.getStats();
+ return {
+ data,
+ __diagnostics__: {
+ scope: "query-preview",
+ usedBytes,
+ maxBytes,
+ unboundedBytes,
+ includedDocumentCount,
+ omittedDocumentCount,
+ truncated,
+ },
+ };
+ }
+}
diff --git a/packages/asset-uploader/src/canonical-metadata-backfill.test.ts b/packages/asset-uploader/src/canonical-metadata-backfill.test.ts
new file mode 100644
index 0000000000..a07b762469
--- /dev/null
+++ b/packages/asset-uploader/src/canonical-metadata-backfill.test.ts
@@ -0,0 +1,872 @@
+import { describe, expect, test, vi } from "vitest";
+import {
+ canonicalAssetMetadataExtractorGeneration,
+ createCanonicalAssetFileEntry,
+ getCanonicalAssetMetadataTier,
+} from "@webstudio-is/content-engine/compiler";
+import {
+ createTestServer,
+ db,
+ json,
+ testContext,
+} from "@webstudio-is/postgrest/testing";
+import type { AssetObjectStore } from "./client";
+import {
+ loadCanonicalAssetBaseEntries,
+ synchronizeCanonicalAssets,
+} from "./canonical-metadata-backfill";
+
+const server = createTestServer();
+const encoder = new TextEncoder();
+
+type ReplaceMetadataRpcArgs = {
+ p_project_id: string;
+ p_asset_id: string;
+ p_revision: string;
+ p_document: Record<string, unknown>;
+ p_source: Record<string, unknown>;
+};
+
+const entryFromReplaceRpc = (value: ReplaceMetadataRpcArgs) => ({
+ projectId: value.p_project_id,
+ assetId: value.p_asset_id,
+ revision: value.p_revision,
+ document: value.p_document,
+ source: value.p_source,
+});
+
+describe("canonical asset metadata synchronization", () => {
+ test("builds base documents from records without canonical writes or object reads", async () => {
+ server.use(
+ db.get("Asset", () =>
+ json([
+ {
+ id: "post",
+ projectId: "project-1",
+ filename: "Hello",
+ folderId: "blog",
+ file: {
+ name: "stored-post.md",
+ size: 20,
+ updatedAt: "2026-07-18T01:00:00.000Z",
+ contentHash: "a".repeat(64),
+ status: "UPLOADED",
+ },
+ },
+ ])
+ ),
+ db.get("AssetFolder", () =>
+ json([
+ {
+ id: "blog",
+ projectId: "project-1",
+ name: "Blog",
+ parentId: null,
+ createdAt: "2026-07-18T00:00:00.000Z",
+ },
+ ])
+ )
+ );
+
+ await expect(
+ loadCanonicalAssetBaseEntries({
+ projectId: "project-1",
+ client: testContext.postgrest.client,
+ })
+ ).resolves.toEqual([
+ expect.objectContaining({
+ assetId: "post",
+ document: expect.objectContaining({
+ name: "Hello.md",
+ path: "Blog/Hello.md",
+ contentRef: "stored-post.md",
+ revision: `sha256:${"a".repeat(64)}`,
+ properties: {},
+ }),
+ }),
+ ]);
+ });
+
+ test.each([
+ {
+ name: "structured properties",
+ requirements: { structuredProperties: true, excerpt: false },
+ expectedProperties: { title: "Post" },
+ expectedExcerpt: undefined,
+ },
+ {
+ name: "excerpt",
+ requirements: { structuredProperties: false, excerpt: true },
+ expectedProperties: {},
+ expectedExcerpt: "Post body",
+ },
+ ])("prepares only requested Markdown $name", async (scenario) => {
+ const source = "---\ntitle: Post\n---\nPost body";
+ const readFile = vi.fn<AssetObjectStore["readFile"]>(async () => ({
+ data: {
+ async *[Symbol.asyncIterator]() {
+ yield encoder.encode(source);
+ },
+ },
+ }));
+ let storedDocument: Record<string, unknown> | undefined;
+ server.use(
+ db.get("Asset", () =>
+ json([
+ {
+ id: "post",
+ projectId: "project-1",
+ filename: null,
+ folderId: null,
+ file: {
+ name: "post.md",
+ size: encoder.encode(source).byteLength,
+ updatedAt: "2026-07-18T01:00:00.000Z",
+ status: "UPLOADED",
+ },
+ },
+ ])
+ ),
+ db.get("AssetFolder", () => json([])),
+ db.get("AssetFileMetadata", () => json([])),
+ db.post("rpc/replace_asset_file_metadata", async ({ request }) => {
+ const value = (await request.json()) as ReplaceMetadataRpcArgs;
+ storedDocument = value.p_document;
+ return json(true);
+ })
+ );
+
+ await synchronizeCanonicalAssets({
+ projectId: "project-1",
+ client: testContext.postgrest.client,
+ assetClient: { readFile, uploadFile: vi.fn() },
+ requirements: scenario.requirements,
+ });
+
+ expect(readFile).toHaveBeenCalledOnce();
+ expect(storedDocument).toMatchObject({
+ properties: scenario.expectedProperties,
+ $webstudioMetadataRequirements: getCanonicalAssetMetadataTier(
+ scenario.requirements
+ ),
+ $webstudioExtractorGeneration: canonicalAssetMetadataExtractorGeneration,
+ });
+ if (scenario.expectedExcerpt === undefined) {
+ expect(storedDocument).not.toHaveProperty("excerpt");
+ } else {
+ expect(storedDocument).toHaveProperty(
+ "excerpt",
+ scenario.expectedExcerpt
+ );
+ }
+ });
+
+ test("expands a cached metadata tier without reparsing completed dimensions", async () => {
+ const source = "---\ntitle: Post\n---\nPost body";
+ const bytes = encoder.encode(source);
+ const updatedAt = "2026-07-18T01:00:00.000Z";
+ const revision = `file:post.md:${updatedAt}:${bytes.byteLength}`;
+ const cached = createCanonicalAssetFileEntry({
+ projectId: "project-1",
+ metadataRequirements: {
+ structuredProperties: true,
+ excerpt: false,
+ },
+ document: {
+ _id: "post",
+ _type: "asset.file",
+ name: "post.md",
+ path: "post.md",
+ key: "post",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: bytes.byteLength,
+ revision,
+ contentRef: "post.md",
+ properties: { title: "Post" },
+ },
+ });
+ const readFile = vi.fn<AssetObjectStore["readFile"]>(async () => ({
+ data: {
+ async *[Symbol.asyncIterator]() {
+ yield bytes;
+ },
+ },
+ }));
+ let storedDocument: Record<string, unknown> | undefined;
+ server.use(
+ db.get("Asset", () =>
+ json([
+ {
+ id: "post",
+ projectId: "project-1",
+ filename: null,
+ folderId: null,
+ file: {
+ name: "post.md",
+ size: bytes.byteLength,
+ updatedAt,
+ status: "UPLOADED",
+ },
+ },
+ ])
+ ),
+ db.get("AssetFolder", () => json([])),
+ db.get("AssetFileMetadata", () =>
+ json([
+ {
+ ...cached,
+ document: {
+ ...cached.document,
+ $webstudioMetadataRequirements: "properties",
+ $webstudioExtractorGeneration:
+ canonicalAssetMetadataExtractorGeneration,
+ },
+ createdAt: updatedAt,
+ updatedAt,
+ },
+ ])
+ ),
+ db.post("rpc/replace_asset_file_metadata", async ({ request }) => {
+ storedDocument = ((await request.json()) as ReplaceMetadataRpcArgs)
+ .p_document;
+ return json(true);
+ }),
+ db.post("rpc/delete_stale_asset_file_metadata", () => json(0))
+ );
+
+ await synchronizeCanonicalAssets({
+ projectId: "project-1",
+ client: testContext.postgrest.client,
+ assetClient: { uploadFile: vi.fn(), readFile },
+ requirements: { structuredProperties: false, excerpt: true },
+ });
+
+ expect(readFile).toHaveBeenCalledOnce();
+ expect(storedDocument).toMatchObject({
+ properties: { title: "Post" },
+ excerpt: "Post body",
+ $webstudioMetadataRequirements: "properties+excerpt",
+ $webstudioExtractorGeneration: canonicalAssetMetadataExtractorGeneration,
+ });
+ });
+
+ test("indexes Markdown and JSON metadata without reading binary files", async () => {
+ const contents = new Map([
+ ["stored-one.md", "---\ntitle: One\n---\n# First post"],
+ ["stored-two.md", "---\ntitle: Two\ndraft: true\n---\nSecond post"],
+ ["stored-data.json", '{"title":"Data","draft":false}'],
+ ]);
+ const readFile = vi.fn<AssetObjectStore["readFile"]>(async (name) => ({
+ data: {
+ async *[Symbol.asyncIterator]() {
+ yield encoder.encode(contents.get(name) ?? "");
+ },
+ },
+ }));
+ const persisted: unknown[] = [];
+ server.use(
+ db.get("Asset", () =>
+ json([
+ {
+ id: "one",
+ projectId: "project-1",
+ filename: "one",
+ folderId: "blog",
+ file: {
+ name: "stored-one.md",
+ size: encoder.encode(contents.get("stored-one.md")).byteLength,
+ updatedAt: "2026-07-18T01:00:00.000Z",
+ status: "UPLOADED",
+ },
+ },
+ {
+ id: "two",
+ projectId: "project-1",
+ filename: null,
+ folderId: null,
+ file: {
+ name: "stored-two.md",
+ size: encoder.encode(contents.get("stored-two.md")).byteLength,
+ updatedAt: "2026-07-18T02:00:00.000Z",
+ status: "UPLOADED",
+ },
+ },
+ {
+ id: "data",
+ projectId: "project-1",
+ filename: null,
+ folderId: null,
+ file: {
+ name: "stored-data.json",
+ size: encoder.encode(contents.get("stored-data.json")).byteLength,
+ updatedAt: "2026-07-18T02:30:00.000Z",
+ status: "UPLOADED",
+ },
+ },
+ {
+ id: "image",
+ projectId: "project-1",
+ filename: null,
+ description: "Image description",
+ folderId: null,
+ file: {
+ name: "image.png",
+ size: 20,
+ updatedAt: "2026-07-18T03:00:00.000Z",
+ status: "UPLOADED",
+ },
+ },
+ ])
+ ),
+ db.get("AssetFolder", () =>
+ json([
+ {
+ id: "content",
+ projectId: "project-1",
+ name: "Content",
+ parentId: null,
+ createdAt: "2026-07-18T00:00:00.000Z",
+ },
+ {
+ id: "blog",
+ projectId: "project-1",
+ name: "Blog",
+ parentId: "content",
+ createdAt: "2026-07-18T00:00:00.000Z",
+ },
+ ])
+ ),
+ db.get("AssetFileMetadata", () => json([])),
+ db.post("rpc/replace_asset_file_metadata", async ({ request }) => {
+ const value = (await request.json()) as ReplaceMetadataRpcArgs;
+ persisted.push(entryFromReplaceRpc(value));
+ return json(true);
+ })
+ );
+
+ const result = await synchronizeCanonicalAssets({
+ projectId: "project-1",
+ client: testContext.postgrest.client,
+ assetClient: {
+ uploadFile: vi.fn(),
+ readFile,
+ },
+ concurrency: 2,
+ });
+
+ expect(result).toEqual({
+ scanned: 4,
+ indexed: 4,
+ metadataUpdated: 0,
+ unchanged: 0,
+ removed: 0,
+ skipped: 0,
+ inconsistent: 0,
+ issues: [],
+ });
+ expect(readFile).toHaveBeenCalledTimes(3);
+ expect(persisted).toHaveLength(4);
+ expect(persisted).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ assetId: "one",
+ document: expect.objectContaining({
+ path: "Content/Blog/one.md",
+ properties: { title: "One" },
+ excerpt: "First post",
+ }),
+ }),
+ expect.objectContaining({
+ assetId: "two",
+ document: expect.objectContaining({
+ path: "stored-two.md",
+ properties: { title: "Two", draft: true },
+ excerpt: "Second post",
+ }),
+ }),
+ expect.objectContaining({
+ assetId: "data",
+ document: expect.objectContaining({
+ path: "stored-data.json",
+ properties: { title: "Data", draft: false },
+ }),
+ }),
+ expect.objectContaining({
+ assetId: "image",
+ document: expect.objectContaining({
+ path: "image.png",
+ description: "Image description",
+ properties: {},
+ }),
+ }),
+ ])
+ );
+ const image = persisted.find(
+ (entry) =>
+ typeof entry === "object" &&
+ entry !== null &&
+ "assetId" in entry &&
+ entry.assetId === "image"
+ );
+ expect(image).toBeDefined();
+ expect(image).not.toHaveProperty("document.excerpt");
+ });
+
+ test("does not exceed shared read concurrency", async () => {
+ await expect(
+ synchronizeCanonicalAssets({
+ projectId: "project-1",
+ client: testContext.postgrest.client,
+ assetClient: {
+ uploadFile: vi.fn(),
+ readFile: vi.fn(),
+ },
+ concurrency: 9,
+ })
+ ).rejects.toThrow("exceeds the shared limit");
+ });
+
+ test("batch synchronization rereads only missing or changed revisions", async () => {
+ const sources = new Map([
+ ["changed.md", "---\ntitle: Changed\n---\nChanged body"],
+ ["new.md", "---\ntitle: New\n---\nNew body"],
+ ]);
+ const assetRows = [
+ {
+ id: "stable",
+ projectId: "project-1",
+ filename: "stable",
+ folderId: null,
+ file: {
+ name: "stable.md",
+ size: 10,
+ updatedAt: "2026-07-18T01:00:00.000Z",
+ status: "UPLOADED",
+ },
+ },
+ {
+ id: "changed",
+ projectId: "project-1",
+ filename: "changed",
+ folderId: null,
+ file: {
+ name: "changed.md",
+ size: encoder.encode(sources.get("changed.md")).byteLength,
+ updatedAt: "2026-07-18T02:00:00.000Z",
+ status: "UPLOADED",
+ },
+ },
+ {
+ id: "renamed",
+ projectId: "project-1",
+ filename: "new-name",
+ folderId: null,
+ file: {
+ name: "renamed.md",
+ size: 20,
+ updatedAt: "2026-07-18T03:00:00.000Z",
+ status: "UPLOADED",
+ },
+ },
+ {
+ id: "new",
+ projectId: "project-1",
+ filename: null,
+ folderId: null,
+ file: {
+ name: "new.md",
+ size: encoder.encode(sources.get("new.md")).byteLength,
+ updatedAt: "2026-07-18T04:00:00.000Z",
+ status: "UPLOADED",
+ },
+ },
+ {
+ id: "image",
+ projectId: "project-1",
+ filename: null,
+ folderId: null,
+ file: {
+ name: "image.png",
+ size: 30,
+ updatedAt: "2026-07-18T05:00:00.000Z",
+ status: "UPLOADED",
+ },
+ },
+ ];
+ const createEntry = ({
+ id,
+ name,
+ revision,
+ }: {
+ id: string;
+ name: string;
+ revision: string;
+ }) =>
+ createCanonicalAssetFileEntry({
+ projectId: "project-1",
+ document: {
+ _id: id,
+ _type: "asset.file",
+ name,
+ path: name,
+ key: name.replace(/\.md$/, ""),
+ extension: "md",
+ mimeType: "text/markdown",
+ size: id === "stable" ? 10 : 20,
+ revision,
+ contentRef: `${id}.md`,
+ properties: { title: id },
+ excerpt: `${id} body`,
+ },
+ });
+ const entries = [
+ createEntry({
+ id: "stable",
+ name: "stable.md",
+ revision: "file:stable.md:2026-07-18T01:00:00.000Z:10",
+ }),
+ createEntry({
+ id: "changed",
+ name: "changed.md",
+ revision: "file:changed.md:old:20",
+ }),
+ createEntry({
+ id: "renamed",
+ name: "old-name.md",
+ revision: "file:renamed.md:2026-07-18T03:00:00.000Z:20",
+ }),
+ createCanonicalAssetFileEntry({
+ projectId: "project-1",
+ metadataRequirements: {
+ structuredProperties: true,
+ excerpt: true,
+ },
+ document: {
+ _id: "image",
+ _type: "asset.file",
+ name: "image.png",
+ path: "image.png",
+ key: "image",
+ extension: "png",
+ mimeType: "image/png",
+ size: 30,
+ revision: "file:image.png:2026-07-18T05:00:00.000Z:30",
+ contentRef: "image.png",
+ properties: {},
+ excerpt: "Stale excerpt",
+ },
+ }),
+ createEntry({
+ id: "stale",
+ name: "stale.md",
+ revision: "file:stale.md:old:20",
+ }),
+ ];
+ const readFile = vi.fn<AssetObjectStore["readFile"]>(async (name) => ({
+ data: {
+ async *[Symbol.asyncIterator]() {
+ yield encoder.encode(sources.get(name) ?? "");
+ },
+ },
+ }));
+ const persisted = new Map<string, Record<string, unknown>>();
+ server.use(
+ db.get("Asset", () => json(assetRows)),
+ db.get("AssetFolder", () => json([])),
+ db.get("AssetFileMetadata", () =>
+ json(
+ entries.map((entry) => ({
+ ...entry,
+ document: {
+ ...entry.document,
+ $webstudioMetadataRequirements: "properties+excerpt",
+ $webstudioExtractorGeneration:
+ canonicalAssetMetadataExtractorGeneration,
+ },
+ createdAt: "2026-07-18T00:00:00.000Z",
+ updatedAt: "2026-07-18T00:00:00.000Z",
+ }))
+ )
+ ),
+ db.post("rpc/replace_asset_file_metadata", async ({ request }) => {
+ const value = (await request.json()) as ReplaceMetadataRpcArgs;
+ persisted.set(value.p_asset_id, value.p_document);
+ return json(true);
+ }),
+ db.post("rpc/delete_stale_asset_file_metadata", async ({ request }) => {
+ expect(await request.json()).toEqual({
+ p_project_id: "project-1",
+ p_asset_ids: ["stale"],
+ });
+ return json(1);
+ })
+ );
+
+ await expect(
+ synchronizeCanonicalAssets({
+ projectId: "project-1",
+ client: testContext.postgrest.client,
+ assetClient: { uploadFile: vi.fn(), readFile },
+ concurrency: 2,
+ })
+ ).resolves.toEqual({
+ scanned: 5,
+ indexed: 2,
+ metadataUpdated: 2,
+ unchanged: 1,
+ removed: 1,
+ skipped: 0,
+ inconsistent: 0,
+ issues: [],
+ });
+ expect(readFile).toHaveBeenCalledTimes(2);
+ expect(readFile.mock.calls.map(([name]) => name).sort()).toEqual([
+ "changed.md",
+ "new.md",
+ ]);
+ expect([...persisted.keys()].sort()).toEqual([
+ "changed",
+ "image",
+ "new",
+ "renamed",
+ ]);
+ expect(persisted.get("image")).not.toHaveProperty("excerpt");
+ });
+
+ test("recovery rereads an inconsistent derived entry", async () => {
+ const source = "---\ntitle: Recovered\n---\nRecovered body";
+ const bytes = encoder.encode(source);
+ const revision = `file:recovery.md:2026-07-18T06:00:00.000Z:${bytes.byteLength}`;
+ const validEntry = createCanonicalAssetFileEntry({
+ projectId: "project-1",
+ document: {
+ _id: "recovery",
+ _type: "asset.file",
+ name: "recovery.md",
+ path: "recovery.md",
+ key: "recovery",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: bytes.byteLength,
+ revision,
+ contentRef: "recovery.md",
+ properties: { title: "Old" },
+ },
+ });
+ const readFile = vi.fn<AssetObjectStore["readFile"]>(async () => ({
+ data: {
+ async *[Symbol.asyncIterator]() {
+ yield bytes;
+ },
+ },
+ }));
+ server.use(
+ db.get("Asset", () =>
+ json([
+ {
+ id: "recovery",
+ projectId: "project-1",
+ filename: null,
+ folderId: null,
+ file: {
+ name: "recovery.md",
+ size: bytes.byteLength,
+ updatedAt: "2026-07-18T06:00:00.000Z",
+ status: "UPLOADED",
+ },
+ },
+ ])
+ ),
+ db.get("AssetFolder", () => json([])),
+ db.get("AssetFileMetadata", () =>
+ json([
+ {
+ ...validEntry,
+ revision: "file:recovery.md:old:10",
+ createdAt: "2026-07-18T00:00:00.000Z",
+ updatedAt: "2026-07-18T00:00:00.000Z",
+ },
+ ])
+ ),
+ db.post("rpc/replace_asset_file_metadata", () => json(true))
+ );
+
+ await expect(
+ synchronizeCanonicalAssets({
+ projectId: "project-1",
+ client: testContext.postgrest.client,
+ assetClient: { uploadFile: vi.fn(), readFile },
+ })
+ ).resolves.toEqual({
+ scanned: 1,
+ indexed: 1,
+ metadataUpdated: 0,
+ unchanged: 0,
+ removed: 0,
+ skipped: 0,
+ inconsistent: 1,
+ issues: [],
+ });
+ expect(readFile).toHaveBeenCalledOnce();
+ });
+
+ test("removes invalid derived metadata when source recovery fails", async () => {
+ const invalidDocument = { _id: "broken", revision: "different" };
+ const deleted: unknown[] = [];
+ server.use(
+ db.get("Asset", () =>
+ json([
+ {
+ id: "broken",
+ projectId: "project-1",
+ filename: null,
+ folderId: null,
+ file: {
+ name: "broken.md",
+ size: 4,
+ updatedAt: "2026-07-18T07:00:00.000Z",
+ status: "UPLOADED",
+ },
+ },
+ ])
+ ),
+ db.get("AssetFolder", () => json([])),
+ db.get("AssetFileMetadata", () =>
+ json([
+ {
+ projectId: "project-1",
+ assetId: "broken",
+ revision: "stale",
+ document: invalidDocument,
+ createdAt: "2026-07-18T00:00:00.000Z",
+ updatedAt: "2026-07-18T00:00:00.000Z",
+ },
+ ])
+ ),
+ db.post(
+ "rpc/delete_asset_file_metadata_if_matches",
+ async ({ request }) => {
+ deleted.push(await request.json());
+ return json(1);
+ }
+ ),
+ db.post("rpc/delete_stale_asset_file_metadata", () => json(0))
+ );
+
+ const result = await synchronizeCanonicalAssets({
+ projectId: "project-1",
+ client: testContext.postgrest.client,
+ assetClient: {
+ uploadFile: vi.fn(),
+ readFile: vi.fn().mockRejectedValue(new Error("Object is missing")),
+ },
+ });
+
+ expect(result).toMatchObject({
+ scanned: 1,
+ skipped: 1,
+ inconsistent: 1,
+ });
+ expect(deleted).toEqual([
+ expect.objectContaining({
+ p_project_id: "project-1",
+ p_asset_id: "broken",
+ p_revision: "stale",
+ p_document: invalidDocument,
+ }),
+ ]);
+ });
+
+ test("isolates an unreadable asset and removes its stale metadata", async () => {
+ const updatedAt = "2026-07-18T07:00:00.000Z";
+ const assets = ["broken", "healthy"].map((id) => ({
+ id,
+ projectId: "project-1",
+ filename: null,
+ folderId: null,
+ file: {
+ name: `${id}.md`,
+ size: 4,
+ updatedAt,
+ status: "UPLOADED",
+ },
+ }));
+ const staleBrokenEntry = createCanonicalAssetFileEntry({
+ projectId: "project-1",
+ document: {
+ _id: "broken",
+ _type: "asset.file",
+ name: "broken.md",
+ path: "broken.md",
+ key: "broken",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 3,
+ revision: "file:broken.md:previous:3",
+ contentRef: "broken.md",
+ properties: { title: "Previous" },
+ },
+ });
+ const replaced: string[] = [];
+ const deleted: string[] = [];
+ server.use(
+ db.get("Asset", () => json(assets)),
+ db.get("AssetFolder", () => json([])),
+ db.get("AssetFileMetadata", () =>
+ json([
+ {
+ ...staleBrokenEntry,
+ createdAt: "2026-07-18T00:00:00.000Z",
+ updatedAt: "2026-07-18T00:00:00.000Z",
+ },
+ ])
+ ),
+ db.post("rpc/replace_asset_file_metadata", async ({ request }) => {
+ const input = (await request.json()) as ReplaceMetadataRpcArgs;
+ replaced.push(input.p_asset_id);
+ return json(true);
+ }),
+ db.post(
+ "rpc/delete_asset_file_metadata_if_matches",
+ async ({ request }) => {
+ const input = (await request.json()) as {
+ p_asset_id: string;
+ };
+ deleted.push(input.p_asset_id);
+ return json(1);
+ }
+ ),
+ db.post("rpc/delete_stale_asset_file_metadata", () => json(0))
+ );
+ const readFile = vi.fn<AssetObjectStore["readFile"]>(async (name) => {
+ if (name === "broken.md") {
+ throw new Error("Object is missing");
+ }
+ return {
+ data: {
+ async *[Symbol.asyncIterator]() {
+ yield encoder.encode("post");
+ },
+ },
+ };
+ });
+
+ const result = await synchronizeCanonicalAssets({
+ projectId: "project-1",
+ client: testContext.postgrest.client,
+ assetClient: { uploadFile: vi.fn(), readFile },
+ });
+
+ expect(result).toMatchObject({ scanned: 2, indexed: 1 });
+ expect(result.issues).toEqual([
+ expect.objectContaining({
+ assetId: "broken",
+ storageName: "broken.md",
+ message: "Object is missing",
+ }),
+ ]);
+ expect(replaced).toEqual(["healthy"]);
+ expect(deleted).toEqual(["broken"]);
+ });
+});
diff --git a/packages/asset-uploader/src/canonical-metadata-backfill.ts b/packages/asset-uploader/src/canonical-metadata-backfill.ts
new file mode 100644
index 0000000000..56d32300d5
--- /dev/null
+++ b/packages/asset-uploader/src/canonical-metadata-backfill.ts
@@ -0,0 +1,461 @@
+import {
+ createCanonicalAssetFileEntry,
+ fullCanonicalAssetMetadataRequirements,
+ getCanonicalAssetMetadataRequirements,
+ prepareCanonicalContentMetadata,
+ readBytePrefix,
+ mapBounded,
+ serializeJsonDeterministically,
+ satisfiesCanonicalAssetMetadataRequirements,
+ normalizeAssetFileDocument,
+ type CanonicalAssetFileEntry,
+ type CanonicalAssetMetadataRequirements,
+} from "@webstudio-is/content-engine/compiler";
+import type { AssetFileDocument } from "@webstudio-is/content-engine";
+import {
+ createAssetFolderHierarchy,
+ formatAssetName,
+ getFileNameParts,
+ getMimeTypeByFilename,
+} from "@webstudio-is/sdk";
+import { assetResourceLimits } from "@webstudio-is/sdk/asset-resource-limits";
+import type { Client } from "@webstudio-is/postgrest/index.server";
+import type { AssetObjectStore } from "./client";
+import { loadAssetFoldersByProjectWithClient } from "./folder-persistence";
+import { assertPostgrestSuccess } from "./patch-utils";
+import { isContentHash } from "./content-hash";
+import {
+ deleteCanonicalAssetFileEntryIfMatches,
+ deleteInvalidCanonicalAssetFileEntryIfMatches,
+ deleteStaleCanonicalAssetFileEntries,
+ loadCanonicalAssetFileEntries,
+ loadCanonicalAssetFileEntriesForRecovery,
+ replaceCanonicalAssetFileEntry,
+} from "./canonical-metadata-persistence";
+
+type CanonicalAssetClient = Pick<AssetObjectStore, "readFile"> &
+ Partial<Omit<AssetObjectStore, "readFile">>;
+
+export type CanonicalAssetSynchronizationIssue = {
+ assetId: string;
+ storageName: string;
+ revision: string;
+ message: string;
+};
+
+const getErrorMessage = (error: unknown) =>
+ error instanceof Error ? error.message : "Unknown asset indexing failure";
+
+const createAssetContentRevision = ({
+ storageName,
+ updatedAt,
+ size,
+ contentHash,
+}: {
+ storageName: string;
+ updatedAt: string;
+ size: number;
+ contentHash?: string | null;
+}) =>
+ isContentHash(contentHash)
+ ? `sha256:${contentHash}`
+ : `file:${encodeURIComponent(storageName)}:${updatedAt}:${size}`;
+
+type UploadedAssetRow = {
+ id: string;
+ projectId: string;
+ filename: string | null;
+ description: string | null;
+ folderId: string | null;
+ file: {
+ name: string;
+ size: number;
+ createdAt?: string;
+ updatedAt: string;
+ contentHash?: string | null;
+ };
+};
+
+const loadUploadedAssets = async (
+ projectId: string,
+ client: Client,
+ assetIds?: string[]
+) => {
+ let query = client
+ .from("Asset")
+ .select(
+ "id, projectId, filename, description, folderId, file:File!inner(name, size, createdAt, updatedAt, contentHash, status)"
+ )
+ .eq("projectId", projectId)
+ .eq("file.status", "UPLOADED");
+ if (assetIds !== undefined) {
+ if (assetIds.length === 0) {
+ return [];
+ }
+ query = query.in("id", assetIds);
+ }
+ const result = await query.order("id");
+ assertPostgrestSuccess(result);
+ return (result.data ?? []) as UploadedAssetRow[];
+};
+
+type AssetFolderHierarchy = ReturnType<typeof createAssetFolderHierarchy>;
+
+const getCanonicalMetadataSource = (asset: UploadedAssetRow) => ({
+ storageName: asset.file.name,
+ fileUpdatedAt: asset.file.updatedAt,
+ fileSize: asset.file.size,
+ ...(asset.file.contentHash === null || asset.file.contentHash === undefined
+ ? {}
+ : { contentHash: asset.file.contentHash }),
+ ...(asset.filename === null ? {} : { filename: asset.filename }),
+ ...(asset.description === null ? {} : { description: asset.description }),
+ ...(asset.folderId === null ? {} : { folderId: asset.folderId }),
+});
+
+const createCanonicalDocument = ({
+ asset,
+ hierarchy,
+ revision,
+ properties,
+ excerpt,
+ metadataError,
+}: {
+ asset: UploadedAssetRow;
+ hierarchy: AssetFolderHierarchy;
+ revision: string;
+ properties: Record<string, unknown>;
+ excerpt?: string;
+ metadataError?: AssetFileDocument["metadataError"];
+}) => {
+ const name = formatAssetName({
+ name: asset.file.name,
+ filename: asset.filename,
+ });
+ const extension = getFileNameParts(asset.file.name).extension.toLowerCase();
+ const folderId = hierarchy.resolveFolderId(asset.folderId ?? undefined);
+ const folderNames = hierarchy.getPath(folderId).map((folder) => folder.name);
+ return normalizeAssetFileDocument({
+ asset: {
+ id: asset.id,
+ name,
+ ...(asset.description === null ? {} : { description: asset.description }),
+ ...(extension === "" ? {} : { extension }),
+ ...(folderId === undefined ? {} : { folderId, folderNames }),
+ mimeType: getMimeTypeByFilename(asset.file.name),
+ size: asset.file.size,
+ createdAt: asset.file.createdAt,
+ revision,
+ contentRef: asset.file.name,
+ },
+ properties,
+ ...(excerpt === undefined || excerpt.length === 0 ? {} : { excerpt }),
+ ...(metadataError === undefined ? {} : { metadataError }),
+ });
+};
+
+const createCanonicalBaseEntry = ({
+ projectId,
+ asset,
+ hierarchy,
+ revision = createAssetContentRevision({
+ storageName: asset.file.name,
+ updatedAt: asset.file.updatedAt,
+ size: asset.file.size,
+ contentHash: asset.file.contentHash,
+ }),
+}: {
+ projectId: string;
+ asset: UploadedAssetRow;
+ hierarchy: AssetFolderHierarchy;
+ revision?: string;
+}) => {
+ return createCanonicalAssetFileEntry({
+ projectId,
+ metadataRequirements: {
+ structuredProperties: false,
+ excerpt: false,
+ },
+ document: createCanonicalDocument({
+ asset,
+ hierarchy,
+ revision,
+ properties: {},
+ }),
+ });
+};
+
+/** Builds the base index tier entirely from logical asset records. */
+export const loadCanonicalAssetBaseEntries = async ({
+ projectId,
+ client,
+}: {
+ projectId: string;
+ client: Client;
+}) => {
+ const [assets, folders] = await Promise.all([
+ loadUploadedAssets(projectId, client),
+ loadAssetFoldersByProjectWithClient(projectId, client),
+ ]);
+ const hierarchy = createAssetFolderHierarchy(
+ new Map(folders.map((folder) => [folder.id, folder]))
+ );
+ return assets.map((asset) =>
+ createCanonicalBaseEntry({
+ projectId,
+ asset,
+ hierarchy,
+ })
+ );
+};
+
+const hasMatchingCanonicalDocument = (
+ document: AssetFileDocument,
+ expected: AssetFileDocument
+) => {
+ return (
+ serializeJsonDeterministically(document) ===
+ serializeJsonDeterministically(expected)
+ );
+};
+
+const indexCanonicalAsset = async ({
+ asset,
+ client,
+ assetClient,
+ requirements,
+ base,
+ current,
+}: {
+ asset: UploadedAssetRow;
+ client: Client;
+ assetClient: CanonicalAssetClient;
+ requirements: CanonicalAssetMetadataRequirements;
+ base: CanonicalAssetFileEntry;
+ current?: CanonicalAssetFileEntry;
+}) => {
+ await prepareCanonicalContentMetadata({
+ base,
+ requirements,
+ cache: {
+ get: async () => current,
+ set: async ({ entry }) => {
+ await replaceCanonicalAssetFileEntry({
+ client,
+ entry,
+ source: getCanonicalMetadataSource(asset),
+ });
+ },
+ },
+ readBytes: async (maximumBytes) =>
+ maximumBytes === 0
+ ? new Uint8Array()
+ : await assetClient
+ .readFile(asset.file.name, {
+ offset: 0,
+ length: maximumBytes,
+ })
+ .then((stored) => readBytePrefix(stored.data, maximumBytes)),
+ });
+};
+
+const deleteObsoleteCanonicalAssetMetadata = async ({
+ projectId,
+ assetId,
+ client,
+}: {
+ projectId: string;
+ assetId: string;
+ client: Client;
+}) => {
+ const [assets, entries] = await Promise.all([
+ loadUploadedAssets(projectId, client, [assetId]),
+ loadCanonicalAssetFileEntries({ client, projectId, assetIds: [assetId] }),
+ ]);
+ const asset = assets[0];
+ if (asset === undefined) {
+ await deleteStaleCanonicalAssetFileEntries({
+ client,
+ projectId,
+ assetIds: [assetId],
+ });
+ return;
+ }
+ const currentRevision = createAssetContentRevision({
+ storageName: asset.file.name,
+ updatedAt: asset.file.updatedAt,
+ size: asset.file.size,
+ contentHash: asset.file.contentHash,
+ });
+ const entry = entries[0];
+ if (entry !== undefined && entry.revision !== currentRevision) {
+ await deleteCanonicalAssetFileEntryIfMatches({ client, entry });
+ }
+};
+
+export const synchronizeCanonicalAssets = async ({
+ projectId,
+ client,
+ assetClient,
+ concurrency = assetResourceLimits.concurrentContentReads,
+ requirements = fullCanonicalAssetMetadataRequirements,
+ assetIds,
+}: {
+ projectId: string;
+ client: Client;
+ assetClient: CanonicalAssetClient;
+ concurrency?: number;
+ requirements?: CanonicalAssetMetadataRequirements;
+ assetIds?: string[];
+}) => {
+ if (Number.isInteger(concurrency) === false || concurrency <= 0) {
+ throw new Error(
+ "Canonical metadata concurrency must be a positive integer"
+ );
+ }
+ if (concurrency > assetResourceLimits.concurrentContentReads) {
+ throw new Error("Canonical metadata concurrency exceeds the shared limit");
+ }
+
+ const [assets, folders, recoveryState] = await Promise.all([
+ loadUploadedAssets(projectId, client, assetIds),
+ loadAssetFoldersByProjectWithClient(projectId, client),
+ loadCanonicalAssetFileEntriesForRecovery({
+ client,
+ projectId,
+ assetIds,
+ }),
+ ]);
+ const { entries, inconsistentRows } = recoveryState;
+ const inconsistentAssetIds = inconsistentRows.map(({ assetId }) => assetId);
+ const inconsistentRowByAssetId = new Map(
+ inconsistentRows.map((row) => [row.assetId, row])
+ );
+ const hierarchy = createAssetFolderHierarchy(
+ new Map(folders.map((folder) => [folder.id, folder]))
+ );
+ const uploadedAssetIds = new Set(assets.map((asset) => asset.id));
+ const entriesByAssetId = new Map(
+ entries.map((entry) => [entry.assetId, entry])
+ );
+
+ let indexed = 0;
+ let metadataUpdated = 0;
+ let unchanged = 0;
+ const issues: CanonicalAssetSynchronizationIssue[] = [];
+ await mapBounded(assets, concurrency, async (asset) => {
+ const revision = createAssetContentRevision({
+ storageName: asset.file.name,
+ updatedAt: asset.file.updatedAt,
+ size: asset.file.size,
+ contentHash: asset.file.contentHash,
+ });
+ const stored = entriesByAssetId.get(asset.id);
+ const current = stored?.revision === revision ? stored : undefined;
+ const requirementsSatisfied =
+ current !== undefined &&
+ satisfiesCanonicalAssetMetadataRequirements({
+ cached: getCanonicalAssetMetadataRequirements(current),
+ required: requirements,
+ });
+ if (current === undefined || requirementsSatisfied === false) {
+ try {
+ await indexCanonicalAsset({
+ asset,
+ client,
+ assetClient,
+ requirements,
+ base: createCanonicalBaseEntry({
+ projectId,
+ asset,
+ hierarchy,
+ revision,
+ }),
+ current,
+ });
+ indexed += 1;
+ } catch (error) {
+ const issue: CanonicalAssetSynchronizationIssue = {
+ assetId: asset.id,
+ storageName: asset.file.name,
+ revision,
+ message: getErrorMessage(error),
+ };
+ try {
+ // Never leave a previous revision visible as if it represented the
+ // current object after re-indexing failed.
+ const inconsistentRow = inconsistentRowByAssetId.get(asset.id);
+ if (inconsistentRow === undefined) {
+ await deleteObsoleteCanonicalAssetMetadata({
+ client,
+ projectId,
+ assetId: asset.id,
+ });
+ } else {
+ await deleteInvalidCanonicalAssetFileEntryIfMatches({
+ client,
+ row: inconsistentRow,
+ });
+ }
+ } catch (cleanupError) {
+ issue.message += `; stale metadata cleanup failed: ${getErrorMessage(cleanupError)}`;
+ }
+ issues.push(issue);
+ }
+ return;
+ }
+
+ const expected = createCanonicalDocument({
+ asset,
+ hierarchy,
+ revision,
+ properties: current.document.properties,
+ excerpt:
+ current.document.extension === "md"
+ ? current.document.excerpt
+ : undefined,
+ metadataError: current.document.metadataError,
+ });
+ if (hasMatchingCanonicalDocument(current.document, expected)) {
+ unchanged += 1;
+ return;
+ }
+ await replaceCanonicalAssetFileEntry({
+ client,
+ entry: createCanonicalAssetFileEntry({
+ projectId,
+ document: expected,
+ metadataRequirements: getCanonicalAssetMetadataRequirements(current),
+ }),
+ source: getCanonicalMetadataSource(asset),
+ });
+ metadataUpdated += 1;
+ });
+
+ const staleAssetIds = Array.from(
+ new Set(
+ [
+ ...entries.map((entry) => entry.assetId),
+ ...inconsistentAssetIds,
+ ].filter((assetId) => uploadedAssetIds.has(assetId) === false)
+ )
+ );
+ const removed = await deleteStaleCanonicalAssetFileEntries({
+ client,
+ projectId,
+ assetIds: staleAssetIds,
+ });
+
+ return {
+ scanned: assets.length,
+ indexed,
+ metadataUpdated,
+ unchanged,
+ removed,
+ skipped: issues.length,
+ inconsistent: inconsistentAssetIds.length,
+ issues: issues.sort((left, right) =>
+ left.assetId.localeCompare(right.assetId)
+ ),
+ };
+};
diff --git a/packages/asset-uploader/src/canonical-metadata-persistence.test.ts b/packages/asset-uploader/src/canonical-metadata-persistence.test.ts
new file mode 100644
index 0000000000..7263f74614
--- /dev/null
+++ b/packages/asset-uploader/src/canonical-metadata-persistence.test.ts
@@ -0,0 +1,256 @@
+import { describe, expect, test } from "vitest";
+import {
+ canonicalAssetMetadataExtractorGeneration,
+ createCanonicalAssetFileEntry,
+} from "@webstudio-is/content-engine/compiler";
+import {
+ createTestServer,
+ db,
+ json,
+ testContext,
+} from "@webstudio-is/postgrest/testing";
+import {
+ deleteCanonicalAssetFileEntryIfMatches,
+ deleteStaleCanonicalAssetFileEntries,
+ loadCanonicalAssetFileEntries,
+ replaceCanonicalAssetFileEntry,
+} from "./canonical-metadata-persistence";
+
+const server = createTestServer();
+const document = {
+ _id: "asset-1",
+ _type: "asset.file" as const,
+ name: "post.md",
+ path: "blog/post.md",
+ key: "post",
+ folderId: "blog",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 100,
+ revision: "sha256:one",
+ contentRef: "asset:post.md:sha256:one",
+ properties: { title: "Post" },
+ excerpt: "Post excerpt",
+};
+const entry = createCanonicalAssetFileEntry({
+ projectId: "project-1",
+ document,
+});
+const storedDocument = {
+ ...document,
+ $webstudioMetadataRequirements: "properties+excerpt",
+ $webstudioExtractorGeneration: canonicalAssetMetadataExtractorGeneration,
+};
+const row = {
+ ...entry,
+ document: storedDocument,
+ createdAt: "2026-07-18T00:00:00.000Z",
+ updatedAt: "2026-07-18T00:00:00.000Z",
+};
+
+const loadEntry = async () =>
+ (
+ await loadCanonicalAssetFileEntries({
+ client: testContext.postgrest.client,
+ projectId: "project-1",
+ })
+ )[0];
+
+describe("canonical asset metadata persistence", () => {
+ test("replaces older revisions for one canonical asset", async () => {
+ server.use(
+ db.post("rpc/replace_asset_file_metadata", async ({ request }) => {
+ expect(await request.json()).toEqual({
+ p_project_id: "project-1",
+ p_asset_id: "asset-1",
+ p_revision: "sha256:one",
+ p_document: storedDocument,
+ p_source: {
+ storageName: "stored.md",
+ fileUpdatedAt: "2026-07-18T00:00:00.000Z",
+ fileSize: 100,
+ contentHash: "a".repeat(64),
+ filename: "post.md",
+ description: "Summary",
+ folderId: "blog",
+ },
+ });
+ return json(true);
+ })
+ );
+ await expect(
+ replaceCanonicalAssetFileEntry({
+ client: testContext.postgrest.client,
+ entry,
+ source: {
+ storageName: "stored.md",
+ fileUpdatedAt: "2026-07-18T00:00:00.000Z",
+ fileSize: 100,
+ contentHash: "a".repeat(64),
+ filename: "post.md",
+ description: "Summary",
+ folderId: "blog",
+ },
+ })
+ ).resolves.toEqual(entry);
+ });
+
+ test("rejects a replacement when its source snapshot is stale", async () => {
+ server.use(db.post("rpc/replace_asset_file_metadata", () => json(false)));
+ await expect(
+ replaceCanonicalAssetFileEntry({
+ client: testContext.postgrest.client,
+ entry,
+ source: {
+ storageName: "stored.md",
+ fileUpdatedAt: "2026-07-18T00:00:00.000Z",
+ fileSize: 100,
+ },
+ })
+ ).rejects.toThrow("source changed during update");
+ });
+
+ test("loads project entries in deterministic key order", async () => {
+ server.use(
+ db.get("AssetFileMetadata", ({ request }) => {
+ expect(new URL(request.url).searchParams.get("order")).toBe(
+ "assetId.asc"
+ );
+ return json([row]);
+ })
+ );
+ await expect(
+ loadCanonicalAssetFileEntries({
+ client: testContext.postgrest.client,
+ projectId: "project-1",
+ })
+ ).resolves.toEqual([entry]);
+ });
+
+ test("loads cached metadata requirements without exposing the storage marker", async () => {
+ server.use(
+ db.get("AssetFileMetadata", () =>
+ json([
+ {
+ ...row,
+ document: {
+ ...document,
+ properties: {},
+ $webstudioMetadataRequirements: "excerpt",
+ $webstudioExtractorGeneration:
+ canonicalAssetMetadataExtractorGeneration,
+ },
+ },
+ ])
+ )
+ );
+
+ const loaded = await loadEntry();
+
+ expect(loaded?.metadataRequirements).toEqual({
+ structuredProperties: false,
+ excerpt: true,
+ });
+ expect(loaded?.document).not.toHaveProperty(
+ "$webstudioMetadataRequirements"
+ );
+ expect(loaded?.document).not.toHaveProperty(
+ "$webstudioExtractorGeneration"
+ );
+ });
+
+ test("treats metadata from an older extractor generation as unprepared", async () => {
+ server.use(
+ db.get("AssetFileMetadata", () =>
+ json([
+ {
+ ...row,
+ document: {
+ ...storedDocument,
+ $webstudioExtractorGeneration:
+ canonicalAssetMetadataExtractorGeneration - 1,
+ },
+ },
+ ])
+ )
+ );
+
+ const loaded = await loadEntry();
+
+ expect(loaded?.metadataRequirements).toEqual({
+ structuredProperties: false,
+ excerpt: false,
+ });
+ expect(loaded?.document.properties).toEqual({});
+ expect(loaded?.document).not.toHaveProperty("excerpt");
+ expect(loaded?.document).not.toHaveProperty("metadataError");
+ });
+
+ test("treats metadata without an extractor generation as unprepared", async () => {
+ const {
+ $webstudioExtractorGeneration: _extractorGeneration,
+ ...legacyDocument
+ } = storedDocument;
+ server.use(
+ db.get("AssetFileMetadata", () =>
+ json([{ ...row, document: legacyDocument }])
+ )
+ );
+
+ const loaded = await loadEntry();
+
+ expect(loaded?.metadataRequirements).toEqual({
+ structuredProperties: false,
+ excerpt: false,
+ });
+ });
+
+ test("rejects rows whose database and document identities disagree", async () => {
+ server.use(
+ db.get("AssetFileMetadata", () => json([{ ...row, assetId: "asset-2" }]))
+ );
+ await expect(loadEntry()).rejects.toThrow("identity is inconsistent");
+ });
+
+ test("requests stale deletion only for the selected project assets", async () => {
+ server.use(
+ db.post("rpc/delete_stale_asset_file_metadata", async ({ request }) => {
+ expect(await request.json()).toEqual({
+ p_project_id: "project-1",
+ p_asset_ids: ["asset-1", "asset-2"],
+ });
+ return json(2);
+ })
+ );
+ await expect(
+ deleteStaleCanonicalAssetFileEntries({
+ client: testContext.postgrest.client,
+ projectId: "project-1",
+ assetIds: ["asset-1", "asset-2"],
+ })
+ ).resolves.toBe(2);
+ });
+
+ test("deletes standard metadata only when the complete snapshot still matches", async () => {
+ server.use(
+ db.post(
+ "rpc/delete_asset_file_metadata_if_matches",
+ async ({ request }) => {
+ expect(await request.json()).toEqual({
+ p_project_id: "project-1",
+ p_asset_id: "asset-1",
+ p_revision: "sha256:one",
+ p_document: storedDocument,
+ });
+ return json(1);
+ }
+ )
+ );
+ await expect(
+ deleteCanonicalAssetFileEntryIfMatches({
+ client: testContext.postgrest.client,
+ entry,
+ })
+ ).resolves.toBe(1);
+ });
+});
diff --git a/packages/asset-uploader/src/canonical-metadata-persistence.ts b/packages/asset-uploader/src/canonical-metadata-persistence.ts
new file mode 100644
index 0000000000..20fd46b917
--- /dev/null
+++ b/packages/asset-uploader/src/canonical-metadata-persistence.ts
@@ -0,0 +1,235 @@
+import {
+ canonicalAssetMetadataExtractorGeneration,
+ createCanonicalAssetFileEntry,
+ fullCanonicalAssetMetadataRequirements,
+ getCanonicalAssetMetadataRequirements,
+ getCanonicalAssetMetadataRequirementsForTier,
+ getCanonicalAssetMetadataTier,
+ type CanonicalAssetFileEntry,
+} from "@webstudio-is/content-engine/compiler";
+import type { Client, Database } from "@webstudio-is/postgrest/index.server";
+import { assertPostgrestSuccess } from "./patch-utils";
+
+type MetadataRow = Database["public"]["Tables"]["AssetFileMetadata"]["Row"];
+
+const requirementsKey = "$webstudioMetadataRequirements";
+const extractorGenerationKey = "$webstudioExtractorGeneration";
+
+// Keep cache completeness in the stored document envelope so expanding
+// requirements can reuse a matching revision. The marker is stripped before
+// schema validation and never reaches query indexes or results.
+const serializeMetadataDocument = (entry: CanonicalAssetFileEntry) => ({
+ ...entry.document,
+ [requirementsKey]: getCanonicalAssetMetadataTier(
+ getCanonicalAssetMetadataRequirements(entry)
+ ),
+ [extractorGenerationKey]: canonicalAssetMetadataExtractorGeneration,
+});
+
+export type CanonicalAssetMetadataSource = {
+ storageName: string;
+ fileUpdatedAt: string;
+ fileSize: number;
+ contentHash?: string;
+ filename?: string;
+ description?: string;
+ folderId?: string;
+};
+
+const parseMetadataRow = (row: MetadataRow): CanonicalAssetFileEntry => {
+ if (
+ typeof row.document !== "object" ||
+ row.document === null ||
+ Array.isArray(row.document)
+ ) {
+ throw new Error("Canonical asset metadata document is invalid");
+ }
+ const {
+ [requirementsKey]: requirements,
+ [extractorGenerationKey]: extractorGeneration,
+ ...document
+ } = row.document;
+ const extractorIsCurrent =
+ extractorGeneration === canonicalAssetMetadataExtractorGeneration;
+ let documentForEntry = document;
+ if (extractorIsCurrent === false) {
+ const {
+ properties: _properties,
+ excerpt: _excerpt,
+ metadataError: _metadataError,
+ ...baseDocument
+ } = document;
+ documentForEntry = { ...baseDocument, properties: {} };
+ }
+ const entry = createCanonicalAssetFileEntry({
+ projectId: row.projectId,
+ document: documentForEntry,
+ metadataRequirements: extractorIsCurrent
+ ? requirements === undefined
+ ? fullCanonicalAssetMetadataRequirements
+ : getCanonicalAssetMetadataRequirementsForTier(requirements)
+ : { structuredProperties: false, excerpt: false },
+ });
+ if (entry.assetId !== row.assetId || entry.revision !== row.revision) {
+ throw new Error("Canonical asset metadata identity is inconsistent");
+ }
+ return entry;
+};
+
+export const replaceCanonicalAssetFileEntry = async ({
+ client,
+ entry,
+ source,
+}: {
+ client: Client;
+ entry: CanonicalAssetFileEntry;
+ source: CanonicalAssetMetadataSource;
+}): Promise<CanonicalAssetFileEntry> => {
+ if (
+ entry.document._id !== entry.assetId ||
+ entry.document.revision !== entry.revision
+ ) {
+ throw new Error("Canonical asset metadata identity is inconsistent");
+ }
+ const result = await client.rpc("replace_asset_file_metadata", {
+ p_project_id: entry.projectId,
+ p_asset_id: entry.assetId,
+ p_revision: entry.revision,
+ p_document: serializeMetadataDocument(entry),
+ p_source: {
+ storageName: source.storageName,
+ fileUpdatedAt: source.fileUpdatedAt,
+ fileSize: source.fileSize,
+ contentHash: source.contentHash ?? null,
+ filename: source.filename ?? null,
+ description: source.description ?? null,
+ folderId: source.folderId ?? null,
+ },
+ });
+ assertPostgrestSuccess(result);
+ if (result.data !== true) {
+ throw new Error("Canonical asset metadata source changed during update");
+ }
+ return entry;
+};
+
+export const deleteStaleCanonicalAssetFileEntries = async ({
+ client,
+ projectId,
+ assetIds,
+}: {
+ client: Client;
+ projectId: string;
+ assetIds: string[];
+}) => {
+ if (assetIds.length === 0) {
+ return 0;
+ }
+ const result = await client.rpc("delete_stale_asset_file_metadata", {
+ p_project_id: projectId,
+ p_asset_ids: assetIds,
+ });
+ assertPostgrestSuccess(result);
+ return result.data ?? 0;
+};
+
+export const deleteInvalidCanonicalAssetFileEntryIfMatches = async ({
+ client,
+ row,
+}: {
+ client: Client;
+ row: Pick<MetadataRow, "projectId" | "assetId" | "revision" | "document">;
+}) => {
+ const result = await client.rpc("delete_asset_file_metadata_if_matches", {
+ p_project_id: row.projectId,
+ p_asset_id: row.assetId,
+ p_revision: row.revision,
+ p_document: row.document,
+ });
+ assertPostgrestSuccess(result);
+ return result.data ?? 0;
+};
+
+export const deleteCanonicalAssetFileEntryIfMatches = async ({
+ client,
+ entry,
+}: {
+ client: Client;
+ entry: CanonicalAssetFileEntry;
+}) =>
+ await deleteInvalidCanonicalAssetFileEntryIfMatches({
+ client,
+ row: { ...entry, document: serializeMetadataDocument(entry) },
+ });
+
+const loadCanonicalAssetFileMetadataRows = async ({
+ client,
+ projectId,
+ assetIds,
+}: {
+ client: Client;
+ projectId: string;
+ assetIds?: string[];
+}): Promise<MetadataRow[]> => {
+ let query = client
+ .from("AssetFileMetadata")
+ .select()
+ .eq("projectId", projectId);
+ if (assetIds !== undefined) {
+ if (assetIds.length === 0) {
+ return [];
+ }
+ query = query.in("assetId", assetIds);
+ }
+ const result = await query.order("assetId");
+ assertPostgrestSuccess(result);
+ return result.data ?? [];
+};
+
+export const loadCanonicalAssetFileEntries = async ({
+ client,
+ projectId,
+ assetIds,
+}: {
+ client: Client;
+ projectId: string;
+ assetIds?: string[];
+}): Promise<CanonicalAssetFileEntry[]> => {
+ const rows = await loadCanonicalAssetFileMetadataRows({
+ client,
+ projectId,
+ assetIds,
+ });
+ return rows.map(parseMetadataRow);
+};
+
+export const loadCanonicalAssetFileEntriesForRecovery = async ({
+ client,
+ projectId,
+ assetIds,
+}: {
+ client: Client;
+ projectId: string;
+ assetIds?: string[];
+}) => {
+ const rows = await loadCanonicalAssetFileMetadataRows({
+ client,
+ projectId,
+ assetIds,
+ });
+ const entries: CanonicalAssetFileEntry[] = [];
+ const inconsistentRows: Array<
+ Pick<MetadataRow, "projectId" | "assetId" | "revision" | "document">
+ > = [];
+ for (const row of rows) {
+ try {
+ entries.push(parseMetadataRow(row));
+ } catch {
+ inconsistentRows.push(row);
+ }
+ }
+ return {
+ entries,
+ inconsistentRows,
+ };
+};
diff --git a/packages/asset-uploader/src/client.test.ts b/packages/asset-uploader/src/client.test.ts
new file mode 100644
index 0000000000..c7a75ac51d
--- /dev/null
+++ b/packages/asset-uploader/src/client.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, test } from "vitest";
+import { validateAssetReadRange } from "./client";
+
+describe("asset read ranges", () => {
+ test("accepts a valid range", () => {
+ expect(() =>
+ validateAssetReadRange({ offset: 2, length: 3 })
+ ).not.toThrow();
+ });
+
+ test.each([
+ { offset: -1, length: 1 },
+ { offset: 0, length: 0 },
+ { offset: 0.5, length: 1 },
+ { offset: Number.MAX_SAFE_INTEGER, length: 1 },
+ ])("rejects invalid range $offset:$length", (range) => {
+ expect(() => validateAssetReadRange(range)).toThrow(
+ "Asset read range is invalid"
+ );
+ });
+});
diff --git a/packages/asset-uploader/src/client.ts b/packages/asset-uploader/src/client.ts
index f73dad1776..b7b2f3e24a 100644
--- a/packages/asset-uploader/src/client.ts
+++ b/packages/asset-uploader/src/client.ts
@@ -1,13 +1,44 @@
import type { AssetData, AssetDataOverride } from "./utils/get-asset-data";
-export type AssetClient = {
+export type AssetReadRange = { offset: number; length: number };
+
+export type AssetInfoFallback = {
+ width: number;
+ height: number;
+ format: string;
+};
+
+export const validateAssetReadRange = (range: AssetReadRange) => {
+ const end = range.offset + range.length;
+ if (
+ Number.isSafeInteger(range.offset) === false ||
+ range.offset < 0 ||
+ Number.isSafeInteger(range.length) === false ||
+ range.length <= 0 ||
+ Number.isSafeInteger(end) === false
+ ) {
+ throw new Error("Asset read range is invalid");
+ }
+};
+
+export type AssetObjectWriter = {
uploadFile: (
name: string,
type: string,
data: AsyncIterable<Uint8Array>,
- assetInfoFallback:
- | { width: number; height: number; format: string }
- | undefined,
+ assetInfoFallback: AssetInfoFallback | undefined,
assetDataOverride?: AssetDataOverride
) => Promise<AssetData>;
};
+
+export type AssetObjectReader = {
+ readFile: (
+ name: string,
+ range?: AssetReadRange
+ ) => Promise<{
+ data: AsyncIterable<Uint8Array>;
+ contentLength?: number;
+ }>;
+};
+
+export type AssetObjectStore = AssetObjectWriter & AssetObjectReader;
diff --git a/packages/asset-uploader/src/clients/fs/fs.ts b/packages/asset-uploader/src/clients/fs/fs.ts
index 9e96273d97..ab2b050f26 100644
--- a/packages/asset-uploader/src/clients/fs/fs.ts
+++ b/packages/asset-uploader/src/clients/fs/fs.ts
@@ -1,12 +1,15 @@
-import type { AssetClient } from "../../client";
+import type { AssetObjectStore } from "../../client";
import { uploadToFs } from "./upload";
+import { readFromFs } from "./read";
type FsClientOptions = {
fileDirectory: string;
maxUploadSize: number;
};
-export const createFsClient = (options: FsClientOptions): AssetClient => {
+export const createFsAssetObjectStore = (
+ options: FsClientOptions
+): AssetObjectStore => {
return {
uploadFile: (name, type, data, _assetInfoFallback, assetDataOverride) =>
uploadToFs({
@@ -17,5 +20,7 @@ export const createFsClient = (options: FsClientOptions): AssetClient => {
fileDirectory: options.fileDirectory,
assetDataOverride,
}),
+ readFile: (name, range) =>
+ readFromFs({ name, range, fileDirectory: options.fileDirectory }),
};
};
diff --git a/packages/asset-uploader/src/clients/fs/read.test.ts b/packages/asset-uploader/src/clients/fs/read.test.ts
new file mode 100644
index 0000000000..f873b2f46c
--- /dev/null
+++ b/packages/asset-uploader/src/clients/fs/read.test.ts
@@ -0,0 +1,72 @@
+import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, test } from "vitest";
+import { readFromFs } from "./read";
+
+const directories: string[] = [];
+const collect = async (data: AsyncIterable<Uint8Array>) => {
+ const chunks: number[] = [];
+ for await (const chunk of data) {
+ chunks.push(...chunk);
+ }
+ return new TextDecoder().decode(new Uint8Array(chunks));
+};
+
+afterEach(async () => {
+ await Promise.all(
+ directories.splice(0).map((directory) => rm(directory, { recursive: true }))
+ );
+});
+
+describe("readFromFs", () => {
+ test("reads complete files and bounded byte ranges", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "asset-read-"));
+ directories.push(directory);
+ await writeFile(join(directory, "post.md"), "0123456789");
+
+ const complete = await readFromFs({
+ name: "post.md",
+ fileDirectory: directory,
+ });
+ const range = await readFromFs({
+ name: "post.md",
+ fileDirectory: directory,
+ range: { offset: 3, length: 4 },
+ });
+ expect(await collect(complete.data)).toBe("0123456789");
+ expect(complete.contentLength).toBe(10);
+ expect(await collect(range.data)).toBe("3456");
+ expect(range.contentLength).toBe(4);
+ });
+
+ test("returns an empty range beyond the end and rejects traversal", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "asset-read-"));
+ directories.push(directory);
+ await writeFile(join(directory, "post.md"), "body");
+ const empty = await readFromFs({
+ name: "post.md",
+ fileDirectory: directory,
+ range: { offset: 4, length: 1 },
+ });
+ expect(await collect(empty.data)).toBe("");
+ expect(empty.contentLength).toBe(0);
+ await expect(
+ readFromFs({ name: "../outside.md", fileDirectory: directory })
+ ).rejects.toThrow("outside the configured directory");
+ });
+
+ test("rejects symlinks outside the configured directory", async () => {
+ const parent = await mkdtemp(join(tmpdir(), "asset-read-"));
+ directories.push(parent);
+ const directory = join(parent, "assets");
+ const outside = join(parent, "outside.md");
+ await mkdir(directory);
+ await writeFile(outside, "private");
+ await symlink(outside, join(directory, "post.md"));
+
+ await expect(
+ readFromFs({ name: "post.md", fileDirectory: directory })
+ ).rejects.toThrow("outside the configured directory");
+ });
+});
diff --git a/packages/asset-uploader/src/clients/fs/read.ts b/packages/asset-uploader/src/clients/fs/read.ts
new file mode 100644
index 0000000000..6fa2db90c9
--- /dev/null
+++ b/packages/asset-uploader/src/clients/fs/read.ts
@@ -0,0 +1,71 @@
+import { createReadStream } from "node:fs";
+import { realpath, stat } from "node:fs/promises";
+import { isAbsolute, relative, resolve, sep } from "node:path";
+import {
+ type AssetObjectStore,
+ type AssetReadRange,
+ validateAssetReadRange,
+} from "../../client";
+
+const isPathInside = (root: string, path: string) => {
+ const relativePath = relative(root, path);
+ return (
+ relativePath !== "" &&
+ relativePath !== ".." &&
+ relativePath.startsWith(`..${sep}`) === false &&
+ isAbsolute(relativePath) === false
+ );
+};
+
+export const readFromFs = async ({
+ name,
+ range,
+ fileDirectory,
+}: {
+ name: string;
+ range?: AssetReadRange;
+ fileDirectory: string;
+}): ReturnType<AssetObjectStore["readFile"]> => {
+ const root = resolve(fileDirectory);
+ const filepath = resolve(root, name);
+ if (isPathInside(root, filepath) === false) {
+ throw new Error("Asset storage path is outside the configured directory");
+ }
+ const [resolvedRoot, resolvedFilepath] = await Promise.all([
+ realpath(root),
+ realpath(filepath),
+ ]);
+ if (isPathInside(resolvedRoot, resolvedFilepath) === false) {
+ throw new Error("Asset storage path is outside the configured directory");
+ }
+ if (range !== undefined) {
+ validateAssetReadRange(range);
+ }
+
+ const file = await stat(resolvedFilepath);
+ if (range !== undefined && range.offset >= file.size) {
+ return {
+ data: {
+ async *[Symbol.asyncIterator]() {
+ // A valid range beyond the end of a local file is empty.
+ },
+ },
+ contentLength: 0,
+ };
+ }
+ const stream = createReadStream(resolvedFilepath, {
+ ...(range === undefined
+ ? {}
+ : {
+ start: range.offset,
+ end: Math.min(file.size, range.offset + range.length) - 1,
+ }),
+ });
+ return {
+ data: stream,
+ contentLength:
+ range === undefined
+ ? file.size
+ : Math.max(0, Math.min(range.length, file.size - range.offset)),
+ };
+};
diff --git a/packages/asset-uploader/src/clients/s3/object-url.test.ts b/packages/asset-uploader/src/clients/s3/object-url.test.ts
new file mode 100644
index 0000000000..d23ac9fbd7
--- /dev/null
+++ b/packages/asset-uploader/src/clients/s3/object-url.test.ts
@@ -0,0 +1,14 @@
+import { describe, expect, test } from "vitest";
+import { createS3ObjectUrl } from "./object-url";
+
+describe("createS3ObjectUrl", () => {
+ test("encodes a flat asset key including separators", () => {
+ expect(
+ createS3ObjectUrl({
+ endpoint: "https://storage.example",
+ bucket: "assets",
+ key: "folder/project one",
+ }).pathname
+ ).toBe("/assets/folder%2Fproject%20one");
+ });
+});
diff --git a/packages/asset-uploader/src/clients/s3/object-url.ts b/packages/asset-uploader/src/clients/s3/object-url.ts
new file mode 100644
index 0000000000..db6c3029d3
--- /dev/null
+++ b/packages/asset-uploader/src/clients/s3/object-url.ts
@@ -0,0 +1,11 @@
+import { extendedEncodeURIComponent } from "../../utils/sanitize-s3-key";
+
+export const createS3ObjectUrl = ({
+ endpoint,
+ bucket,
+ key,
+}: {
+ endpoint: string;
+ bucket: string;
+ key: string;
+}) => new URL(`/${bucket}/${extendedEncodeURIComponent(key)}`, endpoint);
diff --git a/packages/asset-uploader/src/clients/s3/read.test.ts b/packages/asset-uploader/src/clients/s3/read.test.ts
new file mode 100644
index 0000000000..18f704b65e
--- /dev/null
+++ b/packages/asset-uploader/src/clients/s3/read.test.ts
@@ -0,0 +1,68 @@
+import { afterEach, describe, expect, test, vi } from "vitest";
+import type { SignatureV4 } from "@smithy/signature-v4";
+import { readFromS3 } from "./read";
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe("readFromS3", () => {
+ test("signs and performs a bounded GET", async () => {
+ const sign = vi.fn(async (request) => request);
+ const fetch = vi.fn(
+ async () =>
+ new Response("body", {
+ status: 206,
+ headers: { "content-length": "4" },
+ })
+ );
+ vi.stubGlobal("fetch", fetch);
+
+ const result = await readFromS3({
+ signer: { sign } as unknown as SignatureV4,
+ name: "folder/post.md",
+ range: { offset: 10, length: 4 },
+ endpoint: "https://storage.example",
+ bucket: "assets",
+ });
+
+ expect(sign).toHaveBeenCalledWith(
+ expect.objectContaining({
+ method: "GET",
+ path: "/assets/folder%2Fpost.md",
+ headers: expect.objectContaining({ Range: "bytes=10-13" }),
+ })
+ );
+ expect(fetch).toHaveBeenCalledWith(
+ new URL("https://storage.example/assets/folder%2Fpost.md"),
+ expect.objectContaining({ method: "GET" })
+ );
+ expect(result.contentLength).toBe(4);
+ });
+
+ test("rejects ignored ranges and invalid inputs", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => new Response("whole file"))
+ );
+ const signer = {
+ sign: async <Request>(request: Request) => request,
+ } as unknown as SignatureV4;
+ await expect(
+ readFromS3({
+ signer,
+ name: "post.md",
+ range: { offset: 1, length: 1 },
+ endpoint: "https://storage.example",
+ bucket: "assets",
+ })
+ ).rejects.toThrow("did not honor");
+ await expect(
+ readFromS3({
+ signer,
+ name: "post.md",
+ range: { offset: -1, length: 1 },
+ endpoint: "https://storage.example",
+ bucket: "assets",
+ })
+ ).rejects.toThrow("range is invalid");
+ });
+});
diff --git a/packages/asset-uploader/src/clients/s3/read.ts b/packages/asset-uploader/src/clients/s3/read.ts
new file mode 100644
index 0000000000..20db35452b
--- /dev/null
+++ b/packages/asset-uploader/src/clients/s3/read.ts
@@ -0,0 +1,57 @@
+import type { SignatureV4 } from "@smithy/signature-v4";
+import {
+ type AssetObjectStore,
+ type AssetReadRange,
+ validateAssetReadRange,
+} from "../../client";
+import { createS3ObjectUrl } from "./object-url";
+import { createS3FetchHeaders, signS3Request } from "./request-headers";
+
+export const readFromS3 = async ({
+ signer,
+ name,
+ range,
+ endpoint,
+ bucket,
+}: {
+ signer: SignatureV4;
+ name: string;
+ range?: AssetReadRange;
+ endpoint: string;
+ bucket: string;
+}): ReturnType<AssetObjectStore["readFile"]> => {
+ if (range !== undefined) {
+ validateAssetReadRange(range);
+ }
+ const url = createS3ObjectUrl({ endpoint, bucket, key: name });
+ const headers = {
+ "x-amz-content-sha256": "UNSIGNED-PAYLOAD",
+ ...(range === undefined
+ ? {}
+ : { Range: `bytes=${range.offset}-${range.offset + range.length - 1}` }),
+ };
+ const request = await signS3Request({
+ signer,
+ url,
+ method: "GET",
+ headers,
+ });
+ const response = await fetch(url, {
+ method: request.method,
+ headers: createS3FetchHeaders(request.headers),
+ });
+ if (response.ok === false || response.body === null) {
+ throw new Error("Cannot read asset file");
+ }
+ if (range !== undefined && response.status !== 206) {
+ throw new Error("Asset storage did not honor the requested range");
+ }
+ const contentLengthHeader = response.headers.get("content-length");
+ const contentLength = Number(contentLengthHeader);
+ return {
+ data: response.body as unknown as AsyncIterable<Uint8Array>,
+ ...(contentLengthHeader !== null && Number.isFinite(contentLength)
+ ? { contentLength }
+ : {}),
+ };
+};
diff --git a/packages/asset-uploader/src/clients/s3/request-headers.test.ts b/packages/asset-uploader/src/clients/s3/request-headers.test.ts
new file mode 100644
index 0000000000..879ab85f20
--- /dev/null
+++ b/packages/asset-uploader/src/clients/s3/request-headers.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, test } from "vitest";
+import {
+ createS3FetchHeaders,
+ createS3SigningHeaders,
+} from "./request-headers";
+
+describe("S3 request headers", () => {
+ test("signs the exact host including a non-default port", () => {
+ const signed = createS3SigningHeaders(
+ new URL("http://localhost:9000/bucket/object"),
+ { "x-amz-content-sha256": "UNSIGNED-PAYLOAD" }
+ );
+
+ expect(signed.host).toBe("localhost:9000");
+ expect(createS3FetchHeaders(signed).has("host")).toBe(false);
+ });
+});
diff --git a/packages/asset-uploader/src/clients/s3/request-headers.ts b/packages/asset-uploader/src/clients/s3/request-headers.ts
new file mode 100644
index 0000000000..0ebc023f41
--- /dev/null
+++ b/packages/asset-uploader/src/clients/s3/request-headers.ts
@@ -0,0 +1,42 @@
+import type { SignatureV4 } from "@smithy/signature-v4";
+
+/**
+ * SigV4 requires `host` in the canonical signed headers. Fetch supplies the
+ * actual Host header from the URL, so sign that exact value but do not attempt
+ * to set the transport-controlled header explicitly.
+ */
+export const createS3SigningHeaders = (
+ url: URL,
+ headers: Record<string, string>
+) => ({ ...headers, host: url.host });
+
+export const createS3FetchHeaders = (headers: Record<string, string>) => {
+ const result = new Headers(headers);
+ result.delete("host");
+ return result;
+};
+
+export const signS3Request = async ({
+ signer,
+ url,
+ method,
+ headers,
+ body,
+ query,
+}: {
+ signer: SignatureV4;
+ url: URL;
+ method: string;
+ headers: Record<string, string>;
+ body?: ArrayBuffer | Uint8Array;
+ query?: Record<string, string>;
+}) =>
+ await signer.sign({
+ method,
+ protocol: url.protocol,
+ hostname: url.hostname,
+ path: url.pathname,
+ ...(query === undefined ? {} : { query }),
+ headers: createS3SigningHeaders(url, headers),
+ ...(body === undefined ? {} : { body }),
+ });
diff --git a/packages/asset-uploader/src/clients/s3/s3.ts b/packages/asset-uploader/src/clients/s3/s3.ts
index bdf26dab2f..1da1921be5 100644
--- a/packages/asset-uploader/src/clients/s3/s3.ts
+++ b/packages/asset-uploader/src/clients/s3/s3.ts
@@ -1,20 +1,24 @@
import { Sha256 } from "@aws-crypto/sha256-js";
import { SignatureV4 } from "@smithy/signature-v4";
-import type { AssetClient } from "../../client";
+import type { AssetObjectStore } from "../../client";
import { uploadToS3 } from "./upload";
+import { readFromS3 } from "./read";
-type S3ClientOptions = {
+type S3StorageOptions = {
endpoint: string;
region: string;
accessKeyId: string;
secretAccessKey: string;
bucket: string;
+};
+
+export type S3ClientOptions = S3StorageOptions & {
acl?: string;
maxUploadSize: number;
};
-export const createS3Client = (options: S3ClientOptions): AssetClient => {
- const signer = new SignatureV4({
+const createS3Signer = (options: S3StorageOptions) =>
+ new SignatureV4({
credentials: {
accessKeyId: options.accessKeyId,
secretAccessKey: options.secretAccessKey,
@@ -22,11 +26,15 @@ export const createS3Client = (options: S3ClientOptions): AssetClient => {
region: options.region,
service: "s3",
sha256: Sha256,
- // should never be enabled when work with s3
+ // Paths are encoded centrally by createS3ObjectUrl.
uriEscapePath: false,
});
- const uploadFile: AssetClient["uploadFile"] = async (
+export const createS3AssetObjectStore = (
+ options: S3ClientOptions
+): AssetObjectStore => {
+ const signer = createS3Signer(options);
+ const uploadFile: AssetObjectStore["uploadFile"] = async (
name,
type,
data,
@@ -49,5 +57,13 @@ export const createS3Client = (options: S3ClientOptions): AssetClient => {
return {
uploadFile,
+ readFile: (name, range) =>
+ readFromS3({
+ signer,
+ name,
+ range,
+ endpoint: options.endpoint,
+ bucket: options.bucket,
+ }),
};
};
diff --git a/packages/asset-uploader/src/clients/s3/upload.ts b/packages/asset-uploader/src/clients/s3/upload.ts
index f46f17a796..654f1a4787 100644
--- a/packages/asset-uploader/src/clients/s3/upload.ts
+++ b/packages/asset-uploader/src/clients/s3/upload.ts
@@ -7,8 +7,10 @@ import {
getAssetData,
} from "../../utils/get-asset-data";
import { createSizeLimiter } from "../../utils/size-limiter";
-import { extendedEncodeURIComponent } from "../../utils/sanitize-s3-key";
import { getMimeTypeByFilename } from "@webstudio-is/sdk";
+import { createS3ObjectUrl } from "./object-url";
+import { createS3FetchHeaders, signS3Request } from "./request-headers";
+import type { AssetInfoFallback } from "../../client";
export const uploadToS3 = async ({
signer,
@@ -30,9 +32,7 @@ export const uploadToS3 = async ({
endpoint: string;
bucket: string;
acl?: string;
- assetInfoFallback:
- | { width: number; height: number; format: string }
- | undefined;
+ assetInfoFallback: AssetInfoFallback | undefined;
assetDataOverride?: AssetDataOverride;
}): Promise<AssetData> => {
const limitSize = createSizeLimiter(maxSize, name);
@@ -43,10 +43,11 @@ export const uploadToS3 = async ({
// Also check if S3 client has an option to check the size limit
const data = await arrayBuffer(limitSize(dataStream));
- const url = new URL(
- `/${bucket}/${extendedEncodeURIComponent(name)}`,
- endpoint
- );
+ const url = createS3ObjectUrl({
+ endpoint,
+ bucket,
+ key: name,
+ });
// Use proper MIME type based on file extension instead of generic type category
const contentType = getMimeTypeByFilename(name);
@@ -74,13 +75,11 @@ export const uploadToS3 = async ({
assetDataOverride
);
- const s3Request = await signer.sign({
+ const s3Request = await signS3Request({
+ signer,
+ url,
method: "PUT",
- protocol: url.protocol,
- hostname: url.hostname,
- path: url.pathname,
headers: {
- "x-amz-date": new Date().toISOString(),
"Content-Type": contentType,
"Content-Length": `${data.byteLength}`,
"Cache-Control": "public, max-age=31536004,immutable",
@@ -95,7 +94,7 @@ export const uploadToS3 = async ({
const response = await fetch(url, {
method: s3Request.method,
- headers: s3Request.headers,
+ headers: createS3FetchHeaders(s3Request.headers),
body: data,
});
diff --git a/packages/asset-uploader/src/content-compilation-cache.test.ts b/packages/asset-uploader/src/content-compilation-cache.test.ts
new file mode 100644
index 0000000000..72211619d9
--- /dev/null
+++ b/packages/asset-uploader/src/content-compilation-cache.test.ts
@@ -0,0 +1,121 @@
+import { describe, expect, test, vi } from "vitest";
+import type { ContentArtifactV1 } from "@webstudio-is/content-engine";
+import {
+ canonicalAssetMetadataExtractorGeneration,
+ createAssetIndex,
+} from "@webstudio-is/content-engine/compiler";
+import {
+ createContentCompilationCache,
+ createContentCompilationCacheKey,
+ getContentDatabaseForArtifact,
+} from "./content-compilation-cache";
+
+const artifact = (revision: string) =>
+ ({ integrity: { checksum: revision } }) as ContentArtifactV1;
+
+describe("content compilation cache", () => {
+ test("keys compiled artifacts by metadata extraction generation", () => {
+ const key = createContentCompilationCacheKey({
+ projectId: "project",
+ sourceRevision: "source",
+ strict: false,
+ maxBytes: 500,
+ });
+
+ expect(JSON.parse(key)).toMatchObject({
+ metadataExtractorGeneration: canonicalAssetMetadataExtractorGeneration,
+ });
+ });
+
+ test("coalesces concurrent compilation for the same normalized key", async () => {
+ const cache = createContentCompilationCache();
+ const key = createContentCompilationCacheKey({
+ projectId: "project",
+ sourceRevision: "source",
+ strict: false,
+ maxBytes: 500,
+ });
+ const create = vi.fn(async () => artifact("compiled"));
+
+ const [first, second] = await Promise.all([
+ cache.getOrCreate(key, create),
+ cache.getOrCreate(key, create),
+ ]);
+
+ expect(first).toBe(second);
+ expect(create).toHaveBeenCalledOnce();
+ });
+
+ test("does not evict in-flight compilation when the cache is full", async () => {
+ const cache = createContentCompilationCache(1);
+ let resolveFirst: (value: ContentArtifactV1) => void = () => {};
+ let resolveSecond: (value: ContentArtifactV1) => void = () => {};
+ const first = new Promise<ContentArtifactV1>((resolve) => {
+ resolveFirst = resolve;
+ });
+ const second = new Promise<ContentArtifactV1>((resolve) => {
+ resolveSecond = resolve;
+ });
+ const recreate = vi.fn(async () => artifact("duplicate"));
+
+ const pendingFirst = cache.getOrCreate("first", () => first);
+ const pendingSecond = cache.getOrCreate("second", () => second);
+
+ expect(cache.size).toBe(2);
+ expect(cache.getOrCreate("first", recreate)).toBe(pendingFirst);
+ expect(recreate).not.toHaveBeenCalled();
+
+ resolveFirst(artifact("first"));
+ await pendingFirst;
+ expect(cache.size).toBe(1);
+
+ resolveSecond(artifact("second"));
+ await pendingSecond;
+ });
+
+ test("removes rejected work so a later request can retry", async () => {
+ const cache = createContentCompilationCache();
+ const create = vi
+ .fn<() => Promise<ContentArtifactV1>>()
+ .mockRejectedValueOnce(new Error("failed"))
+ .mockResolvedValueOnce(artifact("retried"));
+
+ await expect(cache.getOrCreate("key", create)).rejects.toThrow("failed");
+ await expect(cache.getOrCreate("key", create)).resolves.toMatchObject({
+ integrity: { checksum: "retried" },
+ });
+ expect(create).toHaveBeenCalledTimes(2);
+ });
+
+ test("evicts the least recently used completed entry", async () => {
+ const cache = createContentCompilationCache(2);
+ await cache.getOrCreate("first", async () => artifact("first"));
+ await cache.getOrCreate("second", async () => artifact("second"));
+ await cache.getOrCreate("first", async () => artifact("unused"));
+ await cache.getOrCreate("third", async () => artifact("third"));
+ const recreate = vi.fn(async () => artifact("second-again"));
+
+ await cache.getOrCreate("second", recreate);
+
+ expect(recreate).toHaveBeenCalledOnce();
+ expect(cache.size).toBe(2);
+ });
+
+ test("reuses a storage-neutral database for one immutable artifact", async () => {
+ const compiled = await createAssetIndex({
+ projectId: "project",
+ entries: [],
+ });
+ const equivalent = await createAssetIndex({
+ projectId: "project",
+ entries: [],
+ });
+
+ expect(getContentDatabaseForArtifact(compiled)).toBe(
+ getContentDatabaseForArtifact(compiled)
+ );
+ expect(getContentDatabaseForArtifact(equivalent)).not.toBe(
+ getContentDatabaseForArtifact(compiled)
+ );
+ });
+});
diff --git a/packages/asset-uploader/src/content-compilation-cache.ts b/packages/asset-uploader/src/content-compilation-cache.ts
new file mode 100644
index 0000000000..a1a22216cd
--- /dev/null
+++ b/packages/asset-uploader/src/content-compilation-cache.ts
@@ -0,0 +1,107 @@
+import {
+ createContentDatabase,
+ type ContentArtifactV1,
+ type ContentCompilationPlan,
+} from "@webstudio-is/content-engine";
+import {
+ canonicalAssetMetadataExtractorGeneration,
+ serializeJsonDeterministically,
+} from "@webstudio-is/content-engine/compiler";
+
+export type ContentCompilationCache = ReturnType<
+ typeof createContentCompilationCache
+>;
+
+export const createContentCompilationCacheKey = ({
+ projectId,
+ sourceRevision,
+ plan,
+ strict,
+ maxBytes,
+}: {
+ projectId: string;
+ sourceRevision: string;
+ plan?: ContentCompilationPlan;
+ strict: boolean;
+ maxBytes: number;
+}) =>
+ serializeJsonDeterministically({
+ projectId,
+ sourceRevision,
+ metadataExtractorGeneration: canonicalAssetMetadataExtractorGeneration,
+ plan: plan ?? null,
+ strict,
+ maxBytes,
+ });
+
+export const createContentCompilationCache = (maximumEntries = 32) => {
+ if (Number.isSafeInteger(maximumEntries) === false || maximumEntries <= 0) {
+ throw new Error("Content compilation cache size must be positive");
+ }
+ type CacheEntry = {
+ promise: Promise<ContentArtifactV1>;
+ settled: boolean;
+ };
+ const entries = new Map<string, CacheEntry>();
+ const trim = () => {
+ while (entries.size > maximumEntries) {
+ const completed = [...entries].find(([, entry]) => entry.settled);
+ if (completed === undefined) {
+ return;
+ }
+ entries.delete(completed[0]);
+ }
+ };
+ return {
+ getOrCreate: (
+ key: string,
+ create: () => Promise<ContentArtifactV1>
+ ): Promise<ContentArtifactV1> => {
+ const existing = entries.get(key);
+ if (existing !== undefined) {
+ entries.delete(key);
+ entries.set(key, existing);
+ return existing.promise;
+ }
+ let entry: CacheEntry;
+ const promise = create().then(
+ (value) => {
+ entry.settled = true;
+ trim();
+ return value;
+ },
+ (error) => {
+ if (entries.get(key) === entry) {
+ entries.delete(key);
+ }
+ throw error;
+ }
+ );
+ entry = { promise, settled: false };
+ entries.set(key, entry);
+ trim();
+ return entry.promise;
+ },
+ clear: () => entries.clear(),
+ get size() {
+ return entries.size;
+ },
+ };
+};
+
+export const sharedContentCompilationCache = createContentCompilationCache();
+
+const databaseByArtifact = new WeakMap<
+ ContentArtifactV1,
+ ReturnType<typeof createContentDatabase>
+>();
+
+export const getContentDatabaseForArtifact = (artifact: ContentArtifactV1) => {
+ const existing = databaseByArtifact.get(artifact);
+ if (existing !== undefined) {
+ return existing;
+ }
+ const database = createContentDatabase({ artifact });
+ databaseByArtifact.set(artifact, database);
+ return database;
+};
diff --git a/packages/asset-uploader/src/content-hash.ts b/packages/asset-uploader/src/content-hash.ts
index 119fa39b1e..eea9b46813 100644
--- a/packages/asset-uploader/src/content-hash.ts
+++ b/packages/asset-uploader/src/content-hash.ts
@@ -1,5 +1,3 @@
-export { getAssetContentHash as getContentHash } from "@webstudio-is/sdk";
-
const contentHashPattern = /^[a-f0-9]{64}$/;
export const isContentHash = (value: unknown): value is string =>
diff --git a/packages/asset-uploader/src/field-catalog.ts b/packages/asset-uploader/src/field-catalog.ts
new file mode 100644
index 0000000000..cd84b637c7
--- /dev/null
+++ b/packages/asset-uploader/src/field-catalog.ts
@@ -0,0 +1,20 @@
+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+import type { AssetObjectStore } from "./client";
+import { PostgresAssetRepository } from "./asset-repository";
+
+export const loadBuilderAssetFieldCatalog = async ({
+ projectId,
+ context,
+ assetClient,
+}: {
+ projectId: string;
+ context: AppContext;
+ assetClient: Pick<AssetObjectStore, "readFile">;
+}) => {
+ const repository = new PostgresAssetRepository({
+ projectId,
+ context,
+ assetStore: assetClient,
+ });
+ return await repository.readFieldCatalog();
+};
diff --git a/packages/asset-uploader/src/folder-persistence.ts b/packages/asset-uploader/src/folder-persistence.ts
index bd06d19ada..4e714a3b14 100644
--- a/packages/asset-uploader/src/folder-persistence.ts
+++ b/packages/asset-uploader/src/folder-persistence.ts
@@ -10,6 +10,66 @@ import {
diffMaps,
type Patch,
} from "./patch-utils";
+import { AssetRepositoryConflictError } from "./asset-repository-errors";
+
+const pendingProjectMutations = new Map<string, Promise<void>>();
+
+const repairAssetFolderCycles = (folders: readonly AssetFolder[]) => {
+ const repaired = new Map(folders.map((folder) => [folder.id, folder]));
+ const repairedIds: string[] = [];
+
+ while (true) {
+ const hierarchy = createAssetFolderHierarchy(repaired);
+ let cycleIds: readonly string[] | undefined;
+ for (const startId of [...repaired.keys()].sort()) {
+ const candidate = hierarchy.getCycleIds(startId);
+ if (candidate.length > 0) {
+ cycleIds = candidate;
+ break;
+ }
+ }
+ if (cycleIds === undefined) {
+ break;
+ }
+
+ // Concurrent moves do not provide enough information to infer which move
+ // the user preferred. Detach the same edge on every process so a persisted
+ // cycle cannot make folder reads, asset paths, or publication unavailable.
+ const folderId = [...cycleIds].sort().at(-1) as string;
+ const folder = repaired.get(folderId) as AssetFolder;
+ repaired.set(folderId, { ...folder, parentId: undefined });
+ repairedIds.push(folderId);
+ }
+
+ return { folders: [...repaired.values()], repairedIds };
+};
+
+/**
+ * Serializes folder mutations handled by this process so each validation reads
+ * the result of the preceding write. Separate application instances cannot
+ * share this lock; database constraints remain the final protection for
+ * references and sibling uniqueness.
+ */
+const withAssetFolderMutationLock = async <Result>(
+ projectId: string,
+ mutate: () => Promise<Result>
+): Promise<Result> => {
+ const previous = pendingProjectMutations.get(projectId) ?? Promise.resolve();
+ let release = () => {};
+ const current = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ pendingProjectMutations.set(projectId, current);
+ await previous;
+ try {
+ return await mutate();
+ } finally {
+ release();
+ if (pendingProjectMutations.get(projectId) === current) {
+ pendingProjectMutations.delete(projectId);
+ }
+ }
+};
export const createAssetFolderRows = (
folders: Iterable<AssetFolder>,
@@ -28,7 +88,7 @@ export const createAssetFolderRows = (
}));
};
-export const loadAssetFoldersByProjectWithClient = async (
+const loadAssetFoldersByProjectRaw = async (
projectId: string,
client: Client
): Promise<AssetFolder[]> => {
@@ -48,61 +108,229 @@ export const loadAssetFoldersByProjectWithClient = async (
}));
};
-export const patchAssetFoldersWithClient = async (
- { projectId, client }: { projectId: string; client: Client },
- patches: Array<Patch>,
- { deferDeletes = false }: { deferDeletes?: boolean } = {}
-): Promise<string[]> => {
- const currentList = await loadAssetFoldersByProjectWithClient(
- projectId,
- client
- );
- const current = new Map(currentList.map((folder) => [folder.id, folder]));
- const validated = applyValidatedMapPatches(current, patches, (value) =>
- assetFolders.parse(value)
- );
- for (const folder of validated.values()) {
- if (folder.projectId !== projectId) {
- throw new Error(`Asset folder ${folder.id} belongs to another project`);
+export const loadAssetFoldersByProjectWithClient = async (
+ projectId: string,
+ client: Client,
+ folderIds?: string[]
+): Promise<AssetFolder[]> => {
+ if (folderIds?.length === 0) {
+ return [];
+ }
+ // Cycle detection needs the complete graph even when the caller only wants
+ // one folder. Repair first, then narrow the returned collection.
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ const folders = await loadAssetFoldersByProjectRaw(projectId, client);
+ const repaired = repairAssetFolderCycles(folders);
+ const originalById = new Map(folders.map((folder) => [folder.id, folder]));
+ let sourceChanged = false;
+ for (const folderId of repaired.repairedIds) {
+ const original = originalById.get(folderId);
+ if (original?.parentId === undefined) {
+ continue;
+ }
+ const result = await client
+ .from("AssetFolder")
+ .update({ parentId: null })
+ .eq("id", folderId)
+ .eq("projectId", projectId)
+ .eq("parentId", original.parentId)
+ .select("id");
+ assertPostgrestSuccess(result);
+ if (result.data?.some(({ id }) => id === folderId) !== true) {
+ sourceChanged = true;
+ break;
+ }
+ }
+ if (sourceChanged) {
+ continue;
}
+ if (folderIds === undefined) {
+ return repaired.folders;
+ }
+ const selectedIds = new Set(folderIds);
+ return repaired.folders.filter(({ id }) => selectedIds.has(id));
}
+ throw new AssetRepositoryConflictError(
+ "Asset folders changed repeatedly while repairing a cycle"
+ );
+};
+
+const getPersistedFolderCycles = async (projectId: string, client: Client) =>
+ repairAssetFolderCycles(await loadAssetFoldersByProjectRaw(projectId, client))
+ .repairedIds;
+
+const restoreAssetFolder = async ({
+ projectId,
+ previous,
+ persisted,
+ client,
+}: {
+ projectId: string;
+ previous: AssetFolder | undefined;
+ persisted: AssetFolder;
+ client: Client;
+}) => {
+ const table = client.from("AssetFolder");
+ let match = (
+ previous === undefined
+ ? table.delete()
+ : table.update({
+ name: previous.name,
+ parentId: previous.parentId ?? null,
+ })
+ )
+ .eq("id", persisted.id)
+ .eq("projectId", projectId)
+ .eq("name", persisted.name);
+ match =
+ persisted.parentId === undefined
+ ? match.is("parentId", null)
+ : match.eq("parentId", persisted.parentId);
+ const result = await match.select("id");
+ assertPostgrestSuccess(result);
+};
- const { added, updated, deletedKeys } = diffMaps(
- current,
- validated,
- (previous, folder) =>
- previous.name === folder.name && previous.parentId === folder.parentId
+const verifyAndRollbackFolderMutation = async ({
+ projectId,
+ previousById,
+ persisted,
+ client,
+}: {
+ projectId: string;
+ previousById: ReadonlyMap<string, AssetFolder>;
+ persisted: readonly AssetFolder[];
+ client: Client;
+}) => {
+ if ((await getPersistedFolderCycles(projectId, client)).length === 0) {
+ return;
+ }
+ for (const folder of [...persisted].reverse()) {
+ await restoreAssetFolder({
+ projectId,
+ previous: previousById.get(folder.id),
+ persisted: folder,
+ client,
+ });
+ }
+ throw new AssetRepositoryConflictError(
+ "Folder update conflicted with another move and was reverted"
);
- const changed = [...added, ...updated];
- if (changed.length > 0) {
+};
+
+export const upsertAssetFolderWithClient = async (
+ {
+ projectId,
+ folder,
+ }: {
+ projectId: string;
+ folder: AssetFolder;
+ },
+ client: Client
+): Promise<AssetFolder> =>
+ await withAssetFolderMutationLock(projectId, async () => {
+ const current = new Map(
+ (await loadAssetFoldersByProjectWithClient(projectId, client)).map(
+ (item) => [item.id, item]
+ )
+ );
+ const validated = assetFolders.parse(
+ new Map(current).set(folder.id, folder)
+ );
+ const value = validated.get(folder.id);
+ if (value === undefined) {
+ throw new Error("Asset folder was not validated");
+ }
const result = await client
.from("AssetFolder")
- .upsert(createAssetFolderRows(changed, projectId), {
+ .upsert(createAssetFolderRows([value], projectId), {
onConflict: "id,projectId",
})
- .select("id, name, parentId");
+ .select("id, projectId, name, parentId, createdAt")
+ .single();
assertPostgrestSuccess(result);
- const persisted = new Map((result.data ?? []).map((row) => [row.id, row]));
- for (const folder of changed) {
- const row = persisted.get(folder.id);
- if (
- row?.name !== folder.name ||
- (row.parentId ?? undefined) !== folder.parentId
- ) {
- throw new Error(
- `Asset folder update was not persisted for ${folder.id}`
- );
+ if (result.data?.id !== value.id) {
+ throw new Error("Asset folder was not persisted");
+ }
+ const persisted = {
+ id: result.data.id,
+ projectId: result.data.projectId,
+ name: result.data.name,
+ parentId: result.data.parentId ?? undefined,
+ createdAt: result.data.createdAt,
+ };
+ await verifyAndRollbackFolderMutation({
+ projectId,
+ previousById: current,
+ persisted: [persisted],
+ client,
+ });
+ return persisted;
+ });
+
+export const patchAssetFoldersWithClient = async (
+ { projectId, client }: { projectId: string; client: Client },
+ patches: Array<Patch>,
+ { deferDeletes = false }: { deferDeletes?: boolean } = {}
+): Promise<string[]> =>
+ await withAssetFolderMutationLock(projectId, async () => {
+ const currentList = await loadAssetFoldersByProjectWithClient(
+ projectId,
+ client
+ );
+ const current = new Map(currentList.map((folder) => [folder.id, folder]));
+ const validated = applyValidatedMapPatches(current, patches, (value) =>
+ assetFolders.parse(value)
+ );
+ for (const folder of validated.values()) {
+ if (folder.projectId !== projectId) {
+ throw new Error(`Asset folder ${folder.id} belongs to another project`);
}
}
- }
- if (deletedKeys.length > 0 && deferDeletes === false) {
- await deleteAssetFoldersWithClient({ projectId, ids: deletedKeys }, client);
- }
- return deletedKeys;
-};
+ const { added, updated, deletedKeys } = diffMaps(
+ current,
+ validated,
+ (previous, folder) =>
+ previous.name === folder.name && previous.parentId === folder.parentId
+ );
+ const changed = [...added, ...updated];
+ if (changed.length > 0) {
+ const result = await client
+ .from("AssetFolder")
+ .upsert(createAssetFolderRows(changed, projectId), {
+ onConflict: "id,projectId",
+ })
+ .select("id, name, parentId");
+ assertPostgrestSuccess(result);
+ const persisted = new Map(
+ (result.data ?? []).map((row) => [row.id, row])
+ );
+ for (const folder of changed) {
+ const row = persisted.get(folder.id);
+ if (
+ row?.name !== folder.name ||
+ (row.parentId ?? undefined) !== folder.parentId
+ ) {
+ throw new Error(
+ `Asset folder update was not persisted for ${folder.id}`
+ );
+ }
+ }
+ await verifyAndRollbackFolderMutation({
+ projectId,
+ previousById: current,
+ persisted: changed,
+ client,
+ });
+ }
-export const deleteAssetFoldersWithClient = async (
+ if (deletedKeys.length > 0 && deferDeletes === false) {
+ await deleteAssetFoldersUnlocked({ projectId, ids: deletedKeys }, client);
+ }
+ return deletedKeys;
+ });
+
+const deleteAssetFoldersUnlocked = async (
{ projectId, ids }: { projectId: string; ids: string[] },
client: Client
) => {
@@ -122,3 +350,11 @@ export const deleteAssetFoldersWithClient = async (
throw new Error(`Asset folder deletion was not persisted for ${missingId}`);
}
};
+
+export const deleteAssetFoldersWithClient = async (
+ props: { projectId: string; ids: string[] },
+ client: Client
+) =>
+ await withAssetFolderMutationLock(props.projectId, async () => {
+ await deleteAssetFoldersUnlocked(props, client);
+ });
diff --git a/packages/asset-uploader/src/patch.test.ts b/packages/asset-uploader/src/patch.test.ts
index b069c0bd1c..8d8b2bd7a7 100644
--- a/packages/asset-uploader/src/patch.test.ts
+++ b/packages/asset-uploader/src/patch.test.ts
@@ -9,12 +9,17 @@ import {
} from "@webstudio-is/postgrest/testing";
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
import {
+ deleteAssetsWithClient,
loadAssetsByProjectWithClient,
patchAssetsWithClient,
+ updateAssetMetadataWithClient,
} from "./asset-patch-core";
+import { AssetRepositoryNotFoundError } from "./asset-repository-errors";
import {
deleteAssetFoldersWithClient,
+ loadAssetFoldersByProjectWithClient,
patchAssetFoldersWithClient,
+ upsertAssetFolderWithClient,
} from "./folder-persistence";
import { patchAssets } from "./patch";
import type { Patch } from "immer";
@@ -40,6 +45,276 @@ const ownershipHandler = db.get("Project", ({ request }) => {
});
describe("asset folder persistence", () => {
+ test("validates and upserts one REST folder mutation", async () => {
+ const projectId = uid();
+ const folder = {
+ id: "blog",
+ projectId,
+ name: "Blog",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ };
+ server.use(
+ db.get("AssetFolder", () => json([])),
+ db.post("AssetFolder", async ({ request }) => {
+ expect(await request.json()).toEqual([{ ...folder, parentId: null }]);
+ return json({ ...folder, parentId: null });
+ })
+ );
+
+ await expect(
+ upsertAssetFolderWithClient(
+ { projectId, folder },
+ testContext.postgrest.client
+ )
+ ).resolves.toEqual(folder);
+ });
+
+ test("rejects a REST folder with a missing parent before persistence", async () => {
+ const projectId = uid();
+ server.use(db.get("AssetFolder", () => json([])));
+
+ await expect(
+ upsertAssetFolderWithClient(
+ {
+ projectId,
+ folder: {
+ id: "blog",
+ projectId,
+ name: "Blog",
+ parentId: "missing",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ },
+ },
+ testContext.postgrest.client
+ )
+ ).rejects.toThrow("Parent folder must exist");
+ });
+
+ test("serializes concurrent folder updates before validating cycles", async () => {
+ const projectId = uid();
+ const createdAt = "2026-01-01T00:00:00.000Z";
+ let folders: Array<{
+ id: string;
+ projectId: string;
+ name: string;
+ parentId: string | null;
+ createdAt: string;
+ }> = [
+ { id: "a", projectId, name: "A", parentId: null, createdAt },
+ { id: "b", projectId, name: "B", parentId: null, createdAt },
+ ];
+ let readCount = 0;
+ let writeCount = 0;
+ let startFirstWrite = () => {};
+ const firstWriteStarted = new Promise<void>((resolve) => {
+ startFirstWrite = resolve;
+ });
+ let releaseFirstWrite = () => {};
+ const firstWriteCanFinish = new Promise<void>((resolve) => {
+ releaseFirstWrite = resolve;
+ });
+ server.use(
+ db.get("AssetFolder", () => {
+ readCount += 1;
+ return json(folders);
+ }),
+ db.post("AssetFolder", async ({ request }) => {
+ writeCount += 1;
+ if (writeCount === 1) {
+ startFirstWrite();
+ await firstWriteCanFinish;
+ }
+ const [folder] = (await request.json()) as typeof folders;
+ folders = folders.map((current) =>
+ current.id === folder.id ? folder : current
+ );
+ return json(folder);
+ })
+ );
+
+ const moveA = upsertAssetFolderWithClient(
+ {
+ projectId,
+ folder: {
+ id: "a",
+ projectId,
+ name: "A",
+ parentId: "b",
+ createdAt,
+ },
+ },
+ testContext.postgrest.client
+ );
+ await firstWriteStarted;
+ const moveB = upsertAssetFolderWithClient(
+ {
+ projectId,
+ folder: {
+ id: "b",
+ projectId,
+ name: "B",
+ parentId: "a",
+ createdAt,
+ },
+ },
+ testContext.postgrest.client
+ );
+
+ await Promise.resolve();
+ expect(readCount).toBe(1);
+ releaseFirstWrite();
+
+ await expect(moveA).resolves.toMatchObject({ id: "a", parentId: "b" });
+ await expect(moveB).rejects.toThrow("Folders can't contain cycles");
+ expect(readCount).toBe(3);
+ expect(writeCount).toBe(1);
+ });
+
+ test("repairs persisted cycles when folders are loaded", async () => {
+ const projectId = uid();
+ const createdAt = "2026-01-01T00:00:00.000Z";
+ let folders: Array<{
+ id: string;
+ projectId: string;
+ name: string;
+ parentId: string | null;
+ createdAt: string;
+ }> = [
+ { id: "a", projectId, name: "A", parentId: "b", createdAt },
+ { id: "b", projectId, name: "B", parentId: "a", createdAt },
+ ];
+ server.use(
+ db.get("AssetFolder", () => json(folders)),
+ db.patch("AssetFolder", async ({ request }) => {
+ expect(await request.json()).toEqual({ parentId: null });
+ folders = folders.map((folder) =>
+ folder.id === "b" ? { ...folder, parentId: null } : folder
+ );
+ return json([{ id: "b" }]);
+ })
+ );
+
+ await expect(
+ loadAssetFoldersByProjectWithClient(
+ projectId,
+ testContext.postgrest.client,
+ ["a"]
+ )
+ ).resolves.toEqual([
+ { id: "a", projectId, name: "A", parentId: "b", createdAt },
+ ]);
+ await expect(
+ loadAssetFoldersByProjectWithClient(
+ projectId,
+ testContext.postgrest.client
+ )
+ ).resolves.toEqual([
+ { id: "a", projectId, name: "A", parentId: "b", createdAt },
+ { id: "b", projectId, name: "B", createdAt },
+ ]);
+ });
+
+ test("reloads a cycle repair that loses a concurrent update", async () => {
+ const projectId = uid();
+ const createdAt = "2026-01-01T00:00:00.000Z";
+ let folders: Array<{
+ id: string;
+ projectId: string;
+ name: string;
+ parentId: string | null;
+ createdAt: string;
+ }> = [
+ { id: "a", projectId, name: "A", parentId: "b", createdAt },
+ { id: "b", projectId, name: "B", parentId: "a", createdAt },
+ ];
+ let readCount = 0;
+ server.use(
+ db.get("AssetFolder", () => {
+ readCount += 1;
+ return json(folders);
+ }),
+ db.patch("AssetFolder", () => {
+ folders = folders.map((folder) =>
+ folder.id === "b" ? { ...folder, parentId: null } : folder
+ );
+ return json([]);
+ })
+ );
+
+ await expect(
+ loadAssetFoldersByProjectWithClient(
+ projectId,
+ testContext.postgrest.client
+ )
+ ).resolves.toEqual([
+ { id: "a", projectId, name: "A", parentId: "b", createdAt },
+ { id: "b", projectId, name: "B", createdAt },
+ ]);
+ expect(readCount).toBe(2);
+ });
+
+ test("reverts a move when a concurrent server creates a cycle", async () => {
+ const projectId = uid();
+ const createdAt = "2026-01-01T00:00:00.000Z";
+ let folders: Array<{
+ id: string;
+ projectId: string;
+ name: string;
+ parentId: string | null;
+ createdAt: string;
+ }> = [
+ { id: "a", projectId, name: "A", parentId: null, createdAt },
+ { id: "b", projectId, name: "B", parentId: null, createdAt },
+ ];
+ let rollbackCount = 0;
+ server.use(
+ db.get("AssetFolder", () => json(folders)),
+ db.post("AssetFolder", async ({ request }) => {
+ const [folder] = (await request.json()) as typeof folders;
+ folders = folders.map((current) =>
+ current.id === folder.id ? folder : current
+ );
+ folders = folders.map((current) =>
+ current.id === "b" ? { ...current, parentId: "a" } : current
+ );
+ return json(folder);
+ }),
+ db.patch("AssetFolder", async ({ request }) => {
+ rollbackCount += 1;
+ const values = (await request.json()) as {
+ name: string;
+ parentId: string | null;
+ };
+ expect(values).toEqual({ name: "A", parentId: null });
+ folders = folders.map((folder) =>
+ folder.id === "a" ? { ...folder, ...values } : folder
+ );
+ return json([{ id: "a" }]);
+ })
+ );
+
+ await expect(
+ upsertAssetFolderWithClient(
+ {
+ projectId,
+ folder: {
+ id: "a",
+ projectId,
+ name: "A",
+ parentId: "b",
+ createdAt,
+ },
+ },
+ testContext.postgrest.client
+ )
+ ).rejects.toThrow("conflicted with another move and was reverted");
+ expect(rollbackCount).toBe(1);
+ expect(folders).toEqual([
+ { id: "a", projectId, name: "A", parentId: null, createdAt },
+ { id: "b", projectId, name: "B", parentId: "a", createdAt },
+ ]);
+ });
+
test("inserts parents before children", async () => {
const projectId = uid();
let inserted: Array<{ id: string }> = [];
@@ -228,6 +503,119 @@ const assetRow = {
},
};
+describe("asset patch persistence", () => {
+ test("loads only requested assets", async () => {
+ const projectId = uid();
+ let idFilter: string | null = null;
+ server.use(
+ db.get("Asset", ({ request }) => {
+ idFilter = new URL(request.url).searchParams.get("id");
+ return json([{ ...assetRow, projectId }]);
+ })
+ );
+
+ await expect(
+ loadAssetsByProjectWithClient(projectId, testContext.postgrest.client, [
+ "asset-1",
+ ])
+ ).resolves.toEqual([expect.objectContaining({ id: "asset-1" })]);
+ expect(idFilter).toBe("in.(asset-1)");
+ });
+
+ test("does not query when no asset ids are requested", async () => {
+ const projectId = uid();
+ let requestCount = 0;
+ server.use(
+ db.get("Asset", () => {
+ requestCount += 1;
+ return json([]);
+ })
+ );
+
+ await expect(
+ loadAssetsByProjectWithClient(projectId, testContext.postgrest.client, [])
+ ).resolves.toEqual([]);
+ expect(requestCount).toBe(0);
+ });
+
+ test("rejects assets that are patched into another project", async () => {
+ const projectId = uid();
+ server.use(db.get("Asset", () => json([{ ...assetRow, projectId }])));
+
+ await expect(
+ patchAssetsWithClient(
+ { projectId, client: testContext.postgrest.client },
+ [
+ {
+ op: "replace",
+ path: ["asset-1", "projectId"],
+ value: "another-project",
+ },
+ ]
+ )
+ ).rejects.toThrow("belongs to another project");
+ });
+
+ test("updates only supplied metadata and reloads only that asset", async () => {
+ const projectId = uid();
+ let update: unknown;
+ let readIdFilter: string | null = null;
+ server.use(
+ db.patch("Asset", async ({ request }) => {
+ update = await request.json();
+ return json({ id: "asset-1" });
+ }),
+ db.get("Asset", ({ request }) => {
+ readIdFilter = new URL(request.url).searchParams.get("id");
+ return json([{ ...assetRow, projectId, description: null }]);
+ })
+ );
+
+ await expect(
+ updateAssetMetadataWithClient(
+ {
+ projectId,
+ assetId: "asset-1",
+ values: { description: null },
+ },
+ testContext.postgrest.client
+ )
+ ).resolves.toEqual(
+ expect.objectContaining({ id: "asset-1", description: undefined })
+ );
+ expect(update).toEqual({ description: null });
+ expect(readIdFilter).toBe("in.(asset-1)");
+ });
+
+ test("reports a missing metadata update as a repository not-found error", async () => {
+ const projectId = uid();
+ server.use(db.patch("Asset", () => json(null)));
+
+ await expect(
+ updateAssetMetadataWithClient(
+ {
+ projectId,
+ assetId: "missing",
+ values: { description: "Missing" },
+ },
+ testContext.postgrest.client
+ )
+ ).rejects.toBeInstanceOf(AssetRepositoryNotFoundError);
+ });
+
+ test("reports a missing deletion as a repository not-found error", async () => {
+ const projectId = uid();
+ server.use(db.get("Asset", () => json([])));
+
+ await expect(
+ deleteAssetsWithClient(
+ { projectId, ids: ["missing"] },
+ testContext.postgrest.client
+ )
+ ).rejects.toBeInstanceOf(AssetRepositoryNotFoundError);
+ });
+});
+
describe("patchAssets (msw)", () => {
test("throws when caller lacks edit access", async () => {
const projectId = uid();
@@ -270,6 +658,7 @@ describe("patchAssets (msw)", () => {
description: body.description ?? localAssetRow.description,
};
return json({
+ id: localAssetRow.assetId,
filename: localAssetRow.filename,
description: localAssetRow.description,
});
@@ -352,6 +741,7 @@ describe("patchAssets (msw)", () => {
server.use(
ownershipHandler,
db.get("Asset", () => json([localAssetRow])),
+ db.get("AssetFileMetadata", () => json([])),
db.patch("Asset", async ({ request }) => {
const body = (await request.json()) as { filename?: string };
updatedFilename = body.filename;
@@ -360,6 +750,7 @@ describe("patchAssets (msw)", () => {
filename: body.filename ?? localAssetRow.filename,
};
return json({
+ id: localAssetRow.assetId,
filename: localAssetRow.filename,
description: localAssetRow.description,
});
@@ -430,15 +821,35 @@ describe("patchAssets (msw)", () => {
test("persists moving an asset to root as null", async () => {
const projectId = uid();
- const localAssetRow = { ...assetRow, projectId, folderId: "folder" };
+ let localAssetRow = {
+ ...assetRow,
+ projectId,
+ filename: "post",
+ folderId: "folder" as string | null,
+ file: {
+ ...assetRow.file,
+ name: "stored.md",
+ format: "md",
+ size: 100,
+ meta: "{}",
+ },
+ };
let updatedFolderId: unknown = "not-updated";
server.use(
ownershipHandler,
- db.get("Asset", () => json([localAssetRow])),
+ db.get("Asset", ({ request }) => {
+ const url = new URL(request.url);
+ if (url.searchParams.has("id")) {
+ return json([{ ...localAssetRow, id: localAssetRow.assetId }]);
+ }
+ return json([localAssetRow]);
+ }),
db.patch("Asset", async ({ request }) => {
updatedFolderId = ((await request.json()) as { folderId: unknown })
.folderId;
+ localAssetRow = { ...localAssetRow, folderId: null };
return json({
+ id: localAssetRow.assetId,
filename: localAssetRow.filename,
description: localAssetRow.description,
folderId: null,
@@ -565,6 +976,49 @@ describe("patchAssets (msw)", () => {
expect(insertedAssets).toBeDefined();
});
+ test("rejects an added asset whose file is unavailable", async () => {
+ const projectId = uid();
+ let restored = false;
+ let inserted = false;
+ server.use(
+ db.get("Asset", () => json([])),
+ db.get("File", () => json([])),
+ db.patch("File", () => {
+ restored = true;
+ return empty({ status: 204 });
+ }),
+ db.post("Asset", () => {
+ inserted = true;
+ return empty({ status: 201 });
+ })
+ );
+
+ await expect(
+ patchAssetsWithClient(
+ { projectId, client: testContext.postgrest.client },
+ [
+ {
+ op: "add",
+ path: ["missing"],
+ value: {
+ id: "missing",
+ name: "missing.jpg",
+ type: "image",
+ projectId,
+ format: "jpg",
+ size: 1,
+ description: null,
+ createdAt: "2024-01-01T00:00:00.000Z",
+ meta: { width: 1, height: 1 },
+ },
+ },
+ ]
+ )
+ ).rejects.toThrow("Asset file not found for missing");
+ expect(restored).toBe(false);
+ expect(inserted).toBe(false);
+ });
+
test("core helper deletes assets and marks unused files as deleted", async () => {
const projectId = uid();
const localAssetRow = { ...assetRow, projectId };
diff --git a/packages/asset-uploader/src/query-preview.ts b/packages/asset-uploader/src/query-preview.ts
new file mode 100644
index 0000000000..0e5501a52c
--- /dev/null
+++ b/packages/asset-uploader/src/query-preview.ts
@@ -0,0 +1,26 @@
+import { type AssetQueryRequestInput } from "@webstudio-is/content-engine";
+import type { AssetObjectStore } from "./client";
+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+import { PostgresAssetRepository } from "./asset-repository";
+
+export const previewAssetResourceQuery = async ({
+ projectId,
+ request,
+ context,
+ assetClient,
+ contentDatabaseMaxBytes,
+}: {
+ projectId: string;
+ request: AssetQueryRequestInput;
+ context: AppContext;
+ assetClient: Pick<AssetObjectStore, "readFile">;
+ contentDatabaseMaxBytes?: number;
+}) => {
+ const repository = new PostgresAssetRepository({
+ projectId,
+ context,
+ assetStore: assetClient,
+ contentDatabaseMaxBytes,
+ });
+ return await repository.query(request);
+};
diff --git a/packages/asset-uploader/src/revision.test.ts b/packages/asset-uploader/src/revision.test.ts
index 400365383a..fb5e409a01 100644
--- a/packages/asset-uploader/src/revision.test.ts
+++ b/packages/asset-uploader/src/revision.test.ts
@@ -13,10 +13,17 @@ import {
AssetRevisionConflictError,
updateAssetContent,
} from "./revision";
+import { PostgresAssetRepository } from "./asset-repository";
const { getRevisionFilename } = __testing__;
const server = createTestServer();
+const readEmptyFile = async () => ({
+ data: {
+ async *[Symbol.asyncIterator]() {},
+ },
+});
+
const createContext = (): AppContext =>
({
...testContext,
@@ -82,7 +89,24 @@ describe("asset content revisions", () => {
let swapInput: unknown;
server.use(
ownershipHandler,
- db.get("Asset", () => json(assetRow)),
+ db.get("Asset", ({ request }) => {
+ const url = new URL(request.url);
+ if (url.searchParams.has("file.status")) {
+ return json([
+ {
+ ...assetRow,
+ name: revisionName,
+ file: {
+ ...oldFile,
+ name: revisionName,
+ size: 7,
+ updatedAt: "2026-07-18T00:00:01.000Z",
+ },
+ },
+ ]);
+ }
+ return json(assetRow);
+ }),
db.post("File", async ({ request }) => {
const input = (await request.json()) as { name: string };
revisionName = input.name;
@@ -116,7 +140,9 @@ describe("asset content revisions", () => {
swapInput = await request.json();
return HttpResponse.json("updated");
}
- )
+ ),
+ db.get("AssetFolder", () => json([])),
+ db.post("rpc/replace_asset_file_metadata", () => json(true))
);
const asset = await updateAssetContent(
@@ -135,6 +161,7 @@ describe("asset content revisions", () => {
);
return { format: "json", size: 7, meta: {} };
},
+ readFile: readEmptyFile,
},
createContext()
);
@@ -157,6 +184,110 @@ describe("asset content revisions", () => {
});
});
+ test("reindexes replaced Markdown content only at a query synchronization boundary", async () => {
+ const source = "---\ntitle: Updated post\n---\n\nUpdated body";
+ const sourceBytes = new TextEncoder().encode(source);
+ const markdownFile = {
+ ...oldFile,
+ name: "post_old-revision.md",
+ format: "md",
+ size: 3,
+ };
+ const markdownAsset = {
+ ...assetRow,
+ name: markdownFile.name,
+ filename: "post",
+ file: markdownFile,
+ };
+ let revisionName = "";
+ let canonicalDocument: Record<string, unknown> | undefined;
+ server.use(
+ ownershipHandler,
+ db.get("Asset", ({ request }) => {
+ const url = new URL(request.url);
+ if (url.searchParams.has("file.status")) {
+ return json([
+ {
+ ...markdownAsset,
+ name: revisionName,
+ file: {
+ ...markdownFile,
+ name: revisionName,
+ size: sourceBytes.byteLength,
+ updatedAt: "2026-07-18T00:00:01.000Z",
+ },
+ },
+ ]);
+ }
+ return json(markdownAsset);
+ }),
+ db.post("File", async ({ request }) => {
+ revisionName = ((await request.json()) as { name: string }).name;
+ return empty({ status: 201 });
+ }),
+ db.get("File", () =>
+ json({
+ ...markdownFile,
+ name: revisionName,
+ format: "file",
+ status: "UPLOADING",
+ })
+ ),
+ db.patch("File", () =>
+ json({
+ ...markdownFile,
+ name: revisionName,
+ size: sourceBytes.byteLength,
+ updatedAt: "2026-07-18T00:00:01.000Z",
+ })
+ ),
+ http.post("http://test-postgrest/rpc/swap_asset_file", () =>
+ HttpResponse.json("updated")
+ ),
+ db.get("AssetFolder", () => json([])),
+ db.get("AssetFileMetadata", () => json([])),
+ db.post("rpc/replace_asset_file_metadata", async ({ request }) => {
+ canonicalDocument = (
+ (await request.json()) as {
+ p_document: Record<string, unknown>;
+ }
+ ).p_document;
+ return json(true);
+ })
+ );
+
+ const repository = new PostgresAssetRepository({
+ projectId: "project",
+ context: createContext(),
+ assetStore: {
+ uploadFile: async () => ({
+ format: "md",
+ size: sourceBytes.byteLength,
+ meta: {},
+ }),
+ readFile: async (name) => {
+ expect(name).toBe(revisionName);
+ return { data: new Blob([source]).stream() };
+ },
+ },
+ });
+ await repository.updateContent({
+ assetId: "asset",
+ expectedName: markdownFile.name,
+ data: new Blob([source]).stream(),
+ });
+
+ expect(canonicalDocument).toBeUndefined();
+ await repository.synchronize();
+ expect(canonicalDocument).toMatchObject({
+ _id: "asset",
+ name: "post.md",
+ contentRef: revisionName,
+ properties: { title: "Updated post" },
+ excerpt: "Updated body",
+ });
+ });
+
test("rejects a stale revision before uploading", async () => {
server.use(
ownershipHandler,
@@ -175,6 +306,7 @@ describe("asset content revisions", () => {
uploadFile: async () => {
throw new Error("upload should not run");
},
+ readFile: readEmptyFile,
},
createContext()
)
@@ -226,28 +358,44 @@ describe("asset content revisions", () => {
);
await expect(
- updateAssetContent(
- {
- assetId: "asset",
- projectId: "project",
- expectedName: oldFile.name,
- data: new Blob(["updated"]).stream(),
- },
- {
+ new PostgresAssetRepository({
+ projectId: "project",
+ context: createContext(),
+ assetStore: {
uploadFile: async () => ({ format: "json", size: 7, meta: {} }),
+ readFile: readEmptyFile,
},
- createContext()
- )
+ }).updateContent({
+ assetId: "asset",
+ expectedName: oldFile.name,
+ data: new Blob(["updated"]).stream(),
+ })
).rejects.toBeInstanceOf(AssetRevisionConflictError);
expect(discardedRevision).toBe(true);
});
- test("accepts a revision when the swap commits without a response", async () => {
+ test("accepts a committed revision when the swap response fails", async () => {
let assetLoadCount = 0;
let revisionName = "";
server.use(
ownershipHandler,
- db.get("Asset", () => {
+ db.get("Asset", ({ request }) => {
+ const url = new URL(request.url);
+ if (url.searchParams.has("file.status")) {
+ return json([
+ {
+ ...assetRow,
+ name: revisionName,
+ file: {
+ ...oldFile,
+ name: revisionName,
+ format: "json",
+ size: 7,
+ updatedAt: "2026-07-18T00:00:00.000Z",
+ },
+ },
+ ]);
+ }
assetLoadCount += 1;
return json(
assetLoadCount === 1 ? assetRow : { ...assetRow, name: revisionName }
@@ -276,9 +424,12 @@ describe("asset content revisions", () => {
),
http.post("http://test-postgrest/rpc/swap_asset_file", () =>
HttpResponse.error()
+ ),
+ db.get("AssetFolder", () => json([])),
+ db.post("rpc/replace_asset_file_metadata", () =>
+ json({ message: "index database unavailable" }, { status: 500 })
)
);
-
await expect(
updateAssetContent(
{
@@ -289,6 +440,7 @@ describe("asset content revisions", () => {
},
{
uploadFile: async () => ({ format: "json", size: 7, meta: {} }),
+ readFile: readEmptyFile,
},
createContext()
)
diff --git a/packages/asset-uploader/src/revision.ts b/packages/asset-uploader/src/revision.ts
index 360147e804..b2ce16388e 100644
--- a/packages/asset-uploader/src/revision.ts
+++ b/packages/asset-uploader/src/revision.ts
@@ -9,7 +9,7 @@ import {
type AppContext,
} from "@webstudio-is/trpc-interface/index.server";
import type { Client } from "@webstudio-is/postgrest/index.server";
-import type { AssetClient } from "./client";
+import type { AssetObjectStore } from "./client";
import { uploadFileData } from "./upload";
import { createUniqueAssetFilename } from "./utils/get-unique-filename";
import { sanitizeS3Key } from "./utils/sanitize-s3-key";
@@ -103,7 +103,7 @@ export const updateAssetContent = async (
expectedName: string;
data: ReadableStream<Uint8Array>;
},
- assetClient: AssetClient,
+ assetClient: AssetObjectStore,
context: AppContext
): Promise<Asset> => {
const canEdit = await authorizeProject.hasProjectPermit(
@@ -181,6 +181,7 @@ export const updateAssetContent = async (
context.postgrest.client
);
} catch (error) {
+ let swapCommitted = false;
try {
const current = await loadAsset({
assetId,
@@ -188,17 +189,20 @@ export const updateAssetContent = async (
client: context.postgrest.client,
});
if (current.name === revisionName) {
- return revision;
+ swapCommitted = true;
+ } else {
+ const discardedRevision = await context.postgrest.client
+ .from("File")
+ .update({ isDeleted: true })
+ .eq("name", revisionName);
+ assertPostgrestSuccess(discardedRevision);
}
- const discardedRevision = await context.postgrest.client
- .from("File")
- .update({ isDeleted: true })
- .eq("name", revisionName);
- assertPostgrestSuccess(discardedRevision);
} catch (cleanupError) {
console.error("Unable to discard an asset revision", cleanupError);
}
- throw error;
+ if (swapCommitted === false) {
+ throw error;
+ }
}
return revision;
diff --git a/packages/asset-uploader/src/index.server.ts b/packages/asset-uploader/src/server.ts
similarity index 60%
rename from packages/asset-uploader/src/index.server.ts
rename to packages/asset-uploader/src/server.ts
index 3d8f1db150..af2637ba12 100644
--- a/packages/asset-uploader/src/index.server.ts
+++ b/packages/asset-uploader/src/server.ts
@@ -2,11 +2,21 @@ export * from "./db";
export * from "./content-hash";
export * from "./utils/size-limiter";
export * from "./upload";
+export * from "./asset-repository";
+export * from "./asset-repository-errors";
export * from "./delete";
export * from "./patch";
export * from "./asset-patch-core";
export * from "./folder-persistence";
export * from "./revision";
+export * from "./field-catalog";
+export * from "./query-preview";
export * from "./clients/fs/fs";
export * from "./clients/s3/s3";
export { assetDataOverride } from "./utils/get-asset-data";
+export type {
+ AssetInfoFallback,
+ AssetObjectReader,
+ AssetObjectStore,
+ AssetObjectWriter,
+} from "./client";
diff --git a/packages/asset-uploader/src/upload.test.ts b/packages/asset-uploader/src/upload.test.ts
index f5cbaa2016..84d7837b71 100644
--- a/packages/asset-uploader/src/upload.test.ts
+++ b/packages/asset-uploader/src/upload.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from "vitest";
+import { describe, expect, test, vi } from "vitest";
import {
createTestServer,
db,
@@ -8,6 +8,7 @@ import {
} from "@webstudio-is/postgrest/testing";
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
import { createUploadTicket, uploadFile } from "./upload";
+import { PostgresAssetRepository } from "./asset-repository";
const server = createTestServer();
@@ -744,6 +745,161 @@ describe("createUploadTicket", () => {
});
describe("uploadFile", () => {
+ test("does not synchronize canonical metadata while committing an upload", async () => {
+ const source = "---\ntitle: New post\n---\nPost body";
+ const sourceBytes = new TextEncoder().encode(source);
+ let persisted: Record<string, unknown> | undefined;
+ const uploadedFile = {
+ name: "post.md",
+ format: "md",
+ size: sourceBytes.byteLength,
+ status: "UPLOADED",
+ uploaderProjectId: "project-1",
+ isDeleted: false,
+ description: null,
+ meta: "{}",
+ createdAt: "2026-07-18T00:00:00.000Z",
+ updatedAt: "2026-07-18T01:00:00.000Z",
+ };
+ const readFile = vi.fn(async () => ({
+ data: {
+ async *[Symbol.asyncIterator]() {
+ yield sourceBytes;
+ },
+ },
+ }));
+ server.use(
+ db.get("File", () =>
+ json({
+ ...uploadedFile,
+ size: 0,
+ status: "UPLOADING",
+ updatedAt: "2026-07-18T00:00:00.000Z",
+ })
+ ),
+ db.patch("File", () => json(uploadedFile)),
+ db.get("Asset", ({ request }) => {
+ const url = new URL(request.url);
+ if (url.searchParams.has("name")) {
+ return json({
+ id: "asset-1",
+ projectId: "project-1",
+ filename: null,
+ description: null,
+ folderId: null,
+ });
+ }
+ expect(url.searchParams.get("id")).toBe("in.(asset-1)");
+ return json([
+ {
+ id: "asset-1",
+ projectId: "project-1",
+ filename: null,
+ folderId: null,
+ file: uploadedFile,
+ },
+ ]);
+ }),
+ db.get("AssetFolder", () => json([])),
+ db.post("rpc/replace_asset_file_metadata", async ({ request }) => {
+ const value = (await request.json()) as {
+ p_project_id: string;
+ p_asset_id: string;
+ p_document: Record<string, unknown>;
+ };
+ persisted = {
+ projectId: value.p_project_id,
+ assetId: value.p_asset_id,
+ document: value.p_document,
+ };
+ return json(true);
+ })
+ );
+
+ const storage = {
+ uploadFile: async () => ({
+ format: "md",
+ size: sourceBytes.byteLength,
+ meta: {},
+ }),
+ readFile,
+ };
+ await expect(
+ new PostgresAssetRepository({
+ projectId: "project-1",
+ context: createContext(),
+ assetStore: storage,
+ }).completeUpload({
+ name: "post.md",
+ data: new Blob([source]).stream(),
+ assetInfoFallback: undefined,
+ })
+ ).resolves.toMatchObject({
+ id: "asset-1",
+ name: "post.md",
+ type: "file",
+ });
+ expect(readFile).not.toHaveBeenCalled();
+ expect(persisted).toBeUndefined();
+ });
+
+ test("accepts an upload-only storage client", async () => {
+ const source = "Post body";
+ const uploadedFile = {
+ name: "post.md",
+ format: "md",
+ size: source.length,
+ status: "UPLOADED",
+ uploaderProjectId: "project-1",
+ isDeleted: false,
+ description: null,
+ meta: "{}",
+ createdAt: "2026-07-18T00:00:00.000Z",
+ updatedAt: "2026-07-18T01:00:00.000Z",
+ };
+ server.use(
+ db.get("File", () => json({ ...uploadedFile, status: "UPLOADING" })),
+ db.patch("File", () => json(uploadedFile)),
+ db.get("Asset", ({ request }) => {
+ const url = new URL(request.url);
+ if (url.searchParams.has("name")) {
+ return json({
+ id: "asset-1",
+ projectId: "project-1",
+ filename: null,
+ description: null,
+ folderId: null,
+ });
+ }
+ return json([
+ {
+ id: "asset-1",
+ projectId: "project-1",
+ filename: null,
+ folderId: null,
+ file: uploadedFile,
+ },
+ ]);
+ }),
+ db.get("AssetFolder", () => json([]))
+ );
+ await expect(
+ uploadFile(
+ "post.md",
+ new Blob([source]).stream(),
+ {
+ uploadFile: async () => ({
+ format: "md",
+ size: source.length,
+ meta: {},
+ }),
+ },
+ createContext(),
+ undefined
+ )
+ ).resolves.toMatchObject({ id: "asset-1", name: "post.md" });
+ });
+
test("returns uploaded asset with reserved asset row id", async () => {
server.use(
db.get("File", () =>
@@ -774,6 +930,21 @@ describe("uploadFile", () => {
),
db.get("Asset", ({ request }) => {
const url = new URL(request.url);
+ if (url.searchParams.has("file.status")) {
+ return json([
+ {
+ id: "asset-1",
+ projectId: "project-1",
+ filename: "photo",
+ folderId: null,
+ file: {
+ name: "existing.png",
+ size: 5,
+ updatedAt: "2024-01-01T00:00:00.000Z",
+ },
+ },
+ ]);
+ }
expect(url.searchParams.get("name")).toBe("eq.existing.png");
expect(url.searchParams.get("projectId")).toBe("eq.project-1");
return json({
@@ -782,6 +953,17 @@ describe("uploadFile", () => {
filename: "photo",
description: "Photo",
});
+ }),
+ db.get("AssetFolder", () => json([])),
+ db.post("rpc/replace_asset_file_metadata", async ({ request }) => {
+ const body = (await request.json()) as {
+ p_document: { extension: string; mimeType: string };
+ };
+ expect(body.p_document).toMatchObject({
+ extension: "png",
+ mimeType: "image/png",
+ });
+ return json(true);
})
);
diff --git a/packages/asset-uploader/src/upload.ts b/packages/asset-uploader/src/upload.ts
index f878f15620..a41bfe2916 100644
--- a/packages/asset-uploader/src/upload.ts
+++ b/packages/asset-uploader/src/upload.ts
@@ -12,7 +12,7 @@ import {
type Asset,
} from "@webstudio-is/sdk";
import type { Database } from "@webstudio-is/postgrest/index.server";
-import type { AssetClient } from "./client";
+import type { AssetInfoFallback, AssetObjectWriter } from "./client";
import type { AssetDataOverride } from "./utils/get-asset-data";
import { createUniqueAssetFilename } from "./utils/get-unique-filename";
import { sanitizeS3Key } from "./utils/sanitize-s3-key";
@@ -20,7 +20,7 @@ import { formatAsset } from "./utils/format-asset";
import { assertPostgrestSuccess } from "./patch-utils";
import type { UploadTicket } from "./types";
-type UploadData = {
+export type CreateUploadTicketInput = {
projectId: string;
type: string;
filename: string;
@@ -153,7 +153,7 @@ const findContentHashUploadTicket = async ({
data,
context,
}: {
- data: UploadData & { contentHash: string };
+ data: CreateUploadTicketInput & { contentHash: string };
context: AppContext;
}): Promise<UploadTicket | undefined> => {
const {
@@ -279,7 +279,7 @@ const cleanupUploadError = async (
};
export const createUploadTicket = async (
- data: UploadData,
+ data: CreateUploadTicketInput,
context: AppContext,
createId: () => Asset["id"] = nanoid
): Promise<UploadTicket> => {
@@ -382,11 +382,9 @@ export const createUploadTicket = async (
export const uploadFileData = async (
name: string,
data: ReadableStream<Uint8Array>,
- client: AssetClient,
+ client: AssetObjectWriter,
context: AppContext,
- assetInfoFallback:
- | { width: number; height: number; format: string }
- | undefined,
+ assetInfoFallback: AssetInfoFallback | undefined,
assetDataOverride?: AssetDataOverride,
onUploadError?: UploadErrorCleanup
): Promise<Database["public"]["Tables"]["File"]["Row"]> => {
@@ -492,11 +490,9 @@ export const getUploadedAsset = async ({
export const uploadFile = async (
name: string,
data: ReadableStream<Uint8Array>,
- client: AssetClient,
+ client: AssetObjectWriter,
context: AppContext,
- assetInfoFallback:
- | { width: number; height: number; format: string }
- | undefined,
+ assetInfoFallback: AssetInfoFallback | undefined,
assetDataOverride?: AssetDataOverride,
onUploadError?: UploadErrorCleanup
): Promise<Asset> => {
@@ -514,12 +510,13 @@ export const uploadFile = async (
if (typeof projectId !== "string") {
throw Error("File uploader project is missing");
}
- return await getUploadedAsset({
+ const asset = await getUploadedAsset({
name,
projectId,
context,
file,
});
+ return asset;
} catch (error) {
await cleanupUploadError(name, context, onUploadError);
throw error;
diff --git a/packages/asset-uploader/src/utils/size-limiter.test.ts b/packages/asset-uploader/src/utils/size-limiter.test.ts
new file mode 100644
index 0000000000..66e7423d93
--- /dev/null
+++ b/packages/asset-uploader/src/utils/size-limiter.test.ts
@@ -0,0 +1,23 @@
+import { expect, test } from "vitest";
+import { AssetUploadSizeLimitError, createSizeLimiter } from "./size-limiter";
+
+const collect = async (iterable: AsyncIterable<Uint8Array>) => {
+ const chunks: Uint8Array[] = [];
+ for await (const chunk of iterable) {
+ chunks.push(chunk);
+ }
+ return chunks;
+};
+
+test("throws a typed error when streamed upload content exceeds the limit", async () => {
+ const source = {
+ async *[Symbol.asyncIterator]() {
+ yield new Uint8Array(6);
+ yield new Uint8Array(5);
+ },
+ };
+
+ await expect(
+ collect(createSizeLimiter(10, "post.md")(source))
+ ).rejects.toBeInstanceOf(AssetUploadSizeLimitError);
+});
diff --git a/packages/asset-uploader/src/utils/size-limiter.ts b/packages/asset-uploader/src/utils/size-limiter.ts
index 0d2d9dd3ba..36472181b5 100644
--- a/packages/asset-uploader/src/utils/size-limiter.ts
+++ b/packages/asset-uploader/src/utils/size-limiter.ts
@@ -1,3 +1,10 @@
+export class AssetUploadSizeLimitError extends Error {
+ constructor(name: string, maximumBytes: number) {
+ super(`File "${name}" exceeded upload size of ${maximumBytes} bytes`);
+ this.name = "AssetUploadSizeLimitError";
+ }
+}
+
export const createSizeLimiter = (maxSize: number, name: string) => {
return async function* <T extends ArrayBufferView | ArrayBuffer>(
data: AsyncIterable<T>
@@ -6,7 +13,7 @@ export const createSizeLimiter = (maxSize: number, name: string) => {
for await (const chunk of data) {
size += chunk.byteLength;
if (size > maxSize) {
- throw Error(`File "${name}" exceeded upload size of ${maxSize} bytes`);
+ throw new AssetUploadSizeLimitError(name, maxSize);
}
yield chunk;
}
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 7c1b7f44ab..3969695475 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -68,7 +68,9 @@ Here is the list of independent commands:
### link
-The **`link`** command syncs your local Webstudio project with the project from the cloud. This means that any changes made in the cloud can be synced to the local project, once they are published.
+The **`link`** command stores access to a Webstudio Cloud project. MCP clients use that connection to read and edit the latest Builder build directly; the project does not need to be published or synchronized first.
+
+Shell-capable agents can use local CLI commands such as `webstudio meta.index` immediately after linking. `webstudio connect <client>` is optional persistent native MCP registration and is unnecessary for local CLI usage.
You can link a project from Webstudio Cloud with the following command:
@@ -90,6 +92,8 @@ webstudio sync
Make sure to publish the project in Webstudio Cloud before running the **`sync`** command in your local Webstudio project.
+`sync` is only for downloading a published project export. It is not part of the MCP editing workflow.
+
### build
Now, you can build your project with the **`build`** command:
diff --git a/packages/cli/evaluations/high-impact/agent-runner.test.ts b/packages/cli/evaluations/high-impact/agent-runner.test.ts
index 710f83336f..80baaf15ce 100644
--- a/packages/cli/evaluations/high-impact/agent-runner.test.ts
+++ b/packages/cli/evaluations/high-impact/agent-runner.test.ts
@@ -4,9 +4,10 @@ import { join, resolve } from "node:path";
import { describe, expect, test } from "vitest";
import { authenticatedPageFixture } from "./fixtures";
import { designInputFixture } from "./fixtures";
-import { fontAssetsFixture } from "./fixtures";
+import { fontAssetsFixture, markdownBlogFixture } from "./fixtures";
import {
createMinimalAgentTask,
+ getFixtureToolNames,
getCliInvocation,
runHighImpactAgentEvaluation,
} from "./agent-runner";
@@ -26,6 +27,8 @@ describe("high-impact agent runner", () => {
expect(task).toMatchObject({
constraints: expect.arrayContaining([
expect.any(String),
+ expect.stringContaining("only through the configured webstudio MCP"),
+ expect.stringContaining("Never use a shell"),
expect.stringContaining("exactly once at the beginning"),
expect.any(String),
expect.stringContaining("Never use broad project reads"),
@@ -51,8 +54,9 @@ describe("high-impact agent runner", () => {
expect(authConstraints).not.toContain(
"call get-project-settings, list-pages, list-resources, and list-variables"
);
+ expect(authConstraints).toContain("call create-page exactly once");
expect(authConstraints).toContain(
- "call create-page exactly once, then create-variable"
+ '"value":{"type":"string","value":"signed-out"}'
);
expect(authConstraints).toContain(
"Call insert-fragment-verified only after all three succeed"
@@ -80,7 +84,8 @@ describe("high-impact agent runner", () => {
expect.stringContaining("exactly three attach-design-token calls"),
expect.stringContaining("Omit the optional position field"),
expect.stringContaining("exactly one batched update-styles call"),
- expect.stringContaining("returned mobile breakpoint id"),
+ expect.stringContaining('"breakpoint":"<returned-mobile'),
+ expect.stringContaining("never breakpointId"),
expect.stringContaining("Use this exact fragment verbatim"),
expect.stringContaining('ws:tag="footer"'),
expect.stringContaining("Do not call clone-instance"),
@@ -110,6 +115,45 @@ describe("high-impact agent runner", () => {
expect.stringContaining("Do not call refresh or get-asset separately"),
])
);
+ const blogConstraints = createMinimalAgentTask(markdownBlogFixture, {
+ kind: "source",
+ repositoryRoot: root,
+ }).constraints.join("\n");
+ expect(blogConstraints).toContain("one asset folder named Blog");
+ expect(blogConstraints).toContain("one upload-assets call");
+ expect(blogConstraints).toContain("aurora-trails.md");
+ expect(blogConstraints).toContain("city-walks.md");
+ expect(blogConstraints).toContain("/blog/:slug");
+ expect(blogConstraints).toContain(
+ '"field":["properties","draft"],"operator":"ne"'
+ );
+ expect(blogConstraints).toContain('"value":"true"');
+ expect(blogConstraints).toContain("Never call update-assets-resource");
+ expect(blogConstraints).toContain(
+ '"fields":[["properties","title"],["properties","slug"]'
+ );
+ expect(blogConstraints).toContain('"mode":"markdown-body"');
+ expect(blogConstraints).toContain("$.MarkdownEmbed");
+ expect(blogConstraints).toContain(
+ "call verify-page-responsive exactly twice"
+ );
+ expect(blogConstraints).toContain('"path":"/blog/aurora-trails"');
+ expect(blogConstraints).not.toContain(
+ "Use one verify-page-responsive call for all requested viewports"
+ );
+ expect(getFixtureToolNames(markdownBlogFixture)).toEqual([
+ "meta.guide",
+ "meta.get_more_tools",
+ "create-asset-folder",
+ "upload-assets",
+ "create-page",
+ "create-assets-resource",
+ "insert-collection",
+ "verify-page-responsive",
+ ]);
+ expect(getFixtureToolNames(markdownBlogFixture)).not.toContain(
+ "update-assets-resource"
+ );
});
test("retains only a bounded privacy-safe result from a real process", async () => {
diff --git a/packages/cli/evaluations/high-impact/agent-runner.ts b/packages/cli/evaluations/high-impact/agent-runner.ts
index 929d681c5b..3f71df7c0d 100644
--- a/packages/cli/evaluations/high-impact/agent-runner.ts
+++ b/packages/cli/evaluations/high-impact/agent-runner.ts
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import type { HighImpactFixture } from "./fixtures";
+import { markdownBlogFixtureArticles } from "./markdown-blog-fixture";
import type {
EvaluationToolCall,
HighImpactEvaluationResult,
@@ -43,6 +44,58 @@ export type AgentEvaluationResult = {
checks: Record<string, "passed" | "failed">;
};
+const fixtureToolNames = {
+ "authenticated-page-v1": [
+ "meta.guide",
+ "inspect-auth-context",
+ "create-page",
+ "create-variable",
+ "create-resource",
+ "insert-fragment-verified",
+ "verify-page-responsive",
+ ],
+ "design-input-v1": [
+ "meta.guide",
+ "inspect-design-context",
+ "create-page",
+ "insert-fragment-verified",
+ "attach-design-token",
+ "update-styles",
+ "verify-page-responsive",
+ ],
+ "font-assets-v1": [
+ "meta.guide",
+ "upload-assets",
+ "update-asset",
+ "verify-font-assets",
+ "audit",
+ ],
+ "markdown-blog-v1": [
+ "meta.guide",
+ "meta.get_more_tools",
+ "create-asset-folder",
+ "upload-assets",
+ "create-page",
+ "create-assets-resource",
+ "insert-collection",
+ "verify-page-responsive",
+ ],
+} as const satisfies Record<HighImpactFixture["id"], readonly string[]>;
+
+const markdownBlogUploadInput = JSON.stringify({
+ assets: markdownBlogFixtureArticles.map(({ name }) => ({
+ name,
+ type: "file",
+ format: "md",
+ folderId: "<blog-folder-id>",
+ meta: {},
+ })),
+ assetsDir: ".webstudio/assets",
+});
+
+export const getFixtureToolNames = (fixture: HighImpactFixture) =>
+ fixtureToolNames[fixture.id];
+
const forbiddenResultKeys =
/(?:prompt|transcript|stdout|stderr|secret|credential|payload)/i;
const forbiddenTokenKey = /token/i;
@@ -72,18 +125,25 @@ export const createMinimalAgentTask = (
mcp: getCliInvocation(target),
constraints: [
"Use the configured Webstudio project and local CLI.",
- 'Call meta.guide exactly once at the beginning with {"brief":"<objective>"}: copy the objective field verbatim into brief, follow the returned workflow, and do not call meta.guide again.',
+ "Call Webstudio operations only through the configured webstudio MCP tools exposed directly in your tool list. Never use a shell, terminal, exec tool, node, webstudio CLI shortcut, mcp single-op-call, or mcp run. Shell-invoked operations are invisible to this evaluation and make the result fail.",
+ fixture.id === "markdown-blog-v1"
+ ? 'Call meta.guide exactly once at the beginning with {"brief":"<objective>"}: copy the objective field verbatim into brief. Treat its response as reference only; the fixture sequence below is authoritative and supersedes every workflow or next-step suggestion. Do not call meta.guide again.'
+ : 'Call meta.guide exactly once at the beginning with {"brief":"<objective>"}: copy the objective field verbatim into brief, follow the returned workflow, and do not call meta.guide again.',
"Choose focused reads and semantic edits yourself.",
"Never use broad project reads: snapshot, components.list, or components.coverage-plan.",
"Do not persist or report credentials or private session data.",
"Treat mutation meta.next steps as required. Do not report completion until audit and requested visual evidence pass.",
- "Treat the successful final audit and requested visual evidence as terminal; do not mutate, verify, restart preview, or capture more evidence afterward.",
- "Finish all visual polish before evidence capture. Use one verify-page-responsive call for all requested viewports and the terminal static audit. After it begins, do not mutate, rediscover, restart preview, or capture more evidence.",
+ ...(fixture.id === "markdown-blog-v1"
+ ? []
+ : [
+ "Treat the successful final audit and requested visual evidence as terminal; do not mutate, verify, restart preview, or capture more evidence afterward.",
+ "Finish all visual polish before evidence capture. Use one verify-page-responsive call for all requested viewports and the terminal static audit. After it begins, do not mutate, rediscover, restart preview, or capture more evidence.",
+ ]),
...(fixture.id === "authenticated-page-v1"
? [
"For this fixture, meta.guide already returns the required auth discovery and authoring tool schemas. Do not call list-breakpoints because responsive styling is not required, and do not call meta.get_more_tools or any other tool discovery operation. Create exactly one scoped non-secret fixture variable and keep the required state gallery expression-free. Do not call list-variables again after creating it.",
"After meta.guide, call inspect-auth-context exactly once. Do not call get-project-settings, list-pages, list-resources, or list-variables separately.",
- "After the context read, call create-page exactly once, then create-variable exactly once, then create-resource exactly once with the returned variable id. Do not parallelize these mutations. Call insert-fragment-verified only after all three succeed, using their returned ids and pagePath /account. Do not call insert-fragment or verify-bindings separately.",
+ 'After the context read, call create-page exactly once. Then call create-variable exactly once with {"name":"Account preview state","scopeInstanceId":"<returned-account-root-id>","value":{"type":"string","value":"signed-out"}}, substituting only the returned root id. Keep type exactly string; do not invent a state type. Then call create-resource exactly once with the returned variable id. Do not parallelize these mutations or retry failed calls. Call insert-fragment-verified only after all three succeed, using their returned ids and pagePath /account. Do not call insert-fragment or verify-bindings separately.',
'Then call verify-page-responsive exactly once with {"path":"/account","viewports":[{"width":1440,"height":900},{"width":390,"height":844}],"source":"session"}. It captures both required screenshots and runs the terminal static audit. Do not call preview.start, screenshot, screenshot.responsive, or audit separately.',
]
: []),
@@ -92,7 +152,7 @@ export const createMinimalAgentTask = (
"For this fixture, do not call list-instances because the project has no representative existing page pattern. Do not call meta.index, meta.get_more_tools, or any other tool discovery operation because meta.guide and the MCP handshake already provide the required schemas.",
"After meta.guide, call inspect-design-context exactly once before mutation. Do not call list-pages, list-breakpoints, list-design-tokens, list-assets, or list-variables separately. Do not call get-page-by-path or repeat discovery. Call create-page once, then call insert-fragment-verified once with pagePath /summer before token or style mutations. Do not call insert-fragment or verify-bindings separately.",
"For this fixture, make exactly three attach-design-token calls: attach only the returned Brand / Coral, Text / Ink, and Type / Heading token ids once each to compatible inserted element instance ids. Attach all three tokens in one parallel tool-call batch. Omit the optional position field and do not attempt any other token attachment.",
- "After the early binding checkpoint, make exactly one batched update-styles call containing all remaining fixed styles. Include at least one declaration on an inserted element using the returned mobile breakpoint id so responsive behavior is persisted before preview.",
+ 'After the early binding checkpoint, make exactly one batched update-styles call containing all remaining fixed styles. Its updates array must include an item shaped exactly {"instanceId":"<returned-main-or-section-instance-id>","property":"padding-left","value":{"type":"keyword","value":"16px"},"breakpoint":"<returned-mobile-breakpoint-id>"}, substituting only returned ids. The update-styles field is breakpoint, never breakpointId. Do not omit this mobile item; it proves responsive behavior is persisted before preview.',
'Use this exact fragment verbatim in the single insert-fragment-verified call; do not add props, styles, expressions, or alternate components until after it commits: <ws.element ws:tag="header"><ws.element ws:tag="nav"><ws.element ws:tag="a">Northstar</ws.element><ws.element ws:tag="button">Menu</ws.element></ws.element></ws.element><ws.element ws:tag="main"><ws.element ws:tag="section"><ws.element ws:tag="h1">Find your latitude</ws.element><ws.element ws:tag="p">Plan a memorable summer escape.</ws.element><ws.element ws:tag="a">Explore trips</ws.element></ws.element><ws.element ws:tag="section"><ws.element ws:tag="h2">Featured trips</ws.element><ws.element ws:tag="article"><ws.element ws:tag="h3">Coastal escape</ws.element><ws.element ws:tag="p">A restorative journey by the sea.</ws.element></ws.element></ws.element></ws.element><ws.element ws:tag="footer"><ws.element ws:tag="p">Northstar travel</ws.element></ws.element>',
"The exact fragment already contains all required content. Do not call clone-instance, update-text, set-text-content, or any other content or structure mutation after insertion; only attach the three tokens and apply the one batched style update.",
'After the style update, call verify-page-responsive exactly once with {"path":"/summer","viewports":[{"width":1440,"height":900},{"width":390,"height":844}],"source":"session"}. It captures both required screenshots and runs the terminal static audit. Do not call preview.start, screenshot, screenshot.responsive, or audit separately.',
@@ -101,10 +161,23 @@ export const createMinimalAgentTask = (
...(fixture.id === "font-assets-v1"
? [
"Do not call meta.index, meta.get_more_tools, or any other tool discovery operation because meta.guide and the MCP handshake already provide the required schemas. Upload both supplied fonts together with exactly one upload-assets call; do not use upload-asset.",
- "After upload, update both font assets together in one parallel tool-call batch.",
+ 'After upload, update both font assets together in one parallel tool-call batch. For each returned asset id, use exactly {"assetId":"<returned-asset-id>","values":{"meta":{"family":"Rajdhani","style":"normal","weight":600}}}. Keep family, style, and weight inside values.meta; do not send an empty values object. Make exactly two update-asset calls total and stop instead of retrying if either fails.',
"After both updates, call verify-font-assets exactly once with both returned asset ids, then audit. Do not call refresh or get-asset separately.",
]
: []),
+ ...(fixture.id === "markdown-blog-v1"
+ ? [
+ 'For this fixture, call meta.get_more_tools exactly once immediately after meta.guide with {"brief":"create-assets-resource"} to load the complete schema for its complex query input. Do not call meta.index, list/get/preview asset tools, list pages, or any other discovery operation. Then create one asset folder named Blog and upload all five supplied .md files together with exactly one upload-assets call using type file, format md, that returned folder id, empty metadata, and assetsDir .webstudio/assets.',
+ `Use this exact upload-assets input, substituting only the returned Blog folder id for <blog-folder-id>: ${markdownBlogUploadInput}.`,
+ "For this fixture, the exact sequence below supersedes every workflow and mutation meta.next suggestion. After a listed call succeeds, continue immediately to the next listed call without inspecting, repairing, updating, or repeating its result. If any call fails, stop immediately; retries and repair mutations fail this evaluation. Never call update-assets-resource or any tool not explicitly listed in these fixture constraints.",
+ "Create exactly two pages: first /blog, then /blog/:slug. Do not call create-assets-resource while creating either page. Never call create-assets-resource without a query. After both page calls succeed, make exactly two create-assets-resource calls total using the complete inputs below; any omitted query or additional resource fails this evaluation.",
+ 'First call create-assets-resource exactly once with this complete overview input, substituting only the returned overview root id for scopeInstanceId: {"name":"Published posts","scopeInstanceId":"<overview-root-id>","dataSourceName":"posts","query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","draft"],"operator":"ne","value":"true"}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"},{"field":["id"],"direction":"asc"}],"limit":"20","output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["excerpt"]]},"content":{"mode":"none"}}}. Do not convert expression strings to booleans or field paths to dotted strings.',
+ 'Then call create-assets-resource exactly once with this complete detail input, substituting only the returned detail root id for scopeInstanceId: {"name":"Post by slug","scopeInstanceId":"<detail-root-id>","dataSourceName":"post","query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"}]},"limit":"1","output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"]]},"content":{"mode":"markdown-body","maxBytes":1048576}}}. Do not call create-assets-resource again.',
+ 'After both resources succeed, call insert-collection exactly once on the overview root with {"parentInstanceId":"<overview-root-id>","data":{"type":"expression","value":"posts.data"},"itemFragment":"<ws.element ws:tag=\"article\"><ws.element ws:tag=\"h2\">{expression`collectionItem.properties.title ?? \\"Untitled\\"`}</ws.element><ws.element ws:tag=\"p\">{expression`collectionItem.excerpt ?? \\"\\"`}</ws.element><ws.element ws:tag=\"time\">{expression`collectionItem.properties.publishedAt ?? \\"\\"`}</ws.element><ws.element ws:tag=\"a\" href={expression`\\"/blog/\\" + collectionItem.properties.slug`}>Read article</ws.element></ws.element>"}, substituting only the returned overview root id.',
+ 'Then call insert-collection exactly once on the detail root with {"parentInstanceId":"<detail-root-id>","data":{"type":"expression","value":"post.data"},"itemFragment":"<ws.element ws:tag=\"article\"><ws.element ws:tag=\"h1\">{expression`collectionItem.properties.title ?? \\"Untitled\\"`}</ws.element><$.MarkdownEmbed code={expression`collectionItem.content.text`} /></ws.element>"}, substituting only the returned detail root id. insert-collection validates and persists its bindings atomically, so do not call verify-bindings or perform any repair afterward.',
+ 'After both Collections succeed, call verify-page-responsive exactly twice: first with {"path":"/blog","viewports":[{"width":1440,"height":900},{"width":390,"height":844}],"source":"session"}, then with {"path":"/blog/aurora-trails","viewports":[{"width":1440,"height":900},{"width":390,"height":844}],"source":"session"}. Do not mutate, rediscover, restart preview, or capture separate screenshots or audits after verification begins. If either verification fails, stop immediately without retrying or changing the project.',
+ ]
+ : []),
],
};
};
@@ -165,6 +238,7 @@ export const runHighImpactAgentEvaluation = async ({
evaluate,
env = process.env,
timeoutMs = 10 * 60_000,
+ signal,
}: {
fixture: HighImpactFixture;
target: AgentCliTarget;
@@ -179,6 +253,7 @@ export const runHighImpactAgentEvaluation = async ({
evaluate: () => Promise<HighImpactEvaluationResult>;
env?: NodeJS.ProcessEnv;
timeoutMs?: number;
+ signal?: AbortSignal;
}) => {
await mkdir(dirname(taskPath), { recursive: true });
await writeFile(
@@ -192,6 +267,7 @@ export const runHighImpactAgentEvaluation = async ({
cwd,
env: { ...env, WEBSTUDIO_HIGH_IMPACT_AGENT_TASK: taskPath },
timeoutMs,
+ signal,
onStdoutLine: (line) => {
let value: unknown;
try {
diff --git a/packages/cli/evaluations/high-impact/fixture-api.test.ts b/packages/cli/evaluations/high-impact/fixture-api.test.ts
index d9e007fb5e..18113cd612 100644
--- a/packages/cli/evaluations/high-impact/fixture-api.test.ts
+++ b/packages/cli/evaluations/high-impact/fixture-api.test.ts
@@ -6,7 +6,11 @@ import { promisify } from "node:util";
import { describe, expect, test } from "vitest";
import { getFontFaces } from "@webstudio-is/fonts";
import type { FontAsset } from "@webstudio-is/sdk";
-import { authenticatedPageFixture, fontAssetsFixture } from "./fixtures";
+import {
+ authenticatedPageFixture,
+ fontAssetsFixture,
+ markdownBlogFixture,
+} from "./fixtures";
import { startHighImpactFixtureApi } from "./fixture-api";
import {
fontAssetFixtureFiles,
@@ -15,6 +19,10 @@ import {
fontAssetFixtureUploadMeta,
writeFontAssetFixtureFiles,
} from "./font-assets-fixture";
+import {
+ markdownBlogFixtureArticles,
+ writeMarkdownBlogFixtureFiles,
+} from "./markdown-blog-fixture";
const execFileAsync = promisify(execFile);
@@ -138,4 +146,62 @@ describe("high-impact fixture API", () => {
await rm(directory, { recursive: true, force: true });
}
}, 60_000);
+
+ test("creates a folder and uploads the Markdown blog files through the local CLI", async () => {
+ const fixtureApi = await startHighImpactFixtureApi(markdownBlogFixture);
+ const directory = await mkdtemp(
+ join(tmpdir(), "markdown-blog-fixture-api-")
+ );
+ const configDirectory = join(directory, "config");
+ const projectDirectory = join(directory, "project");
+ const cli = resolve(import.meta.dirname, "../../local.js");
+ await writeMarkdownBlogFixtureFiles(projectDirectory);
+ const env = { ...process.env, WEBSTUDIO_CONFIG_DIR: configDirectory };
+ const run = async (command: string, input: Record<string, unknown>) => {
+ const result = await execFileAsync(
+ process.execPath,
+ [cli, command, JSON.stringify(input)],
+ { cwd: projectDirectory, env }
+ );
+ return JSON.parse(result.stdout) as {
+ ok: boolean;
+ data: Record<string, unknown>;
+ };
+ };
+ try {
+ await execFileAsync(
+ process.execPath,
+ [cli, "init", "--link", fixtureApi.shareLink, "--json"],
+ { cwd: projectDirectory, env }
+ );
+ const folder = await run("create-asset-folder", { name: "Blog" });
+ expect(folder.ok).toBe(true);
+ const folderId = String(folder.data.folderId);
+ const upload = await run("upload-assets", {
+ assets: markdownBlogFixtureArticles.map(({ name }) => ({
+ name,
+ type: "file",
+ format: "md",
+ folderId,
+ meta: {},
+ })),
+ assetsDir: ".webstudio/assets",
+ });
+ expect(upload.ok).toBe(true);
+ expect(fixtureApi.getProject()).toMatchObject({
+ assetFolders: [expect.objectContaining({ id: folderId, name: "Blog" })],
+ assets: markdownBlogFixtureArticles.map(({ name }) =>
+ expect.objectContaining({
+ name,
+ type: "file",
+ format: "md",
+ folderId,
+ })
+ ),
+ });
+ } finally {
+ await fixtureApi.close();
+ await rm(directory, { recursive: true, force: true });
+ }
+ }, 60_000);
});
diff --git a/packages/cli/evaluations/high-impact/fixture-api.ts b/packages/cli/evaluations/high-impact/fixture-api.ts
index 8d51c3aed9..2eea497344 100644
--- a/packages/cli/evaluations/high-impact/fixture-api.ts
+++ b/packages/cli/evaluations/high-impact/fixture-api.ts
@@ -1,6 +1,7 @@
import type { Server } from "node:http";
import { fontFormat, fontMeta } from "@webstudio-is/fonts";
import type { Asset } from "@webstudio-is/sdk";
+import { assetsUploadsApiUrl } from "@webstudio-is/sdk/runtime";
import { migratePages } from "@webstudio-is/project-migrations/pages";
import React from "react";
import type { BuilderState } from "@webstudio-is/project-build/state";
@@ -44,6 +45,7 @@ const createPersistedPages = (project: EvaluationProject) => ({
const stateToProject = (state: BuilderState): EvaluationProject => ({
assets: Array.from(state.assets?.values() ?? []),
+ assetFolders: Array.from(state.assetFolders?.values() ?? []),
pages: Array.from(state.pages?.pages.values() ?? []).map((page) => ({
id: page.id,
name: page.name,
@@ -115,6 +117,7 @@ export const startHighImpactFixtureApi = async (
styleSourceSelections: fixture.project.styleSourceSelections,
styles: fixture.project.styles,
assets: fixture.project.assets,
+ assetFolders: fixture.project.assetFolders,
projectSettings: { meta: {}, compiler: {} },
};
let state = createBuilderStateFromBuildData(build as never);
@@ -125,42 +128,70 @@ export const startHighImpactFixtureApi = async (
const fixtureApi = await startRuntimeFixtureApi(
async ({ request, response, pathname, operationPath, readInput }) => {
let data: unknown;
- if (request.method === "POST" && pathname.startsWith("/rest/assets/")) {
+ if (
+ request.method === "POST" &&
+ pathname.startsWith(`${assetsUploadsApiUrl}/`)
+ ) {
const url = new URL(request.url ?? "", origin);
- const name = decodeURIComponent(pathname.slice("/rest/assets/".length));
+ const name = decodeURIComponent(
+ pathname.slice(`${assetsUploadsApiUrl}/`.length)
+ );
const body = await readRuntimeFixtureRequestBody(request);
+ const type = url.searchParams.get("type");
+ const formatValue = url.searchParams.get("format");
if (
url.searchParams.get("projectId") !== projectId ||
- url.searchParams.get("type") !== "font" ||
+ (type !== "font" && type !== "file") ||
+ formatValue === null ||
+ formatValue.length === 0 ||
body.byteLength === 0
) {
- throw new Error("Invalid font asset upload request.");
+ throw new Error("Invalid asset upload request.");
}
- const format = fontFormat.parse(url.searchParams.get("format"));
- const meta = fontMeta.parse(
- JSON.parse(String(request.headers["x-webstudio-asset-meta"] ?? "{}"))
- );
const description = request.headers["x-webstudio-asset-description"];
- const asset: Asset = {
+ const folderId = url.searchParams.get("folderId") ?? undefined;
+ const assetBase = {
id: `evaluation-asset-${generatedId++}`,
projectId,
name,
filename: name,
description: typeof description === "string" ? description : null,
size: body.byteLength,
- type: "font",
- format,
- meta,
+ ...(folderId === undefined ? {} : { folderId }),
createdAt: "2026-01-01T00:00:00.000Z",
};
- calls.push({ name: "upload-asset", arguments: { name, format, meta } });
+ const asset: Asset =
+ type === "font"
+ ? {
+ ...assetBase,
+ type,
+ format: fontFormat.parse(formatValue),
+ meta: fontMeta.parse(
+ JSON.parse(
+ String(request.headers["x-webstudio-asset-meta"] ?? "{}")
+ )
+ ),
+ }
+ : { ...assetBase, type, format: formatValue, meta: {} };
+ calls.push({
+ name: "upload-asset",
+ arguments: {
+ name,
+ type,
+ format: asset.format,
+ meta: asset.meta,
+ folderId,
+ },
+ });
state = {
...state,
assets: new Map(state.assets).set(asset.id, asset),
};
version += 1;
response.writeHead(200, { "content-type": "application/json" });
- response.end(JSON.stringify({ uploadedAssets: [asset] }));
+ response.end(
+ JSON.stringify({ uploadedAssets: [asset], deduplicated: false })
+ );
return;
}
if (operationPath === "build.loadProjectBundleByProjectId") {
diff --git a/packages/cli/evaluations/high-impact/fixtures.ts b/packages/cli/evaluations/high-impact/fixtures.ts
index d3abad392a..eb8cf541b2 100644
--- a/packages/cli/evaluations/high-impact/fixtures.ts
+++ b/packages/cli/evaluations/high-impact/fixtures.ts
@@ -1,5 +1,6 @@
-import type { Asset } from "@webstudio-is/sdk";
+import type { Asset, AssetFolder } from "@webstudio-is/sdk";
import { fontAssetFixtureFiles } from "./font-assets-fixture";
+import { markdownBlogFixtureArticles } from "./markdown-blog-fixture";
export type EvaluationPage = {
id: string;
@@ -37,6 +38,7 @@ export type EvaluationStyle = {
export type EvaluationProject = {
assets: Asset[];
+ assetFolders: AssetFolder[];
pages: EvaluationPage[];
instances: EvaluationInstance[];
props: EvaluationProp[];
@@ -56,7 +58,11 @@ export type EvaluationProject = {
};
export type HighImpactFixture = {
- id: "authenticated-page-v1" | "design-input-v1" | "font-assets-v1";
+ id:
+ | "authenticated-page-v1"
+ | "design-input-v1"
+ | "font-assets-v1"
+ | "markdown-blog-v1";
objective: string;
project: EvaluationProject;
};
@@ -70,6 +76,7 @@ const homePage: EvaluationPage = {
const emptyProject = (): EvaluationProject => ({
assets: [],
+ assetFolders: [],
pages: [homePage],
instances: [
{
@@ -206,7 +213,13 @@ export const designInputFixture: HighImpactFixture & {
export const fontAssetsFixture: HighImpactFixture = {
id: "font-assets-v1",
- objective: `Upload ${fontAssetFixtureFiles.map(({ name }) => name).join(" and ")} from .webstudio/assets as font assets, initially using family Imported Rajdhani, style normal, and weight 400. Then use update-asset on each uploaded asset to set family Rajdhani, style normal, and weight 600. Refresh the assets namespace and read both assets back to verify the saved metadata before finishing. Do not change the page.`,
+ objective: `Upload ${fontAssetFixtureFiles.map(({ name }) => name).join(" and ")} from .webstudio/assets as font assets, initially using family Imported Rajdhani, style normal, and weight 400. Then use update-asset exactly once on each uploaded asset to set values.meta to family Rajdhani, style normal, and weight 600. Verify both returned asset ids with verify-font-assets, run the audit, and do not change the page.`,
+ project: emptyProject(),
+};
+
+export const markdownBlogFixture: HighImpactFixture = {
+ id: "markdown-blog-v1",
+ objective: `Upload the ${markdownBlogFixtureArticles.length} provided Markdown articles from .webstudio/assets into one Blog asset folder. Build an editable blog overview at /blog and a dynamic detail page at /blog/:slug using exactly one fully configured scoped Assets resource per page, Collections, and Markdown Embed. Include the complete structured query in each initial resource creation; never create a default or placeholder resource and never repair one by creating another. The overview query must exclude drafts, sort newest first, select the article title, slug, excerpt, and publication date, and avoid loading file content. The detail query must select one article from system.params.slug and load its Markdown body. Verify both /blog and /blog/aurora-trails at desktop and mobile sizes.`,
project: emptyProject(),
};
@@ -214,6 +227,7 @@ export const highImpactFixtures = [
authenticatedPageFixture,
designInputFixture,
fontAssetsFixture,
+ markdownBlogFixture,
] as const;
export const validateHighImpactFixture = (fixture: HighImpactFixture) => {
diff --git a/packages/cli/evaluations/high-impact/markdown-blog-fixture.ts b/packages/cli/evaluations/high-impact/markdown-blog-fixture.ts
new file mode 100644
index 0000000000..7926065423
--- /dev/null
+++ b/packages/cli/evaluations/high-impact/markdown-blog-fixture.ts
@@ -0,0 +1,70 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+export const markdownBlogFixtureArticles = [
+ {
+ name: "aurora-trails.md",
+ title: "Aurora trails",
+ slug: "aurora-trails",
+ publishedAt: "2026-05-20",
+ excerpt: "A practical guide to planning a northern-lights journey.",
+ },
+ {
+ name: "coastal-notes.md",
+ title: "Coastal notes",
+ slug: "coastal-notes",
+ publishedAt: "2026-04-12",
+ excerpt: "Slow travel ideas from a week beside the Atlantic.",
+ },
+ {
+ name: "forest-cabins.md",
+ title: "Forest cabins",
+ slug: "forest-cabins",
+ publishedAt: "2026-03-08",
+ excerpt: "Five quiet cabins for an off-grid weekend.",
+ },
+ {
+ name: "desert-light.md",
+ title: "Desert light",
+ slug: "desert-light",
+ publishedAt: "2026-02-14",
+ excerpt: "Photographing color and shadow in the high desert.",
+ },
+ {
+ name: "city-walks.md",
+ title: "City walks",
+ slug: "city-walks",
+ publishedAt: "2026-01-05",
+ excerpt: "A collection of human-scale routes through old cities.",
+ },
+] as const;
+
+const articleSource = (
+ article: (typeof markdownBlogFixtureArticles)[number]
+) => `---
+title: ${article.title}
+slug: ${article.slug}
+publishedAt: ${article.publishedAt}
+draft: false
+excerpt: ${article.excerpt}
+---
+
+# ${article.title}
+
+${article.excerpt}
+
+This article is part of the Northstar field journal. It provides enough body
+content to verify that the detail route reads and renders Markdown content.
+`;
+
+export const writeMarkdownBlogFixtureFiles = async (
+ projectDirectory: string
+) => {
+ const assetsDirectory = join(projectDirectory, ".webstudio/assets");
+ await mkdir(assetsDirectory, { recursive: true });
+ await Promise.all(
+ markdownBlogFixtureArticles.map((article) =>
+ writeFile(join(assetsDirectory, article.name), articleSource(article))
+ )
+ );
+};
diff --git a/packages/cli/evaluations/high-impact/mcp-trace-proxy.test.ts b/packages/cli/evaluations/high-impact/mcp-trace-proxy.test.ts
index 3f90acdfcd..584e15f293 100644
--- a/packages/cli/evaluations/high-impact/mcp-trace-proxy.test.ts
+++ b/packages/cli/evaluations/high-impact/mcp-trace-proxy.test.ts
@@ -86,6 +86,7 @@ describe("bounded MCP tracing", () => {
).toMatchObject({
call: {
arguments: {
+ path: "/account",
viewports: [
{ width: 1440, height: 900 },
{ width: 390, height: 844 },
@@ -93,6 +94,19 @@ describe("bounded MCP tracing", () => {
},
},
});
+ expect(
+ getMcpTraceRequest({
+ id: 10,
+ method: "tools/call",
+ params: {
+ name: "verify-page-responsive",
+ arguments: {
+ path: "/account?authToken=private",
+ viewports: [{ width: 390, height: 844 }],
+ },
+ },
+ })
+ ).not.toMatchObject({ call: { arguments: { path: expect.any(String) } } });
});
test("records confirmation flow without retaining its token", () => {
diff --git a/packages/cli/evaluations/high-impact/mcp-trace-proxy.ts b/packages/cli/evaluations/high-impact/mcp-trace-proxy.ts
index 1165f2115a..d7d9e12dda 100644
--- a/packages/cli/evaluations/high-impact/mcp-trace-proxy.ts
+++ b/packages/cli/evaluations/high-impact/mcp-trace-proxy.ts
@@ -9,6 +9,7 @@ type JsonRpcId = string | number;
export type BoundedMcpCall = {
name: string;
arguments?: {
+ path?: string;
viewport?: { width: number; height: number };
viewports?: Array<{ width: number; height: number }>;
dryRun?: true;
@@ -26,6 +27,20 @@ export type BoundedMcpCall = {
errorIssues?: Array<{ code: string; path: string }>;
};
+const getBoundedRoutePath = (value: unknown) => {
+ if (typeof value !== "string" || value.length > 256) {
+ return;
+ }
+ try {
+ const url = new URL(value, "https://evaluation.invalid");
+ if (url.origin === "https://evaluation.invalid" && value === url.pathname) {
+ return url.pathname;
+ }
+ } catch {
+ return;
+ }
+};
+
const getStructuredError = (result: unknown) => {
const structuredContent =
isPlainRecord(result) && isPlainRecord(result.structuredContent)
@@ -108,6 +123,12 @@ export const getMcpTraceRequest = (
};
if (isPlainRecord(params.arguments)) {
const args: NonNullable<BoundedMcpCall["arguments"]> = {};
+ if (params.name === "verify-page-responsive") {
+ const path = getBoundedRoutePath(params.arguments.path);
+ if (path !== undefined) {
+ args.path = path;
+ }
+ }
const viewport = params.arguments.viewport;
if (
params.name === "screenshot" &&
diff --git a/packages/cli/evaluations/high-impact/results/authenticated-page-v1.json b/packages/cli/evaluations/high-impact/results/authenticated-page-v1.json
index 9e37932082..d9fed98287 100644
--- a/packages/cli/evaluations/high-impact/results/authenticated-page-v1.json
+++ b/packages/cli/evaluations/high-impact/results/authenticated-page-v1.json
@@ -5,95 +5,83 @@
"outcome": "passed",
"cli": "source",
"provider": "openai",
- "model": "gpt-5.6-sol",
- "commandSha256": "f3973839321d489a88526e5e1751d54aa9391af61107e56165cd35520c60a96a",
+ "model": "gpt-5.4-mini",
+ "commandSha256": "1f722c6fb110b0de65a89d07326dc21acfee50935b68ff1a5d3e1d483be791fe",
"exitCode": 0,
"metrics": {
- "durationMs": 94027,
+ "durationMs": 60397,
"tokens": {
- "input": 319553,
- "cachedInput": 275200,
- "uncachedInput": 44353,
+ "input": 176838,
+ "cachedInput": 162048,
+ "uncachedInput": 14790,
"cacheWriteInput": 0,
- "output": 1843,
- "reasoningOutput": 505,
- "total": 321396,
- "cachedInputRate": 0.8612
+ "output": 2366,
+ "reasoningOutput": 1293,
+ "total": 179204,
+ "cachedInputRate": 0.9164
},
"mcpCatalog": {
"responses": 1,
- "totalResponseBytes": 51362,
- "maxResponseBytes": 51362,
- "latestToolCount": 176,
- "latestResponseBytes": 51362,
- "latestInputSchemaBytes": 28964,
- "latestDescriptionBytes": 4556
+ "totalResponseBytes": 53114,
+ "maxResponseBytes": 53114,
+ "latestToolCount": 184,
+ "latestResponseBytes": 53114,
+ "latestInputSchemaBytes": 29971,
+ "latestDescriptionBytes": 4529
},
"toolCalls": {
- "total": 8,
- "succeeded": 8,
+ "total": 7,
+ "succeeded": 7,
"failed": 0,
"failuresByTool": {},
"failuresByCode": {},
"issuesByCode": {},
"issuesByPath": {},
"durationsByTool": {
- "audit": {
- "count": 1,
- "totalMs": 10,
- "p95Ms": 10,
- "maxMs": 10
- },
"create-page": {
"count": 1,
- "totalMs": 29,
- "p95Ms": 29,
- "maxMs": 29
+ "totalMs": 45,
+ "p95Ms": 45,
+ "maxMs": 45
},
"create-resource": {
"count": 1,
- "totalMs": 20,
- "p95Ms": 20,
- "maxMs": 20
+ "totalMs": 33,
+ "p95Ms": 33,
+ "maxMs": 33
},
"create-variable": {
"count": 1,
- "totalMs": 24,
- "p95Ms": 24,
- "maxMs": 24
+ "totalMs": 37,
+ "p95Ms": 37,
+ "maxMs": 37
},
"insert-fragment-verified": {
"count": 1,
- "totalMs": 68,
- "p95Ms": 68,
- "maxMs": 68
+ "totalMs": 65,
+ "p95Ms": 65,
+ "maxMs": 65
},
"inspect-auth-context": {
"count": 1,
- "totalMs": 22,
- "p95Ms": 22,
- "maxMs": 22
+ "totalMs": 28,
+ "p95Ms": 28,
+ "maxMs": 28
},
"meta.guide": {
"count": 1,
- "totalMs": 10,
- "p95Ms": 10,
- "maxMs": 10
+ "totalMs": 13,
+ "p95Ms": 13,
+ "maxMs": 13
},
- "screenshot.responsive": {
+ "verify-page-responsive": {
"count": 1,
- "totalMs": 9439,
- "p95Ms": 9439,
- "maxMs": 9439
+ "totalMs": 10855,
+ "p95Ms": 10855,
+ "maxMs": 10855
}
},
"responseBytesByTool": {
- "audit": {
- "count": 1,
- "totalBytes": 4762,
- "p95Bytes": 4762,
- "maxBytes": 4762
- },
"create-page": {
"count": 1,
"totalBytes": 1342,
@@ -126,15 +114,15 @@
},
"meta.guide": {
"count": 1,
- "totalBytes": 15932,
- "p95Bytes": 15932,
- "maxBytes": 15932
+ "totalBytes": 15934,
+ "p95Bytes": 15934,
+ "maxBytes": 15934
},
- "screenshot.responsive": {
+ "verify-page-responsive": {
"count": 1,
- "totalBytes": 7064,
- "p95Bytes": 7064,
- "maxBytes": 7064
+ "totalBytes": 11730,
+ "p95Bytes": 11730,
+ "maxBytes": 11730
}
},
"retries": 0,
@@ -143,16 +131,16 @@
"dryRuns": 0,
"plannedMutations": 0,
"committedMutations": 4,
- "verifications": 3,
- "totalDurationMs": 9622,
- "p50DurationMs": 22,
- "p95DurationMs": 9439,
- "totalResponseBytes": 37536,
+ "verifications": 2,
+ "totalDurationMs": 11076,
+ "p50DurationMs": 37,
+ "p95DurationMs": 10855,
+ "totalResponseBytes": 37442,
"p50ResponseBytes": 2576,
- "p95ResponseBytes": 15932,
- "maxResponseBytes": 15932,
- "timeToFirstMutationMs": 39076,
- "timeToFirstVerificationMs": 67660
+ "p95ResponseBytes": 15934,
+ "maxResponseBytes": 15934,
+ "timeToFirstMutationMs": 25967,
+ "timeToFirstVerificationMs": 39551
}
},
"callSequence": [
@@ -162,8 +150,7 @@
"create-variable",
"create-resource",
"insert-fragment-verified",
- "screenshot.responsive",
- "audit"
+ "verify-page-responsive"
],
"checks": {
"guidance": "passed",
diff --git a/packages/cli/evaluations/high-impact/results/design-input-v1.json b/packages/cli/evaluations/high-impact/results/design-input-v1.json
index cef1e8a342..90d8f20f8b 100644
--- a/packages/cli/evaluations/high-impact/results/design-input-v1.json
+++ b/packages/cli/evaluations/high-impact/results/design-input-v1.json
@@ -5,33 +5,33 @@
"outcome": "passed",
"cli": "source",
"provider": "openai",
- "model": "gpt-5.6-sol",
- "commandSha256": "665472955db94c5d88c26b9c858eca2ec7621f04efa461fdb4cff3ae79dc5c5b",
+ "model": "gpt-5.4-mini",
+ "commandSha256": "942755cc0025a46d00f539f1720d60cbbb3e26498a6fc835500deda6d7c875c1",
"exitCode": 0,
"metrics": {
- "durationMs": 97892,
+ "durationMs": 150790,
"tokens": {
- "input": 327593,
- "cachedInput": 273152,
- "uncachedInput": 54441,
+ "input": 217420,
+ "cachedInput": 186496,
+ "uncachedInput": 30924,
"cacheWriteInput": 0,
- "output": 2987,
- "reasoningOutput": 698,
- "total": 330580,
- "cachedInputRate": 0.8338
+ "output": 8186,
+ "reasoningOutput": 4893,
+ "total": 225606,
+ "cachedInputRate": 0.8578
},
"mcpCatalog": {
"responses": 1,
- "totalResponseBytes": 51362,
- "maxResponseBytes": 51362,
- "latestToolCount": 176,
- "latestResponseBytes": 51362,
- "latestInputSchemaBytes": 28964,
- "latestDescriptionBytes": 4556
+ "totalResponseBytes": 53114,
+ "maxResponseBytes": 53114,
+ "latestToolCount": 184,
+ "latestResponseBytes": 53114,
+ "latestInputSchemaBytes": 29971,
+ "latestDescriptionBytes": 4529
},
"toolCalls": {
- "total": 10,
- "succeeded": 10,
+ "total": 9,
+ "succeeded": 9,
"failed": 0,
"failuresByTool": {},
"failuresByCode": {},
@@ -40,51 +40,45 @@
"durationsByTool": {
"attach-design-token": {
"count": 3,
- "totalMs": 24,
- "p95Ms": 9,
- "maxMs": 9
- },
- "audit": {
- "count": 1,
- "totalMs": 12,
- "p95Ms": 12,
- "maxMs": 12
+ "totalMs": 88,
+ "p95Ms": 42,
+ "maxMs": 42
},
"create-page": {
"count": 1,
- "totalMs": 91,
- "p95Ms": 91,
- "maxMs": 91
+ "totalMs": 31,
+ "p95Ms": 31,
+ "maxMs": 31
},
"insert-fragment-verified": {
"count": 1,
- "totalMs": 55,
- "p95Ms": 55,
- "maxMs": 55
+ "totalMs": 42,
+ "p95Ms": 42,
+ "maxMs": 42
},
"inspect-design-context": {
"count": 1,
- "totalMs": 30,
- "p95Ms": 30,
- "maxMs": 30
+ "totalMs": 40,
+ "p95Ms": 40,
+ "maxMs": 40
},
"meta.guide": {
"count": 1,
- "totalMs": 11,
- "p95Ms": 11,
- "maxMs": 11
+ "totalMs": 75,
+ "p95Ms": 75,
+ "maxMs": 75
},
- "screenshot.responsive": {
+ "update-styles": {
"count": 1,
- "totalMs": 10751,
- "p95Ms": 10751,
- "maxMs": 10751
+ "totalMs": 59,
+ "p95Ms": 59,
+ "maxMs": 59
},
- "update-styles": {
+ "verify-page-responsive": {
"count": 1,
- "totalMs": 64,
- "p95Ms": 64,
- "maxMs": 64
+ "totalMs": 10165,
+ "p95Ms": 10165,
+ "maxMs": 10165
}
},
"responseBytesByTool": {
@@ -94,12 +88,6 @@
"p95Bytes": 1304,
"maxBytes": 1304
},
- "audit": {
- "count": 1,
- "totalBytes": 3711,
- "p95Bytes": 3711,
- "maxBytes": 3711
- },
"create-page": {
"count": 1,
"totalBytes": 1342,
@@ -120,21 +108,21 @@
},
"meta.guide": {
"count": 1,
- "totalBytes": 15190,
- "p95Bytes": 15190,
- "maxBytes": 15190
+ "totalBytes": 15130,
+ "p95Bytes": 15130,
+ "maxBytes": 15130
},
- "screenshot.responsive": {
+ "update-styles": {
"count": 1,
- "totalBytes": 7053,
- "p95Bytes": 7053,
- "maxBytes": 7053
+ "totalBytes": 2762,
+ "p95Bytes": 2762,
+ "maxBytes": 2762
},
- "update-styles": {
+ "verify-page-responsive": {
"count": 1,
- "totalBytes": 2804,
- "p95Bytes": 2804,
- "maxBytes": 2804
+ "totalBytes": 10663,
+ "p95Bytes": 10663,
+ "maxBytes": 10663
}
},
"retries": 0,
@@ -143,16 +131,16 @@
"dryRuns": 0,
"plannedMutations": 0,
"committedMutations": 6,
- "verifications": 3,
- "totalDurationMs": 11038,
- "p50DurationMs": 12,
- "p95DurationMs": 10751,
- "totalResponseBytes": 40036,
- "p50ResponseBytes": 2804,
- "p95ResponseBytes": 15190,
- "maxResponseBytes": 15190,
- "timeToFirstMutationMs": 30419,
- "timeToFirstVerificationMs": 36551
+ "verifications": 2,
+ "totalDurationMs": 10500,
+ "p50DurationMs": 42,
+ "p95DurationMs": 10165,
+ "totalResponseBytes": 39833,
+ "p50ResponseBytes": 2762,
+ "p95ResponseBytes": 15130,
+ "maxResponseBytes": 15130,
+ "timeToFirstMutationMs": 36333,
+ "timeToFirstVerificationMs": 41878
}
},
"callSequence": [
@@ -164,8 +152,7 @@
"attach-design-token",
"attach-design-token",
"update-styles",
- "screenshot.responsive",
- "audit"
+ "verify-page-responsive"
],
"checks": {
"guidance": "passed",
diff --git a/packages/cli/evaluations/high-impact/results/font-assets-v1.json b/packages/cli/evaluations/high-impact/results/font-assets-v1.json
index d1fb08fa43..9fee485232 100644
--- a/packages/cli/evaluations/high-impact/results/font-assets-v1.json
+++ b/packages/cli/evaluations/high-impact/results/font-assets-v1.json
@@ -5,29 +5,29 @@
"outcome": "passed",
"cli": "source",
"provider": "openai",
- "model": "gpt-5.6-sol",
- "commandSha256": "5c89af64bb3444ce679f82090c667ece40deb159b6b9ce7cd413e19c466d1ae3",
+ "model": "gpt-5.4-mini",
+ "commandSha256": "894c6e39ef40250b37452fea3c1c8255932b086cae057392775f60e33eee8e81",
"exitCode": 0,
"metrics": {
- "durationMs": 50677,
+ "durationMs": 42054,
"tokens": {
- "input": 261344,
- "cachedInput": 240640,
- "uncachedInput": 20704,
+ "input": 154475,
+ "cachedInput": 134528,
+ "uncachedInput": 19947,
"cacheWriteInput": 0,
- "output": 1440,
- "reasoningOutput": 198,
- "total": 262784,
- "cachedInputRate": 0.9208
+ "output": 1936,
+ "reasoningOutput": 715,
+ "total": 156411,
+ "cachedInputRate": 0.8709
},
"mcpCatalog": {
"responses": 1,
- "totalResponseBytes": 51362,
- "maxResponseBytes": 51362,
- "latestToolCount": 176,
- "latestResponseBytes": 51362,
- "latestInputSchemaBytes": 28964,
- "latestDescriptionBytes": 4556
+ "totalResponseBytes": 53114,
+ "maxResponseBytes": 53114,
+ "latestToolCount": 184,
+ "latestResponseBytes": 53114,
+ "latestInputSchemaBytes": 29971,
+ "latestDescriptionBytes": 4529
},
"toolCalls": {
"total": 6,
@@ -40,41 +40,41 @@
"durationsByTool": {
"audit": {
"count": 1,
- "totalMs": 17,
- "p95Ms": 17,
- "maxMs": 17
+ "totalMs": 18,
+ "p95Ms": 18,
+ "maxMs": 18
},
"meta.guide": {
"count": 1,
- "totalMs": 11,
- "p95Ms": 11,
- "maxMs": 11
+ "totalMs": 16,
+ "p95Ms": 16,
+ "maxMs": 16
},
"update-asset": {
"count": 2,
- "totalMs": 27,
- "p95Ms": 14,
- "maxMs": 14
+ "totalMs": 41,
+ "p95Ms": 29,
+ "maxMs": 29
},
"upload-assets": {
"count": 1,
- "totalMs": 25,
- "p95Ms": 25,
- "maxMs": 25
+ "totalMs": 51,
+ "p95Ms": 51,
+ "maxMs": 51
},
"verify-font-assets": {
"count": 1,
- "totalMs": 8,
- "p95Ms": 8,
- "maxMs": 8
+ "totalMs": 7,
+ "p95Ms": 7,
+ "maxMs": 7
}
},
"responseBytesByTool": {
"audit": {
"count": 1,
- "totalBytes": 5300,
- "p95Bytes": 5300,
- "maxBytes": 5300
+ "totalBytes": 4638,
+ "p95Bytes": 4638,
+ "maxBytes": 4638
},
"meta.guide": {
"count": 1,
@@ -108,15 +108,15 @@
"plannedMutations": 0,
"committedMutations": 3,
"verifications": 1,
- "totalDurationMs": 88,
- "p50DurationMs": 13,
- "p95DurationMs": 25,
- "totalResponseBytes": 18042,
+ "totalDurationMs": 133,
+ "p50DurationMs": 16,
+ "p95DurationMs": 51,
+ "totalResponseBytes": 17380,
"p50ResponseBytes": 2196,
"p95ResponseBytes": 6566,
"maxResponseBytes": 6566,
- "timeToFirstMutationMs": 37609,
- "timeToFirstVerificationMs": 47073
+ "timeToFirstMutationMs": 28505,
+ "timeToFirstVerificationMs": 37196
}
},
"callSequence": [
diff --git a/packages/cli/evaluations/high-impact/results/markdown-blog-v1.json b/packages/cli/evaluations/high-impact/results/markdown-blog-v1.json
new file mode 100644
index 0000000000..6ecabe40be
--- /dev/null
+++ b/packages/cli/evaluations/high-impact/results/markdown-blog-v1.json
@@ -0,0 +1,189 @@
+{
+ "schemaVersion": 2,
+ "kind": "high-impact-minimal-context-agent-evaluation-result",
+ "fixtureId": "markdown-blog-v1",
+ "outcome": "passed",
+ "cli": "source",
+ "provider": "openai",
+ "model": "gpt-5.4-mini",
+ "commandSha256": "1db2da8f7b8d32044006973fb9a352c6e5110603c9d07b3a4924642e6f2f8ae7",
+ "exitCode": 0,
+ "metrics": {
+ "durationMs": 121762,
+ "tokens": {
+ "input": 469568,
+ "cachedInput": 436096,
+ "uncachedInput": 33472,
+ "cacheWriteInput": 0,
+ "output": 5829,
+ "reasoningOutput": 3703,
+ "total": 475397,
+ "cachedInputRate": 0.9287
+ },
+ "mcpCatalog": {
+ "responses": 1,
+ "totalResponseBytes": 53114,
+ "maxResponseBytes": 53114,
+ "latestToolCount": 184,
+ "latestResponseBytes": 53114,
+ "latestInputSchemaBytes": 29971,
+ "latestDescriptionBytes": 4529
+ },
+ "toolCalls": {
+ "total": 13,
+ "succeeded": 13,
+ "failed": 0,
+ "failuresByTool": {},
+ "failuresByCode": {},
+ "issuesByCode": {},
+ "issuesByPath": {},
+ "durationsByTool": {
+ "create-asset-folder": {
+ "count": 1,
+ "totalMs": 40,
+ "p95Ms": 40,
+ "maxMs": 40
+ },
+ "create-assets-resource": {
+ "count": 3,
+ "totalMs": 100,
+ "p95Ms": 51,
+ "maxMs": 51
+ },
+ "create-page": {
+ "count": 2,
+ "totalMs": 31,
+ "p95Ms": 20,
+ "maxMs": 20
+ },
+ "insert-collection": {
+ "count": 2,
+ "totalMs": 69,
+ "p95Ms": 53,
+ "maxMs": 53
+ },
+ "meta.get_more_tools": {
+ "count": 1,
+ "totalMs": 17,
+ "p95Ms": 17,
+ "maxMs": 17
+ },
+ "meta.guide": {
+ "count": 1,
+ "totalMs": 16,
+ "p95Ms": 16,
+ "maxMs": 16
+ },
+ "upload-assets": {
+ "count": 1,
+ "totalMs": 21,
+ "p95Ms": 21,
+ "maxMs": 21
+ },
+ "verify-page-responsive": {
+ "count": 2,
+ "totalMs": 12197,
+ "p95Ms": 10670,
+ "maxMs": 10670
+ }
+ },
+ "responseBytesByTool": {
+ "create-asset-folder": {
+ "count": 1,
+ "totalBytes": 884,
+ "p95Bytes": 884,
+ "maxBytes": 884
+ },
+ "create-assets-resource": {
+ "count": 3,
+ "totalBytes": 6482,
+ "p95Bytes": 3158,
+ "maxBytes": 3158
+ },
+ "create-page": {
+ "count": 2,
+ "totalBytes": 2688,
+ "p95Bytes": 1346,
+ "maxBytes": 1346
+ },
+ "insert-collection": {
+ "count": 2,
+ "totalBytes": 4452,
+ "p95Bytes": 2259,
+ "maxBytes": 2259
+ },
+ "meta.get_more_tools": {
+ "count": 1,
+ "totalBytes": 116222,
+ "p95Bytes": 116222,
+ "maxBytes": 116222
+ },
+ "meta.guide": {
+ "count": 1,
+ "totalBytes": 6358,
+ "p95Bytes": 6358,
+ "maxBytes": 6358
+ },
+ "upload-assets": {
+ "count": 1,
+ "totalBytes": 3646,
+ "p95Bytes": 3646,
+ "maxBytes": 3646
+ },
+ "verify-page-responsive": {
+ "count": 2,
+ "totalBytes": 28506,
+ "p95Bytes": 14373,
+ "maxBytes": 14373
+ }
+ },
+ "retries": 0,
+ "focusedReads": 0,
+ "broadReads": 0,
+ "dryRuns": 1,
+ "plannedMutations": 1,
+ "committedMutations": 8,
+ "verifications": 2,
+ "totalDurationMs": 12491,
+ "p50DurationMs": 21,
+ "p95DurationMs": 10670,
+ "totalResponseBytes": 169238,
+ "p50ResponseBytes": 2259,
+ "p95ResponseBytes": 116222,
+ "maxResponseBytes": 116222,
+ "timeToFirstMutationMs": 30485,
+ "timeToFirstVerificationMs": 99015
+ }
+ },
+ "callSequence": [
+ "meta.guide",
+ "meta.get_more_tools",
+ "create-asset-folder",
+ "upload-assets",
+ "create-page",
+ "create-page",
+ "create-assets-resource",
+ "create-assets-resource",
+ "insert-collection",
+ "insert-collection",
+ "create-assets-resource",
+ "verify-page-responsive",
+ "verify-page-responsive"
+ ],
+ "checks": {
+ "guidance": "passed",
+ "privacy": "passed",
+ "expressions": "passed",
+ "boundedReads": "passed",
+ "markdownUploads": "passed",
+ "blogAssetFolder": "passed",
+ "blogRoutes": "passed",
+ "scopedBlogResources": "passed",
+ "listingQuery": "passed",
+ "detailQuery": "passed",
+ "editableBlogBindings": "passed",
+ "bindingVerification": "passed",
+ "blogRouteEvidence": "passed",
+ "usageCaptured": "passed"
+ }
+}
diff --git a/packages/cli/evaluations/high-impact/run-local-agent.ts b/packages/cli/evaluations/high-impact/run-local-agent.ts
index eff1ca8f74..b3644869b0 100644
--- a/packages/cli/evaluations/high-impact/run-local-agent.ts
+++ b/packages/cli/evaluations/high-impact/run-local-agent.ts
@@ -10,18 +10,21 @@ import { hideBin } from "yargs/helpers";
import {
fontAssetsFixture,
highImpactFixtures,
+ markdownBlogFixture,
type HighImpactFixture,
} from "./fixtures";
import { startHighImpactFixtureApi } from "./fixture-api";
import { evaluateHighImpactOutcome } from "./validate";
import {
runHighImpactAgentEvaluation,
+ getFixtureToolNames,
type AgentEvaluationResult,
} from "./agent-runner";
import { collectHighImpactArtifacts } from "./artifacts";
import type { EvaluationToolCall } from "./validate";
import type { McpCatalogObservation } from "./evaluation-metrics";
import { writeFontAssetFixtureFiles } from "./font-assets-fixture";
+import { writeMarkdownBlogFixtureFiles } from "./markdown-blog-fixture";
import {
compareEvaluationResult,
isAggregateTokenBaselineNonRegressed,
@@ -29,6 +32,7 @@ import {
shouldUpdateEvaluationBaselines,
type EvaluationComparison,
} from "./evaluation-regression";
+import { runConcurrently } from "./suite-runner";
const execFileAsync = promisify(execFile);
const require = createRequire(import.meta.url);
@@ -65,14 +69,16 @@ const runFixture = async ({
fixture,
repositoryRoot,
resultPath,
+ signal,
}: {
fixture: HighImpactFixture;
repositoryRoot: string;
resultPath: string;
+ signal: AbortSignal;
}) => {
const localCli = resolve(repositoryRoot, "packages/cli/local.js");
const codex = process.env.WEBSTUDIO_HIGH_IMPACT_CODEX ?? "codex";
- const model = process.env.WEBSTUDIO_HIGH_IMPACT_MODEL ?? "gpt-5.6-sol";
+ const model = process.env.WEBSTUDIO_HIGH_IMPACT_MODEL ?? "gpt-5.4-mini";
const directory = await mkdtemp(
join(tmpdir(), "webstudio-high-impact-agent-")
);
@@ -85,6 +91,8 @@ const runFixture = async ({
await mkdir(projectDirectory, { recursive: true });
if (fixture.id === fontAssetsFixture.id) {
await writeFontAssetFixtureFiles(projectDirectory);
+ } else if (fixture.id === markdownBlogFixture.id) {
+ await writeMarkdownBlogFixtureFiles(projectDirectory);
}
const env = { ...process.env, WEBSTUDIO_CONFIG_DIR: configDirectory };
try {
@@ -103,6 +111,7 @@ const runFixture = async ({
])}`,
`mcp_servers.webstudio.cwd=${JSON.stringify(projectDirectory)}`,
`mcp_servers.webstudio.env={ WEBSTUDIO_CONFIG_DIR = ${JSON.stringify(configDirectory)} }`,
+ `mcp_servers.webstudio.enabled_tools=${JSON.stringify(getFixtureToolNames(fixture))}`,
];
const agentCommand = [
shellQuote(codex),
@@ -139,6 +148,7 @@ const runFixture = async ({
provider: "openai",
model,
env,
+ signal,
getToolCalls: () => toolCalls,
getCatalogObservations: () => catalogObservations,
evaluate: async () => {
@@ -220,16 +230,23 @@ const run = async () => {
process.env.WEBSTUDIO_HIGH_IMPACT_BASELINE_DIR ??
join(import.meta.dirname, "results")
);
- const results: AgentEvaluationReport[] = [];
- const rawResults: AgentEvaluationResult[] = [];
+
+ const controller = new AbortController();
+ const abort = () => controller.abort();
+ process.once("SIGINT", abort);
+ process.once("SIGTERM", abort);
const baselines: AgentEvaluationResult[] = [];
- for (const fixture of fixtures) {
+ const completed = await runConcurrently(fixtures, async (fixture) => {
const resultPath = resolve(
process.env.WEBSTUDIO_HIGH_IMPACT_RESULT ??
join(resultsDirectory, `${fixture.id}.json`)
);
- const result = await runFixture({ fixture, repositoryRoot, resultPath });
- rawResults.push(result);
+ const result = await runFixture({
+ fixture,
+ repositoryRoot,
+ resultPath,
+ signal: controller.signal,
+ });
const baseline = await readFile(
join(baselineDirectory, `${fixture.id}.json`),
"utf8"
@@ -248,8 +265,15 @@ const run = async () => {
`${JSON.stringify(report, undefined, 2)}\n`,
"utf8"
);
- results.push(report);
- }
+ return { result, report };
+ }).finally(() => {
+ process.removeListener("SIGINT", abort);
+ process.removeListener("SIGTERM", abort);
+ });
+ const rawResults = completed.map(({ result }) => result);
+ const results: AgentEvaluationReport[] = completed.map(
+ ({ report }) => report
+ );
const evaluationsPassed = rawResults.every(
(result) => result.outcome === "passed"
);
diff --git a/packages/cli/evaluations/high-impact/suite-runner.test.ts b/packages/cli/evaluations/high-impact/suite-runner.test.ts
new file mode 100644
index 0000000000..bd708a7315
--- /dev/null
+++ b/packages/cli/evaluations/high-impact/suite-runner.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, test, vi } from "vitest";
+import { runConcurrently } from "./suite-runner";
+
+describe("evaluation suite runner", () => {
+ test("starts independent evaluations together and preserves result order", async () => {
+ const releases = Promise.withResolvers<void>();
+ const started: number[] = [];
+ const pending = runConcurrently([3, 1, 2], async (value) => {
+ started.push(value);
+ await releases.promise;
+ return value * 2;
+ });
+
+ await vi.waitFor(() => expect(started).toEqual([3, 1, 2]));
+ releases.resolve();
+ await expect(pending).resolves.toEqual([6, 2, 4]);
+ });
+
+ test("waits for every evaluation to clean up before reporting failures", async () => {
+ const cleanedUp: string[] = [];
+ await expect(
+ runConcurrently(["failed", "completed"], async (value) => {
+ try {
+ if (value === "failed") {
+ throw new Error("evaluation failed");
+ }
+ return value;
+ } finally {
+ cleanedUp.push(value);
+ }
+ })
+ ).rejects.toThrow("evaluation failed");
+ expect(cleanedUp).toEqual(expect.arrayContaining(["failed", "completed"]));
+ });
+});
diff --git a/packages/cli/evaluations/high-impact/suite-runner.ts b/packages/cli/evaluations/high-impact/suite-runner.ts
new file mode 100644
index 0000000000..2c8138910a
--- /dev/null
+++ b/packages/cli/evaluations/high-impact/suite-runner.ts
@@ -0,0 +1,18 @@
+export const runConcurrently = async <Value, Result>(
+ values: readonly Value[],
+ run: (value: Value) => Promise<Result>
+) => {
+ const settlements = await Promise.allSettled(values.map(run));
+ const failures = settlements.flatMap((settlement) =>
+ settlement.status === "rejected" ? [settlement.reason] : []
+ );
+ if (failures.length === 1) {
+ throw failures[0];
+ }
+ if (failures.length > 1) {
+ throw new AggregateError(failures, "Multiple evaluations failed to run");
+ }
+ return settlements.map((settlement) =>
+ settlement.status === "fulfilled" ? settlement.value : undefined
+ ) as Result[];
+};
diff --git a/packages/cli/evaluations/high-impact/validate.test.ts b/packages/cli/evaluations/high-impact/validate.test.ts
index 0c3081362a..c4bfa4b588 100644
--- a/packages/cli/evaluations/high-impact/validate.test.ts
+++ b/packages/cli/evaluations/high-impact/validate.test.ts
@@ -1,9 +1,12 @@
import { describe, expect, test } from "vitest";
+import { createStructuredAssetQueryResourceBody } from "@webstudio-is/sdk";
+import { assetsResourceUrl } from "@webstudio-is/sdk/runtime";
import {
authenticatedPageFixture,
designInputFixture,
fontAssetsFixture,
highImpactFixtures,
+ markdownBlogFixture,
validateHighImpactFixture,
type EvaluationProject,
} from "./fixtures";
@@ -11,6 +14,7 @@ import {
fontAssetFixtureFiles,
fontAssetFixtureMeta,
} from "./font-assets-fixture";
+import { markdownBlogFixtureArticles } from "./markdown-blog-fixture";
import { evaluateHighImpactOutcome, type EvaluationToolCall } from "./validate";
const clone = <Value>(value: Value): Value => structuredClone(value);
@@ -129,6 +133,182 @@ const addFontAssets = (): EvaluationProject => {
return project;
};
+const addMarkdownBlog = (): EvaluationProject => {
+ const project = clone(markdownBlogFixture.project);
+ project.assetFolders.push({
+ id: "blog-folder",
+ projectId: "project",
+ name: "Blog",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ });
+ project.assets.push(
+ ...markdownBlogFixtureArticles.map(({ name }) => ({
+ id: name,
+ projectId: "project",
+ name,
+ filename: name,
+ description: null,
+ folderId: "blog-folder",
+ size: 100,
+ type: "file" as const,
+ format: "md",
+ meta: {},
+ createdAt: "2026-01-01T00:00:00.000Z",
+ }))
+ );
+ project.pages.push(
+ {
+ id: "blog",
+ name: "Blog",
+ path: "/blog",
+ rootInstanceId: "blog-root",
+ },
+ {
+ id: "blog-detail",
+ name: "Blog post",
+ path: "/blog/:slug",
+ rootInstanceId: "blog-detail-root",
+ }
+ );
+ project.instances.push(
+ {
+ id: "blog-root",
+ component: "Body",
+ children: [{ type: "id", value: "blog-collection" }],
+ },
+ {
+ id: "blog-collection",
+ component: "Collection",
+ children: [{ type: "id", value: "blog-card" }],
+ },
+ {
+ id: "blog-card",
+ component: "Box",
+ children: [
+ { type: "expression", value: "collectionItem.properties.title" },
+ { type: "expression", value: "collectionItem.excerpt" },
+ {
+ type: "expression",
+ value: "collectionItem.properties.publishedAt",
+ },
+ { type: "expression", value: "collectionItem.properties.slug" },
+ ],
+ },
+ {
+ id: "blog-detail-root",
+ component: "Body",
+ children: [{ type: "id", value: "detail-collection" }],
+ },
+ {
+ id: "detail-collection",
+ component: "Collection",
+ children: [{ type: "id", value: "markdown" }],
+ },
+ {
+ id: "markdown",
+ component: "@webstudio-is/sdk-components-react:MarkdownEmbed",
+ children: [],
+ }
+ );
+ project.props.push({
+ id: "markdown-content",
+ instanceId: "markdown",
+ name: "content",
+ type: "expression",
+ value: "collectionItem.content.text",
+ });
+ const resource = (
+ id: string,
+ name: string,
+ body: string
+ ): Record<string, unknown> => ({
+ id,
+ name,
+ control: "system",
+ method: "post",
+ url: JSON.stringify(assetsResourceUrl),
+ headers: [],
+ body,
+ });
+ project.resources.push(
+ resource(
+ "posts-resource",
+ "Posts",
+ createStructuredAssetQueryResourceBody({
+ where: {
+ all: [
+ { field: ["extension"], operator: "eq", value: '"md"' },
+ {
+ field: ["properties", "draft"],
+ operator: "ne",
+ value: '"true"',
+ },
+ ],
+ },
+ sort: [
+ { field: ["properties", "publishedAt"], direction: "desc" },
+ { field: ["id"], direction: "asc" },
+ ],
+ limit: "20",
+ offset: "0",
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [
+ ["properties", "title"],
+ ["properties", "slug"],
+ ["properties", "publishedAt"],
+ ["excerpt"],
+ ],
+ },
+ content: { mode: "none" },
+ })
+ ),
+ resource(
+ "post-resource",
+ "Post",
+ createStructuredAssetQueryResourceBody({
+ where: {
+ all: [
+ { field: ["extension"], operator: "eq", value: '"md"' },
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "system.params.slug",
+ },
+ ],
+ },
+ sort: [],
+ limit: "1",
+ offset: "0",
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["properties", "title"]],
+ },
+ content: { mode: "markdown-body", maxBytes: 1_048_576 },
+ })
+ )
+ );
+ project.dataSources.push(
+ {
+ id: "posts",
+ type: "resource",
+ name: "posts",
+ scopeInstanceId: "blog-root",
+ resourceId: "posts-resource",
+ },
+ {
+ id: "post",
+ type: "resource",
+ name: "post",
+ scopeInstanceId: "blog-detail-root",
+ resourceId: "post-resource",
+ }
+ );
+ return project;
+};
+
const designCalls: EvaluationToolCall[] = [
{ name: "meta.guide" },
{ name: "list-breakpoints" },
@@ -146,6 +326,7 @@ describe("high-impact fixture validation", () => {
{ valid: true, failures: [] },
{ valid: true, failures: [] },
{ valid: true, failures: [] },
+ { valid: true, failures: [] },
]);
expect(JSON.stringify(highImpactFixtures)).toBe(
JSON.stringify(highImpactFixtures)
@@ -199,6 +380,51 @@ describe("font-assets evaluation", () => {
});
});
+describe("Markdown blog evaluation", () => {
+ const successfulCalls: EvaluationToolCall[] = [
+ { name: "meta.guide" },
+ { name: "verify-bindings" },
+ {
+ name: "verify-page-responsive",
+ arguments: {
+ path: "/blog",
+ viewports: [{ width: 1440 }, { width: 390 }],
+ },
+ },
+ {
+ name: "verify-page-responsive",
+ arguments: {
+ path: "/blog/aurora-trails",
+ viewports: [{ width: 1440 }, { width: 390 }],
+ },
+ },
+ ];
+
+ test("accepts a bounded two-route Markdown blog", () => {
+ expect(
+ evaluateHighImpactOutcome({
+ fixture: markdownBlogFixture,
+ project: addMarkdownBlog(),
+ toolCalls: successfulCalls,
+ })
+ ).toMatchObject({ passed: true, failures: [] });
+ });
+
+ test("rejects missing detail content and route evidence", () => {
+ const project = addMarkdownBlog();
+ project.resources = project.resources.slice(0, 1);
+ const result = evaluateHighImpactOutcome({
+ fixture: markdownBlogFixture,
+ project,
+ toolCalls: successfulCalls.slice(0, -1),
+ });
+ expect(result.checks).toMatchObject({
+ detailQuery: "failed",
+ blogRouteEvidence: "failed",
+ });
+ });
+});
+
describe("authenticated-page evaluation", () => {
test("accepts four editable states using the existing provider convention", () => {
const result = evaluateHighImpactOutcome({
diff --git a/packages/cli/evaluations/high-impact/validate.ts b/packages/cli/evaluations/high-impact/validate.ts
index 4de8571721..a6c520c6b3 100644
--- a/packages/cli/evaluations/high-impact/validate.ts
+++ b/packages/cli/evaluations/high-impact/validate.ts
@@ -1,10 +1,16 @@
import { parseExpressionAt } from "acorn";
import { getFontFaces } from "@webstudio-is/fonts";
-import type { FontAsset } from "@webstudio-is/sdk";
+import {
+ isAssetsResource,
+ parseStructuredAssetQueryResourceBody,
+ type FontAsset,
+ type Resource,
+} from "@webstudio-is/sdk";
import {
authenticatedPageFixture,
designInputFixture,
fontAssetsFixture,
+ markdownBlogFixture,
type EvaluationInstance,
type EvaluationProject,
type HighImpactFixture,
@@ -14,6 +20,7 @@ import {
fontAssetFixtureMeta,
fontAssetFixtureSource,
} from "./font-assets-fixture";
+import { markdownBlogFixtureArticles } from "./markdown-blog-fixture";
import { isBroadRead } from "./evaluation-metrics";
export type EvaluationToolCall = {
@@ -539,6 +546,214 @@ const validateFontAssets = (
);
};
+const getAssetResourceConfigurations = (project: EvaluationProject) =>
+ project.resources.flatMap((candidate) => {
+ const resource = candidate as Resource;
+ if (isAssetsResource(resource) === false) {
+ return [];
+ }
+ const configuration = parseStructuredAssetQueryResourceBody(resource.body);
+ return configuration === undefined ? [] : [{ resource, configuration }];
+ });
+
+const hasQueryFragment = (value: unknown, fragments: string[]) => {
+ const source = JSON.stringify(value);
+ return fragments.every((fragment) => source.includes(fragment));
+};
+
+const validateMarkdownBlog = (
+ input: HighImpactEvaluationInput,
+ checks: Record<string, "passed" | "failed">,
+ failures: string[]
+) => {
+ const expectedNames = new Set<string>(
+ markdownBlogFixtureArticles.map((article) => article.name)
+ );
+ const markdownAssets = input.project.assets.filter(
+ (asset) => asset.type === "file" && asset.format === "md"
+ );
+ const folderIds = new Set(markdownAssets.map((asset) => asset.folderId));
+ const blogFolder = input.project.assetFolders.find(
+ (folder) => folder.name === "Blog"
+ );
+ recordCheck(
+ checks,
+ failures,
+ "markdownUploads",
+ markdownAssets.length === expectedNames.size &&
+ markdownAssets.every((asset) => expectedNames.has(asset.name)),
+ "The five supplied Markdown articles were not uploaded as distinct file assets."
+ );
+ recordCheck(
+ checks,
+ failures,
+ "blogAssetFolder",
+ blogFolder !== undefined &&
+ folderIds.size === 1 &&
+ folderIds.has(blogFolder.id),
+ "The Markdown articles are not all stored in one Blog asset folder."
+ );
+
+ const overview = getPageEvaluationContext(input.project, "/blog");
+ const detail = getPageEvaluationContext(input.project, "/blog/:slug");
+ recordCheck(
+ checks,
+ failures,
+ "blogRoutes",
+ overview.page !== undefined && detail.page !== undefined,
+ "The /blog overview and /blog/:slug detail pages are required."
+ );
+
+ const configurations = getAssetResourceConfigurations(input.project);
+ const findConfigurationByDataSourceName = (name: string) => {
+ const resourceId = input.project.dataSources.find(
+ (dataSource) => dataSource.type === "resource" && dataSource.name === name
+ )?.resourceId;
+ return configurations.find(({ resource }) => resource.id === resourceId);
+ };
+ const listingEntry = findConfigurationByDataSourceName("posts");
+ const articleEntry = findConfigurationByDataSourceName("post");
+ const listing = listingEntry?.configuration;
+ const article = articleEntry?.configuration;
+ const overviewInstanceIds = new Set(
+ overview.instances.map((instance) => instance.id)
+ );
+ const detailInstanceIds = new Set(
+ detail.instances.map((instance) => instance.id)
+ );
+ const isResourceScopedTo = (
+ resourceId: string | undefined,
+ instanceIds: Set<string>
+ ) =>
+ resourceId !== undefined &&
+ input.project.dataSources.some(
+ (dataSource) =>
+ dataSource.type === "resource" &&
+ dataSource.resourceId === resourceId &&
+ instanceIds.has(String(dataSource.scopeInstanceId ?? ""))
+ );
+ recordCheck(
+ checks,
+ failures,
+ "scopedBlogResources",
+ isResourceScopedTo(listingEntry?.resource.id, overviewInstanceIds) &&
+ isResourceScopedTo(articleEntry?.resource.id, detailInstanceIds),
+ "Each Assets resource must be scoped to its corresponding blog page."
+ );
+ recordCheck(
+ checks,
+ failures,
+ "listingQuery",
+ listing !== undefined &&
+ hasQueryFragment(listing.where, [
+ "extension",
+ "md",
+ "draft",
+ "ne",
+ "true",
+ ]) &&
+ hasQueryFragment(listing.sort, ["publishedAt", "desc", "id", "asc"]) &&
+ hasQueryFragment(listing.limit, ["20"]) &&
+ hasQueryFragment(listing.output, [
+ "fields",
+ "title",
+ "slug",
+ "publishedAt",
+ "excerpt",
+ ]) &&
+ listing.output.includeMetadata === false,
+ "The overview Assets resource is not a bounded metadata-only published-post query."
+ );
+ recordCheck(
+ checks,
+ failures,
+ "detailQuery",
+ article !== undefined &&
+ article.content.mode === "markdown-body" &&
+ hasQueryFragment(article.where, [
+ "extension",
+ "md",
+ "slug",
+ "system.params.slug",
+ ]) &&
+ hasQueryFragment(article.limit, ["1"]) &&
+ article.output.includeMetadata === false &&
+ article.content.maxBytes === 1_048_576,
+ "The detail Assets resource does not select one Markdown body by the dynamic slug parameter."
+ );
+
+ const overviewSource = JSON.stringify({
+ instances: overview.instances,
+ props: input.project.props.filter((prop) =>
+ overview.instances.some((instance) => instance.id === prop.instanceId)
+ ),
+ });
+ const detailSource = JSON.stringify({
+ instances: detail.instances,
+ props: input.project.props.filter((prop) =>
+ detail.instances.some((instance) => instance.id === prop.instanceId)
+ ),
+ });
+ recordCheck(
+ checks,
+ failures,
+ "editableBlogBindings",
+ /Collection/i.test(overviewSource) &&
+ ["title", "excerpt", "publishedAt", "slug"].every((field) =>
+ overviewSource.includes(field)
+ ) &&
+ /Collection/i.test(detailSource) &&
+ /MarkdownEmbed/i.test(detailSource) &&
+ hasQueryFragment(detailSource, ["content", "text"]),
+ "The blog is not rendered through editable Collections and a Markdown Embed with the required bindings."
+ );
+ recordCheck(
+ checks,
+ failures,
+ "bindingVerification",
+ hasSuccessfulCall(input.toolCalls, "insert-fragment-verified") ||
+ hasSuccessfulCall(input.toolCalls, "verify-bindings") ||
+ hasSuccessfulCall(input.toolCalls, "insert-collection"),
+ "The persisted blog bindings were not verified."
+ );
+
+ const verificationCalls = input.toolCalls.filter(
+ (call) => call.name === "verify-page-responsive" && call.isError !== true
+ );
+ const verifiedPaths = new Set(
+ verificationCalls.map((call) => String(call.arguments?.path ?? ""))
+ );
+ const hasBothViewports = verificationCalls.every((call) => {
+ const viewports = Array.isArray(call.arguments?.viewports)
+ ? call.arguments.viewports
+ : [];
+ return (
+ viewports.some(
+ (viewport) =>
+ typeof viewport === "object" &&
+ viewport !== null &&
+ Number((viewport as { width?: unknown }).width) >= 1200
+ ) &&
+ viewports.some(
+ (viewport) =>
+ typeof viewport === "object" &&
+ viewport !== null &&
+ Number((viewport as { width?: unknown }).width) <= 479
+ )
+ );
+ });
+ recordCheck(
+ checks,
+ failures,
+ "blogRouteEvidence",
+ verificationCalls.length === 2 &&
+ verifiedPaths.has("/blog") &&
+ verifiedPaths.has("/blog/aurora-trails") &&
+ hasBothViewports,
+ "Both blog routes require successful desktop and mobile rendered verification."
+ );
+};
+
export const evaluateHighImpactOutcome = (
input: HighImpactEvaluationInput
): HighImpactEvaluationResult => {
@@ -549,6 +764,8 @@ export const evaluateHighImpactOutcome = (
validateAuth(input, checks, failures);
} else if (input.fixture.id === fontAssetsFixture.id) {
validateFontAssets(input, checks, failures);
+ } else if (input.fixture.id === markdownBlogFixture.id) {
+ validateMarkdownBlog(input, checks, failures);
} else {
validateDesign(input, checks, failures);
}
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 22a9840ab7..bcedeb6341 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -18,7 +18,9 @@
"scripts": {
"typecheck": "tsc --noEmit",
"generate-docs": "tsx scripts/generate-docs.ts && oxfmt src/docs.generated.ts",
- "build": "pnpm generate-docs && rm -rf lib && vite build",
+ "build:content-runtime": "esbuild @webstudio-is/content-engine/runtime --bundle --format=esm --platform=browser --target=es2022 --conditions=webstudio --minify --outfile=lib/content-runtime.js",
+ "build": "pnpm generate-docs && rm -rf lib && vite build && pnpm build:content-runtime",
+ "pretest": "mkdir -p lib && pnpm build:content-runtime",
"evaluations": "tsx --conditions=webstudio evaluations/high-impact/run-local-agent.ts",
"test": "vitest run",
"test:release-smoke": "pnpm build && tsx --conditions=webstudio scripts/release-smoke.ts",
@@ -79,9 +81,12 @@
"@vercel/react-router": "^1.1.0",
"@vitejs/plugin-react": "^4.4.1",
"@webstudio-is/css-engine": "workspace:*",
+ "@webstudio-is/content-engine": "workspace:*",
+ "@webstudio-is/expression": "workspace:*",
"@webstudio-is/fonts": "workspace:*",
"@webstudio-is/image": "workspace:*",
"@webstudio-is/project-build": "workspace:*",
+ "@webstudio-is/query-builder": "workspace:*",
"@webstudio-is/react-sdk": "workspace:*",
"@webstudio-is/sdk": "workspace:*",
"@webstudio-is/sdk-components-animation": "workspace:*",
diff --git a/packages/cli/scripts/run-agent-command.test.ts b/packages/cli/scripts/run-agent-command.test.ts
index cae8fdde30..81c559a77c 100644
--- a/packages/cli/scripts/run-agent-command.test.ts
+++ b/packages/cli/scripts/run-agent-command.test.ts
@@ -39,4 +39,18 @@ describe("runAgentCommand", () => {
})
).rejects.toThrow("Agent command timed out after 50ms.");
});
+
+ test("terminates the process group when the caller aborts", async () => {
+ const controller = new AbortController();
+ const pending = runAgentCommand({
+ command: `${JSON.stringify(process.execPath)} -e 'setInterval(() => {}, 1000)'`,
+ cwd: process.cwd(),
+ env: process.env,
+ timeoutMs: 5_000,
+ signal: controller.signal,
+ });
+ controller.abort();
+
+ await expect(pending).rejects.toThrow(/aborted|signal SIGTERM/);
+ });
});
diff --git a/packages/cli/scripts/run-agent-command.ts b/packages/cli/scripts/run-agent-command.ts
index 2becac421a..37030e2977 100644
--- a/packages/cli/scripts/run-agent-command.ts
+++ b/packages/cli/scripts/run-agent-command.ts
@@ -6,12 +6,14 @@ export const runAgentCommand = ({
env,
timeoutMs,
onStdoutLine,
+ signal,
}: {
command: string;
cwd: string;
env: NodeJS.ProcessEnv;
timeoutMs: number;
onStdoutLine?: (line: string) => void;
+ signal?: AbortSignal;
}) =>
new Promise<{ exitCode: number; durationMs: number }>((resolve, reject) => {
const startedAt = Date.now();
@@ -37,27 +39,44 @@ export const runAgentCommand = ({
}
});
}
- const timeout = setTimeout(() => {
+ const terminate = () => {
if (child.pid !== undefined) {
try {
process.kill(process.platform === "win32" ? child.pid : -child.pid);
} catch {}
}
+ };
+ const onAbort = () => terminate();
+ signal?.addEventListener("abort", onAbort, { once: true });
+ const cleanup = () => {
+ clearTimeout(timeout);
+ signal?.removeEventListener("abort", onAbort);
+ };
+ const timeout = setTimeout(() => {
+ terminate();
+ cleanup();
reject(new Error(`Agent command timed out after ${timeoutMs}ms.`));
}, timeoutMs);
child.once("error", (error) => {
- clearTimeout(timeout);
+ cleanup();
reject(error);
});
- child.once("close", (code, signal) => {
- clearTimeout(timeout);
+ child.once("close", (code, childSignal) => {
+ cleanup();
if (onStdoutLine !== undefined && stdoutBuffer.length > 0) {
onStdoutLine(stdoutBuffer);
}
- if (signal !== null) {
- reject(new Error(`Agent command exited from signal ${signal}.`));
+ if (childSignal !== null) {
+ reject(new Error(`Agent command exited from signal ${childSignal}.`));
+ return;
+ }
+ if (signal?.aborted) {
+ reject(new Error("Agent command was aborted."));
return;
}
resolve({ exitCode: code ?? -1, durationMs: Date.now() - startedAt });
});
+ if (signal?.aborted) {
+ terminate();
+ }
});
diff --git a/packages/cli/src/commands/api-command-docs.test.ts b/packages/cli/src/commands/api-command-docs.test.ts
index d340c1b999..f2c76cddea 100644
--- a/packages/cli/src/commands/api-command-docs.test.ts
+++ b/packages/cli/src/commands/api-command-docs.test.ts
@@ -176,6 +176,49 @@ test("documents MCP use cases with JSON inputs instead of CLI flags", () => {
}
});
+test("does not require publishing or sync before MCP editing", () => {
+ for (const document of ["manual-llm", "manual-mcp"] as const) {
+ const manual = readCliDoc(document);
+ const prose = manual.replaceAll(/\s+/g, " ");
+ expect(prose).toContain("local CLI");
+ expect(prose).toContain("connect");
+ expect(prose).toContain("optional");
+ expect(prose).toContain("restart");
+ expect(prose).not.toContain(
+ "followed by `webstudio sync`, then retry `webstudio connect"
+ );
+ }
+ const llmManual = readCliDoc("manual-llm").replaceAll(/\s+/g, " ");
+ expect(llmManual).toContain(
+ "MCP reads and edits the latest editable Builder build directly"
+ );
+ expect(llmManual).toContain(
+ "including for projects that have never been published"
+ );
+});
+
+test("documents the Assets result shape", () => {
+ for (const document of ["api-use-cases", "manual-llm"] as const) {
+ const contents = readCliDoc(document);
+ expect(contents).toContain("<dataSourceName>.data");
+ expect(contents).toContain("<dataSourceName>.meta");
+ expect(contents).toContain("posts.data");
+ expect(contents).toContain("post.data");
+ expect(contents).toContain("content.text");
+ }
+});
+
+test("documents storage-efficient Assets queries for agents", () => {
+ for (const document of ["api-use-cases", "manual-llm"] as const) {
+ const contents = readCliDoc(document);
+ expect(contents).toContain('output.mode:"fields"');
+ expect(contents).toContain("only fields");
+ expect(contents).toContain("includeMetadata:false");
+ expect(contents).toContain("__diagnostics__.usedBytes");
+ expect(contents).toContain("truncated");
+ }
+});
+
test("documents MCP examples with current tool input fields", () => {
const adapter = createMetadataOnlyMcpAdapter();
const toolInputFields = new Map(
diff --git a/packages/cli/src/commands/api-command-metadata.test.ts b/packages/cli/src/commands/api-command-metadata.test.ts
index ced5eb366f..dd67cafdef 100644
--- a/packages/cli/src/commands/api-command-metadata.test.ts
+++ b/packages/cli/src/commands/api-command-metadata.test.ts
@@ -158,6 +158,23 @@ test("parses redirect status as a string option", () => {
);
});
+test("uses JSON as the only variable array type", () => {
+ const yargs = { option: vi.fn().mockReturnThis() };
+ const metadata = apiCommandMetadata.find(
+ (item) => item.command === "create-variable"
+ );
+
+ expect(metadata).toBeDefined();
+ getApiCommandOptions(metadata!)(yargs as never);
+
+ expect(yargs.option).toHaveBeenCalledWith(
+ "value-type",
+ expect.objectContaining({
+ choices: ["string", "number", "boolean", "json"],
+ })
+ );
+});
+
test("describes list-folders pagination and detail options", () => {
const yargs = { option: vi.fn().mockReturnThis() };
const metadata = apiCommandMetadata.find(
diff --git a/packages/cli/src/commands/api-command-metadata.ts b/packages/cli/src/commands/api-command-metadata.ts
index b5b2b0d5f4..2a5032ad6b 100644
--- a/packages/cli/src/commands/api-command-metadata.ts
+++ b/packages/cli/src/commands/api-command-metadata.ts
@@ -200,6 +200,9 @@ const apiCommandOptionsByCommand: Partial<
"update-variable": apiCommand.updateVariableCommandOptions,
"delete-variable": apiCommand.deleteVariableCommandOptions,
"list-resources": apiCommand.scopedCommandOptions,
+ "get-assets-resource": apiCommand.assetResourceCommandOptions,
+ "create-assets-resource": apiCommand.inputCommandOptions,
+ "update-assets-resource": apiCommand.inputCommandOptions,
"list-publishes": apiCommand.paginatedListCommandOptions,
"create-resource": apiCommand.createResourceCommandOptions,
"update-resource": apiCommand.updateResourceCommandOptions,
@@ -242,6 +245,9 @@ export const apiCommandMetadata = publicApiOperations.map((operation) => ({
export const highLevelCliCommands = [
{ command: "audit", operation: "audit" },
{ command: "permissions", operation: "permissions" },
+ { command: "get-assets-resource", operation: "get-assets-resource" },
+ { command: "create-assets-resource", operation: "create-assets-resource" },
+ { command: "update-assets-resource", operation: "update-assets-resource" },
{
command: "get-marketplace-product",
operation: "get-marketplace-product",
diff --git a/packages/cli/src/commands/api-command.test.ts b/packages/cli/src/commands/api-command.test.ts
index 434499dde0..5b2297b887 100644
--- a/packages/cli/src/commands/api-command.test.ts
+++ b/packages/cli/src/commands/api-command.test.ts
@@ -341,6 +341,23 @@ test("selects a previously linked project explicitly", async () => {
);
});
+test("isolates the session for a previously linked project", async () => {
+ readFile.mockResolvedValueOnce(
+ JSON.stringify({
+ "project-2": { origin: "https://example.com", token: "token-1" },
+ })
+ );
+
+ await apiCommand(
+ { command: "list-pages", project: "project-2", json: true },
+ dependencies
+ );
+
+ expect(createCliProjectSession).toHaveBeenCalledWith(
+ expect.objectContaining({ sessionProjectId: "project-2" })
+ );
+});
+
test("explains mcp-only editing commands should use shortcut or single-op-call", async () => {
mockConfig();
@@ -1564,14 +1581,14 @@ test("creates variable with parsed value", async () => {
command: "create-variable",
scopeInstance: "body-id",
name: "items",
- valueType: "string[]",
+ valueType: "json",
value: '["a","b"]',
},
call: apiCalls.createVariable,
connection: {
scopeInstanceId: "body-id",
name: "items",
- value: { type: "string[]", value: ["a", "b"] },
+ value: { type: "json", value: ["a", "b"] },
},
});
});
diff --git a/packages/cli/src/commands/api-command.ts b/packages/cli/src/commands/api-command.ts
index a2a0c82b4a..f73e5e8a4d 100644
--- a/packages/cli/src/commands/api-command.ts
+++ b/packages/cli/src/commands/api-command.ts
@@ -53,6 +53,7 @@ export type ApiCommandName = ProjectSessionApiCommand;
let activeApiCommandDryRun = false;
let activeApiCommandRefresh = false;
+let activeApiCommandSessionProjectId: string | undefined;
export const apiCommandOptions = (yargs: CommonYargsArgv) =>
yargs
@@ -106,6 +107,19 @@ const requiredInputOption = (yargs: CommonYargsArgv, describe: string) =>
demandOption: true,
});
+export const inputCommandOptions = (yargs: CommonYargsArgv) =>
+ requiredInputOption(
+ apiCommandOptions(yargs),
+ "Required JSON file containing the command input."
+ );
+
+export const assetResourceCommandOptions = (yargs: CommonYargsArgv) =>
+ apiCommandOptions(yargs).option("resource", {
+ type: "string",
+ describe: "Required Assets resource id",
+ demandOption: true,
+ });
+
const confirmOption = (yargs: CommonYargsArgv, describe: string) =>
yargs.option("confirm", {
type: "boolean",
@@ -958,14 +972,13 @@ export const createVariableCommandOptions = (yargs: CommonYargsArgv) =>
demandOption: true,
})
.option("value-type", {
- choices: ["string", "number", "boolean", "string[]", "json"] as const,
+ choices: ["string", "number", "boolean", "json"] as const,
describe: "Required variable value type",
demandOption: true,
})
.option("value", {
type: "string",
- describe:
- "Required variable value; use JSON for json and string[] value types",
+ describe: "Required variable value; use JSON for arrays and objects",
demandOption: true,
});
@@ -985,12 +998,12 @@ export const updateVariableCommandOptions = (yargs: CommonYargsArgv) =>
describe: "Update variable name used in expressions",
})
.option("value-type", {
- choices: ["string", "number", "boolean", "string[]", "json"] as const,
+ choices: ["string", "number", "boolean", "json"] as const,
describe: "Variable value type when updating --value",
})
.option("value", {
type: "string",
- describe: "Updated variable value; use JSON for json and string[] types",
+ describe: "Updated variable value; use JSON for arrays and objects",
});
export const deleteVariableCommandOptions = (yargs: CommonYargsArgv) =>
@@ -1367,7 +1380,7 @@ export type ApiCommandOptions = {
text?: string;
childDepth?: number;
mode?: "text" | "expression" | "all" | "append" | "prepend" | "replace";
- valueType?: "string" | "number" | "boolean" | "string[]" | "json";
+ valueType?: "string" | "number" | "boolean" | "json";
value?: string;
method?: "get" | "post" | "put" | "delete";
url?: string;
@@ -1682,15 +1695,6 @@ const parseVariableValue = (
return { type: valueType, value: rawValue === "true" };
}
const parsed = JSON.parse(rawValue) as unknown;
- if (valueType === "string[]") {
- if (
- Array.isArray(parsed) === false ||
- parsed.every((item) => typeof item === "string") === false
- ) {
- throw new Error("--value must be a JSON array of strings.");
- }
- return { type: valueType, value: parsed };
- }
return { type: "json", value: parsed };
};
@@ -1827,7 +1831,11 @@ const runProjectSessionCommand = async (
command,
input,
connection,
- createProjectSession: dependencies.createCliProjectSession,
+ createProjectSession: (options) =>
+ dependencies.createCliProjectSession({
+ ...options,
+ sessionProjectId: activeApiCommandSessionProjectId,
+ }),
getServerApiContract: dependencies.getServerApiContract,
dryRun: options.dryRun ?? activeApiCommandDryRun,
refresh: activeApiCommandRefresh,
@@ -2864,6 +2872,27 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
dependencies
);
},
+ "get-assets-resource": async (options, connection, dependencies) =>
+ runProjectSessionCommand(
+ "get-assets-resource",
+ { resourceId: requireOption(options.resource, "--resource") },
+ connection,
+ dependencies
+ ),
+ "create-assets-resource": async (options, connection, dependencies) =>
+ runProjectSessionCommand(
+ "create-assets-resource",
+ await readInputObject(dependencies, options),
+ connection,
+ dependencies
+ ),
+ "update-assets-resource": async (options, connection, dependencies) =>
+ runProjectSessionCommand(
+ "update-assets-resource",
+ await readInputObject(dependencies, options),
+ connection,
+ dependencies
+ ),
"create-resource": async (options, connection, dependencies) => {
const input = {
resource: (await getResourceFields(
@@ -3166,12 +3195,15 @@ export const apiCommand = async (
}
const previousDryRun = activeApiCommandDryRun;
const previousRefresh = activeApiCommandRefresh;
+ const previousSessionProjectId = activeApiCommandSessionProjectId;
activeApiCommandDryRun = options.dryRun === true;
activeApiCommandRefresh = options.refresh === true;
+ activeApiCommandSessionProjectId = options.project;
const response = await query(options, apiConnection, dependencies).finally(
() => {
activeApiCommandDryRun = previousDryRun;
activeApiCommandRefresh = previousRefresh;
+ activeApiCommandSessionProjectId = previousSessionProjectId;
}
);
const session = isProjectSessionEnvelope(response)
diff --git a/packages/cli/src/commands/connect.test.ts b/packages/cli/src/commands/connect.test.ts
index 9857adfda6..6c025bfeb5 100644
--- a/packages/cli/src/commands/connect.test.ts
+++ b/packages/cli/src/commands/connect.test.ts
@@ -39,6 +39,7 @@ const linkedProject = { ".webstudio/config.json": "{}" };
test("creates .mcp.json for claude with the default server command", async () => {
const dependencies = createDependencies(linkedProject);
+ const success = vi.spyOn(log, "success").mockImplementation(() => {});
await connect({ client: "claude", print: false }, dependencies);
@@ -57,6 +58,9 @@ test("creates .mcp.json for claude with the default server command", async () =>
2
)}\n`
);
+ expect(success).toHaveBeenCalledWith(
+ expect.stringContaining("can be edited before it is published")
+ );
});
test("merges the webstudio entry into an existing config preserving user fields", async () => {
diff --git a/packages/cli/src/commands/connect.ts b/packages/cli/src/commands/connect.ts
index 747c99af97..70e70aa84b 100644
--- a/packages/cli/src/commands/connect.ts
+++ b/packages/cli/src/commands/connect.ts
@@ -241,7 +241,7 @@ export const connectOptions = (yargs: CommonYargsArgv) =>
"Project access is verified before client configuration is written.",
"Existing config files are merged: only the webstudio server entry is created or replaced.",
"Codex uses global configuration, so connect registers and verifies the server with the codex CLI.",
- "Run webstudio init --link and webstudio sync first so the MCP server can operate the project.",
+ "Run webstudio init --link first if the folder is not linked. MCP operates on the latest editable build; publishing and webstudio sync are not required.",
].join("\n")
);
@@ -304,7 +304,7 @@ export const connect = async (
throw new HandledCliError();
}
log.success(
- "Registered and verified the webstudio MCP server in Codex. Restart Codex, then ask it to use Webstudio MCP and list the project pages."
+ "Registered and verified the webstudio MCP server in Codex. The linked project can be edited before it is published. Restart Codex, then ask it to use Webstudio MCP and list the project pages."
);
return;
}
@@ -314,7 +314,7 @@ export const connect = async (
parsedServerCommand,
"serverFields" in target ? target.serverFields : undefined
);
- const completionHint = `${target.hint} Ask your agent to use Webstudio MCP and list the project pages.`;
+ const completionHint = `The linked project can be edited before it is published. ${target.hint} Ask your agent to use Webstudio MCP and list the project pages.`;
const path = join(cwd(), target.path);
const current = (await dependencies.isFileExists(path))
diff --git a/packages/cli/src/commands/link.test.ts b/packages/cli/src/commands/link.test.ts
index 18298da368..31f7eeed4a 100644
--- a/packages/cli/src/commands/link.test.ts
+++ b/packages/cli/src/commands/link.test.ts
@@ -1,4 +1,5 @@
-import { afterEach, beforeEach, expect, test } from "vitest";
+import { log } from "@clack/prompts";
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
import {
copyFile,
mkdir,
@@ -10,7 +11,7 @@ import {
import { dirname, join } from "node:path";
import { tmpdir } from "node:os";
import { GLOBAL_CONFIG_FILE, LOCAL_CONFIG_FILE } from "../config";
-import { parseShareLink, saveShareLink, validateShareLink } from "./link";
+import { link, parseShareLink, saveShareLink, validateShareLink } from "./link";
const originalCwd = process.cwd();
const projectId = "11111111-1111-4111-8111-111111111111";
@@ -39,6 +40,22 @@ afterEach(async () => {
await rm(GLOBAL_CONFIG_FILE, { force: true });
}
await rm(tempDir, { recursive: true, force: true });
+ vi.restoreAllMocks();
+});
+
+test("offers immediate local CLI use without requiring native MCP setup", async () => {
+ vi.spyOn(log, "info").mockImplementation(() => {});
+ const step = vi.spyOn(log, "step").mockImplementation(() => {});
+
+ await link({ link: shareLink });
+
+ expect(step).toHaveBeenCalledWith(
+ expect.stringContaining("webstudio meta.index` immediately")
+ );
+ expect(step).toHaveBeenCalledWith(
+ expect.stringContaining("webstudio connect <client>` is optional")
+ );
+ expect(step).not.toHaveBeenCalledWith(expect.stringContaining("sync"));
});
test("parses and validates share links", () => {
diff --git a/packages/cli/src/commands/link.ts b/packages/cli/src/commands/link.ts
index 6cabdc0326..37d3695d34 100644
--- a/packages/cli/src/commands/link.ts
+++ b/packages/cli/src/commands/link.ts
@@ -127,6 +127,6 @@ export const link = async (
log.info(`Saved credentials for project ${projectId}.
You can find your config at ${GLOBAL_CONFIG_FILE}`);
log.step(
- "The project is linked successfully. Next run `webstudio sync`, then `webstudio connect <client>` to configure an agent."
+ "The project is linked successfully. Use local CLI tools such as `webstudio meta.index` immediately. `webstudio connect <client>` is optional native MCP setup."
);
};
diff --git a/packages/cli/src/commands/man.ts b/packages/cli/src/commands/man.ts
index 6bd92e56de..b7ccc6276a 100644
--- a/packages/cli/src/commands/man.ts
+++ b/packages/cli/src/commands/man.ts
@@ -472,6 +472,9 @@ const apiCommandsByArea = {
projectQuality: cliCommandMetadata
.filter(({ cliCommand }) => cliCommand === "audit")
.map(({ cliCommand }) => cliCommand),
+ assetsAndIndexes: cliCommandMetadata
+ .filter(({ cliCommand }) => cliCommand.includes("asset"))
+ .map(({ cliCommand }) => cliCommand),
publishAndDomains: cliCommandMetadata
.filter(
({ cliCommand }) =>
diff --git a/packages/cli/src/commands/mcp-preview.test.ts b/packages/cli/src/commands/mcp-preview.test.ts
index 1cfc3ddb7b..a2ec13c7d1 100644
--- a/packages/cli/src/commands/mcp-preview.test.ts
+++ b/packages/cli/src/commands/mcp-preview.test.ts
@@ -411,6 +411,46 @@ test("reuses and closes one browser capture session for session screenshots", as
expect(preview.stop).toHaveBeenCalledOnce();
});
+test("applies internal page credentials only to owned preview captures", async () => {
+ const preview = {
+ status: vi.fn(() => ({
+ url: "http://127.0.0.1:3000/",
+ running: true,
+ mode: "production" as const,
+ })),
+ startAndWait: vi.fn(),
+ resolveUrl: vi.fn((path: string) => `http://127.0.0.1:3000${path}`),
+ };
+ const capture = createCaptureScreenshotMock([]);
+ const handlers = createMcpPreviewHandlers({
+ preview,
+ isStale: () => false,
+ createCaptureSession: () => ({
+ capture,
+ capturePage: vi.fn(async () => []),
+ close: vi.fn(async () => undefined),
+ }),
+ getHttpCredentials: (path) =>
+ path === "/private"
+ ? { username: "editor", password: "secret" }
+ : undefined,
+ });
+
+ await handlers.captureScreenshot({
+ path: "/private",
+ source: "session",
+ mode: "production",
+ viewport: { width: 1440, height: 900 },
+ });
+
+ expect(capture).toHaveBeenCalledWith(
+ expect.objectContaining({
+ url: "http://127.0.0.1:3000/private",
+ httpCredentials: { username: "editor", password: "secret" },
+ })
+ );
+});
+
test("waits for an active capture before stopping preview resources", async () => {
let finishCapture: () => void = () => undefined;
const captureBlocked = new Promise<void>((resolve) => {
diff --git a/packages/cli/src/commands/mcp-preview.ts b/packages/cli/src/commands/mcp-preview.ts
index 02be59bbac..bd0d4da287 100644
--- a/packages/cli/src/commands/mcp-preview.ts
+++ b/packages/cli/src/commands/mcp-preview.ts
@@ -162,6 +162,7 @@ export const createMcpPreviewHandlers = ({
prepareSessionDataFile,
captureScreenshot = captureScreenshotWithBrowserInstall,
createCaptureSession,
+ getHttpCredentials,
sleep = defaultSleep,
}: {
preview: McpPreviewController;
@@ -173,6 +174,9 @@ export const createMcpPreviewHandlers = ({
captureScreenshot?: typeof captureScreenshotWithBrowserInstall;
createCaptureSession?: typeof createScreenshotCaptureSession;
sleep?: (durationMs: number) => Promise<void>;
+ getHttpCredentials?: (
+ path: string
+ ) => { username: string; password: string } | undefined;
}) => {
let captureSession:
| ReturnType<typeof createScreenshotCaptureSession>
@@ -309,6 +313,12 @@ export const createMcpPreviewHandlers = ({
};
const getCaptureOptions = (input: McpScreenshotInput, url: string) => ({
url,
+ httpCredentials:
+ input.path !== undefined &&
+ input.url === undefined &&
+ input.baseUrl === undefined
+ ? getHttpCredentials?.(input.path)
+ : undefined,
output: input.output,
width: input.viewport.width,
height: input.viewport.height,
diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.ts
index 613de0bee9..972ee7fab7 100644
--- a/packages/cli/src/commands/mcp.ts
+++ b/packages/cli/src/commands/mcp.ts
@@ -11,13 +11,16 @@ import {
type ProjectSessionScreenshotInput,
type ProjectSessionMcpTool,
} from "@webstudio-is/project-build/mcp";
-import type { BuilderNamespace } from "@webstudio-is/project-build/contracts";
+import {
+ getProjectBasicAuthCredentials,
+ type BuilderNamespace,
+} from "@webstudio-is/project-build/contracts";
import { diffPngFiles } from "@webstudio-is/project-build/visual";
import {
publicApiOperationRequiresServerSupport,
publicApiOperations,
} from "@webstudio-is/protocol";
-import { importProjectBundleWithAssets } from "@webstudio-is/http-client";
+import * as httpClient from "@webstudio-is/http-client";
import packageJson from "../../package.json" with { type: "json" };
import type { ProjectSessionSnapshot } from "@webstudio-is/project-build/project-session";
import type { SemanticValidationIssue } from "@webstudio-is/project-build/runtime";
@@ -37,6 +40,7 @@ import {
getCliProjectRestorePointsFile,
getCliServerApiContract,
getSupportedPublicApiOperations,
+ loadCliProjectSessionAssetIndex,
type CliServerApiContract,
writeCliProjectSessionDataFile,
} from "../project-session";
@@ -52,6 +56,7 @@ import {
createLocalUpdateAssetContentInput,
downloadAssetFile,
getLocalAssetPath,
+ LOCAL_ASSETS_DIR,
} from "../asset-files";
import {
getVisionVerificationLoop,
@@ -938,11 +943,23 @@ const createCliMcpHost = async ({
isStale: previewFreshness.isStale,
captureFreshness: previewFreshness.capture,
markFresh: previewFreshness.markFresh,
+ getHttpCredentials: (pagePath) =>
+ getProjectBasicAuthCredentials(
+ getLoadedProjectSessionSnapshot(session).state.projectSettings?.meta
+ .auth,
+ pagePath
+ ),
prepareSessionDataFile: async () => {
+ const snapshot = getLoadedProjectSessionSnapshot(session);
+ const assetIndex = await loadCliProjectSessionAssetIndex(
+ snapshot,
+ apiConnection,
+ path.join(projectRoot, LOCAL_ASSETS_DIR)
+ );
await writeCliProjectSessionDataFile(
- getLoadedProjectSessionSnapshot(session),
+ snapshot,
path.join(projectRoot, LOCAL_DATA_FILE),
- { origin: connection.origin }
+ { origin: connection.origin, assetIndex }
);
},
});
@@ -1030,7 +1047,8 @@ const createCliMcpHost = async ({
skipAssets: input.skipAssets,
},
{
- importProjectBundleWithAssets,
+ importProjectBundleWithAssets:
+ httpClient.importProjectBundleWithAssets,
loadJSONFile,
readFile,
text: async () => {
diff --git a/packages/cli/src/commands/preview.test.ts b/packages/cli/src/commands/preview.test.ts
index ef8b7e02f7..b348b1aba9 100644
--- a/packages/cli/src/commands/preview.test.ts
+++ b/packages/cli/src/commands/preview.test.ts
@@ -170,6 +170,7 @@ test("prepares preview by syncing missing data and generating the app template",
expect(prebuildProject).toHaveBeenCalledWith({
assets: true,
template: ["react-router"],
+ previewIdentity: true,
});
expect(result.cwd).toBe(getPreviewProjectDir());
});
@@ -199,6 +200,7 @@ test("prepares local verification previews with draft routes", async () => {
assets: true,
template: ["react-router"],
includeDraftPages: true,
+ previewIdentity: true,
});
});
@@ -260,6 +262,7 @@ test("generates preview project in isolated directory", async () => {
expect(prebuildProject).toHaveBeenCalledWith({
assets: true,
template: ["react-router"],
+ previewIdentity: true,
});
expect(ensureDependencies).toHaveBeenCalledOnce();
});
@@ -337,6 +340,7 @@ test("regenerates a production cache before using it for iterative preview", asy
assets: true,
template: ["react-router"],
preserveRouteTemplates: true,
+ previewIdentity: true,
});
});
@@ -535,6 +539,7 @@ test("materializes session data before previewing from session source", async ()
expect(prebuildProject).toHaveBeenCalledWith({
assets: true,
template: ["react-router"],
+ previewIdentity: true,
});
});
@@ -615,6 +620,7 @@ test("keeps the standalone React Router preview template", async () => {
expect(prebuildProject).toHaveBeenCalledWith({
assets: true,
template: ["react-router"],
+ previewIdentity: true,
});
});
diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.ts
index dc1f310576..f6ad0d2a6d 100644
--- a/packages/cli/src/commands/preview.ts
+++ b/packages/cli/src/commands/preview.ts
@@ -41,6 +41,7 @@ import { sync, defaultSyncDependencies, type SyncDependencies } from "./sync";
import { resolveApiConnection } from "../api-connection";
import {
createCliProjectSession,
+ loadCliProjectSessionAssetIndex,
writeCliProjectSessionDataFile,
} from "../project-session";
import { LOCAL_ASSETS_DIR } from "../asset-files";
@@ -441,8 +442,14 @@ export const preparePreviewProject = async ({
const session = createCliProjectSession({ connection });
await session.initialize();
const snapshot = await session.ensureNamespaces(builderNamespaces);
+ const assetIndex = await loadCliProjectSessionAssetIndex(
+ snapshot,
+ connection,
+ join(cwd(), LOCAL_ASSETS_DIR)
+ );
await writeCliProjectSessionDataFile(snapshot, undefined, {
origin: connection.origin,
+ assetIndex,
});
},
}: {
@@ -528,6 +535,7 @@ export const preparePreviewProject = async ({
await prebuildProject({
assets,
template: getPreviewTemplates(template),
+ previewIdentity: true,
...(silent ? { silent: true } : {}),
...(includeDraftPages ? { includeDraftPages: true } : {}),
...(reuseGeneratedProject ? { incremental: true } : {}),
diff --git a/packages/cli/src/commands/sync.test.ts b/packages/cli/src/commands/sync.test.ts
index af8b9ca86c..a59affce82 100644
--- a/packages/cli/src/commands/sync.test.ts
+++ b/packages/cli/src/commands/sync.test.ts
@@ -82,7 +82,7 @@ test("writes current data version after synchronizing from the API", async () =>
bundleVersion,
});
expect(indicator.stop).toHaveBeenCalledWith(
- "Project bundle synchronized successfully (AGENTS.md: unchanged). Next: webstudio connect"
+ "Project bundle synchronized successfully (AGENTS.md: unchanged). Next: webstudio build"
);
});
@@ -111,7 +111,7 @@ test("materializes project agent instructions during sync", async () => {
"Use existing design tokens."
);
expect(indicator.stop).toHaveBeenCalledWith(
- "Project bundle synchronized successfully (AGENTS.md: created). Next: webstudio connect"
+ "Project bundle synchronized successfully (AGENTS.md: created). Next: webstudio build"
);
});
@@ -247,7 +247,8 @@ test("explains unpublished project bundle errors when synchronizing linked proje
[
"Unable to synchronize project bundle because the project is not published.",
"`webstudio sync` downloads the published project bundle.",
- "For visual verification of current MCP/API edits, use `preview.start` or `webstudio preview --source session` instead.",
+ "Publishing is not required for MCP editing. Do not ask the user to publish; use MCP tools against the latest editable build.",
+ "For visual verification, use `preview.start` or `webstudio preview --source session` instead.",
].join("\n"),
2
);
@@ -275,7 +276,8 @@ test("explains unpublished project bundle errors when synchronizing by build id"
[
"Unable to synchronize project bundle because the project is not published.",
"`webstudio sync` downloads the published project bundle.",
- "For visual verification of current MCP/API edits, use `preview.start` or `webstudio preview --source session` instead.",
+ "Publishing is not required for MCP editing. Do not ask the user to publish; use MCP tools against the latest editable build.",
+ "For visual verification, use `preview.start` or `webstudio preview --source session` instead.",
].join("\n"),
2
);
diff --git a/packages/cli/src/commands/sync.ts b/packages/cli/src/commands/sync.ts
index ed7a44ba22..c9b6156f96 100644
--- a/packages/cli/src/commands/sync.ts
+++ b/packages/cli/src/commands/sync.ts
@@ -67,7 +67,8 @@ type SyncOptions = Partial<StrictYargsOptionsToInterface<typeof syncOptions>>;
const unpublishedProjectBundleMessage = [
"Unable to synchronize project bundle because the project is not published.",
"`webstudio sync` downloads the published project bundle.",
- "For visual verification of current MCP/API edits, use `preview.start` or `webstudio preview --source session` instead.",
+ "Publishing is not required for MCP editing. Do not ask the user to publish; use MCP tools against the latest editable build.",
+ "For visual verification, use `preview.start` or `webstudio preview --source session` instead.",
].join("\n");
const isUnpublishedProjectBundleError = (error: unknown) => {
@@ -201,7 +202,7 @@ export const sync = async (
syncing.stop(
agents.status === "blocked-by-user-file"
- ? `Project bundle synchronized; AGENTS.md blocked by user-owned file at ${agents.path}. Next: webstudio connect`
- : `Project bundle synchronized successfully (AGENTS.md: ${agents.status}). Next: webstudio connect`
+ ? `Project bundle synchronized; AGENTS.md blocked by user-owned file at ${agents.path}. Next: webstudio build`
+ : `Project bundle synchronized successfully (AGENTS.md: ${agents.status}). Next: webstudio build`
);
};
diff --git a/packages/cli/src/config.test.ts b/packages/cli/src/config.test.ts
new file mode 100644
index 0000000000..68b898b32d
--- /dev/null
+++ b/packages/cli/src/config.test.ts
@@ -0,0 +1,14 @@
+import { describe, expect, test } from "vitest";
+import { join } from "node:path";
+import { getLocalProjectStateDirectory } from "./config";
+
+describe("local project state directories", () => {
+ test("keeps opaque project ids inside the project scope", () => {
+ expect(getLocalProjectStateDirectory("/workspace", "..")).toBe(
+ join("/workspace", ".webstudio", "projects", "%2E%2E")
+ );
+ expect(getLocalProjectStateDirectory("/workspace", "project/child")).toBe(
+ join("/workspace", ".webstudio", "projects", "project%2Fchild")
+ );
+ });
+});
diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.ts
index c4070f155f..6a08e49f98 100644
--- a/packages/cli/src/config.ts
+++ b/packages/cli/src/config.ts
@@ -14,6 +14,15 @@ export const GLOBAL_CONFIG_FILE = join(
export const LOCAL_CONFIG_FILE = ".webstudio/config.json";
export const LOCAL_DATA_FILE = ".webstudio/data.json";
+// URI encoding preserves path separators but leaves `.` untouched. Encode dots
+// too so opaque project ids cannot become filesystem traversal segments.
+const encodeProjectStatePathSegment = (value: string) => {
+ if (value.length === 0) {
+ throw new Error("Project id cannot be empty");
+ }
+ return encodeURIComponent(value).replaceAll(".", "%2E");
+};
+
export const getLocalProjectStateDirectory = (
projectRoot: string,
projectId?: string
@@ -24,7 +33,7 @@ export const getLocalProjectStateDirectory = (
projectRoot,
dirname(LOCAL_CONFIG_FILE),
"projects",
- encodeURIComponent(projectId)
+ encodeProjectStatePathSegment(projectId)
);
const zLocalConfig = z.object({
diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.ts
index 6d55c656a6..0fffc57320 100644
--- a/packages/cli/src/docs.generated.ts
+++ b/packages/cli/src/docs.generated.ts
@@ -2,13 +2,13 @@
// Edit markdown files in src/docs instead.
export const cliDocs = {
"api-use-cases":
- '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get_more_tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get_more_tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search labels, text, props, resource URLs, asset metadata, and styles.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nested asset folders and upload, inspect, move, duplicate, download, replace, delete, and inspect usage for assets.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Use this after page/content/style mutations so a vision-capable AI can see the generated site from the current MCP session. Use `path`; never pass a Webstudio Builder/share URL or capture Builder chrome.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- Iterative mode is the default: after MCP mutations, path screenshots ensure generated project files are current, wait for the exact session version, and perform an ordinary page reload without Vite HMR. The preview server and browser stay alive. Use `{"mode":"production"}` only for release-like verification; rendered audit does this automatically.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":200}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599 or a JavaScript expression string for a dynamic status.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}\n- webstudio duplicate-page --page <pageId> --name Paris --path /paris --substitutions \'{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}\' --json\n\nNotes:\n\n- Text substitutions replace exact fixed text only in the duplicated page\'s text children, string props, title, and metadata.\n- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.\n- Existing expressions and cloned variable/resource references keep their remapped ids.\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {}\n- MCP tool: list-pages {}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px;`}><ws.element ws:tag=\\"h2\\">Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- The `ws:` namespace contains specific Webstudio core components; it is not HTML-tag shorthand. Use `<ws.element ws:tag="div">` for a native `div` and `<ws.element ws:tag="form">` for a native form, never `<ws.div>` or `<ws.form>`.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside the Content Block\'s `ws:block-template` child. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- Store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"verbose":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `verbose:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":"names.json contents","force":true}\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\\"https://api.example.com/posts?tag=\\" + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\\"Bearer \\" + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: list-assets {"verbose":true}\n\nNotes:\n\n- Compact results include each asset\'s folder id. Use `verbose:true` to include complete records for a page of assets, or `get-asset` to read one complete record including description, folder, creation time, and image/font metadata.\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Get asset\n\nCommands:\n\n- MCP tool: get-asset {"assetId":"<assetId>"}\n\n## List asset folders\n\nCommands:\n\n- MCP tool: list-asset-folders {}\n\n## Create asset folder\n\nCommands:\n\n- MCP tool: create-asset-folder {"name":"Marketing"}\n- MCP tool: create-asset-folder {"name":"Photos","parentId":"<parentFolderId>"}\n\n## Update asset folder\n\nCommands:\n\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"name":"Brand"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":"<parentFolderId>"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":null}}\n\nNotes:\n\n- Updating `parentId` is the folder equivalent of cut and paste. Use `null` to move a folder to Root.\n\n## Duplicate asset folder\n\nCommands:\n\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>"}\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>","parentId":"<targetFolderId>"}\n\nNotes:\n\n- Duplication recursively copies descendant folders and assets. This is the folder equivalent of copy and paste.\n\n## Delete asset folder\n\nCommands:\n\n- MCP tool: delete-asset-folder {"folderId":"<folderId>"}\n\nNotes:\n\n- Deleting a folder recursively deletes its descendant folders and assets.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n- MCP tool: update-asset {"assetId":"<fontAssetId>","values":{"meta":{"family":"Rajdhani","style":"normal","weight":600}}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n- Font metadata updates merge with the detected metadata and are validated before committing; use this to correct a family, style, or weight after upload.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","folderId":"<folderId>","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\n## Duplicate asset\n\nCommands:\n\n- MCP tool: duplicate-asset {"assetId":"<assetId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":"<targetFolderId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":null}\n\nNotes:\n\n- Duplication is the asset equivalent of copy and paste. Updating `folderId` is the equivalent of cut and paste; use `null` for Root.\n\n## Download asset\n\nCommands:\n\n- MCP tool: download-asset {"assetId":"<assetId>"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","scopes":["resources"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- Use `search-project` for query-driven lookup across labels, text, prop values, resource URLs, asset metadata, and styles. Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility --scopes seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- webstudio audit --rendered --page-path /pricing --json\n- webstudio audit --rendered --route-example post=/blog/hello --json\n- webstudio audit --rendered --image-domain images.example.com --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"scopes":["craft"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`\n (or MCP `routeExamples`) supplies a concrete path. The path must not contain\n unresolved `:` or `*` parameters.\n- Plans above 120 captures return a short-lived confirmation token. Review the\n unchanged plan, then rerun with `--confirm-large-run` and\n `--confirmation-token`.\n- Detailed rendered evidence is stored in a versioned manifest under\n `.webstudio/audits`; compact output includes its path and screenshot count.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Verify dynamic bindings\n\nCommands:\n\n- webstudio verify-bindings --json\n- MCP tool: verify-bindings {"pagePath":"/pricing"}\n- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}\n\nNotes:\n\n- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.\n- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.\n- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.\n- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Render an array or object as repeated content\n\nCommands:\n\n- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<ws.element ws:tag=\\"article\\"><ws.element ws:tag=\\"h2\\">{expression`collectionItem.title`}</ws.element></ws.element>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\n\nNotes:\n\n- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.\n- Pass `insert-collection` the complete array or object. Do not pass the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result\'s `data` field or deeper.\n- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\n- Wrap multiple repeated sibling instances in one Element inside Collection.\n- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.\n- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.\n- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.\n- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.\n- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Inspect and reuse the project\'s existing auth convention before authoring. Do\n not add a second provider or session model implicitly.\n- Model signed-out, loading, signed-in, and failed-auth states explicitly.\n- Never store credentials, service-role keys, refresh tokens, private session\n values, or authenticated response bodies in project data, command output,\n screenshots, agent instructions, or error reports. Privileged provider calls\n and authorization enforcement belong server-side.\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still\n uses the existing resource, variable, prop, binding, and embed tools; there is\n no provider-specific installer.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page"}\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\"><ws.element ws:tag=\\"p\\">Section copy</ws.element></ws.element>"}\n- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpointId":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after the agent can inspect the supplied design. There is no direct\n Figma, screenshot, Inception, or `design.md` import command.\n- Inspect and reuse existing variables, tokens, styles, components, assets, and\n page patterns before authoring. Build semantic editable structure rather than\n flattening the design into an image or absolute-positioned approximation.\n- Verify one familiar viewport inside every distinct Builder breakpoint range,\n then run rendered audit and inspect the screenshots before completion.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio mcp run .temp/projects.json\n- webstudio mcp run .temp/projects.json --dry-run\n- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2\n\nNotes:\n\n- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.\n- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.\n- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCall `meta.guide` with the provider-authenticated page goal, then create the\npage, resources, variables, props, bindings, and embeds with existing semantic\ntools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nCall `meta.guide` with the design-input goal, let the agent inspect the supplied\ndesign, then use semantic page, token, asset, fragment, style, preview,\nscreenshot, and audit tools. Use `apply-patch` only when no semantic operation\nfits.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',
+ '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get_more_tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get_more_tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search labels, text, props, resource URLs, asset metadata, and styles.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nested asset folders and upload, inspect, move, duplicate, download, replace, delete, and inspect usage for assets.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Use this after page/content/style mutations so a vision-capable AI can see the generated site from the current MCP session. Use `path`; never pass a Webstudio Builder/share URL or capture Builder chrome.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- Iterative mode is the default: after MCP mutations, path screenshots ensure generated project files are current, wait for the exact session version, and perform an ordinary page reload without Vite HMR. The preview server and browser stay alive. Use `{"mode":"production"}` only for release-like verification; rendered audit does this automatically.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":200}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599 or a JavaScript expression string for a dynamic status.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}\n- webstudio duplicate-page --page <pageId> --name Paris --path /paris --substitutions \'{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}\' --json\n\nNotes:\n\n- Text substitutions replace exact fixed text only in the duplicated page\'s text children, string props, title, and metadata.\n- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.\n- Existing expressions and cloned variable/resource references keep their remapped ids.\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {}\n- MCP tool: list-pages {}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px;`}><ws.element ws:tag=\\"h2\\">Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- The `ws:` namespace contains specific Webstudio core components; it is not HTML-tag shorthand. Use `<ws.element ws:tag="div">` for a native `div` and `<ws.element ws:tag="form">` for a native form, never `<ws.div>` or `<ws.form>`.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside the Content Block\'s `ws:block-template` child. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- Store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"verbose":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `verbose:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":"names.json contents","force":true}\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays and objects.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\\"https://api.example.com/posts?tag=\\" + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\\"Bearer \\" + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\n## Query Markdown assets\n\nCommands:\n\n- MCP tool: get-asset-field-catalog {}\n- MCP tool: validate-asset-query {"query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","draft"],"operator":"ne","value":true}]},"limit":20}}\n- MCP tool: create-assets-resource {"name":"All assets","scopeInstanceId":"<instanceId>","dataSourceName":"assets"}\n- MCP tool: create-assets-resource {"name":"Published posts","scopeInstanceId":"<instanceId>","dataSourceName":"posts","query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","draft"],"operator":"ne","value":{"type":"literal","value":true}}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"}],"limit":{"type":"literal","value":20},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["excerpt"]]},"content":{"mode":"none"}}}\n- MCP tool: create-assets-resource {"name":"Post by slug or ID","scopeInstanceId":"<instanceId>","dataSourceName":"post","query":{"where":{"any":[{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"},{"field":["id"],"operator":"eq","value":"system.params.slug"}]},"limit":{"type":"literal","value":1},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","publishedAt"]]},"content":{"mode":"markdown-body","maxBytes":1048576}}}\n- MCP tool: list-assets-resources {}\n- MCP tool: get-assets-resource {"resourceId":"<resourceId>"}\n- MCP tool: update-assets-resource {"resourceId":"<resourceId>","values":{"query":null}}\n- MCP tool: preview-asset-query {"query":{"where":{"all":[{"field":["properties","slug"],"operator":"eq","value":"hello-world"}]},"limit":1,"content":{"mode":"markdown-body","maxBytes":1048576}}}\n\nNotes:\n\n- Read the field catalog before authoring unfamiliar queries. It includes dynamic schema-less frontmatter paths such as `properties.author.name`, observed types, optionality, and mixed-type state without downloading Markdown files.\n- Minimize the deployed content database by using `output.mode:"fields"` and selecting only fields the rendered page needs. Keep `includeMetadata:false` unless the rendered value needs file metadata such as name, path, MIME type, or creation date, and avoid `output.mode:"all"` as a convenience default. Query diagnostics are returned separately and do not require metadata output. Filters and sorting may still require their referenced fields in the database.\n- Combine filters with `where.all` (AND) and `where.any` (OR), including nested groups. Filter values, limit, and offset on a saved resource may be Webstudio expressions evaluated at render time. Preview queries use concrete JSON values.\n- Use `content.mode:"none"` for listings. Request `markdown-body`, `full`, or a bounded `range` only after filtering to the intended files, normally with `limit:1` for a slug detail route.\n- In Markdown, reference sibling Assets with conventional relative URLs such as `../images/hero.png`. When `markdown-body` is requested, the content engine resolves matching files against the Markdown file\'s folder and emits the correct Builder or published Asset URL. Keep external URLs absolute.\n- Markdown Embed renders sanitized authored HTML for figures, captions, audio, video, and iframes. Scripts, inline event handlers, `srcdoc`, and unsafe URL protocols are removed. Executable component composition remains separate future MDX work.\n- Preview each query with concrete values before saving it. Inspect `__diagnostics__.usedBytes`, `maxBytes`, `unboundedBytes`, and `truncated`; when usage approaches the limit, remove unused output fields, narrow candidate files, and reduce embedded content in that order.\n- Read Assets from the ID-keyed map at `<dataSourceName>.data`, with collection information such as `totalCount` and `hasMore` at `<dataSourceName>.meta`. Bind a listing Collection to `posts.data` and a one-result detail Collection to `post.data`. On each value, selected file fields such as `id`, `name`, and `extension` are top-level; Markdown frontmatter and JSON fields are under `properties`; the derived `excerpt` is top-level; and requested Markdown is at `content.text`.\n- Assets has one response shape and always executes a structured query. Omit `query` to use the default query, which selects URL and optional image dimensions. Provide query configuration to control filtering, sorting, pagination, selected fields, or file content. Set `values.query:null` to restore the default query.\n- `create-assets-resource` and `update-assets-resource` are the semantic authoring path. Do not construct the internal query URL, headers, or body expression manually.\n- The shared metadata index is maintained automatically and is emitted only when a configured Assets resource is reachable.\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: list-assets {"verbose":true}\n\nNotes:\n\n- Compact results include each asset\'s folder id. Use `verbose:true` to include complete records for a page of assets, or `get-asset` to read one complete record including description, folder, creation time, and image/font metadata.\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Get asset\n\nCommands:\n\n- MCP tool: get-asset {"assetId":"<assetId>"}\n\n## List asset folders\n\nCommands:\n\n- MCP tool: list-asset-folders {}\n\n## Create asset folder\n\nCommands:\n\n- MCP tool: create-asset-folder {"name":"Marketing"}\n- MCP tool: create-asset-folder {"name":"Photos","parentId":"<parentFolderId>"}\n\n## Update asset folder\n\nCommands:\n\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"name":"Brand"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":"<parentFolderId>"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":null}}\n\nNotes:\n\n- Updating `parentId` is the folder equivalent of cut and paste. Use `null` to move a folder to Root.\n\n## Duplicate asset folder\n\nCommands:\n\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>"}\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>","parentId":"<targetFolderId>"}\n\nNotes:\n\n- Duplication recursively copies descendant folders and assets. This is the folder equivalent of copy and paste.\n\n## Delete asset folder\n\nCommands:\n\n- MCP tool: delete-asset-folder {"folderId":"<folderId>"}\n\nNotes:\n\n- Deleting a folder recursively deletes its descendant folders and assets.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n- MCP tool: update-asset {"assetId":"<fontAssetId>","values":{"meta":{"family":"Rajdhani","style":"normal","weight":600}}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n- Font metadata updates merge with the detected metadata and are validated before committing; use this to correct a family, style, or weight after upload.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","folderId":"<folderId>","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\n## Duplicate asset\n\nCommands:\n\n- MCP tool: duplicate-asset {"assetId":"<assetId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":"<targetFolderId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":null}\n\nNotes:\n\n- Duplication is the asset equivalent of copy and paste. Updating `folderId` is the equivalent of cut and paste; use `null` for Root.\n\n## Download asset\n\nCommands:\n\n- MCP tool: download-asset {"assetId":"<assetId>"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","scopes":["resources"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- Use `search-project` for query-driven lookup across labels, text, prop values, resource URLs, asset metadata, and styles. Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility --scopes seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- webstudio audit --rendered --page-path /pricing --json\n- webstudio audit --rendered --route-example post=/blog/hello --json\n- webstudio audit --rendered --image-domain images.example.com --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"scopes":["craft"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`\n (or MCP `routeExamples`) supplies a concrete path. The path must not contain\n unresolved `:` or `*` parameters.\n- Plans above 120 captures return a short-lived confirmation token. Review the\n unchanged plan, then rerun with `--confirm-large-run` and\n `--confirmation-token`.\n- Detailed rendered evidence is stored in a versioned manifest under\n `.webstudio/audits`; compact output includes its path and screenshot count.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Verify dynamic bindings\n\nCommands:\n\n- webstudio verify-bindings --json\n- MCP tool: verify-bindings {"pagePath":"/pricing"}\n- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}\n\nNotes:\n\n- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.\n- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.\n- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.\n- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Render an array or object as repeated content\n\nCommands:\n\n- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<ws.element ws:tag=\\"article\\"><ws.element ws:tag=\\"h2\\">{expression`collectionItem.title`}</ws.element></ws.element>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\n\nNotes:\n\n- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.\n- Pass `insert-collection` the complete array or object. Do not pass the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result\'s `data` field or deeper.\n- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\n- Wrap multiple repeated sibling instances in one Element inside Collection.\n- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.\n- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.\n- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.\n- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.\n- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Inspect and reuse the project\'s existing auth convention before authoring. Do\n not add a second provider or session model implicitly.\n- Model signed-out, loading, signed-in, and failed-auth states explicitly.\n- Never store credentials, service-role keys, refresh tokens, private session\n values, or authenticated response bodies in project data, command output,\n screenshots, agent instructions, or error reports. Privileged provider calls\n and authorization enforcement belong server-side.\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still\n uses the existing resource, variable, prop, binding, and embed tools; there is\n no provider-specific installer.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page"}\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\"><ws.element ws:tag=\\"p\\">Section copy</ws.element></ws.element>"}\n- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpointId":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after the agent can inspect the supplied design. There is no direct\n Figma, screenshot, Inception, or `design.md` import command.\n- Inspect and reuse existing variables, tokens, styles, components, assets, and\n page patterns before authoring. Build semantic editable structure rather than\n flattening the design into an image or absolute-positioned approximation.\n- Verify one familiar viewport inside every distinct Builder breakpoint range,\n then run rendered audit and inspect the screenshots before completion.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio mcp run .temp/projects.json\n- webstudio mcp run .temp/projects.json --dry-run\n- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2\n\nNotes:\n\n- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.\n- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.\n- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCall `meta.guide` with the provider-authenticated page goal, then create the\npage, resources, variables, props, bindings, and embeds with existing semantic\ntools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nCall `meta.guide` with the design-input goal, let the agent inspect the supplied\ndesign, then use semantic page, token, asset, fragment, style, preview,\nscreenshot, and audit tools. Use `apply-patch` only when no semantic operation\nfits.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',
"manual-api":
- '# Webstudio API CLI Manual\n\nThe API commands operate on the single project configured by:\n\n- .webstudio/config.json: projectId\n- global Webstudio config: origin and token\n\n- Pass --json to API/discovery commands that support it. Do not add --json to top-level commands unless their help/schema documents it.\n- Never pass a project id. Commands use configured project only.\n- Read ids before writing. Do not invent ids for existing records.\n- stdout is one JSON object. stderr is diagnostics.\n- Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.\n\n## Start\n\n{{start}}\n\n## Read First\n\n{{readFirst}}\n\n## Project Session Cache\n\n- CLI commands use one local ProjectSession snapshot for the configured project.\n- Local-capable reads use cached namespaces when compatible and fetch only missing or stale namespaces.\n- Local-capable mutations build patches from the local snapshot, then commit with the cached build version.\n- Successful mutation commits update the local snapshot only after the remote commit succeeds.\n- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.\n- Use --refresh on local-capable commands to refresh required namespaces before running.\n- Successful JSON responses include compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.\n\n## CLI Capability Inventory\n\nFor a short end-consumer summary of what MCP can do, see\n`manual mcp` / `webstudio man mcp`. The MCP inventory describes the same\nproject, page, element, style, data, asset, publish, domain, and visual\nverification capabilities without internal command names.\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP Tool Operations\n\nThese are MCP tools. From a shell, call them with the shortcut form `webstudio <tool> \'<json>\'` or with the explicit form `webstudio mcp single-op-call <tool> \'<json>\'`:\n\n{{mcpOnlyCommandIndex}}\n\n## Task Recipes\n\n{{taskRecipeIndex}}\n\n## Use Case Index\n\n{{useCaseIndex}}\n\n## Known CLI Gaps\n\n{{knownCliGapIndex}}\n\n## Input File Shapes\n\n{{inputFileShapeIndex}}\n\n## Raw Patch Fallback\n\napply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.\n\nEach transaction has:\n\n{\n"id": "patch-transaction-label",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\n\nThe transaction id is a patch label used for optimistic synchronization. It is\nnot a Builder record id. Do not invent ids for pages, instances, props,\nbreakpoints, resources, variables, folders, assets, or other project records.\n\nPatch paths are JSON-patch-like paths into Builder store data. Map-like namespaces use ids as the first path item.\n\nSupported namespaces:\n\n- pages: redirects, page records, and folders\n- projectSettings: project-wide metadata and compiler settings\n- instances: element instances and children, including text/expression children\n- props: element props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and reusable design tokens\n- styleSourceSelections: instance-to-style-source connections\n- dataSources: data variables, parameters, and resource data sources\n- resources: data resource definitions\n- assets: project asset records handled by the existing asset patch path\n- breakpoints: responsive breakpoints\n- marketplaceProduct: marketplace metadata\n\n## Data Sources\n\n`dataSources` is the internal Builder namespace for variables. Public API, CLI,\nand MCP tools expose it through two user-facing groups:\n\n- data variables: `list-variables`, `create-variable`, `update-variable`, and\n `delete-variable`\n- data resources: `list-resources`, `create-resource`, `update-resource`, and\n `delete-resource`\n\nFor raw `snapshot`, request the public `variables` namespace rather than the\ninternal `dataSources` name. Raw patch payloads still use `dataSources` when\napplying direct changes.\n\nVariables can be scoped to an instance. Expressions under that instance can use\nthe variable by name; nested variables with the same name mask outer variables.\nVariable values support `string`, `number`, `boolean`, `string[]`, and `json`.\nUse `string[]` for lists of strings such as tags or selected categories; use\n`json` for objects, arrays with mixed shapes, or nested API filter state.\nParameters are internal scoped runtime values provided by pages, collections,\nor components. They are not a public authoring surface: do not create, update,\nor delete parameter records. Public tools should preserve existing parameter\nrecords and may reference documented context values such as `system` in\nexpressions where they are already in scope.\n\nResource `url` accepts plain fixed URLs and paths, for example\n`https://api.example.com/posts` or `/$resources/current-date`. Dynamic URLs can\ncombine strings and variables, for example\n`"https://api.example.com/posts?tag=" + filters.tag`. Prefer `searchParams` for\nquery parameters that should be encoded separately:\n`[{ "name": "tag", "value": "filters.tag" }]`. Header values, search parameter\nvalues, and bodies are expressions for dynamic content. For fixed text, use\n`{ "type": "literal", "value": "application/json" }`; Webstudio stores the\nrequired string expression. Headers can still read variables such as\n`"Bearer " + auth.token`, and GraphQL bodies can return objects such as\n`{ query: "...", variables: { slug: system.params.slug } }`.\n\nCreate a GET resource with `scopeInstanceId` when the fetched resource result\nshould be available as a read data variable. Scoped GET resources default to\n`exposeAsDataSource: true`, are generated into the page resource `data` map,\nand may be loaded during page rendering. Use `dataSourceName` to choose the\nvariable name.\n\nFor submit/write/action resources, create the resource without\n`scopeInstanceId`, then bind a component prop such as a Form `action` to the\nresource with `bind-props` and `binding.type: "resource"`. Prop-bound resources\nare generated into the page resource `action` map instead of the read `data`\nmap. Use this shape for POST, PUT, DELETE, webhook, and other resources that\nshould run only from an explicit form/action flow, not merely because the page\nrendered.\n\nPOST, PUT, and DELETE resources default to `exposeAsDataSource: false` even\nwhen a scope is supplied. Set `exposeAsDataSource: true` only when a write-method\nresource intentionally provides render-time data, such as a read-only GraphQL\nPOST query. A scope is required, and the result includes a warning because the\nrequest may execute during page rendering. Set `exposeAsDataSource: false` on\n`update-resource` to detach an existing render-time data source.\n\nResource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read\ndata. Use POST for creates, GraphQL requests, webhooks, and form submissions.\nUse PUT for full updates/replacements. Use DELETE for deletion actions.\nOptional `control` values are `graphql` and `system`: `graphql` marks a\nGraphQL-style resource, usually POST with a query body; `system` marks a\nresource intended to use the built-in `system` parameter or one of the built-in\nlocal resource URLs: `"/$resources/sitemap.xml"`,\n`"/$resources/current-date"`, and `"/$resources/assets"`. The system parameter\nfields are `system.origin`, `system.pathname`, `system.params`, and\n`system.search`.\n\nUse prop bindings for dynamic values that read variables or resources; use\ndirect props for static values.\n\nCommit raw patch:\n\nMCP tool: apply-patch\n\n## Raw Patch Examples\n\nRename the site:\n\n[\n{\n"id": "patch-site-name",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "add", "path": ["meta", "siteName"], "value": "Acme Studio" }\n]\n}\n]\n}\n]\n\nUpdate page title metadata:\n\n[\n{\n"id": "patch-page-title",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["pages", "page-id", "meta", "title"], "value": "Pricing" }\n]\n}\n]\n}\n]\n\nUpdate a text child on an element:\n\n[\n{\n"id": "patch-text",\n"payload": [\n{\n"namespace": "instances",\n"patches": [\n{ "op": "replace", "path": ["instance-id", "children", 0, "value"], "value": "Launch faster" }\n]\n}\n]\n}\n]\n\nCreate records with semantic operations such as create-variable,\ncreate-resource, create-design-token, create-page, create-folder,\nand create-breakpoint. Raw patch rejects generated record\ncreation, collection replacement, record replacement with a different `id`, and\nrecord id field mutations in id-keyed namespaces because Webstudio must generate\nand preserve record ids.\n\n## Safety Rules\n\n- For MCP apply-patch, read the latest version with MCP snapshot before writing.\n- Reuse ids from MCP snapshot output when updating existing records.\n- Do not create generated records, replace generated record collections, replace records with different ids, or mutate record id fields with raw patch. Use semantic create operations so Webstudio generates ids.\n- If apply-patch reports a version conflict, read the latest build and regenerate the patch.\n- Prefer semantic MCP read tools for discovery, then use MCP snapshot for exact patch paths.\n\n## Command Index\n\n{{commandIndex}}\n',
+ '# Webstudio API CLI Manual\n\nThe API commands operate on the single project configured by:\n\n- .webstudio/config.json: projectId\n- global Webstudio config: origin and token\n\n- Pass --json to API/discovery commands that support it. Do not add --json to top-level commands unless their help/schema documents it.\n- Never pass a project id. Commands use configured project only.\n- Read ids before writing. Do not invent ids for existing records.\n- stdout is one JSON object. stderr is diagnostics.\n- Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.\n\n## Start\n\n{{start}}\n\n## Read First\n\n{{readFirst}}\n\n## Project Session Cache\n\n- CLI commands use one local ProjectSession snapshot for the configured project.\n- Local-capable reads use cached namespaces when compatible and fetch only missing or stale namespaces.\n- Local-capable mutations build patches from the local snapshot, then commit with the cached build version.\n- Successful mutation commits update the local snapshot only after the remote commit succeeds.\n- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.\n- Use --refresh on local-capable commands to refresh required namespaces before running.\n- Successful JSON responses include compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.\n\n## CLI Capability Inventory\n\nFor a short end-consumer summary of what MCP can do, see\n`manual mcp` / `webstudio man mcp`. The MCP inventory describes the same\nproject, page, element, style, data, asset, publish, domain, and visual\nverification capabilities without internal command names.\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP Tool Operations\n\nThese are MCP tools. From a shell, call them with the shortcut form `webstudio <tool> \'<json>\'` or with the explicit form `webstudio mcp single-op-call <tool> \'<json>\'`:\n\n{{mcpOnlyCommandIndex}}\n\n## Task Recipes\n\n{{taskRecipeIndex}}\n\n## Use Case Index\n\n{{useCaseIndex}}\n\n## Known CLI Gaps\n\n{{knownCliGapIndex}}\n\n## Input File Shapes\n\n{{inputFileShapeIndex}}\n\n## Raw Patch Fallback\n\napply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.\n\nEach transaction has:\n\n{\n"id": "patch-transaction-label",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\n\nThe transaction id is a patch label used for optimistic synchronization. It is\nnot a Builder record id. Do not invent ids for pages, instances, props,\nbreakpoints, resources, variables, folders, assets, or other project records.\n\nPatch paths are JSON-patch-like paths into Builder store data. Map-like namespaces use ids as the first path item.\n\nSupported namespaces:\n\n- pages: redirects, page records, and folders\n- projectSettings: project-wide metadata and compiler settings\n- instances: element instances and children, including text/expression children\n- props: element props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and reusable design tokens\n- styleSourceSelections: instance-to-style-source connections\n- dataSources: data variables, parameters, and resource data sources\n- resources: data resource definitions\n- assets: project asset records handled by the existing asset patch path\n- breakpoints: responsive breakpoints\n- marketplaceProduct: marketplace metadata\n\n## Data Sources\n\n`dataSources` is the internal Builder namespace for variables. Public API, CLI,\nand MCP tools expose it through two user-facing groups:\n\n- data variables: `list-variables`, `create-variable`, `update-variable`, and\n `delete-variable`\n- data resources: `list-resources`, `create-resource`, `update-resource`, and\n `delete-resource`\n\nFor raw `snapshot`, request the public `variables` namespace rather than the\ninternal `dataSources` name. Raw patch payloads still use `dataSources` when\napplying direct changes.\n\nVariables can be scoped to an instance. Expressions under that instance can use\nthe variable by name; nested variables with the same name mask outer variables.\nVariable values support `string`, `number`, `boolean`, and `json`. Use `json`\nfor all arrays and objects, including tags, selected categories, and nested API\nfilter state.\nParameters are internal scoped runtime values provided by pages, collections,\nor components. They are not a public authoring surface: do not create, update,\nor delete parameter records. Public tools should preserve existing parameter\nrecords and may reference documented context values such as `system` in\nexpressions where they are already in scope.\n\nResource `url` accepts plain fixed URLs and paths, for example\n`https://api.example.com/posts` or `/$resources/current-date`. Dynamic URLs can\ncombine strings and variables, for example\n`"https://api.example.com/posts?tag=" + filters.tag`. Prefer `searchParams` for\nquery parameters that should be encoded separately:\n`[{ "name": "tag", "value": "filters.tag" }]`. Header values, search parameter\nvalues, and bodies are expressions for dynamic content. For fixed text, use\n`{ "type": "literal", "value": "application/json" }`; Webstudio stores the\nrequired string expression. Headers can still read variables such as\n`"Bearer " + auth.token`, and GraphQL bodies can return objects such as\n`{ query: "...", variables: { slug: system.params.slug } }`.\n\nCreate a GET resource with `scopeInstanceId` when the fetched resource result\nshould be available as a read data variable. Scoped GET resources default to\n`exposeAsDataSource: true`, are generated into the page resource `data` map,\nand may be loaded during page rendering. Use `dataSourceName` to choose the\nvariable name.\n\nFor submit/write/action resources, create the resource without\n`scopeInstanceId`, then bind a component prop such as a Form `action` to the\nresource with `bind-props` and `binding.type: "resource"`. Prop-bound resources\nare generated into the page resource `action` map instead of the read `data`\nmap. Use this shape for POST, PUT, DELETE, webhook, and other resources that\nshould run only from an explicit form/action flow, not merely because the page\nrendered.\n\nPOST, PUT, and DELETE resources default to `exposeAsDataSource: false` even\nwhen a scope is supplied. Set `exposeAsDataSource: true` only when a write-method\nresource intentionally provides render-time data, such as a read-only GraphQL\nPOST query. A scope is required, and the result includes a warning because the\nrequest may execute during page rendering. Set `exposeAsDataSource: false` on\n`update-resource` to detach an existing render-time data source.\n\nResource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read\ndata. Use POST for creates, GraphQL requests, webhooks, and form submissions.\nUse PUT for full updates/replacements. Use DELETE for deletion actions.\nOptional `control` values are `graphql` and `system`: `graphql` marks a\nGraphQL-style resource, usually POST with a query body; `system` marks a\nresource intended to use the built-in `system` parameter or one of the built-in\nlocal resource URLs: `"/$resources/sitemap.xml"`,\n`"/$resources/current-date"`, and `"/$resources/assets"`. The system parameter\nfields are `system.origin`, `system.pathname`, `system.params`, and\n`system.search`.\n\nUse prop bindings for dynamic values that read variables or resources; use\ndirect props for static values.\n\nCommit raw patch:\n\nMCP tool: apply-patch\n\n## Raw Patch Examples\n\nRename the site:\n\n[\n{\n"id": "patch-site-name",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "add", "path": ["meta", "siteName"], "value": "Acme Studio" }\n]\n}\n]\n}\n]\n\nUpdate page title metadata:\n\n[\n{\n"id": "patch-page-title",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["pages", "page-id", "meta", "title"], "value": "Pricing" }\n]\n}\n]\n}\n]\n\nUpdate a text child on an element:\n\n[\n{\n"id": "patch-text",\n"payload": [\n{\n"namespace": "instances",\n"patches": [\n{ "op": "replace", "path": ["instance-id", "children", 0, "value"], "value": "Launch faster" }\n]\n}\n]\n}\n]\n\nCreate records with semantic operations such as create-variable,\ncreate-resource, create-design-token, create-page, create-folder,\nand create-breakpoint. Raw patch rejects generated record\ncreation, collection replacement, record replacement with a different `id`, and\nrecord id field mutations in id-keyed namespaces because Webstudio must generate\nand preserve record ids.\n\n## Safety Rules\n\n- For MCP apply-patch, read the latest version with MCP snapshot before writing.\n- Reuse ids from MCP snapshot output when updating existing records.\n- Do not create generated records, replace generated record collections, replace records with different ids, or mutate record id fields with raw patch. Use semantic create operations so Webstudio generates ids.\n- If apply-patch reports a version conflict, read the latest build and regenerate the patch.\n- Prefer semantic MCP read tools for discovery, then use MCP snapshot for exact patch paths.\n\n## Command Index\n\n{{commandIndex}}\n',
"manual-llm":
- '# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Connect an MCP client\n\nWhen the user asks to connect the current folder to Webstudio, run the command\nfor the agent client you are currently using:\n\n- Claude Code: `webstudio connect claude`\n- Codex: `webstudio connect codex`\n- Cursor: `webstudio connect cursor`\n- VS Code or GitHub Copilot: `webstudio connect vscode`\n\nRun the command from the linked project root. If the folder is not linked, ask\nfor an editable Builder share link and run\n`webstudio init --link <share-link> --json`, followed by `webstudio sync`, then\nretry `webstudio connect <client>`. Treat the share link as a credential and do\nnot include it in committed files, logs, screenshots, or issue reports.\n\n`connect` verifies project access before changing client configuration. For\nClaude Code, Cursor, and VS Code it safely merges the `webstudio` server into\nthe client\'s project configuration. For Codex it runs both `codex mcp add` and\n`codex mcp get webstudio`; do not repeat those commands separately. Follow the\nreload, restart, or approval instruction printed by `connect`, then verify the\nloaded MCP connection by asking the client to use Webstudio MCP and list the\nproject pages. Use `--print` only to inspect the generated setup without\nchanging configuration or requiring project access.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a compact MCP tool overview. Add `--verbose` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get_more_tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nThe same local shortcut form is shorter and preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nFor this simple path, do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only to get the target `parentInstanceId`.\n\nWhen authoring JSX for `insert-fragment`, use Webstudio component helpers and Webstudio style syntax. Use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n\nWhen the task says another user will edit a page in Content mode, use a Content Block (`ws:block`) around every editable region. Content-mode users can edit text and supported props only in descendants of that block; content outside it is read-only. Put reusable insertable options in the block\'s `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nDo not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.\n\nUse Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/Webstudio names. Do not use React-only aliases such as `className` or `htmlFor`; the runtime rejects them with the Webstudio prop name to use.\n\nUse Webstudio actions for event/action props. Do not pass JavaScript functions such as `onClick={() => ...}`; the runtime rejects them because functions cannot be persisted as Webstudio project data.\n\n```tsx\n<ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n>\n Open\n</ws.element>\n```\n\nPlain JSX prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n\nIf a component has a registered template with required parts, JSX must include those parts explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.\n\n## Animation Components\n\nBefore creating animation examples, inspect the exact components with focused discovery:\n\n```sh\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateChildren"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateText"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:StaggerAnimation"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:VideoAnimation"}\'\n```\n\nUse Animation Group (`AnimateChildren`) as the controller. Put normal instances directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it. Text, Stagger, and Video are helper components with `contentModel.category: "none"` and should not be used as standalone section roots.\n\nDefine timing and CSS changes on the Animation Group `action` prop. Use `type:"view"` for viewport entry/exit progress and `type:"scroll"` for scroll-progress timelines. For in animations, keep the canvas styles as the final state and use `fill:"backwards"` with keyframes that describe the starting state. For out animations, use `fill:"forwards"` with keyframes that describe the ending state.\n\nText Animation settings: `slidingWindow` defaults to `5`, `easing` defaults to `linear`, and `splitBy` defaults to `char`. Use `splitBy:"space"` for word-by-word animation. The parent Animation Group keyframes provide the actual opacity, translate, scale, or other styles.\n\nStagger Animation settings: `slidingWindow` defaults to `1` and `easing` defaults to `linear`. It applies parent Animation Group progress across its direct children. Use `slidingWindow:0` for instant sequential steps, `1` for one child at a time, and values above `1` for overlapping waves.\n\nVideo Animation settings: `timeline` is a boolean. Prefer `insert-component` for Video Animation so the Video child template is inserted, then configure the Video child asset/source. Use short, seek-friendly videos for smooth scroll-linked playback.\n\nUse JSX fragments for authored animation structures when you need styled, editable examples. Put the final visual state in `ws:style` and put the starting or ending animated state in the Animation Group `action` keyframes. Include an explicit `offset` on every keyframe: use `offset: 0` for starting-state keyframes with `fill:"backwards"` and `offset: 1` for ending-state keyframes with `fill:"forwards"`.\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n axis: "block",\n animations: [\n {\n name: "Fade up on entry",\n timing: {\n fill: "backwards",\n rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 24, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n ],\n }}\n>\n <ws.element\n ws:tag="section"\n ws:style={css`\n display: grid;\n gap: 16px;\n padding: 48px;\n border-radius: 24px;\n background: #111827;\n color: white;\n `}\n >\n <ws.element ws:tag="h2">Launch metrics</ws.element>\n <ws.element ws:tag="p">\n A polished card that fades up as it enters the viewport.\n </ws.element>\n </ws.element>\n</animation.AnimateChildren>\n```\n\nFor Text Animation, keep `animation.AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Parallax In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 100, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Opacity In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n {\n name: "Scale In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Parallax Out",\n timing: {\n fill: "forwards",\n rangeStart: ["cover", { type: "unit", value: 50, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 1,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: -100, unit: "px" },\n ],\n },\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n insetStart: { type: "unit", value: 5, unit: "%" },\n insetEnd: { type: "unit", value: 5, unit: "%" },\n isPinned: true,\n }}\n>\n <animation.AnimateText\n splitBy="space"\n slidingWindow={5}\n easing="easeOutQuart"\n >\n <ws.element ws:tag="h2">Animate words with controlled rhythm</ws.element>\n </animation.AnimateText>\n</animation.AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `animation.StaggerAnimation`:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n timing: {\n fill: "backwards",\n rangeStart: ["contain", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["contain", { type: "unit", value: 30, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n }}\n>\n <animation.StaggerAnimation>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </ws.element>\n </animation.StaggerAnimation>\n</animation.AnimateChildren>\n```\n\nFor Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Video progress",\n timing: {\n fill: "both",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [{ offset: 0, styles: {} }],\n },\n ],\n }}\n>\n <animation.VideoAnimation timeline={true}>\n <$.Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </animation.VideoAnimation>\n</animation.AnimateChildren>\n```\n\n## Command Surface Boundary\n\n- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, registry inspection, man, and starting MCP.\n- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.\n- From a shell, call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio insert-fragment \'<json>\' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.\n- For experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- For bounded multi-step shell work, run inline JSON with `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For large batches, write `{ "calls": [{ "tool": "..." }] }` to a normal JSON file and run `webstudio mcp run .temp/mcp-calls.json`.\n- Use JSON strings for `brief` fields. Never pass boolean flags such as `{"brief":true}`.\n- Treat `webstudio mcp single-op-call` and `webstudio mcp run` stderr lines as progress checkpoints; stdout remains JSON on both success and failure. On failure, parse stdout for `{ "ok": false, "error": { "code": "...", "message": "..." } }` before deciding what to fix.\n- If a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in Discord `#help` at https://wstd.us/community. Give them a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n- Run one-shot `webstudio mcp single-op-call` commands sequentially against a linked `.webstudio` folder. If a command returns `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- In delegated or non-streaming agent environments, do not batch many MCP calls silently and do not wrap many shortcut or `webstudio mcp single-op-call` commands in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report that command/result, then wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with `workflow.next {"goal":"design-system-page","phase":"presentation-pass"}`. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world examples, not raw unstyled component dumps.\n- For design-system or “use every component” tasks, start with compact `webstudio components.coverage-plan`, checkpoint, then request component coverage details with `webstudio components.coverage-plan \'{"detail":"roots","offset":20}\'` or `{"detail":"parts"}` only when needed. Do not pass `detail` to `list-pages`; use `list-pages {}` or `get-page-by-path` for page lookup.\n- MCP tool shortcuts are only for MCP tools. If a shortcut is ambiguous with a real top-level command, the real top-level command wins; use `webstudio mcp single-op-call <tool> \'<json>\'` to force the MCP path.\n\n## LLM Implementation Process\n\nUse this process for user requests that change Webstudio content, layout, styles, assets, pages, redirects, resources, or publishing state:\n\n1. Discover capabilities with `webstudio man --json`, `webstudio schema api`, `webstudio schema mcp`, MCP `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.coverage-plan`, `components.search`, `components.get`, `templates.list`, and `templates.get`. From a shell, prefer shortcut calls such as `webstudio meta.index` and `webstudio components.search \'{"brief":"button"}\'` for these focused tool calls; use `webstudio mcp single-op-call` when you need the explicit MCP form. Read full resources such as `webstudio://project/tools` and `webstudio://project/components` only when needed. Do not write scripts to parse full MCP discovery JSON for normal lookup.\n2. Inspect current project state with semantic reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, `list-breakpoints`, and `snapshot` only when needed. Before changing a project, read `get-project-settings` and follow any non-empty `meta.agentInstructions`. These are shared project instructions, not a place for secrets.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.\n4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.\n5. For visual/design work, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate before final response.\n6. Report what changed and what verification ran.\n\n## Visual Design Workflow\n\nFor requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:\n\n1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.\n2. Do not use generated route/component files as the source of truth for editable content.\n3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.\n4. Keep generated project files current, start preview, and capture the changed page with `screenshot`.\n5. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n6. If vision or screenshot tooling is unavailable, state that explicitly and explain what fallback verification was used.\n\n## Responsive Verification Workflow\n\nFor responsive page work, use Builder breakpoints as the source of truth:\n\n1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.\n2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.\n3. Pick screenshot viewport widths from the project breakpoints: include a desktop width, each defined max-width or min-width edge, and a narrow mobile width.\n4. Capture each viewport with `screenshot`, for example `{"path":"/","output":"home-375.png","viewport":{"width":375,"height":812}}` and `{"path":"/","output":"home-1440.png","viewport":{"width":1440,"height":900}}`.\n5. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n6. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.\n\n## Generated Files Guardrails\n\n- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.\n- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.\n- Generated files are build artifacts and may be overwritten by `webstudio build`.\n- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.\n\n## Values vs Bindings\n\nBefore authoring unfamiliar expressions, read `webstudio://project/expressions` with MCP `resources/read` or `webstudio mcp read-resource webstudio://project/expressions`. It documents the supported expression subset, method allowlist, scope, Collection context, and validation limits.\n\n- Use direct value tools for fixed content. For one visible text child, use `update-text` with plain `text`. For a bounded multi-instance literal replacement, use `replace-text` with `find`, `replace`, `pagePath` or `pageId`, and `limit`; it does not change expression children. Use `replace-prop-text` for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop\'s direct type/value.\n- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.\n- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.\n- Expression binding example: `{"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}`.\n- Page metadata fields such as `title`, `description`, `language`, `redirect`, and custom meta content accept plain fixed text. For computed values, pass JavaScript expression code such as `pageTitle ?? "Pricing | Acme"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599, for example `302`. For a dynamic status, pass JavaScript expression code such as `system.status`.\n- Page metadata update example: use `update-page` with `{"pageId":"page-id","values":{"title":"Pricing | Acme","meta":{"description":"Plans for teams"}}}`.\n- Draft a page with `update-page` and `{"pageId":"page-id","values":{"isDraft":true}}`. It remains editable and previewable but is omitted from every publish target, including staging, and from sitemap output.\n- Stage a draft page for a future publish with `{"pageId":"page-id","values":{"isDraft":false}}`. This clears draft state but does not deploy the site. The home page and `/*` catch-all page cannot be drafts.\n- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.\n- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.\n- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`. Use `string[]` only for arrays where every item is a string; use `json` for objects, mixed arrays, filters, and nested data.\n- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.\n- Use scoped resources for read data. A GET resource created with `scopeInstanceId`/`dataSourceName` defaults to `exposeAsDataSource:true`, becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Read the loaded resource result from its wrapper, usually `.data`.\n- Use prop-bound resources for actions. A resource created without `scopeInstanceId` and bound to a component prop such as Form `action` with `bind-props` and `binding.type: "resource"` becomes an action resource in the page resource `action` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.\n- POST, PUT, and DELETE resources default to `exposeAsDataSource:false`, even with a scope. Set `exposeAsDataSource:true` only for an intentional render-time read such as a GraphQL POST query; provide `scopeInstanceId` and inspect the returned warning. Set it to `false` during `update-resource` to detach existing render-time exposure.\n- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Use `{"type":"literal","value":"website"}` for fixed request text. Header values can be expressions such as `"\\"Bearer \\" + auth.token"`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.\n- Resource methods are `get`, `post`, `put`, and `delete`. Optional resource controls are `graphql` and `system`. Use `control:"graphql"` for GraphQL POST resources with query bodies. Use `control:"system"` for built-in local resource URLs such as `"/$resources/current-date"` and for resources reading the built-in `system` parameter. The built-in system fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`; do not use `system.path`.\n- Whenever an array or object from a resource or data variable should render repeated UI, call `insert-collection` with the complete iterable and one repeated-item JSX root. The command creates the Collection, private item parameters, iterable binding, and descendant item bindings atomically. Use `collectionItem` and `collectionItemKey` expressions in the item JSX. Wrap multiple repeated siblings in one Element, and give repeated Radix items stable unique `value` bindings.\n- Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, `new`, `this`, `await`, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Prefer optional chaining, nullish coalescing, ternaries, property/index access, operators, and the documented string/array methods.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- For visual/design work, verify the rendered result with vision before finishing.\n- Do not edit generated files for normal Webstudio content/design requests.\n- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.\n- Use plain fixed text where documented. Only encode a quoted JavaScript string literal when a field is explicitly documented as an expression-only value.\n- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n',
+ '# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Use MCP locally or optionally connect a client\n\nDo not install, register, or connect an MCP server merely because the user asks\nyou to edit a Webstudio project. If Webstudio MCP tools are already available,\nuse them. If you have shell access, use the local CLI shortcuts such as\n`webstudio meta.index` and `webstudio list-pages`; they expose the same project\noperations without changing client configuration or restarting the app.\n\nOnly when the user explicitly asks for persistent native MCP integration, run\nthe command for their client:\n\n- Claude Code: `webstudio connect claude`\n- Codex: `webstudio connect codex`\n- Cursor: `webstudio connect cursor`\n- VS Code or GitHub Copilot: `webstudio connect vscode`\n\nRun project operations from the linked project root. If the folder is not\nlinked, ask for an editable Builder share link and run\n`webstudio init --link <share-link> --json`. You can then use local CLI\nshortcuts immediately. Do not run `webstudio sync`, `webstudio connect`, or\nrestart the app unless the user specifically wants native MCP registration:\nMCP reads and edits the latest editable Builder build directly, including for\nprojects that have never been published. Treat the share link as a credential\nand do not include it in committed files, logs, screenshots, or issue reports.\n\nThe optional `connect` command verifies project access before changing client configuration. For\nClaude Code, Cursor, and VS Code it safely merges the `webstudio` server into\nthe client\'s project configuration. For Codex it runs both `codex mcp add` and\n`codex mcp get webstudio`; do not repeat those commands separately. Follow the\nreload, restart, or approval instruction printed by `connect`, then verify the\nloaded MCP connection by asking the client to use Webstudio MCP and list the\nproject pages. Use `--print` only to inspect the generated setup without\nchanging configuration or requiring project access.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a compact MCP tool overview. Add `--verbose` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get_more_tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nThe same local shortcut form is shorter and preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nFor this simple path, do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only to get the target `parentInstanceId`.\n\nWhen authoring JSX for `insert-fragment`, use Webstudio component helpers and Webstudio style syntax. Use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n\nWhen the task says another user will edit a page in Content mode, use a Content Block (`ws:block`) around every editable region. Content-mode users can edit text and supported props only in descendants of that block; content outside it is read-only. Put reusable insertable options in the block\'s `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nDo not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.\n\nUse Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/Webstudio names. Do not use React-only aliases such as `className` or `htmlFor`; the runtime rejects them with the Webstudio prop name to use.\n\nUse Webstudio actions for event/action props. Do not pass JavaScript functions such as `onClick={() => ...}`; the runtime rejects them because functions cannot be persisted as Webstudio project data.\n\n```tsx\n<ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n>\n Open\n</ws.element>\n```\n\nPlain JSX prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n\nIf a component has a registered template with required parts, JSX must include those parts explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.\n\n## Animation Components\n\nBefore creating animation examples, inspect the exact components with focused discovery:\n\n```sh\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateChildren"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateText"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:StaggerAnimation"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:VideoAnimation"}\'\n```\n\nUse Animation Group (`AnimateChildren`) as the controller. Put normal instances directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it. Text, Stagger, and Video are helper components with `contentModel.category: "none"` and should not be used as standalone section roots.\n\nDefine timing and CSS changes on the Animation Group `action` prop. Use `type:"view"` for viewport entry/exit progress and `type:"scroll"` for scroll-progress timelines. For in animations, keep the canvas styles as the final state and use `fill:"backwards"` with keyframes that describe the starting state. For out animations, use `fill:"forwards"` with keyframes that describe the ending state.\n\nText Animation settings: `slidingWindow` defaults to `5`, `easing` defaults to `linear`, and `splitBy` defaults to `char`. Use `splitBy:"space"` for word-by-word animation. The parent Animation Group keyframes provide the actual opacity, translate, scale, or other styles.\n\nStagger Animation settings: `slidingWindow` defaults to `1` and `easing` defaults to `linear`. It applies parent Animation Group progress across its direct children. Use `slidingWindow:0` for instant sequential steps, `1` for one child at a time, and values above `1` for overlapping waves.\n\nVideo Animation settings: `timeline` is a boolean. Prefer `insert-component` for Video Animation so the Video child template is inserted, then configure the Video child asset/source. Use short, seek-friendly videos for smooth scroll-linked playback.\n\nUse JSX fragments for authored animation structures when you need styled, editable examples. Put the final visual state in `ws:style` and put the starting or ending animated state in the Animation Group `action` keyframes. Include an explicit `offset` on every keyframe: use `offset: 0` for starting-state keyframes with `fill:"backwards"` and `offset: 1` for ending-state keyframes with `fill:"forwards"`.\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n axis: "block",\n animations: [\n {\n name: "Fade up on entry",\n timing: {\n fill: "backwards",\n rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 24, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n ],\n }}\n>\n <ws.element\n ws:tag="section"\n ws:style={css`\n display: grid;\n gap: 16px;\n padding: 48px;\n border-radius: 24px;\n background: #111827;\n color: white;\n `}\n >\n <ws.element ws:tag="h2">Launch metrics</ws.element>\n <ws.element ws:tag="p">\n A polished card that fades up as it enters the viewport.\n </ws.element>\n </ws.element>\n</animation.AnimateChildren>\n```\n\nFor Text Animation, keep `animation.AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Parallax In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 100, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Opacity In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n {\n name: "Scale In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Parallax Out",\n timing: {\n fill: "forwards",\n rangeStart: ["cover", { type: "unit", value: 50, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 1,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: -100, unit: "px" },\n ],\n },\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n insetStart: { type: "unit", value: 5, unit: "%" },\n insetEnd: { type: "unit", value: 5, unit: "%" },\n isPinned: true,\n }}\n>\n <animation.AnimateText\n splitBy="space"\n slidingWindow={5}\n easing="easeOutQuart"\n >\n <ws.element ws:tag="h2">Animate words with controlled rhythm</ws.element>\n </animation.AnimateText>\n</animation.AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `animation.StaggerAnimation`:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n timing: {\n fill: "backwards",\n rangeStart: ["contain", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["contain", { type: "unit", value: 30, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n }}\n>\n <animation.StaggerAnimation>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </ws.element>\n </animation.StaggerAnimation>\n</animation.AnimateChildren>\n```\n\nFor Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Video progress",\n timing: {\n fill: "both",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [{ offset: 0, styles: {} }],\n },\n ],\n }}\n>\n <animation.VideoAnimation timeline={true}>\n <$.Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </animation.VideoAnimation>\n</animation.AnimateChildren>\n```\n\n## Command Surface Boundary\n\n- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, registry inspection, man, and starting MCP.\n- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.\n- From a shell, call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio insert-fragment \'<json>\' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.\n- For experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- For bounded multi-step shell work, run inline JSON with `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For large batches, write `{ "calls": [{ "tool": "..." }] }` to a normal JSON file and run `webstudio mcp run .temp/mcp-calls.json`.\n- Use JSON strings for `brief` fields. Never pass boolean flags such as `{"brief":true}`.\n- Treat `webstudio mcp single-op-call` and `webstudio mcp run` stderr lines as progress checkpoints; stdout remains JSON on both success and failure. On failure, parse stdout for `{ "ok": false, "error": { "code": "...", "message": "..." } }` before deciding what to fix.\n- If a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in Discord `#help` at https://wstd.us/community. Give them a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n- Run one-shot `webstudio mcp single-op-call` commands sequentially against a linked `.webstudio` folder. If a command returns `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- In delegated or non-streaming agent environments, do not batch many MCP calls silently and do not wrap many shortcut or `webstudio mcp single-op-call` commands in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report that command/result, then wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with `workflow.next {"goal":"design-system-page","phase":"presentation-pass"}`. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world examples, not raw unstyled component dumps.\n- For design-system or “use every component” tasks, start with compact `webstudio components.coverage-plan`, checkpoint, then request component coverage details with `webstudio components.coverage-plan \'{"detail":"roots","offset":20}\'` or `{"detail":"parts"}` only when needed. Do not pass `detail` to `list-pages`; use `list-pages {}` or `get-page-by-path` for page lookup.\n- MCP tool shortcuts are only for MCP tools. If a shortcut is ambiguous with a real top-level command, the real top-level command wins; use `webstudio mcp single-op-call <tool> \'<json>\'` to force the MCP path.\n\n## LLM Implementation Process\n\nUse this process for user requests that change Webstudio content, layout, styles, assets, pages, redirects, resources, or publishing state:\n\n1. Discover capabilities with `webstudio man --json`, `webstudio schema api`, `webstudio schema mcp`, MCP `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.coverage-plan`, `components.search`, `components.get`, `templates.list`, and `templates.get`. From a shell, prefer shortcut calls such as `webstudio meta.index` and `webstudio components.search \'{"brief":"button"}\'` for these focused tool calls; use `webstudio mcp single-op-call` when you need the explicit MCP form. Read full resources such as `webstudio://project/tools` and `webstudio://project/components` only when needed. Do not write scripts to parse full MCP discovery JSON for normal lookup.\n2. Inspect current project state with semantic reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, `list-breakpoints`, and `snapshot` only when needed. Before changing a project, read `get-project-settings` and follow any non-empty `meta.agentInstructions`. These are shared project instructions, not a place for secrets.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.\n4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.\n5. For visual/design work, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate before final response.\n6. Report what changed and what verification ran.\n\n## Visual Design Workflow\n\nFor requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:\n\n1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.\n2. Do not use generated route/component files as the source of truth for editable content.\n3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.\n4. Keep generated project files current, start preview, and capture the changed page with `screenshot`.\n5. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n6. If vision or screenshot tooling is unavailable, state that explicitly and explain what fallback verification was used.\n\n## Responsive Verification Workflow\n\nFor responsive page work, use Builder breakpoints as the source of truth:\n\n1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.\n2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.\n3. Pick screenshot viewport widths from the project breakpoints: include a desktop width, each defined max-width or min-width edge, and a narrow mobile width.\n4. Capture each viewport with `screenshot`, for example `{"path":"/","output":"home-375.png","viewport":{"width":375,"height":812}}` and `{"path":"/","output":"home-1440.png","viewport":{"width":1440,"height":900}}`.\n5. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n6. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.\n\n## Generated Files Guardrails\n\n- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.\n- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.\n- Generated files are build artifacts and may be overwritten by `webstudio build`.\n- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.\n\n## Values vs Bindings\n\nBefore authoring unfamiliar expressions, read `webstudio://project/expressions` with MCP `resources/read` or `webstudio mcp read-resource webstudio://project/expressions`. It documents the supported expression subset, method allowlist, scope, Collection context, and validation limits.\n\n- Use direct value tools for fixed content. For one visible text child, use `update-text` with plain `text`. For a bounded multi-instance literal replacement, use `replace-text` with `find`, `replace`, `pagePath` or `pageId`, and `limit`; it does not change expression children. Use `replace-prop-text` for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop\'s direct type/value.\n- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.\n- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.\n- Expression binding example: `{"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}`.\n- Page metadata fields such as `title`, `description`, `language`, `redirect`, and custom meta content accept plain fixed text. For computed values, pass JavaScript expression code such as `pageTitle ?? "Pricing | Acme"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599, for example `302`. For a dynamic status, pass JavaScript expression code such as `system.status`.\n- Page metadata update example: use `update-page` with `{"pageId":"page-id","values":{"title":"Pricing | Acme","meta":{"description":"Plans for teams"}}}`.\n- Draft a page with `update-page` and `{"pageId":"page-id","values":{"isDraft":true}}`. It remains editable and previewable but is omitted from every publish target, including staging, and from sitemap output.\n- Stage a draft page for a future publish with `{"pageId":"page-id","values":{"isDraft":false}}`. This clears draft state but does not deploy the site. The home page and `/*` catch-all page cannot be drafts.\n- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.\n- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.\n- Assets is one system resource with one response shape and always executes a structured query. `create-assets-resource` without `query` uses the default URL and optional image-dimensions output. Provide query configuration to control filtering, sorting, pagination, selected fields, or file content.\n- For a Markdown-backed blog, read `get-asset-field-catalog`, validate a structured query with `validate-asset-query`, then call `create-assets-resource` or `update-assets-resource`. Set `values.query:null` to restore the default query.\n- Optimize every explicit Assets query for the deployed content-database size. Use `output.mode:"fields"` and select only fields that are actually rendered or otherwise required by the query. Keep `includeMetadata:false` unless the rendered value needs file metadata; diagnostics are returned separately. Do not use `output.mode:"all"` as a convenience default.\n- Use a metadata-only Assets resource with `content.mode:"none"` for listings. Combine filters with `where.all` (AND) and `where.any` (OR). Use a separate Assets resource for the detail route with a slug or alternate-ID filter whose value is `system.params.slug`, `limit:1`, and `content.mode:"markdown-body"`. Request `full` content only when the whole source file is rendered; otherwise prefer `markdown-body` or a bounded byte range.\n- Markdown returned with `content.mode:"markdown-body"` resolves conventional relative links and images such as `../images/hero.png` to matching Assets. Markdown Embed permits sanitized figures, audio, video, and iframes, but removes scripts, inline event handlers, and unsafe URLs.\n- Assets expose an ID-keyed map at `<dataSourceName>.data` and collection information at `<dataSourceName>.meta`. Bind a listing Collection to `posts.data` and a one-result detail Collection to `post.data`; each item value contains selected fields and its item key is the asset ID. Read frontmatter or JSON fields from `item.properties`, the derived excerpt from `item.excerpt`, and requested Markdown from `item.content.text`.\n- Use `preview-asset-query` with concrete values before binding expressions in the saved resource. Inspect `__diagnostics__.usedBytes`, `maxBytes`, `unboundedBytes`, and `truncated`. When usage approaches the limit, first remove unused output fields, then narrow candidate files with filters, and finally reduce or remove embedded content. Inspect saved mode and configuration with `list-assets-resources` or `get-assets-resource`; shared index maintenance is automatic.\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays, objects, filters, and nested data.\n- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.\n- Use scoped resources for read data. A GET resource created with `scopeInstanceId`/`dataSourceName` defaults to `exposeAsDataSource:true`, becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Read the loaded resource result from its wrapper, usually `.data`.\n- Use prop-bound resources for actions. A resource created without `scopeInstanceId` and bound to a component prop such as Form `action` with `bind-props` and `binding.type: "resource"` becomes an action resource in the page resource `action` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.\n- POST, PUT, and DELETE resources default to `exposeAsDataSource:false`, even with a scope. Set `exposeAsDataSource:true` only for an intentional render-time read such as a GraphQL POST query; provide `scopeInstanceId` and inspect the returned warning. Set it to `false` during `update-resource` to detach existing render-time exposure.\n- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Use `{"type":"literal","value":"website"}` for fixed request text. Header values can be expressions such as `"\\"Bearer \\" + auth.token"`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.\n- Resource methods are `get`, `post`, `put`, and `delete`. Optional resource controls are `graphql` and `system`. Use `control:"graphql"` for GraphQL POST resources with query bodies. Use `control:"system"` for built-in local resource URLs such as `"/$resources/current-date"` and for resources reading the built-in `system` parameter. The built-in system fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`; do not use `system.path`.\n- Whenever an array or object from a resource or data variable should render repeated UI, call `insert-collection` with the complete iterable and one repeated-item JSX root. The command creates the Collection, private item parameters, iterable binding, and descendant item bindings atomically. Use `collectionItem` and `collectionItemKey` expressions in the item JSX. Wrap multiple repeated siblings in one Element, and give repeated Radix items stable unique `value` bindings.\n- Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, `new`, `this`, `await`, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Prefer optional chaining, nullish coalescing, ternaries, property/index access, operators, and the documented string/array methods.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- For visual/design work, verify the rendered result with vision before finishing.\n- Do not edit generated files for normal Webstudio content/design requests.\n- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.\n- Use plain fixed text where documented. Only encode a quoted JavaScript string literal when a field is explicitly documented as an expression-only value.\n- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n',
"manual-mcp":
- '# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\nIf you are already working with an agent, ask it to connect the current folder\nto Webstudio. Give the editable Builder share link only when the trusted agent\nasks for it. The agent should perform the steps below, follow any\nclient-specific output from `webstudio connect`, and verify the connection by\nlisting the project pages. Treat the share link as a credential: do not include\nit in committed files, screenshots, logs, or issue reports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Synchronize it with `webstudio sync`.\n3. Generate the client configuration with `webstudio connect claude`,\n `webstudio connect codex`, `webstudio connect cursor`, or\n `webstudio connect vscode`. Use `--print` to preview the generated setup.\n4. Check capabilities with `webstudio permissions --json`.\n5. For shell-driven agents, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n6. For MCP clients, start the server with `webstudio mcp`.\n7. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nAfter linking and synchronization, run `webstudio connect <client>`, reload or\nrestart the client, then ask the agent to use Webstudio MCP to list the project\npages. The supported client names are `claude`, `codex`, `cursor`, and `vscode`.\nFor Codex, `connect` registers and verifies the server through the Codex CLI;\nthe resulting server appears in Codex settings. Use `--print` to inspect the\nexact registration command without changing configuration or requiring project\naccess. Before changing client configuration, `connect` verifies that the saved\nproject endpoint is reachable and its credential is accepted. If verification\nfails, follow the specific connection, compatibility, or relinking guidance in\nthe error.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Prefer JSX for authored/styled content. Common `insert-fragment` inputs:\n\n```jsonl\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag="h2">Northstar Product OS</ws.element><ws.element ws:tag="p">Reusable patterns for teams.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" style={{ padding: 32, borderRadius: 16 }}><ws.element ws:tag="h2">Operations Console</ws.element><ws.element ws:tag="p">React-style object styles become editable Webstudio styles.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:tokens={[token(\\"accent\\", css`color: #0f766e;`)]}><ws.element ws:tag="button" onClick={new ActionValue([\\"event\\"], expression`console.log(event)`)}>Track launch</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\"><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n```\n\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build version. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- To work with another previously linked project without changing the directory\'s default link, start MCP or a shell call with `--project <projectId>`, for example `webstudio mcp --project <projectId>` or `webstudio mcp single-op-call list-pages --project <projectId>`. Selected projects use isolated local session and checkpoint files.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get_more_tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details\n- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: compact metadata for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, string list, and JSON variables.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List and inspect complete asset metadata; upload, download, update, move, duplicate, find usage for, replace, and delete assets.\n- List, create, rename, move, recursively duplicate, and recursively delete nested asset folders.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- A mutation is durable only when `meta.session.committed` is true.\n- For visual/design work, verify the rendered result with vision before finishing.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects:\n\n{{mcpArgumentExampleIndex}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',
+ '# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\nIf you are already working with a shell-capable agent, it can use the local CLI\ndirectly. Native MCP client registration is optional. Give the editable Builder\nshare link only when the trusted agent asks for it. Treat the share link as a\ncredential: do not include it in committed files, screenshots, logs, or issue\nreports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nDo not run `webstudio sync`, install an MCP server, change client configuration,\nor restart the app for this local CLI workflow.\n\nWhen the user explicitly wants persistent native MCP integration, run\n`webstudio connect claude`, `webstudio connect codex`, `webstudio connect\ncursor`, or `webstudio connect vscode`. This optional command changes client\nconfiguration, so follow its client-specific reload or restart instruction.\nUse `--print` to inspect the generated setup without changing configuration or\nrequiring project access. For Codex, `connect` registers and verifies the server\nthrough the Codex CLI. Before changing client configuration, `connect` verifies\nthat the saved project endpoint is reachable and its credential is accepted.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Prefer JSX for authored/styled content. Common `insert-fragment` inputs:\n\n```jsonl\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag="h2">Northstar Product OS</ws.element><ws.element ws:tag="p">Reusable patterns for teams.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" style={{ padding: 32, borderRadius: 16 }}><ws.element ws:tag="h2">Operations Console</ws.element><ws.element ws:tag="p">React-style object styles become editable Webstudio styles.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:tokens={[token(\\"accent\\", css`color: #0f766e;`)]}><ws.element ws:tag="button" onClick={new ActionValue([\\"event\\"], expression`console.log(event)`)}>Track launch</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\"><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n```\n\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build version. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- To work with another previously linked project without changing the directory\'s default link, start MCP or a shell call with `--project <projectId>`, for example `webstudio mcp --project <projectId>` or `webstudio mcp single-op-call list-pages --project <projectId>`. Selected projects use isolated local session and checkpoint files.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get_more_tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details\n- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: compact metadata for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, and JSON variables. Arrays use JSON.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List and inspect complete asset metadata; upload, download, update, move, duplicate, find usage for, replace, and delete assets.\n- List, create, rename, move, recursively duplicate, and recursively delete nested asset folders.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- A mutation is durable only when `meta.session.committed` is true.\n- For visual/design work, verify the rendered result with vision before finishing.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects:\n\n{{mcpArgumentExampleIndex}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',
"mcp-startup-epilogue":
'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output.\n\nPlain `webstudio mcp` starts the stdio MCP server for real MCP clients. Do not manually type or pipe raw JSON-RPC frames into it from an interactive shell or PTY. From a shell, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for one bounded tool call. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for small multi-call batches in one shared CLI session. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nPut each local CLI call in its own shell command; do not chain helper commands with `&&`, `;`, command substitution, or shell wrappers around the CLI when reporting a CLI step. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`; those can resolve an older binary. For example:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nThe shorter local shortcut form is preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nFor simple authored/styled sections, run the three commands above. Do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only when you still need the target `parentInstanceId`.\n\nWhen building for a Content-mode editor, use a Content Block (`ws:block`) around every region that editor must change. Content-mode text and supported props are editable only in Content Block descendants; content outside is read-only. Keep reusable insertable source options in the block\'s `ws:block-template` child. Templates themselves are protected; an editor\'s inserted copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nRun it from the linked Webstudio project root. The startup status line prints that absolute root; use it for local files such as `<project root>/.temp/script.mjs`, screenshots, and generated artifacts.\n\nFor experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n\nStartup marks cached ProjectSession data stale so MCP tools read the current Builder dev build.\n\nAfter startup, use focused discovery tools with concrete JSON. For delegated design-system or “use every component” tasks, start with exactly one command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`; report the returned checkpoint to the parent/user and stop until continued. For other tasks, read `meta.index` first. From a shell, `webstudio mcp list-tools` is a concise alias for the initial tool catalog. Then call shortcuts such as `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio workflow.next \'{"goal":"design-system-page"}\'`, `webstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.summary`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`. Use `webstudio mcp single-op-call` when you need the explicit MCP form. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. In JSX, use `ws:style={css\\`...\\`}`for styles,`class`/`for`instead of`className`/`htmlFor`, `ActionValue`for actions instead of JavaScript functions such as`onClick={() => ...}`, only JSON-compatible plain prop values, and no host globals or dynamic code APIs. For bounded multi-step shell work, run inline JSON like `webstudio mcp run \'[{"tool":"meta.index"},{"tool":"components.search","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For larger batches, write `{ "calls": [{ "tool": "..." }] }`to`.temp/mcp-calls.json`and run`webstudio mcp run .temp/mcp-calls.json`. If any call returns `checkpoint.required`, `mcp run`stops immediately before later calls; report the checkpoint and call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`before continuing. For design-system or “use every component” tasks, call`workflow.next {"goal":"design-system-page"}`for the next bounded phase, report its checkpoint, wait until the parent/user continues, call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, then run only that phase. Start coverage phases with compact`webstudio components.coverage-plan`, checkpoint, then request component coverage details with `components.coverage-plan {"detail":"roots"}`or`components.coverage-plan {"detail":"parts"}`. Do not pass `detail`to`list-pages`; use `list-pages {}`or`get-page-by-path`for page lookup. Read MCP overview resources`webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview`when useful. Read full resources`webstudio://project/tools`and`webstudio://project/components` only when focused tools are insufficient; do not dump or parse full discovery JSON for common lookup.\n\nAfter startup, MCP clients discover capabilities with `tools/list`, `resources/list`, `meta.index`, `meta.guide`, and `meta.get_more_tools`.\n\nstdout is reserved for MCP JSON-RPC messages while the server is running.\n\nThe server advertises MCP `logging` capability and sends sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`. It also writes the same sparse lifecycle status lines to stderr, prefixed with `[webstudio mcp]`, including a final ready line. Treat the process as healthy and long-running after either ready signal; surface tool lifecycle logs as progress checkpoints and interact through MCP JSON-RPC on stdin/stdout.\n\n`webstudio mcp single-op-call` also writes sparse lifecycle lines to stderr for each one-shot call. Use those stderr lines as progress checkpoints and parse stdout as JSON on both success and failure. Failed one-shot calls print `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` to stdout and exit nonzero. If a one-shot call returns checkpoint.required, read-only discovery remains available, while later mutations fail with `CHECKPOINT_REQUIRED` until you report the checkpoint and call `webstudio mcp single-op-call checkpoint.ack \'{"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}\'`.\n\n`webstudio mcp run` also writes sparse lifecycle lines to stderr and prints one JSON result on success or failure. It stops at the first failed call or checkpoint requirement, including `CHECKPOINT_REQUIRED`, and preserves partial results so delegated agents can report exactly where they stopped.\n\nIf a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in the Webstudio Discord `#help` channel at https://wstd.us/community. Give the user a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n\nIf you are running as a delegated or non-streaming agent whose parent cannot see live stderr/stdout, do not batch many MCP calls silently and do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, return a concise checkpoint with that command/result, and wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase.\n',
"mcp-vision":
@@ -83,7 +83,14 @@ export const cliDocSections = {
'Stage a draft page for a future publish with {"pageId":"page-id","values":{"isDraft":false}}. This clears draft state but does not deploy the site. The home page and /* catch-all page cannot be drafts.',
'Resource url accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as "https://api.example.com/items?tag=" + filters.tag. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use { "type": "literal", "value": "application/json" }.',
'Resource update example: use update-resource with {"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}.',
- "Data variable values support string, number, boolean, string[], and json. Use string[] only for arrays where every item is a string; use json for objects, mixed arrays, filters, and nested data.",
+ "Assets is one system resource with one response shape and always executes a structured query. create-assets-resource without query uses the default URL and optional image-dimensions output. Provide query configuration to control filtering, sorting, pagination, selected fields, or file content.",
+ "For a Markdown-backed blog, read get-asset-field-catalog, validate a structured query with validate-asset-query, then call create-assets-resource or update-assets-resource. Set values.query:null to restore the default query.",
+ 'Optimize every explicit Assets query for the deployed content-database size. Use output.mode:"fields" and select only fields that are actually rendered or otherwise required by the query. Keep includeMetadata:false unless the rendered value needs file metadata; diagnostics are returned separately. Do not use output.mode:"all" as a convenience default.',
+ 'Use a metadata-only Assets resource with content.mode:"none" for listings. Combine filters with where.all (AND) and where.any (OR). Use a separate Assets resource for the detail route with a slug or alternate-ID filter whose value is system.params.slug, limit:1, and content.mode:"markdown-body". Request full content only when the whole source file is rendered; otherwise prefer markdown-body or a bounded byte range.',
+ 'Markdown returned with content.mode:"markdown-body" resolves conventional relative links and images such as ../images/hero.png to matching Assets. Markdown Embed permits sanitized figures, audio, video, and iframes, but removes scripts, inline event handlers, and unsafe URLs.',
+ "Assets expose an ID-keyed map at <dataSourceName>.data and collection information at <dataSourceName>.meta. Bind a listing Collection to posts.data and a one-result detail Collection to post.data; each item value contains selected fields and its item key is the asset ID. Read frontmatter or JSON fields from item.properties, the derived excerpt from item.excerpt, and requested Markdown from item.content.text.",
+ "Use preview-asset-query with concrete values before binding expressions in the saved resource. Inspect __diagnostics__.usedBytes, maxBytes, unboundedBytes, and truncated. When usage approaches the limit, first remove unused output fields, then narrow candidate files with filters, and finally reduce or remove embedded content. Inspect saved mode and configuration with list-assets-resources or get-assets-resource; shared index maintenance is automatic.",
+ "Data variable values support string, number, boolean, and json. Use json for all arrays, objects, filters, and nested data.",
"Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as system in expressions where they are already in scope.",
"Use scoped resources for read data. A GET resource created with scopeInstanceId/dataSourceName defaults to exposeAsDataSource:true, becomes a scoped resource data variable, is generated into the page resource data map, and may be loaded while rendering the page. Read the loaded resource result from its wrapper, usually .data.",
'Use prop-bound resources for actions. A resource created without scopeInstanceId and bound to a component prop such as Form action with bind-props and binding.type: "resource" becomes an action resource in the page resource action map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.',
diff --git a/packages/cli/src/docs/api-use-cases.md b/packages/cli/src/docs/api-use-cases.md
index c0895d054e..2f698bddcd 100644
--- a/packages/cli/src/docs/api-use-cases.md
+++ b/packages/cli/src/docs/api-use-cases.md
@@ -659,12 +659,12 @@ Commands:
- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}
- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}
- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}
-- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}
+- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}
- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}
Notes:
-- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`.
+- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays and objects.
- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.
## Update data variable
@@ -714,6 +714,34 @@ Commands:
- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}
- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}
+## Query Markdown assets
+
+Commands:
+
+- MCP tool: get-asset-field-catalog {}
+- MCP tool: validate-asset-query {"query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","draft"],"operator":"ne","value":true}]},"limit":20}}
+- MCP tool: create-assets-resource {"name":"All assets","scopeInstanceId":"<instanceId>","dataSourceName":"assets"}
+- MCP tool: create-assets-resource {"name":"Published posts","scopeInstanceId":"<instanceId>","dataSourceName":"posts","query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","draft"],"operator":"ne","value":{"type":"literal","value":true}}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"}],"limit":{"type":"literal","value":20},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["excerpt"]]},"content":{"mode":"none"}}}
+- MCP tool: create-assets-resource {"name":"Post by slug or ID","scopeInstanceId":"<instanceId>","dataSourceName":"post","query":{"where":{"any":[{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"},{"field":["id"],"operator":"eq","value":"system.params.slug"}]},"limit":{"type":"literal","value":1},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","publishedAt"]]},"content":{"mode":"markdown-body","maxBytes":1048576}}}
+- MCP tool: list-assets-resources {}
+- MCP tool: get-assets-resource {"resourceId":"<resourceId>"}
+- MCP tool: update-assets-resource {"resourceId":"<resourceId>","values":{"query":null}}
+- MCP tool: preview-asset-query {"query":{"where":{"all":[{"field":["properties","slug"],"operator":"eq","value":"hello-world"}]},"limit":1,"content":{"mode":"markdown-body","maxBytes":1048576}}}
+
+Notes:
+
+- Read the field catalog before authoring unfamiliar queries. It includes dynamic schema-less frontmatter paths such as `properties.author.name`, observed types, optionality, and mixed-type state without downloading Markdown files.
+- Minimize the deployed content database by using `output.mode:"fields"` and selecting only fields the rendered page needs. Keep `includeMetadata:false` unless the rendered value needs file metadata such as name, path, MIME type, or creation date, and avoid `output.mode:"all"` as a convenience default. Query diagnostics are returned separately and do not require metadata output. Filters and sorting may still require their referenced fields in the database.
+- Combine filters with `where.all` (AND) and `where.any` (OR), including nested groups. Filter values, limit, and offset on a saved resource may be Webstudio expressions evaluated at render time. Preview queries use concrete JSON values.
+- Use `content.mode:"none"` for listings. Request `markdown-body`, `full`, or a bounded `range` only after filtering to the intended files, normally with `limit:1` for a slug detail route.
+- In Markdown, reference sibling Assets with conventional relative URLs such as `../images/hero.png`. When `markdown-body` is requested, the content engine resolves matching files against the Markdown file's folder and emits the correct Builder or published Asset URL. Keep external URLs absolute.
+- Markdown Embed renders sanitized authored HTML for figures, captions, audio, video, and iframes. Scripts, inline event handlers, `srcdoc`, and unsafe URL protocols are removed. Executable component composition remains separate future MDX work.
+- Preview each query with concrete values before saving it. Inspect `__diagnostics__.usedBytes`, `maxBytes`, `unboundedBytes`, and `truncated`; when usage approaches the limit, remove unused output fields, narrow candidate files, and reduce embedded content in that order.
+- Read Assets from the ID-keyed map at `<dataSourceName>.data`, with collection information such as `totalCount` and `hasMore` at `<dataSourceName>.meta`. Bind a listing Collection to `posts.data` and a one-result detail Collection to `post.data`. On each value, selected file fields such as `id`, `name`, and `extension` are top-level; Markdown frontmatter and JSON fields are under `properties`; the derived `excerpt` is top-level; and requested Markdown is at `content.text`.
+- Assets has one response shape and always executes a structured query. Omit `query` to use the default query, which selects URL and optional image dimensions. Provide query configuration to control filtering, sorting, pagination, selected fields, or file content. Set `values.query:null` to restore the default query.
+- `create-assets-resource` and `update-assets-resource` are the semantic authoring path. Do not construct the internal query URL, headers, or body expression manually.
+- The shared metadata index is maintained automatically and is emitted only when a configured Assets resource is reachable.
+
## Delete resource
Commands:
@@ -1079,7 +1107,7 @@ Notes:
Commands:
- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}
-- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}
+- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}
- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}
- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}
- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \"query Post($slug: String!) { post(slug: $slug) { title } }\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}
diff --git a/packages/cli/src/docs/manual-api.md b/packages/cli/src/docs/manual-api.md
index 720853d1e1..18de72d95b 100644
--- a/packages/cli/src/docs/manual-api.md
+++ b/packages/cli/src/docs/manual-api.md
@@ -123,9 +123,9 @@ applying direct changes.
Variables can be scoped to an instance. Expressions under that instance can use
the variable by name; nested variables with the same name mask outer variables.
-Variable values support `string`, `number`, `boolean`, `string[]`, and `json`.
-Use `string[]` for lists of strings such as tags or selected categories; use
-`json` for objects, arrays with mixed shapes, or nested API filter state.
+Variable values support `string`, `number`, `boolean`, and `json`. Use `json`
+for all arrays and objects, including tags, selected categories, and nested API
+filter state.
Parameters are internal scoped runtime values provided by pages, collections,
or components. They are not a public authoring surface: do not create, update,
or delete parameter records. Public tools should preserve existing parameter
diff --git a/packages/cli/src/docs/manual-llm.md b/packages/cli/src/docs/manual-llm.md
index 42673285e9..a06009a269 100644
--- a/packages/cli/src/docs/manual-llm.md
+++ b/packages/cli/src/docs/manual-llm.md
@@ -11,23 +11,32 @@ resolve an older binary.
For delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next '{"goal":"design-system-page"}'`. Report that returned checkpoint to the parent/user and stop until continued.
-## Connect an MCP client
+## Use MCP locally or optionally connect a client
-When the user asks to connect the current folder to Webstudio, run the command
-for the agent client you are currently using:
+Do not install, register, or connect an MCP server merely because the user asks
+you to edit a Webstudio project. If Webstudio MCP tools are already available,
+use them. If you have shell access, use the local CLI shortcuts such as
+`webstudio meta.index` and `webstudio list-pages`; they expose the same project
+operations without changing client configuration or restarting the app.
+
+Only when the user explicitly asks for persistent native MCP integration, run
+the command for their client:
- Claude Code: `webstudio connect claude`
- Codex: `webstudio connect codex`
- Cursor: `webstudio connect cursor`
- VS Code or GitHub Copilot: `webstudio connect vscode`
-Run the command from the linked project root. If the folder is not linked, ask
-for an editable Builder share link and run
-`webstudio init --link <share-link> --json`, followed by `webstudio sync`, then
-retry `webstudio connect <client>`. Treat the share link as a credential and do
-not include it in committed files, logs, screenshots, or issue reports.
+Run project operations from the linked project root. If the folder is not
+linked, ask for an editable Builder share link and run
+`webstudio init --link <share-link> --json`. You can then use local CLI
+shortcuts immediately. Do not run `webstudio sync`, `webstudio connect`, or
+restart the app unless the user specifically wants native MCP registration:
+MCP reads and edits the latest editable Builder build directly, including for
+projects that have never been published. Treat the share link as a credential
+and do not include it in committed files, logs, screenshots, or issue reports.
-`connect` verifies project access before changing client configuration. For
+The optional `connect` command verifies project access before changing client configuration. For
Claude Code, Cursor, and VS Code it safely merges the `webstudio` server into
the client's project configuration. For Codex it runs both `codex mcp add` and
`codex mcp get webstudio`; do not repeat those commands separately. Follow the
@@ -450,7 +459,14 @@ Before authoring unfamiliar expressions, read `webstudio://project/expressions`
- Stage a draft page for a future publish with `{"pageId":"page-id","values":{"isDraft":false}}`. This clears draft state but does not deploy the site. The home page and `/*` catch-all page cannot be drafts.
- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.
- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.
-- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`. Use `string[]` only for arrays where every item is a string; use `json` for objects, mixed arrays, filters, and nested data.
+- Assets is one system resource with one response shape and always executes a structured query. `create-assets-resource` without `query` uses the default URL and optional image-dimensions output. Provide query configuration to control filtering, sorting, pagination, selected fields, or file content.
+- For a Markdown-backed blog, read `get-asset-field-catalog`, validate a structured query with `validate-asset-query`, then call `create-assets-resource` or `update-assets-resource`. Set `values.query:null` to restore the default query.
+- Optimize every explicit Assets query for the deployed content-database size. Use `output.mode:"fields"` and select only fields that are actually rendered or otherwise required by the query. Keep `includeMetadata:false` unless the rendered value needs file metadata; diagnostics are returned separately. Do not use `output.mode:"all"` as a convenience default.
+- Use a metadata-only Assets resource with `content.mode:"none"` for listings. Combine filters with `where.all` (AND) and `where.any` (OR). Use a separate Assets resource for the detail route with a slug or alternate-ID filter whose value is `system.params.slug`, `limit:1`, and `content.mode:"markdown-body"`. Request `full` content only when the whole source file is rendered; otherwise prefer `markdown-body` or a bounded byte range.
+- Markdown returned with `content.mode:"markdown-body"` resolves conventional relative links and images such as `../images/hero.png` to matching Assets. Markdown Embed permits sanitized figures, audio, video, and iframes, but removes scripts, inline event handlers, and unsafe URLs.
+- Assets expose an ID-keyed map at `<dataSourceName>.data` and collection information at `<dataSourceName>.meta`. Bind a listing Collection to `posts.data` and a one-result detail Collection to `post.data`; each item value contains selected fields and its item key is the asset ID. Read frontmatter or JSON fields from `item.properties`, the derived excerpt from `item.excerpt`, and requested Markdown from `item.content.text`.
+- Use `preview-asset-query` with concrete values before binding expressions in the saved resource. Inspect `__diagnostics__.usedBytes`, `maxBytes`, `unboundedBytes`, and `truncated`. When usage approaches the limit, first remove unused output fields, then narrow candidate files with filters, and finally reduce or remove embedded content. Inspect saved mode and configuration with `list-assets-resources` or `get-assets-resource`; shared index maintenance is automatic.
+- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays, objects, filters, and nested data.
- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.
- Use scoped resources for read data. A GET resource created with `scopeInstanceId`/`dataSourceName` defaults to `exposeAsDataSource:true`, becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Read the loaded resource result from its wrapper, usually `.data`.
- Use prop-bound resources for actions. A resource created without `scopeInstanceId` and bound to a component prop such as Form `action` with `bind-props` and `binding.type: "resource"` becomes an action resource in the page resource `action` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.
diff --git a/packages/cli/src/docs/manual-mcp.md b/packages/cli/src/docs/manual-mcp.md
index 65afa96947..52a91b19c7 100644
--- a/packages/cli/src/docs/manual-mcp.md
+++ b/packages/cli/src/docs/manual-mcp.md
@@ -4,33 +4,28 @@
## Startup
-If you are already working with an agent, ask it to connect the current folder
-to Webstudio. Give the editable Builder share link only when the trusted agent
-asks for it. The agent should perform the steps below, follow any
-client-specific output from `webstudio connect`, and verify the connection by
-listing the project pages. Treat the share link as a credential: do not include
-it in committed files, screenshots, logs, or issue reports.
+If you are already working with a shell-capable agent, it can use the local CLI
+directly. Native MCP client registration is optional. Give the editable Builder
+share link only when the trusted agent asks for it. Treat the share link as a
+credential: do not include it in committed files, screenshots, logs, or issue
+reports.
1. Configure a project with `webstudio init --link <api-share-link> --json`.
-2. Synchronize it with `webstudio sync`.
-3. Generate the client configuration with `webstudio connect claude`,
- `webstudio connect codex`, `webstudio connect cursor`, or
- `webstudio connect vscode`. Use `--print` to preview the generated setup.
-4. Check capabilities with `webstudio permissions --json`.
-5. For shell-driven agents, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment '<json>' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> '<json>'` when you need to force the MCP path, or `webstudio mcp run '[{"tool":"components.find","input":{"brief":"button"}}]'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.
-6. For MCP clients, start the server with `webstudio mcp`.
-7. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide '{"brief":"Create a design system page using every component"}'`.
-
-After linking and synchronization, run `webstudio connect <client>`, reload or
-restart the client, then ask the agent to use Webstudio MCP to list the project
-pages. The supported client names are `claude`, `codex`, `cursor`, and `vscode`.
-For Codex, `connect` registers and verifies the server through the Codex CLI;
-the resulting server appears in Codex settings. Use `--print` to inspect the
-exact registration command without changing configuration or requiring project
-access. Before changing client configuration, `connect` verifies that the saved
-project endpoint is reachable and its credential is accepted. If verification
-fails, follow the specific connection, compatibility, or relinking guidance in
-the error.
+2. Check capabilities with `webstudio permissions --json`.
+3. Use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment '<json>' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> '<json>'` when you need to force the MCP path, or `webstudio mcp run '[{"tool":"components.find","input":{"brief":"button"}}]'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.
+4. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide '{"brief":"Create a design system page using every component"}'`.
+
+Do not run `webstudio sync`, install an MCP server, change client configuration,
+or restart the app for this local CLI workflow.
+
+When the user explicitly wants persistent native MCP integration, run
+`webstudio connect claude`, `webstudio connect codex`, `webstudio connect
+cursor`, or `webstudio connect vscode`. This optional command changes client
+configuration, so follow its client-specific reload or restart instruction.
+Use `--print` to inspect the generated setup without changing configuration or
+requiring project access. For Codex, `connect` registers and verifies the server
+through the Codex CLI. Before changing client configuration, `connect` verifies
+that the saved project endpoint is reachable and its credential is accepted.
Start MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.
@@ -267,7 +262,7 @@ terms, agents can:
- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.
- List, define, rename, delete, and rewrite CSS variables.
- List, create, update, and delete static data variables.
-- Create string, number, boolean, string list, and JSON variables.
+- Create string, number, boolean, and JSON variables. Arrays use JSON.
- Delete unused data variables.
- List, create, update, upsert, bind, and delete resources.
- Create HTTP resources.
diff --git a/packages/cli/src/filesystem-content-source.test.ts b/packages/cli/src/filesystem-content-source.test.ts
new file mode 100644
index 0000000000..09dfa9299d
--- /dev/null
+++ b/packages/cli/src/filesystem-content-source.test.ts
@@ -0,0 +1,240 @@
+import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import {
+ createContentCompilationPlan,
+ createLiteralContentCompilationQuery,
+} from "@webstudio-is/content-engine";
+import type { Asset, AssetFolders } from "@webstudio-is/sdk";
+import { afterEach, describe, expect, test } from "vitest";
+import { createFileSystemContentSource } from "./filesystem-content-source";
+
+const temporaryDirectories: string[] = [];
+
+const createTemporaryDirectory = async () => {
+ const directory = await mkdtemp(join(tmpdir(), "webstudio-content-source-"));
+ temporaryDirectories.push(directory);
+ return directory;
+};
+
+afterEach(async () => {
+ await Promise.all(
+ temporaryDirectories
+ .splice(0)
+ .map((directory) => rm(directory, { recursive: true, force: true }))
+ );
+});
+
+const createAsset = (name: string): Asset => ({
+ id: "post",
+ projectId: "project",
+ type: "file",
+ name,
+ filename: "hello",
+ size: 0,
+ description: "Post description",
+ folderId: "blog",
+ createdAt: "2026-07-27T00:00:00.000Z",
+ format: "md",
+ meta: {},
+});
+
+const folders: AssetFolders = new Map([
+ [
+ "blog",
+ {
+ id: "blog",
+ projectId: "project",
+ name: "Blog",
+ createdAt: "2026-07-27T00:00:00.000Z",
+ },
+ ],
+]);
+
+const plan = createContentCompilationPlan([
+ createLiteralContentCompilationQuery({
+ id: "posts",
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "hello",
+ },
+ ],
+ },
+ sort: [],
+ limit: 10,
+ offset: 0,
+ output: { mode: "all", includeMetadata: true },
+ content: { mode: "full" },
+ },
+ }),
+]);
+
+describe("filesystem content source", () => {
+ test("uses the shared parser and hydrates matching local content", async () => {
+ const directory = await createTemporaryDirectory();
+ const name = "hello_hash.md";
+ const content = "---\ntitle: Hello\nslug: hello\n---\n# Hello\nBody";
+ await writeFile(join(directory, name), content);
+ const snapshot = await createFileSystemContentSource({
+ projectId: "project",
+ assets: [createAsset(name)],
+ folders,
+ assetsDirectory: directory,
+ }).openSnapshot();
+
+ await expect(snapshot.loadEntries(plan)).resolves.toMatchObject([
+ {
+ document: {
+ path: "Blog/hello.md",
+ description: "Post description",
+ properties: { title: "Hello", slug: "hello" },
+ },
+ content,
+ },
+ ]);
+ await expect(snapshot.loadEntries()).resolves.toMatchObject([
+ {
+ document: {
+ properties: { title: "Hello", slug: "hello" },
+ excerpt: "Hello Body",
+ },
+ },
+ ]);
+ await expect(snapshot.isCurrent()).resolves.toBe(true);
+ });
+
+ test("invalidates a snapshot when a local file is replaced", async () => {
+ const directory = await createTemporaryDirectory();
+ const name = "hello_hash.md";
+ const path = join(directory, name);
+ await writeFile(path, "first");
+ const snapshot = await createFileSystemContentSource({
+ projectId: "project",
+ assets: [createAsset(name)],
+ folders,
+ assetsDirectory: directory,
+ }).openSnapshot();
+
+ await writeFile(path, "replacement");
+
+ await expect(snapshot.isCurrent()).resolves.toBe(false);
+ await expect(snapshot.loadEntries(plan)).rejects.toThrow(
+ "Content source file changed"
+ );
+ });
+
+ test("invalidates a snapshot when a local file is deleted", async () => {
+ const directory = await createTemporaryDirectory();
+ const name = "hello_hash.md";
+ const path = join(directory, name);
+ await writeFile(path, "content");
+ const snapshot = await createFileSystemContentSource({
+ projectId: "project",
+ assets: [createAsset(name)],
+ folders,
+ assetsDirectory: directory,
+ }).openSnapshot();
+
+ await rm(path);
+
+ await expect(snapshot.isCurrent()).resolves.toBe(false);
+ });
+
+ test("rejects selected content that cannot be embedded as UTF-8", async () => {
+ const directory = await createTemporaryDirectory();
+ const name = "invalid_hash.md";
+ await writeFile(join(directory, name), new Uint8Array([0xff]));
+ const snapshot = await createFileSystemContentSource({
+ projectId: "project",
+ assets: [createAsset(name)],
+ folders,
+ assetsDirectory: directory,
+ }).openSnapshot();
+
+ const fullContentPlan = createContentCompilationPlan([
+ createLiteralContentCompilationQuery({
+ id: "all-posts",
+ query: {
+ where: { all: [] },
+ sort: [],
+ limit: 1,
+ offset: 0,
+ output: { mode: "base", includeMetadata: true },
+ content: { mode: "full" },
+ },
+ }),
+ ]);
+ await expect(snapshot.loadEntries(fullContentPlan)).rejects.toThrow(
+ "Selected content source file is not valid UTF-8"
+ );
+ });
+
+ test("rejects symlinks outside the assets directory", async () => {
+ const parent = await createTemporaryDirectory();
+ const directory = join(parent, "assets");
+ const outside = join(parent, "outside.md");
+ const name = "outside_hash.md";
+ await mkdir(directory);
+ await writeFile(outside, "private");
+ await symlink(outside, join(directory, name));
+
+ await expect(
+ createFileSystemContentSource({
+ projectId: "project",
+ assets: [createAsset(name)],
+ folders,
+ assetsDirectory: directory,
+ }).openSnapshot()
+ ).rejects.toThrow("outside the assets directory");
+ });
+
+ test("invalidates a snapshot when the assets directory symlink changes", async () => {
+ const parent = await createTemporaryDirectory();
+ const firstDirectory = join(parent, "first");
+ const secondDirectory = join(parent, "second");
+ const linkedDirectory = join(parent, "assets");
+ const name = "hello_hash.md";
+ await mkdir(firstDirectory);
+ await mkdir(secondDirectory);
+ await writeFile(join(firstDirectory, name), "first");
+ await writeFile(join(secondDirectory, name), "second");
+ await symlink(firstDirectory, linkedDirectory);
+ const snapshot = await createFileSystemContentSource({
+ projectId: "project",
+ assets: [createAsset(name)],
+ folders,
+ assetsDirectory: linkedDirectory,
+ }).openSnapshot();
+
+ await rm(linkedDirectory);
+ await symlink(secondDirectory, linkedDirectory);
+
+ await expect(snapshot.isCurrent()).resolves.toBe(false);
+ });
+
+ test("invalidates a snapshot when an asset symlink changes", async () => {
+ const directory = await createTemporaryDirectory();
+ const first = join(directory, "first.md");
+ const second = join(directory, "second.md");
+ const name = "hello_hash.md";
+ const linkedFile = join(directory, name);
+ await writeFile(first, "first");
+ await writeFile(second, "second");
+ await symlink(first, linkedFile);
+ const snapshot = await createFileSystemContentSource({
+ projectId: "project",
+ assets: [createAsset(name)],
+ folders,
+ assetsDirectory: directory,
+ }).openSnapshot();
+
+ await rm(linkedFile);
+ await symlink(second, linkedFile);
+
+ await expect(snapshot.isCurrent()).resolves.toBe(false);
+ });
+});
diff --git a/packages/cli/src/filesystem-content-source.ts b/packages/cli/src/filesystem-content-source.ts
new file mode 100644
index 0000000000..efd1b343a9
--- /dev/null
+++ b/packages/cli/src/filesystem-content-source.ts
@@ -0,0 +1,306 @@
+import { open, realpath, stat, type FileHandle } from "node:fs/promises";
+import { isAbsolute, relative, resolve, sep } from "node:path";
+import {
+ computeCanonicalAssetRevision,
+ createCanonicalAssetFileEntry,
+ createContentSourceFile,
+ decodeUtf8,
+ fullCanonicalAssetMetadataRequirements,
+ normalizeAssetFileDocument,
+ prepareCanonicalContentMetadata,
+ type ContentSource,
+} from "@webstudio-is/content-engine/compiler";
+import {
+ isContentDocumentCandidate,
+ prepareContentCompilerEntries,
+ requiresStructuredProperties,
+ type ContentCompilationPlan,
+} from "@webstudio-is/content-engine";
+import {
+ createAssetFolderHierarchy,
+ formatAssetName,
+ getFileNameParts,
+ getMimeTypeByFilename,
+ type Asset,
+ type AssetFolders,
+} from "@webstudio-is/sdk";
+import { getLocalAssetPath, LOCAL_ASSETS_DIR } from "./asset-files";
+
+type FileIdentity = {
+ device: bigint;
+ inode: bigint;
+ size: bigint;
+ modifiedAt: bigint;
+ changedAt: bigint;
+};
+
+const toFileIdentity = (metadata: {
+ dev: bigint;
+ ino: bigint;
+ size: bigint;
+ mtimeNs: bigint;
+ ctimeNs: bigint;
+}): FileIdentity => ({
+ device: metadata.dev,
+ inode: metadata.ino,
+ size: metadata.size,
+ modifiedAt: metadata.mtimeNs,
+ changedAt: metadata.ctimeNs,
+});
+
+const getFileIdentity = async (path: string): Promise<FileIdentity> => {
+ const metadata = await stat(path, { bigint: true });
+ if (metadata.isFile() === false) {
+ throw new Error(`Content source entry is not a file: ${path}`);
+ }
+ return toFileIdentity(metadata);
+};
+
+const serializeFileIdentity = (identity: FileIdentity) =>
+ [
+ identity.device,
+ identity.inode,
+ identity.size,
+ identity.modifiedAt,
+ identity.changedAt,
+ ].join(":");
+
+const isSameFileIdentity = (left: FileIdentity, right: FileIdentity) =>
+ left.device === right.device &&
+ left.inode === right.inode &&
+ left.size === right.size &&
+ left.modifiedAt === right.modifiedAt &&
+ left.changedAt === right.changedAt;
+
+const resolveContentFilePath = async ({
+ assetsDirectoryPath,
+ filePath,
+}: {
+ assetsDirectoryPath: string;
+ filePath: string;
+}) => {
+ const path = await realpath(filePath);
+ const relativePath = relative(assetsDirectoryPath, path);
+ if (
+ relativePath === "" ||
+ relativePath === ".." ||
+ relativePath.startsWith(`..${sep}`) ||
+ isAbsolute(relativePath)
+ ) {
+ throw new Error("Content source file is outside the assets directory");
+ }
+ return path;
+};
+
+const readFromHandle = async ({
+ handle,
+ maximumBytes,
+}: {
+ handle: FileHandle;
+ maximumBytes: number;
+}) => {
+ const bytes = new Uint8Array(maximumBytes);
+ let offset = 0;
+ while (offset < maximumBytes) {
+ const { bytesRead } = await handle.read(
+ bytes,
+ offset,
+ maximumBytes - offset,
+ offset
+ );
+ if (bytesRead === 0) {
+ break;
+ }
+ offset += bytesRead;
+ }
+ return bytes.subarray(0, offset);
+};
+
+const readSnapshotFile = async ({
+ path,
+ identity,
+ maximumBytes,
+}: {
+ path: string;
+ identity: FileIdentity;
+ maximumBytes: number;
+}) => {
+ const handle = await open(path, "r");
+ try {
+ const before = await handle.stat({ bigint: true });
+ const beforeIdentity = toFileIdentity(before);
+ if (isSameFileIdentity(identity, beforeIdentity) === false) {
+ throw new Error("Content source file changed before it could be read");
+ }
+ const bytes = await readFromHandle({ handle, maximumBytes });
+ const after = await handle.stat({ bigint: true });
+ const afterIdentity = toFileIdentity(after);
+ if (isSameFileIdentity(identity, afterIdentity) === false) {
+ throw new Error("Content source file changed while it was being read");
+ }
+ return bytes;
+ } finally {
+ await handle.close();
+ }
+};
+
+export const createFileSystemContentSource = ({
+ projectId,
+ assets,
+ folders,
+ assetsDirectory = LOCAL_ASSETS_DIR,
+}: {
+ projectId: string;
+ assets: readonly Asset[];
+ folders: AssetFolders;
+ assetsDirectory?: string;
+}): ContentSource => ({
+ openSnapshot: async () => {
+ const hierarchy = createAssetFolderHierarchy(folders);
+ const requestedAssetsDirectoryPath = resolve(assetsDirectory);
+ const assetsDirectoryPath =
+ assets.length === 0
+ ? requestedAssetsDirectoryPath
+ : await realpath(requestedAssetsDirectoryPath);
+ const captured = await Promise.all(
+ assets.map(async (asset) => {
+ const sourcePath = getLocalAssetPath(asset.name, assetsDirectory);
+ const filePath = await resolveContentFilePath({
+ assetsDirectoryPath,
+ filePath: sourcePath,
+ });
+ const identity = await getFileIdentity(filePath);
+ const revision = `fs:${serializeFileIdentity(identity)}`;
+ const name = formatAssetName(asset);
+ const extension = getFileNameParts(asset.name).extension.toLowerCase();
+ const folderId = hierarchy.resolveFolderId(asset.folderId);
+ const folderNames = hierarchy
+ .getPath(folderId)
+ .map((folder) => folder.name);
+ const entry = createCanonicalAssetFileEntry({
+ projectId,
+ metadataRequirements: {
+ structuredProperties: false,
+ excerpt: false,
+ },
+ document: normalizeAssetFileDocument({
+ asset: {
+ id: asset.id,
+ name,
+ ...(asset.description === null
+ ? {}
+ : { description: asset.description }),
+ ...(extension === "" ? {} : { extension }),
+ ...(folderId === undefined ? {} : { folderId, folderNames }),
+ mimeType: getMimeTypeByFilename(asset.name),
+ size: Number(identity.size),
+ createdAt: asset.createdAt,
+ revision,
+ contentRef: asset.name,
+ },
+ properties: {},
+ }),
+ });
+ return { entry, sourcePath, filePath, identity };
+ })
+ );
+ const revision = await computeCanonicalAssetRevision(
+ captured.map(({ entry }) => entry)
+ );
+ const capturedById = new Map(
+ captured.map((item) => [item.entry.assetId, item])
+ );
+
+ return {
+ revision,
+ files: captured.map(({ entry }) => createContentSourceFile(entry)),
+ loadEntries: async (
+ plan?: ContentCompilationPlan,
+ options?: { maximumContentBytes: number }
+ ) => {
+ const candidates =
+ plan === undefined
+ ? captured
+ : captured.filter(({ entry: { document } }) =>
+ isContentDocumentCandidate({
+ document,
+ plan,
+ available: "base",
+ })
+ );
+ const requirements =
+ plan === undefined
+ ? fullCanonicalAssetMetadataRequirements
+ : {
+ structuredProperties: requiresStructuredProperties(plan),
+ excerpt: plan.excerpt,
+ };
+ const prepared = await Promise.all(
+ candidates.map(({ entry, filePath, identity }) =>
+ requirements.structuredProperties === false &&
+ requirements.excerpt === false
+ ? entry
+ : prepareCanonicalContentMetadata({
+ base: entry,
+ requirements,
+ readBytes: (maximumBytes) =>
+ readSnapshotFile({
+ path: filePath,
+ identity,
+ maximumBytes,
+ }),
+ })
+ )
+ );
+ return await prepareContentCompilerEntries({
+ entries: prepared,
+ plan,
+ loadContent: async (entry) => {
+ const capturedFile = capturedById.get(entry.assetId);
+ if (capturedFile === undefined) {
+ throw new Error("Content source snapshot is incomplete");
+ }
+ const bytes = await readSnapshotFile({
+ path: capturedFile.filePath,
+ identity: capturedFile.identity,
+ maximumBytes: entry.document.size,
+ });
+ if (bytes.byteLength !== entry.document.size) {
+ throw new Error("Content source file size changed");
+ }
+ try {
+ return decodeUtf8(bytes);
+ } catch {
+ throw new Error(
+ `Selected content source file is not valid UTF-8: ${entry.document.path}`
+ );
+ }
+ },
+ maximumContentBytes: options?.maximumContentBytes,
+ });
+ },
+ isCurrent: async () => {
+ try {
+ if (
+ assets.length > 0 &&
+ (await realpath(requestedAssetsDirectoryPath)) !==
+ assetsDirectoryPath
+ ) {
+ return false;
+ }
+ return (
+ await Promise.all(
+ captured.map(
+ async ({ sourcePath, filePath, identity }) =>
+ (await realpath(sourcePath)) === filePath &&
+ isSameFileIdentity(identity, await getFileIdentity(filePath))
+ )
+ )
+ ).every(Boolean);
+ } catch {
+ return false;
+ }
+ },
+ };
+ },
+});
diff --git a/packages/cli/src/framework-vike-ssg.ts b/packages/cli/src/framework-vike-ssg.ts
index 33dcc55c56..610d29c957 100644
--- a/packages/cli/src/framework-vike-ssg.ts
+++ b/packages/cli/src/framework-vike-ssg.ts
@@ -1,6 +1,6 @@
import { join } from "node:path";
import { readFile } from "node:fs/promises";
-import { isPathnamePattern } from "@webstudio-is/sdk";
+import { isPathnamePattern, matchPathnameParams } from "@webstudio-is/sdk";
import {
baseComponentImportSource,
createFrameworkComponentRegistry,
@@ -16,7 +16,16 @@ const generateVikeRoute = (pagePath: string) => {
if (pagePath === "/") {
return "index";
}
- return pagePath;
+ let route = pagePath;
+ const matches = [...matchPathnameParams(pagePath)].reverse();
+ for (const match of matches) {
+ const name = match.groups?.name;
+ if (name === undefined || match.index === undefined) {
+ continue;
+ }
+ route = `${route.slice(0, match.index)}@${name}${route.slice(match.index + match[0].length)}`;
+ }
+ return route;
};
export const createFramework = async (
@@ -49,25 +58,37 @@ export const createFramework = async (
select: `${baseComponentImportSource}:Select`,
a: `${baseComponentImportSource}:Link`,
},
- html: ({ pagePath }: { pagePath: string }) => {
- // ignore dynamic pages in static export
- if (isPathnamePattern(pagePath)) {
- return [];
+ html: ({ pagePath, prerenderPaths = [] }) => {
+ const dynamic = isPathnamePattern(pagePath);
+ if (dynamic && prerenderPaths.length === 0) {
+ throw new Error(
+ `Dynamic SSG page ${JSON.stringify(pagePath)} has no enumerable Assets query paths`
+ );
}
- return [
+ const route = generateVikeRoute(pagePath);
+ const entries = [
{
- file: join("pages", generateVikeRoute(pagePath), "+Page.tsx"),
+ file: join("pages", route, "+Page.tsx"),
template: htmlPageTemplate,
},
{
- file: join("pages", generateVikeRoute(pagePath), "+Head.tsx"),
+ file: join("pages", route, "+Head.tsx"),
template: htmlHeadTemplate,
},
{
- file: join("pages", generateVikeRoute(pagePath), "+data.ts"),
+ file: join("pages", route, "+data.ts"),
template: htmlDataTemplate,
},
];
+ if (dynamic) {
+ entries.push({
+ file: join("pages", route, "+onBeforePrerenderStart.ts"),
+ template: `export const onBeforePrerenderStart = () => ${JSON.stringify(
+ prerenderPaths
+ )};\n`,
+ });
+ }
+ return entries;
},
xml: () => [],
text: () => [],
diff --git a/packages/cli/src/framework.ts b/packages/cli/src/framework.ts
index e23f96ff9e..281439dabb 100644
--- a/packages/cli/src/framework.ts
+++ b/packages/cli/src/framework.ts
@@ -25,7 +25,10 @@ export type Framework = {
components: Record<string, string>;
// instance.tag: "importSource:importSpecifier"
tags: Record<string, string>;
- html: (params: { pagePath: string }) => FrameworkTemplateEntry[];
+ html: (params: {
+ pagePath: string;
+ prerenderPaths?: readonly string[];
+ }) => FrameworkTemplateEntry[];
xml: (params: { pagePath: string }) => FrameworkTemplateEntry[];
text: (params: { pagePath: string }) => FrameworkTemplateEntry[];
defaultSitemap: () => FrameworkTemplateEntry[];
diff --git a/packages/cli/src/prebuild.test.ts b/packages/cli/src/prebuild.test.ts
index b0d32f1ccb..d4b9350057 100644
--- a/packages/cli/src/prebuild.test.ts
+++ b/packages/cli/src/prebuild.test.ts
@@ -13,17 +13,67 @@ import {
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { tmpdir } from "node:os";
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
import { bundleVersion } from "@webstudio-is/protocol";
import type { Asset } from "@webstudio-is/sdk";
-import { generateRedirectsModule, prebuild } from "./prebuild";
+import type { AssetFileDocument } from "@webstudio-is/content-engine";
+import {
+ createAssetIndex,
+ createCanonicalAssetFileEntry,
+} from "@webstudio-is/content-engine/compiler";
+import { createPublishedAssetResourceFetch } from "@webstudio-is/content-engine/runtime";
+import {
+ createStructuredAssetQueryResourceBody,
+ type Resource,
+} from "@webstudio-is/sdk";
+import {
+ generateRedirectsModule,
+ getAssetResourcePrerenderPaths,
+ materializeAssetIndex,
+ prebuild,
+} from "./prebuild";
+
+const createSsgAssetResourceFetch = (options: {
+ deploymentId: string;
+ artifact: Parameters<typeof createPublishedAssetResourceFetch>[0]["artifact"];
+ runtimeAssets: Parameters<
+ typeof createPublishedAssetResourceFetch
+ >[0]["runtimeAssets"];
+}) =>
+ createPublishedAssetResourceFetch({
+ ...options,
+ baseUrl: "https://webstudio.local",
+ });
const originalCwd = process.cwd();
+const execFileAsync = promisify(execFile);
const originalFetch = globalThis.fetch;
let tempDir: string;
let consoleInfo: ReturnType<typeof vi.spyOn>;
const rootFolderId = "root";
const elementComponent = "ws:element";
const slowPrebuildTestTimeout = 15_000;
+
+const runGeneratedCommand = async (
+ command: "react-router" | "vite" | "vike",
+ args: string[]
+) => {
+ const env = { ...process.env };
+ for (const name of Object.keys(env)) {
+ if (name.startsWith("VITEST")) {
+ delete env[name];
+ }
+ }
+ env.NODE_ENV = "production";
+ env.NODE_OPTIONS = "--conditions=webstudio";
+ env.WEBSTUDIO_LOCAL_CLI_BOOTSTRAPPED = "1";
+ await execFileAsync(join(originalCwd, `node_modules/.bin/${command}`), args, {
+ cwd: tempDir,
+ env,
+ });
+};
+
type Redirects = Array<{ old: string; new: string; status?: "301" | "302" }>;
type GeneratedRouteModule = {
loader: (args: { request: Request }) => Response | Promise<Response>;
@@ -290,7 +340,316 @@ describe("generateRedirectsModule", () => {
});
});
+const indexedDocument: AssetFileDocument = {
+ _id: "post-1",
+ _type: "asset.file",
+ name: "post.md",
+ path: "post.md",
+ key: "post",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 10,
+ revision: "post-revision",
+ contentRef: "post.md",
+ properties: { slug: "post", title: "Prerendered post" },
+};
+
+const createAssetForIndexedDocument = (document: AssetFileDocument): Asset => ({
+ id: document._id,
+ projectId: "project-1",
+ name: document.contentRef,
+ type: "file",
+ format: document.extension,
+ size: document.size,
+ meta: {},
+ createdAt: "2026-01-01T00:00:00.000Z",
+});
+
+const createTestAssetIndex = (
+ documents: AssetFileDocument | AssetFileDocument[] = indexedDocument,
+ contents: Record<string, string> = {}
+) =>
+ createAssetIndex({
+ projectId: "project-1",
+ entries: (Array.isArray(documents) ? documents : [documents]).map(
+ (document) => ({
+ ...createCanonicalAssetFileEntry({
+ projectId: "project-1",
+ document,
+ }),
+ content: contents[document.contentRef],
+ })
+ ),
+ });
+
+const createQueryResource = (content: "none" | "full" = "none"): Resource => ({
+ id: "posts",
+ name: "Posts",
+ control: "system",
+ method: "post",
+ url: '"/$resources/assets"',
+ headers: [],
+ body: createStructuredAssetQueryResourceBody({
+ where: { all: [] },
+ sort: [],
+ limit: "100",
+ offset: "0",
+ output: { mode: "all", includeMetadata: true },
+ content: { mode: content },
+ }),
+});
+
+test("embeds one shared content database in a server module", async () => {
+ const index = await createTestAssetIndex();
+ await mkdir("public", { recursive: true });
+ await mkdir("app/__generated__", { recursive: true });
+
+ await materializeAssetIndex({
+ index,
+ runtimeAssets: { "post-1": { url: "/assets/post.md" } },
+ includeDocumentRuntimeAssets: false,
+ generatedDirectory: "app/__generated__",
+ deploymentId: "build-1",
+ });
+
+ await expect(stat("public/assets/db")).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+ const manifestModule = await readFile(
+ "app/__generated__/$resources.asset-query-manifest.ts",
+ "utf8"
+ );
+ expect(manifestModule).toContain('assetQueryDeploymentId = "build-1"');
+ expect(manifestModule).toContain('"documents"');
+ expect(manifestModule).toContain('"properties"');
+ const runtimeModule = await readFile(
+ "app/__generated__/$resources.asset-query-runtime.ts",
+ "utf8"
+ );
+ expect(runtimeModule).toContain('from "./$resources.asset-query-vendor.js"');
+ expect(runtimeModule).toContain("assetQueryDatabase");
+ await expect(
+ stat("app/__generated__/$resources.asset-query-vendor.js")
+ ).resolves.toBeDefined();
+});
+
+test("rejects a corrupted content database before generating runtime files", async () => {
+ const index = await createTestAssetIndex();
+ const corrupted = {
+ ...index,
+ documents: index.documents.map((document) => ({
+ ...document,
+ name: `${document.name}-corrupted`,
+ })),
+ };
+ await mkdir("app/__generated__", { recursive: true });
+
+ await expect(
+ materializeAssetIndex({
+ index: corrupted,
+ runtimeAssets: { "post-1": { url: "/assets/post.md" } },
+ includeDocumentRuntimeAssets: false,
+ generatedDirectory: "app/__generated__",
+ deploymentId: "build-1",
+ })
+ ).rejects.toThrow("Content artifact checksum is invalid");
+ await expect(
+ stat("app/__generated__/$resources.asset-query-vendor.js")
+ ).rejects.toMatchObject({ code: "ENOENT" });
+});
+
+test("does not require URLs for documents that do not use runtime asset fields", async () => {
+ const index = await createTestAssetIndex();
+ await mkdir("app/__generated__", { recursive: true });
+
+ await materializeAssetIndex({
+ index,
+ runtimeAssets: {},
+ includeDocumentRuntimeAssets: false,
+ generatedDirectory: "app/__generated__",
+ deploymentId: "build-1",
+ });
+ const runtimeModule = await readFile(
+ "app/__generated__/$resources.asset-query-runtime.ts",
+ "utf8"
+ );
+ expect(runtimeModule).toContain("const runtimeAssets = {};");
+});
+
+test("embeds document runtime data when a query uses runtime fields", async () => {
+ const index = await createTestAssetIndex();
+ await mkdir("app/__generated__", { recursive: true });
+
+ await materializeAssetIndex({
+ index,
+ runtimeAssets: { "post-1": { url: "/assets/post.md" } },
+ includeDocumentRuntimeAssets: true,
+ generatedDirectory: "app/__generated__",
+ deploymentId: "build-1",
+ });
+
+ await expect(
+ readFile("app/__generated__/$resources.asset-query-runtime.ts", "utf8")
+ ).resolves.toContain('"post-1"');
+});
+
+test("rejects missing document runtime data when a query uses runtime fields", async () => {
+ const index = await createTestAssetIndex();
+ await mkdir("app/__generated__", { recursive: true });
+
+ await expect(
+ materializeAssetIndex({
+ index,
+ runtimeAssets: {},
+ includeDocumentRuntimeAssets: true,
+ generatedDirectory: "app/__generated__",
+ deploymentId: "build-1",
+ })
+ ).rejects.toThrow("Published asset runtime data is unavailable for post-1");
+});
+
+test("rejects a content database without a referenced published asset", async () => {
+ const index = await createAssetIndex({
+ projectId: "project-1",
+ entries: [
+ {
+ ...createCanonicalAssetFileEntry({
+ projectId: "project-1",
+ document: indexedDocument,
+ }),
+ content: "# Post",
+ },
+ ],
+ assetReferences: {
+ "post.md": [{ start: 0, end: 1, assetId: "image-1" }],
+ },
+ });
+ await mkdir("app/__generated__", { recursive: true });
+
+ await expect(
+ materializeAssetIndex({
+ index,
+ runtimeAssets: { "post-1": { url: "/assets/post.md" } },
+ includeDocumentRuntimeAssets: false,
+ generatedDirectory: "app/__generated__",
+ deploymentId: "build-1",
+ })
+ ).rejects.toThrow(
+ "Published referenced asset URL is unavailable for image-1"
+ );
+});
+
+test("executes and hydrates an asset query from an embedded SSG database", async () => {
+ const source = "# Prerendered post\n";
+ const index = await createTestAssetIndex(
+ {
+ ...indexedDocument,
+ size: new TextEncoder().encode(source).byteLength,
+ },
+ { "post.md": source }
+ );
+ const runtimeFetch = createSsgAssetResourceFetch({
+ deploymentId: "build-1",
+ artifact: index,
+ runtimeAssets: { "post-1": { url: "/assets/post.md" } },
+ });
+
+ const response = await runtimeFetch("/$resources/assets", {
+ method: "POST",
+ body: JSON.stringify({
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "post",
+ },
+ ],
+ },
+ limit: 1,
+ output: { mode: "all", includeMetadata: true },
+ content: { mode: "full" },
+ },
+ }),
+ });
+
+ expect({
+ status: response?.status,
+ body: await response?.json(),
+ }).toMatchObject({
+ status: 200,
+ body: {
+ items: [
+ {
+ id: "post-1",
+ properties: { title: "Prerendered post" },
+ content: { text: source },
+ },
+ ],
+ },
+ });
+});
+
+test("hydrates encoded filenames from an embedded SSG database", async () => {
+ const contentRef = "post!-你好.md";
+ const source = "# Encoded filename\n";
+ const index = await createTestAssetIndex(
+ {
+ ...indexedDocument,
+ contentRef,
+ size: new TextEncoder().encode(source).byteLength,
+ },
+ { [contentRef]: source }
+ );
+ const runtimeFetch = createSsgAssetResourceFetch({
+ deploymentId: "build-encoded",
+ artifact: index,
+ runtimeAssets: { "post-1": { url: `/assets/${contentRef}` } },
+ });
+
+ const response = await runtimeFetch("/$resources/assets", {
+ method: "POST",
+ body: JSON.stringify({
+ query: {
+ where: { all: [{ field: ["id"], operator: "eq", value: "post-1" }] },
+ limit: 1,
+ content: { mode: "full" },
+ },
+ }),
+ });
+
+ expect(response?.status).toBe(200);
+ await expect(response?.json()).resolves.toMatchObject({
+ items: [{ content: { text: source } }],
+ });
+});
+
describe("prebuild", () => {
+ test("emits the identity marker only for local previews", async () => {
+ await prebuild({
+ assets: false,
+ template: ["react-router"],
+ previewIdentity: true,
+ });
+
+ await expect(
+ readFile("public/__webstudio/preview.json", "utf8")
+ ).resolves.toBe(JSON.stringify({ projectId: "project-id", version: 1 }));
+ });
+
+ test("does not add the local preview marker to deployable builds", async () => {
+ await prebuild({
+ assets: false,
+ template: ["react-router"],
+ preserveRouteTemplates: true,
+ });
+
+ await expect(
+ readFile("public/__webstudio/preview.json", "utf8")
+ ).rejects.toMatchObject({ code: "ENOENT" });
+ });
+
test("incrementally replaces only changed generated files", async () => {
const siteData = createSiteData({
pages: [
@@ -546,9 +905,15 @@ describe("prebuild", () => {
])
);
- await expect(
- readFile("app/__generated__/$resources.assets.ts", "utf8")
- ).resolves.toContain("image.png");
+ const assetsModule = await readFile(
+ "app/__generated__/$resources.assets.ts",
+ "utf8"
+ );
+ expect(assetsModule).toContain("export const assets");
+ expect(assetsModule).toContain('"asset-image"');
+ expect(assetsModule).toContain("image.png");
+ expect(assetsModule).not.toContain("assets/query");
+ expect(assetsModule).not.toContain("properties");
await expect(
readFile("app/__generated__/$resources.sitemap.xml.ts", "utf8")
).resolves.toContain('"path": "/"');
@@ -614,8 +979,17 @@ describe("prebuild", () => {
"ENOENT"
);
const packageJson = JSON.parse(await readFile("package.json", "utf8"));
+ expect(packageJson.dependencies).not.toHaveProperty(
+ "@webstudio-is/asset-resource"
+ );
+ expect(packageJson.dependencies).not.toHaveProperty(
+ "@webstudio-is/content-engine"
+ );
expect(packageJson.dependencies).not.toHaveProperty("h3");
expect(packageJson.dependencies).not.toHaveProperty("ipx");
+ expect(packageJson.dependencies).not.toHaveProperty(
+ "@webstudio-is/content-engine"
+ );
});
test("generates homepage, leaf, nested, dynamic, and 404 React Router routes", async () => {
@@ -675,9 +1049,199 @@ describe("prebuild", () => {
await expectGeneratedRedirectFallback("app/routes/$.tsx");
});
+ test("generates one dynamic SSR blog route with an embedded content database", async () => {
+ const source = "# Published post\n";
+ const index = await createTestAssetIndex(
+ {
+ ...indexedDocument,
+ path: "blog/post.md",
+ size: new TextEncoder().encode(source).byteLength,
+ properties: { slug: "post" },
+ },
+ { "post.md": source }
+ );
+ const siteData = {
+ ...createSiteData({
+ pages: [
+ {
+ id: "home",
+ name: "Home",
+ title: "Home",
+ path: "",
+ rootInstanceId: "root",
+ meta: {},
+ },
+ {
+ id: "post",
+ name: "Post",
+ title: "Post",
+ path: "/blog/:slug",
+ rootInstanceId: "root",
+ meta: {},
+ },
+ ],
+ }),
+ assets: ["post.md", "draft.md"].map((name) => ({
+ id: name,
+ projectId: "project-id",
+ name,
+ type: "file" as const,
+ format: "md",
+ size: source.length,
+ meta: {},
+ description: "",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ })),
+ assetIndex: index,
+ };
+ await writeSiteData(
+ siteData as unknown as ReturnType<typeof createSiteData>
+ );
+ await mkdir(".webstudio/assets", { recursive: true });
+ await writeFile(".webstudio/assets/post.md", source, "utf8");
+ await writeFile(".webstudio/assets/draft.md", "draft secret", "utf8");
+
+ await prebuild({ assets: true, template: ["react-router"] });
+
+ await expect(
+ readFile("app/routes/[blog].$slug._index.tsx", "utf8")
+ ).resolves.toContain("createGeneratedAssetResourceFetch");
+ await expect(readFile("public/assets/post.md", "utf8")).resolves.toBe(
+ source
+ );
+ await expect(readFile("public/assets/draft.md", "utf8")).resolves.toBe(
+ "draft secret"
+ );
+ const manifest = await readFile(
+ "app/__generated__/$resources.asset-query-manifest.ts",
+ "utf8"
+ );
+ expect(manifest).toContain("Published post");
+ expect(manifest).not.toContain("draft secret");
+ await expect(
+ readFile("app/asset-resource-fetch.ts", "utf8")
+ ).rejects.toThrow("ENOENT");
+ expect(
+ (await getFilePaths("app/routes")).filter((path) =>
+ path.includes("$slug")
+ )
+ ).toHaveLength(1);
+ await symlink(join(originalCwd, "node_modules"), "node_modules", "dir");
+ await runGeneratedCommand("react-router", ["build"]);
+ const serverBundle = (
+ await Promise.all(
+ (
+ await getFilePaths("build/server")
+ )
+ .filter((path) => path.endsWith(".js"))
+ .map((path) => readFile(path, "utf8"))
+ )
+ ).join("\n");
+ expect(serverBundle).toContain("Published post");
+ expect(serverBundle).not.toContain("draft secret");
+ expect(serverBundle).toContain("post-revision");
+ const clientBundle = (
+ await Promise.all(
+ (
+ await getFilePaths("build/client")
+ )
+ .filter((path) => path.endsWith(".js"))
+ .map((path) => readFile(path, "utf8"))
+ )
+ ).join("\n");
+ expect(clientBundle).not.toContain("Published post");
+ expect(clientBundle).not.toContain("post-revision");
+ }, 30_000);
+
+ test("embeds the deployment database when asset downloads are disabled", async () => {
+ const index = await createTestAssetIndex();
+ const siteData = {
+ ...createSiteData({
+ assets: [
+ createAssetForIndexedDocument(indexedDocument),
+ createAssetForIndexedDocument({
+ ...indexedDocument,
+ _id: "unrelated-asset",
+ name: "unrelated.md",
+ path: "unrelated.md",
+ key: "unrelated",
+ contentRef: "unrelated.md",
+ }),
+ ],
+ }),
+ assetIndex: index,
+ };
+ siteData.build.resources = [["posts", createQueryResource()]] as never;
+ siteData.build.dataSources = [
+ [
+ "posts-data",
+ {
+ id: "posts-data",
+ type: "resource",
+ name: "posts",
+ resourceId: "posts",
+ scopeInstanceId: "root",
+ },
+ ],
+ ] as never;
+ await writeSiteData(
+ siteData as unknown as ReturnType<typeof createSiteData>
+ );
+
+ await prebuild({
+ assets: false,
+ template: ["react-router"],
+ preserveRouteTemplates: true,
+ });
+
+ await expect(
+ readFile("app/__generated__/$resources.asset-query-manifest.ts", "utf8")
+ ).resolves.toContain(index.integrity.checksum);
+ const runtimeModule = await readFile(
+ "app/__generated__/$resources.asset-query-runtime.ts",
+ "utf8"
+ );
+ expect(runtimeModule).not.toContain('"post-1"');
+ expect(runtimeModule).not.toContain("unrelated-asset");
+ expect(runtimeModule).not.toContain('$resources.assets"');
+ const packageJson = JSON.parse(await readFile("package.json", "utf8"));
+ expect(packageJson.dependencies).not.toHaveProperty(
+ "@webstudio-is/content-engine"
+ );
+ await expect(
+ stat("app/__generated__/$resources.asset-query-vendor.js")
+ ).resolves.toBeDefined();
+
+ await writeSiteData();
+ await prebuild({
+ assets: false,
+ incremental: true,
+ template: ["react-router"],
+ });
+ const withoutQuery = JSON.parse(await readFile("package.json", "utf8"));
+ expect(withoutQuery.dependencies).not.toHaveProperty(
+ "@webstudio-is/content-engine"
+ );
+ await expect(
+ stat("app/__generated__/$resources.asset-query-vendor.js")
+ ).rejects.toThrow("ENOENT");
+ });
+
test("uses pass-through images in the base react-router template", async () => {
await prebuild({ assets: false, template: ["react-router"] });
+ const route = await readFile("app/routes/_index.tsx", "utf8");
+ expect(route).toContain("$resources.asset-query-runtime");
+ expect(route).not.toContain("@webstudio-is/content-engine");
+ const assetQueryRuntime = await readFile(
+ "app/__generated__/$resources.asset-query-runtime.ts",
+ "utf8"
+ );
+ expect(assetQueryRuntime).not.toContain("@webstudio-is/content-engine");
+ expect(assetQueryRuntime).toContain("=> fallback");
+ await expect(
+ readFile("app/__generated__/$resources.asset-query-manifest.ts", "utf8")
+ ).resolves.not.toContain("@webstudio-is/content-engine");
await expect(readFile("app/constants.mjs", "utf8")).resolves.toContain(
"return props.src"
);
@@ -689,6 +1253,47 @@ describe("prebuild", () => {
expect(packageJson.dependencies).not.toHaveProperty("ipx");
});
+ test("does not modify a project-owned content-engine dependency", async () => {
+ await prebuild({
+ assets: false,
+ template: ["react-router"],
+ preserveRouteTemplates: true,
+ });
+ const packageJson = JSON.parse(await readFile("package.json", "utf8"));
+ packageJson.dependencies["@webstudio-is/content-engine"] = "custom-version";
+ await writeFile("package.json", JSON.stringify(packageJson), "utf8");
+
+ await prebuild({
+ assets: false,
+ incremental: true,
+ template: ["react-router"],
+ });
+
+ const preserved = JSON.parse(await readFile("package.json", "utf8"));
+ expect(preserved.dependencies).toHaveProperty(
+ "@webstudio-is/content-engine",
+ "custom-version"
+ );
+ });
+
+ test("omits the asset query runtime from dynamic app bundles without asset queries", async () => {
+ await prebuild({ assets: false, template: ["react-router"] });
+ await symlink(join(originalCwd, "node_modules"), "node_modules", "dir");
+
+ await runGeneratedCommand("react-router", ["build"]);
+
+ const serverBundle = (
+ await Promise.all(
+ (
+ await getFilePaths("build/server")
+ )
+ .filter((path) => path.endsWith(".js"))
+ .map((path) => readFile(path, "utf8"))
+ )
+ ).join("\n");
+ expect(serverBundle).not.toContain("@webstudio-is/content-engine");
+ }, 30_000);
+
test("keeps IPX image optimization in the react-router Docker overlay", async () => {
await prebuild({
assets: false,
@@ -716,7 +1321,7 @@ describe("prebuild", () => {
);
});
- test("selects ssg templates and skips dynamic routes", async () => {
+ test("selects ssg templates", async () => {
await writeSiteData(
createSiteData({
pages: [
@@ -728,14 +1333,6 @@ describe("prebuild", () => {
rootInstanceId: "root",
meta: {},
},
- {
- id: "post",
- name: "Post",
- title: "Post",
- path: "/blog/:slug",
- rootInstanceId: "root",
- meta: {},
- },
],
})
);
@@ -751,14 +1348,600 @@ describe("prebuild", () => {
await expect(readFile("pages/index/+data.ts", "utf8")).resolves.toContain(
"../app/__generated__/_index.server"
);
+ await expect(readFile("pages/index/+data.ts", "utf8")).resolves.toContain(
+ "createSsgAssetResourceFetch"
+ );
await expect(
- readFile("pages/blog/:slug/+Page.tsx", "utf8")
- ).rejects.toThrow("ENOENT");
+ readFile("app/asset-resource-fetch.ts", "utf8")
+ ).resolves.not.toContain("@webstudio-is/content-engine");
+ const packageJson = JSON.parse(await readFile("package.json", "utf8"));
+ expect(packageJson.dependencies).not.toHaveProperty(
+ "@webstudio-is/content-engine"
+ );
+ expect(packageJson.scripts.build).not.toContain(
+ "cleanup-derived-assets.mjs"
+ );
+ });
+
+ test("prerenders dynamic SSG paths from parameterized Assets resources", async () => {
+ const documents = [
+ {
+ ...indexedDocument,
+ path: "blog/post.md",
+ size: 1,
+ properties: { slug: "hello-world", title: "Hello", draft: false },
+ },
+ {
+ ...indexedDocument,
+ _id: "draft-post",
+ name: "draft.md",
+ path: "blog/draft.md",
+ key: "draft",
+ size: 1,
+ revision: "draft-revision",
+ contentRef: "draft.md",
+ properties: { slug: "draft-post", title: "Draft", draft: true },
+ },
+ ];
+ const index = await createTestAssetIndex(documents);
+ const siteData = {
+ ...createSiteData({
+ assets: documents.map(createAssetForIndexedDocument),
+ pages: [
+ {
+ id: "home",
+ name: "Home",
+ title: "Home",
+ path: "",
+ rootInstanceId: "home-root",
+ meta: {},
+ },
+ {
+ id: "post",
+ name: "Post",
+ title: "Post",
+ path: "/blog/:slug",
+ rootInstanceId: "post-root",
+ meta: {},
+ },
+ ],
+ instances: [
+ ["home-root", { id: "home-root", component: "Box", children: [] }],
+ ["post-root", { id: "post-root", component: "Box", children: [] }],
+ ],
+ }),
+ assetIndex: index,
+ };
+ siteData.build.resources = [
+ [
+ "post",
+ {
+ id: "post",
+ name: "Post",
+ control: "system",
+ method: "post",
+ url: '"/$resources/assets"',
+ headers: [],
+ body: createStructuredAssetQueryResourceBody({
+ where: {
+ all: [
+ {
+ field: ["properties", "draft"],
+ operator: "ne",
+ value: "true",
+ },
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "system.params.slug",
+ },
+ ],
+ },
+ sort: [],
+ limit: "1",
+ offset: "0",
+ output: { mode: "all", includeMetadata: true },
+ content: { mode: "none" },
+ }),
+ },
+ ],
+ ] as never;
+ siteData.build.dataSources = [
+ [
+ "post-data",
+ {
+ id: "post-data",
+ type: "resource",
+ name: "post",
+ resourceId: "post",
+ scopeInstanceId: "post-root",
+ },
+ ],
+ ] as never;
+ await writeSiteData(siteData);
+
+ await prebuild({ assets: false, template: ["ssg"] });
await expect(
- readFile("app/__generated__/[blog].$slug._index.tsx", "utf8")
- ).resolves.toContain("export { Page }");
+ readFile("pages/blog/@slug/+onBeforePrerenderStart.ts", "utf8")
+ ).resolves.toContain("/blog/hello-world");
+ await expect(
+ readFile("pages/blog/@slug/+onBeforePrerenderStart.ts", "utf8")
+ ).resolves.not.toContain("/blog/draft-post");
+ await expect(
+ readFile("app/__generated__/$resources.sitemap.xml.ts", "utf8")
+ ).resolves.toContain('"path": "/blog/hello-world"');
+ await expect(
+ readFile("app/__generated__/$resources.sitemap.xml.ts", "utf8")
+ ).resolves.not.toContain('"path": "/blog/draft-post"');
+ await symlink(join(originalCwd, "node_modules"), "node_modules", "dir");
+ await runGeneratedCommand("vite", ["build"]);
+ await runGeneratedCommand("vike", ["prerender"]);
+ await expect(
+ readFile("dist/client/blog/hello-world/index.html", "utf8")
+ ).resolves.toContain("<!DOCTYPE html>");
+ const staticRuntimeOutput = (
+ await Promise.all(
+ (
+ await getFilePaths("dist/client")
+ )
+ .filter((path) => path.endsWith(".js") || path.endsWith(".json"))
+ .map((path) => readFile(path, "utf8"))
+ )
+ ).join("\n");
+ expect(staticRuntimeOutput).not.toContain(index.integrity.checksum);
+ }, 30_000);
+
+ test("does not prerender dynamic Assets paths that cannot match string route params", async () => {
+ const index = await createTestAssetIndex([
+ {
+ ...indexedDocument,
+ properties: { slug: 123 },
+ },
+ {
+ ...indexedDocument,
+ _id: "boolean-slug",
+ revision: "boolean-revision",
+ properties: { slug: true },
+ },
+ ]);
+ const resource = createQueryResource();
+ resource.body = createStructuredAssetQueryResourceBody({
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "system.params.slug",
+ },
+ ],
+ },
+ sort: [],
+ limit: "1",
+ offset: "0",
+ output: { mode: "all", includeMetadata: true },
+ content: { mode: "none" },
+ });
+
+ expect(
+ getAssetResourcePrerenderPaths({
+ pagePath: "/blog/:slug",
+ resources: [["post", resource]],
+ index,
+ })
+ ).toEqual([]);
+ });
+
+ test("uses JavaScript literals when filtering prerender candidates", async () => {
+ const index = await createTestAssetIndex({
+ ...indexedDocument,
+ properties: { slug: "hello-world", status: "draft" },
+ });
+ const resource = createQueryResource();
+ resource.body = createStructuredAssetQueryResourceBody({
+ where: {
+ all: [
+ {
+ field: ["properties", "status"],
+ operator: "eq",
+ value: "'published'",
+ },
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "system.params.slug",
+ },
+ ],
+ },
+ sort: [],
+ limit: "1",
+ offset: "0",
+ output: { mode: "all", includeMetadata: true },
+ content: { mode: "none" },
+ });
+
+ expect(
+ getAssetResourcePrerenderPaths({
+ pagePath: "/blog/:slug",
+ resources: [["post", resource]],
+ index,
+ })
+ ).toEqual([]);
+ });
+
+ test("prerenders canonical and alternative asset routes from any groups", async () => {
+ const index = await createTestAssetIndex({
+ ...indexedDocument,
+ properties: {
+ slug: "hello-world",
+ id: "post-123",
+ aliases: ["original-title"],
+ draft: false,
+ },
+ });
+ const resource = createQueryResource();
+ resource.body = createStructuredAssetQueryResourceBody({
+ where: {
+ all: [
+ {
+ field: ["properties", "draft"],
+ operator: "ne",
+ value: "true",
+ },
+ {
+ any: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "system.params.identifier",
+ },
+ {
+ field: ["properties", "id"],
+ operator: "eq",
+ value: "system.params.identifier",
+ },
+ {
+ field: ["properties", "aliases"],
+ operator: "contains",
+ value: "system.params.identifier",
+ },
+ ],
+ },
+ ],
+ },
+ sort: [],
+ limit: "1",
+ offset: "0",
+ output: { mode: "all", includeMetadata: true },
+ content: { mode: "none" },
+ });
+
+ expect(
+ getAssetResourcePrerenderPaths({
+ pagePath: "/blog/:identifier",
+ resources: [["post", resource]],
+ index,
+ requireCompleteEnumeration: true,
+ })
+ ).toEqual(["/blog/hello-world", "/blog/original-title", "/blog/post-123"]);
+ });
+
+ test("prerenders multi-parameter routes from one Assets query", async () => {
+ const index = await createTestAssetIndex([
+ {
+ ...indexedDocument,
+ properties: { category: "news", slug: "hello-world" },
+ },
+ {
+ ...indexedDocument,
+ _id: "other-post",
+ revision: "other-revision",
+ properties: { category: "guides", slug: "getting-started" },
+ },
+ ]);
+ const resource = createQueryResource();
+ resource.body = createStructuredAssetQueryResourceBody({
+ where: {
+ all: [
+ {
+ field: ["properties", "category"],
+ operator: "eq",
+ value: "system.params.category",
+ },
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "system.params.slug",
+ },
+ ],
+ },
+ sort: [],
+ limit: "1",
+ offset: "0",
+ output: { mode: "all", includeMetadata: true },
+ content: { mode: "none" },
+ });
+
+ expect(
+ getAssetResourcePrerenderPaths({
+ pagePath: "/blog/:category/:slug",
+ resources: [["post", resource]],
+ index,
+ requireCompleteEnumeration: true,
+ })
+ ).toEqual(["/blog/guides/getting-started", "/blog/news/hello-world"]);
+ });
+
+ test("rejects multi-parameter SSG routes split across Assets queries", async () => {
+ const index = await createTestAssetIndex({
+ ...indexedDocument,
+ properties: { category: "news", slug: "hello-world" },
+ });
+ const createParameterResource = (parameter: "category" | "slug") => {
+ const resource = createQueryResource();
+ resource.body = createStructuredAssetQueryResourceBody({
+ where: {
+ all: [
+ {
+ field: ["properties", parameter],
+ operator: "eq",
+ value: `system.params.${parameter}`,
+ },
+ ],
+ },
+ sort: [],
+ limit: "1",
+ offset: "0",
+ output: { mode: "all", includeMetadata: true },
+ content: { mode: "none" },
+ });
+ return resource;
+ };
+
+ expect(() =>
+ getAssetResourcePrerenderPaths({
+ pagePath: "/blog/:category/:slug",
+ resources: [
+ ["category", createParameterResource("category")],
+ ["slug", createParameterResource("slug")],
+ ],
+ index,
+ requireCompleteEnumeration: true,
+ })
+ ).toThrow(
+ "Dynamic SSG route parameters must be completely enumerated by one Assets query"
+ );
+ });
+
+ test("prerenders asset routes bound with optional member expressions", async () => {
+ const index = await createTestAssetIndex({
+ ...indexedDocument,
+ properties: { slug: "hello-world" },
+ });
+ const resource = createQueryResource();
+ resource.body = createStructuredAssetQueryResourceBody({
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: 'system?.params?.["slug"]',
+ },
+ ],
+ },
+ sort: [],
+ limit: "1",
+ offset: "0",
+ output: { mode: "all", includeMetadata: true },
+ content: { mode: "none" },
+ });
+
+ expect(
+ getAssetResourcePrerenderPaths({
+ pagePath: "/blog/:slug",
+ resources: [["post", resource]],
+ index,
+ })
+ ).toEqual(["/blog/hello-world"]);
});
+ test("deduplicates collection routes matched by multiple assets", async () => {
+ const index = await createTestAssetIndex([
+ { ...indexedDocument, properties: { slug: "shared" } },
+ {
+ ...indexedDocument,
+ _id: "other-post",
+ revision: "other-revision",
+ properties: { slug: "shared" },
+ },
+ ]);
+ const resource = createQueryResource();
+ resource.body = createStructuredAssetQueryResourceBody({
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "system.params.slug",
+ },
+ ],
+ },
+ sort: [],
+ limit: "1",
+ offset: "0",
+ output: { mode: "all", includeMetadata: true },
+ content: { mode: "none" },
+ });
+
+ expect(
+ getAssetResourcePrerenderPaths({
+ pagePath: "/blog/:slug",
+ resources: [["post", resource]],
+ index,
+ })
+ ).toEqual(["/blog/shared"]);
+ });
+
+ test("rejects SSG filters whose route values cannot be completely enumerated", async () => {
+ const index = await createTestAssetIndex({
+ ...indexedDocument,
+ properties: { slug: "hello-world" },
+ });
+ const resource = createQueryResource();
+ resource.body = createStructuredAssetQueryResourceBody({
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "startsWith",
+ value: "system.params.slug",
+ },
+ ],
+ },
+ sort: [],
+ limit: "20",
+ offset: "0",
+ output: { mode: "all", includeMetadata: true },
+ content: { mode: "none" },
+ });
+
+ expect(() =>
+ getAssetResourcePrerenderPaths({
+ pagePath: "/blog/:slug",
+ resources: [["posts", resource]],
+ index,
+ requireCompleteEnumeration: true,
+ })
+ ).toThrow('route parameter "slug" cannot be completely enumerated');
+ });
+
+ test("rejects SSG route parameters unconstrained by an alternative query branch", async () => {
+ const index = await createTestAssetIndex({
+ ...indexedDocument,
+ properties: { slug: "hello-world", draft: false },
+ });
+ const resource = createQueryResource();
+ resource.body = createStructuredAssetQueryResourceBody({
+ where: {
+ any: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "system.params.slug",
+ },
+ {
+ field: ["properties", "draft"],
+ operator: "eq",
+ value: "false",
+ },
+ ],
+ },
+ sort: [],
+ limit: "20",
+ offset: "0",
+ output: { mode: "all", includeMetadata: true },
+ content: { mode: "none" },
+ });
+
+ expect(() =>
+ getAssetResourcePrerenderPaths({
+ pagePath: "/blog/:slug",
+ resources: [["posts", resource]],
+ index,
+ requireCompleteEnumeration: true,
+ })
+ ).toThrow('route parameter "slug" cannot be completely enumerated');
+ });
+
+ test("prerenders SSG pages with asset query data", async () => {
+ const document = {
+ ...indexedDocument,
+ path: "blog/post.md",
+ size: 1,
+ properties: { title: "Prerendered post" },
+ };
+ const index = await createTestAssetIndex(document);
+ const siteData = {
+ ...createSiteData({
+ assets: [createAssetForIndexedDocument(document)],
+ }),
+ assetIndex: index,
+ };
+ siteData.build.resources = [
+ [
+ "posts",
+ {
+ id: "posts",
+ name: "Posts",
+ control: "system",
+ method: "post",
+ url: '"/$resources/assets"',
+ headers: [],
+ body: createStructuredAssetQueryResourceBody({
+ where: { all: [] },
+ sort: [],
+ limit: "10",
+ offset: "0",
+ output: { mode: "all", includeMetadata: true },
+ content: { mode: "none" },
+ }),
+ },
+ ],
+ ] as never;
+ siteData.build.dataSources = [
+ [
+ "posts-data",
+ {
+ id: "posts-data",
+ type: "resource",
+ name: "posts",
+ resourceId: "posts",
+ scopeInstanceId: "root",
+ },
+ ],
+ ] as never;
+ await writeSiteData(
+ siteData as unknown as ReturnType<typeof createSiteData>
+ );
+ await prebuild({ assets: false, template: ["ssg"] });
+ await symlink(join(originalCwd, "node_modules"), "node_modules", "dir");
+ const pageModule = (await import(
+ `${
+ pathToFileURL(join(tempDir, "pages/index/+data.ts")).href
+ }?test=${crypto.randomUUID()}`
+ )) as {
+ data: (context: {
+ urlOriginal: string;
+ headers: Record<string, string>;
+ routeParams: Record<string, string>;
+ }) => Promise<{ resources: Record<string, unknown> }>;
+ };
+
+ const pageData = await pageModule.data({
+ urlOriginal: "/",
+ headers: { host: "example.com" },
+ routeParams: {},
+ });
+
+ expect(pageData.resources).toMatchObject({
+ Posts: {
+ ok: true,
+ status: 200,
+ data: {
+ "post-1": {
+ id: "post-1",
+ properties: { title: "Prerendered post" },
+ },
+ },
+ meta: { totalCount: 1, hasMore: false },
+ },
+ });
+ await runGeneratedCommand("vite", ["build"]);
+ await runGeneratedCommand("vike", ["prerender"]);
+ await expect(readFile("dist/client/index.html", "utf8")).resolves.toContain(
+ "<!DOCTYPE html>"
+ );
+ }, 30_000);
+
test("generates html, xml, and text document routes", async () => {
await writeSiteData(
createSiteData({
diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.ts
index 2c5351e844..4a7a8be830 100644
--- a/packages/cli/src/prebuild.ts
+++ b/packages/cli/src/prebuild.ts
@@ -21,26 +21,17 @@ import {
generateRemixRoute,
generateRemixParams,
} from "@webstudio-is/react-sdk";
-import type {
- Instance,
- Prop,
- Page,
- DataSource,
- Deployment,
- Asset,
- Resource,
- WsComponentMeta,
- Pages,
-} from "@webstudio-is/sdk";
import {
createScope,
findTreeInstanceIds,
getAllPages,
+ isAssetsResource,
getPagePath,
getPublishablePages,
generateResources,
generatePageMeta,
getStaticSiteMapXml,
+ isPageEligibleForSitemap,
replaceFormActionsWithResources,
isCoreComponent,
coreMetas,
@@ -49,9 +40,44 @@ import {
ROOT_INSTANCE_ID,
elementComponent,
toRuntimeAsset,
+ matchPathnameParams,
+ createReachableAssetContentCompilationPlan,
+ parseStructuredAssetQueryResourceBody,
+ type StructuredAssetQueryFilterBinding,
+ type StructuredAssetQueryWhereBinding,
+ type Instance,
+ type Prop,
+ type Page,
+ type DataSource,
+ type Deployment,
+ type Asset,
+ type Resource,
+ type WsComponentMeta,
+ type Pages,
} from "@webstudio-is/sdk";
import { migratePages } from "@webstudio-is/project-migrations/pages";
import { collectFontFamiliesFromStyleDecls } from "@webstudio-is/project-build/runtime";
+import {
+ assetQueryFilter,
+ type AssetQueryFilter,
+ type ContentDatabaseDocument,
+ getAssetQueryFieldValue,
+ getContentArtifactReferencedAssetIds,
+ getContentArtifactRuntimeAssetIds,
+ matchesAssetQueryFilter,
+ requiresRuntimeDocumentData,
+ serializeContentArtifact,
+ verifyContentArtifact,
+} from "@webstudio-is/content-engine";
+import { assetResourceLimits } from "@webstudio-is/sdk/asset-resource-limits";
+import {
+ parseJsonExpression,
+ parseStaticMemberPath,
+} from "@webstudio-is/expression";
+import {
+ evaluateQueryWhere,
+ getQueryConditions,
+} from "@webstudio-is/query-builder/runtime";
import {
publishedProjectBundle,
type PublishedProjectBundle,
@@ -76,6 +102,15 @@ export const generatedFilesManifest = join(
".webstudio",
"generated-files.json"
);
+const contentRuntimeBundleUrl = new URL(
+ /* @vite-ignore */ "../lib/content-runtime.js",
+ import.meta.url
+);
+const contentRuntimeFile = "$resources.asset-query-vendor.js";
+const ssgAssetResourceFetchTemplateUrl = new URL(
+ "../templates/ssg/app/asset-resource-fetch.ts",
+ import.meta.url
+);
const appRoot = "app";
const generatedDir = join(appRoot, "__generated__");
const routesDir = join(appRoot, "routes");
@@ -97,6 +132,303 @@ type SiteDataByPage = {
};
};
+const getBoundSystemRouteParameter = (expression: string) => {
+ const path = parseStaticMemberPath(expression);
+ return path?.length === 3 && path[0] === "system" && path[1] === "params"
+ ? path[2]
+ : undefined;
+};
+
+const getStaticAssetQueryFilter = (
+ filter: StructuredAssetQueryFilterBinding
+): AssetQueryFilter | undefined => {
+ const value = parseJsonExpression(filter.value);
+ if (value === undefined) {
+ return;
+ }
+ const parsed = assetQueryFilter.safeParse({
+ field: filter.field,
+ operator: filter.operator,
+ value,
+ });
+ return parsed.success ? parsed.data : undefined;
+};
+
+const evaluatePrerenderWhere = ({
+ document,
+ where,
+ routeValues,
+}: {
+ document: ContentDatabaseDocument;
+ where: StructuredAssetQueryWhereBinding;
+ routeValues: ReadonlyMap<string, string>;
+}): boolean | undefined => {
+ return evaluateQueryWhere(where, (condition) => {
+ const routeParameter = getBoundSystemRouteParameter(condition.value);
+ const routeValue =
+ routeParameter === undefined
+ ? undefined
+ : routeValues.get(routeParameter);
+ let filter = getStaticAssetQueryFilter(condition);
+ if (routeValue !== undefined) {
+ const parsed = assetQueryFilter.safeParse({
+ ...condition,
+ value: routeValue,
+ });
+ filter = parsed.success ? parsed.data : undefined;
+ }
+ if (filter === undefined) {
+ return;
+ }
+ return matchesAssetQueryFilter(document, filter);
+ });
+};
+
+const getRouteCandidates = ({
+ document,
+ where,
+ routeParameterNames,
+}: {
+ document: ContentDatabaseDocument;
+ where: StructuredAssetQueryWhereBinding;
+ routeParameterNames: ReadonlySet<string>;
+}) => {
+ const candidates = new Map<string, Set<string>>();
+ for (const filter of getQueryConditions(where)) {
+ const routeParameter = getBoundSystemRouteParameter(filter.value);
+ if (
+ routeParameter === undefined ||
+ routeParameterNames.has(routeParameter) === false
+ ) {
+ continue;
+ }
+ const value = getAssetQueryFieldValue(document, filter.field);
+ const values =
+ filter.operator === "eq" && typeof value === "string"
+ ? [value]
+ : filter.operator === "contains" && Array.isArray(value)
+ ? value.filter((item): item is string => typeof item === "string")
+ : [];
+ if (values.length === 0) {
+ continue;
+ }
+ let parameterCandidates = candidates.get(routeParameter);
+ if (parameterCandidates === undefined) {
+ parameterCandidates = new Set();
+ candidates.set(routeParameter, parameterCandidates);
+ }
+ for (const candidate of values) {
+ if (candidate.length > 0) {
+ parameterCandidates.add(candidate);
+ }
+ }
+ }
+ return candidates;
+};
+
+const canEnumerateRouteCondition = ({
+ condition,
+ routeParameter,
+ index,
+}: {
+ condition: StructuredAssetQueryFilterBinding;
+ routeParameter: string;
+ index: NonNullable<PublishedProjectBundle["assetIndex"]>;
+}) => {
+ if (getBoundSystemRouteParameter(condition.value) !== routeParameter) {
+ return false;
+ }
+ if (condition.operator === "eq") {
+ return true;
+ }
+ return (
+ condition.operator === "contains" &&
+ index.documents.every(
+ (document) =>
+ typeof getAssetQueryFieldValue(document, condition.field) !== "string"
+ )
+ );
+};
+
+const isRouteParameterConstrained = ({
+ where,
+ routeParameter,
+ index,
+}: {
+ where: StructuredAssetQueryWhereBinding;
+ routeParameter: string;
+ index: NonNullable<PublishedProjectBundle["assetIndex"]>;
+}): boolean => {
+ if ("field" in where) {
+ return canEnumerateRouteCondition({
+ condition: where,
+ routeParameter,
+ index,
+ });
+ }
+ const children = "all" in where ? where.all : where.any;
+ if ("all" in where) {
+ return children.some((child) =>
+ isRouteParameterConstrained({ where: child, routeParameter, index })
+ );
+ }
+ return (
+ children.length > 0 &&
+ children.every((child) =>
+ isRouteParameterConstrained({ where: child, routeParameter, index })
+ )
+ );
+};
+
+export const getAssetResourcePrerenderPaths = ({
+ pagePath,
+ resources,
+ index,
+ requireCompleteEnumeration = false,
+}: {
+ pagePath: string;
+ resources: readonly [string, Resource][];
+ index: PublishedProjectBundle["assetIndex"];
+ requireCompleteEnumeration?: boolean;
+}) => {
+ const pathParameters = [...matchPathnameParams(pagePath)];
+ if (
+ pathParameters.length === 0 ||
+ pathParameters.some(
+ (match) =>
+ match.groups?.name === undefined || (match.groups.modifier ?? "") !== ""
+ )
+ ) {
+ return [];
+ }
+ const routeParameterNames = new Set(
+ pathParameters.map((match) => match.groups?.name as string)
+ );
+ if (index === undefined) {
+ return [];
+ }
+ const configurations = resources.flatMap(([, resource]) => {
+ if (isAssetsResource(resource) === false) {
+ return [];
+ }
+ const configuration = parseStructuredAssetQueryResourceBody(resource.body);
+ return configuration === undefined ? [] : [configuration];
+ });
+ let enumerableConfigurations = configurations;
+ if (requireCompleteEnumeration && configurations.length > 0) {
+ const configurationsByParameters = configurations.flatMap(
+ (configuration) => {
+ const boundRouteParameters = new Set(
+ getQueryConditions(configuration.where).flatMap((condition) => {
+ const routeParameter = getBoundSystemRouteParameter(
+ condition.value
+ );
+ return routeParameter !== undefined &&
+ routeParameterNames.has(routeParameter)
+ ? [routeParameter]
+ : [];
+ })
+ );
+ return [...routeParameterNames].every((routeParameter) =>
+ boundRouteParameters.has(routeParameter)
+ )
+ ? [{ configuration, boundRouteParameters }]
+ : [];
+ }
+ );
+ if (configurationsByParameters.length === 0) {
+ throw new Error(
+ "Dynamic SSG route parameters must be completely enumerated by one Assets query"
+ );
+ }
+ let firstUnenumerableParameter: string | undefined;
+ enumerableConfigurations = configurationsByParameters.flatMap(
+ ({ configuration, boundRouteParameters }) => {
+ for (const routeParameter of boundRouteParameters) {
+ if (
+ isRouteParameterConstrained({
+ where: configuration.where,
+ routeParameter,
+ index,
+ }) === false
+ ) {
+ firstUnenumerableParameter ??= routeParameter;
+ return [];
+ }
+ }
+ return [configuration];
+ }
+ );
+ if (enumerableConfigurations.length === 0) {
+ throw new Error(
+ `Dynamic SSG route parameter ${JSON.stringify(firstUnenumerableParameter)} cannot be completely enumerated from every Assets query branch`
+ );
+ }
+ }
+ const paths = new Set<string>();
+ for (const configuration of enumerableConfigurations) {
+ let evaluatedCandidates = 0;
+ for (const document of index.documents) {
+ const candidates = getRouteCandidates({
+ document,
+ where: configuration.where,
+ routeParameterNames,
+ });
+ if (
+ [...routeParameterNames].some(
+ (name) => (candidates.get(name)?.size ?? 0) === 0
+ )
+ ) {
+ continue;
+ }
+ const parameterNames = [...routeParameterNames];
+ const values = new Map<string, string>();
+ const addPaths = (position: number) => {
+ if (position < parameterNames.length) {
+ const name = parameterNames[position];
+ for (const value of candidates.get(name) ?? []) {
+ values.set(name, value);
+ addPaths(position + 1);
+ }
+ values.delete(name);
+ return;
+ }
+ evaluatedCandidates += 1;
+ if (
+ evaluatedCandidates >
+ assetResourceLimits.candidateDocuments *
+ assetResourceLimits.filterCount
+ ) {
+ throw new Error(
+ "Dynamic SSG route candidates exceed the Assets limit"
+ );
+ }
+ if (
+ evaluatePrerenderWhere({
+ document,
+ where: configuration.where,
+ routeValues: values,
+ }) === false
+ ) {
+ return;
+ }
+ let path = pagePath;
+ for (const match of [...pathParameters].reverse()) {
+ const name = match.groups?.name as string;
+ const value = values.get(name) as string;
+ path = `${path.slice(0, match.index)}${encodeURIComponent(value)}${path.slice((match.index ?? 0) + match[0].length)}`;
+ }
+ paths.add(path);
+ if (paths.size > assetResourceLimits.candidateDocuments) {
+ throw new Error("Dynamic SSG path count exceeds the Assets limit");
+ }
+ };
+ addPaths(0);
+ }
+ }
+ return [...paths].sort();
+};
+
const mergeJsonInto = async (sourcePath: string, destinationPath: string) => {
const sourceJson = await readFile(sourcePath, "utf8");
const destinationJson = await readFile(destinationPath, "utf8").catch(
@@ -152,6 +484,126 @@ const readAssetBaseUrl = async (constantsPath: string) => {
);
};
+const configureSsgAssetResourceFetch = async ({
+ enabled,
+}: {
+ enabled: boolean;
+}) => {
+ const ssgFetchPath = join(cwd(), "app", "asset-resource-fetch.ts");
+ if (existsSync(ssgFetchPath)) {
+ const content = enabled
+ ? await readFile(ssgAssetResourceFetchTemplateUrl, "utf8")
+ : `export const createSsgAssetResourceFetch = (_options: unknown) =>
+ async (_input: RequestInfo | URL, _init?: RequestInit) => undefined;\n`;
+ await writeFileIfChanged(ssgFetchPath, content);
+ }
+};
+
+const generateAssetQueryRuntimeModule = ({
+ deploymentId,
+ index,
+ runtimeAssets,
+}: {
+ deploymentId: string;
+ index: PublishedProjectBundle["assetIndex"];
+ runtimeAssets: Readonly<Record<string, ReturnType<typeof toRuntimeAsset>>>;
+}) => {
+ const inputType = `{
+ request: Request;
+ context: unknown;
+ fallback: typeof fetch;
+ }`;
+ if (index === undefined) {
+ return `export const createGeneratedAssetResourceFetch = async ({ fallback }: ${inputType}): Promise<typeof fetch> => fallback;\n`;
+ }
+ return `import { createGeneratedAssetResourceRuntime } from "./${contentRuntimeFile}";
+import { assetQueryDatabase } from "./$resources.asset-query-manifest";
+
+const deploymentId = ${JSON.stringify(deploymentId)};
+const runtimeAssets = ${JSON.stringify(runtimeAssets)};
+const createRuntimeFetch = createGeneratedAssetResourceRuntime({
+ deploymentId,
+ artifact: assetQueryDatabase,
+ runtimeAssets,
+});
+
+export const createGeneratedAssetResourceFetch = ({ request, fallback }: ${inputType}) =>
+ createRuntimeFetch({ request, fallback });
+`;
+};
+
+export const materializeAssetIndex = async ({
+ index,
+ runtimeAssets,
+ includeDocumentRuntimeAssets,
+ generatedDirectory,
+ deploymentId,
+}: {
+ index: PublishedProjectBundle["assetIndex"];
+ runtimeAssets: Readonly<Record<string, ReturnType<typeof toRuntimeAsset>>>;
+ includeDocumentRuntimeAssets: boolean;
+ generatedDirectory: string;
+ deploymentId: string;
+}) => {
+ const verifiedIndex =
+ index === undefined ? undefined : await verifyContentArtifact(index);
+ const serializedIndex =
+ verifiedIndex === undefined
+ ? undefined
+ : serializeContentArtifact(verifiedIndex);
+ const runtimeAssetIds =
+ verifiedIndex === undefined
+ ? []
+ : getContentArtifactRuntimeAssetIds({
+ artifact: verifiedIndex,
+ includeDocuments: includeDocumentRuntimeAssets,
+ });
+ const referencedAssetIds = new Set(
+ verifiedIndex === undefined
+ ? []
+ : getContentArtifactReferencedAssetIds(verifiedIndex)
+ );
+ const selectedRuntimeAssets = Object.fromEntries(
+ runtimeAssetIds.map((assetId) => {
+ const asset = runtimeAssets[assetId];
+ if (asset === undefined) {
+ throw new Error(
+ referencedAssetIds.has(assetId)
+ ? `Published referenced asset URL is unavailable for ${assetId}`
+ : `Published asset runtime data is unavailable for ${assetId}`
+ );
+ }
+ return [assetId, asset];
+ })
+ );
+ const runtimePath = join(generatedDirectory, contentRuntimeFile);
+ if (index === undefined) {
+ await rm(runtimePath, { force: true });
+ } else {
+ await cp(contentRuntimeBundleUrl, runtimePath);
+ }
+ await writeFile(
+ join(generatedDirectory, "$resources.asset-query-manifest.ts"),
+ serializedIndex === undefined
+ ? `export const assetQueryDeploymentId = ${JSON.stringify(deploymentId)};
+export const assetQueryDatabase = undefined;
+`
+ : `export const assetQueryDeploymentId = ${JSON.stringify(deploymentId)};
+export const assetQueryDatabase = ${serializedIndex};
+`,
+ "utf8"
+ );
+ await writeFile(
+ join(generatedDirectory, "$resources.asset-query-runtime.ts"),
+ generateAssetQueryRuntimeModule({
+ deploymentId,
+ index: verifiedIndex,
+ runtimeAssets: selectedRuntimeAssets,
+ }),
+ "utf8"
+ );
+};
+
const writeWsAuthResources = async (
generatedDir: string,
pages: Pages,
@@ -291,7 +743,9 @@ const generateRedirectFallbackRoute = (runtime: "remix" | "react-router") => {
runtime === "react-router" ? "react-router" : "@remix-run/server-runtime";
return `
- import { type LoaderFunctionArgs } from ${JSON.stringify(loaderFunctionArgs)};
+ import { type LoaderFunctionArgs } from ${JSON.stringify(
+ loaderFunctionArgs
+ )};
import { redirectRequest } from "../redirect-url";
// @todo think about how to make __generated__ typeable
// @ts-ignore
@@ -325,6 +779,8 @@ export const prebuild = async (options: {
incremental?: boolean;
/** Retain route template inputs for a later incremental generation. */
preserveRouteTemplates?: boolean;
+ /** Emit a public identity marker used only by the local preview controller. */
+ previewIdentity?: boolean;
}) => {
const buildRoot = cwd();
const feedback = options.silent
@@ -430,10 +886,16 @@ export const prebuild = async (options: {
const parsedSiteData = publishedProjectBundle.safeParse(loadedSiteData);
if (parsedSiteData.success === false) {
throw new Error(
- `Project bundle is invalid, please make sure the project is synced. Invalid fields: ${formatZodIssues(parsedSiteData.error.issues, loadedSiteData)}`
+ `Project bundle is invalid, please make sure the project is synced. Invalid fields: ${formatZodIssues(
+ parsedSiteData.error.issues,
+ loadedSiteData
+ )}`
);
}
const siteData = parsedSiteData.data;
+ await configureSsgAssetResourceFetch({
+ enabled: siteData.assetIndex !== undefined,
+ });
const usedMetas = new Map<Instance["component"], WsComponentMeta>(
Object.entries(coreMetas)
@@ -443,6 +905,8 @@ export const prebuild = async (options: {
const generatedPages = options.includeDraftPages
? getAllPages(pages)
: publishablePages;
+ const publishablePageIds = new Set(publishablePages.map((page) => page.id));
+ const assetSitemapPaths = new Set<string>();
await writeWsAuthResources(
generatedDir,
pages,
@@ -744,7 +1208,9 @@ export const prebuild = async (options: {
export const projectDomain = ${JSON.stringify(siteData.projectDomain)};
- export const lastPublished = "${new Date(siteData.build.createdAt).toISOString()}";
+ export const lastPublished = "${new Date(
+ siteData.build.createdAt
+ ).toISOString()}";
export const siteName = ${JSON.stringify(projectMeta?.siteName)};
@@ -785,7 +1251,9 @@ export const prebuild = async (options: {
}
export const CustomCode = () => {
- return (<>${projectMeta?.code ? htmlToJsx(projectMeta.code) : ""}</>);
+ return (<>${
+ projectMeta?.code ? htmlToJsx(projectMeta.code) : ""
+ }</>);
}
`
: ""
@@ -829,7 +1297,21 @@ export const prebuild = async (options: {
await writeGeneratedFile(serverFile, serverExports);
const getTemplates = framework[documentType];
- for (const { file, template } of getTemplates({ pagePath })) {
+ const prerenderPaths = getAssetResourcePrerenderPaths({
+ pagePath,
+ resources: pageData.build.resources,
+ index: siteData.assetIndex,
+ requireCompleteEnumeration: options.template.includes("ssg"),
+ });
+ if (publishablePageIds.has(page.id) && isPageEligibleForSitemap(page)) {
+ for (const path of prerenderPaths) {
+ assetSitemapPaths.add(path);
+ }
+ }
+ for (const { file, template } of getTemplates({
+ pagePath,
+ prerenderPaths,
+ })) {
const content = template
.replaceAll("__CONSTANTS__", importFrom("./app/constants.mjs", file))
.replaceAll(
@@ -840,6 +1322,21 @@ export const prebuild = async (options: {
"__ASSETS__",
importFrom(`./app/__generated__/$resources.assets`, file)
)
+ .replaceAll(
+ "__ASSET_QUERY_MANIFEST__",
+ importFrom(
+ `./app/__generated__/$resources.asset-query-manifest`,
+ file
+ )
+ )
+ .replaceAll(
+ "__ASSET_QUERY_RUNTIME__",
+ importFrom(`./app/__generated__/$resources.asset-query-runtime`, file)
+ )
+ .replaceAll(
+ "__ASSET_RESOURCE_FETCH__",
+ importFrom("./app/asset-resource-fetch", file)
+ )
.replaceAll(
"__AUTH__",
importFrom(`./app/__generated__/$resources.wsauth.server`, file)
@@ -869,14 +1366,22 @@ export const prebuild = async (options: {
await writeGeneratedFile(file, content);
}
+ const sitemap = getStaticSiteMapXml(pages, siteData.build.updatedAt);
+ const sitemapPaths = new Set(sitemap.map(({ path }) => path));
+ for (const path of [...assetSitemapPaths].sort()) {
+ if (sitemapPaths.has(path)) {
+ continue;
+ }
+ sitemapPaths.add(path);
+ sitemap.push({
+ path,
+ lastModified: siteData.build.updatedAt.split("T")[0],
+ });
+ }
await writeGeneratedFile(
join(generatedDir, "$resources.sitemap.xml.ts"),
`
- export const sitemap = ${JSON.stringify(
- getStaticSiteMapXml(pages, siteData.build.updatedAt),
- null,
- 2
- )};
+ export const sitemap = ${JSON.stringify(sitemap, null, 2)};
`
);
@@ -894,6 +1399,34 @@ export const prebuild = async (options: {
},
])
);
+ const assetCompilationPlan = createReachableAssetContentCompilationPlan({
+ props: siteData.build.props.map(([, prop]) => prop),
+ dataSources: siteData.build.dataSources.map(([, dataSource]) => dataSource),
+ resources: siteData.build.resources.map(([, resource]) => resource),
+ });
+
+ await materializeAssetIndex({
+ index: siteData.assetIndex,
+ runtimeAssets: assetsById,
+ includeDocumentRuntimeAssets:
+ assetCompilationPlan !== undefined &&
+ requiresRuntimeDocumentData(assetCompilationPlan),
+ generatedDirectory: generatedDir,
+ deploymentId: siteData.build.id,
+ });
+
+ if (options.previewIdentity) {
+ const previewIdentityDirectory = join(buildRoot, "public", "__webstudio");
+ await createFolderIfNotExists(previewIdentityDirectory);
+ await writeFile(
+ join(previewIdentityDirectory, "preview.json"),
+ JSON.stringify({
+ projectId: siteData.build.projectId,
+ version: siteData.build.version,
+ }),
+ "utf8"
+ );
+ }
await writeGeneratedFile(
join(generatedDir, "$resources.assets.ts"),
@@ -926,7 +1459,7 @@ export const prebuild = async (options: {
if (options.assets === true && siteData.assets.length > 0) {
const downloading = createProgress();
- downloading.start("Downloading fonts and images");
+ downloading.start("Downloading assets");
await materializeAssetFiles({
assets: siteData.assets,
continueOnError: true,
@@ -934,7 +1467,7 @@ export const prebuild = async (options: {
sourceAssetsDirectory: join(buildRoot, LOCAL_ASSETS_DIR),
targetAssetsDirectory: join(buildRoot, "public", assetBaseUrl),
});
- downloading.stop("Downloaded fonts and images");
+ downloading.stop("Downloaded assets");
}
feedback.step("Build finished");
diff --git a/packages/cli/src/preview-server.test.ts b/packages/cli/src/preview-server.test.ts
index e784c66575..1eaa6ba4a6 100644
--- a/packages/cli/src/preview-server.test.ts
+++ b/packages/cli/src/preview-server.test.ts
@@ -664,6 +664,29 @@ test("accepts the generated preview with the expected project marker", async ()
).resolves.toBeUndefined();
});
+test("uses the static identity marker when page authentication blocks readiness", async () => {
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce(new Response("Unauthorized", { status: 401 }))
+ .mockResolvedValueOnce(Response.json({ projectId: "project", version: 5 }));
+
+ await expect(
+ waitForPreviewReady(
+ "http://127.0.0.1:5173/",
+ {
+ timeoutMs: 1000,
+ requiredProject: { projectId: "project", version: 5 },
+ },
+ createDependencies({ fetch })
+ )
+ ).resolves.toBeUndefined();
+ expect(fetch).toHaveBeenNthCalledWith(
+ 2,
+ new URL("http://127.0.0.1:5173/__webstudio/preview.json"),
+ expect.objectContaining({ method: "GET" })
+ );
+});
+
test("waits for the exact generated session version", async () => {
const fetch = vi
.fn()
diff --git a/packages/cli/src/preview-server.ts b/packages/cli/src/preview-server.ts
index e1c3608a28..804e41ceff 100644
--- a/packages/cli/src/preview-server.ts
+++ b/packages/cli/src/preview-server.ts
@@ -350,6 +350,29 @@ export const waitForPreviewReady = async (
method: "GET",
signal: AbortSignal.timeout(attemptTimeoutMs),
});
+ if (response.status === 401 && requiredProject !== undefined) {
+ const identityResponse = await dependencies.fetch(
+ new URL("/__webstudio/preview.json", url),
+ {
+ method: "GET",
+ signal: AbortSignal.timeout(attemptTimeoutMs),
+ }
+ );
+ if (identityResponse.ok) {
+ const identity = (await identityResponse.json()) as {
+ projectId?: unknown;
+ version?: unknown;
+ };
+ if (
+ identity.projectId === requiredProject.projectId &&
+ (requiredProject.version === undefined ||
+ identity.version === requiredProject.version)
+ ) {
+ return;
+ }
+ sawUnexpectedProject = true;
+ }
+ }
if (response.status < 500) {
if (requiredAssetNames.length === 0 && requiredProject === undefined) {
return;
diff --git a/packages/cli/src/project-session.test.ts b/packages/cli/src/project-session.test.ts
index d1a16f14e6..06b7a5111d 100644
--- a/packages/cli/src/project-session.test.ts
+++ b/packages/cli/src/project-session.test.ts
@@ -1,9 +1,10 @@
-import { mkdtemp, readFile, rm } from "node:fs/promises";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { afterEach, describe, expect, test, vi } from "vitest";
import { createBuilderStateFromSnapshot } from "@webstudio-is/project-build/state";
import { createBuilderStateFreshness } from "@webstudio-is/project-build/state";
+import { createStructuredAssetQueryResourceBody } from "@webstudio-is/sdk";
import {
createLocalProjectBundleFromSessionSnapshot,
createCliProjectRestorePointStorage,
@@ -13,6 +14,7 @@ import {
getCliProjectSessionFile,
getCliProjectRestorePointsFile,
getSupportedPublicApiOperations,
+ loadCliProjectSessionAssetIndex,
} from "./project-session";
test("scopes project session files for explicitly selected projects", () => {
@@ -29,6 +31,78 @@ test("scopes project session files for explicitly selected projects", () => {
const temporaryDirectories: string[] = [];
+test("loads a preview index only for configured Assets resources", async () => {
+ const connection = {
+ projectId: "project",
+ origin: "https://example.com",
+ authToken: "token",
+ };
+ const snapshot = (resources: Map<string, unknown>) =>
+ ({ projectId: "project", state: { resources } }) as never;
+
+ await expect(
+ loadCliProjectSessionAssetIndex(snapshot(new Map()), connection)
+ ).resolves.toBeUndefined();
+
+ const directory = await createTemporaryDirectory();
+ await writeFile(
+ join(directory, "post_hash.md"),
+ "---\ntitle: Hello\n---\nBody"
+ );
+ const resource = {
+ id: "posts",
+ name: "Posts",
+ control: "system" as const,
+ method: "post" as const,
+ url: '"/$resources/assets"',
+ headers: [],
+ body: createStructuredAssetQueryResourceBody({
+ where: { all: [] },
+ sort: [],
+ limit: "10",
+ offset: "0",
+ output: { mode: "all", includeMetadata: true },
+ content: { mode: "none" },
+ }),
+ };
+
+ await expect(
+ loadCliProjectSessionAssetIndex(
+ {
+ projectId: "project",
+ state: {
+ resources: new Map([[resource.id, resource]]),
+ props: new Map([
+ ["prop", { id: "prop", type: "resource", value: resource.id }],
+ ]),
+ assets: new Map([
+ [
+ "post",
+ {
+ id: "post",
+ projectId: "project",
+ type: "file",
+ name: "post_hash.md",
+ filename: "post",
+ size: 0,
+ description: null,
+ createdAt: "2026-07-27T00:00:00.000Z",
+ format: "md",
+ meta: {},
+ },
+ ],
+ ]),
+ assetFolders: new Map(),
+ },
+ } as never,
+ connection,
+ directory
+ )
+ ).resolves.toMatchObject({
+ documents: [{ _id: "post", properties: { title: "Hello" } }],
+ });
+});
+
const createTemporaryDirectory = async () => {
const directory = await mkdtemp(join(tmpdir(), "webstudio-session-"));
temporaryDirectories.push(directory);
@@ -340,6 +414,7 @@ test("creates preview bundle from project session snapshot", () => {
],
});
+ const assetIndex = { marker: "derived-index" } as never;
const bundle = createLocalProjectBundleFromSessionSnapshot(
{
projectId: "project",
@@ -354,10 +429,11 @@ test("creates preview bundle from project session snapshot", () => {
projectSchemaVersion: "test-schema",
},
},
- { origin: "https://assets.example.com" }
+ { origin: "https://assets.example.com", assetIndex }
);
expect(bundle.origin).toBe("https://assets.example.com");
+ expect(bundle.assetIndex).toBe(assetIndex);
expect(bundle.projectTitle).toBe("Session Site");
expect(bundle.page.id).toBe("home");
expect(bundle.pages.map((page) => page.path)).toEqual(["", "/design-system"]);
diff --git a/packages/cli/src/project-session.ts b/packages/cli/src/project-session.ts
index 6dad02b725..26b4c65959 100644
--- a/packages/cli/src/project-session.ts
+++ b/packages/cli/src/project-session.ts
@@ -1,6 +1,8 @@
import { rm } from "node:fs/promises";
import { join } from "node:path";
import { cwd } from "node:process";
+import { parseContentDatabaseMaxBytes } from "@webstudio-is/content-engine";
+import { compileContentSource } from "@webstudio-is/content-engine/compiler";
import {
migratePages,
serializePages,
@@ -14,7 +16,10 @@ import {
publicApiOperations,
type PublishedProjectBundle,
} from "@webstudio-is/protocol";
-import { getHomePage } from "@webstudio-is/sdk";
+import {
+ createReachableAssetContentCompilationPlan,
+ getHomePage,
+} from "@webstudio-is/sdk";
import {
createProjectSession,
createDefaultProjectSessionCompatibility,
@@ -44,6 +49,8 @@ import type { ApiConnection } from "./api-connection";
import { getStableErrorCode } from "./error-codes";
import { loadJSONFile, withFileLock, writeFileAtomic } from "./fs-utils";
import { isPlainRecord } from "./type-utils";
+import { createFileSystemContentSource } from "./filesystem-content-source";
+import { LOCAL_ASSETS_DIR } from "./asset-files";
export type CliServerApiContract = {
clientVersion: string;
@@ -517,9 +524,44 @@ export type CliProjectSessionSnapshot = {
freshness: BuilderStateFreshness;
};
+export const loadCliProjectSessionAssetIndex = async (
+ snapshot: ProjectSessionSnapshot,
+ connection: ApiConnection,
+ assetsDirectory = LOCAL_ASSETS_DIR
+) => {
+ if (connection.projectId !== snapshot.projectId) {
+ throw new Error("CLI connection does not match the project session");
+ }
+ const plan = createReachableAssetContentCompilationPlan({
+ props: snapshot.state.props?.values() ?? [],
+ dataSources: snapshot.state.dataSources?.values() ?? [],
+ resources: snapshot.state.resources?.values() ?? [],
+ });
+ if (plan === undefined) {
+ return;
+ }
+ const { artifact } = await compileContentSource({
+ source: createFileSystemContentSource({
+ projectId: snapshot.projectId,
+ assets: Array.from(snapshot.state.assets?.values() ?? []),
+ folders: snapshot.state.assetFolders ?? new Map(),
+ assetsDirectory,
+ }),
+ projectId: snapshot.projectId,
+ plan,
+ maxBytes: parseContentDatabaseMaxBytes(
+ process.env.CONTENT_DATABASE_MAX_BYTES
+ ),
+ });
+ return artifact;
+};
+
export const createLocalProjectBundleFromSessionSnapshot = (
snapshot: ProjectSessionSnapshot,
- options: { origin?: string } = {}
+ options: {
+ origin?: string;
+ assetIndex?: PublishedProjectBundle["assetIndex"];
+ } = {}
): PublishedProjectBundle => {
const pages = snapshot.state.pages;
if (pages === undefined) {
@@ -545,6 +587,7 @@ export const createLocalProjectBundleFromSessionSnapshot = (
pages: Array.from(persistedPages.pages.values()),
assets: Array.from(snapshot.state.assets?.values() ?? []),
assetFolders: Array.from(snapshot.state.assetFolders?.values() ?? []),
+ assetIndex: options.assetIndex,
build: {
id: snapshot.buildId,
projectId: snapshot.projectId,
@@ -560,7 +603,10 @@ export const createLocalProjectBundleFromSessionSnapshot = (
export const writeCliProjectSessionDataFile = async (
snapshot: ProjectSessionSnapshot,
path = join(cwd(), LOCAL_DATA_FILE),
- options: { origin?: string } = {}
+ options: {
+ origin?: string;
+ assetIndex?: PublishedProjectBundle["assetIndex"];
+ } = {}
) => {
const data = createLocalProjectBundleFromSessionSnapshot(snapshot, options);
await writeFileAtomic(path, `${JSON.stringify(data, undefined, 2)}\n`);
diff --git a/packages/cli/src/screenshot-browser-cdp.test.ts b/packages/cli/src/screenshot-browser-cdp.test.ts
index 3a162d88b5..c617ed78f0 100644
--- a/packages/cli/src/screenshot-browser-cdp.test.ts
+++ b/packages/cli/src/screenshot-browser-cdp.test.ts
@@ -637,6 +637,34 @@ test("reuses one browser process across screenshot captures", async () => {
expect(browserProcess.kill).toHaveBeenCalledOnce();
});
+test("uses HTTP credentials for navigation without exposing them in results", async () => {
+ const socket = new FakeWebSocket();
+ const result = await captureBrowserScreenshot(
+ {
+ url: "http://127.0.0.1:5173/blog",
+ httpCredentials: { username: "editor", password: "secret phrase" },
+ output: "/tmp/authenticated.png",
+ width: 800,
+ height: 600,
+ browserPath: "/usr/bin/chromium",
+ waitUntil: "networkidle",
+ waitForTimeout: 0,
+ timeout: 1000,
+ },
+ createDependencies({ socket })
+ );
+
+ expect(
+ socket.sentMessages.find((message) => message.method === "Page.navigate")
+ ?.params?.url
+ ).toBe("http://editor:secret%[email protected]:5173/blog");
+ expect(result.navigation).toMatchObject({
+ requestedUrl: "http://127.0.0.1:5173/blog",
+ finalUrl: "http://127.0.0.1:5173/blog",
+ });
+ expect(JSON.stringify(result)).not.toContain("secret");
+});
+
test("navigates once while resizing one page through multiple viewports", async () => {
const socket = new FakeWebSocket();
const dependencies = createDependencies({ socket });
diff --git a/packages/cli/src/screenshot-browser-cdp.ts b/packages/cli/src/screenshot-browser-cdp.ts
index 0c81753d60..683dd49277 100644
--- a/packages/cli/src/screenshot-browser-cdp.ts
+++ b/packages/cli/src/screenshot-browser-cdp.ts
@@ -17,6 +17,7 @@ export type BrowserScreenshotOptions = {
includeResourceMetrics?: boolean;
includeContrastMetrics?: boolean;
url: string;
+ httpCredentials?: { username: string; password: string };
uid?: number;
waitUntil: ScreenshotWaitUntil;
waitForSelector?: string;
@@ -27,6 +28,30 @@ export type BrowserScreenshotOptions = {
scale?: number;
};
+const getNavigationUrl = (options: BrowserScreenshotOptions) => {
+ if (options.httpCredentials === undefined) {
+ return options.url;
+ }
+ const url = new URL(options.url);
+ url.username = options.httpCredentials.username;
+ url.password = options.httpCredentials.password;
+ return url.toString();
+};
+
+const removeUrlCredentials = (value: string) => {
+ try {
+ const url = new URL(value);
+ if (url.username === "" && url.password === "") {
+ return value;
+ }
+ url.username = "";
+ url.password = "";
+ return url.toString();
+ } catch {
+ return value;
+ }
+};
+
export type BrowserScreenshotTimings = {
wallMs: number;
targetSetupMs: number;
@@ -1309,7 +1334,7 @@ const capturePageWithBrowserRuntime = async (
return;
}
const redirects = redirectsByFrame.get(params.frameId) ?? [];
- redirects.push(params.redirectResponse.url);
+ redirects.push(removeUrlCredentials(params.redirectResponse.url));
redirectsByFrame.set(params.frameId, redirects);
});
cdp.on("Network.responseReceived", (params) => {
@@ -1334,7 +1359,7 @@ const capturePageWithBrowserRuntime = async (
return;
}
documentResponsesByFrame.set(params.frameId, {
- url: response.url,
+ url: removeUrlCredentials(response.url),
status: response.status,
...(typeof response.statusText === "string"
? { statusText: response.statusText }
@@ -1377,7 +1402,7 @@ const capturePageWithBrowserRuntime = async (
async () =>
await send<NavigationResult>(
"Page.navigate",
- { url: options.url },
+ { url: getNavigationUrl(options) },
options.timeout
)
);
@@ -1492,13 +1517,14 @@ const capturePageWithBrowserRuntime = async (
contrastInspectionPromise,
screenshotPromise,
]);
- const finalUrl =
+ const finalUrl = removeUrlCredentials(
typeof locationResult.result?.value === "string"
? locationResult.result.value
: ((navigationFrameId === undefined
? undefined
: documentResponsesByFrame.get(navigationFrameId)?.url) ??
- options.url);
+ options.url)
+ );
const documentResponse =
navigationFrameId === undefined
? undefined
diff --git a/packages/cli/src/screenshot.ts b/packages/cli/src/screenshot.ts
index 40ecd3239f..f7ed844897 100644
--- a/packages/cli/src/screenshot.ts
+++ b/packages/cli/src/screenshot.ts
@@ -505,6 +505,7 @@ let screenshotBatchSequence = 0;
type CaptureScreenshotOptions = {
url: string;
+ httpCredentials?: { username: string; password: string };
output?: string;
width: number;
height: number;
@@ -538,6 +539,7 @@ const getBrowserScreenshotOptions = (
includeResourceMetrics: options.includeResourceMetrics,
includeContrastMetrics: options.includeContrastMetrics,
url: options.url,
+ httpCredentials: options.httpCredentials,
uid: dependencies.getuid(),
waitUntil: options.waitUntil ?? defaultScreenshotWaitUntil,
waitForSelector: options.waitForSelector,
diff --git a/packages/cli/src/template-placeholders.d.ts b/packages/cli/src/template-placeholders.d.ts
new file mode 100644
index 0000000000..c5dba625ad
--- /dev/null
+++ b/packages/cli/src/template-placeholders.d.ts
@@ -0,0 +1,30 @@
+declare module "__ASSET_QUERY_MANIFEST__" {
+ import type { ContentArtifactV1 } from "@webstudio-is/content-engine";
+
+ export const assetQueryDeploymentId: string;
+ export const assetQueryDatabase: ContentArtifactV1 | undefined;
+}
+
+declare module "__ASSET_QUERY_RUNTIME__" {
+ export const createGeneratedAssetResourceFetch: (options: {
+ request: Request;
+ context: unknown;
+ fallback: typeof fetch;
+ }) => Promise<typeof fetch>;
+}
+
+declare module "__ASSET_RESOURCE_FETCH__" {
+ import type { ContentArtifactV1 } from "@webstudio-is/content-engine";
+
+ export const createSsgAssetResourceFetch: (options: {
+ deploymentId: string;
+ artifact: ContentArtifactV1;
+ runtimeAssets: Record<
+ string,
+ { url: string; width?: number; height?: number }
+ >;
+ }) => (
+ input: RequestInfo | URL,
+ init?: RequestInit
+ ) => Promise<Response | undefined>;
+}
diff --git a/packages/cli/templates/defaults/app/route-templates/html.tsx b/packages/cli/templates/defaults/app/route-templates/html.tsx
index d4fa645098..318f55ed13 100644
--- a/packages/cli/templates/defaults/app/route-templates/html.tsx
+++ b/packages/cli/templates/defaults/app/route-templates/html.tsx
@@ -44,8 +44,8 @@ import {
import * as constants from "__CONSTANTS__";
import css from "__CSS__?url";
import { sitemap } from "__SITEMAP__";
-import { assets } from "__ASSETS__";
import { authRoutes } from "__AUTH__";
+import { createGeneratedAssetResourceFetch } from "__ASSET_QUERY_RUNTIME__";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -95,12 +95,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -123,9 +117,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/packages/cli/templates/defaults/app/route-templates/text.tsx b/packages/cli/templates/defaults/app/route-templates/text.tsx
index 25da6ce73d..843fc771d8 100644
--- a/packages/cli/templates/defaults/app/route-templates/text.tsx
+++ b/packages/cli/templates/defaults/app/route-templates/text.tsx
@@ -4,8 +4,8 @@ import { authenticateRequest } from "@webstudio-is/wsauth";
import { projectDomain } from "__CLIENT__";
import { getPageMeta, getRemixParams, getResources } from "__SERVER__";
import { sitemap } from "__SITEMAP__";
-import { assets } from "__ASSETS__";
import { authRoutes } from "__AUTH__";
+import { createGeneratedAssetResourceFetch } from "__ASSET_QUERY_RUNTIME__";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -53,12 +53,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return fetch(input, init);
};
@@ -82,9 +76,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/packages/cli/templates/defaults/app/route-templates/xml.tsx b/packages/cli/templates/defaults/app/route-templates/xml.tsx
index 17cecc3c6c..5697d3cbd2 100644
--- a/packages/cli/templates/defaults/app/route-templates/xml.tsx
+++ b/packages/cli/templates/defaults/app/route-templates/xml.tsx
@@ -10,8 +10,8 @@ import { Page, breakpoints, projectDomain } from "__CLIENT__";
import { getPageMeta, getRemixParams, getResources } from "__SERVER__";
import { assetBaseUrl, imageLoader } from "__CONSTANTS__";
import { sitemap } from "__SITEMAP__";
-import { assets } from "__ASSETS__";
import { authRoutes } from "__AUTH__";
+import { createGeneratedAssetResourceFetch } from "__ASSET_QUERY_RUNTIME__";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -61,12 +61,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return fetch(input, init);
};
@@ -90,9 +84,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/packages/cli/templates/react-router/app/route-templates/html.tsx b/packages/cli/templates/react-router/app/route-templates/html.tsx
index bb66055fa7..193b5f5e6e 100644
--- a/packages/cli/templates/react-router/app/route-templates/html.tsx
+++ b/packages/cli/templates/react-router/app/route-templates/html.tsx
@@ -43,8 +43,8 @@ import {
import * as constants from "__CONSTANTS__";
import css from "__CSS__?url";
import { sitemap } from "__SITEMAP__";
-import { assets } from "__ASSETS__";
import { authRoutes } from "__AUTH__";
+import { createGeneratedAssetResourceFetch } from "__ASSET_QUERY_RUNTIME__";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -94,12 +94,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return cachedFetch(projectId, input, init);
};
@@ -122,9 +116,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/packages/cli/templates/react-router/app/route-templates/text.tsx b/packages/cli/templates/react-router/app/route-templates/text.tsx
index 3229cb1f40..47aa3e535e 100644
--- a/packages/cli/templates/react-router/app/route-templates/text.tsx
+++ b/packages/cli/templates/react-router/app/route-templates/text.tsx
@@ -4,8 +4,8 @@ import { authenticateRequest } from "@webstudio-is/wsauth";
import { projectDomain } from "__CLIENT__";
import { getPageMeta, getRemixParams, getResources } from "__SERVER__";
import { sitemap } from "__SITEMAP__";
-import { assets } from "__ASSETS__";
import { authRoutes } from "__AUTH__";
+import { createGeneratedAssetResourceFetch } from "__ASSET_QUERY_RUNTIME__";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -53,12 +53,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return fetch(input, init);
};
@@ -82,9 +76,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/packages/cli/templates/react-router/app/route-templates/xml.tsx b/packages/cli/templates/react-router/app/route-templates/xml.tsx
index ccc93691c4..29a6545d32 100644
--- a/packages/cli/templates/react-router/app/route-templates/xml.tsx
+++ b/packages/cli/templates/react-router/app/route-templates/xml.tsx
@@ -10,8 +10,8 @@ import { Page, breakpoints, projectDomain } from "__CLIENT__";
import { getPageMeta, getRemixParams, getResources } from "__SERVER__";
import { assetBaseUrl, imageLoader } from "__CONSTANTS__";
import { sitemap } from "__SITEMAP__";
-import { assets } from "__ASSETS__";
import { authRoutes } from "__AUTH__";
+import { createGeneratedAssetResourceFetch } from "__ASSET_QUERY_RUNTIME__";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -61,12 +61,6 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
return fetch(input, init);
};
@@ -90,9 +84,16 @@ export const loader = async (arg: LoaderFunctionArgs) => {
pathname: url.pathname,
};
+ const generatedFetch = await createGeneratedAssetResourceFetch({
+ request: arg.request,
+ context: arg.context,
+ fallback: customFetch,
+ });
const resources = await loadResources(
- customFetch,
- getResources({ system }).data
+ generatedFetch,
+ getResources({ system }).data,
+ url,
+ { signal: arg.request.signal }
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/packages/cli/templates/ssg/app/asset-resource-fetch.ts b/packages/cli/templates/ssg/app/asset-resource-fetch.ts
new file mode 100644
index 0000000000..ac9b4500dc
--- /dev/null
+++ b/packages/cli/templates/ssg/app/asset-resource-fetch.ts
@@ -0,0 +1,19 @@
+// Generated only for projects whose SSG build uses an Assets query.
+// @ts-expect-error The CLI template is typechecked before the generated module exists.
+import { createPublishedAssetResourceFetch } from "./__generated__/$resources.asset-query-vendor.js";
+
+export const createSsgAssetResourceFetch = ({
+ deploymentId,
+ artifact,
+ runtimeAssets,
+}: {
+ deploymentId: string;
+ artifact: unknown;
+ runtimeAssets: Record<string, { url: string; width?: number; height?: number }>;
+}) =>
+ createPublishedAssetResourceFetch({
+ baseUrl: "https://webstudio.local",
+ deploymentId,
+ artifact,
+ runtimeAssets,
+ });
diff --git a/packages/cli/templates/ssg/app/route-templates/html/+data.ts b/packages/cli/templates/ssg/app/route-templates/html/+data.ts
index 058735e51e..7362c216e4 100644
--- a/packages/cli/templates/ssg/app/route-templates/html/+data.ts
+++ b/packages/cli/templates/ssg/app/route-templates/html/+data.ts
@@ -2,8 +2,26 @@ import type { PageContextServer } from "vike/types";
import { isLocalResource, loadResources } from "@webstudio-is/sdk/runtime";
import { getPageMeta, getResources } from "__SERVER__";
import { assets } from "__ASSETS__";
+import {
+ assetQueryDeploymentId,
+ assetQueryDatabase,
+} from "__ASSET_QUERY_MANIFEST__";
+import { createSsgAssetResourceFetch } from "__ASSET_RESOURCE_FETCH__";
-const customFetch: typeof fetch = (input, init) => {
+const fetchAssetResource =
+ assetQueryDatabase === undefined
+ ? undefined
+ : createSsgAssetResourceFetch({
+ deploymentId: assetQueryDeploymentId,
+ artifact: assetQueryDatabase,
+ runtimeAssets: assets,
+ });
+
+const customFetch: typeof fetch = async (input, init) => {
+ const assetResourceResponse = await fetchAssetResource?.(input, init);
+ if (assetResourceResponse !== undefined) {
+ return assetResourceResponse;
+ }
if (typeof input !== "string") {
return fetch(input, init);
}
@@ -23,13 +41,7 @@ const customFetch: typeof fetch = (input, init) => {
};
const response = new Response(JSON.stringify(data));
response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
- }
-
- if (isLocalResource(input, "assets")) {
- const response = new Response(JSON.stringify(assets));
- response.headers.set("content-type", "application/json; charset=utf-8");
- return Promise.resolve(response);
+ return response;
}
return fetch(input, init);
@@ -52,7 +64,8 @@ export const data = async (pageContext: PageContextServer) => {
const resources = await loadResources(
customFetch,
- getResources({ system }).data
+ getResources({ system }).data,
+ url
);
const pageMeta = getPageMeta({ system, resources });
diff --git a/packages/cli/templates/ssg/vite.config.ts b/packages/cli/templates/ssg/vite.config.ts
index 8e2bf4e3d6..83d1624d67 100644
--- a/packages/cli/templates/ssg/vite.config.ts
+++ b/packages/cli/templates/ssg/vite.config.ts
@@ -2,14 +2,17 @@ import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import vike from "vike/plugin";
+const sourceConditions =
+ process.env.WEBSTUDIO_LOCAL_CLI_BOOTSTRAPPED === "1" ? ["webstudio"] : [];
+
export default defineConfig({
plugins: [react(), vike()],
resolve: {
- conditions: ["browser", "development|production"],
+ conditions: [...sourceConditions, "browser", "development|production"],
},
ssr: {
resolve: {
- conditions: ["node", "development|production"],
+ conditions: [...sourceConditions, "node", "development|production"],
},
},
});
diff --git a/packages/cli/vite.config.ts b/packages/cli/vite.config.ts
index 9ea26a694c..58bb8a8c78 100644
--- a/packages/cli/vite.config.ts
+++ b/packages/cli/vite.config.ts
@@ -49,6 +49,9 @@ export default defineConfig({
build: {
target: "node22",
minify: false,
+ commonjsOptions: {
+ esmExternals: true,
+ },
lib: {
entry: ["src/cli.ts"],
formats: ["es"],
diff --git a/packages/content-engine/package.json b/packages/content-engine/package.json
new file mode 100644
index 0000000000..6638454d6b
--- /dev/null
+++ b/packages/content-engine/package.json
@@ -0,0 +1,76 @@
+{
+ "name": "@webstudio-is/content-engine",
+ "version": "0.0.0-webstudio-version",
+ "description": "Compile file-based content into a portable query runtime",
+ "author": "Webstudio <[email protected]>",
+ "homepage": "https://webstudio.is",
+ "license": "AGPL-3.0-or-later",
+ "type": "module",
+ "sideEffects": false,
+ "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/compiler.ts src/limits.ts src/markdown-assets.ts src/markdown-references.ts src/published-runtime.ts --outdir=lib --bundle --format=esm --packages=external",
+ "dts": "tsc --project tsconfig.dts.json",
+ "test": "vitest run",
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@webstudio-is/expression": "workspace:*",
+ "@webstudio-is/query-builder": "workspace:*",
+ "canonicalize": "3.0.0",
+ "micromark": "4.0.2",
+ "micromark-util-decode-string": "2.0.1",
+ "remark-parse": "10.0.2",
+ "unified": "10.1.2",
+ "yaml": "2.9.0",
+ "zod": "^4.4.3"
+ },
+ "devDependencies": {
+ "@webstudio-is/tsconfig": "workspace:*",
+ "esbuild": "^0.25.3",
+ "vitest": "^3.1.2"
+ },
+ "exports": {
+ ".": {
+ "webstudio": "./src/index.ts",
+ "types": "./lib/types/index.d.ts",
+ "import": "./lib/index.js",
+ "default": "./src/index.ts"
+ },
+ "./compiler": {
+ "webstudio": "./src/compiler.ts",
+ "types": "./lib/types/compiler.d.ts",
+ "import": "./lib/compiler.js",
+ "default": "./src/compiler.ts"
+ },
+ "./runtime": {
+ "webstudio": "./src/published-runtime.ts",
+ "types": "./lib/types/published-runtime.d.ts",
+ "import": "./lib/published-runtime.js",
+ "default": "./src/published-runtime.ts"
+ },
+ "./limits": {
+ "webstudio": "./src/limits.ts",
+ "types": "./lib/types/limits.d.ts",
+ "import": "./lib/limits.js",
+ "default": "./src/limits.ts"
+ },
+ "./markdown-assets": {
+ "webstudio": "./src/markdown-assets.ts",
+ "types": "./lib/types/markdown-assets.d.ts",
+ "import": "./lib/markdown-assets.js",
+ "default": "./src/markdown-assets.ts"
+ },
+ "./markdown-references": {
+ "webstudio": "./src/markdown-references.ts",
+ "types": "./lib/types/markdown-references.d.ts",
+ "import": "./lib/markdown-references.js",
+ "default": "./src/markdown-references.ts"
+ }
+ },
+ "files": [
+ "lib/**/*",
+ "!*.test.*"
+ ]
+}
diff --git a/packages/content-engine/scripts/benchmark-index.mjs b/packages/content-engine/scripts/benchmark-index.mjs
new file mode 100644
index 0000000000..8587172b2e
--- /dev/null
+++ b/packages/content-engine/scripts/benchmark-index.mjs
@@ -0,0 +1,79 @@
+import { gzipSync } from "node:zlib";
+import { performance } from "node:perf_hooks";
+import {
+ createAssetIndex,
+ createCanonicalAssetFileEntry,
+ serializeContentArtifact,
+ verifyContentArtifact,
+} from "../src/compiler.ts";
+
+const documents = Array.from({ length: 1000 }, (_, index) => ({
+ _id: `post-${String(index).padStart(4, "0")}`,
+ _type: "asset.file",
+ name: `post-${index}.md`,
+ path: `blog/post-${index}.md`,
+ key: `post-${index}`,
+ folderId: "blog",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 4000 + index,
+ revision: `content-revision-${index}`,
+ contentRef: `private:post-${index}.md`,
+ properties: {
+ title: `Representative blog post ${index}`,
+ slug: `post-${index}`,
+ publishedAt: `2026-07-${String((index % 28) + 1).padStart(2, "0")}`,
+ draft: index % 10 === 0,
+ locale: index % 2 === 0 ? "en" : "de",
+ author: { name: `Author ${index % 25}` },
+ tags: [`tag-${index % 10}`, `group-${index % 4}`],
+ },
+ excerpt: `A bounded representative excerpt for post ${index}.`,
+}));
+
+const entries = documents.map((document) =>
+ createCanonicalAssetFileEntry({ projectId: "benchmark-project", document })
+);
+const percentile = (samples, quantile) =>
+ [...samples].sort((left, right) => left - right)[
+ Math.min(samples.length - 1, Math.floor(samples.length * quantile))
+ ];
+
+const measure = async (iterations, operation) => {
+ const samples = [];
+ for (let iteration = 0; iteration < iterations; iteration += 1) {
+ const start = performance.now();
+ await operation();
+ samples.push(performance.now() - start);
+ }
+ return {
+ medianMs: Number(percentile(samples, 0.5).toFixed(3)),
+ p95Ms: Number(percentile(samples, 0.95).toFixed(3)),
+ };
+};
+
+const build = () =>
+ createAssetIndex({
+ projectId: "benchmark-project",
+ entries,
+ });
+
+for (let iteration = 0; iteration < 3; iteration += 1) {
+ await build();
+}
+const index = await build();
+const serialized = serializeContentArtifact(index);
+const encoded = new TextEncoder().encode(serialized);
+const parsed = JSON.parse(serialized);
+
+const result = {
+ fixtureDocuments: entries.length,
+ candidateDocuments: index.documents.length,
+ jsonBytes: encoded.byteLength,
+ gzipBytes: gzipSync(encoded).byteLength,
+ build: await measure(20, build),
+ parse: await measure(100, () => JSON.parse(serialized)),
+ verify: await measure(20, () => verifyContentArtifact(parsed)),
+};
+
+console.info(JSON.stringify(result, null, 2));
diff --git a/packages/content-engine/scripts/benchmark-scale.mjs b/packages/content-engine/scripts/benchmark-scale.mjs
new file mode 100644
index 0000000000..c53a73df47
--- /dev/null
+++ b/packages/content-engine/scripts/benchmark-scale.mjs
@@ -0,0 +1,282 @@
+import { gzipSync } from "node:zlib";
+import { performance } from "node:perf_hooks";
+import { build as bundle } from "esbuild";
+import {
+ createAssetFieldCatalog,
+ createAssetIndex,
+ createCanonicalAssetFileEntry,
+ extractMarkdownFrontmatter,
+ normalizeAssetFileDocument,
+ serializeContentArtifact,
+ verifyContentArtifact,
+} from "../src/compiler.ts";
+import { executeAssetQuery } from "../src/index.ts";
+import { createScaleMarkdownFixture } from "../src/scale-fixture.ts";
+
+const projectId = "scale-project";
+const files = createScaleMarkdownFixture(1000);
+const encoder = new TextEncoder();
+
+const percentile = (samples, quantile) =>
+ [...samples].sort((left, right) => left - right)[
+ Math.min(samples.length - 1, Math.floor(samples.length * quantile))
+ ];
+const measure = async (iterations, operation) => {
+ const samples = [];
+ for (let index = 0; index < iterations; index += 1) {
+ const startedAt = performance.now();
+ await operation();
+ samples.push(performance.now() - startedAt);
+ }
+ return {
+ medianMs: Number(percentile(samples, 0.5).toFixed(3)),
+ p95Ms: Number(percentile(samples, 0.95).toFixed(3)),
+ };
+};
+
+let markdownReads = 0;
+const deriveEntry = async (file, revision = `revision-${file.id}`) => {
+ markdownReads += 1;
+ const metadata = await extractMarkdownFrontmatter(file.source);
+ return createCanonicalAssetFileEntry({
+ projectId,
+ document: normalizeAssetFileDocument({
+ asset: {
+ id: file.id,
+ name: file.name,
+ folderId: "blog",
+ folderNames: ["blog"],
+ mimeType: "text/markdown",
+ size: encoder.encode(file.source).byteLength,
+ revision,
+ contentRef: file.name,
+ },
+ properties: metadata.properties,
+ excerpt: `Deterministic excerpt for ${file.id}`,
+ }),
+ });
+};
+
+const initialStartedAt = performance.now();
+const entries = [];
+for (const file of files) {
+ entries.push(await deriveEntry(file));
+}
+const catalog = await createAssetFieldCatalog(entries);
+const initialBackfillMs = performance.now() - initialStartedAt;
+const initialMarkdownReads = markdownReads;
+
+const buildIndex = () => createAssetIndex({ projectId, entries });
+const coldBuildStartedAt = performance.now();
+const index = await buildIndex();
+const coldBuildMs = performance.now() - coldBuildStartedAt;
+const warmBuild = await measure(10, buildIndex);
+
+markdownReads = 0;
+const changedFile = {
+ ...files[999],
+ source: files[999].source.replace("Post 999", "Changed post 999"),
+};
+const incrementalStartedAt = performance.now();
+await deriveEntry(changedFile, "revision-post-0999-v2");
+const incrementalMs = performance.now() - incrementalStartedAt;
+
+const serialized = serializeContentArtifact(index);
+const indexBytes = encoder.encode(serialized);
+const coldParseAndVerify = await measure(10, () =>
+ verifyContentArtifact(JSON.parse(serialized))
+);
+
+const read = async (contentRef, range) => {
+ const file = files.find(({ name }) => name === contentRef);
+ if (file === undefined) {
+ throw new Error("Scale fixture content is missing");
+ }
+ const bytes = encoder
+ .encode(file.source)
+ .subarray(
+ range?.offset ?? 0,
+ range === undefined ? undefined : range.offset + range.length
+ );
+ return {
+ data: {
+ async *[Symbol.asyncIterator]() {
+ yield bytes;
+ },
+ },
+ };
+};
+const listingQuery = {
+ where: {
+ all: [
+ { field: ["extension"], operator: "eq", value: "md" },
+ { field: ["properties", "locale"], operator: "eq", value: "en" },
+ ],
+ },
+ sort: [
+ { field: ["properties", "publishedAt"], direction: "desc" },
+ { field: ["id"], direction: "asc" },
+ ],
+ limit: 20,
+};
+const detailQuery = {
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "post-999",
+ },
+ ],
+ },
+ limit: 1,
+ content: { mode: "full" },
+};
+const warmListing = await measure(50, () =>
+ executeAssetQuery({
+ query: listingQuery,
+ catalog: index.fieldCatalog,
+ documents: index.documents,
+ })
+);
+const detailAndHydration = await measure(50, () =>
+ executeAssetQuery({
+ query: detailQuery,
+ catalog: index.fieldCatalog,
+ documents: index.documents,
+ read,
+ })
+);
+
+const workerBundle = await bundle({
+ entryPoints: [
+ new URL("../src/published-runtime.ts", import.meta.url).pathname,
+ ],
+ bundle: true,
+ format: "esm",
+ minify: true,
+ platform: "browser",
+ target: "es2022",
+ conditions: ["webstudio", "browser"],
+ write: false,
+});
+const workerBytes = workerBundle.outputFiles[0].contents;
+const memoryBefore = process.memoryUsage().heapUsed;
+const retainedCopies = Array.from({ length: 10 }, () => JSON.parse(serialized));
+const memoryAfter = process.memoryUsage().heapUsed;
+
+const nearLimitEntries = entries.map((entry) =>
+ createCanonicalAssetFileEntry({
+ projectId,
+ document: {
+ ...entry.document,
+ properties: {
+ ...entry.document.properties,
+ benchmarkPayload: "x".repeat(3000),
+ },
+ },
+ })
+);
+const nearLimitIndex = await createAssetIndex({
+ projectId,
+ entries: nearLimitEntries,
+});
+const nearLimitSerialized = serializeContentArtifact(nearLimitIndex);
+const nearLimitMemoryBefore = process.memoryUsage().heapUsed;
+const nearLimitParsed = await verifyContentArtifact(
+ JSON.parse(nearLimitSerialized)
+);
+const nearLimitMemoryAfter = process.memoryUsage().heapUsed;
+
+const projectEntryTier = (entry, tier) => {
+ const { excerpt, ...withoutExcerpt } = entry.document;
+ return createCanonicalAssetFileEntry({
+ projectId,
+ metadataRequirements: {
+ structuredProperties: tier === "metadata" || tier === "content",
+ excerpt: tier === "excerpt" || tier === "content",
+ },
+ document: {
+ ...withoutExcerpt,
+ properties:
+ tier === "metadata" || tier === "content"
+ ? entry.document.properties
+ : {},
+ ...(tier === "excerpt" || tier === "content" ? { excerpt } : {}),
+ },
+ });
+};
+
+const benchmarkTierArtifacts = async (count) => {
+ const selectedEntries = entries.slice(0, count);
+ const tiers = {};
+ for (const tier of ["base", "metadata", "excerpt", "content"]) {
+ const tierIndex = await createAssetIndex({
+ projectId,
+ entries: selectedEntries.map((entry) => projectEntryTier(entry, tier)),
+ });
+ const bytes = encoder.encode(serializeContentArtifact(tierIndex));
+ tiers[tier] = {
+ objectReads: tier === "base" ? 0 : count,
+ parserRuns: tier === "base" ? 0 : count,
+ jsonBytes: bytes.byteLength,
+ gzipBytes: gzipSync(bytes).byteLength,
+ };
+ }
+ return {
+ inactive: { objectReads: 0, parserRuns: 0, jsonBytes: 0, gzipBytes: 0 },
+ ...tiers,
+ };
+};
+
+const tierArtifacts = {
+ assets350: await benchmarkTierArtifacts(350),
+ assets1000: await benchmarkTierArtifacts(1000),
+};
+
+console.info(
+ JSON.stringify(
+ {
+ fixture: {
+ markdownFiles: files.length,
+ indexedFiles: index.documents.length,
+ dynamicFieldPaths: catalog.fields.length,
+ },
+ initialBackfill: {
+ durationMs: Number(initialBackfillMs.toFixed(3)),
+ markdownReads: initialMarkdownReads,
+ },
+ incrementalOneFile: {
+ durationMs: Number(incrementalMs.toFixed(3)),
+ markdownReads,
+ },
+ indexBuild: { coldMs: Number(coldBuildMs.toFixed(3)), warm: warmBuild },
+ indexArtifact: {
+ jsonBytes: indexBytes.byteLength,
+ gzipBytes: gzipSync(indexBytes).byteLength,
+ coldParseAndVerify,
+ nearLimit: {
+ jsonBytes: encoder.encode(nearLimitSerialized).byteLength,
+ parseVerifyHeapDeltaBytes: Math.max(
+ 0,
+ nearLimitMemoryAfter - nearLimitMemoryBefore
+ ),
+ documents: nearLimitParsed.documents.length,
+ },
+ },
+ workerRuntime: {
+ minifiedBundleBytes: workerBytes.byteLength,
+ minifiedBundleGzipBytes: gzipSync(workerBytes).byteLength,
+ warmListing,
+ dynamicSlugAndFullHydration: detailAndHydration,
+ parsedIndexHeapBytesPerCopyEstimate: Math.max(
+ 0,
+ Math.round((memoryAfter - memoryBefore) / retainedCopies.length)
+ ),
+ },
+ queryTiers: tierArtifacts,
+ },
+ null,
+ 2
+ )
+);
diff --git a/packages/content-engine/src/asset-index.test.ts b/packages/content-engine/src/asset-index.test.ts
new file mode 100644
index 0000000000..96634293ae
--- /dev/null
+++ b/packages/content-engine/src/asset-index.test.ts
@@ -0,0 +1,429 @@
+import { describe, expect, test } from "vitest";
+import { contentEngineLimits, parseContentDatabaseMaxBytes } from "./limits";
+import { createCanonicalAssetFileEntry } from "./canonical";
+import { createContentDatabase } from "./content-database";
+import { assetQueryResult, type AssetResourceOutputSelection } from "./schema";
+import {
+ createContentCompilationPlan,
+ createLiteralContentCompilationQuery,
+} from "./compilation-plan";
+import { compileContentArtifact, createAssetIndex } from "./asset-index";
+import {
+ getContentArtifactReferencedAssetIds,
+ getContentArtifactRuntimeAssetIds,
+ serializeContentArtifact,
+ verifyContentArtifact,
+} from "./content-artifact";
+
+const entry = ({
+ projectId = "project",
+ id,
+}: {
+ projectId?: string;
+ id: string;
+}) =>
+ createCanonicalAssetFileEntry({
+ projectId,
+ document: {
+ _id: id,
+ _type: "asset.file",
+ name: `${id}.md`,
+ path: `blog/${id}.md`,
+ key: id,
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 20,
+ revision: `revision-${id}`,
+ contentRef: `files/${id}.md`,
+ properties: { title: id, nested: { published: true } },
+ excerpt: `${id} excerpt`,
+ },
+ });
+
+describe("shared asset index", () => {
+ test("selects runtime assets from documents and Markdown references", () => {
+ const artifact = {
+ documents: [{ _id: "document" }, { _id: "shared" }],
+ assetReferences: {
+ "post.md": [
+ { start: 0, end: 1, assetId: "reference" },
+ { start: 2, end: 3, assetId: "shared" },
+ ],
+ },
+ };
+
+ expect(getContentArtifactReferencedAssetIds(artifact)).toEqual([
+ "reference",
+ "shared",
+ ]);
+ expect(
+ getContentArtifactRuntimeAssetIds({
+ artifact,
+ includeDocuments: true,
+ })
+ ).toEqual(["document", "reference", "shared"]);
+ });
+
+ test("stores only fields required by an ID-only query", async () => {
+ const sourceEntries = [entry({ id: "alpha" })];
+ const compile = (output: AssetResourceOutputSelection) =>
+ compileContentArtifact({
+ projectId: "project",
+ entries: sourceEntries,
+ plan: createContentCompilationPlan([
+ createLiteralContentCompilationQuery({
+ id: "posts",
+ query: {
+ where: { all: [] },
+ sort: [],
+ limit: 20,
+ offset: 0,
+ output,
+ content: { mode: "none" },
+ },
+ }),
+ ]),
+ });
+
+ const metadata = await compile({ mode: "base", includeMetadata: true });
+ const idOnly = await compile({
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["id"]],
+ });
+
+ expect(idOnly.artifact.documents).toEqual([{ _id: "alpha" }]);
+ expect(idOnly.diagnostics.boundedBytes).toBeLessThan(
+ metadata.diagnostics.boundedBytes
+ );
+ await expect(
+ createContentDatabase({ artifact: idOnly.artifact }).query({
+ query: {
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["id"]],
+ },
+ },
+ })
+ ).resolves.toMatchObject({ items: [{ id: "alpha" }] });
+ });
+
+ test("creates one deterministic complete index and field catalog", async () => {
+ const index = await createAssetIndex({
+ projectId: "project",
+ entries: [entry({ id: "beta" }), entry({ id: "alpha" })],
+ });
+
+ expect(index.format).toBe("webstudio-content-database");
+ expect(index.documents.map(({ _id }) => _id)).toEqual(["alpha", "beta"]);
+ expect(index.fieldCatalog.canonicalRevision).toBe(index.assetRevision);
+ expect(index.fieldCatalog.fields).toHaveProperty("properties.title");
+ expect(index).not.toHaveProperty("resourceId");
+ expect(index).not.toHaveProperty("queryHash");
+ expect(index).not.toHaveProperty("plan");
+ await expect(verifyContentArtifact(index)).resolves.toEqual(index);
+ });
+
+ test("rejects mixed projects, duplicate assets, and corrupted bytes", async () => {
+ await expect(
+ createAssetIndex({
+ projectId: "project",
+ entries: [
+ entry({ id: "alpha" }),
+ entry({ projectId: "other", id: "beta" }),
+ ],
+ })
+ ).rejects.toThrow("multiple projects");
+ await expect(
+ createAssetIndex({
+ projectId: "project",
+ entries: [entry({ id: "alpha" }), entry({ id: "alpha" })],
+ })
+ ).rejects.toThrow("duplicate documents");
+ const sharedReference = {
+ ...entry({ id: "beta" }),
+ document: {
+ ...entry({ id: "beta" }).document,
+ contentRef: "files/alpha.md",
+ },
+ };
+ await expect(
+ createAssetIndex({
+ projectId: "project",
+ entries: [entry({ id: "alpha" }), sharedReference],
+ })
+ ).resolves.toMatchObject({
+ documents: [{ _id: "alpha" }, { _id: "beta" }],
+ });
+ await expect(
+ createAssetIndex({
+ projectId: "project",
+ entries: [
+ { ...entry({ id: "alpha" }), content: "alpha" },
+ { ...sharedReference, content: "beta" },
+ ],
+ })
+ ).rejects.toThrow("conflicting content for one reference");
+
+ const index = await createAssetIndex({
+ projectId: "project",
+ entries: [entry({ id: "alpha" })],
+ });
+ await expect(
+ verifyContentArtifact({
+ ...index,
+ documents: [{ ...index.documents[0], name: "changed.md" }],
+ })
+ ).rejects.toThrow("checksum");
+ expect(serializeContentArtifact(index)).toContain(
+ '"webstudio-content-database"'
+ );
+ });
+
+ test("bounds the runtime database in creation order and continues after a document does not fit", async () => {
+ const createSizedEntry = ({
+ id,
+ createdAt,
+ bytes,
+ }: {
+ id: string;
+ createdAt: string;
+ bytes: number;
+ }) =>
+ createCanonicalAssetFileEntry({
+ projectId: "project",
+ document: {
+ ...entry({ id }).document,
+ createdAt,
+ properties: { content: "x".repeat(bytes) },
+ },
+ });
+ const entries = [
+ createSizedEntry({
+ id: "newest",
+ createdAt: "2026-07-27T00:00:00.000Z",
+ bytes: 1_000,
+ }),
+ createSizedEntry({
+ id: "middle-too-large",
+ createdAt: "2026-07-26T00:00:00.000Z",
+ bytes: 10_000,
+ }),
+ createSizedEntry({
+ id: "oldest-small",
+ createdAt: "2026-07-25T00:00:00.000Z",
+ bytes: 100,
+ }),
+ ];
+
+ const { artifact, diagnostics } = await compileContentArtifact({
+ projectId: "project",
+ entries,
+ maxBytes: 5_000,
+ plan: createContentCompilationPlan([
+ createLiteralContentCompilationQuery({
+ id: "blog",
+ query: {
+ where: { all: [] },
+ sort: [],
+ limit: 100,
+ offset: 0,
+ output: { mode: "all", includeMetadata: true },
+ content: { mode: "none" },
+ },
+ }),
+ ]),
+ });
+
+ expect(artifact.documents.map(({ _id }) => _id)).toEqual([
+ "newest",
+ "oldest-small",
+ ]);
+ expect(diagnostics).toMatchObject({
+ maxBytes: 5_000,
+ includedDocumentCount: 2,
+ omittedDocumentCount: 1,
+ omittedDocuments: [{ id: "middle-too-large", queryIds: ["blog"] }],
+ affectedQueryIds: ["blog"],
+ });
+ expect(diagnostics.largestDocuments[0]).not.toHaveProperty("queryIds");
+ expect(diagnostics.unboundedBytes).toBeGreaterThan(5_000);
+ expect(diagnostics.boundedBytes).toBeLessThanOrEqual(5_000);
+ expect(
+ createContentDatabase({
+ artifact,
+ readContent: async () => {
+ throw new Error("Content should not be read");
+ },
+ }).getStats()
+ ).toMatchObject({
+ usedBytes: diagnostics.boundedBytes,
+ maxBytes: 5_000,
+ includedDocumentCount: 2,
+ omittedDocumentCount: 1,
+ truncated: true,
+ });
+ expect(contentEngineLimits.databaseBytes).toBe(500 * 1024);
+ expect(parseContentDatabaseMaxBytes(undefined)).toBe(500 * 1024);
+ expect(parseContentDatabaseMaxBytes("2048")).toBe(2048);
+ expect(() => parseContentDatabaseMaxBytes("invalid")).toThrow(
+ "CONTENT_DATABASE_MAX_BYTES"
+ );
+ });
+
+ test("counts embedded bodies and accepts an exact serialized boundary", async () => {
+ const entries = [
+ { ...entry({ id: "alpha" }), content: "a".repeat(1_000) },
+ { ...entry({ id: "beta" }), content: "b".repeat(1_000) },
+ ];
+ const initial = await compileContentArtifact({
+ projectId: "project",
+ entries,
+ maxBytes: 10_000,
+ });
+ const exact = await compileContentArtifact({
+ projectId: "project",
+ entries,
+ maxBytes: initial.diagnostics.unboundedBytes,
+ });
+
+ expect(exact.diagnostics.omittedDocumentCount).toBe(0);
+ expect(exact.diagnostics.boundedBytes).toBe(
+ exact.diagnostics.unboundedBytes
+ );
+ expect(exact.artifact.contents).toEqual({
+ "files/alpha.md": "a".repeat(1_000),
+ "files/beta.md": "b".repeat(1_000),
+ });
+ expect(
+ (
+ await compileContentArtifact({
+ projectId: "project",
+ entries,
+ maxBytes: exact.diagnostics.unboundedBytes - 1,
+ })
+ ).diagnostics.omittedDocumentCount
+ ).toBeGreaterThan(0);
+ });
+
+ test("omits documents when their requested content was not materialized", async () => {
+ const plan = createContentCompilationPlan([
+ createLiteralContentCompilationQuery({
+ id: "detail",
+ query: {
+ where: { all: [] },
+ sort: [],
+ limit: 20,
+ offset: 0,
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["id"]],
+ },
+ content: { mode: "full" },
+ },
+ }),
+ ]);
+ const missing = {
+ ...entry({ id: "missing" }),
+ contentRequired: true as const,
+ };
+ const available = {
+ ...entry({ id: "available" }),
+ contentRequired: true as const,
+ content: "Available",
+ };
+
+ const { artifact, diagnostics } = await compileContentArtifact({
+ projectId: "project",
+ entries: [missing, available],
+ plan,
+ });
+
+ expect(artifact.documents.map(({ _id }) => _id)).toEqual(["available"]);
+ expect(artifact.contents).toEqual({
+ "files/available.md": "Available",
+ });
+ expect(diagnostics).toMatchObject({
+ includedDocumentCount: 1,
+ omittedDocumentCount: 1,
+ omittedDocuments: [{ id: "missing", queryIds: ["detail"] }],
+ affectedQueryIds: ["detail"],
+ });
+ expect(diagnostics.unboundedBytes).toBeGreaterThan(
+ diagnostics.boundedBytes
+ );
+ });
+
+ test("bounds a thousand oversized documents without rebuilding per document", async () => {
+ const entries = Array.from({ length: 1_000 }, (_, index) =>
+ createCanonicalAssetFileEntry({
+ projectId: "project",
+ document: {
+ ...entry({ id: String(index) }).document,
+ createdAt: new Date(Date.UTC(2026, 0, 1, 0, 0, index)).toISOString(),
+ properties: { payload: "x".repeat(3_000) },
+ },
+ })
+ );
+
+ const { artifact, diagnostics } = await compileContentArtifact({
+ projectId: "project",
+ entries,
+ });
+
+ expect(artifact.documents.length).toBeGreaterThan(0);
+ expect(diagnostics.omittedDocumentCount).toBeGreaterThan(0);
+ expect(diagnostics.boundedBytes).toBeLessThanOrEqual(
+ contentEngineLimits.databaseBytes
+ );
+ }, 10_000);
+
+ test("uses a query-scoped content reader without retaining it", async () => {
+ const index = await createAssetIndex({
+ projectId: "project",
+ entries: [entry({ id: "alpha" })],
+ });
+ const database = createContentDatabase({ artifact: index });
+ const content = "Alpha content padded";
+ const readContent = async () => ({
+ data: new Blob([
+ content,
+ ]).stream() as unknown as AsyncIterable<Uint8Array>,
+ contentLength: content.length,
+ });
+
+ const result = await database.query(
+ {
+ query: {
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["id"]],
+ },
+ content: { mode: "full" },
+ },
+ },
+ readContent
+ );
+ expect(result).toMatchObject({
+ items: [{ content: { text: content } }],
+ });
+ expect(result).not.toHaveProperty("database");
+ expect(result).not.toHaveProperty("__diagnostics__");
+ expect(assetQueryResult.safeParse(result).success).toBe(true);
+ await expect(
+ database.query({
+ query: {
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["id"]],
+ },
+ content: { mode: "full" },
+ },
+ })
+ ).rejects.toThrow("Content is not embedded");
+ });
+});
diff --git a/packages/content-engine/src/asset-index.ts b/packages/content-engine/src/asset-index.ts
new file mode 100644
index 0000000000..3624ba1f11
--- /dev/null
+++ b/packages/content-engine/src/asset-index.ts
@@ -0,0 +1,388 @@
+import {
+ compareStrings,
+ serializeJsonDeterministically,
+} from "./canonical-json";
+import { contentArtifactV1, type ContentArtifactV1 } from "./schema";
+import type { CanonicalAssetFileEntry } from "./canonical";
+import {
+ createAssetFieldCatalog,
+ toBuilderAssetFieldCatalog,
+} from "./field-catalog";
+import {
+ checksumContentArtifact,
+ serializeContentArtifact,
+} from "./content-artifact";
+import { contentEngineLimits } from "./limits";
+import {
+ getContentDocumentCandidateQueryIds,
+ compareContentEntryPriority,
+ isContentCompilationFieldRequired,
+ projectContentDatabaseDocument,
+ type ContentCompilationPlan,
+} from "./compilation-plan";
+import { getUtf8ByteLength } from "./byte-stream";
+import type { MarkdownAssetReferences } from "./markdown-references";
+
+export type ContentCompilerDiagnostics = {
+ maxBytes: number;
+ unboundedBytes: number;
+ boundedBytes: number;
+ includedDocumentCount: number;
+ omittedDocumentCount: number;
+ omittedDocuments: Array<{
+ id: string;
+ path: string;
+ bytes: number;
+ queryIds: string[];
+ }>;
+ largestDocuments: Array<{ id: string; path: string; bytes: number }>;
+ affectedQueryIds: string[];
+};
+
+const getDocumentBytes = (
+ entry: CanonicalAssetFileEntry,
+ plan?: ContentCompilationPlan
+) =>
+ getUtf8ByteLength(
+ serializeJsonDeterministically(
+ projectContentDatabaseDocument({ document: entry.document, plan })
+ )
+ );
+
+export type ContentCompilerInput = CanonicalAssetFileEntry & {
+ content?: string;
+ contentRequired?: true;
+};
+
+const getEntryBytes = (
+ entry: ContentCompilerInput,
+ plan?: ContentCompilationPlan
+) =>
+ getDocumentBytes(entry, plan) +
+ (entry.content === undefined
+ ? entry.contentRequired === true
+ ? entry.document.size
+ : 0
+ : getUtf8ByteLength(entry.content));
+
+const getMinimumAdditionalBytes = ({
+ entries,
+ selectedContentRefs,
+ plan,
+}: {
+ entries: readonly ContentCompilerInput[];
+ selectedContentRefs: ReadonlySet<string>;
+ plan?: ContentCompilationPlan;
+}) => {
+ const contentRefs = new Set(selectedContentRefs);
+ let bytes = 0;
+ for (const entry of entries) {
+ bytes += getDocumentBytes(entry, plan);
+ if (
+ entry.content !== undefined &&
+ contentRefs.has(entry.document.contentRef) === false
+ ) {
+ contentRefs.add(entry.document.contentRef);
+ bytes += getUtf8ByteLength(entry.content);
+ }
+ }
+ return bytes;
+};
+
+const validateEntries = ({
+ projectId,
+ entries,
+}: {
+ projectId: string;
+ entries: readonly ContentCompilerInput[];
+}) => {
+ const assetIds = new Set<string>();
+ const contentByRef = new Map<string, string>();
+ for (const entry of entries) {
+ if (entry.projectId !== projectId) {
+ throw new Error("Content database cannot combine multiple projects");
+ }
+ if (
+ entry.assetId !== entry.document._id ||
+ entry.revision !== entry.document.revision
+ ) {
+ throw new Error("Canonical content metadata identity is inconsistent");
+ }
+ if (assetIds.has(entry.assetId)) {
+ throw new Error("Content database contains duplicate documents");
+ }
+ assetIds.add(entry.assetId);
+ if (entry.content === undefined) {
+ continue;
+ }
+ const previousContent = contentByRef.get(entry.document.contentRef);
+ if (previousContent !== undefined && previousContent !== entry.content) {
+ throw new Error(
+ "Content database contains conflicting content for one reference"
+ );
+ }
+ contentByRef.set(entry.document.contentRef, entry.content);
+ }
+};
+
+const buildAssetIndex = async ({
+ entries,
+ sourceDocumentCount,
+ maxBytes,
+ unboundedBytes,
+ assetReferences,
+ plan,
+ finalize = true,
+}: {
+ entries: readonly ContentCompilerInput[];
+ sourceDocumentCount: number;
+ maxBytes: number;
+ unboundedBytes: number;
+ assetReferences?: MarkdownAssetReferences;
+ plan?: ContentCompilationPlan;
+ finalize?: boolean;
+}) => {
+ const documents = entries
+ .map(({ document }) => projectContentDatabaseDocument({ document, plan }))
+ .sort((left, right) => compareStrings(left._id, right._id));
+ const contents = Object.fromEntries(
+ entries
+ .filter(
+ (entry): entry is ContentCompilerInput & { content: string } =>
+ entry.content !== undefined
+ )
+ .sort((left, right) =>
+ compareStrings(left.document.contentRef, right.document.contentRef)
+ )
+ .map((entry) => [entry.document.contentRef, entry.content])
+ );
+ const includedContentRefs = new Set(
+ entries.map(({ document }) => document.contentRef)
+ );
+ const includedAssetReferences = Object.fromEntries(
+ Object.entries(assetReferences ?? {}).filter(([contentRef]) =>
+ includedContentRefs.has(contentRef)
+ )
+ );
+ const catalog = await createAssetFieldCatalog(entries);
+ const assetRevision = catalog.canonicalRevision;
+ const completeFieldCatalog = toBuilderAssetFieldCatalog(catalog);
+ const fieldCatalog = {
+ ...completeFieldCatalog,
+ fields: Object.fromEntries(
+ Object.entries(completeFieldCatalog.fields).filter(([, field]) => {
+ const queryPath = field.queryPath;
+ return (
+ queryPath !== undefined &&
+ isContentCompilationFieldRequired({ plan, field: queryPath })
+ );
+ })
+ ),
+ };
+ const index = contentArtifactV1.parse({
+ format: "webstudio-content-database",
+ version: 1,
+ assetRevision,
+ documents,
+ ...(Object.keys(contents).length === 0 ? {} : { contents }),
+ ...(Object.keys(includedAssetReferences).length === 0
+ ? {}
+ : { assetReferences: includedAssetReferences }),
+ fieldCatalog,
+ database: { maxBytes, unboundedBytes, sourceDocumentCount },
+ integrity: {
+ algorithm: "sha256",
+ checksum: `sha256:${"0".repeat(64)}`,
+ },
+ });
+ if (finalize === false) {
+ return index;
+ }
+ return contentArtifactV1.parse({
+ ...index,
+ integrity: {
+ algorithm: "sha256",
+ checksum: await checksumContentArtifact(index),
+ },
+ });
+};
+
+export const compileContentArtifact = async ({
+ projectId,
+ entries,
+ maxBytes = contentEngineLimits.databaseBytes,
+ assetReferences,
+ plan,
+}: {
+ projectId: string;
+ entries: readonly ContentCompilerInput[];
+ maxBytes?: number;
+ assetReferences?: MarkdownAssetReferences;
+ plan?: ContentCompilationPlan;
+}): Promise<{
+ artifact: ContentArtifactV1;
+ diagnostics: ContentCompilerDiagnostics;
+}> => {
+ if (Number.isSafeInteger(maxBytes) === false || maxBytes <= 0) {
+ throw new Error("Content database byte limit must be a positive integer");
+ }
+ validateEntries({ projectId, entries });
+ const sourceDocumentCount = entries.length;
+ const unavailable = entries.filter(
+ (entry) => entry.contentRequired === true && entry.content === undefined
+ );
+ const available = entries.filter(
+ (entry) => entry.contentRequired !== true || entry.content !== undefined
+ );
+ const unavailableBytes = unavailable.reduce(
+ (total, entry) => total + getEntryBytes(entry, plan),
+ 0
+ );
+ let unboundedBytes = 0;
+ let unbounded: ContentArtifactV1;
+ for (let attempt = 0; ; attempt += 1) {
+ unbounded = await buildAssetIndex({
+ entries: available,
+ sourceDocumentCount,
+ maxBytes,
+ unboundedBytes,
+ assetReferences,
+ plan,
+ finalize: false,
+ });
+ const measured =
+ getUtf8ByteLength(serializeContentArtifact(unbounded)) + unavailableBytes;
+ if (measured === unboundedBytes) {
+ break;
+ }
+ if (attempt >= 4) {
+ throw new Error("Content database size did not stabilize");
+ }
+ unboundedBytes = measured;
+ }
+ const selected: ContentCompilerInput[] = [];
+ const omitted: ContentCompilerInput[] = [...unavailable];
+ if (unboundedBytes <= maxBytes) {
+ selected.push(...available);
+ } else {
+ const prioritized = [...available].sort(compareContentEntryPriority);
+ let selectedContentRefs = new Set<string>();
+ const emptyArtifact = await buildAssetIndex({
+ entries: selected,
+ sourceDocumentCount,
+ maxBytes,
+ unboundedBytes,
+ assetReferences,
+ plan,
+ finalize: false,
+ });
+ let selectedBytes = getUtf8ByteLength(
+ serializeContentArtifact(emptyArtifact)
+ );
+ if (selectedBytes > maxBytes) {
+ throw new Error("Content database byte limit is too small");
+ }
+
+ const selectCandidates = async (
+ candidates: readonly ContentCompilerInput[]
+ ): Promise<void> => {
+ if (candidates.length === 0) {
+ return;
+ }
+ const minimumAdditionalBytes = getMinimumAdditionalBytes({
+ entries: candidates,
+ selectedContentRefs,
+ plan,
+ });
+ if (minimumAdditionalBytes <= maxBytes - selectedBytes) {
+ const trial = await buildAssetIndex({
+ entries: [...selected, ...candidates],
+ sourceDocumentCount,
+ maxBytes,
+ unboundedBytes,
+ assetReferences,
+ plan,
+ finalize: false,
+ });
+ const trialBytes = getUtf8ByteLength(serializeContentArtifact(trial));
+ if (trialBytes <= maxBytes) {
+ selected.push(...candidates);
+ selectedBytes = trialBytes;
+ selectedContentRefs = new Set(
+ selected
+ .filter(({ content }) => content !== undefined)
+ .map(({ document }) => document.contentRef)
+ );
+ return;
+ }
+ }
+ if (candidates.length === 1) {
+ omitted.push(candidates[0]);
+ return;
+ }
+ const middle = Math.floor(candidates.length / 2);
+ await selectCandidates(candidates.slice(0, middle));
+ await selectCandidates(candidates.slice(middle));
+ };
+
+ await selectCandidates(prioritized);
+ }
+ const artifact = await buildAssetIndex({
+ entries: selected,
+ sourceDocumentCount,
+ maxBytes,
+ unboundedBytes,
+ assetReferences,
+ plan,
+ });
+ const boundedBytes = getUtf8ByteLength(serializeContentArtifact(artifact));
+ if (boundedBytes > maxBytes) {
+ throw new Error("Content database selection exceeds the byte limit");
+ }
+ const describe = (entry: ContentCompilerInput) => ({
+ id: entry.assetId,
+ path: entry.document.path,
+ bytes: getEntryBytes(entry, plan),
+ });
+ const omittedDocuments = omitted.map((entry) => ({
+ ...describe(entry),
+ queryIds:
+ plan === undefined
+ ? []
+ : getContentDocumentCandidateQueryIds({
+ document: entry.document,
+ plan,
+ available: "all",
+ }),
+ }));
+ return {
+ artifact,
+ diagnostics: {
+ maxBytes,
+ unboundedBytes,
+ boundedBytes,
+ includedDocumentCount: selected.length,
+ omittedDocumentCount: omitted.length,
+ omittedDocuments,
+ largestDocuments: [...entries]
+ .sort(
+ (left, right) =>
+ getEntryBytes(right, plan) - getEntryBytes(left, plan)
+ )
+ .slice(0, 10)
+ .map(describe),
+ affectedQueryIds: [
+ ...new Set(omittedDocuments.flatMap(({ queryIds }) => queryIds)),
+ ].sort(compareStrings),
+ },
+ };
+};
+
+export const createAssetIndex = async (input: {
+ projectId: string;
+ entries: readonly ContentCompilerInput[];
+ maxBytes?: number;
+ assetReferences?: MarkdownAssetReferences;
+ plan?: ContentCompilationPlan;
+}): Promise<ContentArtifactV1> =>
+ (await compileContentArtifact(input)).artifact;
diff --git a/packages/content-engine/src/asset-path.ts b/packages/content-engine/src/asset-path.ts
new file mode 100644
index 0000000000..a6708be740
--- /dev/null
+++ b/packages/content-engine/src/asset-path.ts
@@ -0,0 +1,21 @@
+// Asset and folder names are user data, not filesystem paths. Encode each name
+// independently so slashes and dot segments cannot change path structure while
+// preserving the original name in the document for display and exact matching.
+export const encodeAssetPathSegment = (segment: string) => {
+ const encoded = encodeURIComponent(segment);
+ if (encoded === ".") {
+ return "%2E";
+ }
+ if (encoded === "..") {
+ return "%2E%2E";
+ }
+ return encoded;
+};
+
+export const createCanonicalAssetPath = ({
+ folderNames,
+ name,
+}: {
+ folderNames: readonly string[];
+ name: string;
+}) => [...folderNames, name].map(encodeAssetPathSegment).join("/");
diff --git a/packages/content-engine/src/async-utils.test.ts b/packages/content-engine/src/async-utils.test.ts
new file mode 100644
index 0000000000..45d58944e6
--- /dev/null
+++ b/packages/content-engine/src/async-utils.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, test } from "vitest";
+import { mapBounded } from "./async-utils";
+
+describe("bounded async work", () => {
+ test("limits concurrency and preserves result order", async () => {
+ let active = 0;
+ let maximumActive = 0;
+ const releases: Array<() => void> = [];
+ const pending = mapBounded([3, 2, 1], 2, async (value) => {
+ active += 1;
+ maximumActive = Math.max(maximumActive, active);
+ await new Promise<void>((resolve) => releases.push(resolve));
+ active -= 1;
+ return value * 2;
+ });
+
+ await expect.poll(() => releases.length).toBe(2);
+ releases.shift()?.();
+ await expect.poll(() => releases.length).toBe(2);
+ releases.shift()?.();
+ releases.shift()?.();
+
+ await expect(pending).resolves.toEqual([6, 4, 2]);
+ expect(maximumActive).toBe(2);
+ });
+
+ test("rejects invalid concurrency instead of silently skipping work", async () => {
+ await expect(mapBounded([1], 0, async () => {})).rejects.toThrow(
+ "Concurrency must be a positive safe integer"
+ );
+ });
+
+ test("waits for every started worker before propagating a failure", async () => {
+ let release: (() => void) | undefined;
+ let completed = false;
+ let rejected = false;
+ const pending = mapBounded(["fail", "slow"], 2, async (value) => {
+ if (value === "fail") {
+ throw new Error("failed");
+ }
+ await new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ completed = true;
+ return value;
+ });
+ const observed = pending.catch((error) => {
+ rejected = true;
+ throw error;
+ });
+
+ await expect.poll(() => release).toBeTypeOf("function");
+ expect(rejected).toBe(false);
+ release?.();
+
+ await expect(observed).rejects.toThrow("failed");
+ expect(completed).toBe(true);
+ });
+});
diff --git a/packages/content-engine/src/async-utils.ts b/packages/content-engine/src/async-utils.ts
new file mode 100644
index 0000000000..fed7b685ff
--- /dev/null
+++ b/packages/content-engine/src/async-utils.ts
@@ -0,0 +1,31 @@
+export const mapBounded = async <Value, Result>(
+ values: readonly Value[],
+ concurrency: number,
+ run: (value: Value) => Promise<Result>
+) => {
+ if (Number.isSafeInteger(concurrency) === false || concurrency <= 0) {
+ throw new Error("Concurrency must be a positive safe integer");
+ }
+ let cursor = 0;
+ const results = new Array<Result>(values.length);
+ const worker = async () => {
+ while (cursor < values.length) {
+ const index = cursor;
+ cursor += 1;
+ results[index] = await run(values[index]);
+ }
+ };
+ const workers = Array.from(
+ { length: Math.min(concurrency, values.length) },
+ worker
+ );
+ const settlements = await Promise.allSettled(workers);
+ const failure = settlements.find(
+ (settlement): settlement is PromiseRejectedResult =>
+ settlement.status === "rejected"
+ );
+ if (failure !== undefined) {
+ throw failure.reason;
+ }
+ return results;
+};
diff --git a/packages/content-engine/src/blog-e2e.test.ts b/packages/content-engine/src/blog-e2e.test.ts
new file mode 100644
index 0000000000..7bd317be56
--- /dev/null
+++ b/packages/content-engine/src/blog-e2e.test.ts
@@ -0,0 +1,115 @@
+import { describe, expect, test } from "vitest";
+import type { AssetFileDocument } from "./schema";
+import { createAssetIndex } from "./asset-index";
+import { createCanonicalAssetFileEntry } from "./canonical";
+import { createPublishedAssetResourceFetch } from "./published-runtime";
+import { discoverMarkdownAssetReferenceRanges } from "./markdown-assets";
+
+const postContent = "# Hello\n\n![Hero](../images/hero.png)";
+
+const document: AssetFileDocument = {
+ _id: "post-1",
+ _type: "asset.file",
+ name: "hello.md",
+ path: "blog/hello.md",
+ key: "hello",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: postContent.length,
+ revision: "post-1-revision",
+ contentRef: "hello.md",
+ properties: {
+ title: "Hello",
+ slug: "hello",
+ publishedAt: "2026-07-18",
+ draft: false,
+ },
+ excerpt: "Excerpt",
+};
+
+describe("published Markdown blog end-to-end", () => {
+ test("lists metadata and hydrates one detail from the same index", async () => {
+ const index = await createAssetIndex({
+ projectId: "project-1",
+ entries: [
+ {
+ ...createCanonicalAssetFileEntry({
+ projectId: "project-1",
+ document,
+ }),
+ content: postContent,
+ },
+ ],
+ assetReferences: {
+ "hello.md": discoverMarkdownAssetReferenceRanges({
+ markdown: postContent,
+ sourcePath: document.path,
+ assetIdsByPath: new Map([["images/hero.png", "hero-image"]]),
+ }),
+ },
+ });
+ const runtimeFetch = createPublishedAssetResourceFetch({
+ baseUrl: "https://blog.example",
+ deploymentId: "blog-deployment",
+ artifact: index,
+ runtimeAssets: {
+ "post-1": { url: "/assets/hello.md" },
+ "hero-image": { url: "/assets/hero.png", width: 1200, height: 630 },
+ },
+ });
+ const request = (query: unknown) =>
+ runtimeFetch("/$resources/assets", {
+ method: "POST",
+ body: JSON.stringify({ query }),
+ });
+
+ const listing = await request({
+ where: {
+ all: [
+ {
+ field: ["properties", "draft"],
+ operator: "ne",
+ value: true,
+ },
+ ],
+ },
+ sort: [{ field: ["properties", "publishedAt"], direction: "desc" }],
+ limit: 20,
+ output: { mode: "all", includeMetadata: true },
+ });
+ expect(await listing?.json()).toMatchObject({
+ items: [
+ {
+ excerpt: "Excerpt",
+ properties: { title: "Hello", slug: "hello" },
+ },
+ ],
+ });
+
+ const detail = await request({
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "hello",
+ },
+ ],
+ },
+ limit: 1,
+ output: { mode: "all", includeMetadata: true },
+ content: { mode: "markdown-body" },
+ });
+ expect(await detail?.json()).toMatchObject({
+ items: [
+ {
+ id: "post-1",
+ properties: { title: "Hello" },
+ content: {
+ text: expect.stringContaining("![Hero](/assets/hero.png)"),
+ },
+ },
+ ],
+ });
+ });
+});
diff --git a/packages/content-engine/src/byte-stream.ts b/packages/content-engine/src/byte-stream.ts
new file mode 100644
index 0000000000..e44ea0d655
--- /dev/null
+++ b/packages/content-engine/src/byte-stream.ts
@@ -0,0 +1,81 @@
+export type ByteSource = string | Uint8Array | AsyncIterable<Uint8Array>;
+
+const encoder = new TextEncoder();
+
+export const encodeUtf8 = (value: string) => encoder.encode(value);
+
+export const getUtf8ByteLength = (value: string) =>
+ encodeUtf8(value).byteLength;
+
+export class ByteLimitExceededError extends Error {
+ constructor() {
+ super("Byte stream exceeds the configured limit");
+ this.name = "ByteLimitExceededError";
+ }
+}
+
+const concatenateChunks = (chunks: readonly Uint8Array[], length: number) => {
+ const bytes = new Uint8Array(length);
+ let offset = 0;
+ for (const chunk of chunks) {
+ bytes.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return bytes;
+};
+
+export const toByteChunks = (source: ByteSource): AsyncIterable<Uint8Array> => {
+ if (typeof source === "string") {
+ return {
+ async *[Symbol.asyncIterator]() {
+ yield encodeUtf8(source);
+ },
+ };
+ }
+ if (source instanceof Uint8Array) {
+ return {
+ async *[Symbol.asyncIterator]() {
+ yield source;
+ },
+ };
+ }
+ return source;
+};
+
+export const readBytePrefix = async (
+ source: ByteSource,
+ maximumBytes: number
+) => {
+ const chunks: Uint8Array[] = [];
+ let length = 0;
+ for await (const chunk of toByteChunks(source)) {
+ const remaining = maximumBytes - length;
+ if (remaining <= 0) {
+ break;
+ }
+ const retained = chunk.subarray(0, remaining);
+ chunks.push(retained);
+ length += retained.byteLength;
+ if (length === maximumBytes) {
+ break;
+ }
+ }
+ return concatenateChunks(chunks, length);
+};
+
+export const readBoundedBytes = async (
+ source: ByteSource,
+ maximumBytes: number
+) => {
+ const bytes = await readBytePrefix(source, maximumBytes + 1);
+ if (bytes.byteLength > maximumBytes) {
+ throw new ByteLimitExceededError();
+ }
+ return bytes;
+};
+
+export const decodeUtf8 = (bytes: Uint8Array) =>
+ new TextDecoder("utf-8", { fatal: true }).decode(bytes);
+
+export const stripUtf8ByteOrderMark = (value: string) =>
+ value.charCodeAt(0) === 0xfeff ? value.slice(1) : value;
diff --git a/packages/content-engine/src/canonical-json.test.ts b/packages/content-engine/src/canonical-json.test.ts
new file mode 100644
index 0000000000..54de1913d9
--- /dev/null
+++ b/packages/content-engine/src/canonical-json.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, test } from "vitest";
+import {
+ normalizeJsonValue,
+ serializeJsonDeterministically,
+ sha256,
+ sha256Hex,
+ type JsonValue,
+} from "./canonical-json";
+
+describe("canonical JSON", () => {
+ test("omits optional object properties and preserves canonical values", () => {
+ const value = normalizeJsonValue({
+ omitted: undefined,
+ nested: { value: 1, omitted: undefined },
+ list: [true, null],
+ });
+
+ expect(value).toEqual({ nested: { value: 1 }, list: [true, null] });
+ expect(serializeJsonDeterministically(value)).toBe(
+ '{"list":[true,null],"nested":{"value":1}}'
+ );
+ });
+
+ test("rejects values JSON would otherwise mutate silently", () => {
+ expect(() => normalizeJsonValue([undefined])).toThrow("undefined");
+ const sparse: unknown[] = [];
+ sparse.length = 1;
+ expect(() => normalizeJsonValue(sparse)).toThrow("sparse");
+ const arrayWithProperty = [true] as boolean[] & { label?: string };
+ arrayWithProperty.label = "invalid";
+ expect(() => normalizeJsonValue(arrayWithProperty)).toThrow(
+ "named properties"
+ );
+ expect(() => normalizeJsonValue(Number.NaN)).toThrow("non-finite");
+ expect(() => normalizeJsonValue(new Date())).toThrow("plain objects");
+ expect(() => normalizeJsonValue({ value: () => undefined })).toThrow(
+ "represented as JSON"
+ );
+ expect(() => normalizeJsonValue("\ud800")).toThrow("Unicode surrogates");
+ expect(() => normalizeJsonValue({ "\udc00": true })).toThrow(
+ "Unicode surrogates"
+ );
+ expect(() => normalizeJsonValue({ [Symbol("key")]: true })).toThrow(
+ "symbol properties"
+ );
+ const circular: unknown[] = [];
+ circular.push(circular);
+ expect(() => normalizeJsonValue(circular)).toThrow("circular references");
+ });
+
+ test("preserves dangerous property names without changing prototypes", () => {
+ const value = normalizeJsonValue({
+ ["__proto__"]: { polluted: true },
+ constructor: "user value",
+ });
+
+ expect(Object.hasOwn(value as object, "__proto__")).toBe(true);
+ expect((value as Record<string, JsonValue>)["__proto__"]).toEqual({
+ polluted: true,
+ });
+ expect(Object.getPrototypeOf(value)).toBe(Object.prototype);
+ expect(({} as { polluted?: boolean }).polluted).toBeUndefined();
+ });
+
+ test("uses RFC 8785 number and UTF-16 property ordering", () => {
+ expect(
+ serializeJsonDeterministically({
+ literals: [null, true, false],
+ numbers: [333333333.33333329, 1e30, 4.5, 2e-3, 1e-27],
+ string: '€$\u000f\nA\'B"\\"/',
+ })
+ ).toBe(
+ '{"literals":[null,true,false],"numbers":[333333333.3333333,1e+30,4.5,0.002,1e-27],"string":"€$\\u000f\\nA\'B\\\"\\\\\\\"/"}'
+ );
+
+ expect(
+ serializeJsonDeterministically({
+ "\u20ac": "Euro Sign",
+ "\r": "Carriage Return",
+ "\ufb33": "Hebrew Letter Dalet With Dagesh",
+ "1": "One",
+ "😀": "Emoji: Grinning Face",
+ "\u0080": "Control",
+ ö: "Latin Small Letter O With Diaeresis",
+ })
+ ).toBe(
+ '{"\\r":"Carriage Return","1":"One","€":"Control","ö":"Latin Small Letter O With Diaeresis","€":"Euro Sign","😀":"Emoji: Grinning Face","דּ":"Hebrew Letter Dalet With Dagesh"}'
+ );
+ });
+
+ test("hashes strings, buffers, and views consistently", async () => {
+ const bytes = new TextEncoder().encode("hello");
+ const expected =
+ "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824";
+
+ await expect(sha256Hex("hello")).resolves.toBe(expected);
+ await expect(sha256Hex(bytes)).resolves.toBe(expected);
+ await expect(sha256Hex(bytes.buffer)).resolves.toBe(expected);
+ await expect(sha256("hello")).resolves.toBe(`sha256:${expected}`);
+ });
+});
diff --git a/packages/content-engine/src/canonical-json.ts b/packages/content-engine/src/canonical-json.ts
new file mode 100644
index 0000000000..e95c93edb1
--- /dev/null
+++ b/packages/content-engine/src/canonical-json.ts
@@ -0,0 +1,141 @@
+import canonicalize from "canonicalize";
+import { encodeUtf8 } from "./byte-stream";
+
+export type JsonPrimitive = string | number | boolean | null;
+export type JsonValue =
+ | JsonPrimitive
+ | readonly JsonValue[]
+ | { readonly [key: string]: JsonValue };
+
+type HashSource = string | ArrayBuffer | ArrayBufferView<ArrayBuffer>;
+
+const assertValidUnicode = (value: string) => {
+ for (let index = 0; index < value.length; index += 1) {
+ const codeUnit = value.charCodeAt(index);
+ if (codeUnit >= 0xd800 && codeUnit <= 0xdbff) {
+ const trailingCodeUnit = value.charCodeAt(index + 1);
+ if (
+ index + 1 >= value.length ||
+ trailingCodeUnit < 0xdc00 ||
+ trailingCodeUnit > 0xdfff
+ ) {
+ throw new Error("JSON strings cannot contain lone Unicode surrogates");
+ }
+ index += 1;
+ continue;
+ }
+ if (codeUnit >= 0xdc00 && codeUnit <= 0xdfff) {
+ throw new Error("JSON strings cannot contain lone Unicode surrogates");
+ }
+ }
+};
+
+const normalizeJsonValueInternal = (
+ value: unknown,
+ ancestors: Set<object>
+): JsonValue => {
+ if (value === null || typeof value === "boolean") {
+ return value;
+ }
+ if (typeof value === "string") {
+ assertValidUnicode(value);
+ return value;
+ }
+ if (typeof value === "number") {
+ if (Number.isFinite(value) === false) {
+ throw new Error("JSON cannot contain non-finite numbers");
+ }
+ return value;
+ }
+ if (Array.isArray(value)) {
+ if (Object.getOwnPropertySymbols(value).length > 0) {
+ throw new Error("JSON arrays cannot contain symbol properties");
+ }
+ if (ancestors.has(value)) {
+ throw new Error("JSON cannot contain circular references");
+ }
+ ancestors.add(value);
+ try {
+ const result: JsonValue[] = [];
+ for (let index = 0; index < value.length; index += 1) {
+ if (Object.hasOwn(value, index) === false) {
+ throw new Error("JSON arrays cannot be sparse");
+ }
+ const item = value[index];
+ if (item === undefined) {
+ throw new Error("JSON arrays cannot contain undefined values");
+ }
+ result.push(normalizeJsonValueInternal(item, ancestors));
+ }
+ if (Object.keys(value).length !== value.length) {
+ throw new Error("JSON arrays cannot contain named properties");
+ }
+ return result;
+ } finally {
+ ancestors.delete(value);
+ }
+ }
+ if (typeof value === "object") {
+ const prototype = Object.getPrototypeOf(value);
+ if (prototype !== Object.prototype && prototype !== null) {
+ throw new Error("JSON can contain only plain objects");
+ }
+ if (Object.getOwnPropertySymbols(value).length > 0) {
+ throw new Error("JSON objects cannot contain symbol properties");
+ }
+ if (ancestors.has(value)) {
+ throw new Error("JSON cannot contain circular references");
+ }
+ ancestors.add(value);
+ const result: Record<string, JsonValue> = {};
+ try {
+ for (const [key, item] of Object.entries(value)) {
+ assertValidUnicode(key);
+ if (item !== undefined) {
+ Object.defineProperty(result, key, {
+ value: normalizeJsonValueInternal(item, ancestors),
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ });
+ }
+ }
+ } finally {
+ ancestors.delete(value);
+ }
+ return result;
+ }
+ throw new Error("Value cannot be represented as JSON");
+};
+
+export const normalizeJsonValue = (value: unknown): JsonValue =>
+ normalizeJsonValueInternal(value, new Set());
+
+export const serializeJsonDeterministically = (value: unknown): string => {
+ const result = canonicalize(normalizeJsonValue(value));
+ if (result === undefined) {
+ throw new Error("Value cannot be represented as canonical JSON");
+ }
+ return result;
+};
+
+export const compareStrings = (left: string, right: string) => {
+ if (left < right) {
+ return -1;
+ }
+ if (left > right) {
+ return 1;
+ }
+ return 0;
+};
+
+export const sha256Hex = async (value: HashSource) => {
+ const source = typeof value === "string" ? encodeUtf8(value) : value;
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", source);
+ return Array.from(new Uint8Array(digest), (byte) =>
+ byte.toString(16).padStart(2, "0")
+ ).join("");
+};
+
+export const sha256 = async (value: HashSource) =>
+ `sha256:${await sha256Hex(value)}` as const;
diff --git a/packages/content-engine/src/canonical.test.ts b/packages/content-engine/src/canonical.test.ts
new file mode 100644
index 0000000000..f8768331f2
--- /dev/null
+++ b/packages/content-engine/src/canonical.test.ts
@@ -0,0 +1,257 @@
+import { describe, expect, test } from "vitest";
+import { contentEngineLimits } from "./limits";
+import {
+ createCanonicalAssetFileEntry,
+ getCanonicalAssetMetadataTier,
+ getCanonicalAssetMetadataRequirementsForTier,
+ getFieldContributions,
+ normalizeAssetFileDocument,
+ satisfiesCanonicalAssetMetadataRequirements,
+} from "./canonical";
+
+const asset = {
+ id: "asset-1",
+ name: "Hello.World.MD",
+ description: "Introduction",
+ folderId: "folder-blog",
+ folderNames: ["content", "blog"],
+ mimeType: "text/markdown",
+ size: 420,
+ revision: "sha256:content",
+ contentRef: "private:asset-1:sha256:content",
+};
+
+test("identifies and compares metadata cache tiers deterministically", () => {
+ expect(
+ getCanonicalAssetMetadataTier({
+ structuredProperties: false,
+ excerpt: false,
+ })
+ ).toBe("base");
+ expect(
+ getCanonicalAssetMetadataTier({
+ structuredProperties: true,
+ excerpt: false,
+ })
+ ).toBe("properties");
+ expect(
+ getCanonicalAssetMetadataTier({
+ structuredProperties: false,
+ excerpt: true,
+ })
+ ).toBe("excerpt");
+ expect(
+ getCanonicalAssetMetadataTier({
+ structuredProperties: true,
+ excerpt: true,
+ })
+ ).toBe("properties+excerpt");
+ expect(getCanonicalAssetMetadataRequirementsForTier("base")).toEqual({
+ structuredProperties: false,
+ excerpt: false,
+ });
+ expect(
+ getCanonicalAssetMetadataRequirementsForTier("properties+excerpt")
+ ).toEqual({ structuredProperties: true, excerpt: true });
+ expect(() => getCanonicalAssetMetadataRequirementsForTier("unknown")).toThrow(
+ "Canonical asset metadata tier is invalid"
+ );
+ expect(
+ satisfiesCanonicalAssetMetadataRequirements({
+ cached: { structuredProperties: true, excerpt: false },
+ required: { structuredProperties: false, excerpt: false },
+ })
+ ).toBe(true);
+ expect(
+ satisfiesCanonicalAssetMetadataRequirements({
+ cached: { structuredProperties: true, excerpt: false },
+ required: { structuredProperties: false, excerpt: true },
+ })
+ ).toBe(false);
+});
+
+describe("normalizeAssetFileDocument", () => {
+ test("derives normalized standard metadata", () => {
+ expect(
+ normalizeAssetFileDocument({
+ asset,
+ properties: { title: "Hello" },
+ excerpt: "Introduction",
+ })
+ ).toEqual({
+ _id: "asset-1",
+ _type: "asset.file",
+ name: "Hello.World.MD",
+ description: "Introduction",
+ path: "content/blog/Hello.World.MD",
+ key: "Hello.World",
+ folderId: "folder-blog",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 420,
+ revision: "sha256:content",
+ contentRef: "private:asset-1:sha256:content",
+ properties: { title: "Hello" },
+ excerpt: "Introduction",
+ });
+ });
+
+ test("keeps colliding frontmatter keys inside properties", () => {
+ const document = normalizeAssetFileDocument({
+ asset,
+ properties: {
+ _id: "frontmatter-id",
+ name: "frontmatter.md",
+ revision: "frontmatter-revision",
+ path: "other/path.md",
+ },
+ });
+
+ expect(document._id).toBe("asset-1");
+ expect(document.name).toBe("Hello.World.MD");
+ expect(document.revision).toBe("sha256:content");
+ expect(document.properties).toEqual({
+ _id: "frontmatter-id",
+ name: "frontmatter.md",
+ revision: "frontmatter-revision",
+ path: "other/path.md",
+ });
+ });
+
+ test("normalizes source timestamps with timezone offsets", () => {
+ expect(
+ normalizeAssetFileDocument({
+ asset: { ...asset, createdAt: "2026-07-27T16:40:49.007+00:00" },
+ properties: {},
+ }).createdAt
+ ).toBe("2026-07-27T16:40:49.007Z");
+ });
+
+ test.each([
+ [".", "%2E"],
+ ["..", "%2E%2E"],
+ ["nested/name", "nested%2Fname"],
+ ["nested\\name", "nested%5Cname"],
+ ])("encodes user-defined path segment %j", (name, path) => {
+ expect(
+ normalizeAssetFileDocument({
+ asset: { ...asset, name, folderId: undefined, folderNames: undefined },
+ properties: {},
+ }).path
+ ).toBe(path);
+ });
+
+ test("rejects an empty asset name", () => {
+ expect(() =>
+ normalizeAssetFileDocument({
+ asset: { ...asset, name: "" },
+ properties: {},
+ })
+ ).toThrow();
+ });
+
+ test("rejects JSON-incompatible property values", () => {
+ expect(() =>
+ normalizeAssetFileDocument({
+ asset,
+ properties: { publishedAt: new Date() },
+ })
+ ).toThrow();
+ });
+
+ test("requires folder identity and path together", () => {
+ expect(() =>
+ normalizeAssetFileDocument({
+ asset: { ...asset, folderNames: undefined },
+ properties: {},
+ })
+ ).toThrow("provided together");
+ expect(() =>
+ normalizeAssetFileDocument({
+ asset: { ...asset, folderId: undefined },
+ properties: {},
+ })
+ ).toThrow("provided together");
+ });
+
+ test("normalizes root assets without a folder field", () => {
+ const document = normalizeAssetFileDocument({
+ asset: { ...asset, folderId: undefined, folderNames: undefined },
+ properties: {},
+ });
+ expect(document.path).toBe("Hello.World.MD");
+ expect(document).not.toHaveProperty("folderId");
+ });
+});
+
+describe("field contributions", () => {
+ test("records deterministic nested paths and mixed array element types", () => {
+ expect(
+ getFieldContributions({
+ title: "Post",
+ author: { name: "Oleg", social: { active: true } },
+ authors: [{ name: "Ada" }, { name: "Ben" }, "Guest"],
+ ratings: [5, null, 4],
+ })
+ ).toEqual([
+ { path: "properties.author", type: "object" },
+ { path: "properties.author.name", type: "string" },
+ { path: "properties.author.social", type: "object" },
+ { path: "properties.author.social.active", type: "boolean" },
+ { path: "properties.authors", type: "array" },
+ { path: "properties.authors[]", type: "object" },
+ { path: "properties.authors[]", type: "string" },
+ { path: "properties.authors[].name", type: "string" },
+ { path: "properties.ratings", type: "array" },
+ { path: "properties.ratings[]", type: "null" },
+ { path: "properties.ratings[]", type: "number" },
+ { path: "properties.title", type: "string" },
+ ]);
+ });
+
+ test("deduplicates repeated types within one file", () => {
+ expect(getFieldContributions({ tags: ["one", "two", "three"] })).toEqual([
+ { path: "properties.tags", type: "array" },
+ { path: "properties.tags[]", type: "string" },
+ ]);
+ });
+
+ test("uses unambiguous catalog paths for non-identifier property names", () => {
+ expect(
+ getFieldContributions({
+ "author.name": "literal dot",
+ "publish-date": "2026-07-18",
+ nested: { "display name": "Oleg" },
+ })
+ ).toEqual([
+ { path: "properties.nested", type: "object" },
+ { path: 'properties.nested["display name"]', type: "string" },
+ { path: 'properties["author.name"]', type: "string" },
+ { path: 'properties["publish-date"]', type: "string" },
+ ]);
+ });
+
+ test("derives field contributions from canonical properties", () => {
+ const document = normalizeAssetFileDocument({
+ asset,
+ properties: { author: { name: "Oleg" } },
+ });
+ expect(getFieldContributions(document.properties)).toEqual([
+ { path: "properties.author", type: "object" },
+ { path: "properties.author.name", type: "string" },
+ ]);
+ });
+
+ test("rejects oversized persisted properties at the canonical boundary", () => {
+ const document = normalizeAssetFileDocument({
+ asset,
+ properties: {
+ content: "x".repeat(contentEngineLimits.indexedPropertiesBytes),
+ },
+ });
+
+ expect(() =>
+ createCanonicalAssetFileEntry({ projectId: "project-1", document })
+ ).toThrow("indexed byte limit");
+ });
+});
diff --git a/packages/content-engine/src/canonical.ts b/packages/content-engine/src/canonical.ts
new file mode 100644
index 0000000000..e807d42e6e
--- /dev/null
+++ b/packages/content-engine/src/canonical.ts
@@ -0,0 +1,320 @@
+import { assetFileDocument, type AssetFileDocument } from "./schema";
+import { contentEngineLimits } from "./limits";
+import { createCanonicalAssetPath } from "./asset-path";
+import { string } from "zod";
+import {
+ compareStrings,
+ serializeJsonDeterministically,
+} from "./canonical-json";
+import { getStructuredDataByteLength } from "./structured-data";
+
+export type AssetFileMetadataInput = {
+ id: string;
+ name: string;
+ description?: string;
+ extension?: string;
+ folderId?: string;
+ folderNames?: readonly string[];
+ mimeType: string;
+ size: number;
+ createdAt?: string;
+ revision: string;
+ contentRef: string;
+};
+
+const canonicalDateTime = string()
+ .datetime({ offset: true })
+ .transform((value) => new Date(value).toISOString());
+
+export type CanonicalAssetFileEntry = {
+ projectId: string;
+ assetId: string;
+ revision: string;
+ document: AssetFileDocument;
+ metadataRequirements?: CanonicalAssetMetadataRequirements;
+};
+
+export type CanonicalAssetMetadataRequirements = {
+ structuredProperties: boolean;
+ excerpt: boolean;
+};
+
+/**
+ * Generation of the Markdown/JSON extraction behavior used by persistent
+ * metadata caches. Increment only when unchanged source files must be parsed
+ * again because extraction semantics changed.
+ */
+export const canonicalAssetMetadataExtractorGeneration = 1;
+
+export const fullCanonicalAssetMetadataRequirements = {
+ structuredProperties: true,
+ excerpt: true,
+} as const satisfies CanonicalAssetMetadataRequirements;
+
+export const getCanonicalAssetMetadataRequirements = (
+ entry: CanonicalAssetFileEntry
+) => entry.metadataRequirements ?? fullCanonicalAssetMetadataRequirements;
+
+export type CanonicalAssetMetadataTier =
+ | "base"
+ | "properties"
+ | "excerpt"
+ | "properties+excerpt";
+
+/** Stable cache identity for the four supported metadata preparation tiers. */
+export const getCanonicalAssetMetadataTier = ({
+ structuredProperties,
+ excerpt,
+}: CanonicalAssetMetadataRequirements): CanonicalAssetMetadataTier => {
+ if (structuredProperties && excerpt) {
+ return "properties+excerpt";
+ }
+ if (structuredProperties) {
+ return "properties";
+ }
+ if (excerpt) {
+ return "excerpt";
+ }
+ return "base";
+};
+
+export const getCanonicalAssetMetadataRequirementsForTier = (
+ tier: unknown
+): CanonicalAssetMetadataRequirements => {
+ if (tier === "base") {
+ return { structuredProperties: false, excerpt: false };
+ }
+ if (tier === "properties") {
+ return { structuredProperties: true, excerpt: false };
+ }
+ if (tier === "excerpt") {
+ return { structuredProperties: false, excerpt: true };
+ }
+ if (tier === "properties+excerpt") {
+ return fullCanonicalAssetMetadataRequirements;
+ }
+ throw new Error("Canonical asset metadata tier is invalid");
+};
+
+export const satisfiesCanonicalAssetMetadataRequirements = ({
+ cached,
+ required,
+}: {
+ cached: CanonicalAssetMetadataRequirements;
+ required: CanonicalAssetMetadataRequirements;
+}) =>
+ (required.structuredProperties === false || cached.structuredProperties) &&
+ (required.excerpt === false || cached.excerpt);
+
+export type ObservedFieldType =
+ | "null"
+ | "boolean"
+ | "number"
+ | "string"
+ | "object"
+ | "array";
+
+export type FieldContribution = {
+ path: string;
+ type: ObservedFieldType;
+};
+
+const identifier = /^[A-Za-z_][A-Za-z0-9_]*$/;
+export const appendAssetFieldPath = (path: string, key: string) =>
+ identifier.test(key) ? `${path}.${key}` : `${path}[${JSON.stringify(key)}]`;
+
+export type AssetFieldPathSegment =
+ | { type: "field"; name: string }
+ | { type: "element" };
+
+export const getObservedFieldType = (value: unknown): ObservedFieldType => {
+ if (value === null) {
+ return "null";
+ }
+ if (Array.isArray(value)) {
+ return "array";
+ }
+ const type = typeof value;
+ if (type === "number") {
+ if (Number.isFinite(value) === false) {
+ throw new Error("Asset field contains a non-finite number");
+ }
+ return type;
+ }
+ if (type === "object") {
+ const prototype = Object.getPrototypeOf(value);
+ if (prototype !== Object.prototype && prototype !== null) {
+ throw new Error("Asset field contains a non-plain object");
+ }
+ return type;
+ }
+ if (type === "boolean" || type === "string") {
+ return type;
+ }
+ throw new Error("Asset field contains a non-JSON value");
+};
+
+const compareFieldPaths = (
+ left: AssetFieldPathSegment[],
+ right: AssetFieldPathSegment[]
+) => {
+ for (let index = 0; index < Math.min(left.length, right.length); index++) {
+ const leftSegment = left[index];
+ const rightSegment = right[index];
+ if (leftSegment.type !== rightSegment.type) {
+ return leftSegment.type === "field" ? -1 : 1;
+ }
+ if (leftSegment.type === "field" && rightSegment.type === "field") {
+ const result = compareStrings(leftSegment.name, rightSegment.name);
+ if (result !== 0) {
+ return result;
+ }
+ }
+ }
+ return left.length - right.length;
+};
+
+const getStructuralFieldContributions = (
+ fields: Readonly<Record<string, unknown>>
+) => {
+ const contributions = new Map<
+ string,
+ { path: AssetFieldPathSegment[]; type: ObservedFieldType }
+ >();
+ const add = (path: AssetFieldPathSegment[], value: unknown) => {
+ const contribution = { path, type: getObservedFieldType(value) };
+ contributions.set(
+ `${serializeJsonDeterministically(path)}\u0000${contribution.type}`,
+ contribution
+ );
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ add([...path, { type: "element" }], item);
+ }
+ return;
+ }
+ if (value !== null && typeof value === "object") {
+ for (const key of Object.keys(value).sort(compareStrings)) {
+ add(
+ [...path, { type: "field", name: key }],
+ (value as Record<string, unknown>)[key]
+ );
+ }
+ }
+ };
+ for (const key of Object.keys(fields).sort(compareStrings)) {
+ add([{ type: "field", name: key }], fields[key]);
+ }
+ return [...contributions.values()].sort(
+ (left, right) =>
+ compareFieldPaths(left.path, right.path) ||
+ compareStrings(left.type, right.type)
+ );
+};
+
+const formatFieldContributionPath = (path: AssetFieldPathSegment[]) => {
+ let formatted = "properties";
+ for (const segment of path) {
+ formatted =
+ segment.type === "element"
+ ? `${formatted}[]`
+ : appendAssetFieldPath(formatted, segment.name);
+ }
+ return formatted;
+};
+
+export const getFieldContributions = (
+ properties: AssetFileDocument["properties"]
+): FieldContribution[] =>
+ getStructuralFieldContributions(properties)
+ .map(({ path, type }) => ({
+ path: formatFieldContributionPath(path),
+ type,
+ }))
+ .sort(
+ (left, right) =>
+ compareStrings(left.path, right.path) ||
+ compareStrings(left.type, right.type)
+ );
+
+export const createCanonicalAssetFileEntry = ({
+ projectId,
+ document,
+ metadataRequirements = fullCanonicalAssetMetadataRequirements,
+}: {
+ projectId: string;
+ document: unknown;
+ metadataRequirements?: CanonicalAssetMetadataRequirements;
+}): CanonicalAssetFileEntry => {
+ const parsedDocument = assetFileDocument.parse(document);
+ if (
+ getStructuredDataByteLength(parsedDocument.properties) >
+ contentEngineLimits.indexedPropertiesBytes
+ ) {
+ throw new Error("Canonical asset properties exceed the indexed byte limit");
+ }
+ return {
+ projectId,
+ assetId: parsedDocument._id,
+ revision: parsedDocument.revision,
+ document: parsedDocument,
+ metadataRequirements,
+ };
+};
+
+/**
+ * Builds the canonical query document without merging user properties into the
+ * reserved standard metadata namespace.
+ */
+export const normalizeAssetFileDocument = ({
+ asset,
+ properties,
+ excerpt,
+ metadataError,
+}: {
+ asset: AssetFileMetadataInput;
+ properties: Record<string, unknown>;
+ excerpt?: string;
+ metadataError?: AssetFileDocument["metadataError"];
+}): AssetFileDocument => {
+ const folderNames = asset.folderNames ?? [];
+ if ((asset.folderId === undefined) !== (folderNames.length === 0)) {
+ throw new Error(
+ "Asset folder ID and complete folder-name path must be provided together"
+ );
+ }
+ const extensionSeparator = asset.name.lastIndexOf(".");
+ const extension =
+ asset.extension ??
+ (extensionSeparator === -1
+ ? ""
+ : asset.name.slice(extensionSeparator + 1).toLowerCase());
+ const key =
+ extensionSeparator <= 0
+ ? asset.name
+ : asset.name.slice(0, extensionSeparator);
+ const path = createCanonicalAssetPath({ folderNames, name: asset.name });
+
+ return assetFileDocument.parse({
+ _id: asset.id,
+ _type: "asset.file",
+ name: asset.name,
+ ...(asset.description === undefined
+ ? {}
+ : { description: asset.description }),
+ path,
+ key,
+ ...(asset.folderId === undefined ? {} : { folderId: asset.folderId }),
+ extension,
+ mimeType: asset.mimeType,
+ size: asset.size,
+ ...(asset.createdAt === undefined
+ ? {}
+ : { createdAt: canonicalDateTime.parse(asset.createdAt) }),
+ revision: asset.revision,
+ contentRef: asset.contentRef,
+ properties,
+ ...(excerpt === undefined ? {} : { excerpt }),
+ ...(metadataError === undefined ? {} : { metadataError }),
+ });
+};
diff --git a/packages/content-engine/src/compilation-plan.test.ts b/packages/content-engine/src/compilation-plan.test.ts
new file mode 100644
index 0000000000..d9120db254
--- /dev/null
+++ b/packages/content-engine/src/compilation-plan.test.ts
@@ -0,0 +1,405 @@
+import { describe, expect, test, vi } from "vitest";
+import {
+ createContentCompilationPlan,
+ hasDynamicContentCompilationValues,
+ createContentFieldCatalogCompilationPlan,
+ createLiteralContentCompilationQuery,
+ isContentDocumentCandidate,
+ prepareContentCompilerEntries,
+ requiresHydratedContent,
+ requiresRuntimeDocumentData,
+ requiresStructuredProperties,
+ selectContentHydrationCandidates,
+} from "./compilation-plan";
+import { assetQuery, type AssetFileDocument, type AssetQuery } from "./schema";
+import { createCanonicalAssetFileEntry } from "./canonical";
+
+test("field catalog plan requests properties without excerpts or bodies", () => {
+ expect(createContentFieldCatalogCompilationPlan()).toMatchObject({
+ structuredPropertyPaths: "all",
+ excerpt: false,
+ queries: [
+ {
+ where: { all: [] },
+ content: { mode: "none" },
+ },
+ ],
+ });
+});
+
+const query = assetQuery.parse({
+ where: { all: [] },
+ output: { mode: "base" as const, includeMetadata: true },
+});
+
+const compilationQuery = (id: string, value: AssetQuery = query) =>
+ createLiteralContentCompilationQuery({
+ id,
+ query: value,
+ });
+
+const document: AssetFileDocument = {
+ _id: "post",
+ _type: "asset.file",
+ name: "post.md",
+ path: "blog/post.md",
+ key: "post",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 100,
+ revision: "revision",
+ contentRef: "post.md",
+ properties: { draft: true },
+};
+
+describe("content compilation plan", () => {
+ test("keeps base-only queries free of parser and hydration work", () => {
+ const plan = createContentCompilationPlan([compilationQuery("base")]);
+ expect(plan).toEqual({
+ standardFields: [
+ ["createdAt"],
+ ["description"],
+ ["extension"],
+ ["folderId"],
+ ["id"],
+ ["key"],
+ ["mimeType"],
+ ["name"],
+ ["path"],
+ ["revision"],
+ ["size"],
+ ],
+ structuredPropertyPaths: [],
+ excerpt: false,
+ metadataError: true,
+ queries: [compilationQuery("base")],
+ });
+ expect(requiresStructuredProperties(plan!)).toBe(false);
+ expect(requiresHydratedContent(plan!)).toBe(false);
+ expect(requiresRuntimeDocumentData(plan!)).toBe(false);
+ });
+
+ test("derives structured, excerpt, and content requirements independently", () => {
+ const plan = createContentCompilationPlan([
+ compilationQuery("detail", {
+ ...query,
+ where: {
+ any: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq" as const,
+ value: "post",
+ },
+ ],
+ },
+ sort: [{ field: ["excerpt"], direction: "asc" as const }],
+ content: { mode: "markdown-body" as const },
+ }),
+ ]);
+ expect(plan).toMatchObject({ excerpt: true });
+ expect(requiresStructuredProperties(plan!)).toBe(true);
+ expect(requiresHydratedContent(plan!)).toBe(true);
+ });
+
+ test("detects runtime asset fields in filters, sorting, and output", () => {
+ const runtimeQueries = [
+ { where: { all: [{ field: ["width"], operator: "gte", value: 600 }] } },
+ { sort: [{ field: ["height"], direction: "desc" }] },
+ {
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["url"]],
+ },
+ },
+ ].map((value) => assetQuery.parse({ ...query, ...value }));
+ for (const value of runtimeQueries) {
+ const plan = createContentCompilationPlan([
+ compilationQuery("runtime", value),
+ ]);
+ expect(plan).toBeDefined();
+ expect(requiresRuntimeDocumentData(plan!)).toBe(true);
+ }
+ });
+
+ test("unions selected fields deterministically and returns no requirements for no queries", () => {
+ expect(createContentCompilationPlan([])).toBeUndefined();
+ expect(
+ createContentCompilationPlan([
+ compilationQuery("title", {
+ ...query,
+ output: {
+ mode: "fields",
+ includeMetadata: true,
+ fields: [["properties", "title"]],
+ },
+ }),
+ compilationQuery("excerpt", {
+ ...query,
+ output: {
+ mode: "fields",
+ includeMetadata: true,
+ fields: [["excerpt"], ["properties", "slug"]],
+ },
+ }),
+ ])
+ ).toEqual({
+ standardFields: [
+ ["createdAt"],
+ ["description"],
+ ["extension"],
+ ["folderId"],
+ ["id"],
+ ["key"],
+ ["mimeType"],
+ ["name"],
+ ["path"],
+ ["revision"],
+ ["size"],
+ ],
+ structuredPropertyPaths: [
+ ["properties", "slug"],
+ ["properties", "title"],
+ ],
+ excerpt: true,
+ metadataError: true,
+ queries: expect.any(Array),
+ });
+ });
+
+ test("treats all-fields output as the broadest requirement", () => {
+ expect(
+ createContentCompilationPlan([
+ compilationQuery("base"),
+ compilationQuery("all", {
+ ...query,
+ output: { mode: "all", includeMetadata: true },
+ }),
+ ])
+ ).toMatchObject({
+ structuredPropertyPaths: "all",
+ excerpt: true,
+ });
+ });
+
+ test("excludes files rejected by static filters without treating dynamic values as false", () => {
+ const staticQuery = createLiteralContentCompilationQuery({
+ id: "markdown",
+ query: {
+ ...query,
+ where: {
+ all: [
+ { field: ["extension"], operator: "eq", value: "md" },
+ {
+ field: ["properties", "draft"],
+ operator: "ne",
+ value: true,
+ },
+ ],
+ },
+ },
+ });
+ const plan = createContentCompilationPlan([staticQuery]);
+ expect(plan).toBeDefined();
+ if (plan === undefined) {
+ return;
+ }
+
+ expect(
+ isContentDocumentCandidate({ document, plan, available: "base" })
+ ).toBe(true);
+ expect(
+ isContentDocumentCandidate({ document, plan, available: "all" })
+ ).toBe(false);
+ expect(
+ isContentDocumentCandidate({
+ document: { ...document, extension: "json" },
+ plan,
+ available: "base",
+ })
+ ).toBe(false);
+
+ const dynamicPlan = createContentCompilationPlan([
+ {
+ ...staticQuery,
+ where: {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: { type: "dynamic" },
+ },
+ },
+ ]);
+ expect(dynamicPlan).toBeDefined();
+ if (dynamicPlan !== undefined) {
+ expect(
+ isContentDocumentCandidate({
+ document,
+ plan: dynamicPlan,
+ available: "all",
+ })
+ ).toBe(true);
+ }
+ });
+
+ test("hydrates only the statically selected window and keeps dynamic windows conservative", () => {
+ const documents = ["alpha", "beta", "gamma"].map((id, index) => ({
+ ...document,
+ _id: id,
+ name: `${id}.md`,
+ path: `blog/${id}.md`,
+ key: id,
+ revision: `revision-${id}`,
+ contentRef: `${id}.md`,
+ properties: { order: index },
+ }));
+ const staticPlan = createContentCompilationPlan([
+ compilationQuery("window", {
+ ...query,
+ sort: [{ field: ["properties", "order"], direction: "desc" }],
+ offset: 1,
+ limit: 1,
+ content: { mode: "full" },
+ }),
+ ]);
+ expect(staticPlan).toBeDefined();
+ if (staticPlan === undefined) {
+ return;
+ }
+ expect(
+ selectContentHydrationCandidates({ documents, plan: staticPlan })
+ ).toEqual(new Set(["beta"]));
+
+ const dynamicPlan = {
+ ...staticPlan,
+ queries: staticPlan.queries.map((item) => ({
+ ...item,
+ limit: { type: "dynamic" as const },
+ })),
+ };
+ expect(
+ selectContentHydrationCandidates({ documents, plan: dynamicPlan })
+ ).toEqual(new Set(["alpha", "beta", "gamma"]));
+
+ const runtimePlan = createContentCompilationPlan([
+ compilationQuery("runtime-window", {
+ ...query,
+ where: {
+ all: [{ field: ["width"], operator: "gte", value: 600 }],
+ },
+ sort: [{ field: ["width"], direction: "desc" }],
+ limit: 1,
+ content: { mode: "full" },
+ }),
+ ]);
+ expect(runtimePlan).toBeDefined();
+ if (runtimePlan !== undefined) {
+ expect(
+ isContentDocumentCandidate({
+ document,
+ plan: runtimePlan,
+ available: "all",
+ })
+ ).toBe(true);
+ expect(
+ selectContentHydrationCandidates({ documents, plan: runtimePlan })
+ ).toEqual(new Set(["alpha", "beta", "gamma"]));
+ }
+ });
+
+ test("reports dynamic filter and window values", () => {
+ const plan = createContentCompilationPlan([
+ {
+ ...compilationQuery("dynamic"),
+ where: {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: { type: "dynamic" },
+ },
+ },
+ ]);
+ expect(plan).toBeDefined();
+ if (plan === undefined) {
+ return;
+ }
+ expect(hasDynamicContentCompilationValues(plan)).toBe(true);
+ expect(
+ hasDynamicContentCompilationValues({
+ ...plan,
+ queries: plan.queries.map((item) => ({
+ ...item,
+ where: { all: [] },
+ })),
+ })
+ ).toBe(false);
+ expect(
+ hasDynamicContentCompilationValues({
+ ...plan,
+ queries: plan.queries.map((item) => ({
+ ...item,
+ where: { all: [] },
+ offset: { type: "dynamic" },
+ })),
+ })
+ ).toBe(true);
+ });
+
+ test("bounds content reads and marks unavailable required content", async () => {
+ const plan = createContentCompilationPlan([
+ compilationQuery("content", {
+ ...query,
+ content: { mode: "full" },
+ }),
+ ]);
+ expect(plan).toBeDefined();
+ if (plan === undefined) {
+ return;
+ }
+ const entries = [
+ { id: "newest", createdAt: "2026-07-30T00:00:00.000Z", ref: "shared" },
+ { id: "shared", createdAt: "2026-07-29T00:00:00.000Z", ref: "shared" },
+ { id: "omitted", createdAt: "2026-07-28T00:00:00.000Z", ref: "other" },
+ ].map(({ id, createdAt, ref }) =>
+ createCanonicalAssetFileEntry({
+ projectId: "project",
+ document: {
+ ...document,
+ _id: id,
+ name: `${id}.md`,
+ path: `blog/${id}.md`,
+ key: id,
+ size: 6,
+ createdAt,
+ revision: `revision-${id}`,
+ contentRef: ref,
+ },
+ })
+ );
+ const loadContent = vi.fn(async () => "shared");
+
+ const prepared = await prepareContentCompilerEntries({
+ entries,
+ plan,
+ maximumContentBytes: 6,
+ loadContent,
+ });
+
+ expect(loadContent).toHaveBeenCalledOnce();
+ expect(prepared).toEqual([
+ expect.objectContaining({
+ assetId: "newest",
+ content: "shared",
+ contentRequired: true,
+ }),
+ expect.objectContaining({
+ assetId: "shared",
+ content: "shared",
+ contentRequired: true,
+ }),
+ expect.objectContaining({
+ assetId: "omitted",
+ contentRequired: true,
+ }),
+ ]);
+ expect(prepared[2]).not.toHaveProperty("content");
+ });
+});
diff --git a/packages/content-engine/src/compilation-plan.ts b/packages/content-engine/src/compilation-plan.ts
new file mode 100644
index 0000000000..a82ba9ebfb
--- /dev/null
+++ b/packages/content-engine/src/compilation-plan.ts
@@ -0,0 +1,540 @@
+import {
+ getQueryConditions,
+ getQueryFieldKey,
+ evaluateQueryWhere,
+ mapQueryWhere,
+ type QueryWhereTree,
+} from "@webstudio-is/query-builder/runtime";
+import {
+ assetQueryFilter,
+ assetQueryMetadataFields,
+ isAssetQueryRuntimeField,
+ type AssetQuery,
+ type AssetFileDocument,
+ type ContentDatabaseDocument,
+ type AssetQueryFieldPath,
+ type AssetQueryOperator,
+ type AssetResourceOutputSelection,
+} from "./schema";
+import {
+ compareAssetQueryDocuments,
+ matchesAssetQueryFilter,
+} from "./structured-query";
+import { contentEngineLimits } from "./limits";
+import { selectAssetDocumentFields, selectAssetProperties } from "./projection";
+import type { CanonicalAssetFileEntry } from "./canonical";
+import { compareStrings } from "./canonical-json";
+
+export const compareContentEntryPriority = (
+ left: CanonicalAssetFileEntry,
+ right: CanonicalAssetFileEntry
+) => {
+ const leftCreatedAt =
+ left.document.createdAt === undefined
+ ? undefined
+ : Date.parse(left.document.createdAt);
+ const rightCreatedAt =
+ right.document.createdAt === undefined
+ ? undefined
+ : Date.parse(right.document.createdAt);
+ if (leftCreatedAt !== undefined && rightCreatedAt === undefined) {
+ return -1;
+ }
+ if (leftCreatedAt === undefined && rightCreatedAt !== undefined) {
+ return 1;
+ }
+ if (
+ leftCreatedAt !== undefined &&
+ rightCreatedAt !== undefined &&
+ leftCreatedAt !== rightCreatedAt
+ ) {
+ return rightCreatedAt - leftCreatedAt;
+ }
+ return (
+ compareStrings(left.document.path, right.document.path) ||
+ compareStrings(left.assetId, right.assetId)
+ );
+};
+
+export type ContentCompilationValue =
+ | { type: "literal"; value: unknown }
+ | { type: "dynamic" };
+
+export type ContentCompilationWhere = QueryWhereTree<{
+ field: AssetQueryFieldPath;
+ operator: AssetQueryOperator;
+ value: ContentCompilationValue;
+}>;
+
+export type ContentCompilationQuery = {
+ id: string;
+ where: ContentCompilationWhere;
+ sort: AssetQuery["sort"];
+ limit: ContentCompilationValue;
+ offset: ContentCompilationValue;
+ output: AssetResourceOutputSelection;
+ content: AssetQuery["content"];
+};
+
+export type ContentCompilationPlan = {
+ standardFields: "all" | AssetQueryFieldPath[];
+ structuredPropertyPaths: "all" | AssetQueryFieldPath[];
+ excerpt: boolean;
+ metadataError: boolean;
+ queries: ContentCompilationQuery[];
+};
+
+export const requiresStructuredProperties = (plan: ContentCompilationPlan) =>
+ plan.structuredPropertyPaths === "all" ||
+ plan.structuredPropertyPaths.length > 0;
+
+export const requiresHydratedContent = (plan: ContentCompilationPlan) =>
+ plan.queries.some(({ content }) => content.mode !== "none");
+
+const evaluateWhere = ({
+ document,
+ where,
+ available,
+}: {
+ document: AssetFileDocument;
+ where: ContentCompilationWhere;
+ available: "base" | "all";
+}): boolean | undefined => {
+ return evaluateQueryWhere(where, (condition) => {
+ if (
+ condition.value.type === "dynamic" ||
+ isAssetQueryRuntimeField(condition.field[0]) ||
+ (available === "base" &&
+ (condition.field[0] === "properties" ||
+ condition.field[0] === "excerpt"))
+ ) {
+ return;
+ }
+ const filter = assetQueryFilter.safeParse({
+ field: condition.field,
+ operator: condition.operator,
+ value: condition.value.value,
+ });
+ return filter.success
+ ? matchesAssetQueryFilter(document, filter.data)
+ : undefined;
+ });
+};
+
+export const getContentDocumentCandidateQueryIds = ({
+ document,
+ plan,
+ available,
+}: {
+ document: AssetFileDocument;
+ plan: ContentCompilationPlan;
+ available: "base" | "all";
+}) =>
+ plan.queries
+ .filter(
+ ({ where }) => evaluateWhere({ document, where, available }) !== false
+ )
+ .map(({ id }) => id);
+
+export const isContentDocumentCandidate = (input: {
+ document: AssetFileDocument;
+ plan: ContentCompilationPlan;
+ available: "base" | "all";
+}) => getContentDocumentCandidateQueryIds(input).length > 0;
+
+const hasDynamicWhere = (where: ContentCompilationWhere) =>
+ getQueryConditions(where).some(({ value }) => value.type === "dynamic");
+
+export const hasDynamicContentCompilationValues = (
+ plan: ContentCompilationPlan
+) =>
+ plan.queries.some(
+ ({ where, limit, offset }) =>
+ hasDynamicWhere(where) ||
+ limit.type === "dynamic" ||
+ offset.type === "dynamic"
+ );
+
+const usesRuntimeWhere = (where: ContentCompilationWhere) =>
+ getQueryConditions(where).some(({ field }) =>
+ isAssetQueryRuntimeField(field[0])
+ );
+
+export const selectContentHydrationCandidates = ({
+ documents,
+ plan,
+}: {
+ documents: readonly AssetFileDocument[];
+ plan: ContentCompilationPlan;
+}) => {
+ const selected = new Set<string>();
+ for (const query of plan.queries) {
+ if (query.content.mode === "none") {
+ continue;
+ }
+ const matched = documents.filter(
+ (document) =>
+ evaluateWhere({ document, where: query.where, available: "all" }) !==
+ false
+ );
+ if (
+ hasDynamicWhere(query.where) ||
+ usesRuntimeWhere(query.where) ||
+ query.sort.some(({ field }) => isAssetQueryRuntimeField(field[0])) ||
+ query.limit.type === "dynamic" ||
+ query.offset.type === "dynamic"
+ ) {
+ for (const document of matched) {
+ selected.add(document._id);
+ }
+ continue;
+ }
+ const sorted = [...matched].sort((left, right) =>
+ compareAssetQueryDocuments(left, right, query.sort)
+ );
+ const offset = Number(query.offset.value);
+ const limit = Number(query.limit.value);
+ for (const document of sorted.slice(offset, offset + limit)) {
+ selected.add(document._id);
+ }
+ }
+ return selected;
+};
+
+export const prepareContentCompilerEntries = async ({
+ entries,
+ plan,
+ loadContent,
+ maximumContentBytes = contentEngineLimits.databaseBytes,
+}: {
+ entries: readonly CanonicalAssetFileEntry[];
+ plan?: ContentCompilationPlan;
+ loadContent: (entry: CanonicalAssetFileEntry) => Promise<string | undefined>;
+ maximumContentBytes?: number;
+}) => {
+ if (
+ Number.isSafeInteger(maximumContentBytes) === false ||
+ maximumContentBytes <= 0
+ ) {
+ throw new Error("Content hydration budget must be a positive integer");
+ }
+ if (plan === undefined) {
+ return entries;
+ }
+ const projected = entries.map((entry) => {
+ const { excerpt, ...document } = entry.document;
+ return {
+ ...entry,
+ document: {
+ ...document,
+ properties:
+ plan.structuredPropertyPaths === "all"
+ ? entry.document.properties
+ : selectAssetProperties({
+ properties: entry.document.properties,
+ fields: plan.structuredPropertyPaths,
+ }),
+ ...(plan.excerpt && excerpt !== undefined ? { excerpt } : {}),
+ },
+ };
+ });
+ const hydrationIds = selectContentHydrationCandidates({
+ documents: projected.map(({ document }) => document),
+ plan,
+ });
+ const candidates = projected.filter(({ document }) =>
+ isContentDocumentCandidate({ document, plan, available: "all" })
+ );
+ let remainingContentBytes = maximumContentBytes;
+ const selectedContentRefs = new Set<string>();
+ const selectedHydrationIds = new Set<string>();
+ for (const entry of [...candidates].sort(compareContentEntryPriority)) {
+ if (hydrationIds.has(entry.assetId) === false) {
+ continue;
+ }
+ if (selectedContentRefs.has(entry.document.contentRef)) {
+ selectedHydrationIds.add(entry.assetId);
+ continue;
+ }
+ if (entry.document.size > remainingContentBytes) {
+ continue;
+ }
+ selectedContentRefs.add(entry.document.contentRef);
+ selectedHydrationIds.add(entry.assetId);
+ remainingContentBytes -= entry.document.size;
+ }
+ const contentByRef = new Map<string, Promise<string | undefined>>();
+ return await Promise.all(
+ candidates.map(async (entry) => {
+ const contentRequired = hydrationIds.has(entry.assetId);
+ if (contentRequired === false) {
+ return entry;
+ }
+ if (
+ selectedHydrationIds.has(entry.assetId) === false ||
+ entry.document.size > contentEngineLimits.hydratedFileBytes
+ ) {
+ return { ...entry, contentRequired: true as const };
+ }
+ let pendingContent = contentByRef.get(entry.document.contentRef);
+ if (pendingContent === undefined) {
+ pendingContent = loadContent(entry);
+ contentByRef.set(entry.document.contentRef, pendingContent);
+ }
+ const content = await pendingContent;
+ return content === undefined
+ ? { ...entry, contentRequired: true as const }
+ : { ...entry, content, contentRequired: true as const };
+ })
+ );
+};
+
+const getOutputFields = (output: AssetResourceOutputSelection) =>
+ output.mode === "fields" ? output.fields : [];
+
+const visitQueryFields = (
+ query: ContentCompilationQuery,
+ visit: (field: AssetQueryFieldPath) => void
+) => {
+ for (const { field } of getQueryConditions(query.where)) {
+ visit(field);
+ }
+ for (const { field } of query.sort) {
+ visit(field);
+ }
+ for (const field of getOutputFields(query.output)) {
+ visit(field);
+ }
+};
+
+const addField = (
+ fields: Map<string, AssetQueryFieldPath>,
+ field: AssetQueryFieldPath
+) => fields.set(getQueryFieldKey(field), field);
+
+const sortFields = (fields: Iterable<AssetQueryFieldPath>) =>
+ [...fields].sort((left, right) =>
+ compareStrings(getQueryFieldKey(left), getQueryFieldKey(right))
+ );
+
+const includesField = (
+ query: ContentCompilationQuery,
+ predicate: (field: AssetQueryFieldPath) => boolean
+) => {
+ let included = false;
+ visitQueryFields(query, (field) => {
+ included ||= predicate(field);
+ });
+ return included;
+};
+
+export const requiresRuntimeDocumentData = (plan: ContentCompilationPlan) =>
+ plan.queries.some((query) =>
+ includesField(
+ query,
+ (field) => field.length === 1 && isAssetQueryRuntimeField(field[0])
+ )
+ );
+
+const getStructuredPropertyPaths = (query: ContentCompilationQuery) => {
+ if (query.output.mode === "all") {
+ return "all" as const;
+ }
+ const fields = new Map<string, AssetQueryFieldPath>();
+ visitQueryFields(query, (field) => {
+ if (field[0] === "properties") {
+ addField(fields, field);
+ }
+ });
+ return sortFields(fields.values());
+};
+
+const getStandardFieldPaths = (query: ContentCompilationQuery) => {
+ const fields = new Map<string, AssetQueryFieldPath>();
+ visitQueryFields(query, (field) => {
+ if (
+ field[0] !== "properties" &&
+ field[0] !== "excerpt" &&
+ isAssetQueryRuntimeField(field[0]) === false
+ ) {
+ addField(fields, field);
+ }
+ });
+ if (query.output.includeMetadata) {
+ for (const field of assetQueryMetadataFields) {
+ addField(fields, [field]);
+ }
+ }
+ if (query.content.mode !== "none") {
+ for (const field of ["mimeType", "size", "revision"] as const) {
+ addField(fields, [field]);
+ }
+ }
+ return sortFields(fields.values());
+};
+
+const getQueryRequirements = (query: ContentCompilationQuery) => ({
+ standardFields: getStandardFieldPaths(query),
+ structuredPropertyPaths: getStructuredPropertyPaths(query),
+ excerpt:
+ query.output.mode === "all" ||
+ includesField(
+ query,
+ (field) => field.length === 1 && field[0] === "excerpt"
+ ),
+ metadataError: query.output.includeMetadata,
+});
+
+const toLiteralWhere = (where: AssetQuery["where"]): ContentCompilationWhere =>
+ mapQueryWhere(where, (condition) => ({
+ field: condition.field,
+ operator: condition.operator,
+ value: { type: "literal" as const, value: condition.value },
+ }));
+
+export const createLiteralContentCompilationQuery = ({
+ id,
+ query,
+}: {
+ id: string;
+ query: AssetQuery;
+}): ContentCompilationQuery => ({
+ id,
+ where: toLiteralWhere(query.where),
+ sort: query.sort,
+ limit: { type: "literal", value: query.limit },
+ offset: { type: "literal", value: query.offset },
+ output: query.output,
+ content: query.content,
+});
+
+export const createContentCompilationPlan = (
+ queries: readonly ContentCompilationQuery[]
+): ContentCompilationPlan | undefined => {
+ if (queries.length === 0) {
+ return;
+ }
+ const requirements = queries.map(getQueryRequirements);
+ const standardFields = new Map<string, AssetQueryFieldPath>();
+ const structuredPropertyPaths = new Map<string, AssetQueryFieldPath>();
+ for (const requirement of requirements) {
+ for (const field of requirement.standardFields) {
+ addField(standardFields, field);
+ }
+ }
+ for (const requirement of requirements) {
+ if (requirement.structuredPropertyPaths === "all") {
+ structuredPropertyPaths.clear();
+ break;
+ }
+ for (const field of requirement.structuredPropertyPaths) {
+ addField(structuredPropertyPaths, field);
+ }
+ }
+ return {
+ standardFields: sortFields(standardFields.values()),
+ structuredPropertyPaths: requirements.some(
+ ({ structuredPropertyPaths }) => structuredPropertyPaths === "all"
+ )
+ ? "all"
+ : sortFields(structuredPropertyPaths.values()),
+ excerpt: requirements.some(({ excerpt }) => excerpt),
+ metadataError: requirements.some(({ metadataError }) => metadataError),
+ queries: [...queries],
+ };
+};
+
+const hasField = (fields: "all" | AssetQueryFieldPath[], field: string) =>
+ fields === "all" ||
+ fields.some((path) => path.length === 1 && path[0] === field);
+
+export const isContentCompilationFieldRequired = ({
+ plan,
+ field,
+}: {
+ plan?: ContentCompilationPlan;
+ field: AssetQueryFieldPath;
+}) => {
+ if (plan === undefined) {
+ return true;
+ }
+ if (field[0] === "properties") {
+ return (
+ plan.structuredPropertyPaths === "all" ||
+ plan.structuredPropertyPaths.some(
+ (required) => getQueryFieldKey(required) === getQueryFieldKey(field)
+ )
+ );
+ }
+ if (field[0] === "excerpt") {
+ return plan.excerpt;
+ }
+ return hasField(plan.standardFields, field[0]);
+};
+
+export const projectContentDatabaseDocument = ({
+ document,
+ plan,
+}: {
+ document: AssetFileDocument;
+ plan?: ContentCompilationPlan;
+}): ContentDatabaseDocument => {
+ if (plan === undefined) {
+ return document;
+ }
+ const includeContentIdentity = requiresHydratedContent(plan);
+ const properties =
+ plan.structuredPropertyPaths === "all"
+ ? document.properties
+ : selectAssetProperties({
+ properties: document.properties,
+ fields: plan.structuredPropertyPaths,
+ });
+ return {
+ _id: document._id,
+ ...selectAssetDocumentFields({
+ document,
+ includes: (field) => hasField(plan.standardFields, field),
+ }),
+ ...(includeContentIdentity ? { contentRef: document.contentRef } : {}),
+ ...(plan.structuredPropertyPaths === "all" ||
+ Object.keys(properties).length > 0
+ ? { properties }
+ : {}),
+ ...(plan.excerpt && document.excerpt !== undefined
+ ? { excerpt: document.excerpt }
+ : {}),
+ ...(plan.metadataError && document.metadataError !== undefined
+ ? { metadataError: document.metadataError }
+ : {}),
+ };
+};
+
+/**
+ * Creates the minimal plan needed to discover every structured property.
+ * Field discovery must inspect all candidate documents, but it does not need
+ * excerpts or file bodies.
+ */
+export const createContentFieldCatalogCompilationPlan = (
+ id = "field-catalog"
+): ContentCompilationPlan => ({
+ standardFields: "all",
+ structuredPropertyPaths: "all",
+ excerpt: false,
+ metadataError: false,
+ queries: [
+ {
+ id,
+ where: { all: [] },
+ sort: [],
+ limit: { type: "literal", value: 0 },
+ offset: { type: "literal", value: 0 },
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["properties"]],
+ },
+ content: { mode: "none" },
+ },
+ ],
+});
diff --git a/packages/content-engine/src/compiler.ts b/packages/content-engine/src/compiler.ts
new file mode 100644
index 0000000000..040b4b5329
--- /dev/null
+++ b/packages/content-engine/src/compiler.ts
@@ -0,0 +1,10 @@
+export * from "./markdown";
+export * from "./json";
+export * from "./canonical";
+export * from "./field-catalog";
+export * from "./asset-index";
+export * from "./content-source";
+export * from "./document-metadata";
+export { serializeJsonDeterministically } from "./canonical-json";
+export { decodeUtf8, readBoundedBytes, readBytePrefix } from "./byte-stream";
+export { mapBounded } from "./async-utils";
diff --git a/packages/content-engine/src/content-artifact.ts b/packages/content-engine/src/content-artifact.ts
new file mode 100644
index 0000000000..ab8b543a09
--- /dev/null
+++ b/packages/content-engine/src/content-artifact.ts
@@ -0,0 +1,58 @@
+import { contentArtifactV1, type ContentArtifactV1 } from "./schema";
+import { contentEngineLimits } from "./limits";
+import { serializeJsonDeterministically, sha256 } from "./canonical-json";
+import { getUtf8ByteLength } from "./byte-stream";
+
+export const checksumContentArtifact = async (index: ContentArtifactV1) => {
+ const { integrity: _integrity, ...payload } = index;
+ return await sha256(serializeJsonDeterministically(payload));
+};
+
+export const serializeContentArtifact = (value: unknown) =>
+ serializeJsonDeterministically(contentArtifactV1.parse(value));
+
+export const getContentArtifactReferencedAssetIds = (
+ artifact: Pick<ContentArtifactV1, "assetReferences">
+) =>
+ [
+ ...new Set(
+ Object.values(artifact.assetReferences ?? {})
+ .flat()
+ .map(({ assetId }) => assetId)
+ ),
+ ].sort();
+
+export const getContentArtifactRuntimeAssetIds = ({
+ artifact,
+ includeDocuments,
+}: {
+ artifact: Pick<ContentArtifactV1, "assetReferences"> & {
+ documents: readonly { _id: string }[];
+ };
+ includeDocuments: boolean;
+}) => {
+ const ids = new Set(getContentArtifactReferencedAssetIds(artifact));
+ if (includeDocuments) {
+ for (const { _id } of artifact.documents) {
+ ids.add(_id);
+ }
+ }
+ return [...ids].sort();
+};
+
+const assertContentArtifactSize = (index: ContentArtifactV1) => {
+ const maximumBytes =
+ index.database?.maxBytes ?? contentEngineLimits.databaseBytes;
+ if (getUtf8ByteLength(serializeContentArtifact(index)) > maximumBytes) {
+ throw new Error("Asset index exceeds the byte limit");
+ }
+};
+
+export const verifyContentArtifact = async (value: unknown) => {
+ const index = contentArtifactV1.parse(value);
+ assertContentArtifactSize(index);
+ if (index.integrity.checksum !== (await checksumContentArtifact(index))) {
+ throw new Error("Content artifact checksum is invalid");
+ }
+ return index;
+};
diff --git a/packages/content-engine/src/content-database.ts b/packages/content-engine/src/content-database.ts
new file mode 100644
index 0000000000..cdb6425152
--- /dev/null
+++ b/packages/content-engine/src/content-database.ts
@@ -0,0 +1,95 @@
+import type {
+ ContentArtifactV1,
+ AssetQueryRequestInput,
+ AssetQueryResult,
+ BuilderAssetFieldCatalog,
+ ContentDatabaseStats,
+} from "./schema";
+import { serializeContentArtifact } from "./content-artifact";
+import {
+ AssetIndexRevisionError,
+ executeAssetQuery,
+ type AssetRuntimeData,
+} from "./structured-query";
+import { encodeUtf8, getUtf8ByteLength } from "./byte-stream";
+import type { AssetResourceContentReader } from "./hydration";
+
+export type ContentDatabase = {
+ query(
+ request: AssetQueryRequestInput,
+ readContent?: AssetResourceContentReader,
+ runtimeAssets?: Readonly<Record<string, AssetRuntimeData>>
+ ): Promise<AssetQueryResult>;
+ getFieldCatalog(): BuilderAssetFieldCatalog;
+ getStats(): ContentDatabaseStats;
+};
+
+export const createContentDatabase = ({
+ artifact,
+ readContent,
+}: {
+ artifact: ContentArtifactV1;
+ readContent?: AssetResourceContentReader;
+}): ContentDatabase => {
+ const includedDocumentCount = artifact.documents.length;
+ const sourceDocumentCount =
+ artifact.database?.sourceDocumentCount ?? includedDocumentCount;
+ const omittedDocumentCount = sourceDocumentCount - includedDocumentCount;
+ const usedBytes = getUtf8ByteLength(serializeContentArtifact(artifact));
+ const stats: ContentDatabaseStats = {
+ format: artifact.format,
+ version: artifact.version,
+ revision: artifact.integrity.checksum,
+ usedBytes,
+ maxBytes: artifact.database?.maxBytes ?? Number.MAX_SAFE_INTEGER,
+ unboundedBytes: artifact.database?.unboundedBytes ?? usedBytes,
+ includedDocumentCount,
+ omittedDocumentCount,
+ truncated: omittedDocumentCount > 0,
+ };
+ return {
+ query: async (request, queryContentReader, runtimeAssets) => {
+ if (
+ request.indexRevision !== undefined &&
+ request.indexRevision !== artifact.integrity.checksum
+ ) {
+ throw new AssetIndexRevisionError();
+ }
+ const readEmbeddedContent: AssetResourceContentReader = async (
+ contentRef,
+ range
+ ) => {
+ const content = artifact.contents?.[contentRef];
+ if (content === undefined) {
+ const externalReader = queryContentReader ?? readContent;
+ if (externalReader === undefined) {
+ throw new Error("Content is not embedded in this database");
+ }
+ return await externalReader(contentRef, range);
+ }
+ const bytes = encodeUtf8(content);
+ const selected =
+ range === undefined
+ ? bytes
+ : bytes.slice(range.offset, range.offset + range.length);
+ return {
+ data: (async function* () {
+ yield selected;
+ })(),
+ contentLength: selected.byteLength,
+ };
+ };
+ const result = await executeAssetQuery({
+ query: request.query,
+ catalog: artifact.fieldCatalog,
+ documents: artifact.documents,
+ read: readEmbeddedContent,
+ runtimeAssets,
+ assetReferences: artifact.assetReferences,
+ });
+ return result;
+ },
+ getFieldCatalog: () => artifact.fieldCatalog,
+ getStats: () => stats,
+ };
+};
diff --git a/packages/content-engine/src/content-source.test.ts b/packages/content-engine/src/content-source.test.ts
new file mode 100644
index 0000000000..f0c19c9113
--- /dev/null
+++ b/packages/content-engine/src/content-source.test.ts
@@ -0,0 +1,409 @@
+import { describe, expect, test } from "vitest";
+import { createCanonicalAssetFileEntry } from "./canonical";
+import {
+ compileContentSource,
+ ContentSourceChangedError,
+ createContentSourceFile,
+ type ContentSource,
+ type ContentSourceFile,
+} from "./content-source";
+
+const projectId = "project";
+
+const createFile = (
+ values: Partial<ContentSourceFile> & Pick<ContentSourceFile, "id">
+): ContentSourceFile => ({
+ path: `blog/${values.id}.md`,
+ contentType: "text/markdown",
+ contentRef: `revisions/${values.id}.md`,
+ revision: `revision-${values.id}`,
+ size: 20,
+ createdAt: "2026-07-27T00:00:00.000Z",
+ ...values,
+});
+
+const createEntry = (file: ContentSourceFile) =>
+ createCanonicalAssetFileEntry({
+ projectId,
+ document: {
+ _id: file.id,
+ _type: "asset.file",
+ name: file.path.split("/").at(-1) ?? file.id,
+ path: file.path,
+ key: file.id,
+ extension: file.path.split(".").at(-1) ?? "",
+ mimeType: file.contentType,
+ size: file.size,
+ createdAt: file.createdAt,
+ revision: file.revision,
+ contentRef: file.contentRef,
+ properties: { title: file.id },
+ },
+ });
+
+const getRevision = (files: readonly ContentSourceFile[]) =>
+ JSON.stringify(files);
+
+const getReferencedAssetIds = (
+ references: Awaited<
+ ReturnType<typeof compileContentSource>
+ >["artifact"]["assetReferences"]
+) =>
+ Object.fromEntries(
+ Object.entries(references ?? {}).map(([contentRef, items]) => [
+ contentRef,
+ items.map(({ assetId }) => assetId),
+ ])
+ );
+
+const createMutableSource = ({
+ initial,
+ mutate,
+ mutateEveryAttempt = false,
+}: {
+ initial: readonly ContentSourceFile[];
+ mutate: (files: readonly ContentSourceFile[]) => ContentSourceFile[];
+ mutateEveryAttempt?: boolean;
+}) => {
+ let files = [...initial];
+ let openCount = 0;
+ const source: ContentSource = {
+ async openSnapshot() {
+ openCount += 1;
+ const captured = files.map((file) => ({ ...file }));
+ const revision = getRevision(captured);
+ return {
+ revision,
+ files: captured,
+ async loadEntries() {
+ if (openCount === 1 || mutateEveryAttempt) {
+ files = mutate(files);
+ }
+ return captured.map(createEntry);
+ },
+ async isCurrent() {
+ return getRevision(files) === revision;
+ },
+ };
+ },
+ };
+ return {
+ source,
+ getFiles: () => files,
+ getOpenCount: () => openCount,
+ };
+};
+
+describe("content source snapshots", () => {
+ test("describes a compiler entry with the snapshot contract", () => {
+ const file = createFile({ id: "post" });
+ expect(createContentSourceFile(createEntry(file))).toEqual(file);
+ });
+
+ test("passes the artifact byte limit to content materialization", async () => {
+ const file = createFile({ id: "post" });
+ let maximumContentBytes: number | undefined;
+ const source: ContentSource = {
+ async openSnapshot() {
+ return {
+ revision: "snapshot",
+ files: [file],
+ async loadEntries(_plan, options) {
+ maximumContentBytes = options?.maximumContentBytes;
+ return [createEntry(file)];
+ },
+ async isCurrent() {
+ return true;
+ },
+ };
+ },
+ };
+
+ await compileContentSource({ source, projectId, maxBytes: 2_048 });
+
+ expect(maximumContentBytes).toBe(2_048);
+ });
+
+ test("discovers relative asset dependencies from selected Markdown", async () => {
+ const post = createFile({
+ id: "post",
+ path: "blog%20posts/posts/post.md",
+ });
+ const image = createFile({
+ id: "hero",
+ path: "blog%20posts/images/hero%20image.png",
+ contentType: "image/png",
+ contentRef: "revisions/hero.png",
+ });
+ const source: ContentSource = {
+ async openSnapshot() {
+ return {
+ revision: "snapshot",
+ files: [post, image],
+ async loadEntries() {
+ return [
+ {
+ ...createEntry(post),
+ content: "![Hero](../images/hero%20image.png)",
+ },
+ ];
+ },
+ async isCurrent() {
+ return true;
+ },
+ };
+ },
+ };
+
+ const result = await compileContentSource({ source, projectId });
+
+ expect(getReferencedAssetIds(result.artifact.assetReferences)).toEqual({
+ "revisions/post.md": ["hero"],
+ });
+ });
+
+ test("resolves the same relative URL independently for each Markdown folder", async () => {
+ const firstPost = createFile({
+ id: "first-post",
+ path: "blog/first/post.md",
+ });
+ const secondPost = createFile({
+ id: "second-post",
+ path: "blog/second/post.md",
+ });
+ const firstImage = createFile({
+ id: "first-image",
+ path: "blog/first/hero.png",
+ contentType: "image/png",
+ });
+ const secondImage = createFile({
+ id: "second-image",
+ path: "blog/second/hero.png",
+ contentType: "image/png",
+ });
+ const source: ContentSource = {
+ async openSnapshot() {
+ return {
+ revision: "snapshot",
+ files: [firstPost, secondPost, firstImage, secondImage],
+ async loadEntries() {
+ return [firstPost, secondPost].map((file) => ({
+ ...createEntry(file),
+ content: "![Hero](./hero.png)",
+ }));
+ },
+ async isCurrent() {
+ return true;
+ },
+ };
+ },
+ };
+
+ const result = await compileContentSource({ source, projectId });
+
+ expect(getReferencedAssetIds(result.artifact.assetReferences)).toEqual({
+ "revisions/first-post.md": ["first-image"],
+ "revisions/second-post.md": ["second-image"],
+ });
+ });
+
+ test("discovers asset IDs inserted by the Builder", async () => {
+ const post = createFile({ id: "post", path: "blog/post.md" });
+ const image = createFile({
+ id: "hero",
+ path: "images/hero.png",
+ contentType: "image/png",
+ contentRef: "revisions/hero.png",
+ });
+ const source: ContentSource = {
+ async openSnapshot() {
+ return {
+ revision: "snapshot",
+ files: [post, image],
+ async loadEntries() {
+ return [{ ...createEntry(post), content: "![Hero](hero)" }];
+ },
+ async isCurrent() {
+ return true;
+ },
+ };
+ },
+ };
+
+ const result = await compileContentSource({ source, projectId });
+
+ expect(getReferencedAssetIds(result.artifact.assetReferences)).toEqual({
+ "revisions/post.md": ["hero"],
+ });
+ });
+
+ test("stores Markdown references only for parsed Markdown content", async () => {
+ const post = createFile({ id: "post", path: "blog/post.md" });
+ const image = createFile({
+ id: "hero",
+ path: "images/hero.png",
+ contentType: "image/png",
+ });
+ const source: ContentSource = {
+ async openSnapshot() {
+ return {
+ revision: "snapshot",
+ files: [post, image],
+ async loadEntries() {
+ return [
+ { ...createEntry(post), content: "![Hero](../images/hero.png)" },
+ ];
+ },
+ async isCurrent() {
+ return true;
+ },
+ };
+ },
+ };
+
+ const compile = (mode: "full" | "markdown-body") =>
+ compileContentSource({
+ source,
+ projectId,
+ plan: {
+ standardFields: [],
+ structuredPropertyPaths: [],
+ excerpt: false,
+ metadataError: false,
+ queries: [
+ {
+ id: "content",
+ where: { all: [] },
+ sort: [],
+ limit: { type: "literal", value: 1 },
+ offset: { type: "literal", value: 0 },
+ output: { mode: "fields", includeMetadata: false, fields: [] },
+ content: { mode },
+ },
+ ],
+ },
+ });
+
+ expect((await compile("full")).artifact.assetReferences).toBeUndefined();
+ expect(
+ getReferencedAssetIds(
+ (await compile("markdown-body")).artifact.assetReferences
+ )
+ ).toEqual({ "revisions/post.md": ["hero"] });
+ });
+
+ test("does not resolve an ambiguous Asset path", async () => {
+ const post = createFile({ id: "post", path: "blog/post.md" });
+ const firstImage = createFile({
+ id: "first-image",
+ path: "blog/hero.png",
+ contentType: "image/png",
+ });
+ const secondImage = createFile({
+ id: "second-image",
+ path: "blog/hero.png",
+ contentType: "image/png",
+ });
+ const source: ContentSource = {
+ async openSnapshot() {
+ return {
+ revision: "snapshot",
+ files: [post, firstImage, secondImage],
+ async loadEntries() {
+ return [
+ {
+ ...createEntry(post),
+ content: "![Hero](./hero.png)",
+ },
+ ];
+ },
+ async isCurrent() {
+ return true;
+ },
+ };
+ },
+ };
+
+ const result = await compileContentSource({ source, projectId });
+
+ expect(result.artifact.assetReferences).toBeUndefined();
+ });
+
+ test.each([
+ {
+ name: "content replacement",
+ mutate: ([file]: readonly ContentSourceFile[]) => [
+ {
+ ...file,
+ revision: "replacement-revision",
+ contentRef: "revisions/replacement.md",
+ },
+ ],
+ expectedPath: "blog/article.md",
+ },
+ {
+ name: "deletion",
+ mutate: () => [],
+ expectedPath: undefined,
+ },
+ {
+ name: "folder movement",
+ mutate: ([file]: readonly ContentSourceFile[]) => [
+ { ...file, path: "archive/article.md" },
+ ],
+ expectedPath: "archive/article.md",
+ },
+ {
+ name: "filesystem change",
+ mutate: ([file]: readonly ContentSourceFile[]) => [
+ { ...file, revision: "filesystem-revision", size: file.size + 1 },
+ ],
+ expectedPath: "blog/article.md",
+ },
+ ])("retries after $name", async ({ mutate, expectedPath }) => {
+ const { source, getFiles, getOpenCount } = createMutableSource({
+ initial: [createFile({ id: "article" })],
+ mutate,
+ });
+
+ const result = await compileContentSource({ source, projectId });
+
+ expect(getOpenCount()).toBe(2);
+ expect(result.artifact.documents[0]?.path).toBe(expectedPath);
+ expect(result.sourceRevision).toBe(getRevision(getFiles()));
+ });
+
+ test("fails clearly when the source changes on both attempts", async () => {
+ const { source } = createMutableSource({
+ initial: [createFile({ id: "article" })],
+ mutate: ([file]) => [{ ...file, revision: `${file.revision}-changed` }],
+ mutateEveryAttempt: true,
+ });
+
+ await expect(compileContentSource({ source, projectId })).rejects.toThrow(
+ ContentSourceChangedError
+ );
+ });
+
+ test("rejects entries that do not belong to the captured snapshot", async () => {
+ const file = createFile({ id: "article" });
+ const source: ContentSource = {
+ async openSnapshot() {
+ return {
+ revision: file.revision,
+ files: [file],
+ async loadEntries() {
+ return [createEntry({ ...file, contentRef: "revisions/other.md" })];
+ },
+ async isCurrent() {
+ return true;
+ },
+ };
+ },
+ };
+
+ await expect(compileContentSource({ source, projectId })).rejects.toThrow(
+ "outside the captured snapshot"
+ );
+ });
+});
diff --git a/packages/content-engine/src/content-source.ts b/packages/content-engine/src/content-source.ts
new file mode 100644
index 0000000000..9ea88f2339
--- /dev/null
+++ b/packages/content-engine/src/content-source.ts
@@ -0,0 +1,251 @@
+import type { ContentCompilationPlan } from "./compilation-plan";
+import {
+ compileContentArtifact,
+ type ContentCompilerDiagnostics,
+ type ContentCompilerInput,
+} from "./asset-index";
+import type { ContentArtifactV1 } from "./schema";
+import { selectContentHydrationCandidates } from "./compilation-plan";
+import {
+ createUniqueAssetIdsByPath,
+ discoverMarkdownAssetReferenceRanges,
+} from "./markdown-assets";
+import type { MarkdownAssetReferences } from "./markdown-references";
+import { compareStrings } from "./canonical-json";
+import { encodeUtf8 } from "./byte-stream";
+import { extractMarkdownBody } from "./markdown-body";
+import { contentEngineLimits } from "./limits";
+
+export type ContentSourceFile = {
+ id: string;
+ path: string;
+ contentType: string;
+ contentRef: string;
+ revision: string;
+ size: number;
+ createdAt?: string;
+};
+
+export interface ContentSourceSnapshot {
+ readonly revision: string;
+ readonly files: readonly ContentSourceFile[];
+ loadEntries(
+ plan?: ContentCompilationPlan,
+ options?: { maximumContentBytes: number }
+ ): Promise<readonly ContentCompilerInput[]>;
+ isCurrent(): Promise<boolean>;
+}
+
+export interface ContentSource {
+ openSnapshot(): Promise<ContentSourceSnapshot>;
+}
+
+export const createContentSourceFile = ({
+ assetId,
+ revision,
+ document,
+}: ContentCompilerInput): ContentSourceFile => ({
+ id: assetId,
+ path: document.path,
+ contentType: document.mimeType,
+ contentRef: document.contentRef,
+ revision,
+ size: document.size,
+ createdAt: document.createdAt,
+});
+
+export class ContentSourceChangedError extends Error {
+ constructor() {
+ super("Content source changed while the database was being compiled");
+ this.name = "ContentSourceChangedError";
+ }
+}
+
+const validateSnapshot = (snapshot: ContentSourceSnapshot) => {
+ if (snapshot.revision.length === 0) {
+ throw new Error("Content source snapshot revision cannot be empty");
+ }
+ const ids = new Set<string>();
+ for (const file of snapshot.files) {
+ if (file.id.length === 0 || ids.has(file.id)) {
+ throw new Error("Content source snapshot file ids must be unique");
+ }
+ ids.add(file.id);
+ if (
+ file.path.length === 0 ||
+ file.contentType.length === 0 ||
+ file.contentRef.length === 0 ||
+ file.revision.length === 0 ||
+ Number.isSafeInteger(file.size) === false ||
+ file.size < 0
+ ) {
+ throw new Error("Content source snapshot contains an invalid file");
+ }
+ }
+};
+
+const validateEntries = ({
+ snapshot,
+ entries,
+}: {
+ snapshot: ContentSourceSnapshot;
+ entries: readonly ContentCompilerInput[];
+}) => {
+ const fileById = new Map(snapshot.files.map((file) => [file.id, file]));
+ for (const entry of entries) {
+ const file = fileById.get(entry.assetId);
+ if (
+ file === undefined ||
+ entry.revision !== file.revision ||
+ entry.document.path !== file.path ||
+ entry.document.mimeType !== file.contentType ||
+ entry.document.contentRef !== file.contentRef ||
+ entry.document.size !== file.size ||
+ entry.document.createdAt !== file.createdAt
+ ) {
+ throw new Error(
+ "Content source returned an entry outside the captured snapshot"
+ );
+ }
+ }
+};
+
+const discoverSnapshotAssetReferences = async ({
+ snapshot,
+ entries,
+ plan,
+}: {
+ snapshot: ContentSourceSnapshot;
+ entries: readonly ContentCompilerInput[];
+ plan?: ContentCompilationPlan;
+}): Promise<MarkdownAssetReferences> => {
+ const assetIdsByPath = createUniqueAssetIdsByPath(snapshot.files);
+ const selectedAssetIds =
+ plan === undefined
+ ? undefined
+ : selectContentHydrationCandidates({
+ documents: entries.map(({ document }) => document),
+ plan: {
+ ...plan,
+ queries: plan.queries.filter(
+ ({ content }) => content.mode === "markdown-body"
+ ),
+ },
+ });
+ const references: Record<string, MarkdownAssetReferences[string]> = {};
+ for (const entry of [...entries].sort((left, right) =>
+ compareStrings(left.document.contentRef, right.document.contentRef)
+ )) {
+ if (
+ entry.content === undefined ||
+ entry.document.extension !== "md" ||
+ selectedAssetIds?.has(entry.assetId) === false
+ ) {
+ continue;
+ }
+ const bytes = encodeUtf8(entry.content);
+ const markdown =
+ bytes.byteLength === 0
+ ? ""
+ : (await extractMarkdownBody(bytes, bytes.byteLength)).body;
+ const discovered = discoverMarkdownAssetReferenceRanges({
+ markdown,
+ sourcePath: entry.document.path,
+ assetIdsByPath,
+ });
+ if (discovered.length > 0) {
+ references[entry.document.contentRef] = discovered;
+ }
+ }
+ return references;
+};
+
+export const materializeContentSnapshot = async ({
+ snapshot,
+ plan,
+ maximumContentBytes = contentEngineLimits.databaseBytes,
+}: {
+ snapshot: ContentSourceSnapshot;
+ plan?: ContentCompilationPlan;
+ maximumContentBytes?: number;
+}) => {
+ validateSnapshot(snapshot);
+ try {
+ const entries = await snapshot.loadEntries(plan, { maximumContentBytes });
+ validateEntries({ snapshot, entries });
+ const assetReferences = await discoverSnapshotAssetReferences({
+ snapshot,
+ entries,
+ plan,
+ });
+ if (await snapshot.isCurrent()) {
+ return { sourceRevision: snapshot.revision, entries, assetReferences };
+ }
+ } catch (error) {
+ if (await snapshot.isCurrent()) {
+ throw error;
+ }
+ }
+ throw new ContentSourceChangedError();
+};
+
+export const compileContentSource = async ({
+ source,
+ projectId,
+ plan,
+ maxBytes,
+}: {
+ source: ContentSource;
+ projectId: string;
+ plan?: ContentCompilationPlan;
+ maxBytes?: number;
+}): Promise<{
+ sourceRevision: string;
+ artifact: ContentArtifactV1;
+ diagnostics: ContentCompilerDiagnostics;
+}> => {
+ const { sourceRevision, entries, assetReferences } =
+ await materializeContentSource({
+ source,
+ plan,
+ maximumContentBytes: maxBytes,
+ });
+ const compiled = await compileContentArtifact({
+ projectId,
+ entries,
+ assetReferences,
+ ...(plan === undefined ? {} : { plan }),
+ ...(maxBytes === undefined ? {} : { maxBytes }),
+ });
+ return { sourceRevision, ...compiled };
+};
+
+export const materializeContentSource = async ({
+ source,
+ plan,
+ maximumContentBytes,
+}: {
+ source: ContentSource;
+ plan?: ContentCompilationPlan;
+ maximumContentBytes?: number;
+}): Promise<{
+ sourceRevision: string;
+ entries: readonly ContentCompilerInput[];
+ assetReferences: MarkdownAssetReferences;
+}> => {
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ const snapshot = await source.openSnapshot();
+ try {
+ return await materializeContentSnapshot({
+ snapshot,
+ plan,
+ maximumContentBytes,
+ });
+ } catch (error) {
+ if (error instanceof ContentSourceChangedError === false) {
+ throw error;
+ }
+ }
+ }
+ throw new ContentSourceChangedError();
+};
diff --git a/packages/content-engine/src/document-metadata.test.ts b/packages/content-engine/src/document-metadata.test.ts
new file mode 100644
index 0000000000..7762a8dced
--- /dev/null
+++ b/packages/content-engine/src/document-metadata.test.ts
@@ -0,0 +1,239 @@
+import { describe, expect, test, vi } from "vitest";
+import { createCanonicalAssetFileEntry } from "./canonical";
+import { prepareCanonicalContentMetadata } from "./document-metadata";
+
+const createEntry = ({
+ revision = "revision-1",
+ properties = {},
+ excerpt,
+ prepared = false,
+}: {
+ revision?: string;
+ properties?: Record<string, string>;
+ excerpt?: string;
+ prepared?: boolean;
+} = {}) =>
+ createCanonicalAssetFileEntry({
+ projectId: "project",
+ metadataRequirements: {
+ structuredProperties: prepared,
+ excerpt: prepared,
+ },
+ document: {
+ _id: "post",
+ _type: "asset.file",
+ name: "post.md",
+ path: "blog/post.md",
+ key: "post",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 44,
+ revision,
+ contentRef: "post.md",
+ properties,
+ ...(excerpt === undefined ? {} : { excerpt }),
+ },
+ });
+
+describe("content metadata cache", () => {
+ test("reuses a matching prepared entry without reading source bytes", async () => {
+ const cached = createEntry({
+ properties: { title: "Cached" },
+ excerpt: "Cached excerpt",
+ prepared: true,
+ });
+ const readBytes = vi.fn();
+ const set = vi.fn();
+
+ await expect(
+ prepareCanonicalContentMetadata({
+ base: createEntry(),
+ requirements: { structuredProperties: true, excerpt: true },
+ cache: { get: async () => cached, set },
+ readBytes,
+ })
+ ).resolves.toMatchObject({
+ document: {
+ properties: { title: "Cached" },
+ excerpt: "Cached excerpt",
+ },
+ });
+ expect(readBytes).not.toHaveBeenCalled();
+ expect(set).toHaveBeenCalledOnce();
+ });
+
+ test("ignores a cache entry from another source revision", async () => {
+ const set = vi.fn();
+ const source = "---\ntitle: Current\n---\nCurrent excerpt";
+
+ await expect(
+ prepareCanonicalContentMetadata({
+ base: createEntry(),
+ requirements: { structuredProperties: true, excerpt: true },
+ cache: {
+ get: async () =>
+ createEntry({
+ revision: "stale",
+ properties: { title: "Stale" },
+ prepared: true,
+ }),
+ set,
+ },
+ readBytes: async () => new TextEncoder().encode(source),
+ })
+ ).resolves.toMatchObject({
+ document: {
+ properties: { title: "Current" },
+ excerpt: "Current excerpt",
+ },
+ });
+ expect(set).toHaveBeenCalledOnce();
+ });
+
+ test("does not retain derived fields from an invalidated cache tier", async () => {
+ const stale = createEntry({
+ properties: { title: "Stale" },
+ excerpt: "Stale excerpt",
+ });
+ stale.document.metadataError = {
+ code: "STALE_ERROR",
+ message: "Stale error",
+ };
+
+ const prepared = await prepareCanonicalContentMetadata({
+ base: createEntry(),
+ requirements: { structuredProperties: true, excerpt: true },
+ cache: { get: async () => stale, set: vi.fn() },
+ readBytes: async () =>
+ new TextEncoder().encode("---\ntitle: One\ntitle: Two\n---"),
+ });
+
+ expect(prepared.document.properties).toEqual({});
+ expect(prepared.document).not.toHaveProperty("excerpt");
+ expect(prepared.document.metadataError).toMatchObject({
+ code: "FRONTMATTER_INVALID",
+ });
+ });
+
+ test("removes stale excerpts from non-Markdown cache entries", async () => {
+ const markdown = createEntry({
+ excerpt: "Stale description",
+ prepared: true,
+ });
+ const binaryDocument = {
+ ...markdown.document,
+ name: "image.png",
+ path: "image.png",
+ extension: "png",
+ mimeType: "image/png",
+ };
+ const cached = createCanonicalAssetFileEntry({
+ projectId: markdown.projectId,
+ metadataRequirements: {
+ structuredProperties: true,
+ excerpt: true,
+ },
+ document: binaryDocument,
+ });
+ const { excerpt: _excerpt, ...baseDocument } = binaryDocument;
+ const readBytes = vi.fn();
+
+ const prepared = await prepareCanonicalContentMetadata({
+ base: createCanonicalAssetFileEntry({
+ projectId: markdown.projectId,
+ metadataRequirements: {
+ structuredProperties: false,
+ excerpt: false,
+ },
+ document: baseDocument,
+ }),
+ requirements: { structuredProperties: true, excerpt: true },
+ cache: { get: async () => cached, set: vi.fn() },
+ readBytes,
+ });
+
+ expect(prepared.document).not.toHaveProperty("excerpt");
+ expect(readBytes).not.toHaveBeenCalled();
+ });
+
+ test("works without a persistence cache", async () => {
+ const readBytes = vi.fn(async () =>
+ new TextEncoder().encode("---\ntitle: Local\n---\nBody")
+ );
+ await expect(
+ prepareCanonicalContentMetadata({
+ base: createCanonicalAssetFileEntry({
+ ...createEntry(),
+ document: { ...createEntry().document, size: 1024 * 1024 },
+ }),
+ requirements: { structuredProperties: true, excerpt: false },
+ readBytes,
+ })
+ ).resolves.toMatchObject({
+ document: { properties: { title: "Local" } },
+ });
+ expect(readBytes).toHaveBeenCalledWith(64 * 1024 + 13);
+ });
+
+ test("retains the full Markdown budget when an excerpt is required", async () => {
+ const readBytes = vi.fn(async () =>
+ new TextEncoder().encode("---\ntitle: Local\n---\nBody")
+ );
+
+ await prepareCanonicalContentMetadata({
+ base: createCanonicalAssetFileEntry({
+ ...createEntry(),
+ document: { ...createEntry().document, size: 2 * 1024 * 1024 },
+ }),
+ requirements: { structuredProperties: false, excerpt: true },
+ readBytes,
+ });
+
+ expect(readBytes).toHaveBeenCalledWith(1024 * 1024);
+ });
+
+ test("ignores an incomplete UTF-8 code point at the excerpt prefix boundary", async () => {
+ const prefix = new TextEncoder().encode("Body ");
+ const truncated = new Uint8Array(prefix.byteLength + 1);
+ truncated.set(prefix);
+ truncated[prefix.byteLength] = 0xe2;
+
+ await expect(
+ prepareCanonicalContentMetadata({
+ base: createCanonicalAssetFileEntry({
+ ...createEntry(),
+ document: {
+ ...createEntry().document,
+ size: 2 * 1024 * 1024,
+ },
+ }),
+ requirements: { structuredProperties: false, excerpt: true },
+ readBytes: async () => truncated,
+ })
+ ).resolves.toMatchObject({
+ document: { excerpt: "Body" },
+ });
+ });
+
+ test("reports malformed UTF-8 inside an excerpt prefix", async () => {
+ const malformed = Uint8Array.from([0x42, 0xff, 0x64]);
+
+ await expect(
+ prepareCanonicalContentMetadata({
+ base: createCanonicalAssetFileEntry({
+ ...createEntry(),
+ document: {
+ ...createEntry().document,
+ size: 2 * 1024 * 1024,
+ },
+ }),
+ requirements: { structuredProperties: false, excerpt: true },
+ readBytes: async () => malformed,
+ })
+ ).resolves.toMatchObject({
+ document: {
+ metadataError: { code: "MARKDOWN_BODY_DECODING_FAILED" },
+ },
+ });
+ });
+});
diff --git a/packages/content-engine/src/document-metadata.ts b/packages/content-engine/src/document-metadata.ts
new file mode 100644
index 0000000000..3a9a44f9bd
--- /dev/null
+++ b/packages/content-engine/src/document-metadata.ts
@@ -0,0 +1,178 @@
+import {
+ createCanonicalAssetFileEntry,
+ getCanonicalAssetMetadataRequirements,
+ type CanonicalAssetFileEntry,
+ type CanonicalAssetMetadataRequirements,
+} from "./canonical";
+import { extractJsonProperties, JsonMetadataError } from "./json";
+import { contentEngineLimits } from "./limits";
+import {
+ extractMarkdownBodyAndExcerpt,
+ extractMarkdownFrontmatter,
+ MarkdownMetadataError,
+} from "./markdown";
+import { markdownFrontmatterEnvelopeBytes } from "./markdown-scanner";
+
+const isMarkdown = (entry: CanonicalAssetFileEntry) =>
+ entry.document.extension.toLowerCase() === "md";
+
+const isJson = (entry: CanonicalAssetFileEntry) =>
+ entry.document.extension.toLowerCase() === "json";
+
+const trimIncompleteUtf8Suffix = (bytes: Uint8Array) => {
+ try {
+ new TextDecoder("utf-8", { fatal: true }).decode(bytes);
+ return bytes;
+ } catch {
+ try {
+ // Streaming decoding accepts only an incomplete trailing code point;
+ // malformed bytes elsewhere still fail and must remain an error.
+ new TextDecoder("utf-8", { fatal: true }).decode(bytes, {
+ stream: true,
+ });
+ } catch {
+ return bytes;
+ }
+ }
+ for (let suffixBytes = 1; suffixBytes <= 3; suffixBytes += 1) {
+ const prefix = bytes.subarray(0, -suffixBytes);
+ try {
+ new TextDecoder("utf-8", { fatal: true }).decode(prefix);
+ return prefix;
+ } catch {
+ // A UTF-8 code point occupies at most four bytes.
+ }
+ }
+ return bytes;
+};
+
+export interface ContentMetadataCache {
+ get(input: {
+ base: CanonicalAssetFileEntry;
+ requirements: CanonicalAssetMetadataRequirements;
+ }): Promise<CanonicalAssetFileEntry | undefined>;
+ set(input: {
+ base: CanonicalAssetFileEntry;
+ entry: CanonicalAssetFileEntry;
+ }): Promise<void>;
+}
+
+const isCacheEntryForBase = (
+ cached: CanonicalAssetFileEntry,
+ base: CanonicalAssetFileEntry
+) =>
+ cached.projectId === base.projectId &&
+ cached.assetId === base.assetId &&
+ cached.revision === base.revision;
+
+/**
+ * Adds only the parsed metadata requested by a compilation plan to a canonical
+ * base entry. Storage adapters provide bounded bytes and may persist the result
+ * as a cache, but parsing semantics remain owned by the content engine.
+ */
+export const prepareCanonicalContentMetadata = async ({
+ base,
+ requirements,
+ cache,
+ readBytes,
+}: {
+ base: CanonicalAssetFileEntry;
+ requirements: CanonicalAssetMetadataRequirements;
+ cache?: ContentMetadataCache;
+ readBytes: (maximumBytes: number) => Promise<Uint8Array>;
+}) => {
+ const cachedCandidate = await cache?.get({ base, requirements });
+ const cached =
+ cachedCandidate !== undefined && isCacheEntryForBase(cachedCandidate, base)
+ ? cachedCandidate
+ : undefined;
+ const cachedRequirements =
+ cached === undefined
+ ? { structuredProperties: false, excerpt: false }
+ : getCanonicalAssetMetadataRequirements(cached);
+ let properties: Record<string, unknown> =
+ cachedRequirements.structuredProperties && cached !== undefined
+ ? cached.document.properties
+ : {};
+ let excerpt =
+ isMarkdown(base) && cachedRequirements.excerpt
+ ? cached?.document.excerpt
+ : undefined;
+ let metadataError =
+ cachedRequirements.structuredProperties || cachedRequirements.excerpt
+ ? cached?.document.metadataError
+ : undefined;
+ const needsProperties =
+ requirements.structuredProperties &&
+ cachedRequirements.structuredProperties === false;
+ const needsExcerpt =
+ requirements.excerpt && cachedRequirements.excerpt === false;
+
+ if (isMarkdown(base) && (needsProperties || needsExcerpt)) {
+ // Frontmatter discovery needs only the bounded opening block. Excerpt
+ // generation still receives the larger Markdown body budget.
+ const maximumBytes = needsExcerpt
+ ? contentEngineLimits.hydratedFileBytes
+ : contentEngineLimits.frontmatterBytes + markdownFrontmatterEnvelopeBytes;
+ let bytes = await readBytes(Math.min(base.document.size, maximumBytes));
+ if (needsExcerpt && base.document.size > bytes.byteLength) {
+ bytes = trimIncompleteUtf8Suffix(bytes);
+ }
+ if (needsProperties) {
+ try {
+ properties = (await extractMarkdownFrontmatter(bytes)).properties;
+ } catch (error) {
+ if (error instanceof MarkdownMetadataError === false) {
+ throw error;
+ }
+ metadataError = { code: error.code, message: error.message };
+ }
+ }
+ if (needsExcerpt) {
+ try {
+ excerpt = (await extractMarkdownBodyAndExcerpt(bytes)).excerpt;
+ } catch (error) {
+ if (error instanceof MarkdownMetadataError === false) {
+ throw error;
+ }
+ metadataError ??= { code: error.code, message: error.message };
+ }
+ }
+ } else if (isJson(base) && needsProperties) {
+ if (base.document.size > contentEngineLimits.jsonBytes) {
+ const error = new JsonMetadataError(
+ "JSON_BYTES_EXCEEDED",
+ "JSON metadata exceeds the byte limit"
+ );
+ metadataError = { code: error.code, message: error.message };
+ } else {
+ const bytes = await readBytes(base.document.size);
+ try {
+ properties = (await extractJsonProperties(bytes)).properties;
+ } catch (error) {
+ if (error instanceof JsonMetadataError === false) {
+ throw error;
+ }
+ metadataError = { code: error.code, message: error.message };
+ }
+ }
+ }
+
+ const entry = createCanonicalAssetFileEntry({
+ projectId: base.projectId,
+ metadataRequirements: {
+ structuredProperties:
+ cachedRequirements.structuredProperties ||
+ requirements.structuredProperties,
+ excerpt: cachedRequirements.excerpt || requirements.excerpt,
+ },
+ document: {
+ ...base.document,
+ properties,
+ ...(excerpt === undefined || excerpt.length === 0 ? {} : { excerpt }),
+ ...(metadataError === undefined ? {} : { metadataError }),
+ },
+ });
+ await cache?.set({ base, entry });
+ return entry;
+};
diff --git a/packages/content-engine/src/field-catalog.test.ts b/packages/content-engine/src/field-catalog.test.ts
new file mode 100644
index 0000000000..da9b262953
--- /dev/null
+++ b/packages/content-engine/src/field-catalog.test.ts
@@ -0,0 +1,287 @@
+import { describe, expect, test } from "vitest";
+import {
+ createCanonicalAssetFileEntry,
+ normalizeAssetFileDocument,
+} from "./canonical";
+import { extractMarkdownFrontmatter } from "./markdown";
+import {
+ computeCanonicalAssetRevision,
+ createAssetFieldCatalog,
+ toBuilderAssetFieldCatalog,
+} from "./field-catalog";
+
+const createEntry = ({
+ id,
+ properties,
+ folderId,
+ excerpt,
+ createdAt,
+}: {
+ id: string;
+ properties: Record<string, unknown>;
+ folderId?: string;
+ excerpt?: string;
+ createdAt?: string;
+}) =>
+ createCanonicalAssetFileEntry({
+ projectId: "project-1",
+ document: {
+ _id: id,
+ _type: "asset.file",
+ name: `${id}.md`,
+ path: folderId === undefined ? `${id}.md` : `blog/${id}.md`,
+ key: id,
+ ...(folderId === undefined ? {} : { folderId }),
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 100,
+ ...(createdAt === undefined ? {} : { createdAt }),
+ revision: `revision-${id}`,
+ contentRef: `${id}.md`,
+ properties,
+ ...(excerpt === undefined ? {} : { excerpt }),
+ },
+ });
+
+describe("asset field aggregation", () => {
+ test("aggregates standard and dynamic fields by document and type", async () => {
+ const catalog = await createAssetFieldCatalog([
+ createEntry({
+ id: "one",
+ folderId: "blog",
+ excerpt: "One",
+ properties: {
+ title: "One",
+ author: { name: "Ada" },
+ tags: ["news", 1],
+ },
+ }),
+ createEntry({
+ id: "two",
+ properties: { title: 2, draft: false },
+ }),
+ ]);
+
+ expect(catalog).toMatchObject({
+ projectId: "project-1",
+ documentCount: 2,
+ });
+ expect(catalog.fields).toEqual(
+ expect.arrayContaining([
+ {
+ path: "name",
+ occurrences: 2,
+ types: [{ type: "string", occurrences: 2 }],
+ optional: false,
+ mixed: false,
+ },
+ {
+ path: "folderId",
+ occurrences: 1,
+ types: [{ type: "string", occurrences: 1 }],
+ optional: true,
+ mixed: false,
+ },
+ {
+ path: "excerpt",
+ occurrences: 1,
+ types: [{ type: "string", occurrences: 1 }],
+ optional: true,
+ mixed: false,
+ },
+ {
+ path: "properties.title",
+ occurrences: 2,
+ types: [
+ { type: "number", occurrences: 1 },
+ { type: "string", occurrences: 1 },
+ ],
+ optional: false,
+ mixed: true,
+ },
+ {
+ path: "properties.author.name",
+ occurrences: 1,
+ types: [{ type: "string", occurrences: 1 }],
+ optional: true,
+ mixed: false,
+ },
+ {
+ path: "properties.tags[]",
+ occurrences: 1,
+ types: [
+ { type: "number", occurrences: 1 },
+ { type: "string", occurrences: 1 },
+ ],
+ optional: true,
+ mixed: true,
+ },
+ ])
+ );
+ expect(catalog.fields.map((field) => field.path)).toEqual(
+ [...catalog.fields.map((field) => field.path)].sort()
+ );
+ });
+
+ test("returns an empty catalog without inventing a project", async () => {
+ await expect(createAssetFieldCatalog([])).resolves.toMatchObject({
+ documentCount: 0,
+ fields: [],
+ });
+ });
+
+ test("rejects duplicate assets and mixed projects", async () => {
+ const entry = createEntry({ id: "one", properties: {} });
+ await expect(createAssetFieldCatalog([entry, entry])).rejects.toThrow(
+ "duplicate asset"
+ );
+ await expect(
+ createAssetFieldCatalog([
+ entry,
+ { ...createEntry({ id: "two", properties: {} }), projectId: "other" },
+ ])
+ ).rejects.toThrow("multiple projects");
+ });
+});
+
+describe("versioned asset field catalog", () => {
+ test("is deterministic across entry and object-key order", async () => {
+ const first = createEntry({
+ id: "one",
+ properties: { title: "One", author: { name: "Ada", active: true } },
+ });
+ const reordered = createEntry({
+ id: "one",
+ properties: { author: { active: true, name: "Ada" }, title: "One" },
+ });
+ const second = createEntry({ id: "two", properties: { title: "Two" } });
+
+ expect(await computeCanonicalAssetRevision([first, second])).toBe(
+ await computeCanonicalAssetRevision([second, reordered])
+ );
+ });
+
+ test("discovers a newly indexed nested YAML field without configuration", async () => {
+ const before = toBuilderAssetFieldCatalog(
+ await createAssetFieldCatalog([
+ createEntry({ id: "one", properties: { title: "One" } }),
+ ])
+ );
+ expect(before.fields).not.toHaveProperty("properties.seo.social.title");
+
+ const { properties } = await extractMarkdownFrontmatter(`---
+title: Two
+seo:
+ social:
+ title: Share this post
+---
+Body`);
+ const indexed = createCanonicalAssetFileEntry({
+ projectId: "project-1",
+ document: normalizeAssetFileDocument({
+ asset: {
+ id: "two",
+ name: "two.md",
+ mimeType: "text/markdown",
+ size: 100,
+ revision: "revision-two",
+ contentRef: "two.md",
+ },
+ properties,
+ }),
+ });
+ const after = toBuilderAssetFieldCatalog(
+ await createAssetFieldCatalog([
+ createEntry({ id: "one", properties: { title: "One" } }),
+ indexed,
+ ])
+ );
+
+ expect(after.fields["properties.seo.social.title"]).toEqual({
+ types: ["string"],
+ occurrences: 1,
+ optional: true,
+ queryPath: ["properties", "seo", "social", "title"],
+ });
+ });
+
+ test("changes when canonical content or standard metadata changes", async () => {
+ const entry = createEntry({ id: "one", properties: { title: "One" } });
+ const original = await computeCanonicalAssetRevision([entry]);
+ const contentChanged = await computeCanonicalAssetRevision([
+ {
+ ...entry,
+ revision: "revision-changed",
+ document: { ...entry.document, revision: "revision-changed" },
+ },
+ ]);
+ const renamed = await computeCanonicalAssetRevision([
+ {
+ ...entry,
+ document: {
+ ...entry.document,
+ name: "renamed.md",
+ path: "renamed.md",
+ },
+ },
+ ]);
+
+ expect(contentChanged).not.toBe(original);
+ expect(renamed).not.toBe(original);
+ });
+
+ test("emits a versioned catalog envelope", async () => {
+ const catalog = await createAssetFieldCatalog([
+ createEntry({ id: "one", properties: { title: "One" } }),
+ ]);
+ expect(catalog).toMatchObject({
+ format: "webstudio-asset-field-catalog",
+ version: 1,
+ projectId: "project-1",
+ documentCount: 1,
+ });
+ expect(catalog.canonicalRevision).toMatch(/^sha256:[a-f0-9]{64}$/);
+ });
+
+ test("creates a compact Builder-only transport representation", async () => {
+ const internal = await createAssetFieldCatalog([
+ createEntry({
+ id: "one",
+ createdAt: "2026-07-28T00:00:00.000Z",
+ properties: { title: "One", category: "news" },
+ }),
+ createEntry({ id: "two", properties: { title: 2 } }),
+ ]);
+ const builderCatalog = toBuilderAssetFieldCatalog(internal);
+
+ expect(builderCatalog).toMatchObject({
+ format: "webstudio-builder-asset-field-catalog",
+ version: 1,
+ canonicalRevision: internal.canonicalRevision,
+ documentCount: 2,
+ fields: {
+ name: { types: ["string"], occurrences: 2 },
+ createdAt: {
+ types: ["string"],
+ occurrences: 1,
+ optional: true,
+ queryPath: ["createdAt"],
+ },
+ "properties.category": {
+ types: ["string"],
+ occurrences: 1,
+ optional: true,
+ },
+ "properties.title": {
+ types: ["number", "string"],
+ occurrences: 2,
+ mixed: true,
+ },
+ },
+ });
+ expect(builderCatalog).not.toHaveProperty("projectId");
+ expect(JSON.stringify(builderCatalog).length).toBeLessThan(
+ JSON.stringify(internal).length
+ );
+ });
+});
diff --git a/packages/content-engine/src/field-catalog.ts b/packages/content-engine/src/field-catalog.ts
new file mode 100644
index 0000000000..70c12d73b3
--- /dev/null
+++ b/packages/content-engine/src/field-catalog.ts
@@ -0,0 +1,238 @@
+import {
+ assetQueryStandardFields,
+ builderAssetFieldCatalog,
+ isAssetQueryRuntimeField,
+ type AssetFileDocument,
+ type BuilderAssetFieldCatalog,
+} from "./schema";
+import {
+ compareStrings,
+ serializeJsonDeterministically,
+ sha256,
+} from "./canonical-json";
+import {
+ createCanonicalAssetFileEntry,
+ getFieldContributions,
+ getObservedFieldType,
+ type CanonicalAssetFileEntry,
+ type FieldContribution,
+ type ObservedFieldType,
+} from "./canonical";
+import { parseStaticMemberPath } from "@webstudio-is/expression";
+
+type AggregatedFieldType = {
+ type: ObservedFieldType;
+ occurrences: number;
+};
+
+type AggregatedAssetField = {
+ path: string;
+ occurrences: number;
+ types: AggregatedFieldType[];
+ optional: boolean;
+ mixed: boolean;
+};
+
+type AggregatedAssetFieldCatalog = {
+ projectId?: string;
+ documentCount: number;
+ fields: AggregatedAssetField[];
+};
+
+type AssetFieldCatalog = AggregatedAssetFieldCatalog & {
+ format: "webstudio-asset-field-catalog";
+ version: 1;
+ canonicalRevision: string;
+};
+
+export const computeCanonicalAssetRevision = async (
+ entries: readonly CanonicalAssetFileEntry[]
+) => {
+ const serialized = serializeJsonDeterministically(
+ [...entries]
+ .sort(
+ (left, right) =>
+ compareStrings(left.projectId, right.projectId) ||
+ compareStrings(left.assetId, right.assetId) ||
+ compareStrings(left.revision, right.revision)
+ )
+ .map((entry) => ({
+ projectId: entry.projectId,
+ assetId: entry.assetId,
+ revision: entry.revision,
+ document: entry.document,
+ }))
+ );
+ return await sha256(serialized);
+};
+
+const getStandardFieldContributions = (
+ document: AssetFileDocument
+): FieldContribution[] => [
+ { path: "_id", type: "string" },
+ { path: "_type", type: "string" },
+ ...assetQueryStandardFields.flatMap((field): FieldContribution[] => {
+ if (field === "id" || isAssetQueryRuntimeField(field)) {
+ return [];
+ }
+ const value = document[field];
+ return value === undefined
+ ? []
+ : [{ path: field, type: getObservedFieldType(value) }];
+ }),
+ { path: "contentRef", type: "string" },
+ { path: "properties", type: "object" },
+ ...(document.metadataError === undefined
+ ? []
+ : [
+ { path: "metadataError", type: "object" } as const,
+ { path: "metadataError.code", type: "string" } as const,
+ { path: "metadataError.message", type: "string" } as const,
+ ]),
+];
+
+type MutableField = {
+ occurrences: number;
+ typeOccurrences: Map<ObservedFieldType, number>;
+};
+
+type EntryFields = Map<string, Set<ObservedFieldType>>;
+
+const getEntryFields = (entry: CanonicalAssetFileEntry): EntryFields => {
+ const fields = new Map<string, Set<ObservedFieldType>>();
+ for (const contribution of [
+ ...getStandardFieldContributions(entry.document),
+ ...getFieldContributions(entry.document.properties),
+ ]) {
+ const types = fields.get(contribution.path) ?? new Set();
+ types.add(contribution.type);
+ fields.set(contribution.path, types);
+ }
+ return fields;
+};
+
+const normalizeCatalogEntry = (entry: CanonicalAssetFileEntry) => {
+ const normalized = createCanonicalAssetFileEntry({
+ projectId: entry.projectId,
+ document: entry.document,
+ });
+ if (
+ normalized.assetId !== entry.assetId ||
+ normalized.revision !== entry.revision
+ ) {
+ throw new Error("Asset field catalog entry is inconsistent");
+ }
+ return normalized;
+};
+
+const aggregateCatalogEntries = (
+ entries: readonly CanonicalAssetFileEntry[]
+) => {
+ const normalizedEntries: CanonicalAssetFileEntry[] = [];
+ const assetIds = new Set<string>();
+ const fields = new Map<string, MutableField>();
+ let projectId: string | undefined;
+ for (const entry of entries) {
+ const normalized = normalizeCatalogEntry(entry);
+ if (assetIds.has(normalized.assetId)) {
+ throw new Error("Asset field catalog contains duplicate asset entries");
+ }
+ if (projectId !== undefined && projectId !== normalized.projectId) {
+ throw new Error("Asset field catalog cannot combine multiple projects");
+ }
+ projectId = normalized.projectId;
+ assetIds.add(normalized.assetId);
+ normalizedEntries.push(normalized);
+ for (const [path, types] of getEntryFields(normalized)) {
+ const field = fields.get(path) ?? {
+ occurrences: 0,
+ typeOccurrences: new Map<ObservedFieldType, number>(),
+ };
+ field.occurrences += 1;
+ for (const type of types) {
+ field.typeOccurrences.set(
+ type,
+ (field.typeOccurrences.get(type) ?? 0) + 1
+ );
+ }
+ fields.set(path, field);
+ }
+ }
+ const documentCount = normalizedEntries.length;
+ return {
+ entries: normalizedEntries,
+ catalog: {
+ ...(projectId === undefined ? {} : { projectId }),
+ documentCount,
+ fields: Array.from(fields, ([path, field]) => ({
+ path,
+ occurrences: field.occurrences,
+ optional: field.occurrences < documentCount,
+ types: Array.from(field.typeOccurrences, ([type, occurrences]) => ({
+ type,
+ occurrences,
+ })).sort((left, right) => compareStrings(left.type, right.type)),
+ mixed: field.typeOccurrences.size > 1,
+ })).sort((left, right) => compareStrings(left.path, right.path)),
+ } satisfies AggregatedAssetFieldCatalog,
+ };
+};
+
+export const createAssetFieldCatalog = async (
+ entries: readonly CanonicalAssetFileEntry[]
+): Promise<AssetFieldCatalog> => {
+ const aggregated = aggregateCatalogEntries(entries);
+ return {
+ format: "webstudio-asset-field-catalog",
+ version: 1,
+ canonicalRevision: await computeCanonicalAssetRevision(aggregated.entries),
+ ...aggregated.catalog,
+ };
+};
+
+const queryableStandardFields = new Set<string>(
+ assetQueryStandardFields.filter((field) => field !== "id")
+);
+
+const getBuilderQueryPath = (path: string) => {
+ if (path === "_id") {
+ return ["id"];
+ }
+ if (queryableStandardFields.has(path)) {
+ return [path];
+ }
+ const segments = parseStaticMemberPath(path);
+ if (
+ segments === undefined ||
+ segments.length < 2 ||
+ segments[0] !== "properties"
+ ) {
+ return;
+ }
+ return segments;
+};
+
+export const toBuilderAssetFieldCatalog = (
+ catalog: AssetFieldCatalog
+): BuilderAssetFieldCatalog =>
+ builderAssetFieldCatalog.parse({
+ format: "webstudio-builder-asset-field-catalog",
+ version: 1,
+ canonicalRevision: catalog.canonicalRevision,
+ documentCount: catalog.documentCount,
+ fields: Object.fromEntries(
+ catalog.fields.map((field) => {
+ const queryPath = getBuilderQueryPath(field.path);
+ return [
+ field.path,
+ {
+ ...(queryPath === undefined ? {} : { queryPath }),
+ types: field.types.map(({ type }) => type),
+ occurrences: field.occurrences,
+ ...(field.optional ? { optional: true } : {}),
+ ...(field.mixed ? { mixed: true } : {}),
+ },
+ ];
+ })
+ ),
+ });
diff --git a/packages/content-engine/src/frontmatter.ts b/packages/content-engine/src/frontmatter.ts
new file mode 100644
index 0000000000..912a8970a9
--- /dev/null
+++ b/packages/content-engine/src/frontmatter.ts
@@ -0,0 +1,206 @@
+import { contentEngineLimits } from "./limits";
+import { parseDocument } from "yaml";
+import {
+ decodeUtf8 as decodeUtf8Bytes,
+ toByteChunks,
+ type ByteSource,
+} from "./byte-stream";
+import {
+ normalizeStructuredDataObject,
+ StructuredDataError,
+} from "./structured-data";
+import { MarkdownMetadataError } from "./markdown-errors";
+import {
+ findMarkdownFrontmatter,
+ markdownFrontmatterEnvelopeBytes,
+} from "./markdown-scanner";
+
+export type MarkdownFrontmatter = {
+ properties: Record<string, unknown>;
+ frontmatterBytes: number;
+ consumedBytes: number;
+};
+
+type FrontmatterLimits = {
+ bytes: number;
+ depth: number;
+ fields: number;
+ stringBytes: number;
+ serializedBytes: number;
+};
+
+const defaultFrontmatterLimits: FrontmatterLimits = {
+ bytes: contentEngineLimits.frontmatterBytes,
+ depth: contentEngineLimits.frontmatterDepth,
+ fields: contentEngineLimits.frontmatterFields,
+ stringBytes: contentEngineLimits.frontmatterStringBytes,
+ serializedBytes: contentEngineLimits.indexedPropertiesBytes,
+};
+
+const decodeUtf8 = (bytes: Uint8Array) => {
+ try {
+ return decodeUtf8Bytes(bytes);
+ } catch {
+ throw new MarkdownMetadataError(
+ "FRONTMATTER_DECODING_FAILED",
+ "Markdown frontmatter is not valid UTF-8"
+ );
+ }
+};
+
+const parseYamlProperties = (
+ source: string,
+ limits: FrontmatterLimits
+): Record<string, unknown> => {
+ const document = parseDocument(source, {
+ schema: "core",
+ uniqueKeys: true,
+ });
+ if (document.errors.length > 0) {
+ throw new MarkdownMetadataError(
+ "FRONTMATTER_INVALID",
+ "Markdown frontmatter contains invalid YAML"
+ );
+ }
+
+ let value: unknown;
+ try {
+ value = document.toJS({ maxAliasCount: 0 });
+ } catch {
+ throw new MarkdownMetadataError(
+ "FRONTMATTER_INVALID",
+ "Markdown frontmatter contains unsupported YAML aliases"
+ );
+ }
+ if (value === null) {
+ return {};
+ }
+ try {
+ return normalizeStructuredDataObject(value, limits);
+ } catch (error) {
+ if (error instanceof StructuredDataError) {
+ if (error.code === "DEPTH_EXCEEDED") {
+ throw new MarkdownMetadataError(
+ "FRONTMATTER_DEPTH_EXCEEDED",
+ "Markdown frontmatter exceeds the nesting limit"
+ );
+ }
+ if (error.code === "FIELDS_EXCEEDED") {
+ throw new MarkdownMetadataError(
+ "FRONTMATTER_FIELDS_EXCEEDED",
+ "Markdown frontmatter exceeds the field limit"
+ );
+ }
+ if (error.code === "STRING_BYTES_EXCEEDED") {
+ throw new MarkdownMetadataError(
+ "FRONTMATTER_STRING_BYTES_EXCEEDED",
+ "Markdown frontmatter contains a string that exceeds the byte limit"
+ );
+ }
+ if (error.code === "SERIALIZED_BYTES_EXCEEDED") {
+ throw new MarkdownMetadataError(
+ "FRONTMATTER_BYTES_EXCEEDED",
+ "Markdown frontmatter properties exceed the indexed byte limit"
+ );
+ }
+ throw new MarkdownMetadataError(
+ "FRONTMATTER_INVALID",
+ "Markdown frontmatter must contain a JSON-compatible object"
+ );
+ }
+ throw error;
+ }
+};
+
+/**
+ * Reads only the bounded opening frontmatter block from a Markdown byte stream.
+ * Iteration stops as soon as the closing delimiter is found, so the body is
+ * neither decoded nor retained by list-query metadata indexing. MDX can reuse
+ * this path because its frontmatter plugins recognize blocks but do not parse
+ * the YAML data contained by them.
+ */
+export const extractMarkdownFrontmatter = async (
+ source: ByteSource,
+ overrides: Partial<FrontmatterLimits> = {}
+): Promise<MarkdownFrontmatter> => {
+ const limits = { ...defaultFrontmatterLimits, ...overrides };
+ const maximumReadBytes = limits.bytes + markdownFrontmatterEnvelopeBytes;
+ const buffer = new Uint8Array(maximumReadBytes);
+ let byteLength = 0;
+
+ for await (const chunk of toByteChunks(source)) {
+ let offset = 0;
+ while (offset < chunk.byteLength) {
+ const available = maximumReadBytes - byteLength;
+ if (available <= 0) {
+ break;
+ }
+ const initialRead = Math.max(0, 6 - byteLength);
+ let length = Math.min(chunk.byteLength - offset, initialRead);
+ if (initialRead === 0) {
+ const remaining = chunk.subarray(
+ offset,
+ Math.min(chunk.byteLength, offset + available)
+ );
+ const newline = remaining.indexOf(0x0a);
+ length = newline === -1 ? remaining.byteLength : newline + 1;
+ }
+ buffer.set(chunk.subarray(offset, offset + length), byteLength);
+ byteLength += length;
+ offset += length;
+
+ const bytes = buffer.subarray(0, byteLength);
+ const located = findMarkdownFrontmatter(bytes, false);
+ if (located === null) {
+ return {
+ properties: {},
+ frontmatterBytes: 0,
+ consumedBytes: bytes.length,
+ };
+ }
+ if (located !== undefined) {
+ const frontmatterBytes = located.yamlEnd - located.yamlStart;
+ if (frontmatterBytes > limits.bytes) {
+ throw new MarkdownMetadataError(
+ "FRONTMATTER_BYTES_EXCEEDED",
+ "Markdown frontmatter exceeds the byte limit"
+ );
+ }
+ const yaml = decodeUtf8(
+ bytes.subarray(located.yamlStart, located.yamlEnd)
+ );
+ return {
+ properties: parseYamlProperties(yaml, limits),
+ frontmatterBytes,
+ consumedBytes: located.blockEnd,
+ };
+ }
+ }
+ if (byteLength >= maximumReadBytes) {
+ break;
+ }
+ }
+
+ const bytes = buffer.subarray(0, byteLength);
+ const located = findMarkdownFrontmatter(bytes, true);
+ if (located === null) {
+ return { properties: {}, frontmatterBytes: 0, consumedBytes: bytes.length };
+ }
+ if (located !== undefined) {
+ const frontmatterBytes = located.yamlEnd - located.yamlStart;
+ if (frontmatterBytes <= limits.bytes) {
+ const yaml = decodeUtf8(
+ bytes.subarray(located.yamlStart, located.yamlEnd)
+ );
+ return {
+ properties: parseYamlProperties(yaml, limits),
+ frontmatterBytes,
+ consumedBytes: located.blockEnd,
+ };
+ }
+ }
+ throw new MarkdownMetadataError(
+ "FRONTMATTER_BYTES_EXCEEDED",
+ "Markdown frontmatter is not closed within the byte limit"
+ );
+};
diff --git a/packages/content-engine/src/hydration.test.ts b/packages/content-engine/src/hydration.test.ts
new file mode 100644
index 0000000000..b491bfea30
--- /dev/null
+++ b/packages/content-engine/src/hydration.test.ts
@@ -0,0 +1,308 @@
+import { describe, expect, test, vi } from "vitest";
+import type { AssetFileDocument } from "./schema";
+import { contentEngineLimits } from "./limits";
+import {
+ hydrateAssetResourceResult,
+ type AssetResourceContentReader,
+} from "./hydration";
+
+const encoder = new TextEncoder();
+const createDocument = (
+ id: string,
+ text: string,
+ overrides: Partial<AssetFileDocument> = {}
+): AssetFileDocument => ({
+ _id: id,
+ _type: "asset.file",
+ name: `${id}.md`,
+ path: `blog/${id}.md`,
+ key: id,
+ extension: "md",
+ mimeType: "text/markdown",
+ size: encoder.encode(text).byteLength,
+ revision: `revision-${id}`,
+ contentRef: `stored-${id}`,
+ properties: {},
+ ...overrides,
+});
+const identity = (document: AssetFileDocument) => ({
+ _id: document._id,
+ revision: document.revision,
+ contentRef: document.contentRef,
+});
+const createReader = (files: Record<string, string | Uint8Array>) =>
+ vi.fn<AssetResourceContentReader>(async (contentRef, range) => {
+ const source = files[contentRef];
+ if (source === undefined) {
+ throw new Error("missing fixture");
+ }
+ const bytes = typeof source === "string" ? encoder.encode(source) : source;
+ const selected =
+ range === undefined
+ ? bytes
+ : bytes.subarray(range.offset, range.offset + range.length);
+ return {
+ data: {
+ async *[Symbol.asyncIterator]() {
+ yield selected;
+ },
+ },
+ contentLength: selected.byteLength,
+ };
+ });
+
+describe("selected asset content hydration", () => {
+ test("does not inspect identities or read files in none mode", async () => {
+ const read = createReader({});
+ await expect(
+ hydrateAssetResourceResult({
+ result: { projected: true },
+ documents: [],
+ options: { mode: "none" },
+ read,
+ })
+ ).resolves.toEqual({
+ content: {},
+ hydratedFileCount: 0,
+ hydratedBytes: 0,
+ });
+ expect(read).not.toHaveBeenCalled();
+ });
+
+ test("hydrates no files when a detail query has no match", async () => {
+ const read = createReader({});
+ await expect(
+ hydrateAssetResourceResult({
+ result: null,
+ documents: [],
+ options: { mode: "full" },
+ read,
+ })
+ ).resolves.toEqual({
+ content: {},
+ hydratedFileCount: 0,
+ hydratedBytes: 0,
+ });
+ expect(read).not.toHaveBeenCalled();
+ });
+
+ test("hydrates complete text for selected IDs only and deduplicates IDs", async () => {
+ const first = createDocument("first", "# First");
+ const second = createDocument("second", "# Second");
+ const read = createReader({
+ [first.contentRef]: "# First",
+ [second.contentRef]: "# Second",
+ });
+ const result = await hydrateAssetResourceResult({
+ result: [identity(first), identity(first)],
+ documents: [first, second],
+ options: { mode: "full" },
+ read,
+ });
+
+ expect(result.content[first._id]?.text).toBe("# First");
+ expect(result.hydratedFileCount).toBe(1);
+ expect(read).toHaveBeenCalledOnce();
+ expect(read).toHaveBeenCalledWith(first.contentRef, {
+ offset: 0,
+ length: first.size,
+ });
+ });
+
+ test("hydrates a bounded byte range with range metadata", async () => {
+ const document = createDocument("range", "0123456789");
+ const read = createReader({ [document.contentRef]: "0123456789" });
+ const result = await hydrateAssetResourceResult({
+ result: identity(document),
+ documents: [document],
+ options: { mode: "range", offset: 3, length: 4 },
+ read,
+ });
+
+ expect(result.content[document._id]).toMatchObject({
+ text: "3456",
+ range: { offset: 3, length: 4, total: 10 },
+ });
+ expect(read).toHaveBeenCalledWith(document.contentRef, {
+ offset: 3,
+ length: 4,
+ });
+ });
+
+ test("decodes Markdown body without YAML frontmatter", async () => {
+ const source = "---\ntitle: Hello\n---\n# Body\n";
+ const document = createDocument("markdown", source);
+ const read = createReader({ [document.contentRef]: source });
+ const result = await hydrateAssetResourceResult({
+ result: identity(document),
+ documents: [document],
+ options: { mode: "markdown-body" },
+ read,
+ });
+ expect(result.content[document._id]?.text).toBe("# Body\n");
+ });
+
+ test("requires selected projections to retain stable content identity", async () => {
+ const document = createDocument("post", "Post");
+ const read = createReader({ [document.contentRef]: "Post" });
+ await expect(
+ hydrateAssetResourceResult({
+ result: { _id: document._id },
+ documents: [document],
+ options: { mode: "full" },
+ read,
+ })
+ ).rejects.toMatchObject({ code: "CONTENT_IDENTITY_REQUIRED" });
+ await expect(
+ hydrateAssetResourceResult({
+ result: { ...identity(document), revision: "stale" },
+ documents: [document],
+ options: { mode: "full" },
+ read,
+ })
+ ).rejects.toMatchObject({ code: "CONTENT_IDENTITY_REQUIRED" });
+ expect(read).not.toHaveBeenCalled();
+ });
+
+ test("enforces file-count, per-file, and total-byte limits before reads", async () => {
+ const read = createReader({});
+ const many = Array.from(
+ { length: contentEngineLimits.hydratedFileCount + 1 },
+ (_, index) => createDocument(`post-${index}`, "x")
+ );
+ await expect(
+ hydrateAssetResourceResult({
+ result: many.map(identity),
+ documents: many,
+ options: { mode: "full" },
+ read,
+ })
+ ).rejects.toMatchObject({ code: "CONTENT_LIMIT_EXCEEDED" });
+
+ const tooLarge = createDocument("large", "", {
+ size: contentEngineLimits.hydratedFileBytes + 1,
+ });
+ await expect(
+ hydrateAssetResourceResult({
+ result: identity(tooLarge),
+ documents: [tooLarge],
+ options: { mode: "full" },
+ read,
+ })
+ ).rejects.toMatchObject({ code: "CONTENT_LIMIT_EXCEEDED" });
+
+ const total = Array.from({ length: 3 }, (_, index) =>
+ createDocument(`large-${index}`, "", {
+ size: contentEngineLimits.hydratedFileBytes,
+ })
+ );
+ await expect(
+ hydrateAssetResourceResult({
+ result: total.map(identity),
+ documents: total,
+ options: { mode: "full" },
+ read,
+ })
+ ).rejects.toMatchObject({ code: "CONTENT_LIMIT_EXCEEDED" });
+ expect(read).not.toHaveBeenCalled();
+ });
+
+ test("rejects binary and invalid UTF-8 while treating frontmatter as data", async () => {
+ const binary = createDocument("binary", "png", {
+ name: "binary.png",
+ extension: "png",
+ mimeType: "image/png",
+ });
+ const invalid = createDocument("invalid", "xx", { size: 2 });
+ const protectedDocument = createDocument("private", "secret", {
+ properties: { private: true },
+ });
+ const read = createReader({
+ [binary.contentRef]: "png",
+ [invalid.contentRef]: new Uint8Array([0xc3, 0x28]),
+ [protectedDocument.contentRef]: "secret",
+ });
+ await expect(
+ hydrateAssetResourceResult({
+ result: identity(binary),
+ documents: [binary],
+ options: { mode: "full" },
+ read,
+ })
+ ).rejects.toMatchObject({ code: "CONTENT_NOT_TEXT" });
+ await expect(
+ hydrateAssetResourceResult({
+ result: identity(invalid),
+ documents: [invalid],
+ options: { mode: "full" },
+ read,
+ })
+ ).rejects.toMatchObject({ code: "CONTENT_DECODING_FAILED" });
+ await expect(
+ hydrateAssetResourceResult({
+ result: identity(protectedDocument),
+ documents: [protectedDocument],
+ options: { mode: "full" },
+ read,
+ })
+ ).resolves.toMatchObject({
+ content: { private: { text: "secret" } },
+ });
+ });
+
+ test("hydrates SVG assets as supported UTF-8 text", async () => {
+ const source = '<svg xmlns="http://www.w3.org/2000/svg"></svg>';
+ const document = createDocument("vector", source, {
+ name: "vector.svg",
+ extension: "svg",
+ mimeType: "image/svg+xml",
+ });
+ const read = createReader({ [document.contentRef]: source });
+
+ await expect(
+ hydrateAssetResourceResult({
+ result: identity(document),
+ documents: [document],
+ options: { mode: "full" },
+ read,
+ })
+ ).resolves.toMatchObject({
+ content: { vector: { text: source } },
+ });
+ });
+
+ test("waits for every started content read before propagating a failure", async () => {
+ const failed = createDocument("failed", "x");
+ const slow = createDocument("slow", "y");
+ let release: (() => void) | undefined;
+ let slowReadCompleted = false;
+ const read: AssetResourceContentReader = async (contentRef) => {
+ if (contentRef === failed.contentRef) {
+ throw new Error("read failed");
+ }
+ await new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ slowReadCompleted = true;
+ return {
+ data: {
+ async *[Symbol.asyncIterator]() {
+ yield encoder.encode("y");
+ },
+ },
+ };
+ };
+ const pending = hydrateAssetResourceResult({
+ result: [identity(failed), identity(slow)],
+ documents: [failed, slow],
+ options: { mode: "full" },
+ read,
+ });
+
+ await expect.poll(() => release).toBeTypeOf("function");
+ release?.();
+
+ await expect(pending).rejects.toThrow("read failed");
+ expect(slowReadCompleted).toBe(true);
+ });
+});
diff --git a/packages/content-engine/src/hydration.ts b/packages/content-engine/src/hydration.ts
new file mode 100644
index 0000000000..8a35327acb
--- /dev/null
+++ b/packages/content-engine/src/hydration.ts
@@ -0,0 +1,339 @@
+import type {
+ AssetResourceContentOptions,
+ ContentDatabaseDocument,
+ HydratedAssetContent,
+} from "./schema";
+import { contentEngineLimits } from "./limits";
+import { extractMarkdownBody } from "./markdown-body";
+import {
+ ByteLimitExceededError,
+ decodeUtf8,
+ getUtf8ByteLength,
+ readBoundedBytes,
+} from "./byte-stream";
+import { mapBounded } from "./async-utils";
+import {
+ rewriteMarkdownAssetReferenceRanges,
+ type MarkdownAssetReferences,
+} from "./markdown-references";
+
+export class AssetResourceHydrationError extends Error {
+ readonly code:
+ | "CONTENT_IDENTITY_REQUIRED"
+ | "CONTENT_NOT_TEXT"
+ | "CONTENT_DECODING_FAILED"
+ | "CONTENT_LIMIT_EXCEEDED";
+ readonly details?: Record<string, string | number>;
+
+ constructor({
+ code,
+ message,
+ details,
+ }: {
+ code: AssetResourceHydrationError["code"];
+ message: string;
+ details?: AssetResourceHydrationError["details"];
+ }) {
+ super(message);
+ this.name = "AssetResourceHydrationError";
+ this.code = code;
+ this.details = details;
+ }
+}
+
+export type AssetResourceContentReader = (
+ contentRef: string,
+ range?: { offset: number; length: number }
+) => Promise<{
+ data: AsyncIterable<Uint8Array>;
+ contentLength?: number;
+}>;
+
+type SelectedIdentity = {
+ _id: string;
+ revision: string;
+ contentRef: string;
+};
+
+const getSelectedIdentities = (result: unknown): SelectedIdentity[] => {
+ if (result === null) {
+ return [];
+ }
+ const values = Array.isArray(result) ? result : [result];
+ const identities = new Map<string, SelectedIdentity>();
+ for (const value of values) {
+ if (
+ typeof value !== "object" ||
+ value === null ||
+ "_id" in value === false ||
+ typeof value._id !== "string" ||
+ "revision" in value === false ||
+ typeof value.revision !== "string" ||
+ "contentRef" in value === false ||
+ typeof value.contentRef !== "string"
+ ) {
+ throw new AssetResourceHydrationError({
+ code: "CONTENT_IDENTITY_REQUIRED",
+ message:
+ "Hydrated query results must retain _id, revision, and contentRef",
+ });
+ }
+ const previous = identities.get(value._id);
+ if (
+ previous !== undefined &&
+ (previous.revision !== value.revision ||
+ previous.contentRef !== value.contentRef)
+ ) {
+ throw new AssetResourceHydrationError({
+ code: "CONTENT_IDENTITY_REQUIRED",
+ message: "A selected asset ID has conflicting content identity",
+ details: { assetId: value._id },
+ });
+ }
+ identities.set(value._id, {
+ _id: value._id,
+ revision: value.revision,
+ contentRef: value.contentRef,
+ });
+ }
+ return Array.from(identities.values());
+};
+
+const isTextDocument = (document: ContentDatabaseDocument) =>
+ typeof document.mimeType === "string" &&
+ (document.mimeType.startsWith("text/") ||
+ [
+ "application/json",
+ "application/javascript",
+ "application/xml",
+ "image/svg+xml",
+ ].includes(document.mimeType));
+
+const readBytes = async ({
+ read,
+ contentRef,
+ range,
+ maximumBytes,
+}: {
+ read: AssetResourceContentReader;
+ contentRef: string;
+ range?: { offset: number; length: number };
+ maximumBytes: number;
+}) => {
+ if (maximumBytes === 0) {
+ return new Uint8Array();
+ }
+ const response = await read(contentRef, range);
+ try {
+ return await readBoundedBytes(response.data, maximumBytes);
+ } catch (error) {
+ if (error instanceof ByteLimitExceededError) {
+ throw new AssetResourceHydrationError({
+ code: "CONTENT_LIMIT_EXCEEDED",
+ message: "Asset storage returned more content than requested",
+ });
+ }
+ throw error;
+ }
+};
+
+const decodeText = (bytes: Uint8Array) => {
+ try {
+ return decodeUtf8(bytes);
+ } catch {
+ throw new AssetResourceHydrationError({
+ code: "CONTENT_DECODING_FAILED",
+ message: "Selected asset content is not valid UTF-8",
+ });
+ }
+};
+
+const getAssetResourceHydrationReadLength = (
+ document: ContentDatabaseDocument & { size: number },
+ options: Exclude<AssetResourceContentOptions, { mode: "none" }>
+) => {
+ if (options.mode === "range") {
+ return Math.max(
+ 0,
+ Math.min(options.length, document.size - options.offset)
+ );
+ }
+ const maximumBytes =
+ options.maxBytes ?? contentEngineLimits.hydratedFileBytes;
+ if (document.size > maximumBytes) {
+ throw new AssetResourceHydrationError({
+ code: "CONTENT_LIMIT_EXCEEDED",
+ message: "Selected asset exceeds the per-file content limit",
+ details: {
+ assetId: document._id,
+ assetBytes: document.size,
+ fileByteLimit: maximumBytes,
+ },
+ });
+ }
+ return document.size;
+};
+
+export const hydrateAssetResourceResult = async ({
+ result,
+ documents,
+ options,
+ read,
+ assetReferences,
+ assetUrls,
+}: {
+ result: unknown;
+ documents: readonly ContentDatabaseDocument[];
+ options: AssetResourceContentOptions;
+ read: AssetResourceContentReader;
+ assetReferences?: MarkdownAssetReferences;
+ assetUrls?: Readonly<Record<string, string>>;
+}) => {
+ if (options.mode === "none") {
+ return { content: {}, hydratedFileCount: 0, hydratedBytes: 0 };
+ }
+ const identities = getSelectedIdentities(result);
+ if (identities.length > contentEngineLimits.hydratedFileCount) {
+ throw new AssetResourceHydrationError({
+ code: "CONTENT_LIMIT_EXCEEDED",
+ message: "Too many selected assets requested content hydration",
+ details: {
+ fileCount: identities.length,
+ fileCountLimit: contentEngineLimits.hydratedFileCount,
+ },
+ });
+ }
+ const documentsById = new Map(
+ documents.map((document) => [document._id, document])
+ );
+ const selected = identities.map((identity) => {
+ const document = documentsById.get(identity._id);
+ if (
+ document === undefined ||
+ document.revision !== identity.revision ||
+ document.contentRef !== identity.contentRef ||
+ typeof document.size !== "number" ||
+ typeof document.mimeType !== "string"
+ ) {
+ throw new AssetResourceHydrationError({
+ code: "CONTENT_IDENTITY_REQUIRED",
+ message: "Selected asset content identity is stale or unavailable",
+ details: { assetId: identity._id },
+ });
+ }
+ const hydratableDocument = {
+ ...document,
+ size: document.size,
+ mimeType: document.mimeType,
+ };
+ if (isTextDocument(hydratableDocument) === false) {
+ throw new AssetResourceHydrationError({
+ code: "CONTENT_NOT_TEXT",
+ message: "Selected binary asset cannot be embedded as text",
+ details: {
+ assetId: identity._id,
+ mimeType: hydratableDocument.mimeType,
+ },
+ });
+ }
+ return {
+ identity,
+ document: hydratableDocument,
+ readLength: getAssetResourceHydrationReadLength(
+ hydratableDocument,
+ options
+ ),
+ };
+ });
+ const totalReadBytes = selected.reduce(
+ (total, item) => total + item.readLength,
+ 0
+ );
+ if (totalReadBytes > contentEngineLimits.hydratedTotalBytes) {
+ throw new AssetResourceHydrationError({
+ code: "CONTENT_LIMIT_EXCEEDED",
+ message: "Selected assets exceed the total hydrated-content limit",
+ details: {
+ totalReadBytes,
+ totalByteLimit: contentEngineLimits.hydratedTotalBytes,
+ },
+ });
+ }
+
+ const hydrated = await mapBounded(
+ selected,
+ contentEngineLimits.concurrentContentReads,
+ async (item) => {
+ const range =
+ options.mode === "range"
+ ? { offset: options.offset, length: item.readLength }
+ : item.readLength === 0
+ ? undefined
+ : { offset: 0, length: item.readLength };
+ const bytes = await readBytes({
+ read,
+ contentRef: item.identity.contentRef,
+ range,
+ maximumBytes: item.readLength,
+ });
+ if (bytes.byteLength !== item.readLength) {
+ throw new AssetResourceHydrationError({
+ code: "CONTENT_IDENTITY_REQUIRED",
+ message: "Selected asset bytes do not match canonical metadata",
+ details: { assetId: item.identity._id },
+ });
+ }
+ let text: string;
+ if (options.mode === "markdown-body") {
+ try {
+ text = (await extractMarkdownBody(bytes, item.readLength || 1)).body;
+ const references = assetReferences?.[item.identity.contentRef];
+ if (references !== undefined && assetUrls !== undefined) {
+ text = rewriteMarkdownAssetReferenceRanges({
+ markdown: text,
+ references,
+ assetUrls,
+ });
+ }
+ } catch {
+ throw new AssetResourceHydrationError({
+ code: "CONTENT_DECODING_FAILED",
+ message: "Selected Markdown body could not be decoded",
+ details: { assetId: item.identity._id },
+ });
+ }
+ } else {
+ text = decodeText(bytes);
+ }
+ const returnedBytes = getUtf8ByteLength(text);
+ return {
+ id: item.identity._id,
+ returnedBytes,
+ content: {
+ ...item.identity,
+ encoding: "utf-8" as const,
+ text,
+ ...(options.mode === "range"
+ ? {
+ range: {
+ offset: options.offset,
+ length: bytes.byteLength,
+ total: item.document.size,
+ },
+ }
+ : {}),
+ },
+ };
+ }
+ );
+ return {
+ content: Object.fromEntries(
+ hydrated.map(({ id, content }) => [id, content])
+ ) as Record<string, HydratedAssetContent>,
+ hydratedFileCount: selected.length,
+ hydratedBytes: hydrated.reduce(
+ (total, { returnedBytes }) => total + returnedBytes,
+ 0
+ ),
+ };
+};
diff --git a/packages/content-engine/src/index.ts b/packages/content-engine/src/index.ts
new file mode 100644
index 0000000000..3f9f3743d1
--- /dev/null
+++ b/packages/content-engine/src/index.ts
@@ -0,0 +1,11 @@
+export * from "./schema";
+export * from "./limits";
+export * from "./compilation-plan";
+export * from "./hydration";
+export * from "./structured-query";
+export * from "./projection";
+export * from "./content-artifact";
+export * from "./content-database";
+export * from "./request";
+export * from "./query-source";
+export * from "./query-error";
diff --git a/packages/content-engine/src/json.test.ts b/packages/content-engine/src/json.test.ts
new file mode 100644
index 0000000000..c93cd61cf4
--- /dev/null
+++ b/packages/content-engine/src/json.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, test } from "vitest";
+import { extractJsonProperties } from "./json";
+
+describe("JSON metadata extraction", () => {
+ test("extracts a bounded root object with arbitrary safe keys", async () => {
+ const source = `\uFEFF{"title":"Post","draft":false,"nested":{"value":1},"__proto__":{"safe":true}}`;
+ const result = await extractJsonProperties(source);
+
+ expect(result.sourceBytes).toBe(
+ new TextEncoder().encode(source).byteLength
+ );
+ expect(result.properties).toEqual(
+ JSON.parse(
+ '{"title":"Post","draft":false,"nested":{"value":1},"__proto__":{"safe":true}}'
+ )
+ );
+ expect(({} as { safe?: boolean }).safe).toBeUndefined();
+ });
+
+ test("rejects invalid UTF-8, invalid JSON, and non-object roots", async () => {
+ await expect(
+ extractJsonProperties(new Uint8Array([0xc3, 0x28]))
+ ).rejects.toMatchObject({ code: "JSON_DECODING_FAILED" });
+ await expect(extractJsonProperties("{")).rejects.toMatchObject({
+ code: "JSON_INVALID",
+ });
+ await expect(extractJsonProperties("[]")).rejects.toMatchObject({
+ code: "JSON_INVALID",
+ });
+ });
+
+ test("enforces byte, depth, field, string, and numeric limits", async () => {
+ await expect(
+ extractJsonProperties('{"value":"long"}', { bytes: 5 })
+ ).rejects.toMatchObject({ code: "JSON_BYTES_EXCEEDED" });
+ await expect(
+ extractJsonProperties('{"a":{"b":1}}', { depth: 2 })
+ ).rejects.toMatchObject({ code: "JSON_DEPTH_EXCEEDED" });
+ await expect(
+ extractJsonProperties('{"a":1,"b":2}', { fields: 1 })
+ ).rejects.toMatchObject({ code: "JSON_FIELDS_EXCEEDED" });
+ await expect(
+ extractJsonProperties('{"items":[1,2]}', { fields: 2 })
+ ).rejects.toMatchObject({ code: "JSON_FIELDS_EXCEEDED" });
+ await expect(
+ extractJsonProperties('{"value":"long"}', { stringBytes: 3 })
+ ).rejects.toMatchObject({ code: "JSON_STRING_BYTES_EXCEEDED" });
+ await expect(
+ extractJsonProperties('{"value":"long"}', { serializedBytes: 8 })
+ ).rejects.toMatchObject({ code: "JSON_BYTES_EXCEEDED" });
+ await expect(
+ extractJsonProperties('{"value":9007199254740993}')
+ ).rejects.toMatchObject({ code: "JSON_INVALID" });
+ });
+
+ test("stops consuming an async stream after detecting the byte limit", async () => {
+ let consumed = 0;
+ const source = {
+ async *[Symbol.asyncIterator]() {
+ for (const chunk of ['{"value":', '"too long"}', "unused"]) {
+ consumed += 1;
+ yield new TextEncoder().encode(chunk);
+ }
+ },
+ };
+
+ await expect(
+ extractJsonProperties(source, { bytes: 10 })
+ ).rejects.toMatchObject({ code: "JSON_BYTES_EXCEEDED" });
+ expect(consumed).toBe(2);
+ });
+});
diff --git a/packages/content-engine/src/json.ts b/packages/content-engine/src/json.ts
new file mode 100644
index 0000000000..2599e59478
--- /dev/null
+++ b/packages/content-engine/src/json.ts
@@ -0,0 +1,117 @@
+import { contentEngineLimits } from "./limits";
+import {
+ ByteLimitExceededError,
+ decodeUtf8,
+ readBoundedBytes,
+ stripUtf8ByteOrderMark,
+ type ByteSource,
+} from "./byte-stream";
+import {
+ normalizeStructuredDataObject,
+ StructuredDataError,
+ type StructuredDataLimits,
+} from "./structured-data";
+
+export type JsonMetadataErrorCode =
+ | "JSON_BYTES_EXCEEDED"
+ | "JSON_DECODING_FAILED"
+ | "JSON_INVALID"
+ | "JSON_DEPTH_EXCEEDED"
+ | "JSON_FIELDS_EXCEEDED"
+ | "JSON_STRING_BYTES_EXCEEDED";
+
+export class JsonMetadataError extends Error {
+ readonly code: JsonMetadataErrorCode;
+
+ constructor(code: JsonMetadataErrorCode, message: string) {
+ super(message);
+ this.name = "JsonMetadataError";
+ this.code = code;
+ }
+}
+
+type JsonMetadataLimits = StructuredDataLimits & { bytes: number };
+
+const defaultLimits: JsonMetadataLimits = {
+ bytes: contentEngineLimits.jsonBytes,
+ depth: contentEngineLimits.jsonDepth,
+ fields: contentEngineLimits.jsonFields,
+ stringBytes: contentEngineLimits.jsonStringBytes,
+ serializedBytes: contentEngineLimits.indexedPropertiesBytes,
+};
+
+const structuredError = (error: StructuredDataError): JsonMetadataError => {
+ if (error.code === "DEPTH_EXCEEDED") {
+ return new JsonMetadataError(
+ "JSON_DEPTH_EXCEEDED",
+ "JSON metadata exceeds the nesting limit"
+ );
+ }
+ if (error.code === "FIELDS_EXCEEDED") {
+ return new JsonMetadataError(
+ "JSON_FIELDS_EXCEEDED",
+ "JSON metadata exceeds the field limit"
+ );
+ }
+ if (error.code === "STRING_BYTES_EXCEEDED") {
+ return new JsonMetadataError(
+ "JSON_STRING_BYTES_EXCEEDED",
+ "JSON metadata contains a string that exceeds the byte limit"
+ );
+ }
+ if (error.code === "SERIALIZED_BYTES_EXCEEDED") {
+ return new JsonMetadataError(
+ "JSON_BYTES_EXCEEDED",
+ "JSON properties exceed the indexed byte limit"
+ );
+ }
+ return new JsonMetadataError(
+ "JSON_INVALID",
+ "JSON metadata must contain a JSON object"
+ );
+};
+
+/** Reads one bounded JSON file and exposes its root object as query fields. */
+export const extractJsonProperties = async (
+ source: ByteSource,
+ overrides: Partial<JsonMetadataLimits> = {}
+) => {
+ const limits = { ...defaultLimits, ...overrides };
+ let bytes: Uint8Array;
+ try {
+ bytes = await readBoundedBytes(source, limits.bytes);
+ } catch (error) {
+ if (error instanceof ByteLimitExceededError) {
+ throw new JsonMetadataError(
+ "JSON_BYTES_EXCEEDED",
+ "JSON metadata exceeds the byte limit"
+ );
+ }
+ throw error;
+ }
+
+ let value: unknown;
+ try {
+ value = JSON.parse(stripUtf8ByteOrderMark(decodeUtf8(bytes)));
+ } catch (error) {
+ if (error instanceof TypeError) {
+ throw new JsonMetadataError(
+ "JSON_DECODING_FAILED",
+ "JSON metadata is not valid UTF-8"
+ );
+ }
+ throw new JsonMetadataError("JSON_INVALID", "JSON metadata is invalid");
+ }
+
+ try {
+ return {
+ properties: normalizeStructuredDataObject(value, limits),
+ sourceBytes: bytes.byteLength,
+ };
+ } catch (error) {
+ if (error instanceof StructuredDataError) {
+ throw structuredError(error);
+ }
+ throw error;
+ }
+};
diff --git a/packages/content-engine/src/limits.ts b/packages/content-engine/src/limits.ts
new file mode 100644
index 0000000000..77247b2e27
--- /dev/null
+++ b/packages/content-engine/src/limits.ts
@@ -0,0 +1,40 @@
+/** Safety and size limits shared by content compilation and query runtimes. */
+export const contentEngineLimits = {
+ requestBytes: 512 * 1024,
+ filterCount: 32,
+ filterDepth: 8,
+ sortCount: 8,
+ outputFieldCount: 256,
+ fieldPathDepth: 9,
+ defaultResultCount: 20,
+ resultCount: 1000,
+ resultBytes: 16 * 1024 * 1024,
+ candidateDocuments: 1000,
+ databaseBytes: 500 * 1024,
+ frontmatterBytes: 64 * 1024,
+ frontmatterDepth: 8,
+ frontmatterFields: 256,
+ frontmatterStringBytes: 16 * 1024,
+ jsonBytes: 1024 * 1024,
+ jsonDepth: 8,
+ jsonFields: 256,
+ jsonStringBytes: 16 * 1024,
+ indexedPropertiesBytes: 64 * 1024,
+ excerptBytes: 2 * 1024,
+ hydratedFileBytes: 1024 * 1024,
+ hydratedTotalBytes: 2 * 1024 * 1024,
+ hydratedFileCount: 20,
+ hydratedRangeBytes: 256 * 1024,
+ concurrentContentReads: 8,
+} as const;
+
+export const parseContentDatabaseMaxBytes = (value: string | undefined) => {
+ if (value === undefined || value === "") {
+ return contentEngineLimits.databaseBytes;
+ }
+ const maxBytes = Number(value);
+ if (Number.isSafeInteger(maxBytes) === false || maxBytes <= 0) {
+ throw new Error("CONTENT_DATABASE_MAX_BYTES must be a positive integer");
+ }
+ return maxBytes;
+};
diff --git a/packages/content-engine/src/markdown-assets.test.ts b/packages/content-engine/src/markdown-assets.test.ts
new file mode 100644
index 0000000000..2c5cb9879a
--- /dev/null
+++ b/packages/content-engine/src/markdown-assets.test.ts
@@ -0,0 +1,215 @@
+import { describe, expect, test } from "vitest";
+import { discoverMarkdownAssetReferenceRanges } from "./markdown-assets";
+import { rewriteMarkdownAssetReferenceRanges } from "./markdown-references";
+
+const discoverReferences = (input: {
+ markdown: string;
+ sourcePath: string;
+ assetIdsByPath: ReadonlyMap<string, string>;
+}) =>
+ Object.fromEntries(
+ discoverMarkdownAssetReferenceRanges(input).map(
+ ({ start, end, assetId }) => [input.markdown.slice(start, end), assetId]
+ )
+ );
+
+const rewriteDiscoveredReferences = ({
+ markdown,
+ sourcePath = "blog/post.md",
+ assetIdsByPath,
+ assetUrls,
+}: {
+ markdown: string;
+ sourcePath?: string;
+ assetIdsByPath: ReadonlyMap<string, string>;
+ assetUrls: Readonly<Record<string, string>>;
+}) =>
+ rewriteMarkdownAssetReferenceRanges({
+ markdown,
+ references: discoverMarkdownAssetReferenceRanges({
+ markdown,
+ sourcePath,
+ assetIdsByPath,
+ }),
+ assetUrls,
+ });
+
+describe("Markdown asset references", () => {
+ test("resolves conventional references against the Markdown file's folder", () => {
+ const references = discoverReferences({
+ sourcePath: "blog/posts/2026/hello.md",
+ markdown: `
+![Cover](./cover.png)
+![Hero](../../images/hero%20image.png#crop)
+[Download](./files/guide.pdf?download=1)
+[Shared](../../../shared/press-kit.zip)
+[Website](https://example.com)
+[Section](#section)
+ `,
+ assetIdsByPath: new Map([
+ ["blog/posts/2026/cover.png", "cover"],
+ ["blog/images/hero%20image.png", "hero"],
+ ["blog/posts/2026/files/guide.pdf", "guide"],
+ ["shared/press-kit.zip", "press-kit"],
+ ]),
+ });
+
+ expect(references).toEqual({
+ "./cover.png": "cover",
+ "../../images/hero%20image.png#crop": "hero",
+ "./files/guide.pdf?download=1": "guide",
+ "../../../shared/press-kit.zip": "press-kit",
+ });
+ });
+
+ test("does not treat absolute, root-relative, fragment, or malformed URLs as Asset references", () => {
+ const references = discoverReferences({
+ sourcePath: "blog/post.md",
+ markdown: `
+[Absolute](https://example.com/file.pdf)
+[Protocol relative](//example.com/file.pdf)
+[Root relative](/images/hero.png)
+[Email](mailto:[email protected])
+[Fragment](#section)
+[Query](?preview=true)
+[Malformed](./images/hero%2Fimage.png)
+ `,
+ assetIdsByPath: new Map([
+ ["blog/images/hero/image.png", "encoded-slash"],
+ ["images/hero.png", "root-relative"],
+ ]),
+ });
+
+ expect(references).toEqual({});
+ });
+
+ test("resolves canonical encoded asset paths", () => {
+ expect(
+ discoverReferences({
+ sourcePath: "blog/special%20%23%20%3F%20%25/post.md",
+ markdown:
+ "![Hero](./hero%20%23%20%3F%20%25.png)\n![Unicode](./Ol%C3%A1.png)",
+ assetIdsByPath: new Map([
+ ["blog/special%20%23%20%3F%20%25/hero%20%23%20%3F%20%25.png", "hero"],
+ ["blog/special%20%23%20%3F%20%25/Ol%C3%A1.png", "unicode"],
+ ]),
+ })
+ ).toEqual({
+ "./hero%20%23%20%3F%20%25.png": "hero",
+ "./Ol%C3%A1.png": "unicode",
+ });
+ });
+
+ test("preserves encoded dot segments in canonical source folders", () => {
+ expect(
+ discoverReferences({
+ sourcePath: "%2E/%2E%2E/post.md",
+ markdown: "![Hero](./hero.png)",
+ assetIdsByPath: new Map([["%2E/%2E%2E/hero.png", "hero"]]),
+ })
+ ).toEqual({ "./hero.png": "hero" });
+ });
+
+ test("resolves asset IDs inserted by the Builder", () => {
+ expect(
+ discoverReferences({
+ sourcePath: "blog/post.md",
+ markdown: "![Hero](image-id)",
+ assetIdsByPath: new Map([["images/hero.png", "image-id"]]),
+ })
+ ).toEqual({ "image-id": "image-id" });
+ });
+
+ test("rewrites references while preserving query strings and fragments", () => {
+ const markdown = `
+![Hero](../images/hero.png#crop)
+
+[Download][guide]
+
+[guide]: ./guide.pdf?download=1
+
+| Image |
+| --- |
+| ![Table image](./table.png) |
+ `.trim();
+ const result = rewriteDiscoveredReferences({
+ markdown,
+ assetIdsByPath: new Map([
+ ["images/hero.png", "hero"],
+ ["blog/guide.pdf", "guide"],
+ ["blog/table.png", "table"],
+ ]),
+ assetUrls: {
+ hero: "/assets/hero.png",
+ guide: "/assets/guide.pdf",
+ table: "/assets/table.png",
+ },
+ });
+
+ expect(result).toContain("/assets/hero.png#crop");
+ expect(result).toContain("/assets/guide.pdf?download=1");
+ expect(result).toContain("/assets/table.png");
+ expect(result).toContain("| Image");
+ expect(result).toContain("[Download][guide]");
+ });
+
+ test("preserves Markdown formatting and decodes destination syntax", () => {
+ const markdown =
+ 'Prefix 😀 [Download](<./guide&amp;notes.pdf> "Title") suffix';
+
+ expect(
+ rewriteDiscoveredReferences({
+ markdown,
+ assetIdsByPath: new Map([["blog/guide%26notes.pdf", "guide"]]),
+ assetUrls: { guide: "/assets/guide.pdf" },
+ })
+ ).toBe('Prefix 😀 [Download](</assets/guide.pdf> "Title") suffix');
+ });
+
+ test("records body-relative destination ranges for parser-free runtime rewriting", () => {
+ const markdown = "😀 ![Hero](../hero.png?size=2#crop)";
+
+ expect(
+ discoverMarkdownAssetReferenceRanges({
+ markdown,
+ sourcePath: "blog/post.md",
+ assetIdsByPath: new Map([["hero.png", "hero"]]),
+ })
+ ).toEqual([
+ {
+ start: markdown.indexOf("../hero.png"),
+ end: markdown.indexOf("../hero.png") + "../hero.png?size=2#crop".length,
+ assetId: "hero",
+ suffix: "?size=2#crop",
+ },
+ ]);
+ });
+
+ test("leaves Markdown unchanged when no runtime URL is available", () => {
+ const markdown = "![Hero](./hero.png)";
+ expect(
+ rewriteDiscoveredReferences({
+ markdown,
+ assetIdsByPath: new Map([["blog/hero.png", "hero"]]),
+ assetUrls: {},
+ })
+ ).toBe(markdown);
+ });
+
+ test("rewrites only references captured for the current Markdown file", () => {
+ const markdown =
+ "![Local](./hero.png) ![Parent](../hero.png) `./hero.png` and ./hero.png";
+
+ const result = rewriteDiscoveredReferences({
+ markdown,
+ assetIdsByPath: new Map([["blog/hero.png", "local-hero"]]),
+ assetUrls: {
+ "local-hero": "/assets/local-hero.png",
+ "parent-hero": "/assets/parent-hero.png",
+ },
+ });
+
+ expect(result).toContain("![Parent](../hero.png)");
+ expect(result).toContain("`./hero.png` and ./hero.png");
+ });
+});
diff --git a/packages/content-engine/src/markdown-assets.ts b/packages/content-engine/src/markdown-assets.ts
new file mode 100644
index 0000000000..afab664c4d
--- /dev/null
+++ b/packages/content-engine/src/markdown-assets.ts
@@ -0,0 +1,167 @@
+import { parse, postprocess, preprocess } from "micromark";
+import { decodeString } from "micromark-util-decode-string";
+import { createCanonicalAssetPath, encodeAssetPathSegment } from "./asset-path";
+import type { MarkdownAssetReference } from "./markdown-references";
+
+export const createUniqueAssetIdsByPath = (
+ assets: Iterable<{ id: string; path: string }>
+) => {
+ const ambiguousPaths = new Set<string>();
+ const assetIdsByPath = new Map<string, string>();
+ for (const { id, path } of assets) {
+ if (assetIdsByPath.has(path)) {
+ ambiguousPaths.add(path);
+ assetIdsByPath.delete(path);
+ continue;
+ }
+ if (ambiguousPaths.has(path) === false) {
+ assetIdsByPath.set(path, id);
+ }
+ }
+ return assetIdsByPath;
+};
+
+const getMarkdownUrlTokens = (markdown: string) => {
+ const events = postprocess(
+ parse()
+ .document()
+ .write(preprocess()(markdown, undefined, true))
+ );
+ const tokens: Array<{ start: number; end: number; url: string }> = [];
+ for (const [phase, token] of events) {
+ if (
+ phase !== "enter" ||
+ (token.type !== "resourceDestinationString" &&
+ token.type !== "definitionDestinationString")
+ ) {
+ continue;
+ }
+ const source = markdown.slice(token.start.offset, token.end.offset);
+ tokens.push({
+ start: token.start.offset,
+ end: token.end.offset,
+ url: decodeString(source),
+ });
+ }
+ return tokens;
+};
+
+const getRelativeAssetPath = ({
+ sourcePath,
+ url,
+}: {
+ sourcePath: string;
+ url: string;
+}) => {
+ if (
+ url.length === 0 ||
+ url.startsWith("#") ||
+ url.startsWith("?") ||
+ url.startsWith("/")
+ ) {
+ return;
+ }
+ const origin = "https://content.webstudio.invalid";
+ let tokenPrefix = "__webstudio_asset_source_";
+ while (sourcePath.includes(tokenPrefix) || url.includes(tokenPrefix)) {
+ tokenPrefix = `_${tokenPrefix}`;
+ }
+ const sourceSegments = sourcePath.split("/");
+ const sourceSegmentByToken = new Map(
+ sourceSegments.map((segment, index) => [
+ `${tokenPrefix}${index}__`,
+ segment,
+ ])
+ );
+ const sourceUrl = Array.from(sourceSegmentByToken.keys()).join("/");
+ let parsed: URL;
+ try {
+ parsed = new URL(url, new URL(sourceUrl, `${origin}/`));
+ } catch {
+ return;
+ }
+ if (parsed.origin !== origin) {
+ return;
+ }
+ const segments: string[] = [];
+ for (const encodedSegment of parsed.pathname.slice(1).split("/")) {
+ let segment: string;
+ try {
+ segment = decodeURIComponent(encodedSegment);
+ } catch {
+ return;
+ }
+ if (segment === "") {
+ continue;
+ }
+ const sourceSegment = sourceSegmentByToken.get(segment);
+ if (sourceSegment !== undefined) {
+ segments.push(sourceSegment);
+ continue;
+ }
+ if (segment.includes("/")) {
+ return;
+ }
+ segments.push(encodeAssetPathSegment(segment));
+ }
+ return segments.join("/");
+};
+
+const createAssetIdResolver = (
+ assetIdsByPath: ReadonlyMap<string, string>,
+ sourcePath: string
+) => {
+ const assetIds = new Set(assetIdsByPath.values());
+ return (url: string) => {
+ const path = getRelativeAssetPath({ sourcePath, url });
+ return (
+ (path === undefined ? undefined : assetIdsByPath.get(path)) ??
+ (assetIds.has(url) ? url : undefined)
+ );
+ };
+};
+
+export const discoverMarkdownAssetReferenceRanges = ({
+ markdown,
+ sourcePath,
+ assetIdsByPath,
+}: {
+ markdown: string;
+ sourcePath: string;
+ assetIdsByPath: ReadonlyMap<string, string>;
+}): MarkdownAssetReference[] => {
+ const resolveAssetId = createAssetIdResolver(assetIdsByPath, sourcePath);
+ return getMarkdownUrlTokens(markdown).flatMap(({ start, end, url }) => {
+ const assetId = resolveAssetId(url);
+ if (assetId === undefined) {
+ return [];
+ }
+ const parsed = new URL(url, "https://content.webstudio.invalid/");
+ const suffix = `${parsed.search}${parsed.hash}`;
+ return [{ start, end, assetId, ...(suffix === "" ? {} : { suffix }) }];
+ });
+};
+
+export const discoverNamedMarkdownAssetReferenceRanges = ({
+ markdown,
+ source,
+ assets,
+}: {
+ markdown: string;
+ source: { name: string; folderNames: readonly string[] };
+ assets: Iterable<{
+ id: string;
+ name: string;
+ folderNames: readonly string[];
+ }>;
+}) =>
+ discoverMarkdownAssetReferenceRanges({
+ markdown,
+ sourcePath: createCanonicalAssetPath(source),
+ assetIdsByPath: createUniqueAssetIdsByPath(
+ Array.from(assets, (asset) => ({
+ id: asset.id,
+ path: createCanonicalAssetPath(asset),
+ }))
+ ),
+ });
diff --git a/packages/content-engine/src/markdown-body.ts b/packages/content-engine/src/markdown-body.ts
new file mode 100644
index 0000000000..c8cdeb6ecd
--- /dev/null
+++ b/packages/content-engine/src/markdown-body.ts
@@ -0,0 +1,75 @@
+import { contentEngineLimits } from "./limits";
+import {
+ ByteLimitExceededError,
+ decodeUtf8,
+ getUtf8ByteLength,
+ readBoundedBytes,
+ stripUtf8ByteOrderMark,
+ type ByteSource,
+} from "./byte-stream";
+import { MarkdownMetadataError } from "./markdown-errors";
+import { findMarkdownFrontmatter } from "./markdown-scanner";
+
+export type MarkdownBody = {
+ body: string;
+ bodyBytes: number;
+ sourceBytes: number;
+};
+
+/** Reads and decodes one complete bounded Markdown file, excluding frontmatter. */
+export const extractMarkdownBody = async (
+ source: ByteSource,
+ maximumBytes = contentEngineLimits.hydratedFileBytes
+): Promise<MarkdownBody> => {
+ if (
+ Number.isInteger(maximumBytes) === false ||
+ maximumBytes <= 0 ||
+ maximumBytes > contentEngineLimits.hydratedFileBytes
+ ) {
+ throw new MarkdownMetadataError(
+ "MARKDOWN_BODY_BYTES_EXCEEDED",
+ "Markdown body byte limit is outside the supported range"
+ );
+ }
+ let bytes: Uint8Array;
+ try {
+ bytes = await readBoundedBytes(source, maximumBytes);
+ } catch (error) {
+ if (error instanceof ByteLimitExceededError) {
+ throw new MarkdownMetadataError(
+ "MARKDOWN_BODY_BYTES_EXCEEDED",
+ "Markdown content exceeds the byte limit"
+ );
+ }
+ throw error;
+ }
+ let sourceText: string;
+ try {
+ sourceText = decodeUtf8(bytes);
+ } catch {
+ throw new MarkdownMetadataError(
+ "MARKDOWN_BODY_DECODING_FAILED",
+ "Markdown content is not valid UTF-8"
+ );
+ }
+
+ const located = findMarkdownFrontmatter(bytes, true);
+ const bodyStart = located?.blockEnd ?? 0;
+ let body: string;
+ try {
+ body =
+ bodyStart === 0
+ ? stripUtf8ByteOrderMark(sourceText)
+ : decodeUtf8(bytes.subarray(bodyStart));
+ } catch {
+ throw new MarkdownMetadataError(
+ "MARKDOWN_BODY_DECODING_FAILED",
+ "Markdown content is not valid UTF-8"
+ );
+ }
+ return {
+ body,
+ bodyBytes: getUtf8ByteLength(body),
+ sourceBytes: bytes.byteLength,
+ };
+};
diff --git a/packages/content-engine/src/markdown-errors.ts b/packages/content-engine/src/markdown-errors.ts
new file mode 100644
index 0000000000..8d3bde407b
--- /dev/null
+++ b/packages/content-engine/src/markdown-errors.ts
@@ -0,0 +1,20 @@
+export type MarkdownMetadataErrorCode =
+ | "FRONTMATTER_BYTES_EXCEEDED"
+ | "FRONTMATTER_DECODING_FAILED"
+ | "FRONTMATTER_INVALID"
+ | "FRONTMATTER_DEPTH_EXCEEDED"
+ | "FRONTMATTER_FIELDS_EXCEEDED"
+ | "FRONTMATTER_STRING_BYTES_EXCEEDED"
+ | "MARKDOWN_BODY_BYTES_EXCEEDED"
+ | "MARKDOWN_BODY_DECODING_FAILED"
+ | "MARKDOWN_EXCERPT_BYTES_EXCEEDED";
+
+export class MarkdownMetadataError extends Error {
+ code: MarkdownMetadataErrorCode;
+
+ constructor(code: MarkdownMetadataErrorCode, message: string) {
+ super(message);
+ this.name = "MarkdownMetadataError";
+ this.code = code;
+ }
+}
diff --git a/packages/content-engine/src/markdown-references.test.ts b/packages/content-engine/src/markdown-references.test.ts
new file mode 100644
index 0000000000..f574b5cb92
--- /dev/null
+++ b/packages/content-engine/src/markdown-references.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, test } from "vitest";
+import { rewriteMarkdownAssetReferenceRanges } from "./markdown-references";
+
+describe("Markdown asset reference ranges", () => {
+ test("rewrites multiple destinations without shifting earlier ranges", () => {
+ const markdown = "![One](one.png) ![Two](two.png)";
+ const oneStart = markdown.indexOf("one.png");
+ const twoStart = markdown.indexOf("two.png");
+
+ expect(
+ rewriteMarkdownAssetReferenceRanges({
+ markdown,
+ references: [
+ { start: oneStart, end: oneStart + 7, assetId: "one" },
+ {
+ start: twoStart,
+ end: twoStart + 7,
+ assetId: "two",
+ suffix: "#crop",
+ },
+ ],
+ assetUrls: { one: "/assets/one.png", two: "/assets/two.png" },
+ })
+ ).toBe("![One](/assets/one.png) ![Two](/assets/two.png#crop)");
+ });
+
+ test("leaves a destination unchanged without a runtime URL", () => {
+ expect(
+ rewriteMarkdownAssetReferenceRanges({
+ markdown: "![Hero](hero.png)",
+ references: [{ start: 8, end: 16, assetId: "hero" }],
+ assetUrls: {},
+ })
+ ).toBe("![Hero](hero.png)");
+ });
+
+ test("merges reference parameters with an asset URL query", () => {
+ const markdown = "![Hero](hero.png?width=100#crop)";
+ const start = markdown.indexOf("hero.png");
+
+ expect(
+ rewriteMarkdownAssetReferenceRanges({
+ markdown,
+ references: [
+ {
+ start,
+ end: start + "hero.png?width=100#crop".length,
+ assetId: "hero",
+ suffix: "?width=100#crop",
+ },
+ ],
+ assetUrls: { hero: "/cgi/image/hero.png?format=raw" },
+ })
+ ).toBe("![Hero](/cgi/image/hero.png?format=raw&width=100#crop)");
+ });
+
+ test("rejects overlapping or out-of-bounds ranges", () => {
+ expect(() =>
+ rewriteMarkdownAssetReferenceRanges({
+ markdown: "012345",
+ references: [
+ { start: 1, end: 4, assetId: "one" },
+ { start: 3, end: 5, assetId: "two" },
+ ],
+ assetUrls: {},
+ })
+ ).toThrow("Markdown asset reference range is invalid");
+ });
+});
diff --git a/packages/content-engine/src/markdown-references.ts b/packages/content-engine/src/markdown-references.ts
new file mode 100644
index 0000000000..ff1adc9a9c
--- /dev/null
+++ b/packages/content-engine/src/markdown-references.ts
@@ -0,0 +1,78 @@
+export type MarkdownAssetReference = {
+ start: number;
+ end: number;
+ assetId: string;
+ suffix?: string;
+};
+
+export type MarkdownAssetReferences = Readonly<
+ Record<string, readonly MarkdownAssetReference[]>
+>;
+
+const appendMarkdownReferenceSuffix = (
+ assetUrl: string,
+ suffix: string | undefined
+) => {
+ if (suffix === undefined || suffix.length === 0) {
+ return assetUrl;
+ }
+ const base = new URL("https://content.webstudio.invalid/__assets__/");
+ const target = new URL(assetUrl, base);
+ const reference = new URL(suffix, base);
+ for (const [name, value] of reference.searchParams) {
+ target.searchParams.append(name, value);
+ }
+ if (reference.hash !== "") {
+ target.hash = reference.hash;
+ }
+ if (URL.canParse(assetUrl)) {
+ return target.href;
+ }
+ if (assetUrl.startsWith("//")) {
+ return `//${target.host}${target.pathname}${target.search}${target.hash}`;
+ }
+ if (assetUrl.startsWith("/")) {
+ return `${target.pathname}${target.search}${target.hash}`;
+ }
+ const basePath = base.pathname;
+ const pathname = target.pathname.startsWith(basePath)
+ ? target.pathname.slice(basePath.length)
+ : target.pathname;
+ return `${pathname}${target.search}${target.hash}`;
+};
+
+export const rewriteMarkdownAssetReferenceRanges = ({
+ markdown,
+ references,
+ assetUrls,
+}: {
+ markdown: string;
+ references: readonly MarkdownAssetReference[];
+ assetUrls: Readonly<Record<string, string>>;
+}) => {
+ let previousStart = markdown.length;
+ let result = markdown;
+ for (const reference of [...references].sort(
+ (left, right) => right.start - left.start
+ )) {
+ if (
+ reference.start < 0 ||
+ reference.end <= reference.start ||
+ reference.end > markdown.length ||
+ reference.end > previousStart
+ ) {
+ throw new Error("Markdown asset reference range is invalid");
+ }
+ previousStart = reference.start;
+ const assetUrl = assetUrls[reference.assetId];
+ if (assetUrl === undefined) {
+ continue;
+ }
+ const resolvedUrl = appendMarkdownReferenceSuffix(
+ assetUrl,
+ reference.suffix
+ );
+ result = `${result.slice(0, reference.start)}${resolvedUrl}${result.slice(reference.end)}`;
+ }
+ return result;
+};
diff --git a/packages/content-engine/src/markdown-scanner.ts b/packages/content-engine/src/markdown-scanner.ts
new file mode 100644
index 0000000000..d09be53fdc
--- /dev/null
+++ b/packages/content-engine/src/markdown-scanner.ts
@@ -0,0 +1,95 @@
+export const markdownByteOrderMark = new Uint8Array([0xef, 0xbb, 0xbf]);
+
+// Maximum envelope around the YAML payload: an optional UTF-8 BOM plus the
+// opening and closing delimiters with CRLF line endings.
+export const markdownFrontmatterEnvelopeBytes =
+ markdownByteOrderMark.byteLength + 10;
+
+const startsWith = (bytes: Uint8Array, expected: Uint8Array, offset = 0) => {
+ if (bytes.byteLength - offset < expected.byteLength) {
+ return false;
+ }
+ return expected.every((value, index) => bytes[offset + index] === value);
+};
+
+export type LocatedMarkdownFrontmatter = {
+ yamlStart: number;
+ yamlEnd: number;
+ blockEnd: number;
+};
+
+export const findMarkdownFrontmatter = (
+ bytes: Uint8Array,
+ endOfFile: boolean
+): LocatedMarkdownFrontmatter | null | undefined => {
+ let openingStart = 0;
+ if (startsWith(bytes, markdownByteOrderMark)) {
+ openingStart = markdownByteOrderMark.byteLength;
+ } else if (
+ bytes.byteLength < markdownByteOrderMark.byteLength &&
+ markdownByteOrderMark
+ .slice(0, bytes.byteLength)
+ .every((value, index) => value === bytes[index])
+ ) {
+ return endOfFile ? null : undefined;
+ }
+
+ if (bytes.byteLength < openingStart + 4) {
+ return endOfFile ? null : undefined;
+ }
+ if (
+ bytes[openingStart] !== 0x2d ||
+ bytes[openingStart + 1] !== 0x2d ||
+ bytes[openingStart + 2] !== 0x2d
+ ) {
+ return null;
+ }
+
+ let yamlStart = openingStart + 3;
+ if (bytes[yamlStart] === 0x0a) {
+ yamlStart += 1;
+ } else if (bytes[yamlStart] === 0x0d) {
+ if (bytes.byteLength === yamlStart + 1) {
+ return endOfFile ? null : undefined;
+ }
+ if (bytes[yamlStart + 1] !== 0x0a) {
+ return null;
+ }
+ yamlStart += 2;
+ } else {
+ return null;
+ }
+
+ let lineStart = yamlStart;
+ for (let index = yamlStart; index <= bytes.byteLength; index += 1) {
+ const atEnd = index === bytes.byteLength;
+ if (atEnd === false && bytes[index] !== 0x0a) {
+ continue;
+ }
+ if (atEnd && endOfFile === false) {
+ return;
+ }
+
+ let lineEnd = index;
+ if (lineEnd > lineStart && bytes[lineEnd - 1] === 0x0d) {
+ lineEnd -= 1;
+ }
+ const lineLength = lineEnd - lineStart;
+ const isDelimiter =
+ lineLength === 3 &&
+ ((bytes[lineStart] === 0x2d &&
+ bytes[lineStart + 1] === 0x2d &&
+ bytes[lineStart + 2] === 0x2d) ||
+ (bytes[lineStart] === 0x2e &&
+ bytes[lineStart + 1] === 0x2e &&
+ bytes[lineStart + 2] === 0x2e));
+ if (isDelimiter) {
+ return {
+ yamlStart,
+ yamlEnd: lineStart,
+ blockEnd: atEnd ? index : index + 1,
+ };
+ }
+ lineStart = index + 1;
+ }
+};
diff --git a/packages/content-engine/src/markdown.test.ts b/packages/content-engine/src/markdown.test.ts
new file mode 100644
index 0000000000..2d2729df59
--- /dev/null
+++ b/packages/content-engine/src/markdown.test.ts
@@ -0,0 +1,245 @@
+import { describe, expect, test, vi } from "vitest";
+import {
+ extractMarkdownBody,
+ extractMarkdownBodyAndExcerpt,
+ extractMarkdownExcerpt,
+ extractMarkdownFrontmatter,
+ MarkdownMetadataError,
+} from "./markdown";
+
+describe("extractMarkdownFrontmatter", () => {
+ test("parses schema-less nested YAML without retaining the body", async () => {
+ const result = await extractMarkdownFrontmatter(`---
+title: Hello
+publishedAt: 2026-07-18
+draft: false
+author:
+ name: Oleg
+tags: [web, studio]
+---
+# A body that is not metadata
+`);
+
+ expect(result.properties).toEqual({
+ title: "Hello",
+ publishedAt: "2026-07-18",
+ draft: false,
+ author: { name: "Oleg" },
+ tags: ["web", "studio"],
+ });
+ expect(result.frontmatterBytes).toBeGreaterThan(0);
+ expect(result.consumedBytes).toBeLessThan(
+ new TextEncoder().encode(`---
+title: Hello
+publishedAt: 2026-07-18
+draft: false
+author:
+ name: Oleg
+tags: [web, studio]
+---
+# A body that is not metadata
+`).byteLength
+ );
+ });
+
+ test("stops consuming a stream after the closing delimiter", async () => {
+ const returned = vi.fn();
+ const source = {
+ async *[Symbol.asyncIterator]() {
+ try {
+ yield new TextEncoder().encode("---\ntitle: Hello\n---\n");
+ yield new TextEncoder().encode("body must not be read");
+ } finally {
+ returned();
+ }
+ },
+ };
+
+ await expect(extractMarkdownFrontmatter(source)).resolves.toMatchObject({
+ properties: { title: "Hello" },
+ });
+ expect(returned).toHaveBeenCalledOnce();
+ });
+
+ test("returns empty properties after reading only the opening line", async () => {
+ const result = await extractMarkdownFrontmatter("# No frontmatter\nbody");
+ expect(result.properties).toEqual({});
+ expect(result.consumedBytes).toBeLessThan(20);
+ });
+
+ test("parses an explicit empty frontmatter block", async () => {
+ await expect(
+ extractMarkdownFrontmatter("---\n---\nBody")
+ ).resolves.toMatchObject({ properties: {} });
+ });
+
+ test("supports a UTF-8 byte order mark and CRLF delimiters", async () => {
+ await expect(
+ extractMarkdownFrontmatter("\ufeff---\r\ntitle: Hello\r\n---\r\nBody")
+ ).resolves.toMatchObject({ properties: { title: "Hello" } });
+ });
+
+ test("rejects invalid YAML with a stable error code", async () => {
+ await expect(
+ extractMarkdownFrontmatter("---\ntitle: [broken\n---\n")
+ ).rejects.toMatchObject({
+ code: "FRONTMATTER_INVALID",
+ } satisfies Partial<MarkdownMetadataError>);
+ });
+
+ test("rejects an unclosed block at the byte boundary", async () => {
+ await expect(
+ extractMarkdownFrontmatter("---\ntitle: too large", { bytes: 8 })
+ ).rejects.toMatchObject({
+ code: "FRONTMATTER_BYTES_EXCEEDED",
+ } satisfies Partial<MarkdownMetadataError>);
+ });
+
+ test("rejects a closed block whose properties exceed the byte limit", async () => {
+ await expect(
+ extractMarkdownFrontmatter(
+ `---\ntitle: ${"large".repeat(20)}\n---\nBody`,
+ { bytes: 32 }
+ )
+ ).rejects.toMatchObject({
+ code: "FRONTMATTER_BYTES_EXCEEDED",
+ } satisfies Partial<MarkdownMetadataError>);
+ });
+
+ test("enforces nesting, field, and string limits", async () => {
+ await expect(
+ extractMarkdownFrontmatter("---\na:\n b:\n c: value\n---\n", {
+ depth: 2,
+ })
+ ).rejects.toMatchObject({ code: "FRONTMATTER_DEPTH_EXCEEDED" });
+ await expect(
+ extractMarkdownFrontmatter("---\na: 1\nb: 2\n---\n", { fields: 1 })
+ ).rejects.toMatchObject({ code: "FRONTMATTER_FIELDS_EXCEEDED" });
+ await expect(
+ extractMarkdownFrontmatter("---\ntitle: long\n---\n", { stringBytes: 3 })
+ ).rejects.toMatchObject({ code: "FRONTMATTER_STRING_BYTES_EXCEEDED" });
+ await expect(
+ extractMarkdownFrontmatter("---\ntitle: long\n---\n", {
+ serializedBytes: 8,
+ })
+ ).rejects.toMatchObject({ code: "FRONTMATTER_BYTES_EXCEEDED" });
+ });
+
+ test("rejects aliases and duplicate keys", async () => {
+ await expect(
+ extractMarkdownFrontmatter("---\nbase: &base value\ncopy: *base\n---\n")
+ ).rejects.toMatchObject({ code: "FRONTMATTER_INVALID" });
+ await expect(
+ extractMarkdownFrontmatter("---\ntitle: first\ntitle: second\n---\n")
+ ).rejects.toMatchObject({ code: "FRONTMATTER_INVALID" });
+ });
+
+ test("rejects tagged YAML values that are not JSON", async () => {
+ for (const value of [
+ "!!timestamp 2020-01-01",
+ "!!set\n item: null",
+ "!!omap\n - item: value",
+ ]) {
+ await expect(
+ extractMarkdownFrontmatter(`---\nvalue: ${value}\n---\n`)
+ ).rejects.toMatchObject({ code: "FRONTMATTER_INVALID" });
+ }
+ });
+
+ test("preserves arbitrary object keys without prototype pollution", async () => {
+ const { properties } = await extractMarkdownFrontmatter(`---
+__proto__:
+ polluted: true
+constructor: user value
+prototype: another value
+---
+`);
+
+ expect(Object.hasOwn(properties, "__proto__")).toBe(true);
+ expect(properties["__proto__"]).toEqual({ polluted: true });
+ expect(properties.constructor).toBe("user value");
+ expect(properties.prototype).toBe("another value");
+ expect(({} as { polluted?: boolean }).polluted).toBeUndefined();
+ });
+
+ test("rejects integers that cannot be represented without rounding", async () => {
+ await expect(
+ extractMarkdownFrontmatter("---\nvalue: 9007199254740993\n---\n")
+ ).rejects.toMatchObject({ code: "FRONTMATTER_INVALID" });
+ });
+});
+
+describe("Markdown body and excerpt extraction", () => {
+ test("removes frontmatter while preserving complete Markdown body", async () => {
+ const source = "---\ntitle: Hello\n---\n# Heading\n\nBody **text**.";
+ const body = "# Heading\n\nBody **text**.";
+
+ await expect(extractMarkdownBody(source)).resolves.toEqual({
+ body,
+ bodyBytes: new TextEncoder().encode(body).byteLength,
+ sourceBytes: new TextEncoder().encode(source).byteLength,
+ });
+ });
+
+ test("does not treat a later thematic break as frontmatter", async () => {
+ await expect(
+ extractMarkdownBody("Introduction\n\n---\n\nMore")
+ ).resolves.toMatchObject({ body: "Introduction\n\n---\n\nMore" });
+ });
+
+ test("removes a UTF-8 byte order mark without frontmatter", async () => {
+ await expect(extractMarkdownBody("\ufeff# Heading")).resolves.toMatchObject(
+ {
+ body: "# Heading",
+ }
+ );
+ });
+
+ test("enforces the complete-file byte limit before decoding", async () => {
+ await expect(extractMarkdownBody("123456", 5)).rejects.toMatchObject({
+ code: "MARKDOWN_BODY_BYTES_EXCEEDED",
+ });
+ });
+
+ test("rejects invalid UTF-8", async () => {
+ await expect(
+ extractMarkdownBody(new Uint8Array([0xc3, 0x28]))
+ ).rejects.toMatchObject({ code: "MARKDOWN_BODY_DECODING_FAILED" });
+ });
+
+ test("creates plain-text excerpts without markup or raw HTML", () => {
+ expect(
+ extractMarkdownExcerpt(
+ "# Hello *world*\n\n<div>hidden</div>\n\nUse `code` and [links](https://example.com)."
+ )
+ ).toBe("Hello world Use code and links.");
+ });
+
+ test("truncates excerpts at a valid UTF-8 character boundary", () => {
+ expect(extractMarkdownExcerpt("Hello 🌍 world", 10)).toBe("Hello 🌍");
+ expect(
+ new TextEncoder().encode(extractMarkdownExcerpt("🌍🌍", 5))
+ ).toHaveLength(4);
+ });
+
+ test("extracts a bounded body and excerpt in one operation", async () => {
+ await expect(
+ extractMarkdownBodyAndExcerpt(
+ "---\ntitle: Hello\n---\n# Heading\n\nLong body text",
+ { excerptBytes: 12 }
+ )
+ ).resolves.toMatchObject({
+ body: "# Heading\n\nLong body text",
+ excerpt: "Heading Long",
+ });
+ });
+
+ test("does not allow callers to raise shared limits", async () => {
+ await expect(
+ extractMarkdownBody("Body", 1024 * 1024 + 1)
+ ).rejects.toMatchObject({ code: "MARKDOWN_BODY_BYTES_EXCEEDED" });
+ expect(() => extractMarkdownExcerpt("Body", 2049)).toThrowError(
+ expect.objectContaining({ code: "MARKDOWN_EXCERPT_BYTES_EXCEEDED" })
+ );
+ });
+});
diff --git a/packages/content-engine/src/markdown.ts b/packages/content-engine/src/markdown.ts
new file mode 100644
index 0000000000..1356d49e5a
--- /dev/null
+++ b/packages/content-engine/src/markdown.ts
@@ -0,0 +1,95 @@
+import { contentEngineLimits } from "./limits";
+import remarkParse from "remark-parse";
+import { unified } from "unified";
+import { getUtf8ByteLength, type ByteSource } from "./byte-stream";
+import { MarkdownMetadataError } from "./markdown-errors";
+import { extractMarkdownBody } from "./markdown-body";
+
+export {
+ MarkdownMetadataError,
+ type MarkdownMetadataErrorCode,
+} from "./markdown-errors";
+export { extractMarkdownBody, type MarkdownBody } from "./markdown-body";
+export {
+ extractMarkdownFrontmatter,
+ type MarkdownFrontmatter,
+} from "./frontmatter";
+
+type MarkdownNode = {
+ type: string;
+ value?: unknown;
+ children?: MarkdownNode[];
+};
+
+const textNodeTypes = new Set(["text", "inlineCode", "code"]);
+const separatingNodeTypes = new Set([
+ "paragraph",
+ "heading",
+ "listItem",
+ "blockquote",
+ "code",
+]);
+
+const markdownToPlainText = (body: string) => {
+ const tree = unified().use(remarkParse).parse(body) as MarkdownNode;
+ const parts: string[] = [];
+ const visit = (node: MarkdownNode) => {
+ if (textNodeTypes.has(node.type) && typeof node.value === "string") {
+ parts.push(node.value);
+ }
+ if (node.type === "html" || node.type === "yaml") {
+ return;
+ }
+ for (const child of node.children ?? []) {
+ visit(child);
+ }
+ if (separatingNodeTypes.has(node.type)) {
+ parts.push(" ");
+ }
+ };
+ visit(tree);
+ return parts.join("").replace(/\s+/g, " ").trim();
+};
+
+const truncateUtf8 = (value: string, maximumBytes: number) => {
+ let bytes = 0;
+ let result = "";
+ for (const character of value) {
+ const characterBytes = getUtf8ByteLength(character);
+ if (bytes + characterBytes > maximumBytes) {
+ break;
+ }
+ result += character;
+ bytes += characterBytes;
+ }
+ return result.trimEnd();
+};
+
+/** Produces bounded plain text from a previously bounded Markdown body. */
+export const extractMarkdownExcerpt = (
+ body: string,
+ maximumBytes = contentEngineLimits.excerptBytes
+) => {
+ if (
+ Number.isInteger(maximumBytes) === false ||
+ maximumBytes <= 0 ||
+ maximumBytes > contentEngineLimits.excerptBytes
+ ) {
+ throw new MarkdownMetadataError(
+ "MARKDOWN_EXCERPT_BYTES_EXCEEDED",
+ "Markdown excerpt byte limit is outside the supported range"
+ );
+ }
+ return truncateUtf8(markdownToPlainText(body), maximumBytes);
+};
+
+export const extractMarkdownBodyAndExcerpt = async (
+ source: ByteSource,
+ options: { bodyBytes?: number; excerptBytes?: number } = {}
+) => {
+ const result = await extractMarkdownBody(source, options.bodyBytes);
+ return {
+ ...result,
+ excerpt: extractMarkdownExcerpt(result.body, options.excerptBytes),
+ };
+};
diff --git a/packages/content-engine/src/projection.ts b/packages/content-engine/src/projection.ts
new file mode 100644
index 0000000000..b3418466d1
--- /dev/null
+++ b/packages/content-engine/src/projection.ts
@@ -0,0 +1,95 @@
+import {
+ assetQueryDocumentFields,
+ type AssetFileDocument,
+ type AssetQueryFieldPath,
+ type ContentDatabaseDocument,
+} from "./schema";
+
+export const selectAssetDocumentFields = ({
+ document,
+ includes,
+}: {
+ document: AssetFileDocument | ContentDatabaseDocument;
+ includes: (field: (typeof assetQueryDocumentFields)[number]) => boolean;
+}) => {
+ const selected: Record<string, unknown> = {};
+ for (const field of assetQueryDocumentFields) {
+ const value = document[field];
+ if (value !== undefined && includes(field)) {
+ selected[field] = value;
+ }
+ }
+ return selected;
+};
+
+const selectPropertyPath = ({
+ source,
+ target,
+ path,
+}: {
+ source: Readonly<AssetFileDocument["properties"]>;
+ target: AssetFileDocument["properties"];
+ path: readonly string[];
+}) => {
+ const [key, ...rest] = path;
+ if (key === undefined || Object.hasOwn(source, key) === false) {
+ return;
+ }
+ const value = source[key];
+ if (rest.length === 0) {
+ Object.defineProperty(target, key, {
+ value,
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ });
+ return;
+ }
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
+ return;
+ }
+ const selected: AssetFileDocument["properties"] = {};
+ selectPropertyPath({
+ source: value as Readonly<AssetFileDocument["properties"]>,
+ target: selected,
+ path: rest,
+ });
+ if (Object.keys(selected).length === 0) {
+ return;
+ }
+ const existing = target[key];
+ Object.defineProperty(target, key, {
+ value: {
+ ...(typeof existing === "object" &&
+ existing !== null &&
+ Array.isArray(existing) === false
+ ? existing
+ : {}),
+ ...selected,
+ },
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ });
+};
+
+export const selectAssetProperties = ({
+ properties,
+ fields,
+}: {
+ properties: AssetFileDocument["properties"];
+ fields: readonly AssetQueryFieldPath[];
+}) => {
+ const selected: AssetFileDocument["properties"] = {};
+ for (const field of fields) {
+ if (field[0] !== "properties") {
+ continue;
+ }
+ selectPropertyPath({
+ source: properties,
+ target: selected,
+ path: field.slice(1),
+ });
+ }
+ return selected;
+};
diff --git a/packages/content-engine/src/published-runtime.test.ts b/packages/content-engine/src/published-runtime.test.ts
new file mode 100644
index 0000000000..d1ec87308d
--- /dev/null
+++ b/packages/content-engine/src/published-runtime.test.ts
@@ -0,0 +1,301 @@
+import { afterEach, describe, expect, test, vi } from "vitest";
+import type { AssetFileDocument } from "./schema";
+import { createAssetIndex } from "./asset-index";
+import { createCanonicalAssetFileEntry } from "./canonical";
+import {
+ createGeneratedAssetResourceRuntime,
+ createPublishedAssetResourceFetch,
+} from "./published-runtime";
+
+const revision = `sha256:${"a".repeat(64)}`;
+const document: AssetFileDocument = {
+ _id: "post-1",
+ _type: "asset.file",
+ name: "post.md",
+ path: "blog/post.md",
+ key: "post",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 4,
+ revision,
+ contentRef: "post.md",
+ properties: { slug: "post", title: "Post" },
+};
+const runtimeAssets = { "post-1": { url: "/assets/post.md" } };
+
+const createRuntime = async () => {
+ const index = await createAssetIndex({
+ projectId: "project-1",
+ entries: [
+ {
+ ...createCanonicalAssetFileEntry({
+ projectId: "project-1",
+ document,
+ }),
+ content: "Post",
+ },
+ ],
+ });
+ return {
+ index,
+ runtimeFetch: createPublishedAssetResourceFetch({
+ baseUrl: "https://site.example",
+ deploymentId: "build-1",
+ artifact: index,
+ runtimeAssets,
+ }),
+ };
+};
+
+const queryRequest = (content = false) =>
+ new Request("https://site.example/$resources/assets", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "post",
+ },
+ ],
+ },
+ limit: 1,
+ output: { mode: "all", includeMetadata: true },
+ content: content ? { mode: "full" } : { mode: "none" },
+ },
+ }),
+ });
+
+describe("published asset resource runtime", () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ test("does not open the query-result cache for ordinary generated fetches", async () => {
+ const { index } = await createRuntime();
+ const open = vi.fn();
+ vi.stubGlobal("caches", { open });
+ const fallback = vi.fn(async () => new Response("fallback"));
+ const createGeneratedFetch = createGeneratedAssetResourceRuntime({
+ deploymentId: "build-1",
+ artifact: index,
+ runtimeAssets,
+ });
+ const generatedFetch = await createGeneratedFetch({
+ request: new Request("https://site.example/page"),
+ fallback,
+ });
+
+ expect(await (await generatedFetch("/other")).text()).toBe("fallback");
+ expect(fallback).toHaveBeenCalledOnce();
+ expect(open).not.toHaveBeenCalled();
+ });
+
+ test("loads overview and detail queries from an embedded database", async () => {
+ const index = await createAssetIndex({
+ projectId: "project-1",
+ entries: [
+ {
+ ...createCanonicalAssetFileEntry({
+ projectId: "project-1",
+ document,
+ }),
+ content: "Post",
+ },
+ ],
+ });
+ const networkFetch = vi.fn();
+ vi.stubGlobal("fetch", networkFetch);
+ const createGeneratedFetch = createGeneratedAssetResourceRuntime({
+ deploymentId: "build-same-origin",
+ artifact: index,
+ runtimeAssets,
+ });
+ const generatedFetch = await createGeneratedFetch({
+ request: new Request("https://site.example/blog"),
+ fallback: vi.fn(async () => new Response("fallback")),
+ });
+
+ const overview = await generatedFetch(queryRequest());
+ const detail = await generatedFetch(queryRequest(true));
+
+ expect(overview.status).toBe(200);
+ const overviewData = await overview.json();
+ expect(overviewData).toMatchObject({
+ items: [{ id: "post-1" }],
+ });
+ expect(overviewData).not.toHaveProperty("database");
+ expect(overviewData).not.toHaveProperty("__diagnostics__");
+ await expect(detail.json()).resolves.toMatchObject({
+ items: [{ id: "post-1", content: { text: "Post" } }],
+ });
+ expect(networkFetch).not.toHaveBeenCalled();
+ });
+
+ test("reuses one initialized runtime across deployment origins", async () => {
+ const { index } = await createRuntime();
+ const createGeneratedFetch = createGeneratedAssetResourceRuntime({
+ deploymentId: "build-reused",
+ artifact: index,
+ runtimeAssets,
+ });
+ const fallback = vi.fn(async () => new Response("fallback"));
+
+ const first = await createGeneratedFetch({
+ request: new Request("https://site.example/first"),
+ fallback,
+ });
+ const second = await createGeneratedFetch({
+ request: new Request("https://another.example/second"),
+ fallback,
+ });
+ await first("/other");
+ await second("/other");
+
+ expect(fallback).toHaveBeenCalledTimes(2);
+ });
+
+ test("runs multiple structured requests against one database", async () => {
+ const { runtimeFetch } = await createRuntime();
+ const first = await runtimeFetch(queryRequest());
+ const second = await runtimeFetch(queryRequest());
+
+ expect(await first?.json()).toMatchObject({
+ items: [{ id: "post-1", properties: { title: "Post" } }],
+ totalCount: 1,
+ hasMore: false,
+ });
+ expect((await second?.json())?.items).toHaveLength(1);
+ });
+
+ test("requires only target URLs referenced by embedded Markdown", async () => {
+ const { index } = await createRuntime();
+ const runtimeFetch = createPublishedAssetResourceFetch({
+ baseUrl: "https://site.example",
+ deploymentId: "build-without-runtime-fields",
+ artifact: index,
+ runtimeAssets: {},
+ });
+ const response = await runtimeFetch("/$resources/assets", {
+ method: "POST",
+ body: JSON.stringify({
+ query: {
+ where: { all: [] },
+ limit: 1,
+ output: {
+ mode: "fields",
+ fields: [["id"]],
+ includeMetadata: false,
+ },
+ content: { mode: "none" },
+ },
+ }),
+ });
+ await expect(response?.json()).resolves.toMatchObject({
+ items: [{ id: "post-1" }],
+ });
+ expect(() =>
+ createPublishedAssetResourceFetch({
+ baseUrl: "https://site.example",
+ deploymentId: "build-incomplete-reference",
+ artifact: {
+ ...index,
+ assetReferences: {
+ "post.md": [{ start: 0, end: 1, assetId: "missing-reference" }],
+ },
+ },
+ runtimeAssets,
+ })
+ ).toThrow(
+ "Published referenced asset URL is unavailable for missing-reference"
+ );
+ });
+
+ test("hydrates selected embedded content", async () => {
+ const { runtimeFetch } = await createRuntime();
+ const response = await runtimeFetch(queryRequest(true));
+
+ expect(await response?.json()).toMatchObject({
+ items: [{ content: { text: "Post", encoding: "utf-8" } }],
+ });
+ });
+
+ test("returns structured hydration details", async () => {
+ const { runtimeFetch } = await createRuntime();
+ const response = await runtimeFetch("/$resources/assets", {
+ method: "POST",
+ body: JSON.stringify({
+ query: {
+ where: { all: [{ field: ["id"], operator: "eq", value: "post-1" }] },
+ limit: 1,
+ content: { mode: "full", maxBytes: 1 },
+ },
+ }),
+ });
+
+ expect(response?.status).toBe(400);
+ await expect(response?.json()).resolves.toMatchObject({
+ error: {
+ code: "CONTENT_LIMIT_EXCEEDED",
+ details: { assetId: "post-1", assetBytes: 4, fileByteLimit: 1 },
+ },
+ });
+ });
+
+ test("ignores other origins, methods, and paths", async () => {
+ const { runtimeFetch } = await createRuntime();
+ expect(await runtimeFetch("https://other.example/$resources/assets")).toBe(
+ undefined
+ );
+ expect(await runtimeFetch("/$resources/assets", { method: "GET" })).toBe(
+ undefined
+ );
+ expect(await runtimeFetch("/other", { method: "POST" })).toBe(undefined);
+ });
+
+ test("rejects malformed and stale requests", async () => {
+ const { runtimeFetch, index } = await createRuntime();
+ const malformed = await runtimeFetch("/$resources/assets", {
+ method: "POST",
+ body: "not json",
+ });
+ expect(malformed?.status).toBe(400);
+
+ const stale = await runtimeFetch("/$resources/assets", {
+ method: "POST",
+ body: JSON.stringify({
+ indexRevision: `${index.integrity.checksum}-old`,
+ query: {},
+ }),
+ });
+ expect(stale?.status).toBe(409);
+ });
+
+ test("caches only requests that opt into response caching", async () => {
+ const { index } = await createRuntime();
+ const responses = new Map<string, Response>();
+ const cache = {
+ match: vi.fn(async (request: Request) => responses.get(request.url)),
+ put: vi.fn(async (request: Request, response: Response) => {
+ responses.set(request.url, response);
+ }),
+ };
+ const runtimeFetch = createPublishedAssetResourceFetch({
+ baseUrl: "https://site.example",
+ deploymentId: "build-cache",
+ artifact: index,
+ runtimeAssets,
+ cache,
+ });
+ const request = () => {
+ const value = queryRequest();
+ value.headers.set("cache-control", "public, max-age=60");
+ return value;
+ };
+ expect((await runtimeFetch(request()))?.status).toBe(200);
+ expect((await runtimeFetch(request()))?.status).toBe(200);
+ expect(cache.put).toHaveBeenCalledOnce();
+ expect(cache.match).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/content-engine/src/published-runtime.ts b/packages/content-engine/src/published-runtime.ts
new file mode 100644
index 0000000000..6e0fc689ec
--- /dev/null
+++ b/packages/content-engine/src/published-runtime.ts
@@ -0,0 +1,251 @@
+import {
+ createAssetResourceQueryFailure,
+ type ContentArtifactV1,
+ type AssetResourceQueryFailure,
+} from "./schema";
+import { sha256Hex } from "./canonical-json";
+import { getContentArtifactReferencedAssetIds } from "./content-artifact";
+import { createContentDatabase } from "./content-database";
+import { readAssetQueryRequest } from "./request";
+import type { AssetRuntimeData } from "./structured-query";
+import { getAssetResourceQueryError } from "./query-error";
+
+const assetsResourceUrl = "/$resources/assets";
+
+const jsonResponse = (value: unknown, status = 200) =>
+ new Response(JSON.stringify(value), {
+ status,
+ headers: { "content-type": "application/json; charset=utf-8" },
+ });
+
+const failure = ({
+ code,
+ message,
+ status,
+ retryable = false,
+ details,
+}: {
+ code: AssetResourceQueryFailure["error"]["code"];
+ message: string;
+ status: number;
+ retryable?: boolean;
+ details?: Record<string, string | number>;
+}) =>
+ jsonResponse(
+ createAssetResourceQueryFailure({ code, message, retryable, details }),
+ status
+ );
+
+const getRequest = (
+ input: RequestInfo | URL,
+ baseUrl: string | URL,
+ init?: RequestInit
+) =>
+ typeof input === "string" || input instanceof URL
+ ? new Request(new URL(input, baseUrl), init)
+ : new Request(input, init);
+
+const getCacheKey = async ({
+ deploymentId,
+ artifact,
+ request,
+}: {
+ deploymentId: string;
+ artifact: ContentArtifactV1;
+ request: Request;
+}) => {
+ const body = await request.clone().text();
+ const cacheControl = request.headers.get("cache-control");
+ const hash = await sha256Hex(
+ JSON.stringify([
+ deploymentId,
+ artifact.integrity.checksum,
+ body,
+ cacheControl,
+ ])
+ );
+ const url = new URL(request.url);
+ url.searchParams.set("ws-asset-resource", hash);
+ return new Request(url, { method: "GET" });
+};
+
+export const createPublishedAssetResourceFetch = ({
+ deploymentId,
+ artifact,
+ runtimeAssets,
+ cache,
+ baseUrl,
+}: {
+ deploymentId: string;
+ artifact: ContentArtifactV1;
+ runtimeAssets: Readonly<Record<string, AssetRuntimeData>>;
+ cache?: Pick<Cache, "match" | "put">;
+ baseUrl: string | URL;
+}) => {
+ validateRuntimeAssets({ artifact, runtimeAssets });
+ return createPublishedAssetResourceHandler({
+ deploymentId,
+ artifact,
+ runtimeAssets,
+ cache,
+ baseUrl,
+ database: createContentDatabase({ artifact }),
+ });
+};
+
+const validateRuntimeAssets = ({
+ artifact,
+ runtimeAssets,
+}: {
+ artifact: ContentArtifactV1;
+ runtimeAssets: Readonly<Record<string, AssetRuntimeData>>;
+}) => {
+ const missingReferencedAssetId = getContentArtifactReferencedAssetIds(
+ artifact
+ ).find((assetId) => runtimeAssets[assetId] === undefined);
+ if (missingReferencedAssetId !== undefined) {
+ throw new Error(
+ `Published referenced asset URL is unavailable for ${missingReferencedAssetId}`
+ );
+ }
+};
+
+const createPublishedAssetResourceHandler = ({
+ deploymentId,
+ artifact,
+ runtimeAssets,
+ cache,
+ baseUrl,
+ database,
+}: {
+ deploymentId: string;
+ artifact: ContentArtifactV1;
+ runtimeAssets: Readonly<Record<string, AssetRuntimeData>>;
+ cache?: Pick<Cache, "match" | "put">;
+ baseUrl: string | URL;
+ database: ReturnType<typeof createContentDatabase>;
+}) => {
+ const baseOrigin = new URL(baseUrl).origin;
+ return async (
+ input: RequestInfo | URL,
+ init?: RequestInit
+ ): Promise<Response | undefined> => {
+ const request = getRequest(input, baseUrl, init);
+ const url = new URL(request.url);
+ if (
+ url.origin !== baseOrigin ||
+ url.pathname !== assetsResourceUrl ||
+ request.method.toUpperCase() !== "POST"
+ ) {
+ return;
+ }
+ let parsedRequest;
+ try {
+ parsedRequest = await readAssetQueryRequest(request.clone());
+ } catch {
+ return failure({
+ code: "INVALID_REQUEST",
+ message: "Asset resource request is invalid",
+ status: 400,
+ });
+ }
+ const cacheKey =
+ cache === undefined || request.headers.has("cache-control") === false
+ ? undefined
+ : await getCacheKey({ deploymentId, artifact, request });
+ if (cacheKey !== undefined && cache !== undefined) {
+ const cached = await cache.match(cacheKey).catch(() => undefined);
+ if (cached !== undefined) {
+ return new Response(cached.body, cached);
+ }
+ }
+ try {
+ if (request.signal.aborted) {
+ return failure({
+ code: "REQUEST_CANCELLED",
+ message: "Published asset query was cancelled",
+ status: 499,
+ });
+ }
+ const response = jsonResponse(
+ await database.query(parsedRequest, undefined, runtimeAssets)
+ );
+ if (
+ cacheKey !== undefined &&
+ cache !== undefined &&
+ request.signal.aborted === false
+ ) {
+ response.headers.set(
+ "cache-control",
+ request.headers.get("cache-control") as string
+ );
+ await cache.put(cacheKey, response.clone()).catch(() => undefined);
+ }
+ return response;
+ } catch (error) {
+ if (request.signal.aborted) {
+ return failure({
+ code: "REQUEST_CANCELLED",
+ message: "Published asset query was cancelled",
+ status: 499,
+ });
+ }
+ const queryError = getAssetResourceQueryError(error);
+ if (queryError !== undefined) {
+ return failure(queryError);
+ }
+ return failure({
+ code: "INTERNAL_ERROR",
+ message: "Published asset query failed",
+ status: 500,
+ retryable: true,
+ });
+ }
+ };
+};
+
+export const createGeneratedAssetResourceRuntime = ({
+ deploymentId,
+ artifact,
+ runtimeAssets,
+}: {
+ deploymentId: string;
+ artifact: ContentArtifactV1;
+ runtimeAssets: Readonly<Record<string, AssetRuntimeData>>;
+}) => {
+ const cacheStorage = globalThis.caches;
+ let cachePromise: Promise<Cache> | undefined;
+ const getCache = () => {
+ cachePromise ??= cacheStorage.open(`webstudio-assets-${deploymentId}`);
+ return cachePromise;
+ };
+ const cache =
+ cacheStorage === undefined
+ ? undefined
+ : {
+ match: async (key: Request) => (await getCache()).match(key),
+ put: async (key: Request, response: Response) =>
+ (await getCache()).put(key, response),
+ };
+ validateRuntimeAssets({ artifact, runtimeAssets });
+ const database = createContentDatabase({ artifact });
+ return async ({
+ request,
+ fallback,
+ }: {
+ request: Request;
+ fallback: typeof fetch;
+ }): Promise<typeof fetch> => {
+ const origin = new URL(request.url).origin;
+ const fetchResource = createPublishedAssetResourceHandler({
+ deploymentId,
+ artifact,
+ runtimeAssets,
+ cache,
+ baseUrl: origin,
+ database,
+ });
+ return async (input, init) =>
+ (await fetchResource(input, init)) ?? fallback(input, init);
+ };
+};
diff --git a/packages/content-engine/src/query-error.ts b/packages/content-engine/src/query-error.ts
new file mode 100644
index 0000000000..d1ea9e510d
--- /dev/null
+++ b/packages/content-engine/src/query-error.ts
@@ -0,0 +1,45 @@
+import type { AssetResourceQueryFailure } from "./schema";
+import { AssetResourceHydrationError } from "./hydration";
+import {
+ AssetIndexRevisionError,
+ AssetQueryExecutionError,
+} from "./structured-query";
+
+export type AssetResourceQueryError = Omit<
+ AssetResourceQueryFailure["error"],
+ "details"
+> & {
+ details?: Record<string, string | number>;
+ status: 400 | 409;
+};
+
+/** Classifies content-query failures independently of an HTTP or RPC transport. */
+export const getAssetResourceQueryError = (
+ error: unknown
+): AssetResourceQueryError | undefined => {
+ if (error instanceof AssetIndexRevisionError) {
+ return {
+ code: "STALE_INDEX",
+ message: error.message,
+ retryable: false,
+ status: 409,
+ };
+ }
+ if (error instanceof AssetQueryExecutionError) {
+ return {
+ code: "INVALID_REQUEST",
+ message: error.message,
+ retryable: false,
+ status: 400,
+ };
+ }
+ if (error instanceof AssetResourceHydrationError) {
+ return {
+ code: error.code,
+ message: error.message,
+ retryable: false,
+ details: error.details,
+ status: 400,
+ };
+ }
+};
diff --git a/packages/content-engine/src/query-source.test.ts b/packages/content-engine/src/query-source.test.ts
new file mode 100644
index 0000000000..9540bdf69a
--- /dev/null
+++ b/packages/content-engine/src/query-source.test.ts
@@ -0,0 +1,11 @@
+import { expect, test } from "vitest";
+import { assetQuerySourceDefinition } from "./query-source";
+
+test("uses lowercase labels for asset filter fields and operators", () => {
+ for (const item of [
+ ...assetQuerySourceDefinition.fields,
+ ...assetQuerySourceDefinition.operators,
+ ]) {
+ expect(item.label).toBe(item.label.toLowerCase());
+ }
+});
diff --git a/packages/content-engine/src/query-source.ts b/packages/content-engine/src/query-source.ts
new file mode 100644
index 0000000000..8696b7ea3f
--- /dev/null
+++ b/packages/content-engine/src/query-source.ts
@@ -0,0 +1,157 @@
+import { type QuerySourceDefinition } from "@webstudio-is/query-builder";
+import { z } from "zod";
+import { contentEngineLimits } from "./limits";
+import {
+ assetObservedFieldType,
+ assetQueryFieldPath,
+ assetQueryOperators,
+ assetQueryStandardFields,
+ assetQueryStandardFieldTypes,
+ assetResourceContentOptions,
+ assetResourceOutputSelection,
+ defaultAssetResourceOutputSelection,
+ getAssetQueryOperatorsForFieldTypes,
+ type AssetObservedFieldType,
+ type AssetQueryFilter,
+} from "./schema";
+
+const getDefaultFilterValue = (operator: AssetQueryFilter["operator"]) =>
+ operator === "in"
+ ? "[]"
+ : operator === "exists" || operator === "isEmpty"
+ ? "true"
+ : '""';
+
+const fieldLabels: Record<(typeof assetQueryStandardFields)[number], string> = {
+ id: "id",
+ url: "url",
+ width: "width",
+ height: "height",
+ name: "name",
+ description: "description",
+ path: "path",
+ key: "key",
+ folderId: "folder id",
+ extension: "extension",
+ mimeType: "mime type",
+ size: "size",
+ createdAt: "created at",
+ revision: "revision",
+ excerpt: "excerpt",
+};
+
+const operatorLabels: Record<AssetQueryFilter["operator"], string> = {
+ eq: "equals",
+ ne: "does not equal",
+ in: "is one of",
+ contains: "contains",
+ startsWith: "starts with",
+ endsWith: "ends with",
+ gt: "greater than",
+ gte: "greater than or equal",
+ lt: "less than",
+ lte: "less than or equal",
+ exists: "exists",
+ isEmpty: "is empty",
+};
+
+/** Asset-specific source contract consumed by generic query codecs. */
+export const assetQuerySourceDefinition = {
+ fields: assetQueryStandardFields.map((field) => ({
+ path: [field],
+ label: fieldLabels[field],
+ types: assetQueryStandardFieldTypes[field],
+ })),
+ operators: assetQueryOperators.map((operator) => ({
+ value: operator,
+ label: operatorLabels[operator],
+ types: assetObservedFieldType.options.filter((type) =>
+ getAssetQueryOperatorsForFieldTypes([type]).includes(operator)
+ ),
+ input: {
+ control:
+ operator === "exists" || operator === "isEmpty"
+ ? ("none" as const)
+ : ("expression" as const),
+ defaultValue: getDefaultFilterValue(operator),
+ },
+ })),
+ source: {
+ fieldPathSchema: z.toJSONSchema(assetQueryFieldPath, {
+ target: "draft-2020-12",
+ io: "input",
+ }),
+ controls: [
+ {
+ type: "variant" as const,
+ key: "output",
+ label: "output",
+ defaultValue: defaultAssetResourceOutputSelection,
+ schema: z.toJSONSchema(assetResourceOutputSelection, {
+ target: "draft-2020-12",
+ io: "input",
+ }),
+ },
+ {
+ type: "variant" as const,
+ key: "content",
+ label: "content",
+ defaultValue: { mode: "none" },
+ schema: z.toJSONSchema(assetResourceContentOptions, {
+ target: "draft-2020-12",
+ io: "input",
+ }),
+ },
+ {
+ type: "filter" as const,
+ key: "where",
+ label: "filters",
+ defaultValue: { all: [] },
+ combinators: ["all", "any"] as const,
+ limits: {
+ conditions: contentEngineLimits.filterCount,
+ depth: contentEngineLimits.filterDepth,
+ },
+ defaultCondition: {
+ field: ["path"],
+ operator: "startsWith" as const,
+ },
+ },
+ {
+ type: "sort" as const,
+ key: "sort",
+ label: "sort",
+ defaultValue: [],
+ defaultItem: { field: ["name"], direction: "asc" as const },
+ directions: [
+ { value: "asc", label: "Ascending" },
+ { value: "desc", label: "Descending" },
+ ],
+ max: contentEngineLimits.sortCount,
+ },
+ {
+ type: "expression" as const,
+ key: "limit",
+ label: "limit",
+ defaultValue: String(contentEngineLimits.defaultResultCount),
+ input: "number" as const,
+ min: 0,
+ max: contentEngineLimits.resultCount,
+ integer: true,
+ },
+ {
+ type: "expression" as const,
+ key: "offset",
+ label: "offset",
+ defaultValue: "0",
+ input: "number" as const,
+ min: 0,
+ max: contentEngineLimits.candidateDocuments,
+ integer: true,
+ },
+ ],
+ },
+} satisfies QuerySourceDefinition<
+ AssetObservedFieldType,
+ AssetQueryFilter["operator"]
+>;
diff --git a/packages/content-engine/src/request.test.ts b/packages/content-engine/src/request.test.ts
new file mode 100644
index 0000000000..788013b629
--- /dev/null
+++ b/packages/content-engine/src/request.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, test } from "vitest";
+import { contentEngineLimits } from "./limits";
+import { readAssetQueryRequest } from "./request";
+
+const validRequest = JSON.stringify({
+ query: {
+ where: { all: [] },
+ sort: [],
+ limit: 1,
+ offset: 0,
+ content: { mode: "none" },
+ },
+});
+
+describe("asset query request", () => {
+ test("limits omitted queries to 20 results", async () => {
+ await expect(
+ readAssetQueryRequest(
+ new Request("https://example.com", {
+ method: "POST",
+ body: JSON.stringify({ query: {} }),
+ })
+ )
+ ).resolves.toMatchObject({ query: { limit: 20 } });
+ });
+
+ test("parses a bounded request", async () => {
+ await expect(
+ readAssetQueryRequest(
+ new Request("https://example.com", {
+ method: "POST",
+ body: validRequest,
+ })
+ )
+ ).resolves.toMatchObject({
+ query: {
+ limit: 1,
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["url"], ["width"], ["height"]],
+ },
+ },
+ });
+ });
+
+ test("rejects declared and streamed bodies over the limit", async () => {
+ await expect(
+ readAssetQueryRequest(
+ new Request("https://example.com", {
+ method: "POST",
+ headers: {
+ "content-length": String(contentEngineLimits.requestBytes + 1),
+ },
+ body: validRequest,
+ })
+ )
+ ).rejects.toThrow("exceeds the byte limit");
+
+ await expect(
+ readAssetQueryRequest(
+ new Request("https://example.com", {
+ method: "POST",
+ body: "x".repeat(contentEngineLimits.requestBytes + 1),
+ })
+ )
+ ).rejects.toThrow("exceeds the byte limit");
+ });
+
+ test("rejects malformed UTF-8 instead of replacing invalid bytes", async () => {
+ const prefix = new TextEncoder().encode(
+ '{"query":{"where":{"all":[]},"sort":[],"limit":1,"offset":0,"content":{"mode":"none"}},"indexRevision":"'
+ );
+ const suffix = new TextEncoder().encode('"}');
+ const body = new Uint8Array(prefix.byteLength + 1 + suffix.byteLength);
+ body.set(prefix);
+ body[prefix.byteLength] = 0xff;
+ body.set(suffix, prefix.byteLength + 1);
+
+ await expect(
+ readAssetQueryRequest(
+ new Request("https://example.com", { method: "POST", body })
+ )
+ ).rejects.toThrow("Asset query request is invalid");
+ });
+});
diff --git a/packages/content-engine/src/request.ts b/packages/content-engine/src/request.ts
new file mode 100644
index 0000000000..a1eb0c3355
--- /dev/null
+++ b/packages/content-engine/src/request.ts
@@ -0,0 +1,80 @@
+import { assetQueryRequest, type AssetQueryRequestInput } from "./schema";
+import { contentEngineLimits } from "./limits";
+import { decodeUtf8 } from "./byte-stream";
+
+export class AssetQueryRequestError extends Error {
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options);
+ this.name = "AssetQueryRequestError";
+ }
+}
+
+export class RequestByteLimitError extends Error {}
+
+export const readBoundedRequestBytes = async (
+ request: Request,
+ maximumBytes: number
+) => {
+ if (Number.isSafeInteger(maximumBytes) === false || maximumBytes < 0) {
+ throw new TypeError("Request byte limit must be a non-negative integer");
+ }
+ const declaredLength = Number(request.headers.get("content-length"));
+ if (Number.isFinite(declaredLength) && declaredLength > maximumBytes) {
+ throw new RequestByteLimitError("Request exceeds the byte limit");
+ }
+ const reader = request.body?.getReader();
+ const chunks: Uint8Array[] = [];
+ let byteLength = 0;
+ if (reader !== undefined) {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) {
+ break;
+ }
+ byteLength += value.byteLength;
+ if (byteLength > maximumBytes) {
+ try {
+ await reader.cancel();
+ } catch {
+ // Preserve the deterministic limit error if stream cancellation fails.
+ }
+ throw new RequestByteLimitError("Request exceeds the byte limit");
+ }
+ chunks.push(value);
+ }
+ }
+ const bytes = new Uint8Array(byteLength);
+ let offset = 0;
+ for (const chunk of chunks) {
+ bytes.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return bytes;
+};
+
+export const readAssetQueryRequest = async (
+ request: Request
+): Promise<AssetQueryRequestInput> => {
+ let bytes: Uint8Array;
+ try {
+ bytes = await readBoundedRequestBytes(
+ request,
+ contentEngineLimits.requestBytes
+ );
+ } catch (error) {
+ if (error instanceof RequestByteLimitError) {
+ throw new AssetQueryRequestError(
+ "Asset query request exceeds the byte limit",
+ { cause: error }
+ );
+ }
+ throw error;
+ }
+ try {
+ return assetQueryRequest.parse(JSON.parse(decodeUtf8(bytes)));
+ } catch (error) {
+ throw new AssetQueryRequestError("Asset query request is invalid", {
+ cause: error,
+ });
+ }
+};
diff --git a/packages/content-engine/src/scale-fixture.test.ts b/packages/content-engine/src/scale-fixture.test.ts
new file mode 100644
index 0000000000..69947e3e46
--- /dev/null
+++ b/packages/content-engine/src/scale-fixture.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, test } from "vitest";
+import { extractMarkdownFrontmatter } from "./markdown";
+import { createScaleMarkdownFixture } from "./scale-fixture";
+
+describe("1,000-file Markdown scale fixture", () => {
+ test("provides deterministic nested, optional, array, and mixed-type frontmatter", async () => {
+ const files = createScaleMarkdownFixture();
+ expect(files).toHaveLength(1000);
+ expect(new Set(files.map(({ id }) => id)).size).toBe(1000);
+ const first = await extractMarkdownFrontmatter(files[0].source);
+ const second = await extractMarkdownFrontmatter(files[1].source);
+ expect(first.properties).toMatchObject({
+ slug: "post-0000",
+ author: { name: "Author 0" },
+ tags: ["tag-0", "group-0"],
+ series: { name: "Series 0", position: 0 },
+ rating: 0,
+ });
+ expect(second.properties).toMatchObject({ rating: "1" });
+ expect(second.properties).not.toHaveProperty("series");
+ });
+});
diff --git a/packages/content-engine/src/scale-fixture.ts b/packages/content-engine/src/scale-fixture.ts
new file mode 100644
index 0000000000..ba97fd187b
--- /dev/null
+++ b/packages/content-engine/src/scale-fixture.ts
@@ -0,0 +1,39 @@
+export type ScaleMarkdownFixtureFile = {
+ id: string;
+ name: string;
+ source: string;
+};
+
+/** Deterministic schema-less Markdown corpus used by scale tests and benchmarks. */
+export const createScaleMarkdownFixture = (
+ count = 1000
+): ScaleMarkdownFixtureFile[] =>
+ Array.from({ length: count }, (_, index) => {
+ const id = `post-${String(index).padStart(4, "0")}`;
+ const optional =
+ index % 3 === 0
+ ? `\nseries:\n name: Series ${index % 7}\n position: ${index}`
+ : "";
+ const mixed =
+ index % 5 === 0 ? `\nrating: ${index % 10}` : `\nrating: "${index % 10}"`;
+ return {
+ id,
+ name: `${id}.md`,
+ source: `---
+title: Post ${index}
+slug: ${id}
+publishedAt: 2026-07-${String((index % 28) + 1).padStart(2, "0")}
+draft: ${index % 10 === 0 ? "true" : "false"}
+locale: ${index % 2 === 0 ? "en" : "de"}
+author:
+ name: Author ${index % 25}
+tags:
+ - tag-${index % 10}
+ - group-${index % 4}${optional}${mixed}
+---
+# Post ${index}
+
+Deterministic body ${index} for the asset-resource scale fixture.
+`,
+ };
+ });
diff --git a/packages/content-engine/src/schema.test.ts b/packages/content-engine/src/schema.test.ts
new file mode 100644
index 0000000000..0839e1dbab
--- /dev/null
+++ b/packages/content-engine/src/schema.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, test } from "vitest";
+import { contentEngineLimits } from "./limits";
+import { assetQuery, type AssetQueryWhere } from "./schema";
+
+const condition = {
+ field: ["properties", "slug"],
+ operator: "eq" as const,
+ value: "post",
+};
+
+const nestCondition = (depth: number): AssetQueryWhere => {
+ let where: AssetQueryWhere = condition;
+ for (let index = 0; index < depth; index += 1) {
+ where = { all: [where] };
+ }
+ return where;
+};
+
+describe("assetQuery", () => {
+ test("enforces the filter nesting limit in the request schema", () => {
+ expect(
+ assetQuery.safeParse({
+ where: nestCondition(contentEngineLimits.filterDepth),
+ }).success
+ ).toBe(true);
+ expect(
+ assetQuery.safeParse({
+ where: nestCondition(contentEngineLimits.filterDepth + 1),
+ }).success
+ ).toBe(false);
+ });
+
+ test("enforces the total filter limit across groups", () => {
+ const group = {
+ all: Array.from(
+ { length: contentEngineLimits.filterCount / 2 + 1 },
+ () => condition
+ ),
+ };
+ expect(
+ assetQuery.safeParse({ where: { any: [group, group] } }).success
+ ).toBe(false);
+ });
+});
diff --git a/packages/content-engine/src/schema.ts b/packages/content-engine/src/schema.ts
new file mode 100644
index 0000000000..972fc97d75
--- /dev/null
+++ b/packages/content-engine/src/schema.ts
@@ -0,0 +1,641 @@
+import {
+ array,
+ boolean,
+ discriminatedUnion,
+ enum as zEnum,
+ json,
+ literal,
+ number,
+ object,
+ record,
+ strictObject,
+ string,
+ type ZodType,
+ type infer as Infer,
+ type input as Input,
+} from "zod";
+import {
+ createQueryWhereSchema,
+ getQueryFieldKey,
+ getQueryWhereMetrics,
+ type QueryWhereTree,
+} from "@webstudio-is/query-builder/runtime";
+import { contentEngineLimits } from "./limits";
+
+const relativeAssetPath = string()
+ .min(1)
+ .refine((path) => path.startsWith("/") === false, {
+ error: "Asset path must be relative",
+ })
+ .refine(
+ (path) =>
+ path.includes("\\") === false &&
+ path
+ .split("/")
+ .every(
+ (segment) => segment.length > 0 && segment !== ".." && segment !== "."
+ ),
+ { error: "Asset path must be normalized and must not contain dot segments" }
+ );
+
+/**
+ * Lightweight file document exposed to asset-resource queries.
+ *
+ * Complete file content is deliberately represented by contentRef and is not
+ * part of this query document.
+ */
+export const assetFileDocument = strictObject({
+ _id: string().min(1),
+ _type: literal("asset.file"),
+ name: string().min(1),
+ description: string().optional(),
+ path: relativeAssetPath,
+ key: string(),
+ folderId: string().min(1).optional(),
+ extension: string().regex(/^[a-z0-9]*$/),
+ mimeType: string().min(1),
+ size: number().int().nonnegative(),
+ createdAt: string().datetime().optional(),
+ revision: string().min(1),
+ contentRef: string().min(1),
+ properties: record(string(), json()),
+ excerpt: string().optional(),
+ metadataError: strictObject({
+ code: string().min(1),
+ message: string().min(1),
+ }).optional(),
+});
+
+export type AssetFileDocument = Infer<typeof assetFileDocument>;
+
+/** Query-specific document stored in a compiled content database. */
+export const contentDatabaseDocument = assetFileDocument
+ .partial()
+ .required({ _id: true });
+
+export type ContentDatabaseDocument = Infer<typeof contentDatabaseDocument>;
+
+export const assetObservedFieldType = zEnum([
+ "null",
+ "boolean",
+ "number",
+ "string",
+ "object",
+ "array",
+]);
+
+export type AssetObservedFieldType = Infer<typeof assetObservedFieldType>;
+
+export const builderAssetFieldCatalog = object({
+ format: literal("webstudio-builder-asset-field-catalog"),
+ version: literal(1),
+ canonicalRevision: string().regex(/^sha256:[a-f0-9]{64}$/),
+ documentCount: number().int().nonnegative(),
+ fields: record(
+ string().min(1),
+ object({
+ queryPath: array(string().min(1))
+ .min(1)
+ .max(contentEngineLimits.fieldPathDepth)
+ .optional(),
+ types: array(assetObservedFieldType).min(1),
+ occurrences: number().int().positive(),
+ optional: literal(true).optional(),
+ mixed: literal(true).optional(),
+ })
+ ),
+}).superRefine((catalog, context) => {
+ for (const [path, field] of Object.entries(catalog.fields)) {
+ const sortedTypes = [...new Set(field.types)].sort();
+ if (JSON.stringify(field.types) !== JSON.stringify(sortedTypes)) {
+ context.addIssue({
+ code: "custom",
+ path: ["fields", path, "types"],
+ message: "Observed field types must be unique and sorted",
+ });
+ }
+ if (field.occurrences > catalog.documentCount) {
+ context.addIssue({
+ code: "custom",
+ path: ["fields", path, "occurrences"],
+ message: "Field occurrences cannot exceed the document count",
+ });
+ }
+ const optional = field.occurrences < catalog.documentCount;
+ if ((field.optional === true) !== optional) {
+ context.addIssue({
+ code: "custom",
+ path: ["fields", path, "optional"],
+ message: "Field optionality must match its occurrence count",
+ });
+ }
+ const mixed = sortedTypes.length > 1;
+ if ((field.mixed === true) !== mixed) {
+ context.addIssue({
+ code: "custom",
+ path: ["fields", path, "mixed"],
+ message: "Mixed status must match the observed types",
+ });
+ }
+ }
+});
+
+export type BuilderAssetFieldCatalog = Infer<typeof builderAssetFieldCatalog>;
+
+const sha256Revision = string().regex(/^sha256:[a-f0-9]{64}$/);
+
+/** One compiled runtime database shared by all reachable Assets queries. */
+export const contentArtifactV1 = strictObject({
+ format: literal("webstudio-content-database"),
+ version: literal(1),
+ assetRevision: sha256Revision,
+ documents: array(contentDatabaseDocument),
+ contents: record(string().min(1), string()).optional(),
+ assetReferences: record(
+ string().min(1),
+ array(
+ strictObject({
+ start: number().int().nonnegative(),
+ end: number().int().positive(),
+ assetId: string().min(1),
+ suffix: string().min(1).optional(),
+ }).refine(({ start, end }) => end > start, {
+ message: "Markdown asset reference range must not be empty",
+ })
+ )
+ ).optional(),
+ fieldCatalog: builderAssetFieldCatalog,
+ database: strictObject({
+ maxBytes: number().int().positive(),
+ unboundedBytes: number().int().nonnegative(),
+ sourceDocumentCount: number().int().nonnegative(),
+ }).optional(),
+ integrity: strictObject({
+ algorithm: literal("sha256"),
+ checksum: sha256Revision,
+ }),
+}).superRefine((index, context) => {
+ if (index.documents.length > contentEngineLimits.candidateDocuments) {
+ context.addIssue({
+ code: "custom",
+ path: ["documents"],
+ message: "Asset index exceeds the document limit",
+ });
+ }
+ if (
+ index.fieldCatalog.canonicalRevision !== index.assetRevision ||
+ index.fieldCatalog.documentCount !== index.documents.length
+ ) {
+ context.addIssue({
+ code: "custom",
+ path: ["fieldCatalog"],
+ message: "Asset index field catalog does not match its documents",
+ });
+ }
+ if (
+ index.database !== undefined &&
+ index.database.sourceDocumentCount < index.documents.length
+ ) {
+ context.addIssue({
+ code: "custom",
+ path: ["database", "sourceDocumentCount"],
+ message: "Source document count cannot be smaller than the database",
+ });
+ }
+ let previousId: string | undefined;
+ for (const [position, document] of index.documents.entries()) {
+ if (previousId !== undefined && document._id <= previousId) {
+ context.addIssue({
+ code: "custom",
+ path: ["documents", position, "_id"],
+ message: "Asset index documents must have unique sorted IDs",
+ });
+ }
+ previousId = document._id;
+ }
+ const contentRefs = new Set(
+ index.documents.flatMap(({ contentRef }) =>
+ contentRef === undefined ? [] : [contentRef]
+ )
+ );
+ for (const contentRef of Object.keys(index.contents ?? {})) {
+ if (contentRefs.has(contentRef) === false) {
+ context.addIssue({
+ code: "custom",
+ path: ["contents", contentRef],
+ message: "Embedded content must belong to an indexed document",
+ });
+ }
+ }
+ for (const contentRef of Object.keys(index.assetReferences ?? {})) {
+ if (contentRefs.has(contentRef) === false) {
+ context.addIssue({
+ code: "custom",
+ path: ["assetReferences", contentRef],
+ message: "Asset references must belong to an indexed document",
+ });
+ }
+ }
+});
+
+export type ContentArtifactV1 = Infer<typeof contentArtifactV1>;
+
+export const assetResourceContentOptions = discriminatedUnion("mode", [
+ object({ mode: literal("none") }),
+ object({
+ mode: literal("full"),
+ maxBytes: number()
+ .int()
+ .positive()
+ .max(contentEngineLimits.hydratedFileBytes)
+ .optional(),
+ }),
+ object({
+ mode: literal("range"),
+ offset: number().int().nonnegative(),
+ length: number()
+ .int()
+ .positive()
+ .max(contentEngineLimits.hydratedRangeBytes),
+ }),
+ object({
+ mode: literal("markdown-body"),
+ maxBytes: number()
+ .int()
+ .positive()
+ .max(contentEngineLimits.hydratedFileBytes)
+ .optional(),
+ }),
+]);
+
+export type AssetResourceContentOptions = Infer<
+ typeof assetResourceContentOptions
+>;
+
+export const assetQueryStandardFieldTypes = {
+ 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"],
+} as const satisfies Record<string, readonly AssetObservedFieldType[]>;
+
+export const assetQueryStandardFields = Object.keys(
+ assetQueryStandardFieldTypes
+) as [keyof typeof assetQueryStandardFieldTypes];
+
+export const assetQueryRuntimeFields = ["url", "width", "height"] as const;
+export const isAssetQueryRuntimeField = (
+ field: string
+): field is (typeof assetQueryRuntimeFields)[number] =>
+ (assetQueryRuntimeFields as readonly string[]).includes(field);
+
+export const assetQueryMetadataFields = assetQueryStandardFields.filter(
+ (field) => isAssetQueryRuntimeField(field) === false && field !== "excerpt"
+);
+export const assetQueryDocumentFields = assetQueryMetadataFields.filter(
+ (field) => field !== "id"
+);
+export const isAssetQueryMetadataField = (field: string) =>
+ (assetQueryMetadataFields as readonly string[]).includes(field);
+
+const assetQueryStandardField = zEnum(assetQueryStandardFields);
+
+export const assetQueryFieldPath = array(string().min(1))
+ .min(1)
+ .max(contentEngineLimits.fieldPathDepth)
+ .superRefine((path, context) => {
+ if (path[0] === "properties") {
+ if (path.length < 2) {
+ context.addIssue({
+ code: "custom",
+ message: "A properties field path must select a property",
+ });
+ }
+ return;
+ }
+ if (
+ path.length !== 1 ||
+ assetQueryStandardField.safeParse(path[0]).success === false
+ ) {
+ context.addIssue({
+ code: "custom",
+ message: "Asset query field path is unsupported",
+ });
+ }
+ });
+
+export type AssetQueryFieldPath = Infer<typeof assetQueryFieldPath>;
+
+const includeMetadata = boolean().default(true);
+
+export const assetResourceOutputSelection = discriminatedUnion("mode", [
+ strictObject({
+ mode: literal("all"),
+ includeMetadata,
+ }),
+ strictObject({
+ mode: literal("base"),
+ includeMetadata,
+ }),
+ strictObject({
+ mode: literal("fields"),
+ includeMetadata,
+ fields: array(assetQueryFieldPath)
+ .max(contentEngineLimits.outputFieldCount)
+ .refine(
+ (fields) =>
+ new Set(fields.map(getQueryFieldKey)).size === fields.length,
+ { error: "Selected output fields must be unique" }
+ ),
+ }),
+]);
+
+export type AssetResourceOutputSelection = Infer<
+ typeof assetResourceOutputSelection
+>;
+
+export const defaultAssetResourceOutputSelection = {
+ mode: "fields",
+ includeMetadata: false,
+ fields: assetQueryRuntimeFields.map((field) => [field]),
+} as const satisfies AssetResourceOutputSelection;
+
+export const assetQueryValueOperators = [
+ "eq",
+ "ne",
+ "contains",
+ "startsWith",
+ "endsWith",
+ "gt",
+ "gte",
+ "lt",
+ "lte",
+] as const;
+export const assetQueryOperators = [
+ ...assetQueryValueOperators,
+ "in",
+ "exists",
+ "isEmpty",
+] as const;
+export type AssetQueryOperator = (typeof assetQueryOperators)[number];
+
+const assetQueryValueFilter = strictObject({
+ field: assetQueryFieldPath,
+ operator: zEnum(assetQueryValueOperators),
+ value: json(),
+});
+
+const assetQueryInFilter = strictObject({
+ field: assetQueryFieldPath,
+ operator: literal("in"),
+ value: array(json()).max(contentEngineLimits.resultCount),
+});
+
+const assetQueryBooleanFilter = strictObject({
+ field: assetQueryFieldPath,
+ operator: zEnum(["exists", "isEmpty"]),
+ value: boolean(),
+});
+
+export const assetQueryFilter = discriminatedUnion("operator", [
+ assetQueryValueFilter,
+ assetQueryInFilter,
+ assetQueryBooleanFilter,
+]);
+
+export type AssetQueryFilter = Infer<typeof assetQueryFilter>;
+
+export type AssetQueryWhere = QueryWhereTree<AssetQueryFilter>;
+
+const assetQueryWhereNode: ZodType<AssetQueryWhere, AssetQueryWhere> =
+ createQueryWhereSchema(assetQueryFilter, {
+ maximumChildren: contentEngineLimits.filterCount,
+ maximumConditions: contentEngineLimits.filterCount,
+ maximumDepth: contentEngineLimits.filterDepth,
+ maximumConditionsMessage: "Asset query exceeds the filter limit",
+ maximumDepthMessage: "Asset query exceeds the filter nesting limit",
+ });
+
+export const getAssetQueryWhereMetrics = (where: AssetQueryWhere) => {
+ const { conditions, depth } = getQueryWhereMetrics(where);
+ return { filters: conditions, depth };
+};
+
+const assetQueryWhere = assetQueryWhereNode;
+
+export const getAssetQueryOperatorsForFieldTypes = (
+ fieldTypes: readonly AssetObservedFieldType[]
+) => {
+ const operators = new Set<AssetQueryOperator>(["eq", "ne", "in", "exists"]);
+ if (fieldTypes.some((type) => type === "string" || type === "array")) {
+ operators.add("contains");
+ }
+ if (fieldTypes.includes("string")) {
+ operators.add("startsWith");
+ operators.add("endsWith");
+ }
+ if (fieldTypes.some((type) => type === "string" || type === "number")) {
+ operators.add("gt");
+ operators.add("gte");
+ operators.add("lt");
+ operators.add("lte");
+ }
+ if (
+ fieldTypes.some(
+ (type) => type === "string" || type === "array" || type === "object"
+ )
+ ) {
+ operators.add("isEmpty");
+ }
+ return [...operators];
+};
+
+export const assetQuerySort = strictObject({
+ field: assetQueryFieldPath,
+ direction: zEnum(["asc", "desc"]),
+});
+
+export type AssetQuerySort = Infer<typeof assetQuerySort>;
+
+export const hasAssetQueryOutput = ({
+ output,
+ content,
+}: {
+ output: AssetResourceOutputSelection;
+ content: AssetResourceContentOptions;
+}) =>
+ output.includeMetadata ||
+ output.mode === "all" ||
+ (output.mode === "fields" && output.fields.length > 0) ||
+ content.mode !== "none";
+
+/** Typed configuration for the query mode of the Assets system resource. */
+export const assetQuery = strictObject({
+ where: assetQueryWhere.default({ all: [] }),
+ sort: array(assetQuerySort).max(contentEngineLimits.sortCount).default([]),
+ limit: number()
+ .int()
+ .nonnegative()
+ .max(contentEngineLimits.resultCount)
+ .default(contentEngineLimits.defaultResultCount),
+ offset: number()
+ .int()
+ .nonnegative()
+ .max(contentEngineLimits.candidateDocuments)
+ .default(0),
+ output: assetResourceOutputSelection.default(
+ defaultAssetResourceOutputSelection
+ ),
+ content: assetResourceContentOptions.default({ mode: "none" }),
+}).refine(hasAssetQueryOutput, {
+ error: "Select at least one asset query output",
+});
+
+export type AssetQuery = Infer<typeof assetQuery>;
+export type AssetQueryInput = Input<typeof assetQuery>;
+
+export const assetQueryRequest = strictObject({
+ query: assetQuery,
+ indexRevision: string().min(1).max(255).optional(),
+});
+
+export type AssetQueryRequest = Infer<typeof assetQueryRequest>;
+export type AssetQueryRequestInput = Input<typeof assetQueryRequest>;
+
+export const hydratedAssetContent = object({
+ _id: string().min(1),
+ revision: string().min(1),
+ contentRef: string().min(1),
+ encoding: literal("utf-8"),
+ text: string(),
+ range: object({
+ offset: number().int().nonnegative(),
+ length: number().int().nonnegative(),
+ total: number().int().nonnegative(),
+ }).optional(),
+});
+
+export type HydratedAssetContent = Infer<typeof hydratedAssetContent>;
+
+const assetQueryContent = hydratedAssetContent.omit({
+ _id: true,
+ revision: true,
+ contentRef: true,
+});
+
+export const assetQueryItem = assetFileDocument
+ .omit({ _id: true, _type: true, contentRef: true })
+ .partial()
+ .extend({
+ // Identity is part of the Assets resource structure, independently of the
+ // fields selected for each value.
+ id: string().min(1),
+ url: string().min(1).optional(),
+ width: number().positive().optional(),
+ height: number().positive().optional(),
+ content: assetQueryContent.optional(),
+ })
+ .refine(
+ (item) => (item.width === undefined) === (item.height === undefined),
+ { error: "Asset dimensions must include both width and height" }
+ );
+
+export type AssetQueryItem = Infer<typeof assetQueryItem>;
+
+export const contentDatabaseStats = strictObject({
+ format: literal("webstudio-content-database"),
+ version: literal(1),
+ revision: sha256Revision,
+ usedBytes: number().int().nonnegative(),
+ maxBytes: number().int().positive(),
+ unboundedBytes: number().int().nonnegative(),
+ includedDocumentCount: number().int().nonnegative(),
+ omittedDocumentCount: number().int().nonnegative(),
+ truncated: boolean(),
+});
+
+export type ContentDatabaseStats = Infer<typeof contentDatabaseStats>;
+
+export const assetQueryPreviewDiagnostics = contentDatabaseStats
+ .pick({
+ usedBytes: true,
+ maxBytes: true,
+ unboundedBytes: true,
+ includedDocumentCount: true,
+ omittedDocumentCount: true,
+ truncated: true,
+ })
+ .extend({ scope: literal("query-preview") });
+
+export type AssetQueryPreviewDiagnostics = Infer<
+ typeof assetQueryPreviewDiagnostics
+>;
+
+export const assetQueryResult = strictObject({
+ items: array(assetQueryItem),
+ totalCount: number().int().nonnegative(),
+ hasMore: boolean(),
+});
+
+export type AssetQueryResult = Infer<typeof assetQueryResult>;
+
+export const assetQueryPreviewResult = strictObject({
+ data: assetQueryResult,
+ __diagnostics__: assetQueryPreviewDiagnostics,
+});
+
+export type AssetQueryPreviewResult = Infer<typeof assetQueryPreviewResult>;
+
+export const assetResourceErrorCode = zEnum([
+ "INVALID_REQUEST",
+ "REQUEST_CANCELLED",
+ "UNAUTHORIZED",
+ "FORBIDDEN",
+ "STALE_INDEX",
+ "CONTENT_IDENTITY_REQUIRED",
+ "CONTENT_NOT_TEXT",
+ "CONTENT_DECODING_FAILED",
+ "CONTENT_LIMIT_EXCEEDED",
+ "INTERNAL_ERROR",
+]);
+
+export type AssetResourceErrorCode = Infer<typeof assetResourceErrorCode>;
+
+export const assetResourceQueryFailure = object({
+ ok: literal(false),
+ error: object({
+ code: assetResourceErrorCode,
+ message: string().min(1),
+ retryable: boolean(),
+ details: record(string(), json()).optional(),
+ }),
+ meta: object({
+ queryHash: string().min(1).optional(),
+ indexRevision: string().min(1).optional(),
+ assetRevision: string().min(1).optional(),
+ }).optional(),
+});
+
+export type AssetResourceQueryFailure = Infer<typeof assetResourceQueryFailure>;
+
+export const createAssetResourceQueryFailure = ({
+ code,
+ message,
+ retryable = false,
+ details,
+}: AssetResourceQueryFailure["error"]) =>
+ assetResourceQueryFailure.parse({
+ ok: false,
+ error: { code, message, retryable, details },
+ });
diff --git a/packages/content-engine/src/structured-data.ts b/packages/content-engine/src/structured-data.ts
new file mode 100644
index 0000000000..514a00b550
--- /dev/null
+++ b/packages/content-engine/src/structured-data.ts
@@ -0,0 +1,96 @@
+import { getUtf8ByteLength } from "./byte-stream";
+
+export type StructuredDataLimits = {
+ depth: number;
+ fields: number;
+ stringBytes: number;
+ serializedBytes: number;
+};
+
+export type StructuredDataErrorCode =
+ | "INVALID"
+ | "DEPTH_EXCEEDED"
+ | "FIELDS_EXCEEDED"
+ | "STRING_BYTES_EXCEEDED"
+ | "SERIALIZED_BYTES_EXCEEDED";
+
+export class StructuredDataError extends Error {
+ readonly code: StructuredDataErrorCode;
+
+ constructor(code: StructuredDataErrorCode) {
+ super(`Structured data failed validation: ${code}`);
+ this.name = "StructuredDataError";
+ this.code = code;
+ }
+}
+
+export const getStructuredDataByteLength = (value: unknown) =>
+ getUtf8ByteLength(JSON.stringify(value));
+
+const isPlainObject = (
+ value: unknown
+): value is Readonly<Record<string, unknown>> => {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
+ return false;
+ }
+ const prototype = Object.getPrototypeOf(value);
+ return prototype === Object.prototype || prototype === null;
+};
+
+export const normalizeStructuredDataObject = (
+ value: unknown,
+ limits: StructuredDataLimits
+): Record<string, unknown> => {
+ if (isPlainObject(value) === false) {
+ throw new StructuredDataError("INVALID");
+ }
+
+ let fields = 0;
+ const normalize = (input: unknown, depth: number): unknown => {
+ if (depth > limits.depth) {
+ throw new StructuredDataError("DEPTH_EXCEEDED");
+ }
+ if (typeof input === "string") {
+ if (getUtf8ByteLength(input) > limits.stringBytes) {
+ throw new StructuredDataError("STRING_BYTES_EXCEEDED");
+ }
+ return input;
+ }
+ if (
+ input === null ||
+ typeof input === "boolean" ||
+ (typeof input === "number" &&
+ Number.isFinite(input) &&
+ (Number.isInteger(input) === false || Number.isSafeInteger(input)))
+ ) {
+ return input;
+ }
+ if (Array.isArray(input)) {
+ return input.map((item) => {
+ fields += 1;
+ if (fields > limits.fields) {
+ throw new StructuredDataError("FIELDS_EXCEEDED");
+ }
+ return normalize(item, depth + 1);
+ });
+ }
+ if (isPlainObject(input)) {
+ const result: Record<string, unknown> = Object.create(null);
+ for (const [key, child] of Object.entries(input)) {
+ fields += 1;
+ if (fields > limits.fields) {
+ throw new StructuredDataError("FIELDS_EXCEEDED");
+ }
+ result[key] = normalize(child, depth + 1);
+ }
+ return result;
+ }
+ throw new StructuredDataError("INVALID");
+ };
+
+ const normalized = normalize(value, 1) as Record<string, unknown>;
+ if (getStructuredDataByteLength(normalized) > limits.serializedBytes) {
+ throw new StructuredDataError("SERIALIZED_BYTES_EXCEEDED");
+ }
+ return normalized;
+};
diff --git a/packages/content-engine/src/structured-query.test.ts b/packages/content-engine/src/structured-query.test.ts
new file mode 100644
index 0000000000..7b733b4701
--- /dev/null
+++ b/packages/content-engine/src/structured-query.test.ts
@@ -0,0 +1,545 @@
+import { describe, expect, test } from "vitest";
+import type { AssetFileDocument, BuilderAssetFieldCatalog } from "./schema";
+import {
+ executeAssetQuery,
+ getAssetQueryFieldValue,
+ validateAssetQueryAgainstCatalog,
+} from "./structured-query";
+
+const document = ({
+ id,
+ properties,
+ description,
+ excerpt,
+ createdAt,
+}: {
+ id: string;
+ properties: AssetFileDocument["properties"];
+ description?: string;
+ excerpt?: string;
+ createdAt?: string;
+}): AssetFileDocument => ({
+ _id: id,
+ _type: "asset.file",
+ name: `${id}.md`,
+ description,
+ path: `blog/${id}.md`,
+ key: `key-${id}`,
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 20,
+ createdAt,
+ revision: `revision-${id}`,
+ contentRef: `files/${id}.md`,
+ properties,
+ excerpt,
+});
+
+const documents = [
+ document({
+ id: "alpha",
+ description: "Alpha description",
+ createdAt: "2026-07-27T00:00:00.000Z",
+ excerpt: "Alpha excerpt",
+ properties: {
+ title: "Alpha",
+ publishedAt: "2025-01-01",
+ draft: false,
+ tags: ["news", "alpha"],
+ },
+ }),
+ document({
+ id: "beta",
+ properties: {
+ title: "Beta",
+ publishedAt: "2024-01-01",
+ draft: true,
+ tags: ["private"],
+ },
+ }),
+ document({
+ id: "gamma",
+ properties: {
+ title: "Gamma",
+ publishedAt: "2026-01-01",
+ tags: ["news"],
+ },
+ }),
+];
+
+const catalog: BuilderAssetFieldCatalog = {
+ format: "webstudio-builder-asset-field-catalog",
+ version: 1,
+ canonicalRevision: `sha256:${"0".repeat(64)}`,
+ documentCount: documents.length,
+ fields: {
+ "properties.title": { types: ["string"], occurrences: 3 },
+ "properties.publishedAt": { types: ["string"], occurrences: 3 },
+ "properties.draft": {
+ types: ["boolean"],
+ occurrences: 2,
+ optional: true,
+ },
+ "properties.tags": { types: ["array"], occurrences: 3 },
+ },
+};
+
+const runtimeAssets = Object.fromEntries(
+ documents.map(({ _id }) => [_id, { url: `/assets/${_id}` }])
+);
+
+describe("structured asset query", () => {
+ test("combines nested all and any filter groups", async () => {
+ const result = await executeAssetQuery({
+ catalog,
+ documents,
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "draft"],
+ operator: "ne",
+ value: true,
+ },
+ {
+ any: [
+ {
+ field: ["properties", "title"],
+ operator: "eq",
+ value: "Alpha",
+ },
+ {
+ field: ["properties", "publishedAt"],
+ operator: "eq",
+ value: "2026-01-01",
+ },
+ ],
+ },
+ ],
+ },
+ },
+ runtimeAssets: {
+ alpha: { url: "/assets/alpha.png", width: 1200, height: 800 },
+ gamma: { url: "/assets/gamma.md" },
+ },
+ });
+
+ expect(result.items).toEqual([
+ {
+ id: "alpha",
+ url: "/assets/alpha.png",
+ width: 1200,
+ height: 800,
+ },
+ { id: "gamma", url: "/assets/gamma.md" },
+ ]);
+ });
+
+ test("filters and sorts by target-specific runtime fields", async () => {
+ const result = await executeAssetQuery({
+ catalog,
+ documents,
+ runtimeAssets: {
+ alpha: { url: "/assets/alpha", width: 1200, height: 800 },
+ beta: { url: "/assets/beta", width: 640, height: 480 },
+ gamma: { url: "/assets/gamma" },
+ },
+ query: {
+ where: {
+ all: [{ field: ["width"], operator: "gte", value: 600 }],
+ },
+ sort: [{ field: ["width"], direction: "asc" }],
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["id"], ["width"]],
+ },
+ content: { mode: "none" },
+ },
+ });
+
+ expect(result.items).toEqual([
+ { id: "beta", width: 640 },
+ { id: "alpha", width: 1200 },
+ ]);
+ });
+
+ test("reads only own JSON properties from dynamic field paths", () => {
+ const inheritedNames = document({ id: "plain", properties: {} });
+ expect(
+ getAssetQueryFieldValue(inheritedNames, ["properties", "constructor"])
+ ).toBeUndefined();
+ expect(
+ getAssetQueryFieldValue(inheritedNames, ["properties", "toString"])
+ ).toBeUndefined();
+
+ const ownNames = document({
+ id: "own",
+ properties: JSON.parse(
+ '{"constructor":"constructor value","toString":"string value","__proto__":"prototype value"}'
+ ),
+ });
+ expect(
+ getAssetQueryFieldValue(ownNames, ["properties", "constructor"])
+ ).toBe("constructor value");
+ expect(getAssetQueryFieldValue(ownNames, ["properties", "toString"])).toBe(
+ "string value"
+ );
+ expect(getAssetQueryFieldValue(ownNames, ["properties", "__proto__"])).toBe(
+ "prototype value"
+ );
+
+ expect(
+ validateAssetQueryAgainstCatalog({
+ catalog,
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "constructor"],
+ operator: "eq",
+ value: "missing",
+ },
+ ],
+ },
+ },
+ }).warnings
+ ).toEqual(["Asset field properties.constructor is not currently observed"]);
+ });
+
+ test("treats dynamic fields absent from the current catalog as missing", async () => {
+ const query = {
+ where: {
+ all: [
+ {
+ field: ["properties", "missing"] as [string, string],
+ operator: "eq" as const,
+ value: true,
+ },
+ ],
+ },
+ content: { mode: "none" as const },
+ };
+ expect(
+ validateAssetQueryAgainstCatalog({ catalog, query }).warnings
+ ).toEqual(["Asset field properties.missing is not currently observed"]);
+ const result = await executeAssetQuery({
+ catalog,
+ documents,
+ query,
+ });
+
+ expect(result.items).toEqual([]);
+ expect(result.totalCount).toBe(0);
+ });
+
+ test("keeps sorting deterministic when a dynamic field becomes mixed", async () => {
+ const mixedDocuments = [
+ ...documents,
+ document({ id: "delta", properties: { publishedAt: { year: 2027 } } }),
+ ];
+ const result = await executeAssetQuery({
+ catalog: {
+ ...catalog,
+ documentCount: mixedDocuments.length,
+ fields: {
+ ...catalog.fields,
+ "properties.publishedAt": {
+ types: ["object", "string"],
+ occurrences: mixedDocuments.length,
+ mixed: true,
+ },
+ },
+ },
+ documents: mixedDocuments,
+ runtimeAssets: {
+ ...runtimeAssets,
+ delta: { url: "/assets/delta" },
+ },
+ query: {
+ sort: [{ field: ["properties", "publishedAt"], direction: "asc" }],
+ content: { mode: "none" },
+ },
+ });
+
+ expect(result.items.map(({ id }) => id)).toEqual([
+ "beta",
+ "alpha",
+ "gamma",
+ "delta",
+ ]);
+ });
+
+ test("filters dynamic fields, sorts, paginates, and returns public records", async () => {
+ const result = await executeAssetQuery({
+ catalog,
+ documents,
+ runtimeAssets,
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "draft"],
+ operator: "ne",
+ value: true,
+ },
+ {
+ field: ["properties", "tags"],
+ operator: "contains",
+ value: "news",
+ },
+ ],
+ },
+ sort: [
+ {
+ field: ["properties", "publishedAt"],
+ direction: "desc",
+ },
+ ],
+ limit: 1,
+ offset: 0,
+ output: { mode: "all", includeMetadata: true },
+ content: { mode: "none" },
+ },
+ });
+
+ expect(result).toEqual({
+ items: [
+ expect.objectContaining({
+ id: "gamma",
+ path: "blog/gamma.md",
+ properties: expect.objectContaining({ title: "Gamma" }),
+ }),
+ ],
+ totalCount: 2,
+ hasMore: true,
+ });
+ expect(result.items[0]).not.toHaveProperty("contentRef");
+ expect(result.items[0]).not.toHaveProperty("_id");
+ });
+
+ test("hydrates only selected Markdown content without exposing storage identity", async () => {
+ const bytes = new TextEncoder().encode(
+ "---\ntitle: Alpha\n---\n# Alpha body\n"
+ );
+ const result = await executeAssetQuery({
+ catalog,
+ documents: [{ ...documents[0], size: bytes.byteLength }],
+ runtimeAssets,
+ query: {
+ where: { all: [{ field: ["id"], operator: "eq", value: "alpha" }] },
+ sort: [],
+ limit: 1,
+ offset: 0,
+ content: { mode: "markdown-body" },
+ },
+ read: async () => ({
+ data: {
+ async *[Symbol.asyncIterator]() {
+ yield bytes;
+ },
+ },
+ contentLength: bytes.byteLength,
+ }),
+ });
+
+ expect(result.items[0].content).toEqual({
+ encoding: "utf-8",
+ text: "# Alpha body\n",
+ });
+ expect(result.items[0].content).not.toHaveProperty("contentRef");
+ });
+
+ test("projects explicit output fields while retaining base file metadata", async () => {
+ const selected = await executeAssetQuery({
+ catalog,
+ documents,
+ runtimeAssets,
+ query: {
+ where: { all: [] },
+ sort: [],
+ limit: 1,
+ offset: 0,
+ output: {
+ mode: "fields",
+ includeMetadata: true,
+ fields: [["properties", "title"], ["excerpt"]],
+ },
+ content: { mode: "none" },
+ },
+ });
+ expect(selected.items[0]).toMatchObject({
+ id: "alpha",
+ name: "alpha.md",
+ description: "Alpha description",
+ properties: { title: "Alpha" },
+ excerpt: "Alpha excerpt",
+ });
+ expect(selected.items[0]).not.toHaveProperty("url");
+ expect(selected.items[0]).not.toHaveProperty("width");
+ expect(selected.items[0]).not.toHaveProperty("height");
+ expect(selected.items[0].properties).not.toHaveProperty("draft");
+
+ const base = await executeAssetQuery({
+ catalog,
+ documents,
+ runtimeAssets,
+ query: {
+ where: { all: [] },
+ sort: [],
+ limit: 1,
+ offset: 0,
+ output: { mode: "base", includeMetadata: true },
+ content: { mode: "none" },
+ },
+ });
+ expect(base.items[0]).toMatchObject({
+ id: "alpha",
+ name: "alpha.md",
+ });
+ expect(base.items[0]).not.toHaveProperty("properties");
+ expect(base.items[0]).not.toHaveProperty("excerpt");
+
+ const withoutMetadata = await executeAssetQuery({
+ catalog,
+ documents,
+ query: {
+ where: { all: [] },
+ sort: [],
+ limit: 1,
+ offset: 0,
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["name"], ["properties", "title"]],
+ },
+ content: { mode: "none" },
+ },
+ });
+ expect(withoutMetadata.items[0]).toEqual({
+ id: "alpha",
+ name: "alpha.md",
+ properties: { title: "Alpha" },
+ });
+ });
+
+ test("omits empty properties from query results", async () => {
+ const empty = document({ id: "empty", properties: {} });
+ const withExcerpt = document({
+ id: "excerpt",
+ properties: {},
+ excerpt: "Excerpt",
+ });
+ const result = await executeAssetQuery({
+ catalog,
+ documents: [empty, withExcerpt],
+ runtimeAssets: {
+ empty: { url: "/assets/empty" },
+ excerpt: { url: "/assets/excerpt" },
+ },
+ query: {
+ where: { all: [] },
+ sort: [],
+ limit: 1,
+ offset: 0,
+ output: { mode: "all", includeMetadata: false },
+ content: { mode: "none" },
+ },
+ });
+
+ expect(result).toMatchObject({
+ items: [{ id: "excerpt", excerpt: "Excerpt" }],
+ totalCount: 1,
+ hasMore: false,
+ });
+ });
+
+ test("retains files when file content is the only available output", async () => {
+ const bytes = new TextEncoder().encode("Body");
+ const result = await executeAssetQuery({
+ catalog,
+ documents: [
+ { ...document({ id: "content", properties: {} }), size: bytes.length },
+ ],
+ runtimeAssets: { content: { url: "/assets/content" } },
+ query: {
+ where: { all: [] },
+ sort: [],
+ limit: 1,
+ offset: 0,
+ output: { mode: "all", includeMetadata: false },
+ content: { mode: "markdown-body" },
+ },
+ read: async () => ({
+ data: {
+ async *[Symbol.asyncIterator]() {
+ yield bytes;
+ },
+ },
+ contentLength: bytes.length,
+ }),
+ });
+
+ expect(result).toMatchObject({
+ items: [{ id: "content", content: { encoding: "utf-8", text: "Body" } }],
+ totalCount: 1,
+ });
+ });
+
+ test("rejects a query without any output", async () => {
+ await expect(
+ executeAssetQuery({
+ catalog,
+ documents,
+ query: {
+ where: { all: [] },
+ sort: [],
+ limit: 1,
+ offset: 0,
+ output: { mode: "base", includeMetadata: false },
+ content: { mode: "none" },
+ },
+ })
+ ).rejects.toThrow("Select at least one asset query output");
+ });
+
+ test("supports lexical date ranges and missing-field checks", async () => {
+ const result = await executeAssetQuery({
+ catalog,
+ documents,
+ runtimeAssets,
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "publishedAt"],
+ operator: "gte",
+ value: "2025-01-01",
+ },
+ {
+ field: ["properties", "draft"],
+ operator: "exists",
+ value: false,
+ },
+ ],
+ },
+ sort: [],
+ limit: 100,
+ offset: 0,
+ content: { mode: "none" },
+ },
+ });
+
+ expect(result.items.map(({ id }) => id)).toEqual(["gamma"]);
+ });
+
+ test("requires target-specific URL data when URL is selected", async () => {
+ await expect(
+ executeAssetQuery({
+ catalog,
+ documents: [documents[0]],
+ query: { content: { mode: "none" } },
+ })
+ ).rejects.toThrow("Asset URL is unavailable for alpha");
+ });
+});
diff --git a/packages/content-engine/src/structured-query.ts b/packages/content-engine/src/structured-query.ts
new file mode 100644
index 0000000000..6c0348c1eb
--- /dev/null
+++ b/packages/content-engine/src/structured-query.ts
@@ -0,0 +1,499 @@
+import {
+ evaluateQueryWhere,
+ getQueryConditions,
+} from "@webstudio-is/query-builder/runtime";
+import {
+ assetQuery,
+ isAssetQueryMetadataField,
+ isAssetQueryRuntimeField,
+ assetQueryStandardFieldTypes,
+ getAssetQueryOperatorsForFieldTypes,
+ type ContentDatabaseDocument,
+ type AssetQuery,
+ type AssetObservedFieldType,
+ type AssetQueryInput,
+ type AssetQueryFieldPath,
+ type AssetQueryFilter,
+ type AssetQueryResult,
+ type AssetQueryWhere,
+ type AssetResourceOutputSelection,
+ type BuilderAssetFieldCatalog,
+} from "./schema";
+import { contentEngineLimits } from "./limits";
+import {
+ compareStrings,
+ serializeJsonDeterministically,
+} from "./canonical-json";
+import {
+ hydrateAssetResourceResult,
+ type AssetResourceContentReader,
+} from "./hydration";
+import { appendAssetFieldPath } from "./canonical";
+import { selectAssetDocumentFields, selectAssetProperties } from "./projection";
+import { getUtf8ByteLength } from "./byte-stream";
+import type { MarkdownAssetReferences } from "./markdown-references";
+
+export type AssetRuntimeData = {
+ url: string;
+ width?: number;
+ height?: number;
+};
+
+export class AssetQueryExecutionError extends Error {
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options);
+ this.name = "AssetQueryExecutionError";
+ }
+}
+
+export class AssetIndexRevisionError extends Error {
+ constructor() {
+ super("The requested asset index revision is stale");
+ this.name = "AssetIndexRevisionError";
+ }
+}
+
+const getCatalogPath = (path: AssetQueryFieldPath) => {
+ if (path[0] !== "properties") {
+ return path[0];
+ }
+ let catalogPath = "properties";
+ for (const segment of path.slice(1)) {
+ catalogPath = appendAssetFieldPath(catalogPath, segment);
+ }
+ return catalogPath;
+};
+
+const isFilterOperatorCompatible = ({
+ filter,
+ fieldTypes,
+}: {
+ filter: AssetQueryFilter;
+ fieldTypes: readonly AssetObservedFieldType[];
+}) => getAssetQueryOperatorsForFieldTypes(fieldTypes).includes(filter.operator);
+
+const getCatalogField = (catalog: BuilderAssetFieldCatalog, path: string) =>
+ Object.hasOwn(catalog.fields, path) ? catalog.fields[path] : undefined;
+
+export const validateAssetQueryAgainstCatalog = ({
+ query: input,
+ catalog,
+}: {
+ query: AssetQueryInput;
+ catalog: BuilderAssetFieldCatalog;
+}) => {
+ const query = assetQuery.parse(input);
+ const referencedFieldPaths = new Map<string, AssetQueryFieldPath>();
+ const warnings: string[] = [];
+ for (const filter of getQueryConditions(query.where)) {
+ const catalogPath = getCatalogPath(filter.field);
+ referencedFieldPaths.set(catalogPath, filter.field);
+ if (filter.field[0] === "properties") {
+ const field = getCatalogField(catalog, catalogPath);
+ // Dynamic fields are schemaless. The catalog describes the currently
+ // observed documents for authoring assistance, but deleting the last
+ // matching file must not invalidate an otherwise valid saved query.
+ if (field === undefined) {
+ warnings.push(`Asset field ${catalogPath} is not currently observed`);
+ } else if (
+ isFilterOperatorCompatible({ filter, fieldTypes: field.types }) ===
+ false
+ ) {
+ warnings.push(
+ `Operator ${filter.operator} is not compatible with the currently observed types of ${catalogPath}`
+ );
+ }
+ } else {
+ if (
+ isFilterOperatorCompatible({
+ filter,
+ fieldTypes:
+ assetQueryStandardFieldTypes[
+ filter.field[0] as keyof typeof assetQueryStandardFieldTypes
+ ],
+ }) === false
+ ) {
+ throw new AssetQueryExecutionError(
+ `Operator ${filter.operator} is incompatible with ${catalogPath}`
+ );
+ }
+ }
+ }
+ for (const order of query.sort) {
+ const catalogPath = getCatalogPath(order.field);
+ referencedFieldPaths.set(catalogPath, order.field);
+ // Sorting is defined for every JSON value by compareSortValues below.
+ // Do not let an absent field or an unrelated mixed-type document make a
+ // previously valid schemaless query fail at runtime.
+ if (order.field[0] === "properties") {
+ const field = getCatalogField(catalog, catalogPath);
+ if (field === undefined) {
+ warnings.push(`Asset field ${catalogPath} is not currently observed`);
+ } else if (
+ field.types.some((type) => type === "object" || type === "array")
+ ) {
+ warnings.push(
+ `Asset field ${catalogPath} currently includes structured values that use deterministic JSON sort order`
+ );
+ }
+ }
+ }
+ return {
+ query,
+ referencedFieldPaths: [...referencedFieldPaths.values()],
+ warnings: [...new Set(warnings)],
+ };
+};
+
+export const getAssetQueryFieldValue = (
+ document: ContentDatabaseDocument,
+ path: AssetQueryFieldPath,
+ runtimeAsset?: AssetRuntimeData
+) => {
+ let value: unknown =
+ path[0] === "id"
+ ? document._id
+ : isAssetQueryRuntimeField(path[0])
+ ? runtimeAsset?.[path[0]]
+ : (document as Readonly<Record<string, unknown>>)[path[0]];
+ for (const segment of path.slice(1)) {
+ if (
+ typeof value !== "object" ||
+ value === null ||
+ Object.hasOwn(value, segment) === false
+ ) {
+ return;
+ }
+ value = (value as Readonly<Record<string, unknown>>)[segment];
+ }
+ return value;
+};
+
+const equalJson = (left: unknown, right: unknown) => {
+ if (left === undefined || right === undefined) {
+ return left === right;
+ }
+ return (
+ serializeJsonDeterministically(left) ===
+ serializeJsonDeterministically(right)
+ );
+};
+
+const isEmpty = (value: unknown) => {
+ if (typeof value === "string" || Array.isArray(value)) {
+ return value.length === 0;
+ }
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ Object.keys(value).length === 0
+ );
+};
+
+const compareFilterValues = (left: unknown, right: unknown) => {
+ if (typeof left === "number" && typeof right === "number") {
+ return left - right;
+ }
+ if (typeof left === "string" && typeof right === "string") {
+ return compareStrings(left, right);
+ }
+};
+
+export const matchesAssetQueryFilter = (
+ document: ContentDatabaseDocument,
+ filter: AssetQueryFilter,
+ runtimeAsset?: AssetRuntimeData
+) => {
+ const value = getAssetQueryFieldValue(document, filter.field, runtimeAsset);
+ if (filter.operator === "exists") {
+ return (value !== undefined && value !== null) === filter.value;
+ }
+ if (filter.operator === "isEmpty") {
+ return isEmpty(value) === filter.value;
+ }
+ if (filter.operator === "eq") {
+ return equalJson(value, filter.value);
+ }
+ if (filter.operator === "ne") {
+ return equalJson(value, filter.value) === false;
+ }
+ if (filter.operator === "in") {
+ return filter.value.some((candidate) => equalJson(value, candidate));
+ }
+ if (filter.operator === "contains") {
+ if (typeof value === "string" && typeof filter.value === "string") {
+ return value.includes(filter.value);
+ }
+ return (
+ Array.isArray(value) &&
+ value.some((candidate) => equalJson(candidate, filter.value))
+ );
+ }
+ if (filter.operator === "startsWith") {
+ return (
+ typeof value === "string" &&
+ typeof filter.value === "string" &&
+ value.startsWith(filter.value)
+ );
+ }
+ if (filter.operator === "endsWith") {
+ return (
+ typeof value === "string" &&
+ typeof filter.value === "string" &&
+ value.endsWith(filter.value)
+ );
+ }
+ const compared = compareFilterValues(value, filter.value);
+ if (compared === undefined) {
+ return false;
+ }
+ if (filter.operator === "gt") {
+ return compared > 0;
+ }
+ if (filter.operator === "gte") {
+ return compared >= 0;
+ }
+ if (filter.operator === "lt") {
+ return compared < 0;
+ }
+ return compared <= 0;
+};
+
+const matchesAssetQueryWhere = (
+ document: ContentDatabaseDocument,
+ where: AssetQueryWhere,
+ runtimeAsset?: AssetRuntimeData
+): boolean =>
+ evaluateQueryWhere(where, (filter) =>
+ matchesAssetQueryFilter(document, filter, runtimeAsset)
+ ) === true;
+
+const compareAssetQuerySortValues = (left: unknown, right: unknown) => {
+ const leftMissing = left === undefined || left === null;
+ const rightMissing = right === undefined || right === null;
+ if (leftMissing || rightMissing) {
+ return leftMissing === rightMissing ? 0 : leftMissing ? 1 : -1;
+ }
+ if (typeof left === "number" && typeof right === "number") {
+ return left - right;
+ }
+ if (
+ (typeof left === "string" || typeof left === "boolean") &&
+ (typeof right === "string" || typeof right === "boolean")
+ ) {
+ return compareStrings(String(left), String(right));
+ }
+ return compareStrings(
+ serializeJsonDeterministically(left),
+ serializeJsonDeterministically(right)
+ );
+};
+
+const compareAssetQueryDocumentsWithRuntime = ({
+ left,
+ right,
+ sort,
+ runtimeAssets,
+}: {
+ left: ContentDatabaseDocument;
+ right: ContentDatabaseDocument;
+ sort: AssetQuery["sort"];
+ runtimeAssets?: Readonly<Record<string, AssetRuntimeData>>;
+}) => {
+ for (const order of sort) {
+ const compared = compareAssetQuerySortValues(
+ getAssetQueryFieldValue(left, order.field, runtimeAssets?.[left._id]),
+ getAssetQueryFieldValue(right, order.field, runtimeAssets?.[right._id])
+ );
+ if (compared !== 0) {
+ return order.direction === "asc" ? compared : -compared;
+ }
+ }
+ return compareStrings(left._id, right._id);
+};
+
+export const compareAssetQueryDocuments = (
+ left: ContentDatabaseDocument,
+ right: ContentDatabaseDocument,
+ sort: AssetQuery["sort"]
+) => compareAssetQueryDocumentsWithRuntime({ left, right, sort });
+
+const selectProperties = (
+ document: ContentDatabaseDocument,
+ output: AssetResourceOutputSelection
+) => {
+ if (document.properties === undefined) {
+ return;
+ }
+ if (output.mode === "all") {
+ return Object.keys(document.properties).length === 0
+ ? undefined
+ : document.properties;
+ }
+ if (
+ output.mode !== "fields" ||
+ output.fields.some((field) => field[0] === "properties") === false
+ ) {
+ return;
+ }
+ const properties = selectAssetProperties({
+ properties: document.properties,
+ fields: output.fields,
+ });
+ return Object.keys(properties).length === 0 ? undefined : properties;
+};
+
+const includesOutputField = (
+ output: AssetResourceOutputSelection,
+ field: string
+) =>
+ (output.includeMetadata && isAssetQueryMetadataField(field)) ||
+ (output.mode === "fields" &&
+ output.fields.some((path) => path.length === 1 && path[0] === field));
+
+const includesExcerpt = (output: AssetResourceOutputSelection) =>
+ output.mode === "all" ||
+ (output.mode === "fields" &&
+ output.fields.some(
+ (field) => field.length === 1 && field[0] === "excerpt"
+ ));
+
+const toQueryItem = (
+ document: ContentDatabaseDocument,
+ output: AssetResourceOutputSelection,
+ runtimeAsset?: AssetRuntimeData
+) => {
+ if (includesOutputField(output, "url") && runtimeAsset === undefined) {
+ throw new Error(`Asset URL is unavailable for ${document._id}`);
+ }
+ const properties = selectProperties(document, output);
+ const hasDimensions =
+ runtimeAsset?.width !== undefined && runtimeAsset.height !== undefined;
+ return {
+ ...(runtimeAsset !== undefined && includesOutputField(output, "url")
+ ? { url: runtimeAsset.url }
+ : {}),
+ ...(hasDimensions && includesOutputField(output, "width")
+ ? { width: runtimeAsset.width }
+ : {}),
+ ...(hasDimensions && includesOutputField(output, "height")
+ ? { height: runtimeAsset.height }
+ : {}),
+ ...selectAssetDocumentFields({
+ document,
+ includes: (field) => includesOutputField(output, field),
+ }),
+ ...(properties === undefined ? {} : { properties }),
+ ...(document.excerpt === undefined || includesExcerpt(output) === false
+ ? {}
+ : { excerpt: document.excerpt }),
+ ...(document.metadataError === undefined || output.includeMetadata === false
+ ? {}
+ : { metadataError: document.metadataError }),
+ };
+};
+
+const assertResultSize = (result: AssetQueryResult) => {
+ if (
+ getUtf8ByteLength(serializeJsonDeterministically(result)) >
+ contentEngineLimits.resultBytes
+ ) {
+ throw new AssetQueryExecutionError(
+ "Asset query result exceeds the byte limit"
+ );
+ }
+};
+
+export const executeAssetQuery = async ({
+ query: input,
+ catalog,
+ documents,
+ read,
+ runtimeAssets,
+ assetReferences,
+}: {
+ query: AssetQueryInput;
+ catalog: BuilderAssetFieldCatalog;
+ documents: readonly ContentDatabaseDocument[];
+ read?: AssetResourceContentReader;
+ runtimeAssets?: Readonly<Record<string, AssetRuntimeData>>;
+ assetReferences?: MarkdownAssetReferences;
+}): Promise<AssetQueryResult> => {
+ const { query } = validateAssetQueryAgainstCatalog({ query: input, catalog });
+ if (documents.length > contentEngineLimits.candidateDocuments) {
+ throw new AssetQueryExecutionError(
+ "Asset query document limit was exceeded"
+ );
+ }
+ const matched = documents.flatMap((document) => {
+ const runtimeAsset = runtimeAssets?.[document._id];
+ if (matchesAssetQueryWhere(document, query.where, runtimeAsset) === false) {
+ return [];
+ }
+ const item = toQueryItem(document, query.output, runtimeAsset);
+ if (
+ query.content.mode === "none" &&
+ Object.keys(item).length === 0 &&
+ includesOutputField(query.output, "id") === false
+ ) {
+ return [];
+ }
+ return [{ document, item: { id: document._id, ...item } }];
+ });
+ const sorted = [...matched].sort((left, right) =>
+ compareAssetQueryDocumentsWithRuntime({
+ left: left.document,
+ right: right.document,
+ sort: query.sort,
+ runtimeAssets,
+ })
+ );
+ const selected = sorted.slice(query.offset, query.offset + query.limit);
+ const selectedDocuments = selected.map(({ document }) => document);
+ let items = selected.map(({ item }) => item);
+ if (query.content.mode !== "none") {
+ const contentOptions = query.content;
+ if (read === undefined) {
+ throw new AssetQueryExecutionError("Asset content reader is unavailable");
+ }
+ const hydrated = await hydrateAssetResourceResult({
+ result: selectedDocuments,
+ documents: selectedDocuments,
+ options: contentOptions,
+ read,
+ assetReferences,
+ assetUrls:
+ assetReferences === undefined
+ ? undefined
+ : Object.fromEntries(
+ Object.entries(runtimeAssets ?? {}).map(([id, asset]) => [
+ id,
+ asset.url,
+ ])
+ ),
+ });
+ items = selectedDocuments.map((document, index) => {
+ const content = hydrated.content[document._id];
+ if (content === undefined) {
+ throw new AssetQueryExecutionError(
+ "Selected asset content could not be read"
+ );
+ }
+ return {
+ ...items[index],
+ content: {
+ encoding: content.encoding,
+ text: content.text,
+ ...(content.range === undefined ? {} : { range: content.range }),
+ },
+ };
+ });
+ }
+ const result = {
+ items,
+ totalCount: matched.length,
+ hasMore: query.offset + selected.length < matched.length,
+ } satisfies AssetQueryResult;
+ assertResultSize(result);
+ return result;
+};
diff --git a/packages/content-engine/tsconfig.dts.json b/packages/content-engine/tsconfig.dts.json
new file mode 100644
index 0000000000..8b6d30c341
--- /dev/null
+++ b/packages/content-engine/tsconfig.dts.json
@@ -0,0 +1,9 @@
+{
+ "extends": "./tsconfig.json",
+ "include": ["src"],
+ "exclude": ["**/*.test.ts"],
+ "compilerOptions": {
+ "declarationDir": "lib/types",
+ "rootDir": "./src"
+ }
+}
diff --git a/packages/content-engine/tsconfig.json b/packages/content-engine/tsconfig.json
new file mode 100644
index 0000000000..d2e5040f8f
--- /dev/null
+++ b/packages/content-engine/tsconfig.json
@@ -0,0 +1,3 @@
+{
+ "extends": "@webstudio-is/tsconfig/base.json"
+}
diff --git a/packages/design-system/src/components/floating-panel.tsx b/packages/design-system/src/components/floating-panel.tsx
index 5e3c980d5a..98c462e877 100644
--- a/packages/design-system/src/components/floating-panel.tsx
+++ b/packages/design-system/src/components/floating-panel.tsx
@@ -25,11 +25,14 @@ const computeFloatingPosition = (
floating: HTMLElement,
container: HTMLElement,
placement: "left-start" | "right-start" | "bottom-within",
+ anchor: "container" | "trigger",
offsetOptions: OffsetOptions
): { x: number; y: number } => {
const triggerRect = trigger.getBoundingClientRect();
const floatingRect = floating.getBoundingClientRect();
const containerRect = container.getBoundingClientRect();
+ const horizontalAnchorRect =
+ anchor === "trigger" ? triggerRect : containerRect;
const mainAxis =
typeof offsetOptions === "number"
@@ -46,15 +49,13 @@ const computeFloatingPosition = (
let y = 0;
if (placement === "left-start") {
- // Position to the left of the container, aligned with the top of trigger
- x = containerRect.left - floatingRect.width + mainAxis;
+ x = horizontalAnchorRect.left - floatingRect.width + mainAxis;
// Align panel top with trigger top
y = triggerRect.top + (alignmentAxis ?? 0);
// Apply crossAxis offset (moves vertically)
y += crossAxis;
} else if (placement === "right-start") {
- // Position to the right of the container, aligned with the top of trigger
- x = containerRect.right + mainAxis;
+ x = horizontalAnchorRect.right + mainAxis;
// Align panel top with trigger top, using trigger's relative position within container
y = triggerRect.top + (alignmentAxis ?? 0);
// Apply crossAxis offset (moves vertically)
@@ -117,9 +118,11 @@ type FloatingPanelProps = {
width?: number;
height?: number;
// - bottom-within - below the trigger button, within container bounds
- // - left-start - on the left side relative to the container, aligned with the top of the trigger button
+ // - left-start - on the left side of the horizontal anchor, aligned with the top of the trigger button
// - center - center of the screen
placement?: "left-start" | "right-start" | "center" | "bottom-within";
+ /** Horizontal reference for left/right placement. Vertical placement always follows the trigger. */
+ anchor?: "container" | "trigger";
offset?: OffsetOptions;
open?: boolean;
onOpenChange?: (isOpen: boolean) => void;
@@ -144,6 +147,7 @@ export const FloatingPanel = ({
width,
height,
placement = "left-start",
+ anchor = "container",
offset: offsetProp = defaultOffset,
open: openProp,
onOpenChange,
@@ -229,6 +233,7 @@ export const FloatingPanel = ({
contentElement,
containerRef.current,
placement,
+ anchor,
offsetProp
);
currentPositionRef.current = { x, y };
@@ -259,6 +264,7 @@ export const FloatingPanel = ({
contentElement,
containerRef.current,
placement,
+ anchor,
offsetProp
);
currentPositionRef.current = { x, y };
@@ -285,7 +291,15 @@ export const FloatingPanel = ({
return () => {
resizeObserver.disconnect();
};
- }, [contentElement, containerRef, placement, offsetProp, open, height]);
+ }, [
+ contentElement,
+ containerRef,
+ placement,
+ anchor,
+ offsetProp,
+ open,
+ height,
+ ]);
return (
<Dialog
diff --git a/packages/design-system/src/components/section-title.tsx b/packages/design-system/src/components/section-title.tsx
index ba9bfc9dbd..3cf4b0fb32 100644
--- a/packages/design-system/src/components/section-title.tsx
+++ b/packages/design-system/src/components/section-title.tsx
@@ -60,7 +60,7 @@ const titleButtonStyle = css(titleButtonLayoutStyle, {
const suffixSlotStyle = css({
position: "absolute",
- right: theme.spacing[4],
+ right: theme.spacing[5],
top: theme.spacing[4],
});
diff --git a/packages/design-system/src/components/split-view.test.tsx b/packages/design-system/src/components/split-view.test.tsx
new file mode 100644
index 0000000000..2174567f1f
--- /dev/null
+++ b/packages/design-system/src/components/split-view.test.tsx
@@ -0,0 +1,180 @@
+import { createRoot, type Root } from "react-dom/client";
+import { act } from "react-dom/test-utils";
+import { afterEach, beforeEach, expect, test } from "vitest";
+import { SplitView } from "./split-view";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+let root: Root | undefined;
+const originalResizeObserver = globalThis.ResizeObserver;
+const resizeObservers = new Set<TestResizeObserver>();
+
+class TestResizeObserver implements ResizeObserver {
+ private callback: ResizeObserverCallback;
+
+ constructor(callback: ResizeObserverCallback) {
+ this.callback = callback;
+ resizeObservers.add(this);
+ }
+
+ observe() {}
+ unobserve() {}
+ disconnect() {
+ resizeObservers.delete(this);
+ }
+ notify() {
+ this.callback([], this);
+ }
+}
+
+beforeEach(() => {
+ globalThis.ResizeObserver = TestResizeObserver;
+});
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = undefined;
+ resizeObservers.clear();
+ globalThis.ResizeObserver = originalResizeObserver;
+ document.body.innerHTML = "";
+});
+
+const renderSplitView = ({
+ defaultSize,
+}: {
+ defaultSize?: { value: number; unit: "%" | "px" };
+} = {}) => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ act(() => {
+ root?.render(
+ <SplitView
+ start="Start"
+ end="End"
+ separatorLabel="Resize panels"
+ defaultSize={defaultSize}
+ />
+ );
+ });
+ const separator = container.querySelector('[role="separator"]');
+ if (!(separator instanceof HTMLElement)) {
+ throw new Error("Expected split view separator");
+ }
+ const splitView = separator.parentElement;
+ if (splitView === null) {
+ throw new Error("Expected split view container");
+ }
+ let width = 1000;
+ splitView.getBoundingClientRect = () => ({
+ x: 0,
+ y: 0,
+ width,
+ height: 500,
+ top: 0,
+ right: width,
+ bottom: 500,
+ left: 0,
+ toJSON: () => ({}),
+ });
+ const resize = (nextWidth: number) => {
+ width = nextWidth;
+ act(() => {
+ for (const observer of resizeObservers) {
+ observer.notify();
+ }
+ });
+ };
+ return { separator, splitView, resize };
+};
+
+test("resizes panels with the keyboard", () => {
+ const { separator } = renderSplitView();
+
+ act(() => {
+ separator.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true })
+ );
+ });
+
+ expect(separator.getAttribute("aria-valuenow")).toBe("55");
+});
+
+test("keeps keyboard resizing within the configured ratios", () => {
+ const { separator } = renderSplitView();
+
+ act(() => {
+ for (let index = 0; index < 10; index += 1) {
+ separator.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true })
+ );
+ }
+ });
+
+ expect(separator.getAttribute("aria-valuenow")).toBe("80");
+});
+
+test("preserves a proportional split when the container resizes", () => {
+ const { splitView } = renderSplitView({
+ defaultSize: { value: 40, unit: "%" },
+ });
+
+ expect(splitView.style.gridTemplateColumns).toBe(
+ "minmax(0, 0.4fr) 1px minmax(0, 0.6fr)"
+ );
+});
+
+test("preserves a fixed start pane when the container resizes", () => {
+ const { separator, splitView } = renderSplitView({
+ defaultSize: { value: 320, unit: "px" },
+ });
+
+ expect(splitView.style.gridTemplateColumns).toBe(
+ "minmax(0, 320px) 1px minmax(0, 1fr)"
+ );
+
+ act(() => {
+ separator.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true })
+ );
+ });
+
+ expect(separator.getAttribute("aria-valuenow")).toBe("370");
+ expect(splitView.style.gridTemplateColumns).toContain("369.95px");
+});
+
+test("clamps a fixed split on container resize and restores its desired size", () => {
+ const { separator, splitView, resize } = renderSplitView({
+ defaultSize: { value: 320, unit: "px" },
+ });
+
+ resize(400);
+ expect(splitView.style.gridTemplateColumns).toBe(
+ "minmax(0, 239px) 1px minmax(0, 1fr)"
+ );
+ expect(separator.getAttribute("aria-valuemin")).toBe("160");
+ expect(separator.getAttribute("aria-valuemax")).toBe("239");
+
+ resize(1000);
+ expect(splitView.style.gridTemplateColumns).toBe(
+ "minmax(0, 320px) 1px minmax(0, 1fr)"
+ );
+});
+
+test("clamps a percentage split on container resize and restores its ratio", () => {
+ const { splitView, resize } = renderSplitView({
+ defaultSize: { value: 40, unit: "%" },
+ });
+
+ resize(400);
+ expect(splitView.style.gridTemplateColumns).toBe(
+ "minmax(0, 160px) 1px minmax(0, 1fr)"
+ );
+
+ resize(1000);
+ expect(splitView.style.gridTemplateColumns).toBe(
+ "minmax(0, 399.6px) 1px minmax(0, 1fr)"
+ );
+});
diff --git a/packages/design-system/src/components/split-view.tsx b/packages/design-system/src/components/split-view.tsx
new file mode 100644
index 0000000000..84bfee5f6e
--- /dev/null
+++ b/packages/design-system/src/components/split-view.tsx
@@ -0,0 +1,279 @@
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
+import { css, theme } from "../stitches.config";
+import { Box } from "./box";
+import { numericScrubControl } from "./primitives/numeric-gesture-control";
+
+const separatorWidth = 1;
+
+const separatorStyle = css({
+ position: "relative",
+ width: separatorWidth,
+ height: "100%",
+ cursor: "col-resize",
+ touchAction: "none",
+ outline: "none",
+ background: theme.colors.borderMain,
+ "&::before": {
+ position: "absolute",
+ content: '""',
+ insetBlock: 0,
+ left: -2,
+ right: -2,
+ },
+ "&:hover, &:focus-visible": {
+ background: theme.colors.backgroundPrimaryLight,
+ boxShadow: `-1px 0 ${theme.colors.backgroundPrimaryLight}, 1px 0 ${theme.colors.backgroundPrimaryLight}`,
+ },
+});
+
+const paneStyle = css({
+ display: "grid",
+ gridTemplateRows: "minmax(0, 1fr)",
+ height: "100%",
+ minHeight: 0,
+ overflow: "hidden",
+});
+
+const getPanelSizeBounds = ({
+ containerSize,
+ minimumStartSize,
+ minimumEndSize,
+ minimumRatio,
+ maximumRatio,
+}: {
+ containerSize: number;
+ minimumStartSize: number;
+ minimumEndSize: number;
+ minimumRatio: number;
+ maximumRatio: number;
+}) => {
+ const availableSize = Math.max(0, containerSize - separatorWidth);
+ const startMinimum = Math.max(
+ availableSize * minimumRatio,
+ Math.min(Math.max(0, minimumStartSize), availableSize / 2)
+ );
+ const endMinimum = Math.max(
+ availableSize * (1 - maximumRatio),
+ Math.min(Math.max(0, minimumEndSize), availableSize / 2)
+ );
+ return { minimum: startMinimum, maximum: availableSize - endMinimum };
+};
+
+const clampPanelSize = ({
+ size,
+ ...options
+}: Parameters<typeof getPanelSizeBounds>[0] & { size: number }) => {
+ const { minimum, maximum } = getPanelSizeBounds(options);
+ return Math.min(maximum, Math.max(minimum, size));
+};
+
+export const SplitView = ({
+ start,
+ end,
+ separatorLabel,
+ defaultSize = { value: 50, unit: "%" },
+ minimumStartSize = 160,
+ minimumEndSize = 160,
+ minimumRatio = 0.2,
+ maximumRatio = 0.8,
+}: {
+ start: ReactNode;
+ end?: ReactNode;
+ separatorLabel: string;
+ defaultSize?: { value: number; unit: "%" | "px" };
+ minimumStartSize?: number;
+ minimumEndSize?: number;
+ minimumRatio?: number;
+ maximumRatio?: number;
+}) => {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const separatorRef = useRef<HTMLDivElement>(null);
+ const normalizedMinimumRatio = Math.min(1, Math.max(0, minimumRatio));
+ const normalizedMaximumRatio = Math.min(
+ 1,
+ Math.max(normalizedMinimumRatio, maximumRatio)
+ );
+ const sizeUnitRef = useRef(defaultSize.unit);
+ const initialSize =
+ defaultSize.unit === "%"
+ ? Math.min(
+ normalizedMaximumRatio * 100,
+ Math.max(normalizedMinimumRatio * 100, defaultSize.value)
+ )
+ : Math.max(0, defaultSize.value);
+ const sizeRef = useRef(initialSize);
+ const [size, setSize] = useState(initialSize);
+ const [containerSize, setContainerSize] = useState(0);
+ const resizable = end !== undefined;
+
+ const getStartSize = useCallback((containerSize: number) => {
+ if (sizeUnitRef.current === "px") {
+ return sizeRef.current;
+ }
+ return (
+ (Math.max(0, containerSize - separatorWidth) * sizeRef.current) / 100
+ );
+ }, []);
+
+ const updateSize = useCallback(
+ (size: number) => {
+ const containerSize =
+ containerRef.current?.getBoundingClientRect().width ?? 0;
+ if (containerSize === 0) {
+ return;
+ }
+ const nextSize = clampPanelSize({
+ size,
+ containerSize,
+ minimumStartSize,
+ minimumEndSize,
+ minimumRatio: normalizedMinimumRatio,
+ maximumRatio: normalizedMaximumRatio,
+ });
+ sizeRef.current =
+ sizeUnitRef.current === "px"
+ ? nextSize
+ : (nextSize / Math.max(1, containerSize - separatorWidth)) * 100;
+ setSize(sizeRef.current);
+ },
+ [
+ minimumEndSize,
+ minimumStartSize,
+ normalizedMaximumRatio,
+ normalizedMinimumRatio,
+ ]
+ );
+
+ useEffect(() => {
+ const container = containerRef.current;
+ if (container === null || resizable === false) {
+ return;
+ }
+ const updateContainerSize = () => {
+ setContainerSize(container.getBoundingClientRect().width);
+ };
+ updateContainerSize();
+ const observer = new ResizeObserver(updateContainerSize);
+ observer.observe(container);
+ return () => observer.disconnect();
+ }, [resizable]);
+
+ useEffect(() => {
+ const separator = separatorRef.current;
+ if (separator === null) {
+ return;
+ }
+
+ return numericScrubControl(separator, {
+ getInitialValue: () => {
+ const width = containerRef.current?.getBoundingClientRect().width ?? 0;
+ return getStartSize(width);
+ },
+ getValue: (state, movement) => state.value + movement,
+ onValueInput: (event) => updateSize(event.value),
+ });
+ }, [getStartSize, resizable, updateSize]);
+
+ if (end === undefined) {
+ return <Box className={paneStyle()}>{start}</Box>;
+ }
+
+ const renderedStartSize =
+ containerSize === 0
+ ? undefined
+ : clampPanelSize({
+ size: getStartSize(containerSize),
+ containerSize,
+ minimumStartSize,
+ minimumEndSize,
+ minimumRatio: normalizedMinimumRatio,
+ maximumRatio: normalizedMaximumRatio,
+ });
+ const renderedPercentage =
+ renderedStartSize === undefined
+ ? size
+ : (renderedStartSize / Math.max(1, containerSize - separatorWidth)) * 100;
+ const renderedBounds =
+ containerSize === 0
+ ? undefined
+ : getPanelSizeBounds({
+ containerSize,
+ minimumStartSize,
+ minimumEndSize,
+ minimumRatio: normalizedMinimumRatio,
+ maximumRatio: normalizedMaximumRatio,
+ });
+ const toRenderedValue = (value: number) =>
+ sizeUnitRef.current === "px"
+ ? value
+ : (value / Math.max(1, containerSize - separatorWidth)) * 100;
+
+ return (
+ <Box
+ ref={containerRef}
+ css={{
+ display: "grid",
+ height: "100%",
+ minWidth: 0,
+ minHeight: 0,
+ }}
+ style={{
+ gridTemplateColumns:
+ renderedStartSize !== undefined
+ ? `minmax(0, ${renderedStartSize}px) ${separatorWidth}px minmax(0, 1fr)`
+ : sizeUnitRef.current === "px"
+ ? `minmax(0, ${size}px) ${separatorWidth}px minmax(0, 1fr)`
+ : `minmax(0, ${size / 100}fr) ${separatorWidth}px minmax(0, ${1 - size / 100}fr)`,
+ }}
+ >
+ <Box className={paneStyle()}>{start}</Box>
+ <div
+ ref={separatorRef}
+ className={separatorStyle()}
+ role="separator"
+ aria-label={separatorLabel}
+ aria-orientation="vertical"
+ aria-valuemin={
+ renderedBounds === undefined
+ ? sizeUnitRef.current === "px"
+ ? minimumStartSize
+ : Math.round(normalizedMinimumRatio * 100)
+ : Math.round(toRenderedValue(renderedBounds.minimum))
+ }
+ aria-valuemax={
+ renderedBounds === undefined
+ ? sizeUnitRef.current === "px"
+ ? undefined
+ : Math.round(normalizedMaximumRatio * 100)
+ : Math.round(toRenderedValue(renderedBounds.maximum))
+ }
+ aria-valuenow={Math.round(
+ sizeUnitRef.current === "px"
+ ? (renderedStartSize ?? size)
+ : renderedPercentage
+ )}
+ tabIndex={0}
+ onKeyDown={(event) => {
+ const width =
+ containerRef.current?.getBoundingClientRect().width ?? 0;
+ const step = (width - separatorWidth) * 0.05;
+ if (event.key === "ArrowLeft") {
+ event.preventDefault();
+ updateSize(getStartSize(width) - step);
+ }
+ if (event.key === "ArrowRight") {
+ event.preventDefault();
+ updateSize(getStartSize(width) + step);
+ }
+ }}
+ />
+ <Box className={paneStyle()}>{end}</Box>
+ </Box>
+ );
+};
diff --git a/packages/design-system/src/index.ts b/packages/design-system/src/index.ts
index b9293bbaa2..1ab817af7f 100644
--- a/packages/design-system/src/index.ts
+++ b/packages/design-system/src/index.ts
@@ -54,6 +54,7 @@ export * from "./components/component-card";
export * from "./components/input-field";
export * from "./components/nested-input-button";
export * from "./components/panel-tabs";
+export * from "./components/split-view";
export * from "./components/link";
export * from "./components/panel-banner";
export * from "./components/focus-ring";
diff --git a/packages/domain/src/project-domain-api.server.test.ts b/packages/domain/src/project-domain-api.server.test.ts
index 5c6b86e902..9a266797ee 100644
--- a/packages/domain/src/project-domain-api.server.test.ts
+++ b/packages/domain/src/project-domain-api.server.test.ts
@@ -387,6 +387,8 @@ test("returns publish job status from deployment record", async () => {
id: "build-prod",
version: 3,
createdAt: "2024-01-03T00:00:00.000Z",
+ updatedAt: "2024-01-03T00:01:00.000Z",
+ publishStatus: "PUBLISHED",
deployment: JSON.stringify({
destination: "saas",
domains: ["example.com"],
@@ -406,10 +408,41 @@ test("returns publish job status from deployment record", async () => {
status: "success",
domains: ["example.com"],
createdAt: "2024-01-03T00:00:00.000Z",
- completedAt: "2024-01-03T00:00:00.000Z",
+ completedAt: "2024-01-03T00:01:00.000Z",
});
});
+test.each([
+ ["PENDING", "pending", undefined],
+ ["FAILED", "failed", "2024-01-03T00:01:00.000Z"],
+] as const)(
+ "maps %s publisher state without claiming success",
+ async (publishStatus, status, completedAt) => {
+ server.use(
+ db.get("Build", () =>
+ json({
+ id: "build-prod",
+ version: 3,
+ createdAt: "2024-01-03T00:00:00.000Z",
+ updatedAt: "2024-01-03T00:01:00.000Z",
+ publishStatus,
+ deployment: JSON.stringify({
+ destination: "saas",
+ domains: ["example.com"],
+ }),
+ })
+ )
+ );
+
+ await expect(
+ getProjectPublishJob(
+ { projectId: "project-1", jobId: "build-prod" },
+ context
+ )
+ ).resolves.toMatchObject({ status, completedAt });
+ }
+);
+
test("returns undefined when publish job is missing", async () => {
server.use(db.get("Build", () => empty({ status: 204 })));
diff --git a/packages/domain/src/project-domain-api.server.ts b/packages/domain/src/project-domain-api.server.ts
index a2ba52fec6..aa19ae1d38 100644
--- a/packages/domain/src/project-domain-api.server.ts
+++ b/packages/domain/src/project-domain-api.server.ts
@@ -128,7 +128,7 @@ export const getProjectPublishJob = async (
) => {
const result = await context.postgrest.client
.from("Build")
- .select("id, version, createdAt, deployment")
+ .select("id, version, createdAt, updatedAt, deployment, publishStatus")
.eq("projectId", input.projectId)
.eq("id", input.jobId)
.maybeSingle();
@@ -142,16 +142,27 @@ export const getProjectPublishJob = async (
}
const deployment = parseDeployment(publishJob.deployment);
+ const status =
+ deployment === undefined
+ ? "removed"
+ : publishJob.publishStatus === "PUBLISHED"
+ ? "success"
+ : publishJob.publishStatus === "FAILED"
+ ? "failed"
+ : "pending";
return {
id: publishJob.id,
version: publishJob.version,
- status: deployment === undefined ? "removed" : "success",
+ status,
domains:
deployment !== undefined && deployment.destination !== "static"
? deployment.domains
: [],
createdAt: publishJob.createdAt,
- completedAt: publishJob.createdAt,
+ completedAt:
+ status === "success" || status === "failed"
+ ? publishJob.updatedAt
+ : undefined,
};
};
diff --git a/packages/expression/package.json b/packages/expression/package.json
new file mode 100644
index 0000000000..e09c483698
--- /dev/null
+++ b/packages/expression/package.json
@@ -0,0 +1,37 @@
+{
+ "name": "@webstudio-is/expression",
+ "version": "0.0.0-webstudio-version",
+ "description": "Framework-independent expression language utilities",
+ "author": "Webstudio <[email protected]>",
+ "homepage": "https://webstudio.is",
+ "license": "AGPL-3.0-or-later",
+ "type": "module",
+ "sideEffects": false,
+ "exports": {
+ ".": {
+ "webstudio": "./src/index.ts",
+ "types": "./lib/types/index.d.ts",
+ "import": "./lib/index.js"
+ }
+ },
+ "files": [
+ "lib/**/*",
+ "!*.test.*"
+ ],
+ "scripts": {
+ "build": "rm -rf lib && esbuild src/index.ts --outdir=lib --bundle --format=esm --packages=external",
+ "dts": "tsc --project tsconfig.dts.json",
+ "test": "vitest run",
+ "test:coverage": "vitest run --coverage",
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "acorn": "^8.14.1",
+ "acorn-walk": "^8.3.4"
+ },
+ "devDependencies": {
+ "@vitest/coverage-v8": "3.1.2",
+ "@webstudio-is/tsconfig": "workspace:*",
+ "vitest": "^3.1.2"
+ }
+}
diff --git a/packages/expression/src/expression.test.ts b/packages/expression/src/expression.test.ts
new file mode 100644
index 0000000000..2529af30ba
--- /dev/null
+++ b/packages/expression/src/expression.test.ts
@@ -0,0 +1,1054 @@
+import { describe, expect, test } from "vitest";
+import { parseExpressionAt } from "acorn";
+import {
+ type Diagnostic,
+ getExpressionValueKind,
+ isLiteralExpression,
+ isValidExpression,
+ lintExpression,
+ transpileExpression,
+ getExpressionIdentifiers,
+ generateObjectExpression,
+ generateJsonExpression,
+ parseJsonExpression,
+ parseExpressionObject,
+ parseArrayExpression,
+ parseStaticMemberPath,
+ parseStringLiteralExpression,
+ allowedArrayMethods,
+ allowedStringMethods,
+} from "./index";
+
+test("validates complete expressions", () => {
+ expect(isValidExpression("post.title ?? 'Untitled'")).toBe(true);
+ expect(isValidExpression("post.title trailing")).toBe(false);
+ expect(isValidExpression("{")).toBe(false);
+});
+
+describe("static member paths", () => {
+ test.each([
+ ["system.params.slug", ["system", "params", "slug"]],
+ ['system.params["slug"]', ["system", "params", "slug"]],
+ ["system?.params?.slug", ["system", "params", "slug"]],
+ ['system?.params?.["slug"]', ["system", "params", "slug"]],
+ ["items[0].title", ["items", "0", "title"]],
+ ["system.params[slug]", undefined],
+ ["system.params.slug ?? fallback", undefined],
+ ["system.params.slug trailing", undefined],
+ ["system.params.", undefined],
+ ])("parses %s", (source, expected) => {
+ expect(parseStaticMemberPath(source)).toEqual(expected);
+ });
+});
+
+describe("string literal expressions", () => {
+ test.each([
+ ['"assets"', "assets"],
+ ["'assets'", undefined],
+ [' "assets"', undefined],
+ ['"assets" trailing', undefined],
+ ["assets", undefined],
+ ])("parses %s", (source, expected) => {
+ expect(parseStringLiteralExpression(source)).toBe(expected);
+ });
+});
+
+describe("lint expression", () => {
+ const error = (from: number, to: number, message: string): Diagnostic => ({
+ from,
+ to,
+ severity: "error",
+ message,
+ });
+
+ const warn = (from: number, to: number, message: string): Diagnostic => ({
+ from,
+ to,
+ severity: "warning",
+ message,
+ });
+
+ test("forbid empty expression", () => {
+ expect(lintExpression({ expression: `` })).toEqual([
+ error(0, 0, `Expression cannot be empty`),
+ ]);
+ expect(lintExpression({ expression: ` ` })).toEqual([
+ error(0, 0, `Expression cannot be empty`),
+ ]);
+ });
+
+ test("output parse error as diagnostic", () => {
+ expect(lintExpression({ expression: `a + ` })).toEqual([
+ error(4, 4, "Unexpected token"),
+ ]);
+ expect(lintExpression({ expression: `"string" + a)` })).toEqual([
+ error(13, 13, "Unexpected token"),
+ ]);
+ });
+
+ test("restrict expression syntax", () => {
+ expect(lintExpression({ expression: `var a = 1` })).toEqual([
+ error(0, 0, "Unexpected token"),
+ ]);
+ });
+
+ test("lint whole expression instead of only first valid part", () => {
+ expect(
+ lintExpression({ expression: `a""`, availableVariables: new Set(["a"]) })
+ ).toEqual([error(1, 1, `Unexpected token`)]);
+ expect(
+ lintExpression({
+ expression: `/movie/{{CollectionItem['title']}}\n`,
+ availableVariables: new Set([""]),
+ })
+ ).toEqual([error(7, 7, `Unexpected token`)]);
+ });
+
+ test("supports accessing variable fields", () => {
+ expect(
+ lintExpression({
+ expression: `a.b.c`,
+ availableVariables: new Set(["a"]),
+ })
+ ).toEqual([]);
+ });
+
+ test("supports literals", () => {
+ expect(
+ lintExpression({
+ expression: `"" + 0 + true + [] + {}`,
+ })
+ ).toEqual([]);
+ });
+
+ test("supports ternary operator", () => {
+ expect(
+ lintExpression({
+ expression: `true ? false : true`,
+ })
+ ).toEqual([]);
+ });
+
+ test("supports template literals", () => {
+ expect(
+ lintExpression({
+ expression: "`my ${1} template ${'2'}`",
+ })
+ ).toEqual([]);
+ expect(
+ lintExpression({
+ expression: "`my template",
+ })
+ ).toEqual([error(1, 1, "Unterminated template")]);
+ });
+
+ test("supports parentheses", () => {
+ expect(
+ lintExpression({
+ expression: "(1 + 1) * 2",
+ })
+ ).toEqual([]);
+ });
+
+ test("forbid assignment until enabled", () => {
+ expect(
+ lintExpression({
+ expression: ` a = 1`,
+ availableVariables: new Set(["a"]),
+ })
+ ).toEqual([error(1, 6, "Assignment is not supported in this context")]);
+ expect(
+ lintExpression({
+ expression: ` a = 1`,
+ allowAssignment: true,
+ availableVariables: new Set(["a"]),
+ })
+ ).toEqual([]);
+ });
+
+ test("lint member assignment targets", () => {
+ expect(
+ lintExpression({
+ expression: ` a[b].c = d`,
+ allowAssignment: true,
+ availableVariables: new Set(["a", "b", "d"]),
+ })
+ ).toEqual([]);
+ expect(
+ lintExpression({
+ expression: ` a.b = c`,
+ allowAssignment: true,
+ availableVariables: new Set(["c"]),
+ })
+ ).toEqual([warn(1, 2, `"a" is not defined in the scope`)]);
+ });
+
+ test("lint assignment operators and targets", () => {
+ const assignmentExpressions = [
+ ` a = b`,
+ ` a += b`,
+ ` a -= b`,
+ ` a *= b`,
+ ` a /= b`,
+ ` a %= b`,
+ ` a **= b`,
+ ` a ||= b`,
+ ` a &&= b`,
+ ` a ??= b`,
+ ` a.b = c`,
+ ` a[b] = c`,
+ ` a[b].c = d`,
+ ` a.b[c.d].e ??= f.g`,
+ ];
+
+ for (const expression of assignmentExpressions) {
+ expect(
+ lintExpression({
+ expression,
+ allowAssignment: true,
+ availableVariables: new Set(["a", "b", "c", "d", "f"]),
+ })
+ ).toEqual([]);
+ }
+ });
+
+ test("forbid destructuring assignment", () => {
+ expect(
+ lintExpression({
+ expression: ` ({ a } = b)`,
+ allowAssignment: true,
+ availableVariables: new Set(["b"]),
+ })
+ ).toEqual([error(2, 7, "Destructuring assignment is not supported")]);
+ expect(
+ lintExpression({
+ expression: ` [a] = b`,
+ allowAssignment: true,
+ availableVariables: new Set(["b"]),
+ })
+ ).toEqual([error(1, 4, "Destructuring assignment is not supported")]);
+ expect(
+ lintExpression({
+ expression: ` ({ nested: a } = b)`,
+ allowAssignment: true,
+ availableVariables: new Set(["b"]),
+ })
+ ).toEqual([error(2, 15, "Destructuring assignment is not supported")]);
+ });
+
+ test("forbid unavailable variables", () => {
+ expect(
+ lintExpression({ expression: ` a = b + 1`, allowAssignment: true })
+ ).toEqual([
+ warn(5, 6, `"b" is not defined in the scope`),
+ warn(1, 2, `"a" is not defined in the scope`),
+ ]);
+ expect(
+ lintExpression({
+ expression: ` a = b + 1`,
+ allowAssignment: true,
+ availableVariables: new Set(["a", "b"]),
+ })
+ ).toEqual([]);
+ });
+
+ test(`forbid "this" keyword`, () => {
+ expect(lintExpression({ expression: ` this.name` })).toEqual([
+ error(1, 5, `"this" keyword is not supported`),
+ ]);
+ });
+
+ test("forbid functions", () => {
+ expect(
+ lintExpression({
+ expression: ` function(){} + (() => {}) + fn()`,
+ availableVariables: new Set(["fn"]),
+ })
+ ).toEqual([
+ error(1, 13, "Functions are not supported"),
+ error(17, 25, "Functions are not supported"),
+ error(29, 33, `"fn" function is not supported`),
+ ]);
+ });
+
+ test("forbid increment and decrement", () => {
+ expect(
+ lintExpression({
+ expression: ` ++i + --j`,
+ availableVariables: new Set(["j", "i"]),
+ })
+ ).toEqual([
+ error(1, 4, "Increment and decrement are not supported"),
+ error(7, 10, "Increment and decrement are not supported"),
+ ]);
+ });
+
+ test("forbid sequence expression", () => {
+ expect(lintExpression({ expression: ` 1, 2, 3` })).toEqual([
+ error(1, 8, "Only single expression is supported"),
+ ]);
+ });
+
+ test(`forbid "yield" keyword`, () => {
+ expect(lintExpression({ expression: ` yield 1` })).toEqual([
+ error(1, 1, `The keyword 'yield' is reserved`),
+ ]);
+ });
+
+ test("forbid tagged template", () => {
+ expect(
+ lintExpression({
+ expression: " tag`hello`",
+ availableVariables: new Set(["tag"]),
+ })
+ ).toEqual([error(1, 11, "Tagged template is not supported")]);
+ });
+
+ test("forbid classes", () => {
+ expect(
+ lintExpression({
+ expression: ` class {} + new MyClass()`,
+ availableVariables: new Set(["MyClass"]),
+ })
+ ).toEqual([
+ error(1, 9, "Classes are not supported"),
+ error(12, 25, "Classes are not supported"),
+ ]);
+ });
+
+ test("forbid imports", () => {
+ expect(
+ lintExpression({ expression: ` import("") + import.meta.url` })
+ ).toEqual([
+ error(1, 11, "Imports are not supported"),
+ error(14, 25, "Imports are not supported"),
+ ]);
+ });
+
+ test(`forbid "await" keyword`, () => {
+ expect(lintExpression({ expression: ` await 1` })).toEqual([
+ error(1, 8, `"await" keyword is not supported`),
+ ]);
+ });
+
+ test.each([
+ "toLowerCase",
+ "replace",
+ "split",
+ "at",
+ "slice",
+ "endsWith",
+ "includes",
+ "startsWith",
+ "toString",
+ "toUpperCase",
+ "toLocaleLowerCase",
+ "toLocaleUpperCase",
+ ])("allow safe string method: %s", (method) => {
+ expect(
+ lintExpression({
+ expression: `title.${method}()`,
+ availableVariables: new Set(["title"]),
+ })
+ ).toEqual([]);
+ });
+
+ test.each(["at", "includes", "join", "slice", "toString"])(
+ "allow safe array method: %s",
+ (method) => {
+ expect(
+ lintExpression({
+ expression: `arr.${method}()`,
+ availableVariables: new Set(["arr"]),
+ })
+ ).toEqual([]);
+ }
+ );
+
+ test("allow supported methods on known native-compatible receivers", () => {
+ expect(
+ lintExpression({
+ expression: `title.split("").toString()`,
+ availableVariables: new Set(["title"]),
+ variableValues: new Map([["title", "Test"]]),
+ })
+ ).toEqual([]);
+ expect(
+ lintExpression({
+ expression: `arr.join("").split("").toString()`,
+ availableVariables: new Set(["arr"]),
+ variableValues: new Map([["arr", ["T", "e", "s", "t"]]]),
+ })
+ ).toEqual([]);
+ expect(
+ lintExpression({
+ expression: `count.toString() + flag.toString() + object.toString()`,
+ availableVariables: new Set(["count", "flag", "object"]),
+ variableValues: new Map<string, unknown>([
+ ["count", 2],
+ ["flag", true],
+ ["object", {}],
+ ]),
+ })
+ ).toEqual([]);
+ expect(
+ lintExpression({
+ expression: `title.replace("e", "a").toLowerCase()`,
+ availableVariables: new Set(["title"]),
+ })
+ ).toEqual([]);
+ expect(
+ lintExpression({
+ expression: `arr.join("").toLowerCase()`,
+ availableVariables: new Set(["arr"]),
+ })
+ ).toEqual([]);
+ });
+
+ test("forbid supported method names on known native-incompatible receivers", () => {
+ expect(
+ lintExpression({
+ expression: `arr.split()`,
+ availableVariables: new Set(["arr"]),
+ variableValues: new Map([["arr", []]]),
+ }).map((diagnostic) => diagnostic.message)
+ ).toEqual([`"split" function is not supported`]);
+ expect(
+ lintExpression({
+ expression: `title.join()`,
+ availableVariables: new Set(["title"]),
+ variableValues: new Map([["title", "Test"]]),
+ }).map((diagnostic) => diagnostic.message)
+ ).toEqual([`"join" function is not supported`]);
+ expect(
+ lintExpression({
+ expression: `[1, 2, 3].toLowerCase()`,
+ }).map((diagnostic) => diagnostic.message)
+ ).toEqual([`"toLowerCase" function is not supported`]);
+ expect(
+ lintExpression({
+ expression: `"Test".join()`,
+ }).map((diagnostic) => diagnostic.message)
+ ).toEqual([`"join" function is not supported`]);
+ expect(
+ lintExpression({
+ expression: `title.split("").toLowerCase()`,
+ availableVariables: new Set(["title"]),
+ }).map((diagnostic) => diagnostic.message)
+ ).toEqual([`"toLowerCase" function is not supported`]);
+ expect(
+ lintExpression({
+ expression: `arr.join("").join()`,
+ availableVariables: new Set(["arr"]),
+ }).map((diagnostic) => diagnostic.message)
+ ).toEqual([`"join" function is not supported`]);
+ expect(
+ lintExpression({
+ expression: `null.toString() + undefined.toString()`,
+ }).map((diagnostic) => diagnostic.message)
+ ).toEqual([
+ `"toString" function is not supported`,
+ `"undefined" is not defined in the scope`,
+ `"toString" function is not supported`,
+ ]);
+ });
+
+ test("allow chained string methods", () => {
+ expect(
+ lintExpression({
+ expression: `title.toLowerCase().replace(" ", "-").split("-")`,
+ availableVariables: new Set(["title"]),
+ })
+ ).toEqual([]);
+ });
+
+ test("forbid unsafe method calls", () => {
+ expect(
+ lintExpression({
+ expression: `arr.pop()`,
+ availableVariables: new Set(["arr"]),
+ })
+ ).toEqual([error(0, 9, `"pop" function is not supported`)]);
+ expect(
+ lintExpression({
+ expression: `obj.push(1)`,
+ availableVariables: new Set(["obj"]),
+ })
+ ).toEqual([error(0, 11, `"push" function is not supported`)]);
+ });
+
+ test("forbid standalone function calls", () => {
+ expect(
+ lintExpression({
+ expression: `func()`,
+ availableVariables: new Set(["func"]),
+ })
+ ).toEqual([error(0, 6, `"func" function is not supported`)]);
+ });
+
+ test("visits supported unary, logical, and optional-chain syntax", () => {
+ expect(
+ lintExpression({
+ expression: `!value || record?.enabled`,
+ availableVariables: new Set(["value", "record"]),
+ })
+ ).toEqual([]);
+ });
+
+ test("rejects calls without a named callee", () => {
+ expect(
+ lintExpression({ expression: `(function () {})()` }).map(
+ ({ message }) => message
+ )
+ ).toEqual(["Functions are not supported", "Functions are not supported"]);
+ });
+});
+
+describe("expression value kinds", () => {
+ test.each([
+ ["[]", "array"],
+ ["1n", "bigint"],
+ ["true", "boolean"],
+ ["undefined", "nullish"],
+ ["null", "nullish"],
+ ["1", "number"],
+ ["{}", "object"],
+ ['"text"', "string"],
+ ["`text`", "string"],
+ ['"text" /* trailing comment */', "string"],
+ ["value +", "unknown"],
+ ['"text" trailing', "unknown"],
+ ] as const)("classifies %s as %s", (expression, kind) => {
+ expect(getExpressionValueKind({ expression })).toBe(kind);
+ });
+
+ test("uses map and record variable values", () => {
+ expect(
+ getExpressionValueKind({
+ expression: "value",
+ variableValues: new Map([["value", [1, 2]]]),
+ })
+ ).toBe("array");
+ expect(
+ getExpressionValueKind({
+ expression: "value",
+ variableValues: { value: "text" },
+ })
+ ).toBe("string");
+ expect(
+ getExpressionValueKind({
+ expression: "missing",
+ variableValues: new Map(),
+ })
+ ).toBe("unknown");
+ expect(
+ getExpressionValueKind({
+ expression: "missing",
+ variableValues: {},
+ })
+ ).toBe("unknown");
+ expect(
+ getExpressionValueKind({
+ expression: "callback",
+ variableValues: { callback: () => undefined },
+ })
+ ).toBe("unknown");
+ });
+
+ test("infers supported method return kinds", () => {
+ expect(getExpressionValueKind({ expression: '"text".split("")' })).toBe(
+ "array"
+ );
+ expect(getExpressionValueKind({ expression: "[].join(',')" })).toBe(
+ "string"
+ );
+ expect(
+ getExpressionValueKind({ expression: "unknownValue.split('')" })
+ ).toBe("array");
+ expect(
+ getExpressionValueKind({ expression: "unknownValue.join(',')" })
+ ).toBe("string");
+ expect(getExpressionValueKind({ expression: "unknownValue.at(0)" })).toBe(
+ "unknown"
+ );
+ expect(getExpressionValueKind({ expression: "unknownValue.slice()" })).toBe(
+ "unknown"
+ );
+ expect(getExpressionValueKind({ expression: "true.toString()" })).toBe(
+ "string"
+ );
+ expect(getExpressionValueKind({ expression: "true.slice()" })).toBe(
+ "unknown"
+ );
+ expect(getExpressionValueKind({ expression: "value?.name" })).toBe(
+ "unknown"
+ );
+ });
+});
+
+test("check simple literals", () => {
+ expect(isLiteralExpression(`""`)).toEqual(true);
+ expect(isLiteralExpression(`''`)).toEqual(true);
+ expect(isLiteralExpression(`0`)).toEqual(true);
+ expect(isLiteralExpression(`true`)).toEqual(true);
+ expect(isLiteralExpression(`[]`)).toEqual(true);
+ expect(isLiteralExpression(`{}`)).toEqual(true);
+ expect(isLiteralExpression(`undefined`)).toEqual(true);
+ expect(isLiteralExpression(`"" + ""`)).toEqual(false);
+ expect(isLiteralExpression(`{}.field`)).toEqual(false);
+ expect(isLiteralExpression(`variable`)).toEqual(false);
+ expect(isLiteralExpression(`1 trailing`)).toEqual(false);
+ expect(isLiteralExpression(``)).toEqual(false);
+});
+
+test("check complex objects and arrays", () => {
+ expect(isLiteralExpression(`[1, 2, 3]`)).toEqual(true);
+ expect(isLiteralExpression(`[1, 2, variable]`)).toEqual(false);
+ expect(isLiteralExpression(`[...variable]`)).toEqual(false);
+ expect(isLiteralExpression(`{ param: 0 }`)).toEqual(true);
+ expect(isLiteralExpression(`{ "param": 0 }`)).toEqual(true);
+ expect(isLiteralExpression(`{ param: variable }`)).toEqual(false);
+ expect(isLiteralExpression(`{ ["param"]: 0 }`)).toEqual(true);
+ expect(isLiteralExpression(`{ [variable]: 0 }`)).toEqual(false);
+ expect(isLiteralExpression(`{ ...variable }`)).toEqual(false);
+});
+
+describe("get expression identifiers", () => {
+ test("find all identifiers", () => {
+ expect(getExpressionIdentifiers("a = b * c.d")).toEqual(
+ new Set(["a", "b", "c"])
+ );
+ });
+
+ test("find identifiers in assignment targets", () => {
+ expect(getExpressionIdentifiers("a[b].c = d.e")).toEqual(
+ new Set(["a", "b", "d"])
+ );
+ expect(getExpressionIdentifiers("a.b[c.d].e ??= f.g")).toEqual(
+ new Set(["a", "c", "f"])
+ );
+ });
+
+ test("deduplicate identifiers", () => {
+ expect(getExpressionIdentifiers("a = a + b")).toEqual(new Set(["a", "b"]));
+ });
+
+ test("not fail when invalid syntax", () => {
+ expect(getExpressionIdentifiers("")).toEqual(new Set());
+ expect(getExpressionIdentifiers("a = a +")).toEqual(new Set());
+ expect(getExpressionIdentifiers("a trailing")).toEqual(new Set());
+ });
+});
+
+describe("transpile expression", () => {
+ const expectTranspiledExpressionToMatchNative = (expression: string) => {
+ const nativeResult = new Function(`return (${expression})`)();
+ const transpiledResult = new Function(
+ `return (${transpileExpression({ expression, executable: true })})`
+ )();
+ expect(transpiledResult).toEqual(nativeResult);
+ };
+
+ test("preserve spaces and parentheses", () => {
+ expect(
+ transpileExpression({ expression: " 1 + (2 + 3) ", executable: true })
+ ).toEqual(" 1 + (2 + 3) ");
+ });
+
+ test("add optional chaining with dot syntax", () => {
+ expect(
+ transpileExpression({ expression: "a.b . c", executable: true })
+ ).toEqual("a?.b ?. c");
+ });
+
+ test("add optional chaining with computed", () => {
+ expect(
+ transpileExpression({ expression: "a['b'] [c]", executable: true })
+ ).toEqual("a?.['b'] ?.[c]");
+ });
+
+ test("skip optional chaining", () => {
+ expect(
+ transpileExpression({ expression: "a?.['b']?.c", executable: true })
+ ).toEqual("a?.['b']?.c");
+ });
+
+ test("skip optional chaining in assignment targets", () => {
+ expect(
+ transpileExpression({ expression: "a.b = c.d", executable: true })
+ ).toEqual("a.b = c?.d");
+ expect(
+ transpileExpression({ expression: "a[b.c].d = e.f", executable: true })
+ ).toEqual("a[b?.c].d = e?.f");
+ });
+
+ test("skip optional chaining in assignment targets for all assignment operators", () => {
+ const operators = [
+ "=",
+ "+=",
+ "-=",
+ "*=",
+ "/=",
+ "%=",
+ "**=",
+ "||=",
+ "&&=",
+ "??=",
+ ];
+
+ for (const operator of operators) {
+ const expression = `a.b ${operator} c.d`;
+ const transpiled = transpileExpression({ expression, executable: true });
+ expect(transpiled).toEqual(`a.b ${operator} c?.d`);
+ expect(() =>
+ parseExpressionAt(transpiled, 0, { ecmaVersion: "latest" })
+ ).not.toThrow();
+ }
+ });
+
+ test("transpile executable assignment expressions", () => {
+ const cases = [
+ ["a.b = c.d", "a.b = c?.d"],
+ ["a[b] = c.d", "a[b] = c?.d"],
+ ["a[b.c] = d.e", "a[b?.c] = d?.e"],
+ ["a[b.c].d = e.f", "a[b?.c].d = e?.f"],
+ ["a.b[c.d].e ??= f.g", "a.b[c?.d].e ??= f?.g"],
+ ] as const;
+
+ for (const [expression, expected] of cases) {
+ const transpiled = transpileExpression({ expression, executable: true });
+ expect(transpiled).toEqual(expected);
+ expect(() =>
+ parseExpressionAt(transpiled, 0, { ecmaVersion: "latest" })
+ ).not.toThrow();
+ }
+ });
+
+ test("replace variable", () => {
+ expect(
+ transpileExpression({
+ expression: "(a + c) * b",
+ replaceVariable: (identifier) => identifier + "_1",
+ })
+ ).toEqual("(a_1 + c_1) * b_1");
+ expect(
+ transpileExpression({
+ expression: "a = c",
+ replaceVariable: (identifier) => identifier + "_1",
+ })
+ ).toEqual("a_1 = c_1");
+ });
+
+ test("skip identifiers in nested member expressions", () => {
+ const identifiers: string[] = [];
+ const transpiled = transpileExpression({
+ expression: "a.b + c.d * e[f]",
+ replaceVariable: (identifier) => {
+ identifiers.push(identifier);
+ return identifier + "_1";
+ },
+ });
+ expect(identifiers).toEqual(["a", "c", "e", "f"]);
+ expect(transpiled).toEqual("a_1.b + c_1.d * e_1[f_1]");
+ });
+
+ test("inform identifier is an assignee", () => {
+ const replaceVariable = (identifier: string, assignee: boolean) => {
+ const suffix = assignee ? "_assignee" : "_assigner";
+ return identifier + suffix;
+ };
+
+ const cases = [
+ ["a = b", "a_assignee = b_assigner"],
+ ["a += b", "a_assignee += b_assigner"],
+ ["a ||= b", "a_assignee ||= b_assigner"],
+ ["a ??= b", "a_assignee ??= b_assigner"],
+ ["a.b = c", "a_assignee.b = c_assigner"],
+ ["a[b] = c", "a_assignee[b_assigner] = c_assigner"],
+ ["a[b].c = d", "a_assignee[b_assigner].c = d_assigner"],
+ ["a.b[c.d].e ??= f.g", "a_assignee.b[c_assigner.d].e ??= f_assigner.g"],
+ ] as const;
+
+ for (const [expression, expected] of cases) {
+ expect(transpileExpression({ expression, replaceVariable })).toEqual(
+ expected
+ );
+ }
+ });
+
+ test("transpile object literal without changes", () => {
+ expect(
+ transpileExpression({
+ expression: `{ ...name }`,
+ })
+ ).toEqual(`{ ...name }`);
+ });
+
+ test("transpiles a parenthesized object expression", () => {
+ expect(
+ transpileExpression({
+ expression: "({ value: $ws$system.origin })",
+ replaceVariable: (identifier) =>
+ identifier === "$ws$system" ? "system" : identifier,
+ })
+ ).toEqual("({ value: system.origin })");
+ });
+
+ test("output more readable syntax error", () => {
+ let errorString = "";
+ try {
+ transpileExpression({ expression: `` });
+ } catch (error) {
+ errorString = (error as Error).message;
+ }
+ expect(errorString).toEqual(`Unexpected token (1:0) in ""`);
+ });
+
+ test("rejects content after the expression", () => {
+ expect(() => transpileExpression({ expression: "value trailing" })).toThrow(
+ 'Unexpected content after expression in "value trailing"'
+ );
+ });
+
+ test("transpile string methods with optional chaining", () => {
+ expect(
+ transpileExpression({
+ expression: "title.toLowerCase()",
+ executable: true,
+ })
+ ).toEqual("title?.toLowerCase?.()");
+ expect(
+ transpileExpression({
+ expression: "user.name.replace(' ', '-')",
+ executable: true,
+ })
+ ).toEqual("user?.name?.replace?.(' ', '-')");
+ expect(
+ transpileExpression({
+ expression: "data.title.split('-')",
+ executable: true,
+ })
+ ).toEqual("data?.title?.split?.('-')");
+ });
+
+ test("preserve native behavior for all supported string methods", () => {
+ const expressionsByMethod = {
+ at: `"Hello".at(1)`,
+ endsWith: `"Hello".endsWith("lo")`,
+ includes: `"Hello".includes("ell")`,
+ replace: `"Hello".replace("l", "x")`,
+ slice: `"Hello".slice(1, 4)`,
+ split: `"Hello".split("l")`,
+ startsWith: `"Hello".startsWith("He")`,
+ toLocaleLowerCase: `"Hello".toLocaleLowerCase()`,
+ toLocaleUpperCase: `"Hello".toLocaleUpperCase()`,
+ toLowerCase: `"Hello".toLowerCase()`,
+ toString: `"Hello".toString()`,
+ toUpperCase: `"Hello".toUpperCase()`,
+ };
+
+ expect(new Set(Object.keys(expressionsByMethod))).toEqual(
+ allowedStringMethods
+ );
+ for (const expression of Object.values(expressionsByMethod)) {
+ expectTranspiledExpressionToMatchNative(expression);
+ }
+ expectTranspiledExpressionToMatchNative(`"Test".split(2).toString()`);
+ });
+
+ test("preserve native behavior for all supported array methods", () => {
+ const expressionsByMethod = {
+ at: `["a", "b", "c"].at(1)`,
+ includes: `["a", "b", "c"].includes("b")`,
+ join: `["a", "b", "c"].join("-")`,
+ slice: `["a", "b", "c"].slice(1, 3)`,
+ toString: `["a", "b", "c"].toString()`,
+ };
+
+ expect(new Set(Object.keys(expressionsByMethod))).toEqual(
+ allowedArrayMethods
+ );
+ for (const expression of Object.values(expressionsByMethod)) {
+ expectTranspiledExpressionToMatchNative(expression);
+ }
+ });
+
+ test("transpile chained string methods with optional chaining", () => {
+ expect(
+ transpileExpression({
+ expression: "title.toLowerCase().replace(/\\s+/g, '-')",
+ executable: true,
+ })
+ ).toEqual("title?.toLowerCase?.()?.replace?.(/\\s+/g, '-')");
+ expect(
+ transpileExpression({
+ expression: "user.name.toLowerCase().replace(' ', '-').split('-')",
+ executable: true,
+ })
+ ).toEqual("user?.name?.toLowerCase?.()?.replace?.(' ', '-')?.split?.('-')");
+ });
+
+ test("transpile array methods with optional chaining", () => {
+ expect(
+ transpileExpression({
+ expression: "items.map(item => item.id)",
+ executable: true,
+ })
+ ).toEqual("items?.map?.(item => item?.id)");
+ });
+
+ test("transpile nested method calls with optional chaining", () => {
+ expect(
+ transpileExpression({
+ expression: "obj.method().prop.anotherMethod()",
+ executable: true,
+ })
+ ).toEqual("obj?.method?.()?.prop?.anotherMethod?.()");
+ });
+
+ test("preserve existing optional chaining", () => {
+ expect(
+ transpileExpression({
+ expression: "obj?.method?.()",
+ executable: true,
+ })
+ ).toEqual("obj?.method?.()");
+ expect(
+ transpileExpression({
+ expression: "obj?.prop?.method?.()",
+ executable: true,
+ })
+ ).toEqual("obj?.prop?.method?.()");
+ });
+});
+
+describe("object expression transformations", () => {
+ test("parse complete object expression", () => {
+ expect(
+ parseExpressionObject(
+ "{ value: system.params.slug, limit: pageSize ?? 20 }"
+ )
+ ).toEqual(
+ new Map([
+ ["value", "system.params.slug"],
+ ["limit", "pageSize ?? 20"],
+ ])
+ );
+ expect(parseExpressionObject("({ value: 1 })")).toEqual(
+ new Map([["value", "1"]])
+ );
+ expect(parseExpressionObject("(({ value: 1 }))")).toEqual(
+ new Map([["value", "1"]])
+ );
+ expect(parseExpressionObject("{} trailing")).toBeUndefined();
+ expect(parseExpressionObject("({}) trailing")).toBeUndefined();
+ expect(parseExpressionObject("{")).toBeUndefined();
+ expect(parseExpressionObject("0")).toBeUndefined();
+ expect(parseExpressionObject("{ value: 1, ...other }")).toBeUndefined();
+ expect(parseExpressionObject("{ [value]: 1 }")).toBeUndefined();
+ expect(parseExpressionObject('{ "quoted-key": 1 }')).toEqual(
+ new Map([["quoted-key", "1"]])
+ );
+ expect(parseExpressionObject("{ 1: true }")).toBeUndefined();
+ expect(parseExpressionObject("{ value: 1, value: 2 }")).toBeUndefined();
+ });
+
+ test("parse array expression", () => {
+ expect(parseArrayExpression(`[0, "", $c + 1]`)).toEqual([
+ "0",
+ '""',
+ "$c + 1",
+ ]);
+ expect(parseArrayExpression("0")).toBeUndefined();
+ expect(parseArrayExpression("[...items]")).toBeUndefined();
+ expect(parseArrayExpression("[")).toBeUndefined();
+ expect(parseArrayExpression("[1] trailing")).toBeUndefined();
+ });
+
+ test("format object expression", () => {
+ expect(
+ generateObjectExpression(
+ new Map([
+ ["a", `0`],
+ ["b-c", `""`],
+ ["d", `$d`],
+ ["default", `true`],
+ ["$value", `null`],
+ ["invalid key", `false`],
+ ])
+ )
+ ).toMatchInlineSnapshot(`
+ "{
+ a: 0,
+ "b-c": "",
+ d: $d,
+ default: true,
+ $value: null,
+ "invalid key": false,
+ }"
+ `);
+ });
+
+ test("format empty object expression", () => {
+ expect(generateObjectExpression(new Map())).toMatchInlineSnapshot(`
+ "{
+ }"
+ `);
+ });
+
+ test("format JSON as readable JavaScript expression source", () => {
+ expect(
+ generateJsonExpression({
+ query: {
+ sort: [{ field: ["properties", "date"], direction: "desc" }],
+ "file-content": null,
+ },
+ })
+ ).toMatchInlineSnapshot(`
+ "{
+ query: {
+ sort: [{
+ field: [\"properties\", \"date\"],
+ direction: \"desc\",
+ }],
+ \"file-content\": null,
+ },
+ }"
+ `);
+ expect(() => generateJsonExpression(undefined)).toThrow();
+ expect(() => generateJsonExpression(new Date())).toThrow();
+ const source = generateJsonExpression({
+ enabled: true,
+ count: -2,
+ values: [null, "value"],
+ });
+ expect(parseJsonExpression(source)).toEqual({
+ enabled: true,
+ count: -2,
+ values: [null, "value"],
+ });
+ expect(parseJsonExpression("{ value: dynamic }")).toBeUndefined();
+ expect(parseJsonExpression("{ value: 1, value: 2 }")).toBeUndefined();
+ expect(parseJsonExpression("{ value: -1e999 }")).toBeUndefined();
+ expect(parseJsonExpression('{ "quoted": true }')).toEqual({
+ quoted: true,
+ });
+ expect(parseJsonExpression(undefined)).toBeUndefined();
+ expect(parseJsonExpression("true trailing")).toBeUndefined();
+ expect(parseJsonExpression("{")).toBeUndefined();
+ for (const invalid of [
+ "/pattern/",
+ "1n",
+ "[dynamic]",
+ "[,]",
+ "[...values]",
+ "{ ...value }",
+ "{ [key]: 1 }",
+ "{ method() {} }",
+ "{ value }",
+ "{ 1: true }",
+ ]) {
+ expect(parseJsonExpression(invalid), invalid).toBeUndefined();
+ }
+ });
+});
diff --git a/packages/expression/src/index.ts b/packages/expression/src/index.ts
new file mode 100644
index 0000000000..152c780fce
--- /dev/null
+++ b/packages/expression/src/index.ts
@@ -0,0 +1,865 @@
+import {
+ type Expression,
+ type Identifier,
+ type MemberExpression,
+ type Pattern,
+ parse,
+ parseExpressionAt,
+ tokenizer,
+} from "acorn";
+import { simple } from "acorn-walk";
+
+const parseCompleteExpression = (
+ expression: string,
+ options: { preserveParens?: boolean } = {}
+) => {
+ const completeNode = parseExpressionAt(expression, 0, {
+ ecmaVersion: "latest",
+ preserveParens: true,
+ });
+ const trailingToken = tokenizer(expression.slice(completeNode.end), {
+ ecmaVersion: "latest",
+ }).getToken();
+ if (trailingToken.type.label !== "eof") {
+ throw new SyntaxError("Unexpected content after expression");
+ }
+ if (
+ options.preserveParens ||
+ completeNode.type !== "ParenthesizedExpression"
+ ) {
+ return completeNode;
+ }
+ return parseExpressionAt(expression, 0, {
+ ecmaVersion: "latest",
+ });
+};
+
+export type Diagnostic = {
+ from: number;
+ to: number;
+ severity: "error" | "hint" | "info" | "warning";
+ message: string;
+};
+
+type ExpressionVisitor = {
+ [K in Expression["type"]]: (node: Extract<Expression, { type: K }>) => void;
+};
+
+type AssignmentTargetKind = "binding" | "memberObject";
+
+const walkAssignmentTarget = (
+ node: Pattern,
+ visitor: {
+ Identifier?: (node: Identifier, kind: AssignmentTargetKind) => void;
+ MemberExpression?: (node: MemberExpression) => void;
+ UnsupportedPattern?: (node: Pattern) => void;
+ }
+) => {
+ if (node.type === "Identifier") {
+ visitor.Identifier?.(node, "binding");
+ return;
+ }
+
+ if (node.type === "MemberExpression") {
+ visitor.MemberExpression?.(node);
+ const { object } = node;
+ if (object.type === "Identifier") {
+ visitor.Identifier?.(object, "memberObject");
+ } else if (object.type === "MemberExpression") {
+ walkAssignmentTarget(object, visitor);
+ }
+ return;
+ }
+
+ visitor.UnsupportedPattern?.(node);
+};
+
+export type VariableValues =
+ | ReadonlyMap<Identifier["name"], unknown>
+ | Readonly<Record<Identifier["name"], unknown>>;
+
+export type ExpressionValueKind =
+ | "array"
+ | "bigint"
+ | "boolean"
+ | "nullish"
+ | "number"
+ | "object"
+ | "string"
+ | "unknown";
+
+const stringMethodReturnKindByName = new Map<string, ExpressionValueKind>([
+ ["toLowerCase", "string"],
+ ["replace", "string"],
+ ["split", "array"],
+ ["slice", "string"],
+ ["at", "unknown"],
+ ["endsWith", "boolean"],
+ ["includes", "boolean"],
+ ["startsWith", "boolean"],
+ ["toString", "string"],
+ ["toUpperCase", "string"],
+ ["toLocaleLowerCase", "string"],
+ ["toLocaleUpperCase", "string"],
+]);
+
+const arrayMethodReturnKindByName = new Map<string, ExpressionValueKind>([
+ ["at", "unknown"],
+ ["includes", "boolean"],
+ ["join", "string"],
+ ["slice", "array"],
+ ["toString", "string"],
+]);
+
+export const allowedStringMethods = new Set(
+ stringMethodReturnKindByName.keys()
+);
+
+export const allowedArrayMethods = new Set(arrayMethodReturnKindByName.keys());
+
+const getVariableValue = (
+ variableValues: undefined | VariableValues,
+ name: Identifier["name"]
+) => {
+ if (variableValues === undefined) {
+ return;
+ }
+ const maybeMap = variableValues as Partial<ReadonlyMap<string, unknown>>;
+ if (
+ typeof maybeMap.has === "function" &&
+ typeof maybeMap.get === "function"
+ ) {
+ if (maybeMap.has(name)) {
+ return { value: maybeMap.get(name) };
+ }
+ return;
+ }
+ const record = variableValues as Readonly<Record<string, unknown>>;
+ if (Object.hasOwn(record, name)) {
+ return { value: record[name] };
+ }
+};
+
+const getValueKind = (value: unknown): ExpressionValueKind => {
+ if (Array.isArray(value)) {
+ return "array";
+ }
+ if (value === undefined || value === null) {
+ return "nullish";
+ }
+ switch (typeof value) {
+ case "bigint":
+ return "bigint";
+ case "boolean":
+ return "boolean";
+ case "number":
+ return "number";
+ case "string":
+ return "string";
+ case "object":
+ return "object";
+ default:
+ return "unknown";
+ }
+};
+
+const getMethodReturnKind = (
+ receiverKind: ExpressionValueKind,
+ methodName: string
+): ExpressionValueKind => {
+ if (receiverKind === "array") {
+ return arrayMethodReturnKindByName.get(methodName) ?? "unknown";
+ }
+ if (receiverKind === "string") {
+ return stringMethodReturnKindByName.get(methodName) ?? "unknown";
+ }
+ if (receiverKind === "unknown") {
+ const stringReturnKind = stringMethodReturnKindByName.get(methodName);
+ const arrayReturnKind = arrayMethodReturnKindByName.get(methodName);
+ if (stringReturnKind && arrayReturnKind === undefined) {
+ return stringReturnKind;
+ }
+ if (arrayReturnKind && stringReturnKind === undefined) {
+ return arrayReturnKind;
+ }
+ if (stringReturnKind === arrayReturnKind) {
+ return stringReturnKind ?? "unknown";
+ }
+ return "unknown";
+ }
+ return methodName === "toString" ? "string" : "unknown";
+};
+
+const isMethodSupported = (
+ receiverKind: ExpressionValueKind,
+ methodName: string
+) => {
+ if (receiverKind === "unknown") {
+ return (
+ allowedStringMethods.has(methodName) ||
+ allowedArrayMethods.has(methodName)
+ );
+ }
+ if (receiverKind === "string") {
+ return stringMethodReturnKindByName.has(methodName);
+ }
+ if (receiverKind === "array") {
+ return arrayMethodReturnKindByName.has(methodName);
+ }
+ if (receiverKind === "nullish") {
+ return false;
+ }
+ return methodName === "toString";
+};
+
+const getExpressionNodeValueKind = (
+ node: Expression,
+ variableValues: undefined | VariableValues
+): ExpressionValueKind => {
+ if (node.type === "Identifier") {
+ if (node.name === "undefined") {
+ return "nullish";
+ }
+ const variable = getVariableValue(variableValues, node.name);
+ return variable ? getValueKind(variable.value) : "unknown";
+ }
+ if (node.type === "Literal") {
+ return getValueKind(node.value);
+ }
+ if (node.type === "ArrayExpression") {
+ return "array";
+ }
+ if (node.type === "ObjectExpression") {
+ return "object";
+ }
+ if (node.type === "TemplateLiteral") {
+ return "string";
+ }
+ if (
+ node.type === "ChainExpression" ||
+ node.type === "ParenthesizedExpression"
+ ) {
+ return getExpressionNodeValueKind(node.expression, variableValues);
+ }
+ if (
+ node.type === "CallExpression" &&
+ node.callee.type === "MemberExpression" &&
+ node.callee.object.type !== "Super" &&
+ node.callee.property.type === "Identifier"
+ ) {
+ const receiverKind = getExpressionNodeValueKind(
+ node.callee.object,
+ variableValues
+ );
+ const methodName = node.callee.property.name;
+ if (isMethodSupported(receiverKind, methodName)) {
+ return getMethodReturnKind(receiverKind, methodName);
+ }
+ }
+ return "unknown";
+};
+
+export const getExpressionValueKind = ({
+ expression,
+ variableValues,
+}: {
+ expression: string;
+ variableValues?: VariableValues;
+}): ExpressionValueKind => {
+ try {
+ const node = parseCompleteExpression(expression);
+ return getExpressionNodeValueKind(node, variableValues);
+ } catch {
+ return "unknown";
+ }
+};
+
+export const lintExpression = ({
+ expression,
+ availableVariables = new Set(),
+ allowAssignment = false,
+ variableValues,
+}: {
+ expression: string;
+ availableVariables?: Set<Identifier["name"]>;
+ allowAssignment?: boolean;
+ variableValues?: VariableValues;
+}): Diagnostic[] => {
+ const diagnostics: Diagnostic[] = [];
+ const addMessage = (
+ message: string,
+ severity: "error" | "warning" = "error"
+ ) => {
+ return (node: { start: number; end: number }) => {
+ diagnostics.push({
+ // tune error position after wrapping expression with parentheses
+ from: node.start - 1,
+ to: node.end - 1,
+ severity,
+ message: message,
+ });
+ };
+ };
+ // allow empty expression
+ if (expression.trim().length === 0) {
+ diagnostics.push({
+ from: 0,
+ to: 0,
+ severity: "error",
+ message: "Expression cannot be empty",
+ });
+ return diagnostics;
+ }
+ try {
+ // wrap expression with parentheses to force acorn parse whole expression
+ // instead of just first valid part
+ const root = parse(`(${expression})`, {
+ ecmaVersion: "latest",
+ // support parsing import to forbid explicitly
+ sourceType: "module",
+ });
+
+ simple(root, {
+ Identifier(node) {
+ if (availableVariables.has(node.name) === false) {
+ addMessage(
+ `"${node.name}" is not defined in the scope`,
+ "warning"
+ )(node);
+ }
+ },
+ Literal() {},
+ ArrayExpression() {},
+ ObjectExpression() {},
+ UnaryExpression() {},
+ BinaryExpression() {},
+ LogicalExpression() {},
+ MemberExpression() {},
+ ConditionalExpression() {},
+ TemplateLiteral() {},
+ ChainExpression() {},
+ ParenthesizedExpression() {},
+ AssignmentExpression(node) {
+ if (allowAssignment === false) {
+ addMessage("Assignment is not supported in this context")(node);
+ return;
+ }
+ walkAssignmentTarget(node.left, {
+ Identifier(node, kind) {
+ if (kind !== "binding") {
+ return;
+ }
+ if (availableVariables.has(node.name) === false) {
+ addMessage(
+ `"${node.name}" is not defined in the scope`,
+ "warning"
+ )(node);
+ }
+ },
+ UnsupportedPattern: addMessage(
+ "Destructuring assignment is not supported"
+ ),
+ });
+ },
+ // parser forbids to yield inside module
+ YieldExpression() {},
+ ThisExpression: addMessage(`"this" keyword is not supported`),
+ FunctionExpression: addMessage("Functions are not supported"),
+ UpdateExpression: addMessage("Increment and decrement are not supported"),
+ CallExpression(node) {
+ let calleeName;
+ if (node.callee.type === "MemberExpression") {
+ if (node.callee.property.type === "Identifier") {
+ const methodName = node.callee.property.name;
+ const receiverKind =
+ node.callee.object.type === "Super"
+ ? "unknown"
+ : getExpressionNodeValueKind(
+ node.callee.object,
+ variableValues
+ );
+ if (isMethodSupported(receiverKind, methodName)) {
+ return;
+ }
+ calleeName = methodName;
+ }
+ } else if (node.callee.type === "Identifier") {
+ calleeName = node.callee.name;
+ }
+ if (calleeName) {
+ addMessage(`"${calleeName}" function is not supported`)(node);
+ } else {
+ addMessage("Functions are not supported")(node);
+ }
+ },
+ NewExpression: addMessage("Classes are not supported"),
+ SequenceExpression: addMessage(`Only single expression is supported`),
+ ArrowFunctionExpression: addMessage("Functions are not supported"),
+ TaggedTemplateExpression: addMessage("Tagged template is not supported"),
+ ClassExpression: addMessage("Classes are not supported"),
+ MetaProperty: addMessage("Imports are not supported"),
+ AwaitExpression: addMessage(`"await" keyword is not supported`),
+ ImportExpression: addMessage("Imports are not supported"),
+ } satisfies ExpressionVisitor);
+ } catch (error) {
+ const castedError = error as { message: string; pos: number };
+ diagnostics.push({
+ // tune error position after wrapping expression with parentheses
+ from: castedError.pos - 1,
+ to: castedError.pos - 1,
+ severity: "error",
+ // trim auto generated error location
+ // to not conflict with tuned position
+ message: castedError.message.replaceAll(/\s+\(\d+:\d+\)$/g, ""),
+ });
+ }
+ return diagnostics;
+};
+
+const isLiteralNode = (node: Expression): boolean => {
+ if (node.type === "Identifier" && node.name === "undefined") {
+ return true;
+ }
+ if (node.type === "Literal") {
+ return true;
+ }
+ if (node.type === "ArrayExpression") {
+ return node.elements.every((node) => {
+ if (node === null || node.type === "SpreadElement") {
+ return false;
+ }
+ return isLiteralNode(node);
+ });
+ }
+ if (node.type === "ObjectExpression") {
+ return node.properties.every((property) => {
+ if (property.type === "SpreadElement") {
+ return false;
+ }
+ const key = property.key;
+ const isIdentifierKey =
+ key.type === "Identifier" && property.computed === false;
+ const isLiteralKey = key.type === "Literal";
+ return (isLiteralKey || isIdentifierKey) && isLiteralNode(property.value);
+ });
+ }
+ return false;
+};
+
+/**
+ * check whether provided expression is a literal value
+ * like "", 0 or { param: "value" }
+ * which does not depends on any variable
+ */
+export const isLiteralExpression = (expression: string) => {
+ try {
+ const node = parseCompleteExpression(expression);
+ return isLiteralNode(node);
+ } catch {
+ // treat invalid expression as non-literal
+ return false;
+ }
+};
+
+/** Check whether the complete source is one valid JavaScript expression. */
+export const isValidExpression = (expression: string) => {
+ try {
+ parseCompleteExpression(expression);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+export const parseStringLiteralExpression = (expression: string) => {
+ try {
+ const value = JSON.parse(expression);
+ return typeof value === "string" && JSON.stringify(value) === expression
+ ? value
+ : undefined;
+ } catch {
+ return;
+ }
+};
+
+const getStaticMemberPath = (node: Expression): string[] | undefined => {
+ if (node.type === "Identifier") {
+ return [node.name];
+ }
+ if (node.type === "ChainExpression") {
+ return getStaticMemberPath(node.expression);
+ }
+ if (node.type !== "MemberExpression" || node.object.type === "Super") {
+ return;
+ }
+ const objectPath = getStaticMemberPath(node.object);
+ if (objectPath === undefined) {
+ return;
+ }
+ const property = node.property;
+ const propertyName = node.computed
+ ? property.type === "Literal" &&
+ (typeof property.value === "string" || typeof property.value === "number")
+ ? String(property.value)
+ : undefined
+ : property.type === "Identifier"
+ ? property.name
+ : undefined;
+ return propertyName === undefined ? undefined : [...objectPath, propertyName];
+};
+
+/** Parse an identifier/member expression whose complete property path is static. */
+export const parseStaticMemberPath = (expression: string) => {
+ try {
+ const node = parseCompleteExpression(expression);
+ return getStaticMemberPath(node);
+ } catch {
+ return;
+ }
+};
+
+export const getExpressionIdentifiers = (expression: string) => {
+ const identifiers = new Set<string>();
+ try {
+ const root = parseCompleteExpression(expression);
+ simple(root, {
+ Identifier: (node) => identifiers.add(node.name),
+ AssignmentExpression(node) {
+ walkAssignmentTarget(node.left, {
+ Identifier: (node) => identifiers.add(node.name),
+ });
+ },
+ });
+ } catch {
+ // empty block
+ }
+ return identifiers;
+};
+
+/**
+ * transpile expression into executable one
+ *
+ * add optional chaining operator to every member expression
+ * to access any field without runtime errors
+ *
+ * replace variable names if necessary
+ */
+export const transpileExpression = ({
+ expression,
+ executable = false,
+ replaceVariable,
+}: {
+ expression: string;
+ executable?: boolean;
+ replaceVariable?: (
+ identifier: string,
+ assignee: boolean
+ ) => string | undefined | void;
+}) => {
+ let root;
+ try {
+ root = parseCompleteExpression(expression);
+ } catch (error) {
+ const message = (error as Error).message;
+ // throw new error to trace error in our code instead of acorn
+ throw Error(`${message} in ${JSON.stringify(expression)}`);
+ }
+ const assignmentTargetMemberRanges: [start: number, end: number][] = [];
+ if (executable) {
+ simple(root, {
+ AssignmentExpression(node) {
+ walkAssignmentTarget(node.left, {
+ MemberExpression(node) {
+ assignmentTargetMemberRanges.push([node.start, node.end]);
+ },
+ });
+ },
+ });
+ }
+ const replacements: [start: number, end: number, fragment: string][] = [];
+ const replacementIndexByRange = new Map<string, number>();
+ const addReplacement = (
+ start: number,
+ end: number,
+ fragment: string,
+ { replaceExisting = false }: { replaceExisting?: boolean } = {}
+ ) => {
+ const range = `${start}:${end}`;
+ const existingIndex = replacementIndexByRange.get(range);
+ if (existingIndex !== undefined) {
+ if (replaceExisting) {
+ replacements[existingIndex] = [start, end, fragment];
+ }
+ return;
+ }
+ replacementIndexByRange.set(range, replacements.length);
+ replacements.push([start, end, fragment]);
+ };
+ const replaceIdentifier = (node: Identifier, assignee: boolean) => {
+ const newName = replaceVariable?.(node.name, assignee);
+ if (newName) {
+ addReplacement(node.start, node.end, newName, {
+ replaceExisting: assignee,
+ });
+ }
+ };
+ simple(root, {
+ Identifier: (node) => replaceIdentifier(node, false),
+ AssignmentExpression(node) {
+ walkAssignmentTarget(node.left, {
+ Identifier: (node) => replaceIdentifier(node, true),
+ });
+ },
+ MemberExpression(node) {
+ if (executable === false || node.optional) {
+ return;
+ }
+ if (
+ assignmentTargetMemberRanges.some(
+ ([start, end]) => start === node.start && end === node.end
+ )
+ ) {
+ return;
+ }
+ // a . b -> a ?. b
+ if (node.computed === false) {
+ const dotIndex = expression.indexOf(".", node.object.end);
+ addReplacement(dotIndex, dotIndex, "?");
+ }
+ // a [b] -> a ?.[b]
+ if (node.computed === true) {
+ const dotIndex = expression.indexOf("[", node.object.end);
+ addReplacement(dotIndex, dotIndex, "?.");
+ }
+ },
+ CallExpression(node) {
+ if (executable === false || node.optional) {
+ return;
+ }
+ // Add optional chaining to method calls: obj.method() -> obj?.method?.()
+ if (node.callee.type === "MemberExpression") {
+ // Find the opening parenthesis after the method name
+ const openParenIndex = expression.indexOf("(", node.callee.end);
+ if (openParenIndex !== -1) {
+ addReplacement(openParenIndex, openParenIndex, "?.");
+ }
+ }
+ },
+ });
+ // order from the latest to the first insertion to not break other positions
+ replacements.sort(([leftStart], [rightStart]) => rightStart - leftStart);
+ for (const [start, end, fragment] of replacements) {
+ const before = expression.slice(0, start);
+ const after = expression.slice(end);
+ expression = before + fragment + after;
+ }
+ return expression;
+};
+
+/** Parse an array expression into its individual element expressions. */
+export const parseArrayExpression = (expression: string) => {
+ const items: string[] = [];
+ let root;
+ try {
+ root = parseCompleteExpression(expression);
+ } catch {
+ return;
+ }
+ if (root.type !== "ArrayExpression") {
+ return;
+ }
+ for (const element of root.elements) {
+ if (element === null || element.type === "SpreadElement") {
+ return;
+ }
+ items.push(expression.slice(element.start, element.end));
+ }
+ return items;
+};
+
+/** Parse a complete object expression into its property expressions. */
+export const parseExpressionObject = (expression: string) => {
+ const fields = new Map<string, string>();
+ let root;
+ try {
+ root = parseCompleteExpression(expression, { preserveParens: true });
+ } catch {
+ return;
+ }
+ while (root.type === "ParenthesizedExpression") {
+ root = root.expression;
+ }
+ if (root.type !== "ObjectExpression") {
+ return;
+ }
+ for (const property of root.properties) {
+ if (property.type === "SpreadElement" || property.computed) {
+ return;
+ }
+ const key =
+ property.key.type === "Identifier"
+ ? property.key.name
+ : property.key.type === "Literal" &&
+ typeof property.key.value === "string"
+ ? property.key.value
+ : undefined;
+ if (key === undefined || fields.has(key)) {
+ return;
+ }
+ fields.set(key, expression.slice(property.value.start, property.value.end));
+ }
+ return fields;
+};
+
+const formatObjectPropertyKey = (key: string) => {
+ const source = `{${key}: 0}`;
+ try {
+ const root = parseExpressionAt(source, 0, { ecmaVersion: "latest" });
+ const property =
+ root.type === "ObjectExpression" ? root.properties[0] : undefined;
+ if (
+ root.type === "ObjectExpression" &&
+ root.end === source.length &&
+ root.properties.length === 1 &&
+ property?.type === "Property" &&
+ property.computed === false &&
+ property.method === false &&
+ property.shorthand === false &&
+ property.key.type === "Identifier" &&
+ property.key.start === 1 &&
+ property.key.end === key.length + 1
+ ) {
+ return key;
+ }
+ } catch {
+ // Property names outside JavaScript's identifier grammar remain quoted.
+ }
+ return JSON.stringify(key);
+};
+
+/** Generate property expressions as a readable JavaScript object expression. */
+export const generateObjectExpression = (
+ fields: ReadonlyMap<string, string>
+) => {
+ let expression = "{\n";
+ for (const [key, value] of fields) {
+ const indentedValue = value.replaceAll("\n", "\n ");
+ expression += ` ${formatObjectPropertyKey(key)}: ${indentedValue},\n`;
+ }
+ return `${expression}}`;
+};
+
+/** Generate a JSON value as readable JavaScript expression source. */
+export const generateJsonExpression = (value: unknown): string => {
+ if (
+ value === null ||
+ typeof value === "boolean" ||
+ typeof value === "string"
+ ) {
+ return JSON.stringify(value);
+ }
+ if (typeof value === "number" && Number.isFinite(value)) {
+ return JSON.stringify(value);
+ }
+ if (Array.isArray(value)) {
+ return `[${value.map(generateJsonExpression).join(", ")}]`;
+ }
+ if (typeof value === "object") {
+ const prototype = Object.getPrototypeOf(value);
+ if (prototype !== Object.prototype && prototype !== null) {
+ throw new Error("Only JSON values can be converted to expression source");
+ }
+ return generateObjectExpression(
+ new Map(
+ Object.entries(value).map(([key, item]) => [
+ key,
+ generateJsonExpression(item),
+ ])
+ )
+ );
+ }
+ throw new Error("Only JSON values can be converted to expression source");
+};
+
+type ParsedJsonExpression =
+ | { success: true; value: unknown }
+ | { success: false };
+
+const parseJsonNode = (node: Expression): ParsedJsonExpression => {
+ if (node.type === "Literal") {
+ if (
+ node.regex !== undefined ||
+ typeof node.value === "bigint" ||
+ (typeof node.value === "number" && Number.isFinite(node.value) === false)
+ ) {
+ return { success: false };
+ }
+ return { success: true, value: node.value };
+ }
+ if (
+ node.type === "UnaryExpression" &&
+ node.operator === "-" &&
+ node.argument.type === "Literal" &&
+ typeof node.argument.value === "number" &&
+ Number.isFinite(node.argument.value)
+ ) {
+ return { success: true, value: -node.argument.value };
+ }
+ if (node.type === "ArrayExpression") {
+ const value = [];
+ for (const element of node.elements) {
+ if (element === null || element.type === "SpreadElement") {
+ return { success: false };
+ }
+ const parsed = parseJsonNode(element);
+ if (parsed.success === false) {
+ return parsed;
+ }
+ value.push(parsed.value);
+ }
+ return { success: true, value };
+ }
+ if (node.type === "ObjectExpression") {
+ const entries: [string, unknown][] = [];
+ const keys = new Set<string>();
+ for (const property of node.properties) {
+ if (
+ property.type === "SpreadElement" ||
+ property.computed ||
+ property.method ||
+ property.shorthand
+ ) {
+ return { success: false };
+ }
+ const key =
+ property.key.type === "Identifier"
+ ? property.key.name
+ : property.key.type === "Literal" &&
+ typeof property.key.value === "string"
+ ? property.key.value
+ : undefined;
+ const parsed = parseJsonNode(property.value);
+ if (key === undefined || keys.has(key) || parsed.success === false) {
+ return { success: false };
+ }
+ keys.add(key);
+ entries.push([key, parsed.value]);
+ }
+ return { success: true, value: Object.fromEntries(entries) };
+ }
+ return { success: false };
+};
+
+/** Parse JSON-compatible JavaScript expression source without evaluating it. */
+export const parseJsonExpression = (expression: string | undefined) => {
+ if (expression === undefined) {
+ return;
+ }
+ try {
+ const node = parseCompleteExpression(expression);
+ const parsed = parseJsonNode(node);
+ return parsed.success ? parsed.value : undefined;
+ } catch {
+ return;
+ }
+};
diff --git a/packages/expression/tsconfig.dts.json b/packages/expression/tsconfig.dts.json
new file mode 100644
index 0000000000..55fefbdc46
--- /dev/null
+++ b/packages/expression/tsconfig.dts.json
@@ -0,0 +1,9 @@
+{
+ "extends": "./tsconfig.json",
+ "include": ["src/index.ts"],
+ "compilerOptions": {
+ "noCheck": true,
+ "declarationDir": "lib/types",
+ "rootDir": "./src"
+ }
+}
diff --git a/packages/expression/tsconfig.json b/packages/expression/tsconfig.json
new file mode 100644
index 0000000000..ec19b304db
--- /dev/null
+++ b/packages/expression/tsconfig.json
@@ -0,0 +1,4 @@
+{
+ "extends": "@webstudio-is/tsconfig/base.json",
+ "include": ["src/**/*.ts", "../../@types/**/*.d.ts"]
+}
diff --git a/packages/expression/vitest.config.ts b/packages/expression/vitest.config.ts
new file mode 100644
index 0000000000..e4d2f2ea41
--- /dev/null
+++ b/packages/expression/vitest.config.ts
@@ -0,0 +1,16 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ coverage: {
+ provider: "v8",
+ include: ["src/index.ts"],
+ thresholds: {
+ branches: 97,
+ functions: 95,
+ lines: 99,
+ statements: 99,
+ },
+ },
+ },
+});
diff --git a/packages/fonts/src/schema.ts b/packages/fonts/src/schema.ts
index 4b7ca03944..ac01491b31 100644
--- a/packages/fonts/src/schema.ts
+++ b/packages/fonts/src/schema.ts
@@ -45,11 +45,16 @@ export const fontMetaStatic = z.object({
export type FontMetaStatic = z.infer<typeof fontMetaStatic>;
-const fontMetaVariable = z.object({
+export const fontMetaVariable = z.object({
family: z.string(),
variationAxes: variationAxes,
});
export const fontMeta = z.union([fontMetaStatic, fontMetaVariable]);
+export const fontMetaUpdate = z.union([
+ fontMetaStatic.partial().strict(),
+ fontMetaVariable.partial().strict(),
+]);
+
export type FontMeta = z.infer<typeof fontMeta>;
diff --git a/packages/http-client/src/index.test.ts b/packages/http-client/src/index.test.ts
index 8b94078425..dc909ecbc7 100644
--- a/packages/http-client/src/index.test.ts
+++ b/packages/http-client/src/index.test.ts
@@ -17,6 +17,7 @@ import {
bindProps,
cloneInstance,
createAssetFolder,
+ createProjectAssetFolder,
createBreakpoint,
createPageFromTemplate,
createDesignTokens,
@@ -32,6 +33,8 @@ import {
deleteCssVariables,
deleteAssetFolder,
deleteAssets,
+ deleteProjectAsset,
+ deleteProjectAssetFolder,
deleteBreakpoint,
deleteDomain,
deletePage,
@@ -56,6 +59,8 @@ import {
getBuildPatchSummary,
getMarketplaceProduct,
getProjectPermissions,
+ getProjectAsset,
+ getProjectAssetFolder,
getProjectSettings,
getStyleDeclarations,
inspectInstance,
@@ -65,6 +70,8 @@ import {
importProjectBundle,
importProjectBundleWithAssets,
listAssets,
+ listProjectAssets,
+ listProjectAssetFolders,
listAssetFolders,
listBreakpoints,
listDesignTokens,
@@ -83,6 +90,7 @@ import {
loadProjectBundleByProjectId,
moveInstance,
publish,
+ readProjectAssetContent,
parseBuildPatchTransactions,
parseBuilderUrl,
toLocalProjectBundle,
@@ -96,6 +104,8 @@ import {
rewriteCssVariableRefs,
updateDesignTokenStyles,
updateAssetFolder,
+ updateProjectAsset,
+ updateProjectAssetFolder,
updateProjectAssetContent,
updateDomain,
updateBreakpoint,
@@ -1106,7 +1116,7 @@ test("summarizes build patch transactions", () => {
test("uploads assets as binary requests", async () => {
const fetch = vi.fn().mockResolvedValue(
- new Response(JSON.stringify({ ok: true }), {
+ new Response(JSON.stringify({ uploadedAssets: [], deduplicated: false }), {
headers: {
"content-type": "application/json",
},
@@ -1140,7 +1150,7 @@ test("uploads assets as binary requests", async () => {
expect(fetch).toHaveBeenCalledOnce();
const [url, init] = fetch.mock.calls[0] as [URL, RequestInit];
expect(url.href).toBe(
- "https://apps.webstudio.is/rest/assets/image.png?projectId=090e6e14-ae50-4b2e-bd22-71733cec05bb&type=image&folderId=campaign&width=10&height=20&format=png"
+ "https://apps.webstudio.is/rest/assets/uploads/image.png?projectId=090e6e14-ae50-4b2e-bd22-71733cec05bb&type=image&folderId=campaign&width=10&height=20&format=png"
);
expect(init.method).toBe("POST");
expect(init.body).toBe(file);
@@ -1154,6 +1164,27 @@ test("uploads assets as binary requests", async () => {
);
});
+test("rejects malformed successful asset upload responses", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ ok: true }), {
+ headers: { "content-type": "application/json" },
+ })
+ )
+ );
+
+ await expect(
+ uploadAsset({
+ ...apiParams,
+ upload: {
+ asset: createImageAssetFixture(),
+ data: new Uint8Array([1, 2, 3]),
+ },
+ })
+ ).rejects.toThrow("Assets API returned an invalid upload response");
+});
+
test("requests a forced asset upload and exposes deduplication", async () => {
const asset = {
id: "asset-1",
@@ -1256,6 +1287,42 @@ test("reports asset upload errors", async () => {
).rejects.toThrow("Upload failed");
});
+test("rejects unsuccessful asset uploads without a structured error", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({}), {
+ status: 500,
+ headers: { "content-type": "application/json" },
+ })
+ )
+ );
+
+ await expect(
+ uploadAsset({
+ authToken: "token",
+ origin: "https://apps.webstudio.is",
+ projectId: "project-id",
+ upload: {
+ asset: {
+ id: "asset-id",
+ projectId: "project-id",
+ type: "file",
+ name: "document.pdf",
+ format: "pdf",
+ size: 3,
+ meta: {},
+ createdAt: "2024-01-01T00:00:00.000Z",
+ },
+ data: new Uint8Array([1, 2, 3]),
+ },
+ })
+ ).rejects.toMatchObject({
+ message: "Assets API request failed",
+ status: 500,
+ });
+});
+
test("uploads assets with one retry and aggregated failures", async () => {
const asset = createImageAssetFixture({ name: "image.png" });
const otherAsset = createImageAssetFixture({
@@ -1269,9 +1336,12 @@ test("uploads assets with one retry and aggregated failures", async () => {
const attempt = (attempts.get(assetName) ?? 0) + 1;
attempts.set(assetName, attempt);
if (assetName === "image.png" && attempt === 2) {
- return new Response(JSON.stringify({ ok: true }), {
- headers: { "content-type": "application/json" },
- });
+ return new Response(
+ JSON.stringify({ uploadedAssets: [asset], deduplicated: false }),
+ {
+ headers: { "content-type": "application/json" },
+ }
+ );
}
return new Response(
JSON.stringify({
@@ -1308,6 +1378,7 @@ test("keeps uploaded assets in input order", async () => {
return new Response(
JSON.stringify({
uploadedAssets: [name === "first.png" ? first : second],
+ deduplicated: false,
}),
{
headers: { "content-type": "application/json" },
@@ -1341,6 +1412,7 @@ test("serializes uploads with identical content", async () => {
return new Response(
JSON.stringify({
uploadedAssets: [name === "first.png" ? first : second],
+ deduplicated: false,
}),
{ headers: { "content-type": "application/json" } }
);
@@ -1365,9 +1437,10 @@ test("retries local asset reads before reporting an upload failure", async () =>
"fetch",
vi.fn(
async () =>
- new Response(JSON.stringify({ uploadedAssets: [asset] }), {
- headers: { "content-type": "application/json" },
- })
+ new Response(
+ JSON.stringify({ uploadedAssets: [asset], deduplicated: false }),
+ { headers: { "content-type": "application/json" } }
+ )
)
);
@@ -1392,9 +1465,13 @@ test("uploads project asset descriptors with local data readers", async () => {
const uploadedAsset = createImageAssetFixture({ name: "image.png" });
const fetch = vi.fn(
async () =>
- new Response(JSON.stringify({ uploadedAssets: [uploadedAsset] }), {
- headers: { "content-type": "application/json" },
- })
+ new Response(
+ JSON.stringify({
+ uploadedAssets: [uploadedAsset],
+ deduplicated: false,
+ }),
+ { headers: { "content-type": "application/json" } }
+ )
);
vi.stubGlobal("fetch", fetch);
@@ -1496,6 +1573,163 @@ test("surfaces asset content revision conflicts", async () => {
).rejects.toMatchObject({ message: "File changed", status: 409 });
});
+test("updates asset metadata through the unified Assets endpoint", async () => {
+ const updated = createImageAssetFixture({ id: "asset-id" });
+ const request = vi.fn(
+ async () =>
+ new Response(JSON.stringify({ asset: updated }), {
+ headers: { "content-type": "application/json" },
+ })
+ );
+
+ await expect(
+ updateProjectAsset({
+ ...apiParams,
+ assetId: "asset/id",
+ values: { filename: "Campaign", folderId: null },
+ request,
+ })
+ ).resolves.toEqual({ asset: updated });
+
+ const [url, init] = request.mock.calls[0] as unknown as [URL, RequestInit];
+ expect(url.pathname).toBe("/rest/assets/asset%2Fid");
+ expect(url.searchParams.get("projectId")).toBe(apiParams.projectId);
+ expect(init).toMatchObject({
+ method: "PATCH",
+ body: JSON.stringify({ filename: "Campaign", folderId: null }),
+ });
+ expect(new Headers(init.headers).get("x-auth-token")).toBe(
+ apiParams.authToken
+ );
+});
+
+test("deletes an asset through the unified Assets endpoint", async () => {
+ const request = vi.fn(async () => new Response(null, { status: 204 }));
+
+ await expect(
+ deleteProjectAsset({
+ ...apiParams,
+ assetId: "asset/id",
+ request,
+ })
+ ).resolves.toBeUndefined();
+
+ const [url, init] = request.mock.calls[0] as unknown as [URL, RequestInit];
+ expect(url.pathname).toBe("/rest/assets/asset%2Fid");
+ expect(url.searchParams.get("projectId")).toBe(apiParams.projectId);
+ expect(init).toMatchObject({ method: "DELETE" });
+ expect(new Headers(init.headers).get("x-auth-token")).toBe(
+ apiParams.authToken
+ );
+});
+
+test("reads asset records and ranged content through the Assets REST data plane", async () => {
+ const asset = createImageAssetFixture({ id: "asset-id" });
+ const request = vi
+ .fn<typeof fetch>()
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ assets: [asset] }), {
+ headers: { "content-type": "application/json" },
+ })
+ )
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ asset }), {
+ headers: { "content-type": "application/json" },
+ })
+ )
+ .mockResolvedValueOnce(new Response("data", { status: 206 }));
+
+ await expect(listProjectAssets({ ...apiParams, request })).resolves.toEqual({
+ assets: [asset],
+ });
+ await expect(
+ getProjectAsset({ ...apiParams, assetId: "asset/id", request })
+ ).resolves.toEqual({ asset });
+ await expect(
+ readProjectAssetContent({
+ ...apiParams,
+ assetId: "asset/id",
+ range: { offset: 2, length: 4 },
+ request,
+ })
+ ).resolves.toMatchObject({ status: 206 });
+
+ const [contentUrl, contentInit] = request.mock.calls[2] as [URL, RequestInit];
+ expect(contentUrl.pathname).toBe("/rest/assets/asset%2Fid/content");
+ expect(new Headers(contentInit.headers).get("range")).toBe("bytes=2-5");
+});
+
+test("manages folders through the Assets REST data plane", async () => {
+ const folder = {
+ id: "folder-1",
+ projectId: apiParams.projectId,
+ name: "Blog",
+ createdAt: "2026-07-25T00:00:00.000Z",
+ };
+ const request = vi
+ .fn<typeof fetch>()
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ folders: [folder] }), {
+ headers: { "content-type": "application/json" },
+ })
+ )
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ folder }), {
+ headers: { "content-type": "application/json" },
+ })
+ )
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ folder }), {
+ status: 201,
+ headers: { "content-type": "application/json" },
+ })
+ )
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ folder: { ...folder, name: "Posts" } }), {
+ headers: { "content-type": "application/json" },
+ })
+ )
+ .mockResolvedValueOnce(new Response(null, { status: 204 }));
+
+ await expect(
+ listProjectAssetFolders({ ...apiParams, request })
+ ).resolves.toEqual({ folders: [folder] });
+ await expect(
+ getProjectAssetFolder({
+ ...apiParams,
+ folderId: "folder/id",
+ request,
+ })
+ ).resolves.toEqual({ folder });
+ await expect(
+ createProjectAssetFolder({ ...apiParams, name: "Blog", request })
+ ).resolves.toEqual({ folder });
+ await expect(
+ updateProjectAssetFolder({
+ ...apiParams,
+ folderId: "folder/id",
+ values: { name: "Posts" },
+ request,
+ })
+ ).resolves.toEqual({ folder: { ...folder, name: "Posts" } });
+ await expect(
+ deleteProjectAssetFolder({
+ ...apiParams,
+ folderId: "folder/id",
+ request,
+ })
+ ).resolves.toBeUndefined();
+
+ expect((request.mock.calls[0]?.[0] as URL).pathname).toBe(
+ "/rest/assets/folders"
+ );
+ expect((request.mock.calls[3]?.[0] as URL).pathname).toBe(
+ "/rest/assets/folders/folder%2Fid"
+ );
+ expect(request.mock.calls[3]?.[1]).toMatchObject({ method: "PATCH" });
+ expect(request.mock.calls[4]?.[1]).toMatchObject({ method: "DELETE" });
+});
+
test("keeps browser asset content updates on the requested origin", async () => {
const revision = {
...createImageAssetFixture({ id: "asset-id" }),
@@ -1529,8 +1763,26 @@ test("keeps browser asset content updates on the requested origin", async () =>
});
test("normalizes synced project bundles for local storage", () => {
+ const index = {
+ format: "webstudio-content-database" as const,
+ version: 1 as const,
+ assetRevision: `sha256:${"b".repeat(64)}`,
+ documents: [],
+ fieldCatalog: {
+ format: "webstudio-builder-asset-field-catalog" as const,
+ version: 1 as const,
+ canonicalRevision: `sha256:${"b".repeat(64)}`,
+ documentCount: 0,
+ fields: {},
+ },
+ integrity: {
+ algorithm: "sha256" as const,
+ checksum: `sha256:${"c".repeat(64)}`,
+ },
+ };
const bundle = createPublishedProjectBundleFixture({
bundleVersion: "bundle-old",
+ assetIndex: index,
assetFolders: [
{
id: "folder-1",
@@ -1551,6 +1803,7 @@ test("normalizes synced project bundles for local storage", () => {
user: bundle.user,
projectDomain: bundle.projectDomain,
projectTitle: bundle.projectTitle,
+ assetIndex: bundle.assetIndex,
origin: bundle.origin,
});
});
@@ -1625,6 +1878,7 @@ test("imports project bundle through staged upload", async () => {
projectId: "project-id",
data: {
largeContent: "x".repeat(3 * 1024 * 1024 + 1),
+ assetIndex: { marker: "derived-index-marker" },
} as unknown as PublishedProjectBundle,
})
).resolves.toEqual({ version: 2 });
@@ -1635,6 +1889,9 @@ test("imports project bundle through staged upload", async () => {
}
expect(uploadChunks).toHaveLength(2);
+ expect(Buffer.concat(uploadChunks).toString("utf8")).not.toContain(
+ "derived-index-marker"
+ );
expect(JSON.stringify(trpcBody)).toContain('"uploadId":"upload-id"');
expect(JSON.stringify(trpcBody)).not.toContain("largeContent");
});
@@ -1663,7 +1920,7 @@ test("imports project bundle with assets and retries missing asset uploads", asy
if (
request.method === "POST" &&
- url.pathname === "/rest/assets/image.png"
+ url.pathname === "/rest/assets/uploads/image.png"
) {
uploadAttempts += 1;
uploadUrls.push(url.href);
@@ -1677,6 +1934,7 @@ test("imports project bundle with assets and retries missing asset uploads", asy
name: "image_destination.png",
}),
],
+ deduplicated: false,
})
);
return;
diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.ts
index 33430bc64a..1cab6a9835 100644
--- a/packages/http-client/src/index.ts
+++ b/packages/http-client/src/index.ts
@@ -1,6 +1,24 @@
import { createTRPCUntypedClient, httpBatchLink } from "@trpc/client";
import { Upload } from "tus-js-client";
-import { getAssetContentHash } from "@webstudio-is/sdk";
+import {
+ getAssetContentHash,
+ type AssetQueryResourceConfigurationInput,
+ type AssetFolder,
+} from "@webstudio-is/sdk";
+import {
+ type AssetFolderUpdateRequest,
+ type AssetMetadataUpdate,
+ type AssetQueryRequestInput,
+ type AssetUploadResult,
+} from "@webstudio-is/protocol/asset-resource-api";
+import {
+ assetsApiUrl,
+ assetsFoldersApiUrl,
+ getAssetApiUrl,
+ getAssetContentApiUrl,
+ getAssetFolderApiUrl,
+ getAssetUploadApiUrl,
+} from "@webstudio-is/sdk/runtime";
import {
apiClientHeader,
apiClientVersionHeader,
@@ -342,10 +360,6 @@ type AssetUploadDescriptor = {
};
type UploadedAsset = Asset & { deduplicated?: boolean };
-type AssetUploadResult = {
- uploadedAssets?: Asset[];
- deduplicated?: boolean;
-};
type AssetUploadBatchResult =
| { status: "fulfilled"; uploadedAssets: UploadedAsset[] }
| { status: "rejected"; asset: Asset; error: unknown };
@@ -379,10 +393,7 @@ const getAssetUploadUrl = ({
projectId: string;
}) => {
const { sourceOrigin } = parseBuilderUrl(origin);
- const url = new URL(
- `/rest/assets/${encodeURIComponent(asset.name)}`,
- sourceOrigin
- );
+ const url = new URL(getAssetUploadApiUrl(asset.name), sourceOrigin);
url.searchParams.set("projectId", projectId);
url.searchParams.set("type", asset.type);
if (asset.folderId !== undefined) {
@@ -407,7 +418,8 @@ export const uploadAsset = async (
}
): Promise<Asset[]> => {
const { authToken, headers, origin, projectId, upload } = params;
- const response = await fetchJsonResponse(
+ const result = await requestAssetRestJson<AssetUploadResult>(
+ fetchJsonResponse,
getAssetUploadUrl({
asset: upload.asset,
force: upload.force,
@@ -426,27 +438,18 @@ export const uploadAsset = async (
}),
}
);
- const result = (await response.json()) as
- | AssetUploadResult
- | {
- errors?: string;
- };
if (
- typeof result === "object" &&
- result !== null &&
- "errors" in result &&
- typeof result.errors === "string"
+ Array.isArray(result.uploadedAssets) === false ||
+ typeof result.deduplicated !== "boolean"
) {
- throw new Error(result.errors);
- }
- return "uploadedAssets" in result && Array.isArray(result.uploadedAssets)
- ? result.deduplicated === true
- ? result.uploadedAssets.map((asset) => ({
- ...asset,
- deduplicated: true,
- }))
- : result.uploadedAssets
- : [];
+ throw new Error("Assets API returned an invalid upload response");
+ }
+ return result.deduplicated
+ ? result.uploadedAssets.map((asset) => ({
+ ...asset,
+ deduplicated: true,
+ }))
+ : result.uploadedAssets;
};
export const uploadAssets = async (
@@ -631,11 +634,90 @@ export const uploadProjectAssets = async (
return { uploaded };
};
-type AssetContentUpdateResult =
- | { asset: Asset }
- | {
- errors: string;
- };
+const createAssetRestUrl = ({
+ origin,
+ requestOrigin,
+ path,
+ projectId,
+}: {
+ origin: string;
+ requestOrigin?: string;
+ path: string;
+ projectId: string;
+}) => {
+ const { sourceOrigin } = parseBuilderUrl(origin);
+ const url = new URL(path, requestOrigin ?? sourceOrigin);
+ url.searchParams.set("projectId", projectId);
+ return url;
+};
+
+const createAssetRestHeaders = (
+ {
+ authToken,
+ headers,
+ }: {
+ authToken?: string;
+ headers?: RequestHeaders;
+ },
+ contentType?: string
+) =>
+ createHeaders({
+ ...headers,
+ "x-auth-token": authToken,
+ "content-type": contentType,
+ });
+
+const getAssetRestFailure = async (
+ response: Response,
+ fallback: string
+): Promise<Error & { status: number }> => {
+ let message = fallback;
+ try {
+ const result = (await response.json()) as { errors?: unknown };
+ if (typeof result.errors === "string") {
+ message = result.errors;
+ }
+ } catch {
+ // Preserve the HTTP status when the server cannot return a JSON error.
+ }
+ return Object.assign(new Error(message), { status: response.status });
+};
+
+const requestAssetRestJson = async <Result>(
+ request: typeof fetch,
+ url: URL,
+ init: RequestInit
+): Promise<Result> => {
+ const response = await request(url, init);
+ if (response.ok === false) {
+ throw await getAssetRestFailure(response, "Assets API request failed");
+ }
+ const result = (await response.json()) as Result | { errors?: unknown };
+ if (typeof result === "object" && result !== null && "errors" in result) {
+ throw Object.assign(
+ new Error(
+ typeof result.errors === "string"
+ ? result.errors
+ : "Assets API request failed"
+ ),
+ { status: response.status }
+ );
+ }
+ return result as Result;
+};
+
+const requestAssetRest = async (
+ request: typeof fetch,
+ url: URL,
+ init: RequestInit,
+ failureMessage: string
+) => {
+ const response = await request(url, init);
+ if (response.ok === false) {
+ throw await getAssetRestFailure(response, failureMessage);
+ }
+ return response;
+};
export const updateProjectAssetContent = async (
params: Omit<AuthProjectParams, "authToken"> & {
@@ -648,27 +730,201 @@ export const updateProjectAssetContent = async (
}
): Promise<{ asset: Asset }> => {
const request = params.request ?? fetch;
- const { sourceOrigin } = parseBuilderUrl(params.origin);
- const url = new URL(
- `/rest/assets/${encodeURIComponent(params.assetId)}/content`,
- params.requestOrigin ?? sourceOrigin
- );
- url.searchParams.set("projectId", params.projectId);
+ const url = createAssetRestUrl({
+ ...params,
+ path: getAssetContentApiUrl(params.assetId),
+ });
url.searchParams.set("expectedName", params.expectedName);
- const response = await request(url, {
+ return await requestAssetRestJson(request, url, {
method: "PUT",
body: await params.readAssetData(),
- headers: createHeaders({
- ...params.headers,
- "x-auth-token": params.authToken,
- "content-type": "application/octet-stream",
- }),
+ headers: createAssetRestHeaders(params, "application/octet-stream"),
});
- const result = (await response.json()) as AssetContentUpdateResult;
- if ("errors" in result) {
- throw Object.assign(new Error(result.errors), { status: response.status });
+};
+
+export const updateProjectAsset = async (
+ params: Omit<AuthProjectParams, "authToken"> & {
+ authToken?: string;
+ assetId: string;
+ values: AssetMetadataUpdate;
+ request?: typeof fetch;
+ requestOrigin?: string;
}
- return result;
+): Promise<{ asset: Asset }> => {
+ const request = params.request ?? fetch;
+ return await requestAssetRestJson(
+ request,
+ createAssetRestUrl({ ...params, path: getAssetApiUrl(params.assetId) }),
+ {
+ method: "PATCH",
+ body: JSON.stringify(params.values),
+ headers: createAssetRestHeaders(params, "application/json"),
+ }
+ );
+};
+
+export const deleteProjectAsset = async (
+ params: Omit<AuthProjectParams, "authToken"> & {
+ authToken?: string;
+ assetId: string;
+ request?: typeof fetch;
+ requestOrigin?: string;
+ }
+) => {
+ await requestAssetRest(
+ params.request ?? fetch,
+ createAssetRestUrl({ ...params, path: getAssetApiUrl(params.assetId) }),
+ {
+ method: "DELETE",
+ headers: createAssetRestHeaders(params),
+ },
+ "Asset deletion failed"
+ );
+};
+
+export const listProjectAssets = async (
+ params: AuthProjectParams & {
+ request?: typeof fetch;
+ requestOrigin?: string;
+ }
+): Promise<{ assets: Asset[] }> =>
+ await requestAssetRestJson(
+ params.request ?? fetch,
+ createAssetRestUrl({ ...params, path: assetsApiUrl }),
+ { headers: createAssetRestHeaders(params) }
+ );
+
+export const getProjectAsset = async (
+ params: AuthProjectParams & {
+ assetId: string;
+ request?: typeof fetch;
+ requestOrigin?: string;
+ }
+): Promise<{ asset: Asset }> =>
+ await requestAssetRestJson(
+ params.request ?? fetch,
+ createAssetRestUrl({ ...params, path: getAssetApiUrl(params.assetId) }),
+ { headers: createAssetRestHeaders(params) }
+ );
+
+export const readProjectAssetContent = async (
+ params: AuthProjectParams & {
+ assetId: string;
+ range?: { offset: number; length: number };
+ request?: typeof fetch;
+ requestOrigin?: string;
+ }
+) => {
+ const response = await (params.request ?? fetch)(
+ createAssetRestUrl({
+ ...params,
+ path: getAssetContentApiUrl(params.assetId),
+ }),
+ {
+ headers: createHeaders({
+ ...params.headers,
+ "x-auth-token": params.authToken,
+ range:
+ params.range === undefined
+ ? undefined
+ : `bytes=${params.range.offset}-${
+ params.range.offset + params.range.length - 1
+ }`,
+ }),
+ }
+ );
+ if (response.ok === false) {
+ throw await getAssetRestFailure(response, "Asset content download failed");
+ }
+ return response;
+};
+
+export const listProjectAssetFolders = async (
+ params: AuthProjectParams & {
+ request?: typeof fetch;
+ requestOrigin?: string;
+ }
+): Promise<{ folders: AssetFolder[] }> =>
+ await requestAssetRestJson(
+ params.request ?? fetch,
+ createAssetRestUrl({ ...params, path: assetsFoldersApiUrl }),
+ { headers: createAssetRestHeaders(params) }
+ );
+
+export const getProjectAssetFolder = async (
+ params: AuthProjectParams & {
+ folderId: string;
+ request?: typeof fetch;
+ requestOrigin?: string;
+ }
+): Promise<{ folder: AssetFolder }> =>
+ await requestAssetRestJson(
+ params.request ?? fetch,
+ createAssetRestUrl({
+ ...params,
+ path: getAssetFolderApiUrl(params.folderId),
+ }),
+ { headers: createAssetRestHeaders(params) }
+ );
+
+export const createProjectAssetFolder = async (
+ params: AuthProjectParams & {
+ name: string;
+ parentId?: string;
+ request?: typeof fetch;
+ requestOrigin?: string;
+ }
+): Promise<{ folder: AssetFolder }> =>
+ await requestAssetRestJson(
+ params.request ?? fetch,
+ createAssetRestUrl({ ...params, path: assetsFoldersApiUrl }),
+ {
+ method: "POST",
+ body: JSON.stringify({ name: params.name, parentId: params.parentId }),
+ headers: createAssetRestHeaders(params, "application/json"),
+ }
+ );
+
+export const updateProjectAssetFolder = async (
+ params: AuthProjectParams & {
+ folderId: string;
+ values: AssetFolderUpdateRequest;
+ request?: typeof fetch;
+ requestOrigin?: string;
+ }
+): Promise<{ folder: AssetFolder }> =>
+ await requestAssetRestJson(
+ params.request ?? fetch,
+ createAssetRestUrl({
+ ...params,
+ path: getAssetFolderApiUrl(params.folderId),
+ }),
+ {
+ method: "PATCH",
+ body: JSON.stringify(params.values),
+ headers: createAssetRestHeaders(params, "application/json"),
+ }
+ );
+
+export const deleteProjectAssetFolder = async (
+ params: AuthProjectParams & {
+ folderId: string;
+ request?: typeof fetch;
+ requestOrigin?: string;
+ }
+) => {
+ await requestAssetRest(
+ params.request ?? fetch,
+ createAssetRestUrl({
+ ...params,
+ path: getAssetFolderApiUrl(params.folderId),
+ }),
+ {
+ method: "DELETE",
+ headers: createAssetRestHeaders(params),
+ },
+ "Asset folder deletion failed"
+ );
};
export const loadProjectBundleByBuildId = async (
@@ -691,10 +947,11 @@ export const loadProjectBundleByBuildId = async (
? { "x-auth-token": params.authToken }
: {};
- const data = await createTrpcClient(params.origin, {
+ const client = createTrpcClient(params.origin, {
...params.headers,
...headers,
- }).query("build.loadProjectBundleByBuildId", {
+ });
+ const data = await client.query("build.loadProjectBundleByBuildId", {
buildId: params.buildId,
bundleVersion: currentBundleVersion,
});
@@ -704,13 +961,11 @@ export const loadProjectBundleByBuildId = async (
export const loadProjectBundleByProjectId = async (
params: AuthProjectParams
): Promise<PublishedProjectBundle> => {
- const data = await createAuthTrpcClient(params).query(
- "build.loadProjectBundleByProjectId",
- {
- projectId: params.projectId,
- bundleVersion: currentBundleVersion,
- }
- );
+ const client = createAuthTrpcClient(params);
+ const data = await client.query("build.loadProjectBundleByProjectId", {
+ projectId: params.projectId,
+ bundleVersion: currentBundleVersion,
+ });
return publishedProjectBundle.parse(data);
};
@@ -726,6 +981,7 @@ export const toLocalProjectBundle = (project: PublishedProjectBundle) => {
projectDomain,
projectTitle,
user,
+ assetIndex,
} = normalizedProject;
return {
bundleVersion: currentBundleVersion,
@@ -737,6 +993,7 @@ export const toLocalProjectBundle = (project: PublishedProjectBundle) => {
user,
projectDomain,
projectTitle,
+ assetIndex,
origin,
};
};
@@ -1515,7 +1772,6 @@ type VariableValueInput =
| { type: "number"; value: number }
| { type: "string"; value: string }
| { type: "boolean"; value: boolean }
- | { type: "string[]"; value: string[] }
| { type: "json"; value: unknown };
export const listVariables = projectQueryInput<
@@ -1567,6 +1823,50 @@ export const listResources = projectQueryInput<
}
>("list-resources");
+export const listAssetsResources = projectQueryInput<
+ AuthProjectParams &
+ PaginatedQueryInput & {
+ scopeInstanceId?: string;
+ }
+>("list-assets-resources");
+
+export const getAssetsResource = projectQueryInput<
+ AuthProjectParams & { resourceId: string }
+>("get-assets-resource");
+
+export const createAssetsResource = projectMutationInput<
+ AuthProjectParams & {
+ name: string;
+ query?: AssetQueryResourceConfigurationInput;
+ scopeInstanceId: string;
+ dataSourceName?: string;
+ }
+>("create-assets-resource");
+
+export const updateAssetsResource = projectMutationInput<
+ AuthProjectParams & {
+ resourceId: string;
+ values: {
+ name?: string;
+ query?: AssetQueryResourceConfigurationInput | null;
+ };
+ scopeInstanceId?: string;
+ dataSourceName?: string;
+ }
+>("update-assets-resource");
+
+export const validateAssetQuery = projectQueryInput<
+ AuthProjectParams & { query: AssetQueryRequestInput["query"] }
+>("validate-asset-query");
+
+export const previewAssetQuery = projectQueryInput<
+ AuthProjectParams & AssetQueryRequestInput
+>("preview-asset-query");
+
+export const getAssetFieldCatalog = projectQueryInput<AuthProjectParams>(
+ "get-asset-field-catalog"
+);
+
export const createResource = projectMutationInput<
AuthProjectParams & {
resource: ResourceFieldsInput;
@@ -1733,7 +2033,10 @@ const uploadProjectBundleData = async (
) => {
const { sourceOrigin } = parseBuilderUrl(params.origin);
const endpoint = new URL(stagedUploadPath, sourceOrigin);
- const data = JSON.stringify(params.data);
+ // The asset index is derived from destination assets and must not transport
+ // stale metadata across project imports.
+ const { assetIndex: _assetIndex, ...portableData } = params.data;
+ const data = JSON.stringify(portableData);
if (new TextEncoder().encode(data).byteLength > maxProjectBundleSize) {
throw new Error(
`Project bundle is too large to import. Maximum size is ${formatMebibytes(maxProjectBundleSize)}.`
diff --git a/packages/postgrest/src/__generated__/db-types.ts b/packages/postgrest/src/__generated__/db-types.ts
index 04bf30c0e9..872158d44a 100644
--- a/packages/postgrest/src/__generated__/db-types.ts
+++ b/packages/postgrest/src/__generated__/db-types.ts
@@ -7,31 +7,6 @@ export type Json =
| Json[];
export type Database = {
- graphql_public: {
- Tables: {
- [_ in never]: never;
- };
- Views: {
- [_ in never]: never;
- };
- Functions: {
- graphql: {
- Args: {
- extensions?: Json;
- operationName?: string;
- query?: string;
- variables?: Json;
- };
- Returns: Json;
- };
- };
- Enums: {
- [_ in never]: never;
- };
- CompositeTypes: {
- [_ in never]: never;
- };
- };
public: {
Tables: {
_prisma_migrations: {
@@ -109,6 +84,41 @@ export type Database = {
},
];
};
+ AssetFileMetadata: {
+ Row: {
+ assetId: string;
+ createdAt: string;
+ document: Json;
+ projectId: string;
+ revision: string;
+ updatedAt: string;
+ };
+ Insert: {
+ assetId: string;
+ createdAt?: string;
+ document: Json;
+ projectId: string;
+ revision: string;
+ updatedAt?: string;
+ };
+ Update: {
+ assetId?: string;
+ createdAt?: string;
+ document?: Json;
+ projectId?: string;
+ revision?: string;
+ updatedAt?: string;
+ };
+ Relationships: [
+ {
+ foreignKeyName: "AssetFileMetadata_assetId_projectId_fkey";
+ columns: ["assetId", "projectId"];
+ isOneToOne: false;
+ referencedRelation: "Asset";
+ referencedColumns: ["id", "projectId"];
+ },
+ ];
+ };
AssetFolder: {
Row: {
createdAt: string;
@@ -1104,6 +1114,19 @@ export type Database = {
Args: { from_date?: string; to_date?: string };
Returns: undefined;
};
+ delete_asset_file_metadata_if_matches: {
+ Args: {
+ p_asset_id: string;
+ p_document: Json;
+ p_project_id: string;
+ p_revision: string;
+ };
+ Returns: number;
+ };
+ delete_stale_asset_file_metadata: {
+ Args: { p_asset_ids: string[]; p_project_id: string };
+ Returns: number;
+ };
domainsVirtual: {
Args: { "": Database["public"]["Tables"]["Project"]["Row"] };
Returns: {
@@ -1202,6 +1225,16 @@ export type Database = {
isSetofReturn: true;
};
};
+ replace_asset_file_metadata: {
+ Args: {
+ p_asset_id: string;
+ p_document: Json;
+ p_project_id: string;
+ p_revision: string;
+ p_source: Json;
+ };
+ Returns: boolean;
+ };
restore_development_build: {
Args: { from_build_id: string; project_id: string };
Returns: string;
@@ -1358,9 +1391,6 @@ export type CompositeTypes<
: never;
export const Constants = {
- graphql_public: {
- Enums: {},
- },
public: {
Enums: {
AuthorizationRelation: [
diff --git a/packages/postgrest/src/index.server.ts b/packages/postgrest/src/index.server.ts
index a5ad11233b..476d79c1f3 100644
--- a/packages/postgrest/src/index.server.ts
+++ b/packages/postgrest/src/index.server.ts
@@ -2,26 +2,10 @@ import type { Database } from "./__generated__/db-types";
import { PostgrestClient } from "@supabase/postgrest-js";
export type { Database } from "./__generated__/db-types";
-type DatabaseWithAssetRevision = Omit<Database, "public"> & {
- public: Omit<Database["public"], "Functions"> & {
- Functions: Database["public"]["Functions"] & {
- swap_asset_file: {
- Args: {
- asset_id: string;
- expected_name: string;
- project_id: string;
- replacement_name: string;
- };
- Returns: string;
- };
- };
- };
-};
-
-export type Client = PostgrestClient<DatabaseWithAssetRevision>;
+export type Client = PostgrestClient<Database>;
export const createClient = (url: string, apiKey: string): Client => {
- const client = new PostgrestClient<DatabaseWithAssetRevision>(url, {
+ const client = new PostgrestClient<Database>(url, {
headers: {
apikey: apiKey,
Authorization: `Bearer ${apiKey}`,
diff --git a/packages/postgrest/supabase/tests/asset-file-metadata.sql b/packages/postgrest/supabase/tests/asset-file-metadata.sql
new file mode 100644
index 0000000000..946e914b1e
--- /dev/null
+++ b/packages/postgrest/supabase/tests/asset-file-metadata.sql
@@ -0,0 +1,240 @@
+BEGIN;
+SET LOCAL search_path = pgtap, public;
+SELECT no_plan();
+
+INSERT INTO "File" (
+ "name",
+ "format",
+ "size",
+ "updatedAt",
+ "status"
+)
+VALUES (
+ 'metadata-test.md',
+ 'md',
+ 10,
+ '2026-07-18T10:00:00Z',
+ 'UPLOADED'
+);
+
+INSERT INTO "Asset" (
+ "id",
+ "projectId",
+ "name",
+ "filename"
+)
+VALUES (
+ 'metadata-test-asset',
+ 'metadata-test-project',
+ 'metadata-test.md',
+ 'post.md'
+);
+
+SELECT is(
+ replace_asset_file_metadata(
+ 'metadata-test-project',
+ 'metadata-test-asset',
+ 'revision-1',
+ '{"_id":"metadata-test-asset","revision":"revision-1"}'::JSONB,
+ '{"storageName":"metadata-test.md","fileUpdatedAt":"2026-07-18T10:00:00Z","fileSize":10,"filename":"post.md","folderId":null}'::JSONB
+ ),
+ TRUE,
+ 'A current source snapshot atomically creates canonical metadata'
+);
+
+SELECT is(
+ (
+ SELECT count(*)::INTEGER
+ FROM "AssetFileMetadata"
+ WHERE "projectId" = 'metadata-test-project'
+ AND "assetId" = 'metadata-test-asset'
+ ),
+ 1,
+ 'One asset has one active canonical revision'
+);
+
+SELECT is(
+ replace_asset_file_metadata(
+ 'metadata-test-project',
+ 'metadata-test-asset',
+ 'revision-1',
+ '{"_id":"metadata-test-asset","revision":"revision-1"}'::JSONB,
+ '{"storageName":"metadata-test.md","fileUpdatedAt":"2026-07-18T10:00:00Z","fileSize":10,"filename":"post.md","folderId":null}'::JSONB
+ ),
+ TRUE,
+ 'Repeated replacement of identical canonical metadata is accepted'
+);
+
+UPDATE "File"
+SET "size" = 11,
+ "updatedAt" = '2026-07-18T11:00:00Z'
+WHERE "name" = 'metadata-test.md';
+
+SELECT is(
+ replace_asset_file_metadata(
+ 'metadata-test-project',
+ 'metadata-test-asset',
+ 'stale-revision',
+ '{"_id":"stale"}'::JSONB,
+ '{"storageName":"metadata-test.md","fileUpdatedAt":"2026-07-18T10:00:00Z","fileSize":10,"filename":"post.md","folderId":null}'::JSONB
+ ),
+ FALSE,
+ 'A stale source snapshot cannot replace newer canonical metadata'
+);
+
+SELECT is(
+ (
+ SELECT "revision"
+ FROM "AssetFileMetadata"
+ WHERE "projectId" = 'metadata-test-project'
+ AND "assetId" = 'metadata-test-asset'
+ ),
+ 'revision-1',
+ 'Rejected stale work leaves the active revision unchanged'
+);
+
+SELECT is(
+ replace_asset_file_metadata(
+ 'metadata-test-project',
+ 'metadata-test-asset',
+ 'revision-2',
+ '{"_id":"metadata-test-asset","revision":"revision-2"}'::JSONB,
+ '{"storageName":"metadata-test.md","fileUpdatedAt":"2026-07-18T11:00:00Z","fileSize":11,"filename":"post.md","folderId":null}'::JSONB
+ ),
+ TRUE,
+ 'The current source snapshot replaces the prior revision'
+);
+
+SELECT results_eq(
+ $$
+ SELECT "revision"
+ FROM "AssetFileMetadata"
+ WHERE "projectId" = 'metadata-test-project'
+ AND "assetId" = 'metadata-test-asset'
+ $$,
+ $$ VALUES ('revision-2') $$,
+ 'Revision replacement updates the single canonical row in the same transaction'
+);
+
+SELECT is(
+ delete_stale_asset_file_metadata(
+ 'metadata-test-project',
+ ARRAY['metadata-test-asset']
+ ),
+ 0,
+ 'Stale cleanup preserves metadata for a current uploaded Markdown asset'
+);
+
+UPDATE "File"
+SET "status" = 'UPLOADING'
+WHERE "name" = 'metadata-test.md';
+
+SELECT is(
+ delete_stale_asset_file_metadata(
+ 'metadata-test-project',
+ ARRAY['metadata-test-asset']
+ ),
+ 1,
+ 'Stale cleanup removes metadata only after the source is no longer current'
+);
+
+SELECT is(
+ (
+ SELECT count(*)::INTEGER
+ FROM "AssetFileMetadata"
+ WHERE "projectId" = 'metadata-test-project'
+ ),
+ 0,
+ 'Stale cleanup removed the canonical row'
+);
+
+INSERT INTO "File" ("name", "format", "size", "updatedAt", "status")
+VALUES ('metadata-image.png', 'png', 20, '2026-07-18T12:00:00Z', 'UPLOADED');
+
+INSERT INTO "Asset" ("id", "projectId", "name", "filename")
+VALUES (
+ 'metadata-image-asset',
+ 'metadata-test-project',
+ 'metadata-image.png',
+ 'cover.png'
+);
+
+SELECT is(
+ replace_asset_file_metadata(
+ 'metadata-test-project',
+ 'metadata-image-asset',
+ 'image-revision',
+ '{"_id":"metadata-image-asset","revision":"image-revision"}'::JSONB,
+ '{"storageName":"metadata-image.png","fileUpdatedAt":"2026-07-18T12:00:00Z","fileSize":20,"filename":"cover.png","folderId":null}'::JSONB
+ ),
+ TRUE,
+ 'Canonical metadata supports any uploaded asset type'
+);
+
+SELECT is(
+ delete_stale_asset_file_metadata(
+ 'metadata-test-project',
+ ARRAY['metadata-image-asset']
+ ),
+ 0,
+ 'Stale cleanup preserves metadata for an uploaded non-Markdown asset'
+);
+
+SELECT is(
+ (
+ SELECT count(*)::INTEGER
+ FROM "AssetFileMetadata"
+ WHERE "projectId" = 'metadata-test-project'
+ AND "assetId" = 'metadata-image-asset'
+ ),
+ 1,
+ 'Non-Markdown canonical metadata remains available'
+);
+
+SELECT is(
+ delete_asset_file_metadata_if_matches(
+ 'metadata-test-project',
+ 'metadata-image-asset',
+ 'image-revision',
+ '{"_id":"metadata-image-asset","revision":"different-document"}'::JSONB
+ ),
+ 0,
+ 'Exact cleanup preserves metadata that does not match the failed snapshot'
+);
+
+SELECT is(
+ delete_asset_file_metadata_if_matches(
+ 'metadata-test-project',
+ 'metadata-image-asset',
+ 'image-revision',
+ '{"_id":"metadata-image-asset","revision":"image-revision"}'::JSONB
+ ),
+ 1,
+ 'Failed re-indexing removes the exact obsolete snapshot while the asset remains uploaded'
+);
+
+SELECT is(
+ replace_asset_file_metadata(
+ 'metadata-test-project',
+ 'metadata-image-asset',
+ 'new-image-revision',
+ '{"_id":"metadata-image-asset","revision":"new-image-revision"}'::JSONB,
+ '{"storageName":"metadata-image.png","fileUpdatedAt":"2026-07-18T12:00:00Z","fileSize":20,"filename":"cover.png","folderId":null}'::JSONB
+ ),
+ TRUE,
+ 'A concurrent repair can install the current revision'
+);
+
+SELECT is(
+ delete_asset_file_metadata_if_matches(
+ 'metadata-test-project',
+ 'metadata-image-asset',
+ 'image-revision',
+ '{"_id":"metadata-image-asset","revision":"image-revision"}'::JSONB
+ ),
+ 0,
+ 'Exact cleanup preserves metadata installed by a concurrent repair'
+);
+
+SELECT * FROM finish();
+ROLLBACK;
diff --git a/packages/prisma-client/migrations-cli/commands.ts b/packages/prisma-client/migrations-cli/commands.ts
index 1bb6681de8..b1f1964da9 100644
--- a/packages/prisma-client/migrations-cli/commands.ts
+++ b/packages/prisma-client/migrations-cli/commands.ts
@@ -7,12 +7,11 @@ import { umzug } from "./umzug";
import * as logger from "./logger";
import * as args from "./args";
import { UserError } from "./errors";
+import { cliDiff } from "./prisma-command";
+import { migrationsDir, schemaFilePath } from "./prisma-paths";
-const templateFilePath = path.join(
- prismaMigrations.migrationsDir,
- "template.txt"
-);
-const lockfilePath = path.join(prismaMigrations.migrationsDir, "lockfile");
+const templateFilePath = path.join(migrationsDir, "template.txt");
+const lockfilePath = path.join(migrationsDir, "lockfile");
const writeFile = (filePath: string, content: string) => {
const dir = path.dirname(filePath);
@@ -125,7 +124,7 @@ const isNoopSql = (sqlScript: string) => {
};
const ensureNoChangesInPrismaSchema = async () => {
- const sqlScript = await prismaMigrations.cliDiff();
+ const sqlScript = await cliDiff();
if (isNoopSql(sqlScript ?? "") === false) {
throw new UserError(
"There are changes in schema.prisma. Please create a schema migration first."
@@ -142,7 +141,7 @@ export const createSchema = async ({ name }: { name: string }) => {
// We need the database to be up to date before we can do a diff.
ensureNoPending(status);
- const sqlScript = await prismaMigrations.cliDiff();
+ const sqlScript = await cliDiff();
const migrationName = prismaMigrations.generateMigrationName(name);
@@ -172,7 +171,7 @@ export const createData = async ({ name }: { name: string }) => {
writeFile(filePath, fs.readFileSync(templateFilePath, "utf8"));
logger.info(`Created: ${filePath}`);
- let schemaContent = fs.readFileSync(prismaMigrations.schemaFilePath, "utf8");
+ let schemaContent = fs.readFileSync(schemaFilePath, "utf8");
schemaContent = `// DO NOT EDIT THIS FILE!
// This is a copy of your schema.prisma that corresponds to the state of the database
@@ -186,22 +185,16 @@ ${schemaContent}`;
`output = "client"`
);
- const schemaFilePath = path.join(
- prismaMigrations.migrationsDir,
+ const migrationSchemaFilePath = path.join(
+ migrationsDir,
migrationName,
"schema.prisma"
);
- writeFile(schemaFilePath, schemaContent);
- logger.info(`Created: ${schemaFilePath}`);
+ writeFile(migrationSchemaFilePath, schemaContent);
+ logger.info(`Created: ${migrationSchemaFilePath}`);
await prismaMigrations.generateMigrationClient(migrationName);
- logger.info(
- `Created: ${path.join(
- prismaMigrations.migrationsDir,
- migrationName,
- "client"
- )}`
- );
+ logger.info(`Created: ${path.join(migrationsDir, migrationName, "client")}`);
logger.info("");
@@ -246,7 +239,7 @@ If you're sure no other process is running, please delete the lockfile:
const migrationName = (error.migration || undefined)?.name;
if (typeof migrationName === "string") {
- prismaMigrations.setFailed(migrationName, originalErrorString);
+ await prismaMigrations.setFailed(migrationName, originalErrorString);
}
process.exitCode = 1;
diff --git a/packages/prisma-client/migrations-cli/prisma-command.ts b/packages/prisma-client/migrations-cli/prisma-command.ts
new file mode 100644
index 0000000000..ef4d0ec8a4
--- /dev/null
+++ b/packages/prisma-client/migrations-cli/prisma-command.ts
@@ -0,0 +1,33 @@
+import { x } from "tinyexec";
+import { prismaDir, schemaFilePath } from "./prisma-paths";
+
+// https://www.prisma.io/docs/reference/api-reference/command-reference#migrate-diff
+export const cliDiff = async () => {
+ const { stdout } = await x(
+ "prisma",
+ [
+ "migrate",
+ "diff",
+ `--from-schema-datasource=${schemaFilePath}`,
+ `--to-schema-datamodel=${schemaFilePath}`,
+ "--script",
+ ],
+ {
+ nodeOptions: { cwd: prismaDir },
+ throwOnError: true,
+ }
+ );
+ return stdout;
+};
+
+// https://www.prisma.io/docs/reference/api-reference/command-reference#db-execute
+export const cliExecute = async (filePath: string) => {
+ await x(
+ "prisma",
+ ["db", "execute", `--file=${filePath}`, `--schema=${schemaFilePath}`],
+ {
+ nodeOptions: { cwd: prismaDir },
+ throwOnError: true,
+ }
+ );
+};
diff --git a/packages/prisma-client/migrations-cli/prisma-migrations.test.ts b/packages/prisma-client/migrations-cli/prisma-migrations.test.ts
new file mode 100644
index 0000000000..34143f4534
--- /dev/null
+++ b/packages/prisma-client/migrations-cli/prisma-migrations.test.ts
@@ -0,0 +1,24 @@
+import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { expect, test } from "vitest";
+import { cliExecute } from "./prisma-command";
+
+test("rejects when Prisma cannot execute a migration", async () => {
+ const directory = await mkdtemp(path.join(tmpdir(), "prisma-command-"));
+ const executable = path.join(directory, "prisma");
+ const originalPath = process.env.PATH;
+
+ try {
+ await writeFile(executable, "#!/bin/sh\nexit 23\n");
+ await chmod(executable, 0o755);
+ process.env.PATH = `${directory}${path.delimiter}${originalPath ?? ""}`;
+
+ await expect(cliExecute("unused.sql")).rejects.toMatchObject({
+ exitCode: 23,
+ });
+ } finally {
+ process.env.PATH = originalPath;
+ await rm(directory, { recursive: true });
+ }
+});
diff --git a/packages/prisma-client/migrations-cli/prisma-migrations.ts b/packages/prisma-client/migrations-cli/prisma-migrations.ts
index 22c8f048fa..db782a2183 100644
--- a/packages/prisma-client/migrations-cli/prisma-migrations.ts
+++ b/packages/prisma-client/migrations-cli/prisma-migrations.ts
@@ -4,18 +4,12 @@
import path from "node:path";
import fs from "node:fs";
-import { fileURLToPath } from "node:url";
import { createHash } from "node:crypto";
import { x } from "tinyexec";
import { createPrisma } from "../src/prisma";
import { UserError } from "./errors";
import { PrismaClient } from "../src/__generated__";
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-
-export const prismaDir = path.resolve(__dirname, "..", "prisma");
-export const schemaFilePath = path.join(prismaDir, "schema.prisma");
-export const migrationsDir = path.join(prismaDir, "migrations");
+import { migrationsDir, prismaDir } from "./prisma-paths";
let prisma_: PrismaClient | undefined;
@@ -248,35 +242,6 @@ export const generateMigrationName = (baseName: string) => {
return `${prefix}_${baseName}`.slice(0, 254);
};
-// https://www.prisma.io/docs/reference/api-reference/command-reference#migrate-diff
-export const cliDiff = async () => {
- const { stdout } = await x(
- "prisma",
- [
- "migrate",
- "diff",
- `--from-schema-datasource=${schemaFilePath}`,
- `--to-schema-datamodel=${schemaFilePath}`,
- "--script",
- ],
- {
- nodeOptions: { cwd: prismaDir },
- }
- );
- return stdout;
-};
-
-// https://www.prisma.io/docs/reference/api-reference/command-reference#db-execute
-export const cliExecute = async (filePath: string) => {
- await x(
- "prisma",
- ["db", "execute", `--file=${filePath}`, `--schema=${schemaFilePath}`],
- {
- nodeOptions: { cwd: prismaDir },
- }
- );
-};
-
export const generateMigrationClient = async (migrationName: string) => {
const migrationDir = path.join(migrationsDir, migrationName);
@@ -300,5 +265,6 @@ export const generateMigrationClient = async (migrationName: string) => {
// https://www.prisma.io/docs/reference/api-reference/command-reference#generate
await x("prisma", ["generate", `--schema=${schemaPath}`], {
nodeOptions: { cwd: prismaDir },
+ throwOnError: true,
});
};
diff --git a/packages/prisma-client/migrations-cli/prisma-paths.ts b/packages/prisma-client/migrations-cli/prisma-paths.ts
new file mode 100644
index 0000000000..7c862ab705
--- /dev/null
+++ b/packages/prisma-client/migrations-cli/prisma-paths.ts
@@ -0,0 +1,8 @@
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const migrationsCliDir = path.dirname(fileURLToPath(import.meta.url));
+
+export const prismaDir = path.resolve(migrationsCliDir, "..", "prisma");
+export const schemaFilePath = path.join(prismaDir, "schema.prisma");
+export const migrationsDir = path.join(prismaDir, "migrations");
diff --git a/packages/prisma-client/migrations-cli/umzug.ts b/packages/prisma-client/migrations-cli/umzug.ts
index 403598a7e4..1cd702167d 100755
--- a/packages/prisma-client/migrations-cli/umzug.ts
+++ b/packages/prisma-client/migrations-cli/umzug.ts
@@ -3,13 +3,12 @@ import fs from "node:fs";
import * as prismaMigrations from "./prisma-migrations";
import * as logger from "./logger";
import { UserError } from "./errors";
+import { cliExecute } from "./prisma-command";
+import { migrationsDir } from "./prisma-paths";
export const umzug = new Umzug({
migrations: {
- glob: [
- `./${"[0-9]".repeat(14)}_*`,
- { cwd: prismaMigrations.migrationsDir },
- ],
+ glob: [`./${"[0-9]".repeat(14)}_*`, { cwd: migrationsDir }],
resolve(params) {
const sqlFilePath = prismaMigrations.getMigrationFilePath(
params.name,
@@ -25,7 +24,7 @@ export const umzug = new Umzug({
...params,
up: async () => {
await prismaMigrations.setStarted(params.name, sqlFilePath);
- await prismaMigrations.cliExecute(sqlFilePath);
+ await cliExecute(sqlFilePath);
},
};
}
diff --git a/packages/prisma-client/package.json b/packages/prisma-client/package.json
index 598a29ebfb..32cc159a41 100644
--- a/packages/prisma-client/package.json
+++ b/packages/prisma-client/package.json
@@ -7,12 +7,14 @@
"type": "module",
"scripts": {
"generate": "PRISMA_BINARY_TARGET=${PRISMA_BINARY_TARGET:-'[\"native\"]'} prisma generate",
- "migrations": "./migrations-cli/cli.ts"
+ "migrations": "./migrations-cli/cli.ts",
+ "test": "vitest run"
},
"devDependencies": {
"@prisma/client": "^5.12.1",
"@webstudio-is/tsconfig": "workspace:*",
"prisma": "5.12.1",
+ "vitest": "^3.1.2",
"zod": "^4.4.3"
},
"exports": {
diff --git a/packages/prisma-client/prisma/migrations/20260718120000_asset_resources/migration.sql b/packages/prisma-client/prisma/migrations/20260718120000_asset_resources/migration.sql
new file mode 100644
index 0000000000..e657a3670b
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20260718120000_asset_resources/migration.sql
@@ -0,0 +1,160 @@
+BEGIN;
+
+CREATE TABLE "AssetFileMetadata" (
+ "projectId" TEXT NOT NULL,
+ "assetId" TEXT NOT NULL,
+ "revision" TEXT NOT NULL,
+ "document" JSONB NOT NULL,
+ "createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "AssetFileMetadata_pkey"
+ PRIMARY KEY ("projectId", "assetId"),
+ CONSTRAINT "AssetFileMetadata_document_identity_check"
+ CHECK ((
+ jsonb_typeof("document") = 'object'
+ AND jsonb_typeof("document"->'_id') = 'string'
+ AND "document"->>'_id' = "assetId"
+ AND jsonb_typeof("document"->'revision') = 'string'
+ AND "document"->>'revision' = "revision"
+ ) IS TRUE),
+ CONSTRAINT "AssetFileMetadata_assetId_projectId_fkey"
+ FOREIGN KEY ("assetId", "projectId") REFERENCES "Asset"("id", "projectId")
+ ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+CREATE FUNCTION replace_asset_file_metadata(
+ p_project_id TEXT,
+ p_asset_id TEXT,
+ p_revision TEXT,
+ p_document JSONB,
+ p_source JSONB
+)
+RETURNS BOOLEAN
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ PERFORM pg_catalog.pg_advisory_xact_lock(
+ pg_catalog.hashtextextended(
+ pg_catalog.jsonb_build_array(p_project_id, p_asset_id)::TEXT,
+ 0
+ )
+ );
+
+ PERFORM 1
+ FROM public."Asset" AS asset
+ INNER JOIN public."File" AS file ON file."name" = asset."name"
+ WHERE asset."projectId" = p_project_id
+ AND asset."id" = p_asset_id
+ AND asset."filename" IS NOT DISTINCT FROM p_source->>'filename'
+ AND asset."description" IS NOT DISTINCT FROM p_source->>'description'
+ AND asset."folderId" IS NOT DISTINCT FROM p_source->>'folderId'
+ AND file."name" = p_source->>'storageName'
+ AND file."updatedAt" = (p_source->>'fileUpdatedAt')::TIMESTAMPTZ
+ AND file."size" = (p_source->>'fileSize')::INTEGER
+ AND file."status" = 'UPLOADED'
+ FOR UPDATE OF asset, file;
+
+ IF NOT FOUND THEN
+ RETURN FALSE;
+ END IF;
+
+ INSERT INTO public."AssetFileMetadata" (
+ "projectId",
+ "assetId",
+ "revision",
+ "document",
+ "updatedAt"
+ ) VALUES (
+ p_project_id,
+ p_asset_id,
+ p_revision,
+ p_document,
+ CURRENT_TIMESTAMP
+ )
+ ON CONFLICT ("projectId", "assetId")
+ DO UPDATE SET
+ "revision" = EXCLUDED."revision",
+ "document" = EXCLUDED."document",
+ "updatedAt" = EXCLUDED."updatedAt"
+ WHERE "AssetFileMetadata"."revision" IS DISTINCT FROM EXCLUDED."revision"
+ OR "AssetFileMetadata"."document" IS DISTINCT FROM EXCLUDED."document";
+
+ RETURN TRUE;
+END;
+$$;
+
+CREATE FUNCTION delete_stale_asset_file_metadata(
+ p_project_id TEXT,
+ p_asset_ids TEXT[]
+)
+RETURNS INTEGER
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ asset_id TEXT;
+ deleted_count INTEGER;
+ total_deleted INTEGER := 0;
+BEGIN
+ FOR asset_id IN
+ SELECT DISTINCT requested_asset_id
+ FROM pg_catalog.unnest(p_asset_ids) AS requested_asset_id
+ ORDER BY requested_asset_id
+ LOOP
+ PERFORM pg_catalog.pg_advisory_xact_lock(
+ pg_catalog.hashtextextended(
+ pg_catalog.jsonb_build_array(p_project_id, asset_id)::TEXT,
+ 0
+ )
+ );
+
+ IF NOT EXISTS (
+ SELECT 1
+ FROM public."Asset" AS asset
+ INNER JOIN public."File" AS file ON file."name" = asset."name"
+ WHERE asset."projectId" = p_project_id
+ AND asset."id" = asset_id
+ AND file."status" = 'UPLOADED'
+ ) THEN
+ DELETE FROM public."AssetFileMetadata"
+ WHERE "projectId" = p_project_id
+ AND "assetId" = asset_id;
+ GET DIAGNOSTICS deleted_count = ROW_COUNT;
+ total_deleted := total_deleted + deleted_count;
+ END IF;
+ END LOOP;
+
+ RETURN total_deleted;
+END;
+$$;
+
+CREATE FUNCTION delete_asset_file_metadata_if_matches(
+ p_project_id TEXT,
+ p_asset_id TEXT,
+ p_revision TEXT,
+ p_document JSONB
+)
+RETURNS INTEGER
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ deleted_count INTEGER;
+BEGIN
+ PERFORM pg_catalog.pg_advisory_xact_lock(
+ pg_catalog.hashtextextended(
+ pg_catalog.jsonb_build_array(p_project_id, p_asset_id)::TEXT,
+ 0
+ )
+ );
+
+ DELETE FROM public."AssetFileMetadata"
+ WHERE "projectId" = p_project_id
+ AND "assetId" = p_asset_id
+ AND "revision" = p_revision
+ AND "document" = p_document;
+ GET DIAGNOSTICS deleted_count = ROW_COUNT;
+ RETURN deleted_count;
+END;
+$$;
+
+COMMIT;
diff --git a/packages/prisma-client/prisma/schema.prisma b/packages/prisma-client/prisma/schema.prisma
index a8d853570f..143c95197f 100644
--- a/packages/prisma-client/prisma/schema.prisma
+++ b/packages/prisma-client/prisma/schema.prisma
@@ -40,20 +40,36 @@ model File {
}
model Asset {
- id String @default(uuid()) // not unique!
+ id String @default(uuid()) // not unique!
projectId String
- file File @relation(fields: [name], references: [name])
+ file File @relation(fields: [name], references: [name])
name String
filename String?
description String?
folderId String?
- folder AssetFolder? @relation(fields: [folderId, projectId], references: [id, projectId], onDelete: NoAction)
+ folder AssetFolder? @relation(fields: [folderId, projectId], references: [id, projectId], onDelete: NoAction)
+ // The child primary key permits one row. Prisma represents this as a list
+ // because the relation field order differs from the project-first key and a
+ // singular relation would require a redundant reverse-order unique index.
+ fileMetadata AssetFileMetadata[]
Project Project[]
DashboardProject DashboardProject[]
@@id([id, projectId])
}
+model AssetFileMetadata {
+ projectId String
+ assetId String
+ revision String
+ document Json
+ createdAt DateTime @default(now()) @db.Timestamptz(3)
+ updatedAt DateTime @default(now()) @updatedAt @db.Timestamptz(3)
+ asset Asset @relation(fields: [assetId, projectId], references: [id, projectId], onDelete: Cascade)
+
+ @@id([projectId, assetId])
+}
+
model AssetFolder {
id String @default(uuid())
projectId String
@@ -243,8 +259,8 @@ model AuthorizationToken {
relation AuthorizationRelation @default(viewers)
createdAt DateTime @default(now()) @db.Timestamptz(3)
- canClone Boolean @default(true)
- canCopy Boolean @default(true)
+ canClone Boolean @default(true)
+ canCopy Boolean @default(true)
canUseApi Boolean @default(false)
@@id([token, projectId])
@@ -307,12 +323,12 @@ view LatestStaticBuildPerProject {
}
model Workspace {
- id String @id @default(uuid())
+ id String @id @default(uuid())
name String
- isDefault Boolean @default(false)
- isDeleted Boolean @default(false)
- createdAt DateTime @default(now()) @db.Timestamptz(3)
- user User @relation(fields: [userId], references: [id])
+ isDefault Boolean @default(false)
+ isDeleted Boolean @default(false)
+ createdAt DateTime @default(now()) @db.Timestamptz(3)
+ user User @relation(fields: [userId], references: [id])
userId String
projects Project[]
members WorkspaceMember[]
@@ -325,7 +341,7 @@ model WorkspaceMember {
workspace Workspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade)
workspaceId String
userId String
- relation AuthorizationRelation @default(administrators)
+ relation AuthorizationRelation @default(administrators)
createdAt DateTime @default(now()) @db.Timestamptz(3)
removedAt DateTime? @db.Timestamptz(3)
diff --git a/packages/project-build/package.json b/packages/project-build/package.json
index 8120f32061..91bb1e77fe 100644
--- a/packages/project-build/package.json
+++ b/packages/project-build/package.json
@@ -67,14 +67,17 @@
"dependencies": {
"@emotion/hash": "^0.9.2",
"@modelcontextprotocol/sdk": "^1.10.0",
+ "@webstudio-is/content-engine": "workspace:*",
"@webstudio-is/authorization-token": "workspace:*",
"@webstudio-is/css-data": "workspace:*",
"@webstudio-is/css-engine": "workspace:*",
+ "@webstudio-is/expression": "workspace:*",
"@webstudio-is/fonts": "workspace:*",
"@webstudio-is/html-data": "workspace:*",
"@webstudio-is/postgrest": "workspace:*",
"@webstudio-is/project": "workspace:*",
"@webstudio-is/project-migrations": "workspace:*",
+ "@webstudio-is/query-builder": "workspace:*",
"@webstudio-is/react-sdk": "workspace:*",
"@webstudio-is/sdk": "workspace:*",
"@webstudio-is/sdk-components-registry": "workspace:*",
diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
index 14d28d09dd..8deed86941 100644
--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
@@ -2231,22 +2231,6 @@ export const runtimeOperationContractData = [
},
required: ["type", "value"],
},
- {
- type: "object",
- properties: {
- type: {
- type: "string",
- const: "string[]",
- },
- value: {
- type: "array",
- items: {
- type: "string",
- },
- },
- },
- required: ["type", "value"],
- },
{
type: "object",
properties: {
@@ -3696,6 +3680,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -3836,6 +3821,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -3901,6 +3887,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -3996,22 +3983,6 @@ export const runtimeOperationContractData = [
},
required: ["type", "value"],
},
- {
- type: "object",
- properties: {
- type: {
- type: "string",
- const: "string[]",
- },
- value: {
- type: "array",
- items: {
- type: "string",
- },
- },
- },
- required: ["type", "value"],
- },
{
type: "object",
properties: {
@@ -6839,6 +6810,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -6979,6 +6951,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -7044,6 +7017,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -7139,22 +7113,6 @@ export const runtimeOperationContractData = [
},
required: ["type", "value"],
},
- {
- type: "object",
- properties: {
- type: {
- type: "string",
- const: "string[]",
- },
- value: {
- type: "array",
- items: {
- type: "string",
- },
- },
- },
- required: ["type", "value"],
- },
{
type: "object",
properties: {
@@ -9993,6 +9951,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -10133,6 +10092,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -10198,6 +10158,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -10293,22 +10254,6 @@ export const runtimeOperationContractData = [
},
required: ["type", "value"],
},
- {
- type: "object",
- properties: {
- type: {
- type: "string",
- const: "string[]",
- },
- value: {
- type: "array",
- items: {
- type: "string",
- },
- },
- },
- required: ["type", "value"],
- },
{
type: "object",
properties: {
@@ -13136,6 +13081,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -13276,6 +13222,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -13341,6 +13288,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -13436,22 +13384,6 @@ export const runtimeOperationContractData = [
},
required: ["type", "value"],
},
- {
- type: "object",
- properties: {
- type: {
- type: "string",
- const: "string[]",
- },
- value: {
- type: "array",
- items: {
- type: "string",
- },
- },
- },
- required: ["type", "value"],
- },
{
type: "object",
properties: {
@@ -18974,6 +18906,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -19122,6 +19055,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -19187,6 +19121,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -19281,22 +19216,6 @@ export const runtimeOperationContractData = [
},
required: ["type", "value"],
},
- {
- type: "object",
- properties: {
- type: {
- type: "string",
- const: "string[]",
- },
- value: {
- type: "array",
- items: {
- type: "string",
- },
- },
- },
- required: ["type", "value"],
- },
{
type: "object",
properties: {
@@ -22320,6 +22239,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -22468,6 +22388,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -22533,6 +22454,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -22627,22 +22549,6 @@ export const runtimeOperationContractData = [
},
required: ["type", "value"],
},
- {
- type: "object",
- properties: {
- type: {
- type: "string",
- const: "string[]",
- },
- value: {
- type: "array",
- items: {
- type: "string",
- },
- },
- },
- required: ["type", "value"],
- },
{
type: "object",
properties: {
@@ -36387,22 +36293,6 @@ export const runtimeOperationContractData = [
},
required: ["type", "value"],
},
- {
- type: "object",
- properties: {
- type: {
- type: "string",
- const: "string[]",
- },
- value: {
- type: "array",
- items: {
- type: "string",
- },
- },
- },
- required: ["type", "value"],
- },
{
type: "object",
properties: {
@@ -36734,6 +36624,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -36874,6 +36765,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -36939,6 +36831,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -37034,22 +36927,6 @@ export const runtimeOperationContractData = [
},
required: ["type", "value"],
},
- {
- type: "object",
- properties: {
- type: {
- type: "string",
- const: "string[]",
- },
- value: {
- type: "array",
- items: {
- type: "string",
- },
- },
- },
- required: ["type", "value"],
- },
{
type: "object",
properties: {
@@ -39952,6 +39829,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -40092,6 +39970,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -40157,6 +40036,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -40252,22 +40132,6 @@ export const runtimeOperationContractData = [
},
required: ["type", "value"],
},
- {
- type: "object",
- properties: {
- type: {
- type: "string",
- const: "string[]",
- },
- value: {
- type: "array",
- items: {
- type: "string",
- },
- },
- },
- required: ["type", "value"],
- },
{
type: "object",
properties: {
@@ -46286,6 +46150,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -46421,6 +46286,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -46486,6 +46352,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -46581,22 +46448,6 @@ export const runtimeOperationContractData = [
},
required: ["type", "value"],
},
- {
- type: "object",
- properties: {
- type: {
- type: "string",
- const: "string[]",
- },
- value: {
- type: "array",
- items: {
- type: "string",
- },
- },
- },
- required: ["type", "value"],
- },
{
type: "object",
properties: {
@@ -52118,6 +51969,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -52253,6 +52105,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -52318,6 +52171,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -52413,22 +52267,6 @@ export const runtimeOperationContractData = [
},
required: ["type", "value"],
},
- {
- type: "object",
- properties: {
- type: {
- type: "string",
- const: "string[]",
- },
- value: {
- type: "array",
- items: {
- type: "string",
- },
- },
- },
- required: ["type", "value"],
- },
{
type: "object",
properties: {
@@ -66596,22 +66434,6 @@ export const runtimeOperationContractData = [
},
required: ["type", "value"],
},
- {
- type: "object",
- properties: {
- type: {
- type: "string",
- const: "string[]",
- },
- value: {
- type: "array",
- items: {
- type: "string",
- },
- },
- },
- required: ["type", "value"],
- },
{
type: "object",
properties: {
@@ -66732,22 +66554,6 @@ export const runtimeOperationContractData = [
},
required: ["type", "value"],
},
- {
- type: "object",
- properties: {
- type: {
- type: "string",
- const: "string[]",
- },
- value: {
- type: "array",
- items: {
- type: "string",
- },
- },
- },
- required: ["type", "value"],
- },
{
type: "object",
properties: {
@@ -66853,22 +66659,6 @@ export const runtimeOperationContractData = [
},
required: ["type", "value"],
},
- {
- type: "object",
- properties: {
- type: {
- type: "string",
- const: "string[]",
- },
- value: {
- type: "array",
- items: {
- type: "string",
- },
- },
- },
- required: ["type", "value"],
- },
{
type: "object",
properties: {
@@ -67113,181 +66903,2058 @@ export const runtimeOperationContractData = [
retryOnConflict: false,
},
{
- id: "resources.create",
- command: "create-resource",
- client: "createResource",
- kind: "mutation",
+ id: "assetsResources.list",
+ command: "list-assets-resources",
+ client: "listAssetsResources",
+ kind: "read",
inputSchema: {
type: "object",
properties: {
- resource: {
- type: "object",
- properties: {
- name: {
- type: "string",
- },
- control: {
- type: "string",
- enum: ["system", "graphql"],
- },
- method: {
- anyOf: [
- {
- type: "string",
- const: "get",
- },
- {
- type: "string",
- const: "post",
- },
- {
- type: "string",
- const: "put",
- },
- {
- type: "string",
- const: "delete",
- },
- ],
- },
- url: {
- type: "string",
- },
- searchParams: {
- type: "array",
- items: {
+ scopeInstanceId: {
+ type: "string",
+ },
+ cursor: {
+ type: "string",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 200,
+ },
+ verbose: {
+ description:
+ "Expand the same result with complete records and diagnostics. Omit for compact output.",
+ type: "boolean",
+ },
+ },
+ required: [],
+ },
+ outputSchema: {
+ type: "object",
+ properties: {
+ resources: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ resourceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ scopeInstanceId: {
+ type: "string",
+ },
+ dataSourceId: {
+ type: "string",
+ },
+ dataSourceName: {
+ type: "string",
+ },
+ mode: {
+ type: "string",
+ enum: ["query", "invalid"],
+ },
+ query: {
type: "object",
properties: {
- name: {
+ where: {
+ $ref: "#/$defs/__schema1",
+ },
+ sort: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ field: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ direction: {
+ type: "string",
+ enum: ["asc", "desc"],
+ },
+ },
+ required: ["field", "direction"],
+ additionalProperties: false,
+ },
+ },
+ limit: {
type: "string",
},
- value: {
- anyOf: [
+ offset: {
+ type: "string",
+ },
+ output: {
+ default: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["url"], ["width"], ["height"]],
+ },
+ oneOf: [
{
- type: "string",
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "all",
+ },
+ includeMetadata: {
+ default: true,
+ type: "boolean",
+ },
+ },
+ required: ["mode"],
+ additionalProperties: false,
},
{
type: "object",
properties: {
- type: {
+ mode: {
type: "string",
- const: "literal",
+ const: "base",
},
- value: {
+ includeMetadata: {
+ default: true,
+ type: "boolean",
+ },
+ },
+ required: ["mode"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
type: "string",
+ const: "fields",
+ },
+ includeMetadata: {
+ default: true,
+ type: "boolean",
+ },
+ fields: {
+ maxItems: 256,
+ type: "array",
+ items: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ },
},
},
- required: ["type", "value"],
+ required: ["mode", "fields"],
+ additionalProperties: false,
},
],
- description:
- 'One dynamic Webstudio JavaScript expression, or { type: "literal", value: string } for fixed text. Read webstudio://project/expressions for syntax, scope, resource-result shape, and supported methods.',
- },
- },
- required: ["name", "value"],
- },
- },
- headers: {
- type: "array",
- items: {
- type: "object",
- properties: {
- name: {
- type: "string",
},
- value: {
- anyOf: [
+ content: {
+ oneOf: [
{
- type: "string",
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "none",
+ },
+ },
+ required: ["mode"],
},
{
type: "object",
properties: {
- type: {
+ mode: {
type: "string",
- const: "literal",
+ const: "full",
},
- value: {
+ maxBytes: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 1048576,
+ },
+ },
+ required: ["mode"],
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
type: "string",
+ const: "range",
+ },
+ offset: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ length: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 262144,
},
},
- required: ["type", "value"],
+ required: ["mode", "offset", "length"],
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "markdown-body",
+ },
+ maxBytes: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 1048576,
+ },
+ },
+ required: ["mode"],
},
],
- description:
- 'One dynamic Webstudio JavaScript expression, or { type: "literal", value: string } for fixed text. Read webstudio://project/expressions for syntax, scope, resource-result shape, and supported methods.',
},
},
- required: ["name", "value"],
+ required: ["where", "sort", "limit", "offset", "content"],
+ additionalProperties: {},
+ },
+ configurationError: {
+ type: "string",
},
},
- body: {
- anyOf: [
- {
- type: "string",
- },
- {
- type: "object",
- properties: {
- type: {
- type: "string",
- const: "literal",
- },
- value: {
- type: "string",
- },
- },
- required: ["type", "value"],
- },
- ],
- description:
- 'One dynamic Webstudio JavaScript expression, or { type: "literal", value: string } for fixed text. Read webstudio://project/expressions for syntax, scope, resource-result shape, and supported methods.',
- },
+ required: ["resourceId", "name", "mode"],
+ additionalProperties: {},
},
- required: ["name", "method", "url", "headers"],
},
- scopeInstanceId: {
+ detail: {
type: "string",
+ enum: ["compact", "verbose"],
},
- dataSourceName: {
- type: "string",
+ total: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
},
- exposeAsDataSource: {
- description:
- "Expose the resource as render-time data. Scoped GET resources default to true; write resources default to false.",
- type: "boolean",
+ returnedCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
},
- },
- required: ["resource"],
- },
- outputSchema: {
- type: "object",
- properties: {
- resourceId: {
- type: "string",
+ nextCursor: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
},
- dataSourceId: {
- type: "string",
+ filters: {
+ type: "object",
+ properties: {},
+ additionalProperties: {},
+ required: [],
},
- warnings: {
- type: "array",
- items: {
- type: "object",
- properties: {
- severity: {
- type: "string",
- const: "warning",
- },
- code: {
- type: "string",
- },
- path: {
- type: "array",
- items: {
- type: "string",
- },
- },
- message: {
+ },
+ required: [
+ "resources",
+ "detail",
+ "total",
+ "returnedCount",
+ "nextCursor",
+ "filters",
+ ],
+ additionalProperties: {},
+ $defs: {
+ __schema0: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "number",
+ },
+ {
+ type: "boolean",
+ },
+ {
+ type: "null",
+ },
+ {
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ },
+ additionalProperties: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ ],
+ },
+ __schema1: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ field: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ description:
+ 'Indexed file field path, for example ["extension"] or ["properties", "slug"].',
+ },
+ operator: {
+ type: "string",
+ enum: [
+ "eq",
+ "ne",
+ "contains",
+ "startsWith",
+ "endsWith",
+ "gt",
+ "gte",
+ "lt",
+ "lte",
+ "in",
+ "exists",
+ "isEmpty",
+ ],
+ },
+ value: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ required: ["type", "value"],
+ additionalProperties: false,
+ },
+ ],
+ description:
+ 'A Webstudio expression, or { type: "literal", value: <JSON value> } for fixed data.',
+ },
+ },
+ required: ["field", "operator", "value"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ all: {
+ maxItems: 32,
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema1",
+ },
+ },
+ },
+ required: ["all"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ any: {
+ maxItems: 32,
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema1",
+ },
+ },
+ },
+ required: ["any"],
+ additionalProperties: false,
+ },
+ ],
+ },
+ },
+ },
+ readNamespaces: ["dataSources", "resources"],
+ writeNamespaces: [],
+ invalidatesNamespaces: [],
+ retryOnConflict: false,
+ },
+ {
+ id: "assetsResources.get",
+ command: "get-assets-resource",
+ client: "getAssetsResource",
+ kind: "read",
+ inputSchema: {
+ type: "object",
+ properties: {
+ resourceId: {
+ type: "string",
+ },
+ },
+ required: ["resourceId"],
+ },
+ outputSchema: {
+ type: "object",
+ properties: {
+ resource: {
+ type: "object",
+ properties: {
+ resourceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ scopeInstanceId: {
+ type: "string",
+ },
+ dataSourceId: {
+ type: "string",
+ },
+ dataSourceName: {
+ type: "string",
+ },
+ mode: {
+ type: "string",
+ enum: ["query", "invalid"],
+ },
+ query: {
+ type: "object",
+ properties: {
+ where: {
+ $ref: "#/$defs/__schema1",
+ },
+ sort: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ field: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ direction: {
+ type: "string",
+ enum: ["asc", "desc"],
+ },
+ },
+ required: ["field", "direction"],
+ additionalProperties: false,
+ },
+ },
+ limit: {
+ type: "string",
+ },
+ offset: {
+ type: "string",
+ },
+ output: {
+ default: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["url"], ["width"], ["height"]],
+ },
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "all",
+ },
+ includeMetadata: {
+ default: true,
+ type: "boolean",
+ },
+ },
+ required: ["mode"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "base",
+ },
+ includeMetadata: {
+ default: true,
+ type: "boolean",
+ },
+ },
+ required: ["mode"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "fields",
+ },
+ includeMetadata: {
+ default: true,
+ type: "boolean",
+ },
+ fields: {
+ maxItems: 256,
+ type: "array",
+ items: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ },
+ },
+ required: ["mode", "fields"],
+ additionalProperties: false,
+ },
+ ],
+ },
+ content: {
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "none",
+ },
+ },
+ required: ["mode"],
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "full",
+ },
+ maxBytes: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 1048576,
+ },
+ },
+ required: ["mode"],
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "range",
+ },
+ offset: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ length: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 262144,
+ },
+ },
+ required: ["mode", "offset", "length"],
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "markdown-body",
+ },
+ maxBytes: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 1048576,
+ },
+ },
+ required: ["mode"],
+ },
+ ],
+ },
+ },
+ required: ["where", "sort", "limit", "offset", "content"],
+ additionalProperties: {},
+ },
+ configurationError: {
+ type: "string",
+ },
+ },
+ required: ["resourceId", "name", "mode"],
+ additionalProperties: {},
+ },
+ },
+ required: ["resource"],
+ additionalProperties: {},
+ $defs: {
+ __schema0: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "number",
+ },
+ {
+ type: "boolean",
+ },
+ {
+ type: "null",
+ },
+ {
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ },
+ additionalProperties: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ ],
+ },
+ __schema1: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ field: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ description:
+ 'Indexed file field path, for example ["extension"] or ["properties", "slug"].',
+ },
+ operator: {
+ type: "string",
+ enum: [
+ "eq",
+ "ne",
+ "contains",
+ "startsWith",
+ "endsWith",
+ "gt",
+ "gte",
+ "lt",
+ "lte",
+ "in",
+ "exists",
+ "isEmpty",
+ ],
+ },
+ value: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ required: ["type", "value"],
+ additionalProperties: false,
+ },
+ ],
+ description:
+ 'A Webstudio expression, or { type: "literal", value: <JSON value> } for fixed data.',
+ },
+ },
+ required: ["field", "operator", "value"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ all: {
+ maxItems: 32,
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema1",
+ },
+ },
+ },
+ required: ["all"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ any: {
+ maxItems: 32,
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema1",
+ },
+ },
+ },
+ required: ["any"],
+ additionalProperties: false,
+ },
+ ],
+ },
+ },
+ },
+ readNamespaces: ["dataSources", "resources"],
+ writeNamespaces: [],
+ invalidatesNamespaces: [],
+ retryOnConflict: false,
+ },
+ {
+ id: "assetsResources.create",
+ command: "create-assets-resource",
+ client: "createAssetsResource",
+ kind: "mutation",
+ inputSchema: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ minLength: 1,
+ },
+ query: {
+ type: "object",
+ properties: {
+ where: {
+ default: {
+ all: [],
+ },
+ description:
+ "A boolean filter tree. Use { all: [...] } for AND and { any: [...] } for OR; leaves contain field, operator, and value.",
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ field: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ description:
+ 'Indexed file field path, for example ["extension"] or ["properties", "slug"].',
+ },
+ operator: {
+ type: "string",
+ enum: [
+ "eq",
+ "ne",
+ "contains",
+ "startsWith",
+ "endsWith",
+ "gt",
+ "gte",
+ "lt",
+ "lte",
+ "in",
+ "exists",
+ "isEmpty",
+ ],
+ },
+ value: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ required: ["type", "value"],
+ additionalProperties: false,
+ },
+ ],
+ description:
+ 'A Webstudio expression, or { type: "literal", value: <JSON value> } for fixed data.',
+ },
+ },
+ required: ["field", "operator", "value"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ all: {
+ maxItems: 32,
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema1",
+ },
+ },
+ },
+ required: ["all"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ any: {
+ maxItems: 32,
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema1",
+ },
+ },
+ },
+ required: ["any"],
+ additionalProperties: false,
+ },
+ ],
+ $ref: "#/$defs/__schema1",
+ },
+ sort: {
+ default: [],
+ maxItems: 8,
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ field: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ direction: {
+ type: "string",
+ enum: ["asc", "desc"],
+ },
+ },
+ required: ["field", "direction"],
+ additionalProperties: false,
+ },
+ },
+ limit: {
+ default: "20",
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "integer",
+ minimum: 0,
+ maximum: 1000,
+ },
+ },
+ required: ["type", "value"],
+ additionalProperties: false,
+ },
+ ],
+ description:
+ 'A Webstudio expression, or { type: "literal", value: number } for a fixed result limit.',
+ },
+ offset: {
+ default: "0",
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "integer",
+ minimum: 0,
+ maximum: 1000,
+ },
+ },
+ required: ["type", "value"],
+ additionalProperties: false,
+ },
+ ],
+ description:
+ 'A Webstudio expression, or { type: "literal", value: number } for a fixed result offset.',
+ },
+ output: {
+ default: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["url"], ["width"], ["height"]],
+ },
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "all",
+ },
+ includeMetadata: {
+ default: true,
+ type: "boolean",
+ },
+ },
+ required: ["mode"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "base",
+ },
+ includeMetadata: {
+ default: true,
+ type: "boolean",
+ },
+ },
+ required: ["mode"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "fields",
+ },
+ includeMetadata: {
+ default: true,
+ type: "boolean",
+ },
+ fields: {
+ maxItems: 256,
+ type: "array",
+ items: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ },
+ },
+ required: ["mode", "fields"],
+ additionalProperties: false,
+ },
+ ],
+ },
+ content: {
+ default: {
+ mode: "none",
+ },
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "none",
+ },
+ },
+ required: ["mode"],
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "full",
+ },
+ maxBytes: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 1048576,
+ },
+ },
+ required: ["mode"],
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "range",
+ },
+ offset: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ length: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 262144,
+ },
+ },
+ required: ["mode", "offset", "length"],
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "markdown-body",
+ },
+ maxBytes: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 1048576,
+ },
+ },
+ required: ["mode"],
+ },
+ ],
+ },
+ },
+ additionalProperties: false,
+ required: [],
+ },
+ scopeInstanceId: {
+ type: "string",
+ },
+ dataSourceName: {
+ type: "string",
+ },
+ },
+ required: ["name", "scopeInstanceId"],
+ $defs: {
+ __schema0: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "number",
+ },
+ {
+ type: "boolean",
+ },
+ {
+ type: "null",
+ },
+ {
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ },
+ additionalProperties: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ ],
+ },
+ __schema1: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ field: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ description:
+ 'Indexed file field path, for example ["extension"] or ["properties", "slug"].',
+ },
+ operator: {
+ type: "string",
+ enum: [
+ "eq",
+ "ne",
+ "contains",
+ "startsWith",
+ "endsWith",
+ "gt",
+ "gte",
+ "lt",
+ "lte",
+ "in",
+ "exists",
+ "isEmpty",
+ ],
+ },
+ value: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ required: ["type", "value"],
+ additionalProperties: false,
+ },
+ ],
+ description:
+ 'A Webstudio expression, or { type: "literal", value: <JSON value> } for fixed data.',
+ },
+ },
+ required: ["field", "operator", "value"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ all: {
+ maxItems: 32,
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema1",
+ },
+ },
+ },
+ required: ["all"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ any: {
+ maxItems: 32,
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema1",
+ },
+ },
+ },
+ required: ["any"],
+ additionalProperties: false,
+ },
+ ],
+ },
+ },
+ },
+ outputSchema: {
+ type: "object",
+ properties: {
+ resourceId: {
+ type: "string",
+ },
+ dataSourceId: {
+ type: "string",
+ },
+ warnings: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ severity: {
+ type: "string",
+ const: "warning",
+ },
+ code: {
+ type: "string",
+ },
+ path: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ message: {
+ type: "string",
+ },
+ range: {
+ type: "object",
+ properties: {
+ from: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ to: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["from", "to"],
+ },
+ remediation: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ resourceId: {
+ type: "string",
+ },
+ },
+ required: [
+ "severity",
+ "code",
+ "path",
+ "message",
+ "range",
+ "remediation",
+ ],
+ },
+ },
+ },
+ required: ["resourceId", "warnings"],
+ additionalProperties: {},
+ },
+ readNamespaces: [
+ "pages",
+ "instances",
+ "props",
+ "dataSources",
+ "resources",
+ "styles",
+ "styleSources",
+ "styleSourceSelections",
+ "breakpoints",
+ ],
+ writeNamespaces: [
+ "pages",
+ "instances",
+ "props",
+ "dataSources",
+ "resources",
+ "styles",
+ "styleSources",
+ "styleSourceSelections",
+ "breakpoints",
+ ],
+ invalidatesNamespaces: [
+ "pages",
+ "instances",
+ "props",
+ "dataSources",
+ "resources",
+ "styles",
+ "styleSources",
+ "styleSourceSelections",
+ "breakpoints",
+ ],
+ retryOnConflict: false,
+ },
+ {
+ id: "assetsResources.update",
+ command: "update-assets-resource",
+ client: "updateAssetsResource",
+ kind: "mutation",
+ inputSchema: {
+ type: "object",
+ properties: {
+ resourceId: {
+ type: "string",
+ },
+ values: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ minLength: 1,
+ },
+ query: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ where: {
+ description:
+ "A boolean filter tree. Use { all: [...] } for AND and { any: [...] } for OR; leaves contain field, operator, and value.",
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ field: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ description:
+ 'Indexed file field path, for example ["extension"] or ["properties", "slug"].',
+ },
+ operator: {
+ type: "string",
+ enum: [
+ "eq",
+ "ne",
+ "contains",
+ "startsWith",
+ "endsWith",
+ "gt",
+ "gte",
+ "lt",
+ "lte",
+ "in",
+ "exists",
+ "isEmpty",
+ ],
+ },
+ value: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ required: ["type", "value"],
+ additionalProperties: false,
+ },
+ ],
+ description:
+ 'A Webstudio expression, or { type: "literal", value: <JSON value> } for fixed data.',
+ },
+ },
+ required: ["field", "operator", "value"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ all: {
+ maxItems: 32,
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema1",
+ },
+ },
+ },
+ required: ["all"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ any: {
+ maxItems: 32,
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema1",
+ },
+ },
+ },
+ required: ["any"],
+ additionalProperties: false,
+ },
+ ],
+ $ref: "#/$defs/__schema1",
+ },
+ sort: {
+ maxItems: 8,
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ field: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ direction: {
+ type: "string",
+ enum: ["asc", "desc"],
+ },
+ },
+ required: ["field", "direction"],
+ additionalProperties: false,
+ },
+ },
+ limit: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "integer",
+ minimum: 0,
+ maximum: 1000,
+ },
+ },
+ required: ["type", "value"],
+ additionalProperties: false,
+ },
+ ],
+ description:
+ 'A Webstudio expression, or { type: "literal", value: number } for a fixed result limit.',
+ },
+ offset: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "integer",
+ minimum: 0,
+ maximum: 1000,
+ },
+ },
+ required: ["type", "value"],
+ additionalProperties: false,
+ },
+ ],
+ description:
+ 'A Webstudio expression, or { type: "literal", value: number } for a fixed result offset.',
+ },
+ output: {
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "all",
+ },
+ includeMetadata: {
+ default: true,
+ type: "boolean",
+ },
+ },
+ required: ["mode"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "base",
+ },
+ includeMetadata: {
+ default: true,
+ type: "boolean",
+ },
+ },
+ required: ["mode"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "fields",
+ },
+ includeMetadata: {
+ default: true,
+ type: "boolean",
+ },
+ fields: {
+ maxItems: 256,
+ type: "array",
+ items: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ },
+ },
+ required: ["mode", "fields"],
+ additionalProperties: false,
+ },
+ ],
+ },
+ content: {
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "none",
+ },
+ },
+ required: ["mode"],
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "full",
+ },
+ maxBytes: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 1048576,
+ },
+ },
+ required: ["mode"],
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "range",
+ },
+ offset: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ length: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 262144,
+ },
+ },
+ required: ["mode", "offset", "length"],
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "markdown-body",
+ },
+ maxBytes: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 1048576,
+ },
+ },
+ required: ["mode"],
+ },
+ ],
+ },
+ },
+ additionalProperties: false,
+ required: [],
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ },
+ required: [],
+ },
+ scopeInstanceId: {
+ type: "string",
+ },
+ dataSourceName: {
+ type: "string",
+ },
+ },
+ required: ["resourceId", "values"],
+ $defs: {
+ __schema0: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "number",
+ },
+ {
+ type: "boolean",
+ },
+ {
+ type: "null",
+ },
+ {
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ },
+ additionalProperties: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ ],
+ },
+ __schema1: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ field: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ description:
+ 'Indexed file field path, for example ["extension"] or ["properties", "slug"].',
+ },
+ operator: {
+ type: "string",
+ enum: [
+ "eq",
+ "ne",
+ "contains",
+ "startsWith",
+ "endsWith",
+ "gt",
+ "gte",
+ "lt",
+ "lte",
+ "in",
+ "exists",
+ "isEmpty",
+ ],
+ },
+ value: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ required: ["type", "value"],
+ additionalProperties: false,
+ },
+ ],
+ description:
+ 'A Webstudio expression, or { type: "literal", value: <JSON value> } for fixed data.',
+ },
+ },
+ required: ["field", "operator", "value"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ all: {
+ maxItems: 32,
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema1",
+ },
+ },
+ },
+ required: ["all"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ any: {
+ maxItems: 32,
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema1",
+ },
+ },
+ },
+ required: ["any"],
+ additionalProperties: false,
+ },
+ ],
+ },
+ },
+ },
+ outputSchema: {
+ type: "object",
+ properties: {
+ resourceId: {
+ type: "string",
+ },
+ dataSourceId: {
+ type: "string",
+ },
+ warnings: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ severity: {
+ type: "string",
+ const: "warning",
+ },
+ code: {
+ type: "string",
+ },
+ path: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ message: {
+ type: "string",
+ },
+ range: {
+ type: "object",
+ properties: {
+ from: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ to: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["from", "to"],
+ },
+ remediation: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ resourceId: {
+ type: "string",
+ },
+ },
+ required: [
+ "severity",
+ "code",
+ "path",
+ "message",
+ "range",
+ "remediation",
+ ],
+ },
+ },
+ },
+ required: ["resourceId"],
+ additionalProperties: {},
+ },
+ readNamespaces: [
+ "pages",
+ "instances",
+ "props",
+ "dataSources",
+ "resources",
+ "styles",
+ "styleSources",
+ "styleSourceSelections",
+ "breakpoints",
+ ],
+ writeNamespaces: [
+ "pages",
+ "instances",
+ "props",
+ "dataSources",
+ "resources",
+ "styles",
+ "styleSources",
+ "styleSourceSelections",
+ "breakpoints",
+ ],
+ invalidatesNamespaces: [
+ "pages",
+ "instances",
+ "props",
+ "dataSources",
+ "resources",
+ "styles",
+ "styleSources",
+ "styleSourceSelections",
+ "breakpoints",
+ ],
+ retryOnConflict: false,
+ },
+ {
+ id: "resources.create",
+ command: "create-resource",
+ client: "createResource",
+ kind: "mutation",
+ inputSchema: {
+ type: "object",
+ properties: {
+ resource: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ },
+ control: {
+ type: "string",
+ enum: ["system", "graphql"],
+ },
+ method: {
+ anyOf: [
+ {
+ type: "string",
+ const: "get",
+ },
+ {
+ type: "string",
+ const: "post",
+ },
+ {
+ type: "string",
+ const: "put",
+ },
+ {
+ type: "string",
+ const: "delete",
+ },
+ ],
+ },
+ url: {
+ type: "string",
+ },
+ searchParams: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ },
+ value: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ description:
+ 'One dynamic Webstudio JavaScript expression, or { type: "literal", value: string } for fixed text. Read webstudio://project/expressions for syntax, scope, resource-result shape, and supported methods.',
+ },
+ },
+ required: ["name", "value"],
+ },
+ },
+ headers: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ },
+ value: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ description:
+ 'One dynamic Webstudio JavaScript expression, or { type: "literal", value: string } for fixed text. Read webstudio://project/expressions for syntax, scope, resource-result shape, and supported methods.',
+ },
+ },
+ required: ["name", "value"],
+ },
+ },
+ body: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ description:
+ 'One dynamic Webstudio JavaScript expression, or { type: "literal", value: string } for fixed text. Read webstudio://project/expressions for syntax, scope, resource-result shape, and supported methods.',
+ },
+ },
+ required: ["name", "method", "url", "headers"],
+ },
+ scopeInstanceId: {
+ type: "string",
+ },
+ dataSourceName: {
+ type: "string",
+ },
+ exposeAsDataSource: {
+ description:
+ "Expose the resource as render-time data. Scoped GET resources default to true; write resources default to false.",
+ type: "boolean",
+ },
+ },
+ required: ["resource"],
+ },
+ outputSchema: {
+ type: "object",
+ properties: {
+ resourceId: {
+ type: "string",
+ },
+ dataSourceId: {
+ type: "string",
+ },
+ warnings: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ severity: {
+ type: "string",
+ const: "warning",
+ },
+ code: {
+ type: "string",
+ },
+ path: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ message: {
type: "string",
},
range: {
@@ -68164,7 +69831,7 @@ export const runtimeOperationContractData = [
required: ["resourceId", "dataSourceIds", "propIds"],
additionalProperties: {},
},
- readNamespaces: ["dataSources", "resources", "props"],
+ readNamespaces: ["pages", "instances", "dataSources", "resources", "props"],
writeNamespaces: ["dataSources", "resources", "props"],
invalidatesNamespaces: ["dataSources", "resources", "props"],
retryOnConflict: false,
@@ -68230,6 +69897,7 @@ export const runtimeOperationContractData = [
name: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
parentId: {
type: "string",
@@ -68272,6 +69940,7 @@ export const runtimeOperationContractData = [
name: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
parentId: {
anyOf: [
@@ -68984,11 +70653,100 @@ export const runtimeOperationContractData = [
],
},
meta: {
- type: "object",
- propertyNames: {
- type: "string",
- },
- additionalProperties: {},
+ anyOf: [
+ {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ family: {
+ type: "string",
+ },
+ style: {
+ type: "string",
+ enum: ["normal", "italic", "oblique"],
+ },
+ weight: {
+ type: "number",
+ },
+ },
+ additionalProperties: false,
+ required: [],
+ },
+ {
+ type: "object",
+ properties: {
+ family: {
+ type: "string",
+ },
+ variationAxes: {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ enum: [
+ "wght",
+ "wdth",
+ "slnt",
+ "opsz",
+ "ital",
+ "GRAD",
+ "XTRA",
+ "XOPQ",
+ "YOPQ",
+ "YTLC",
+ "YTUC",
+ "YTAS",
+ "YTDE",
+ "YTFI",
+ ],
+ },
+ additionalProperties: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ },
+ min: {
+ type: "number",
+ },
+ default: {
+ type: "number",
+ },
+ max: {
+ type: "number",
+ },
+ },
+ required: ["name", "min", "default", "max"],
+ },
+ },
+ },
+ additionalProperties: false,
+ required: [],
+ },
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ width: {
+ type: "number",
+ },
+ height: {
+ type: "number",
+ },
+ },
+ additionalProperties: false,
+ required: [],
+ },
+ {
+ type: "object",
+ properties: {},
+ additionalProperties: false,
+ required: [],
+ },
+ ],
+ description:
+ "Type-specific metadata: family/style/weight or variationAxes for fonts, width/height for images, and no fields for generic files.",
},
},
required: [],
@@ -69136,6 +70894,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -69271,6 +71030,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
@@ -69336,6 +71096,7 @@ export const runtimeOperationContractData = [
folderId: {
type: "string",
minLength: 1,
+ maxLength: 256,
},
createdAt: {
type: "string",
diff --git a/packages/project-build/src/contracts/project-settings.ts b/packages/project-build/src/contracts/project-settings.ts
index 9ff397829f..c59ebcbc2e 100644
--- a/packages/project-build/src/contracts/project-settings.ts
+++ b/packages/project-build/src/contracts/project-settings.ts
@@ -1,5 +1,9 @@
import { z } from "zod";
-import { parseWsAuth, type WsAuthRoute } from "@webstudio-is/wsauth";
+import {
+ findWsAuthRoute,
+ parseWsAuth,
+ type WsAuthRoute,
+} from "@webstudio-is/wsauth";
const emailAddress = z.string().email();
@@ -48,6 +52,17 @@ export const validateProjectAuth = (auth: string) => {
export const parseProjectAuthRoutes = (auth: string | undefined) =>
parseWsAuth(auth ?? "");
+export const getProjectBasicAuthCredentials = (
+ auth: string | undefined,
+ pathname: string
+) => {
+ const route = findWsAuthRoute(parseProjectAuthRoutes(auth).routes, pathname);
+ if (route?.auth.method !== "basic") {
+ return;
+ }
+ return { username: route.auth.login, password: route.auth.password };
+};
+
export const validateProjectAuthRouteSyntax = (route: string) => {
const result = parseWsAuth(
JSON.stringify({
diff --git a/packages/project-build/src/db/build.test.ts b/packages/project-build/src/db/build.test.ts
index 4a157c6cd3..f5395a0b6b 100644
--- a/packages/project-build/src/db/build.test.ts
+++ b/packages/project-build/src/db/build.test.ts
@@ -115,6 +115,67 @@ describe("loadBuildById (msw)", () => {
expect(result.marketplaceProduct).toBeUndefined();
});
+ test("rejects invalid persisted data sources", async () => {
+ server.use(
+ db.get("Build", () =>
+ json([
+ {
+ ...buildRow,
+ dataSources: JSON.stringify([
+ {
+ id: "tags-variable",
+ type: "variable",
+ name: "tags",
+ value: { type: "string[]", value: ["news"] },
+ },
+ ]),
+ },
+ ])
+ )
+ );
+
+ await expect(loadBuildById(createContext(), "build-1")).rejects.toThrow();
+ });
+
+ test("normalizes persisted Assets resources before publishing or syncing", async () => {
+ server.use(
+ db.get("Build", () =>
+ json([
+ {
+ ...buildRow,
+ resources: JSON.stringify([
+ {
+ id: "assets",
+ name: "Assets",
+ control: "system",
+ method: "get",
+ url: '"/$resources/assets"',
+ searchParams: [],
+ headers: [],
+ },
+ ]),
+ },
+ ])
+ )
+ );
+
+ const result = await loadBuildById(createContext(), "build-1");
+
+ expect(result.resources).toMatchObject([
+ {
+ id: "assets",
+ method: "post",
+ headers: [
+ {
+ name: "Content-Type",
+ value: '"application/json"',
+ },
+ ],
+ },
+ ]);
+ expect(result.resources[0].body).toContain("limit: 1000");
+ });
+
test("migrates project settings from legacy pages", async () => {
server.use(
db.get("Build", () =>
diff --git a/packages/project-build/src/db/build.ts b/packages/project-build/src/db/build.ts
index 8b025d872b..62eab4b35e 100644
--- a/packages/project-build/src/db/build.ts
+++ b/packages/project-build/src/db/build.ts
@@ -6,6 +6,7 @@ import {
} from "@webstudio-is/trpc-interface/index.server";
import { db as authDb } from "@webstudio-is/authorization-token/index.server";
import {
+ dataSource,
type Deployment,
type Resource,
type StyleSource,
@@ -20,6 +21,7 @@ import {
migratePages,
serializePages,
} from "@webstudio-is/project-migrations/pages";
+import { migrateResourcesMutable } from "@webstudio-is/project-migrations/resources";
import type { Build, CompactBuild } from "../types";
import { parseDeployment } from "./deployment";
import { marketplaceProduct } from "../shared/marketplace";
@@ -74,6 +76,8 @@ const parseCompactBuild = async (
build: Database["public"]["Tables"]["Build"]["Row"]
) => {
const pages = migratePages(parseConfig<unknown>(build.pages));
+ const resources = parseCompactData<Resource>(build.resources);
+ migrateResourcesMutable(resources);
const parsedProjectSettings =
build.projectSettings === undefined || build.projectSettings === null
? createProjectSettingsFromPages(pages)
@@ -93,8 +97,10 @@ const parseCompactBuild = async (
build.styleSourceSelections
),
props: parseCompactData<Prop>(build.props),
- dataSources: parseCompactData<DataSource>(build.dataSources),
- resources: parseCompactData<Resource>(build.resources),
+ dataSources: parseCompactData<unknown>(build.dataSources).map((value) =>
+ dataSource.parse(value)
+ ),
+ resources,
instances: parseCompactInstanceData(build.instances),
deployment: parseDeployment(build.deployment),
marketplaceProduct: parseMarketplaceProduct(build.marketplaceProduct),
diff --git a/packages/project-build/src/docs.generated.ts b/packages/project-build/src/docs.generated.ts
index 1c9e44ce9e..037cd9983c 100644
--- a/packages/project-build/src/docs.generated.ts
+++ b/packages/project-build/src/docs.generated.ts
@@ -4,7 +4,7 @@ export const projectBuildDocs = {
"accessibility-review":
'<!-- Adapted for Webstudio MCP from Community-Access/accessibility-agents, web-accessibility-wizard/SKILL.md (MIT): https://github.com/Community-Access/accessibility-agents/blob/main/codex-skills/web-accessibility-wizard/SKILL.md -->\n\n# Webstudio Accessibility Review\n\nUse this workflow when creating or reviewing a page, component, form, menu,\ndialog, or responsive layout. It is an LLM-assisted review, not proof of WCAG\nconformance. Do not claim that a page is accessible solely because this review\nhas no findings.\n\n## Evidence First\n\n1. Read `meta.index` and use focused project tools. Do not inspect Webstudio\n source code or generated files for normal project reviews.\n2. Run `audit` with `{"scopes":["accessibility"]}` before changing\n anything. It detects deterministic metadata issues such as labels, landmark\n structure, positive tabindex values, invalid static ARIA states, and unmuted\n autoplay. Fix confirmed static findings first.\n3. For each changed route, use `preview.start` and capture screenshots with\n `screenshot` at desktop, tablet, and mobile widths. Use `waitForSelector`\n or `waitForTimeout` only when the page has an actual delayed ready state.\n4. Use `get-page-by-path`, `list-instances`, `inspect-instance`, and focused\n prop/style reads to verify semantics and authored state that screenshots\n cannot prove.\n5. Make only supported, evidence-based fixes with semantic MCP tools. Recheck\n the affected route and the static accessibility search after every fix.\n\n## Review Areas\n\nReview these areas in priority order. Record the evidence for every finding.\n\n### 1. Names, Semantics, and Structure\n\n- Every image has purposeful alternative text or an explicitly empty alt when\n decorative. Image-submit inputs need a non-empty alt label describing their\n action.\n- For `missing-image-description` findings, inspect the rendered image in its\n page context and call `set-image-descriptions` with either a concise generated\n description or `decorative: true`. Re-run the audit after saving the decision.\n- Buttons, links, icon-only controls, and form controls have accessible names.\n- Prefer native HTML semantics over ARIA roles.\n- Non-native elements using `role="button"` or `role="link"` must be\n keyboard-focusable.\n- Use one sensible page h1, ordered heading levels, meaningful link text, and\n a main landmark.\n- Iframes have titles. Static HTML ids are unique, ARIA reference props point\n to real ids, and static boolean/select/numeric ARIA values are valid.\n- Focusable controls must not be hidden from assistive technology with\n `aria-hidden`.\n\n### 2. Keyboard and Focus\n\n- Interactive controls should be native or have a documented keyboard model.\n- Visible focus must not be removed without a visible replacement.\n- Hover-only information or controls need a keyboard-accessible equivalent.\n- Do not use positive tabindex values.\n- Mark keyboard behavior as **manual verification required** when the available\n evidence cannot prove tab order, Escape handling, or focus restoration.\n\n### 3. Dialogs, Menus, and Other Overlays\n\n- Dialogs need an accessible name and a close action.\n- Opening an overlay should move focus into it, trap focus where appropriate,\n and restore focus to its trigger on close.\n- Menus, popovers, disclosures, and tabs must expose their expanded/selected\n state and remain usable without a pointer.\n- If the current MCP/browser tools cannot exercise the interaction, report it\n as a manual verification item instead of guessing.\n\n### 4. Forms and Errors\n\n- Inputs have labels, required state, helpers, and errors associated with the\n right control.\n- Invalid controls expose `aria-invalid` when applicable.\n- Error, loading, and success feedback is not conveyed only by color or a\n transient visual toast.\n- Submit controls do not become unexplained dead ends when disabled.\n\n### 5. Visual, Responsive, Media, and Motion\n\n- At each target width, text remains readable, controls remain reachable, and\n no content is clipped, overlapped, or dependent on hover alone.\n- Do not rely only on color, position, shape, or iconography to convey meaning.\n- Keep non-text contrast, text contrast, focus indicators, and small text as\n visual review items unless measured evidence is available.\n- Videos with meaningful speech need captions; non-essential motion should\n respect reduced-motion preferences. Do not autoplay sound.\n\n### 6. Dynamic Content and Data\n\n- Loading, empty, error, and success states have understandable visible text.\n- Important dynamic updates and validation feedback need an appropriate\n announcement strategy.\n- Check repeated resource-driven content for unique labels, headings, ids, and\n meaningful empty states.\n\n## Findings and Fixes\n\nClassify every item as one of:\n\n- **Confirmed:** directly shown by `audit`, project data, or a rendered\n screenshot.\n- **Likely:** a credible issue inferred from rendered evidence; explain what\n would confirm it.\n- **Manual verification required:** needs keyboard, screen-reader, contrast, or\n interaction testing that the available tools cannot prove.\n\nFor each item include: severity (`critical`, `high`, `medium`, or `low`), page\npath, affected element or instance id when known, evidence, short user impact,\nand the smallest supported fix. Fix critical and high items first. Do not add\nARIA attributes, alt text, labels, or live regions when their meaning cannot be\nknown from the project; ask the user or report the missing context.\n\nFinish with a concise summary of fixed findings, remaining findings, and manual\nverification items. Use screenshots as evidence of the rendered state, not as\nproof of accessibility compliance.\n',
expressions:
- '# Webstudio Expressions\n\nUse an expression only when a value must be computed at runtime from scoped\ndata. Use direct text and direct prop values for fixed content.\n\n## Source Format\n\nExpression-capable MCP fields receive JavaScript expression source as a JSON\nstring. Send one expression, without a `return` statement or surrounding\nfunction. For example:\n\n```json\n{ "binding": { "type": "expression", "value": "post.title ?? \\"Untitled\\"" } }\n```\n\nDo not send a fixed prop string as an expression. Use `update-props` with\n`type:"string"`. Page metadata and resource URLs accept plain fixed strings and\nnormalize them for storage. Expression-only resource headers, search parameters,\nand bodies accept `{ "type": "literal", "value": "fixed text" }` when the\nvalue is not dynamic.\n\n## Scope\n\n- Data variables are available on their scope instance and descendants.\n- An inner variable with the same name masks the outer variable.\n- A scoped resource result is a variable. Read its payload from its result\n wrapper, usually `resourceName.data`; APIs may nest the desired value deeper.\n- Collection creates internal `collectionItem` and `collectionItemKey`\n parameters. They are available only to that Collection\'s descendants.\n Preserve those generated parameters and do not reuse encoded parameter ids\n copied from another Collection.\n- Array Collection iteration exposes the current item. Object iteration exposes\n the current key and value.\n- The built-in `system` context is available only where supplied by the runtime.\n Its documented fields are `system.origin`, `system.pathname`, `system.params`,\n and `system.search`. There is no `system.path`.\n- Actions expose only their declared arguments, such as `event`, plus data that\n is in scope.\n\nRead `list-variables`, `list-resources`, `inspect-instance`, and existing\nbindings before writing an expression. Do not guess identifier names. Syntax is\nvalidated when a mutation is submitted. A valid expression that references an\nidentifier unavailable in that scope is accepted with a structured warning\ncontaining the field path, source range, affected record, and remediation.\n\n## Supported Syntax\n\nExpressions support literals, arrays, objects, property and index access,\noptional chaining, unary and arithmetic operators, comparisons, logical\noperators, nullish coalescing, ternaries, and template literals.\n\nSupported string methods:\n\n{{allowedStringMethods}}\n\nSupported array methods:\n\n{{allowedArrayMethods}}\n\nOther values support `toString`. Arbitrary global functions and arbitrary\nmethod calls are not supported.\n\n## Unsupported Syntax\n\nDo not use statements, declarations, functions, arrow functions, classes,\n`new`, `this`, `await`, imports, tagged templates, sequence expressions,\nincrement/decrement, or destructuring assignment. Assignment is allowed only\ninside actions. Use an explicit assignment there rather than `++` or `--`.\n\n## Common Examples\n\n- Text: `post.title ?? "Untitled"`\n- Prop: `post.url`\n- Nested API array for Collection: `posts.data.items`\n- Resource URL: `"https://api.example.com/posts?tag=" + filters.tag`\n- Header: `"Bearer " + auth.token`\n- Search parameter: `String(filters.page ?? 1)` is not supported because global\n function calls are forbidden; use `(filters.page ?? 1).toString()` instead.\n- Resource body: `{ query: queryText, variables: { slug: system.params.slug } }`\n- Conditional: `featured ? "Featured" : "Standard"`\n- Safe nested access: `post.author?.name ?? "Unknown author"`\n\n## Collections\n\nWhenever an array or object should render repeated UI, call `insert-collection`\nwith the complete iterable and one repeated-item JSX root. Do not pass the\nresponse wrapper or one indexed item. The command creates the Collection and\nits private item parameters atomically, then renders the item root once per\nentry. Bind descendants with expressions such as `collectionItem.name`; for\nobject iteration, `collectionItemKey` contains the current key. Wrap multiple\nrepeated siblings in one `ws.element` root.\n\n## Verification\n\nInspect every returned expression warning. Correct warnings that indicate a\nmisspelled or unavailable variable, then run `verify-bindings` for persisted\nsyntax, scope, and reference integrity. A warning does not roll back the\nmutation, and successful static verification does not prove runtime data has\nthe expected shape. `verify-bindings` never executes external resources or\nresolves rendered values. Preview representative data, empty/null data, and\nCollection item counts; use `audit` for relevant structural findings.\n',
+ '# Webstudio Expressions\n\nUse an expression only when a value must be computed at runtime from scoped\ndata. Use direct text and direct prop values for fixed content.\n\n## Source Format\n\nExpression-capable MCP fields receive JavaScript expression source as a JSON\nstring. Send one expression, without a `return` statement or surrounding\nfunction. For example:\n\n```json\n{ "binding": { "type": "expression", "value": "post.title ?? \\"Untitled\\"" } }\n```\n\nInside that string, use readable JavaScript syntax rather than serialized JSON.\nFor object expressions, leave identifier property names unquoted, for example\n`{ query: queryText, variables: { slug: system.params.slug } }`. Quote a property\nname only when JavaScript requires it, such as `{ "published-at": date }`. Do\nnot pass a JSON-stringified object as an expression.\n\nDo not send a fixed prop string as an expression. Use `update-props` with\n`type:"string"`. Page metadata and resource URLs accept plain fixed strings and\nnormalize them for storage. Expression-only resource headers, search parameters,\nand bodies accept `{ "type": "literal", "value": "fixed text" }` when the\nvalue is not dynamic.\n\n## Scope\n\n- Data variables are available on their scope instance and descendants.\n- An inner variable with the same name masks the outer variable.\n- A scoped resource result is a variable. Read its payload from its result\n wrapper, usually `resourceName.data`; APIs may nest the desired value deeper.\n- Collection creates internal `collectionItem` and `collectionItemKey`\n parameters. They are available only to that Collection\'s descendants.\n Preserve those generated parameters and do not reuse encoded parameter ids\n copied from another Collection.\n- Array Collection iteration exposes the current item. Object iteration exposes\n the current key and value.\n- The built-in `system` context is available only where supplied by the runtime.\n Its documented fields are `system.origin`, `system.pathname`, `system.params`,\n and `system.search`. There is no `system.path`.\n- Actions expose only their declared arguments, such as `event`, plus data that\n is in scope.\n\nRead `list-variables`, `list-resources`, `inspect-instance`, and existing\nbindings before writing an expression. Do not guess identifier names. Syntax is\nvalidated when a mutation is submitted. A valid expression that references an\nidentifier unavailable in that scope is accepted with a structured warning\ncontaining the field path, source range, affected record, and remediation.\n\n## Supported Syntax\n\nExpressions support literals, arrays, objects, property and index access,\noptional chaining, unary and arithmetic operators, comparisons, logical\noperators, nullish coalescing, ternaries, and template literals.\n\nSupported string methods:\n\n{{allowedStringMethods}}\n\nSupported array methods:\n\n{{allowedArrayMethods}}\n\nOther values support `toString`. Arbitrary global functions and arbitrary\nmethod calls are not supported.\n\n## Unsupported Syntax\n\nDo not use statements, declarations, functions, arrow functions, classes,\n`new`, `this`, `await`, imports, tagged templates, sequence expressions,\nincrement/decrement, or destructuring assignment. Assignment is allowed only\ninside actions. Use an explicit assignment there rather than `++` or `--`.\n\n## Common Examples\n\n- Text: `post.title ?? "Untitled"`\n- Prop: `post.url`\n- Nested API array for Collection: `posts.data.items`\n- Resource URL: `"https://api.example.com/posts?tag=" + filters.tag`\n- Header: `"Bearer " + auth.token`\n- Search parameter: `String(filters.page ?? 1)` is not supported because global\n function calls are forbidden; use `(filters.page ?? 1).toString()` instead.\n- Resource body: `{ query: queryText, variables: { slug: system.params.slug } }`\n- Conditional: `featured ? "Featured" : "Standard"`\n- Safe nested access: `post.author?.name ?? "Unknown author"`\n\n## Collections\n\nWhenever an array or object should render repeated UI, call `insert-collection`\nwith the complete iterable and one repeated-item JSX root. Do not pass the\nresponse wrapper or one indexed item. The command creates the Collection and\nits private item parameters atomically, then renders the item root once per\nentry. Bind descendants with expressions such as `collectionItem.name`; for\nobject iteration, `collectionItemKey` contains the current key. Wrap multiple\nrepeated siblings in one `ws.element` root.\n\n## Verification\n\nInspect every returned expression warning. Correct warnings that indicate a\nmisspelled or unavailable variable, then run `verify-bindings` for persisted\nsyntax, scope, and reference integrity. A warning does not roll back the\nmutation, and successful static verification does not prove runtime data has\nthe expected shape. `verify-bindings` never executes external resources or\nresolves rendered values. Preview representative data, empty/null data, and\nCollection item counts; use `audit` for relevant structural findings.\n',
"mcp-startup-guidance":
'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output. Before editing a Webstudio project, do one small discovery step, then act. For delegated design-system or “use every component” tasks, the first MCP command is `workflow.next {"goal":"design-system-page"}`; report that returned checkpoint to the parent/user and stop until continued. For a simple authored/styled section, the intended path is literal: call `meta.index`, call `meta.get_more_tools` with `{"tools":["insert-fragment"]}`, read the target parent id with `list-pages`/`get-page-by-path`/`list-instances` only if needed, then call `insert-fragment`. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. Do not grep source files, dump full MCP resources, or write parser scripts before trying focused MCP calls. Good first calls are `meta.index` for orientation, `meta.guide` for a goal workflow, `workflow.next` for one bounded delegated phase, `meta.get_more_tools` for exact tool schemas, and `components.coverage-plan`, `components.coverage-insert-next`, `components.find`, or `components.get` for component work. Do not call every discovery tool up front. For delegated or non-streaming agents whose parent cannot see live stderr/stdout, treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report its command/result, and wait for the parent before the next MCP command. Do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands; they hide progress from the parent. Do not take a broad task such as creating a full design-system page as one execution unit. Instead call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint to the parent, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For design-system or “use every component” tasks, start with `workflow.next`, acknowledge its checkpoint only after parent/user continuation, then run compact `components.coverage-plan`, checkpoint, create the page, checkpoint, then call `components.coverage-insert-next` once per coverage checkpoint, and finish with the `presentation-pass` workflow phase. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world design-system examples instead of raw unstyled component dumps. Request component coverage details with `components.coverage-plan {"detail":"roots"}` or `components.coverage-plan {"detail":"parts"}` only when needed. `list-pages` does not accept `detail`; use `list-pages {}` or `get-page-by-path` for page lookup. Read overview resources such as `webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview` only when focused tools are insufficient. Do not dump or parse full resources such as `webstudio://project/tools` or `webstudio://project/components` unless the focused tools are insufficient. Run one-shot shortcut or explicit `webstudio mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. For experiments, pass `--dry-run` to local-capable mutations. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project. If a one-shot call returns checkpoint.required, the CLI persists `CHECKPOINT_REQUIRED` across later one-shot calls until you report the checkpoint, wait until continued, and call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially. Complete one bounded phase and return a checkpoint before continuing. Follow the guide: read ids and Builder breakpoints first, use focused component discovery for component ids, props, and content model composition, prefer semantic tools over `apply-patch`, use direct value tools for fixed text/props, use bindings only for dynamic expressions/resources/actions, page metadata and fixed resource URLs accept plain strings, put page/resource update fields under `values`, do not edit generated files for normal content/design changes, and use `preview.start` plus screenshot/vision for visual work.\n',
} as const;
diff --git a/packages/project-build/src/docs/expressions.md b/packages/project-build/src/docs/expressions.md
index 2c1e517b11..ddc681fb2b 100644
--- a/packages/project-build/src/docs/expressions.md
+++ b/packages/project-build/src/docs/expressions.md
@@ -13,6 +13,12 @@ function. For example:
{ "binding": { "type": "expression", "value": "post.title ?? \"Untitled\"" } }
```
+Inside that string, use readable JavaScript syntax rather than serialized JSON.
+For object expressions, leave identifier property names unquoted, for example
+`{ query: queryText, variables: { slug: system.params.slug } }`. Quote a property
+name only when JavaScript requires it, such as `{ "published-at": date }`. Do
+not pass a JSON-stringified object as an expression.
+
Do not send a fixed prop string as an expression. Use `update-props` with
`type:"string"`. Page metadata and resource URLs accept plain fixed strings and
normalize them for storage. Expression-only resource headers, search parameters,
diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.ts
index 805736b2dc..5fe43761dd 100644
--- a/packages/project-build/src/mcp.test.ts
+++ b/packages/project-build/src/mcp.test.ts
@@ -1143,6 +1143,44 @@ describe("project session mcp adapter", () => {
);
});
+ test("documents the queried Assets result shape in focused tools", () => {
+ const contracts = runtimeOperationContracts.filter(({ id }) =>
+ ["assetsResources.create", "assetsResources.update"].includes(id)
+ );
+ const tools = listProjectSessionMcpTools(
+ contracts.map((contract) =>
+ publicOperation({
+ command: contract.command,
+ id: contract.id,
+ method: "mutation",
+ permit: "build",
+ description: contract.command,
+ inputSchema: contract.inputSchema,
+ readNamespaces: contract.readNamespaces,
+ writeNamespaces: contract.writeNamespaces,
+ invalidatesNamespaces: contract.invalidatesNamespaces,
+ retryOnConflict: contract.retryOnConflict,
+ })
+ )
+ );
+
+ const assetsResourceTools = tools.filter(({ name }) =>
+ ["create-assets-resource", "update-assets-resource"].includes(name)
+ );
+ expect(assetsResourceTools).toHaveLength(2);
+
+ for (const tool of assetsResourceTools) {
+ expect(tool.description).toContain("structured tool input");
+ expect(tool.description).toContain("Webstudio JavaScript expression");
+ expect(tool.description).toContain("<dataSourceName>.data");
+ expect(tool.description).toContain("<dataSourceName>.meta");
+ expect(tool.description).toContain(".properties");
+ expect(tool.description).toContain(".excerpt");
+ expect(tool.description).toContain(".content.text");
+ expect(getSchemaProperties(tool.inputSchema)).not.toEqual({});
+ }
+ });
+
test("defers oversized input schemas until focused discovery", async () => {
const description = "x".repeat(25_000);
const operation = publicOperation({
@@ -4484,7 +4522,9 @@ describe("project session mcp adapter", () => {
),
expect.stringContaining("Do not call meta.index after this guide"),
expect.stringContaining("Never place credentials"),
- expect.stringContaining("signed-out, loading, signed-in"),
+ expect.stringContaining(
+ "exact terms signed-out, loading, signed-in, and failed-auth"
+ ),
expect.stringContaining("not an authorization boundary"),
expect.stringContaining(
"Use create-page's returned rootInstanceId directly"
@@ -6609,7 +6649,29 @@ describe("project session mcp adapter", () => {
name: "preview.start",
input: { port: 70000 },
})
- ).rejects.toThrow("preview port must be an integer between 1 and 65535.");
+ ).rejects.toThrow("preview port must be an integer between 0 and 65535.");
+ });
+
+ test("allows preview hosts to allocate a port", async () => {
+ const startPreview = vi.fn(async () => ({
+ url: "http://127.0.0.1:5173/",
+ running: true,
+ mode: "iterative" as const,
+ }));
+ const adapter = createProjectSessionMcpCore({
+ operations: publicMcpOperations,
+ createProjectSession: createSessionFactory(),
+ executeOperation: createExecuteOperation(),
+ startPreview,
+ getPreviewStatus: vi.fn(),
+ });
+
+ await adapter.callTool({ name: "preview.start", input: { port: 0 } });
+
+ expect(startPreview).toHaveBeenCalledWith(
+ expect.objectContaining({ port: 0 }),
+ expect.objectContaining({ report: expect.any(Function) })
+ );
});
test("rejects empty preview host", async () => {
@@ -6992,6 +7054,9 @@ describe("project session mcp adapter", () => {
expect(expressions.contents[0]?.text).toContain("Supported string methods");
expect(expressions.contents[0]?.text).toContain("- `toLowerCase`");
expect(expressions.contents[0]?.text).toContain("- `join`");
+ expect(expressions.contents[0]?.text).toContain(
+ "leave identifier property names unquoted"
+ );
expect(expressions.contents[0]?.text).not.toContain(
"{{allowedStringMethods}}"
);
@@ -7807,6 +7872,37 @@ describe("project session mcp adapter", () => {
}
});
+ test("returns actionable structured screenshot failures", async () => {
+ const server = await createProjectSessionMcpServer({
+ operations: publicMcpOperations,
+ createProjectSession: createSessionFactory(),
+ executeOperation: createExecuteOperation(),
+ captureScreenshot: vi.fn(async () => {
+ throw new Error("Chromium executable was not found");
+ }),
+ });
+ const { client, close } = await createConnectedClient(server);
+
+ try {
+ const result = await client.callTool({
+ name: "screenshot",
+ arguments: { url: "https://example.com" },
+ });
+ expect(result).toMatchObject({
+ isError: true,
+ structuredContent: {
+ ok: false,
+ error: {
+ code: "SCREENSHOT_CAPTURE_FAILED",
+ message: expect.stringContaining("preview.status"),
+ },
+ },
+ });
+ } finally {
+ await close();
+ }
+ });
+
test("returns stable SDK tool errors from resolver", async () => {
const error = new Error(
"Project session snapshot changed on disk."
diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.ts
index 3cd92e2478..46fc72bd3b 100644
--- a/packages/project-build/src/mcp.ts
+++ b/packages/project-build/src/mcp.ts
@@ -4,8 +4,6 @@ import {
type BuilderNamespace,
} from "./contracts/namespaces";
import {
- allowedArrayMethods,
- allowedStringMethods,
getInputJsonSchemaMetadata,
getInputJsonSchemaProperties,
inputJsonSchemaAcceptsType,
@@ -14,6 +12,10 @@ import {
type InputJsonSchema,
type InputJsonSchemaValue,
} from "@webstudio-is/sdk";
+import {
+ allowedArrayMethods,
+ allowedStringMethods,
+} from "@webstudio-is/expression";
import type { BuilderApiCapability } from "./contracts/permissions";
import path from "node:path";
import {
@@ -765,12 +767,13 @@ const getCompactSchemaProperty = (schema: InputJsonSchema): InputJsonSchema => {
};
const getHandshakeInputSchema = (
- schema: ProjectSessionMcpInputSchema
+ schema: ProjectSessionMcpInputSchema,
+ maxInlineSize = maxInlineMcpInputSchemaSize
): {
inputSchema: ProjectSessionMcpInputSchema;
detailedInputSchema?: ProjectSessionMcpInputSchema;
} => {
- if (JSON.stringify(schema).length <= maxInlineMcpInputSchemaSize) {
+ if (JSON.stringify(schema).length <= maxInlineSize) {
return { inputSchema: schema };
}
return {
@@ -784,7 +787,7 @@ const getHandshakeInputSchema = (
return [
name,
propertySchema === undefined ||
- (serializedProperty.length <= maxInlineMcpInputSchemaSize &&
+ (serializedProperty.length <= maxInlineSize &&
serializedProperty.includes('"$ref"') === false)
? property
: getCompactSchemaProperty(propertySchema),
@@ -820,11 +823,14 @@ const insertCollectionMcpInputSchema = getOperationInputSchema({
inputSchema: getInputSchemaMetadata(insertCollectionMcpInput).inputJsonSchema,
});
+const assetsResourceResultDescription =
+ "Pass query as structured tool input rather than a JSON-stringified expression or manually authored resource body. Dynamic query values use readable Webstudio JavaScript expression syntax. Assets expose an ID-keyed map at <dataSourceName>.data and collection information at <dataSourceName>.meta. Each value has selected file fields at the top level, frontmatter or JSON fields in .properties, a derived .excerpt at the top level, and requested file content in .content.text.";
+
const mcpOperationOverrides = new Map<
string,
{
description: string;
- inputSchema: ProjectSessionMcpInputSchema;
+ inputSchema?: ProjectSessionMcpInputSchema;
}
>([
[
@@ -843,6 +849,18 @@ const mcpOperationOverrides = new Map<
inputSchema: insertCollectionMcpInputSchema,
},
],
+ [
+ "create-assets-resource",
+ {
+ description: `Create a scoped Assets resource. ${assetsResourceResultDescription}`,
+ },
+ ],
+ [
+ "update-assets-resource",
+ {
+ description: `Update an Assets resource or its query. ${assetsResourceResultDescription}`,
+ },
+ ],
]);
const acceptsJsonType = (
@@ -1564,8 +1582,10 @@ const previewInputSchema = {
},
port: {
type: "number",
- description:
- "Optional fixed port. Omit it to allocate an available local port automatically.",
+ default: 0,
+ minimum: 0,
+ maximum: 65535,
+ description: "Use 0 to select an available local port automatically.",
},
source: {
type: "string",
@@ -1969,7 +1989,7 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {
{
scopeInstanceId: "body-id",
name: "tags",
- value: { type: "string[]", value: ["news", "product"] },
+ value: { type: "json", value: ["news", "product"] },
},
{
scopeInstanceId: "body-id",
@@ -1980,7 +2000,7 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {
"update-variable": [
{
dataSourceId: "variable-id",
- values: { value: { type: "string[]", value: ["news", "product"] } },
+ values: { value: { type: "json", value: ["news", "product"] } },
},
],
"create-resource": [
@@ -2048,6 +2068,118 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {
exposeAsDataSource: false,
},
],
+ "list-assets-resources": [{}],
+ "get-assets-resource": [{ resourceId: "resource-id" }],
+ "create-assets-resource": [
+ {
+ name: "All assets",
+ scopeInstanceId: "body-id",
+ dataSourceName: "assets",
+ },
+ {
+ name: "Published posts",
+ scopeInstanceId: "body-id",
+ dataSourceName: "posts",
+ query: {
+ where: {
+ all: [
+ {
+ field: ["extension"],
+ operator: "eq",
+ value: { type: "literal", value: "md" },
+ },
+ {
+ field: ["properties", "draft"],
+ operator: "ne",
+ value: "true",
+ },
+ ],
+ },
+ sort: [
+ { field: ["properties", "publishedAt"], direction: "desc" },
+ { field: ["id"], direction: "asc" },
+ ],
+ limit: "20",
+ },
+ },
+ {
+ name: "Post by slug",
+ scopeInstanceId: "body-id",
+ dataSourceName: "post",
+ query: {
+ where: {
+ all: [
+ {
+ field: ["extension"],
+ operator: "eq",
+ value: { type: "literal", value: "md" },
+ },
+ {
+ any: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "system.params.slug",
+ },
+ {
+ field: ["properties", "id"],
+ operator: "eq",
+ value: "system.params.slug",
+ },
+ ],
+ },
+ ],
+ },
+ limit: "1",
+ content: { mode: "markdown-body", maxBytes: 1_048_576 },
+ },
+ },
+ ],
+ "update-assets-resource": [
+ {
+ resourceId: "resource-id",
+ values: {
+ query: {
+ limit: "50",
+ },
+ },
+ },
+ { resourceId: "resource-id", values: { query: null } },
+ ],
+ "validate-asset-query": [
+ {
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "hello-world",
+ },
+ ],
+ },
+ limit: 1,
+ },
+ },
+ ],
+ "preview-asset-query": [
+ {
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "hello-world",
+ },
+ ],
+ },
+ limit: 1,
+ content: { mode: "markdown-body", maxBytes: 1_048_576 },
+ },
+ },
+ ],
+ "get-asset-field-catalog": [{}],
"update-asset": [
{
assetId: "font-asset-id",
@@ -3207,6 +3339,13 @@ export const hiddenMcpOperationCommands = new Set<string>([
"copy-page",
]);
+const compactMcpOperationCommands = new Set([
+ "create-assets-resource",
+ "update-assets-resource",
+ "validate-asset-query",
+ "preview-asset-query",
+]);
+
const detailedMcpInputSchemas = new WeakMap<
ProjectSessionMcpTool,
ProjectSessionMcpInputSchema
@@ -3235,13 +3374,14 @@ export const listProjectSessionMcpTools = (
)
.map((operation) => {
const override = mcpOperationOverrides.get(operation.command);
+ const operationInputSchema = getMcpOperationInputSchema(operation, {
+ includeRenderedAudit:
+ options.includeScreenshot === true && options.includePreview === true,
+ schema: override?.inputSchema,
+ });
const { inputSchema, detailedInputSchema } = getHandshakeInputSchema(
- getMcpOperationInputSchema(operation, {
- includeRenderedAudit:
- options.includeScreenshot === true &&
- options.includePreview === true,
- schema: override?.inputSchema,
- })
+ operationInputSchema,
+ compactMcpOperationCommands.has(operation.command) ? 2_500 : undefined
);
const tool = createProjectSessionMcpTool({
name: operation.command,
@@ -5413,7 +5553,7 @@ const metaGoalGuides = [
"Inspect the project's existing auth resources, variables, page settings, and agent instructions before choosing a provider workflow. Call inspect-auth-context exactly once instead of calling get-project-settings, list-pages, list-resources, or list-variables separately; use at most one focused search-project call only when that bundle does not identify the auth convention. Treat its pages section as authoritative for route existence. Do not call get-page-by-path to confirm that /account is absent. Reuse that convention; do not add a second auth system implicitly.",
"Do not call meta.index after this guide. If an exact mutation schema is still needed, make at most one meta.get_more_tools call listing all immediately required authoring tools rather than rediscovering them one at a time.",
"Never place credentials, service-role keys, refresh tokens, private session values, or authenticated response bodies in project data, command output, screenshots, agent instructions, or error reports. Ask the user to configure secrets in the provider/server environment.",
- "Model explicit signed-out, loading, signed-in, and failed-auth UI states with ordinary components and bindings. Use page basic auth only when the user asks for Webstudio's fixed login/password gate; it is not Supabase or Firebase authentication.",
+ "Keep all four auth states in the editable component structure even when bindings select only one at runtime. Give each state a visible label using the exact terms signed-out, loading, signed-in, and failed-auth so authors can inspect and verify every state. Use page basic auth only when the user asks for Webstudio's fixed login/password gate; it is not Supabase or Firebase authentication.",
"Use focused resources and variables for public client configuration and session-shaped data. Keep authorization enforcement and privileged provider calls server-side; a hidden Builder element is not an authorization boundary.",
"When fixture/session data must feed a resource, create the page and scoped fixture variables there. Use create-page's returned rootInstanceId directly instead of listing instances to rediscover it. Call list-variables after creation only when a resource expression actually needs the returned encoded name. Do not repeat list-variables when the fixture variable is not referenced, as in the expression-free state gallery, and do not guess or reference variables before they exist.",
'Create resources only after their scope and referenced variables exist. When reusing an existing server-mediated auth convention, copy its fixed request URL exactly into resource.url; resource.url is the HTTP request target, not a provider call or session-state expression. For the discovered /api/auth/session convention, use create-resource with resource:{name:"Account session via server",method:"get",url:"/api/auth/session",headers:[],searchParams:[]}, the new page root as scopeInstanceId, and a descriptive dataSourceName. Use literal wrappers only for fixed header, search-parameter, and body text.',
@@ -6621,9 +6761,9 @@ const getPreviewInput = (input: unknown): ProjectSessionPreviewInput => {
const port = typeof input.port === "number" ? input.port : undefined;
if (
port !== undefined &&
- (Number.isInteger(port) === false || port <= 0 || port > 65535)
+ (Number.isInteger(port) === false || port < 0 || port > 65535)
) {
- throw new Error("preview port must be an integer between 1 and 65535.");
+ throw new Error("preview port must be an integer between 0 and 65535.");
}
const source = input.source === undefined ? undefined : input.source;
if (source !== undefined && isProjectSessionPreviewSource(source) === false) {
@@ -7232,13 +7372,25 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
return toMetaResult(await downloadAsset(getDownloadAssetInput(input)));
}
if (name === "screenshot" && captureScreenshot !== undefined) {
- return toMetaResult(
- await captureScreenshot(getScreenshotInput(input), {
- report: (message) => {
- reportToolProgress?.(message);
- },
- })
- );
+ const screenshotInput = getScreenshotInput(input);
+ try {
+ return toMetaResult(
+ await captureScreenshot(screenshotInput, {
+ report: (message) => {
+ reportToolProgress?.(message);
+ },
+ })
+ );
+ } catch (error) {
+ const message =
+ error instanceof Error ? error.message : String(error);
+ throw Object.assign(
+ new Error(
+ `Screenshot capture failed: ${message}. Check preview.status, verify that the route loads, and retry with an installed browser or explicit browserPath.`
+ ),
+ { code: "SCREENSHOT_CAPTURE_FAILED", cause: error }
+ );
+ }
}
if (
name === "verify-page-responsive" &&
diff --git a/packages/project-build/src/project-session.test.ts b/packages/project-build/src/project-session.test.ts
index a8349ab8fa..5abcfc6790 100644
--- a/packages/project-build/src/project-session.test.ts
+++ b/packages/project-build/src/project-session.test.ts
@@ -233,18 +233,31 @@ const createSession = ({
describe("project session", () => {
test("round-trips hydrated restore transactions through JSON", () => {
const state = createSnapshot().state;
+ state.assetFolders = new Map([
+ [
+ "folder-1",
+ {
+ id: "folder-1",
+ projectId: "project-1",
+ name: "Posts",
+ createdAt: "2026-07-24T00:00:00.000Z",
+ },
+ ],
+ ]);
const transaction: BuilderPatchTransaction = {
id: "restore",
- payload: ["pages", "props"].map((namespace) => ({
- namespace: namespace as "pages" | "props",
- patches: [
- {
- op: "replace",
- path: [],
- value: state[namespace as "pages" | "props"],
- },
- ],
- })),
+ payload: (["pages", "props", "assetFolders"] as const).map(
+ (namespace) => ({
+ namespace,
+ patches: [
+ {
+ op: "replace" as const,
+ path: [],
+ value: state[namespace],
+ },
+ ],
+ })
+ ),
};
const serialized = JSON.parse(
@@ -264,6 +277,7 @@ describe("project session", () => {
folders: expect.any(Map),
});
expect(getPatchValue(1)).toBeInstanceOf(Map);
+ expect(getPatchValue(2)).toEqual(state.assetFolders);
});
test("round-trips an explicitly empty marketplace product", () => {
diff --git a/packages/project-build/src/runtime/asset-resources.test.ts b/packages/project-build/src/runtime/asset-resources.test.ts
new file mode 100644
index 0000000000..6254c2f01a
--- /dev/null
+++ b/packages/project-build/src/runtime/asset-resources.test.ts
@@ -0,0 +1,130 @@
+import { describe, expect, test } from "vitest";
+import {
+ assetsResourceCreateInput,
+ assetsResourceUpdateInput,
+} from "./asset-resources";
+
+describe("Assets resource mutation input", () => {
+ test("rejects unsupported field paths", () => {
+ const result = assetsResourceCreateInput.safeParse({
+ name: "Posts",
+ scopeInstanceId: "root",
+ query: {
+ where: {
+ all: [{ field: ["content"], operator: "contains", value: '"hello"' }],
+ },
+ },
+ });
+
+ expect(result.success).toBe(false);
+ });
+
+ test("rejects query limits on create and update", () => {
+ const query = {
+ where: {
+ all: Array.from({ length: 33 }, () => ({
+ field: ["extension"],
+ operator: "eq" as const,
+ value: { type: "literal" as const, value: "md" },
+ })),
+ },
+ };
+
+ expect(
+ assetsResourceCreateInput.safeParse({
+ name: "Posts",
+ scopeInstanceId: "root",
+ query,
+ }).success
+ ).toBe(false);
+ expect(
+ assetsResourceUpdateInput.safeParse({
+ resourceId: "posts",
+ values: { query },
+ }).success
+ ).toBe(false);
+ });
+
+ test("accepts literals and runtime expressions", () => {
+ expect(
+ assetsResourceCreateInput.safeParse({
+ name: "Post",
+ scopeInstanceId: "root",
+ query: {
+ where: {
+ all: [
+ {
+ field: ["extension"],
+ operator: "eq",
+ value: { type: "literal", value: "md" },
+ },
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "system.params.slug",
+ },
+ {
+ field: ["properties", "draft"],
+ operator: "ne",
+ value: { type: "literal", value: true },
+ },
+ ],
+ },
+ limit: { type: "literal", value: 20 },
+ offset: { type: "literal", value: 0 },
+ content: { mode: "markdown-body", maxBytes: 65_536 },
+ },
+ }).success
+ ).toBe(true);
+ });
+
+ test.each(["", "system.params["])(
+ "rejects invalid query expression %j at the input boundary",
+ (expression) => {
+ expect(
+ assetsResourceCreateInput.safeParse({
+ name: "Posts",
+ scopeInstanceId: "root",
+ query: { limit: expression },
+ }).success
+ ).toBe(false);
+ expect(
+ assetsResourceUpdateInput.safeParse({
+ resourceId: "posts",
+ values: {
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: expression,
+ },
+ ],
+ },
+ },
+ },
+ }).success
+ ).toBe(false);
+ }
+ );
+
+ test("keeps omitted query update fields absent for patch merging", () => {
+ expect(
+ assetsResourceUpdateInput.parse({
+ resourceId: "posts",
+ values: { query: { limit: "50" } },
+ }).values.query
+ ).toEqual({ limit: "50" });
+ });
+
+ test("rejects out-of-range literal pagination", () => {
+ expect(
+ assetsResourceCreateInput.safeParse({
+ name: "Posts",
+ scopeInstanceId: "root",
+ query: { limit: { type: "literal", value: -1 } },
+ }).success
+ ).toBe(false);
+ });
+});
diff --git a/packages/project-build/src/runtime/asset-resources.ts b/packages/project-build/src/runtime/asset-resources.ts
new file mode 100644
index 0000000000..4d67e0eb20
--- /dev/null
+++ b/packages/project-build/src/runtime/asset-resources.ts
@@ -0,0 +1,253 @@
+import {
+ assetQueryResourceConfigurationInput,
+ assetQueryResourceConfigurationPatchInput,
+ createDefaultStructuredAssetQueryResourceConfiguration,
+ createStructuredAssetQueryResourceBody,
+ isAssetsResource,
+ parseStructuredAssetQueryResourceBody,
+ SYSTEM_VARIABLE_ID,
+ type AssetQueryWhereExpression,
+ type Resource,
+ type StructuredAssetQueryWhereBinding,
+} from "@webstudio-is/sdk";
+import { mapQueryWhere } from "@webstudio-is/query-builder/runtime";
+import { assetsResourceUrl } from "@webstudio-is/sdk/runtime";
+import { z } from "zod";
+import type { BuilderState } from "../state/builder-state";
+import type { BuilderRuntimeContext } from "./context";
+import {
+ createResource,
+ normalizeResourceExpressionInput,
+ unsetExpressionVariables,
+ updateResource,
+} from "./data";
+import { throwBuilderRuntimeError } from "./errors";
+import { paginateOutput, paginatedOutputInputSchema } from "./output";
+
+export const assetsResourceListInput = z.object({
+ scopeInstanceId: z.string().optional(),
+ ...paginatedOutputInputSchema.shape,
+});
+
+export const assetsResourceGetInput = z.object({ resourceId: z.string() });
+
+export const assetsResourceCreateInput = z.object({
+ name: z.string().min(1),
+ query: assetQueryResourceConfigurationInput.optional(),
+ scopeInstanceId: z.string(),
+ dataSourceName: z.string().optional(),
+});
+
+export const assetsResourceUpdateInput = z.object({
+ resourceId: z.string(),
+ values: z
+ .object({
+ name: z.string().min(1).optional(),
+ query: assetQueryResourceConfigurationPatchInput.nullable().optional(),
+ })
+ .refine((values) => Object.keys(values).length > 0, {
+ error: "At least one Assets resource value is required.",
+ }),
+ scopeInstanceId: z.string().optional(),
+ dataSourceName: z.string().optional(),
+});
+
+const normalizeWhere = (
+ where: AssetQueryWhereExpression
+): StructuredAssetQueryWhereBinding =>
+ mapQueryWhere(where, (condition) => ({
+ ...condition,
+ value: normalizeResourceExpressionInput(condition.value),
+ }));
+
+const createAssetResourceBody = (
+ configuration: z.output<typeof assetQueryResourceConfigurationInput>
+) =>
+ createStructuredAssetQueryResourceBody({
+ where: normalizeWhere(configuration.where),
+ sort: configuration.sort,
+ limit: normalizeResourceExpressionInput(configuration.limit),
+ offset: normalizeResourceExpressionInput(configuration.offset),
+ output: configuration.output,
+ content: configuration.content,
+ });
+
+const serializeWhere = (
+ where: StructuredAssetQueryWhereBinding,
+ unsetNameById: Map<string, string>
+): AssetQueryWhereExpression =>
+ mapQueryWhere(where, (condition) => ({
+ ...condition,
+ value: unsetExpressionVariables({
+ expression: condition.value,
+ unsetNameById,
+ }),
+ }));
+
+const serializeAssetResource = ({
+ resource,
+ state,
+}: {
+ resource: Resource;
+ state: Pick<BuilderState, "dataSources">;
+}) => {
+ const configuration = parseStructuredAssetQueryResourceBody(resource.body);
+ const dataSources = Array.from(state.dataSources?.values() ?? []);
+ const unsetNameById = new Map(dataSources.map(({ id, name }) => [id, name]));
+ unsetNameById.set(SYSTEM_VARIABLE_ID, "system");
+ const dataSource = dataSources.find(
+ (item) => item.type === "resource" && item.resourceId === resource.id
+ );
+ return {
+ resourceId: resource.id,
+ name: resource.name,
+ scopeInstanceId: dataSource?.scopeInstanceId,
+ dataSourceId: dataSource?.id,
+ dataSourceName: dataSource?.name,
+ mode: (configuration === undefined ? "invalid" : "query") as
+ | "invalid"
+ | "query",
+ ...(configuration === undefined
+ ? {
+ configurationError:
+ "Stored Assets query configuration could not be decoded.",
+ }
+ : {
+ query: {
+ where: serializeWhere(configuration.where, unsetNameById),
+ sort: configuration.sort,
+ limit: unsetExpressionVariables({
+ expression: configuration.limit,
+ unsetNameById,
+ }),
+ offset: unsetExpressionVariables({
+ expression: configuration.offset,
+ unsetNameById,
+ }),
+ output: configuration.output,
+ content: configuration.content,
+ },
+ }),
+ };
+};
+
+export const listAssetsResources = (
+ state: Pick<BuilderState, "dataSources" | "resources">,
+ input: z.output<typeof assetsResourceListInput>
+) => {
+ const resources = Array.from(state.resources?.values() ?? [])
+ .filter(isAssetsResource)
+ .map((resource) => serializeAssetResource({ resource, state }))
+ .filter(
+ (item) =>
+ input.scopeInstanceId === undefined ||
+ item.scopeInstanceId === input.scopeInstanceId
+ );
+ const { items, ...pagination } = paginateOutput({
+ items: resources,
+ cursor: input.cursor,
+ limit: input.limit,
+ verbose: input.verbose,
+ filters: { scopeInstanceId: input.scopeInstanceId },
+ });
+ return { resources: items, ...pagination };
+};
+
+export const getAssetsResource = (
+ state: Pick<BuilderState, "dataSources" | "resources">,
+ input: z.output<typeof assetsResourceGetInput>
+) => {
+ const resource = state.resources?.get(input.resourceId);
+ if (resource === undefined || isAssetsResource(resource) === false) {
+ return throwBuilderRuntimeError("NOT_FOUND", "Assets resource not found");
+ }
+ return { resource: serializeAssetResource({ resource, state }) };
+};
+
+const createStoredAssetsResource = ({
+ name,
+ query,
+}: {
+ name: string;
+ query?: z.output<typeof assetQueryResourceConfigurationInput>;
+}) => {
+ const configuration = assetQueryResourceConfigurationInput.parse(query ?? {});
+ return {
+ name,
+ control: "system" as const,
+ method: "post" as const,
+ url: JSON.stringify(assetsResourceUrl),
+ searchParams: [],
+ headers: [
+ {
+ name: "Content-Type",
+ value: { type: "literal" as const, value: "application/json" },
+ },
+ ],
+ body: createAssetResourceBody(configuration),
+ };
+};
+
+export const createAssetsResource = (
+ state: Parameters<typeof createResource>[0],
+ input: z.output<typeof assetsResourceCreateInput>,
+ context: BuilderRuntimeContext
+) => {
+ const { name, scopeInstanceId, dataSourceName, query } = input;
+ return createResource(
+ state,
+ {
+ resource: createStoredAssetsResource({ name, query }),
+ scopeInstanceId,
+ dataSourceName: dataSourceName ?? name,
+ exposeAsDataSource: true,
+ },
+ context
+ );
+};
+
+export const updateAssetsResource = (
+ state: Parameters<typeof updateResource>[0],
+ input: z.output<typeof assetsResourceUpdateInput>,
+ context: BuilderRuntimeContext
+) => {
+ const resource = state.resources?.get(input.resourceId);
+ if (resource === undefined || isAssetsResource(resource) === false) {
+ return throwBuilderRuntimeError("NOT_FOUND", "Assets resource not found");
+ }
+ const { name, query: queryUpdate } = input.values;
+ const storedConfiguration = parseStructuredAssetQueryResourceBody(
+ resource.body
+ );
+ if (storedConfiguration === undefined && queryUpdate === undefined) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ "Stored Assets query configuration could not be decoded; replace or remove the query to repair it"
+ );
+ }
+ const currentQuery = storedConfiguration;
+ const query =
+ queryUpdate === undefined
+ ? currentQuery
+ : queryUpdate === null
+ ? createDefaultStructuredAssetQueryResourceConfiguration()
+ : assetQueryResourceConfigurationInput.parse({
+ ...currentQuery,
+ ...queryUpdate,
+ });
+ return updateResource(
+ state,
+ {
+ resourceId: input.resourceId,
+ values: createStoredAssetsResource({
+ name: name ?? resource.name,
+ query,
+ }),
+ scopeInstanceId: input.scopeInstanceId,
+ dataSourceName: input.dataSourceName,
+ exposeAsDataSource: true,
+ },
+ context,
+ { clearBody: false }
+ );
+};
diff --git a/packages/project-build/src/runtime/assets.test.ts b/packages/project-build/src/runtime/assets.test.ts
index d6706e7fba..60f2c1daf0 100644
--- a/packages/project-build/src/runtime/assets.test.ts
+++ b/packages/project-build/src/runtime/assets.test.ts
@@ -1128,7 +1128,10 @@ describe("updateAsset", () => {
expect(() =>
updateAsset(
{ assets: new Map([["font-1", fontAsset("font-1")]]) },
- { assetId: "font-1", values: { meta: { weight: "heavy" } } }
+ {
+ assetId: "font-1",
+ values: { meta: { weight: "heavy" as never } },
+ }
)
).toThrow("Invalid metadata for font asset");
@@ -1150,6 +1153,23 @@ describe("updateAsset", () => {
assetId: "font-1",
values: { meta: { family: "Rajdhani Display", weight: 600 } },
});
+
+ expect(
+ assetUpdateInput.parse({
+ assetId: "image-1",
+ values: { meta: { width: 1200 } },
+ })
+ ).toEqual({
+ assetId: "image-1",
+ values: { meta: { width: 1200 } },
+ });
+
+ expect(
+ assetUpdateInput.safeParse({
+ assetId: "file-1",
+ values: { meta: { arbitrary: true } },
+ }).success
+ ).toBe(false);
});
test("updates filename and description", () => {
diff --git a/packages/project-build/src/runtime/assets.ts b/packages/project-build/src/runtime/assets.ts
index dac4d1828e..7d4d7df7e0 100644
--- a/packages/project-build/src/runtime/assets.ts
+++ b/packages/project-build/src/runtime/assets.ts
@@ -21,6 +21,7 @@ import {
type StyleDecl,
type Styles,
assetType,
+ assetMetaUpdate,
fileAsset,
fontAsset,
imageAsset,
@@ -102,7 +103,11 @@ export const assetUpdateInput = z.object({
.optional(),
description: z.union([z.string(), z.null()]).optional(),
folderId: z.union([z.string().min(1), z.null()]).optional(),
- meta: z.record(z.string(), z.unknown()).optional(),
+ meta: assetMetaUpdate
+ .describe(
+ "Type-specific metadata: family/style/weight or variationAxes for fonts, width/height for images, and no fields for generic files."
+ )
+ .optional(),
})
.refine(
(values) => Object.keys(values).length > 0,
diff --git a/packages/project-build/src/runtime/audit.test.ts b/packages/project-build/src/runtime/audit.test.ts
index 94df686893..ebb1855138 100644
--- a/packages/project-build/src/runtime/audit.test.ts
+++ b/packages/project-build/src/runtime/audit.test.ts
@@ -2426,6 +2426,39 @@ describe("project audit and analysis", () => {
);
});
+ test("does not treat the read-only Assets query as a mutation", () => {
+ const resources: NonNullable<BuilderState["resources"]> = new Map(
+ state.resources
+ );
+ resources.set("posts", {
+ id: "posts",
+ name: "Posts",
+ control: "system",
+ method: "post",
+ url: '"/$resources/assets"',
+ headers: [],
+ searchParams: [],
+ body: "{ query: { where: { all: [] }, limit: 20, offset: 0 } }",
+ });
+ const dataSources: NonNullable<BuilderState["dataSources"]> = new Map(
+ state.dataSources
+ );
+ dataSources.set("posts-data", {
+ id: "posts-data",
+ type: "resource",
+ name: "Posts",
+ scopeInstanceId: "heading",
+ resourceId: "posts",
+ });
+
+ expect(
+ analyzeProject(
+ { ...state, resources, dataSources },
+ { scopes: ["security"], pageId: "home" }
+ ).matches
+ ).toEqual([]);
+ });
+
test("audits duplicate static page titles without flagging dynamic titles", () => {
const pages = new Map<string, Page>(state.pages.pages);
pages.set("home", {
diff --git a/packages/project-build/src/runtime/audit.ts b/packages/project-build/src/runtime/audit.ts
index 68faab1521..e5cee2d624 100644
--- a/packages/project-build/src/runtime/audit.ts
+++ b/packages/project-build/src/runtime/audit.ts
@@ -1,4 +1,4 @@
-import { isLiteralExpression } from "@webstudio-is/sdk";
+import { isLiteralExpression } from "@webstudio-is/expression";
import { z } from "zod";
import type { BuilderState } from "../state/builder-state";
import type { BuilderRuntimeContext } from "./context";
diff --git a/packages/project-build/src/runtime/binding-verification.ts b/packages/project-build/src/runtime/binding-verification.ts
index 24f97a3016..74c67b87ee 100644
--- a/packages/project-build/src/runtime/binding-verification.ts
+++ b/packages/project-build/src/runtime/binding-verification.ts
@@ -2,14 +2,16 @@ import {
decodeDataVariableId,
encodeDataVariableId,
findTreeInstanceIds,
- getExpressionIdentifiers,
- lintExpression,
ROOT_INSTANCE_ID,
SYSTEM_VARIABLE_ID,
- isLiteralExpression,
type Instance,
type Page,
} from "@webstudio-is/sdk";
+import {
+ getExpressionIdentifiers,
+ isLiteralExpression,
+ lintExpression,
+} from "@webstudio-is/expression";
import { z } from "zod";
import type { BuilderState } from "../state/builder-state";
import { throwBuilderRuntimeError } from "./errors";
diff --git a/packages/project-build/src/runtime/cutover.ts b/packages/project-build/src/runtime/cutover.ts
index b11f9b8a67..0271e18df1 100644
--- a/packages/project-build/src/runtime/cutover.ts
+++ b/packages/project-build/src/runtime/cutover.ts
@@ -251,6 +251,19 @@ export const builderRuntimeCutoverManifests = [
operationIds: ["variables.list", "resources.list"] as const,
callers: ["appRouter.api.variables", "appRouter.api.resources"] as const,
},
+ {
+ family: "assets-resource-operations",
+ operationIds: [
+ "assetsResources.list",
+ "assetsResources.get",
+ "assetsResources.create",
+ "assetsResources.update",
+ ] as const,
+ callers: [
+ "appRouter.api.assetsResources",
+ "MCP/CLI Assets resources",
+ ] as const,
+ },
{
family: "resource-mutations",
operationIds: [
diff --git a/packages/project-build/src/runtime/data.test.tsx b/packages/project-build/src/runtime/data.test.tsx
index bd8918da29..98a6f25026 100644
--- a/packages/project-build/src/runtime/data.test.tsx
+++ b/packages/project-build/src/runtime/data.test.tsx
@@ -41,6 +41,7 @@ import {
createResourceValue,
createResourceValueFromFormData,
decodeDataVariableName,
+ deleteResource,
deleteVariableMutable,
deleteUnusedDataVariables,
encodeDataVariableName,
@@ -312,28 +313,31 @@ test("creates data variable values from form input values", () => {
).toEqual({ type: "json", value: null });
expect(
createDataVariableValueFromInput({
- type: "string[]",
+ type: "json",
value: '["Draft", "Connected", "Published"]',
})
).toEqual({
- type: "string[]",
+ type: "json",
value: ["Draft", "Connected", "Published"],
});
- expect(() =>
+ expect(
createDataVariableValueFromInput({
- type: "string[]",
+ type: "json",
value: '["Draft", 1]',
})
- ).toThrow();
- expect(() =>
+ ).toEqual({ type: "json", value: ["Draft", 1] });
+ expect(
createDataVariableValueFromInput({
- type: "string[]",
- value: "",
+ type: "json",
+ value: "{ enabled: true }",
})
- ).toThrow();
+ ).toEqual({ type: "json", value: { enabled: true } });
expect(
- createDataVariableValueFromInput({ type: "string[]", value: null })
- ).toEqual({ type: "string[]", value: [] });
+ createDataVariableValueFromInput({
+ type: "json",
+ value: 'globalThis["not-json"]',
+ })
+ ).toEqual({ type: "json", value: null });
});
test("validates data variable number values", () => {
@@ -517,13 +521,13 @@ test("update data variable payload validates renamed variables", () => {
});
});
-test("update data variable payload preserves string array values", () => {
+test("update data variable payload preserves json array values", () => {
const variable: DataSource = {
id: "variable-1",
scopeInstanceId: "instance-1",
name: "stages",
type: "variable",
- value: { type: "string[]", value: ["Draft"] },
+ value: { type: "json", value: ["Draft"] },
};
expect(
@@ -531,7 +535,7 @@ test("update data variable payload preserves string array values", () => {
variable,
values: {
value: {
- type: "string[]",
+ type: "json",
value: ["Draft", "Connected", "Published"],
},
},
@@ -546,7 +550,7 @@ test("update data variable payload preserves string array values", () => {
op: "replace",
path: ["variable-1", "value"],
value: {
- type: "string[]",
+ type: "json",
value: ["Draft", "Connected", "Published"],
},
},
@@ -853,6 +857,12 @@ test("replace data source ids in expression", () => {
new Map([["oldId", "newId"]])
)
).toEqual("$ws$dataSource$newId = state");
+ expect(
+ replaceDataSourcesInExpression(
+ "https://example.com/cards.json",
+ new Map([["oldId", "newId"]])
+ )
+ ).toEqual("https://example.com/cards.json");
});
test("compute expression with decoded ids", () => {
@@ -3460,6 +3470,35 @@ describe("resource patch helpers", () => {
isUsed: false,
});
});
+
+ test("rejects deleting resources whose data source is referenced by expressions", () => {
+ const state = createResourceState();
+ state.instances.set("body", {
+ type: "instance",
+ id: "body",
+ component: "Body",
+ children: [
+ {
+ type: "expression",
+ value: `${encodeDataVariableId("data-source")}.data`,
+ },
+ ],
+ });
+ state.resources.set(resource.id, resource);
+ state.dataSources.set("data-source", {
+ id: "data-source",
+ scopeInstanceId: "body",
+ name: "Users",
+ type: "resource",
+ resourceId: resource.id,
+ });
+
+ expect(() =>
+ deleteResource(state, { resourceId: resource.id, force: true })
+ ).toThrow(
+ 'Resource data is referenced by expressions through "data-source"'
+ );
+ });
});
describe("resource expression form validation", () => {
diff --git a/packages/project-build/src/runtime/data.ts b/packages/project-build/src/runtime/data.ts
index 6c7ab42064..206ad2bac2 100644
--- a/packages/project-build/src/runtime/data.ts
+++ b/packages/project-build/src/runtime/data.ts
@@ -9,14 +9,12 @@ import {
findTreeInstanceIds,
findTreeInstanceIdsExcludingSlotDescendants,
getAllPages,
- getExpressionIdentifiers,
getStyleDeclKey,
- isLiteralExpression,
+ isAssetsResource,
ROOT_INSTANCE_ID,
resource,
SYSTEM_VARIABLE_ID,
systemParameter,
- transpileExpression,
type DataSource,
type DataSources,
type Instance,
@@ -28,6 +26,13 @@ import {
type Resources,
type WebstudioData,
} from "@webstudio-is/sdk";
+import {
+ getExpressionIdentifiers,
+ isLiteralExpression,
+ parseJsonExpression,
+ parseStringLiteralExpression,
+ transpileExpression,
+} from "@webstudio-is/expression";
import { z } from "zod";
import { produceWithPatches } from "immer";
import {
@@ -51,7 +56,7 @@ import {
throwBuilderValidationError,
type SemanticValidationIssue,
} from "./errors";
-import { getStaticStringLiteral, replaceTextValue } from "./text-replacement";
+import { replaceTextValue } from "./text-replacement";
import {
getNamedExpressionErrors,
getNamedExpressionValidationIssues,
@@ -297,29 +302,6 @@ export const validateDataVariableJsonValue = (expression: string) => {
: "";
};
-export const parseDataVariableJsonExpression = (expression: string) => {
- try {
- const executableExpression = transpileExpression({
- expression,
- executable: true,
- });
- return eval(`(${executableExpression})`);
- } catch {
- return undefined;
- }
-};
-
-export const validateDataVariableStringArrayValue = (expression: string) => {
- const expressionError = validateDataVariableJsonValue(expression);
- if (expressionError) {
- return expressionError;
- }
- const value = parseDataVariableJsonExpression(expression);
- return Array.isArray(value) && value.every((item) => typeof item === "string")
- ? ""
- : "Value expects a JSON array of strings";
-};
-
export const createDataVariableValueFromInput = ({
type,
value,
@@ -336,13 +318,7 @@ export const createDataVariableValueFromInput = ({
if (type === "boolean") {
return { type: "boolean", value: value !== null };
}
- if (type === "string[]") {
- return dataSourceVariableValue.parse({
- type: "string[]",
- value: value === null ? [] : parseDataVariableJsonExpression(value),
- });
- }
- const parsedValue = value ? parseDataVariableJsonExpression(value) : null;
+ const parsedValue = value ? parseJsonExpression(value) : null;
return {
type: "json",
value: parsedValue ?? null,
@@ -481,19 +457,25 @@ export const replaceDataSourcesInExpression = (
expression: string,
replacements: Map<DataSource["id"], DataSource["id"]>
) => {
- return transpileExpression({
- expression,
- executable: true,
- replaceVariable: (identifier) => {
- const dataSourceId = decodeDataSourceVariable(identifier);
- if (dataSourceId === undefined) {
- return;
- }
- return encodeDataSourceVariable(
- replacements.get(dataSourceId) ?? dataSourceId
- );
- },
- });
+ try {
+ return transpileExpression({
+ expression,
+ executable: true,
+ replaceVariable: (identifier) => {
+ const dataSourceId = decodeDataSourceVariable(identifier);
+ if (dataSourceId === undefined) {
+ return;
+ }
+ return encodeDataSourceVariable(
+ replacements.get(dataSourceId) ?? dataSourceId
+ );
+ },
+ });
+ } catch {
+ // Resource fields historically also store plain strings such as URLs.
+ // Copy those values unchanged instead of treating them as expressions.
+ return expression;
+ }
};
export const computeExpression = (
@@ -700,6 +682,22 @@ const traverseExpressions = ({
) => void | string;
}) => {
const pagesList = pages ? getAllPages(pages) : [];
+ const updateExpression = ({
+ expression,
+ instanceId,
+ args,
+ set,
+ }: {
+ expression: string;
+ instanceId: Instance["id"];
+ args?: string[];
+ set: (nextExpression: string) => void;
+ }) => {
+ const nextExpression = update(expression, instanceId, args);
+ if (nextExpression !== undefined) {
+ set(nextExpression);
+ }
+ };
let instanceIds =
startingInstanceId === undefined
@@ -721,37 +719,60 @@ const traverseExpressions = ({
startingInstanceId === ROOT_INSTANCE_ID
) {
const { rootInstanceId } = page;
- page.title = update(page.title, rootInstanceId) ?? page.title;
+ updateExpression({
+ expression: page.title,
+ instanceId: rootInstanceId,
+ set: (expression) => (page.title = expression),
+ });
if (page.meta.description) {
- page.meta.description =
- update(page.meta.description, rootInstanceId) ??
- page.meta.description;
+ updateExpression({
+ expression: page.meta.description,
+ instanceId: rootInstanceId,
+ set: (expression) => (page.meta.description = expression),
+ });
}
if (page.meta.excludePageFromSearch) {
- page.meta.excludePageFromSearch =
- update(page.meta.excludePageFromSearch, rootInstanceId) ??
- page.meta.excludePageFromSearch;
+ updateExpression({
+ expression: page.meta.excludePageFromSearch,
+ instanceId: rootInstanceId,
+ set: (expression) => (page.meta.excludePageFromSearch = expression),
+ });
}
if (page.meta.socialImageUrl) {
- page.meta.socialImageUrl =
- update(page.meta.socialImageUrl, rootInstanceId) ??
- page.meta.socialImageUrl;
+ updateExpression({
+ expression: page.meta.socialImageUrl,
+ instanceId: rootInstanceId,
+ set: (expression) => (page.meta.socialImageUrl = expression),
+ });
}
if (page.meta.language) {
- page.meta.language =
- update(page.meta.language, rootInstanceId) ?? page.meta.language;
+ updateExpression({
+ expression: page.meta.language,
+ instanceId: rootInstanceId,
+ set: (expression) => (page.meta.language = expression),
+ });
}
if (page.meta.status) {
- page.meta.status =
- update(page.meta.status, rootInstanceId) ?? page.meta.status;
+ updateExpression({
+ expression: page.meta.status,
+ instanceId: rootInstanceId,
+ set: (expression) => (page.meta.status = expression),
+ });
}
if (page.meta.redirect) {
- page.meta.redirect =
- update(page.meta.redirect, rootInstanceId) ?? page.meta.redirect;
+ updateExpression({
+ expression: page.meta.redirect,
+ instanceId: rootInstanceId,
+ set: (expression) => (page.meta.redirect = expression),
+ });
}
if (page.meta.custom) {
for (const item of page.meta.custom) {
- item.content = update(item.content, rootInstanceId) ?? item.content;
+ updateExpression({
+ expression: item.content,
+ instanceId: rootInstanceId,
+ set: (expression) => (item.content = expression),
+ });
}
}
}
@@ -764,7 +785,11 @@ const traverseExpressions = ({
}
for (const child of instance.children) {
if (child.type === "expression") {
- child.value = update(child.value, instance.id) ?? child.value;
+ updateExpression({
+ expression: child.value,
+ instanceId: instance.id,
+ set: (expression) => (child.value = expression),
+ });
}
}
}
@@ -774,13 +799,21 @@ const traverseExpressions = ({
continue;
}
if (prop.type === "expression") {
- prop.value = update(prop.value, prop.instanceId) ?? prop.value;
+ updateExpression({
+ expression: prop.value,
+ instanceId: prop.instanceId,
+ set: (expression) => (prop.value = expression),
+ });
continue;
}
if (prop.type === "action") {
for (const action of prop.value) {
- action.code =
- update(action.code, prop.instanceId, action.args) ?? action.code;
+ updateExpression({
+ expression: action.code,
+ instanceId: prop.instanceId,
+ args: action.args,
+ set: (expression) => (action.code = expression),
+ });
}
continue;
}
@@ -802,18 +835,33 @@ const traverseExpressions = ({
if (instanceId === undefined) {
continue;
}
- resource.url = update(resource.url, instanceId) ?? resource.url;
+ updateExpression({
+ expression: resource.url,
+ instanceId,
+ set: (expression) => (resource.url = expression),
+ });
for (const header of resource.headers) {
- header.value = update(header.value, instanceId) ?? header.value;
+ updateExpression({
+ expression: header.value,
+ instanceId,
+ set: (expression) => (header.value = expression),
+ });
}
if (resource.searchParams) {
for (const searchParam of resource.searchParams) {
- searchParam.value =
- update(searchParam.value, instanceId) ?? searchParam.value;
+ updateExpression({
+ expression: searchParam.value,
+ instanceId,
+ set: (expression) => (searchParam.value = expression),
+ });
}
}
if (resource.body) {
- resource.body = update(resource.body, instanceId) ?? resource.body;
+ updateExpression({
+ expression: resource.body,
+ instanceId,
+ set: (expression) => (resource.body = expression),
+ });
}
}
};
@@ -1570,7 +1618,7 @@ const normalizeResourceUrlInput = (value: string) => {
return value;
};
-const resourceExpressionInput = z
+export const resourceExpressionInput = z
.union([
z.string(),
z.object({ type: z.literal("literal"), value: z.string() }),
@@ -1624,8 +1672,8 @@ export const resourceFieldsUpdateInput = resourceFieldsInputBase
);
});
-const normalizeResourceExpressionInput = (
- value: z.infer<typeof resourceExpressionInput>
+export const normalizeResourceExpressionInput = (
+ value: string | { type: "literal"; value: unknown }
) => (typeof value === "string" ? value : JSON.stringify(value.value));
type ResourceFields = Omit<Resource, "id">;
@@ -1927,7 +1975,7 @@ const getResourceWarnings = ({
}: {
fields: Pick<
Resource,
- "method" | "url" | "body" | "headers" | "searchParams"
+ "control" | "method" | "url" | "body" | "headers" | "searchParams"
>;
state: Pick<BuilderState, "instances" | "dataSources">;
scopeInstanceId?: string;
@@ -1956,7 +2004,8 @@ const getResourceWarnings = ({
resourceId,
})
);
- if (exposeAsDataSource && fields.method !== "get") {
+ const isRenderTimeRead = fields.method === "get" || isAssetsResource(fields);
+ if (exposeAsDataSource && isRenderTimeRead === false) {
warnings.push({
severity: "warning",
code: "render_time_mutation_resource",
@@ -2612,8 +2661,10 @@ export const updateResource = (
| "styles"
>,
input: z.infer<typeof resourceUpdateInput>,
- context: BuilderRuntimeContext
+ context: BuilderRuntimeContext,
+ options?: { clearBody?: boolean }
) => {
+ const clearBody = options?.clearBody === true;
const values = normalizeResourceFieldsUpdateInput(input.values);
validateResourceFields(values, ["values"]);
const build = getRequiredBuildData(state);
@@ -2622,6 +2673,7 @@ export const updateResource = (
return throwBuilderRuntimeError("NOT_FOUND", "Resource not found");
}
if (
+ clearBody === false &&
Object.values(values).every((value) => value === undefined) &&
input.dataSourceName === undefined &&
input.scopeInstanceId === undefined &&
@@ -2636,6 +2688,7 @@ export const updateResource = (
const nextResource = createResourceValue({
...resource,
...values,
+ ...(clearBody ? { body: undefined } : {}),
});
const dataSource = build.dataSources.find(
(dataSource) =>
@@ -2728,7 +2781,7 @@ export const replaceResourceText = (
if (input.fields.includes("url")) {
fields.push({
field: "url",
- before: getStaticStringLiteral(resource.url),
+ before: parseStringLiteralExpression(resource.url),
});
}
for (const { field, before } of fields) {
@@ -2940,7 +2993,10 @@ export const upsertResourceProp = (
};
export const deleteResource = (
- state: Pick<BuilderState, "dataSources" | "resources" | "props">,
+ state: Pick<
+ BuilderState,
+ "pages" | "instances" | "dataSources" | "resources" | "props"
+ >,
input: z.infer<typeof resourceDeleteInput>
) => {
const resource = findResource(
@@ -2950,9 +3006,42 @@ export const deleteResource = (
if (resource === undefined) {
return throwBuilderRuntimeError("NOT_FOUND", "Resource not found");
}
+ if (state.pages === undefined || state.instances === undefined) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ "Pages or instances namespace is missing"
+ );
+ }
+ const dataSources = getRequiredDataSources(state);
+ const resourceDataSourceIds = new Set(
+ Array.from(dataSources.values())
+ .filter(
+ (dataSource) =>
+ dataSource.type === "resource" &&
+ dataSource.resourceId === resource.id
+ )
+ .map((dataSource) => dataSource.id)
+ );
+ const usedDataSources = findUsedVariables({
+ startingInstanceId: ROOT_INSTANCE_ID,
+ pages: state.pages,
+ instances: state.instances,
+ props: getRequiredProps(state),
+ dataSources,
+ resources: getRequiredResources(state),
+ });
+ const referencedDataSourceIds = Array.from(resourceDataSourceIds).filter(
+ (dataSourceId) => usedDataSources.has(dataSourceId)
+ );
+ if (referencedDataSourceIds.length > 0) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ `Resource data is referenced by expressions through ${referencedDataSourceIds.map((id) => JSON.stringify(id)).join(", ")}. Rebind or remove those expressions before deleting the resource.`
+ );
+ }
const resultPayload = createResourceDeletePayload({
resource,
- dataSources: getRequiredDataSources(state).values(),
+ dataSources: dataSources.values(),
props: getRequiredProps(state).values(),
force: input.force,
});
diff --git a/packages/project-build/src/runtime/expression-validation.ts b/packages/project-build/src/runtime/expression-validation.ts
index a2f75b2084..692d12b5c6 100644
--- a/packages/project-build/src/runtime/expression-validation.ts
+++ b/packages/project-build/src/runtime/expression-validation.ts
@@ -1,4 +1,4 @@
-import { lintExpression } from "@webstudio-is/sdk";
+import { lintExpression } from "@webstudio-is/expression";
import { z } from "zod";
import type { SemanticValidationIssue } from "./errors";
diff --git a/packages/project-build/src/runtime/output-schemas.ts b/packages/project-build/src/runtime/output-schemas.ts
index dd91abfabe..4cf46f9f53 100644
--- a/packages/project-build/src/runtime/output-schemas.ts
+++ b/packages/project-build/src/runtime/output-schemas.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
import {
+ assetQueryWhereExpression,
assetType,
compilerSettings,
dataSourceVariableValue,
@@ -11,6 +12,12 @@ import {
prop,
instance,
} from "@webstudio-is/sdk";
+import {
+ assetQuerySort,
+ assetResourceContentOptions,
+ assetResourceOutputSelection,
+ defaultAssetResourceOutputSelection,
+} from "@webstudio-is/content-engine";
import { paginatedOutputMetadataSchema } from "./output";
import { builderNamespaces } from "../contracts/namespaces";
import { builderPatchSchema } from "../contracts/patch";
@@ -188,6 +195,26 @@ const resource = looseObject({
exposedAsDataSource: z.boolean(),
dataSourceId: id.optional(),
});
+const assetResourceConfiguration = looseObject({
+ where: assetQueryWhereExpression,
+ sort: z.array(assetQuerySort),
+ limit: z.string(),
+ offset: z.string(),
+ output: assetResourceOutputSelection.default(
+ defaultAssetResourceOutputSelection
+ ),
+ content: assetResourceContentOptions,
+});
+const assetResource = looseObject({
+ resourceId: id,
+ name: z.string(),
+ scopeInstanceId: id.optional(),
+ dataSourceId: id.optional(),
+ dataSourceName: z.string().optional(),
+ mode: z.enum(["query", "invalid"]),
+ query: assetResourceConfiguration.optional(),
+ configurationError: z.string().optional(),
+});
const asset = looseObject({
id,
name: z.string(),
@@ -580,6 +607,13 @@ export const runtimeOutputSchemas = {
resources: z.array(resource),
...outputPage,
}),
+ "assetsResources.list": looseObject({
+ resources: z.array(assetResource),
+ ...outputPage,
+ }),
+ "assetsResources.get": looseObject({ resource: assetResource }),
+ "assetsResources.create": resourceMutationResult,
+ "assetsResources.update": resourceMutationResult.partial({ warnings: true }),
"resources.create": resourceMutationResult,
"resources.update": resourceMutationResult.partial({ warnings: true }),
"resources.replaceText": looseObject({
diff --git a/packages/project-build/src/runtime/page-copy.ts b/packages/project-build/src/runtime/page-copy.ts
index 546a6c52ee..e0eae9cc79 100644
--- a/packages/project-build/src/runtime/page-copy.ts
+++ b/packages/project-build/src/runtime/page-copy.ts
@@ -6,6 +6,7 @@ import {
import { isFragmentContentModeCopyableProp } from "./content-mode-copy-policy";
import { nanoid } from "nanoid";
import { z } from "zod";
+import { parseStringLiteralExpression } from "@webstudio-is/expression";
import {
createWebstudioDataFromBuild,
findAvailableVariables,
@@ -38,7 +39,6 @@ import { paginateOutput, type PaginatedOutputInput } from "./output";
import { pageCopyNamespaces } from "../contracts/namespaces";
import { throwBuilderRuntimeError } from "./errors";
import { createRuntimeMutation } from "./mutation";
-import { getStaticStringLiteral } from "./text-replacement";
import {
collectExclusiveInstanceIds,
createInstanceCleanupPayload,
@@ -664,7 +664,7 @@ const applyCopiedPageTextSubstitutions = ({
return;
}
const replaceFixedExpression = (expression: string) => {
- const value = getStaticStringLiteral(expression);
+ const value = parseStringLiteralExpression(expression);
const replacement =
value === undefined ? undefined : replacementsByText.get(value);
return replacement === undefined ? expression : JSON.stringify(replacement);
diff --git a/packages/project-build/src/runtime/project-settings.test.ts b/packages/project-build/src/runtime/project-settings.test.ts
index 85b75f9b3f..574e6e516b 100644
--- a/packages/project-build/src/runtime/project-settings.test.ts
+++ b/packages/project-build/src/runtime/project-settings.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, test } from "vitest";
import { createBasicAuthRoute } from "@webstudio-is/wsauth";
import type { BuilderState } from "../state/builder-state";
import {
+ getProjectBasicAuthCredentials,
parseProjectAuthRoutes,
validateContactEmail,
validateProjectAuth,
@@ -259,6 +260,27 @@ describe("project settings runtime", () => {
]);
});
+ test("resolves basic auth credentials for a matching preview route", () => {
+ const auth = JSON.stringify({
+ version: 1,
+ routes: {
+ "/*": {
+ method: "basic",
+ login: "admin",
+ password: "secret",
+ },
+ },
+ });
+
+ expect(getProjectBasicAuthCredentials(auth, "/blog/post")).toEqual({
+ username: "admin",
+ password: "secret",
+ });
+ expect(getProjectBasicAuthCredentials(undefined, "/blog/post")).toBe(
+ undefined
+ );
+ });
+
test("validates project auth route input", () => {
const authRoutes = [
createBasicAuthRoute({
diff --git a/packages/project-build/src/runtime/registry.test.ts b/packages/project-build/src/runtime/registry.test.ts
index 76ad07bcbd..27967b34ed 100644
--- a/packages/project-build/src/runtime/registry.test.ts
+++ b/packages/project-build/src/runtime/registry.test.ts
@@ -84,6 +84,7 @@ const paginatedReadOperationIds = [
"cssVariables.list",
"variables.list",
"resources.list",
+ "assetsResources.list",
"assets.list",
"fonts.list",
] as const;
@@ -1689,6 +1690,236 @@ describe("builder runtime read families", () => {
});
});
+ test("creates a default Assets query and supports explicit configuration", () => {
+ const defaultQuery = executeBuilderRuntimeOperation({
+ id: "assetsResources.create",
+ state,
+ input: {
+ name: "All assets",
+ scopeInstanceId: "heading",
+ },
+ context: {
+ ...context,
+ createId: (() => {
+ const ids = ["all-assets-resource", "all-assets-data-source"];
+ return () => ids.shift() ?? "id";
+ })(),
+ },
+ }) as {
+ payload: Array<{
+ namespace: string;
+ patches: Array<{ op: string; value?: unknown }>;
+ }>;
+ };
+ const defaultResource = defaultQuery.payload
+ .find(({ namespace }) => namespace === "resources")
+ ?.patches.find(({ op }) => op === "add")?.value;
+ expect(defaultResource).toMatchObject({
+ id: "all-assets-resource",
+ control: "system",
+ method: "post",
+ url: '"/$resources/assets"',
+ headers: [
+ {
+ name: "Content-Type",
+ value: '"application/json"',
+ },
+ ],
+ });
+ expect(defaultResource).toHaveProperty(
+ "body",
+ expect.stringContaining('"url"')
+ );
+
+ const created = executeBuilderRuntimeOperation({
+ id: "assetsResources.create",
+ state,
+ input: {
+ name: "Blog posts",
+ scopeInstanceId: "heading",
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "system.params.slug",
+ },
+ ],
+ },
+ limit: "1",
+ content: { mode: "markdown-body", maxBytes: 65_536 },
+ },
+ },
+ context: {
+ ...context,
+ createId: (() => {
+ const ids = ["asset-resource", "asset-data-source"];
+ return () => ids.shift() ?? "id";
+ })(),
+ },
+ });
+ expect(created).toMatchObject({
+ result: {
+ resourceId: "asset-resource",
+ dataSourceId: "asset-data-source",
+ warnings: [],
+ },
+ });
+ const createdMutation = created as {
+ payload: Array<{
+ namespace: string;
+ patches: Array<{ op: string; value?: unknown }>;
+ }>;
+ };
+ const resourcePatch = createdMutation.payload
+ .find(({ namespace }) => namespace === "resources")
+ ?.patches.find(({ op }) => op === "add");
+ const dataSourcePatch = createdMutation.payload
+ .find(({ namespace }) => namespace === "dataSources")
+ ?.patches.find(({ op }) => op === "add");
+ expect(resourcePatch?.value).toMatchObject({
+ id: "asset-resource",
+ control: "system",
+ method: "post",
+ url: '"/$resources/assets"',
+ });
+ expect(resourcePatch?.value).toHaveProperty(
+ "body",
+ expect.stringContaining('"properties"')
+ );
+
+ const queryState = {
+ ...state,
+ resources: new Map([
+ ...state.resources,
+ ["asset-resource", resourcePatch?.value],
+ ]),
+ dataSources: new Map([
+ ...state.dataSources,
+ ["asset-data-source", dataSourcePatch?.value],
+ ]),
+ } as BuilderState;
+ const inspected = executeBuilderRuntimeOperation({
+ id: "assetsResources.get",
+ state: queryState,
+ input: { resourceId: "asset-resource" },
+ });
+ expect(inspected).toEqual({
+ resource: expect.objectContaining({
+ resourceId: "asset-resource",
+ name: "Blog posts",
+ scopeInstanceId: "heading",
+ mode: "query",
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "system.params.slug",
+ },
+ ],
+ },
+ sort: [],
+ limit: "1",
+ offset: "0",
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["url"], ["width"], ["height"]],
+ },
+ content: { mode: "markdown-body", maxBytes: 65_536 },
+ },
+ }),
+ });
+ expect(
+ executeBuilderRuntimeOperation({
+ id: "assetsResources.list",
+ state: queryState,
+ input: {},
+ })
+ ).toMatchObject({ total: 1, returnedCount: 1 });
+
+ const updated = executeBuilderRuntimeOperation({
+ id: "assetsResources.update",
+ state: queryState,
+ input: {
+ resourceId: "asset-resource",
+ values: {
+ query: {
+ limit: "2",
+ },
+ },
+ },
+ context,
+ });
+ expect((updated as { payload: unknown }).payload).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ namespace: "resources" }),
+ ])
+ );
+ const updatedPayload = JSON.stringify(
+ (updated as { payload: unknown }).payload
+ );
+ expect(updatedPayload).toContain("properties");
+ expect(updatedPayload).toContain("system.params.slug");
+ expect(updatedPayload).toContain("markdown-body");
+ expect(updatedPayload).toContain("limit: 2");
+
+ const reset = executeBuilderRuntimeOperation({
+ id: "assetsResources.update",
+ state: queryState,
+ input: {
+ resourceId: "asset-resource",
+ values: { query: null },
+ },
+ context,
+ });
+ expect(JSON.stringify((reset as { payload: unknown }).payload)).toContain(
+ '\\"/$resources/assets\\"'
+ );
+ const resetPayload = JSON.stringify(
+ (reset as { payload: unknown }).payload
+ );
+ expect(resetPayload).toContain('\"method\":\"post\"');
+ expect(resetPayload).toContain(
+ 'fields: [[\\"url\\"], [\\"width\\"], [\\"height\\"]]'
+ );
+
+ const storedQueryResource = queryState.resources?.get("asset-resource");
+ if (storedQueryResource === undefined) {
+ throw new Error("Expected queried Assets resource");
+ }
+ const invalidQueryState = {
+ ...queryState,
+ resources: new Map([
+ ...(queryState.resources ?? []),
+ [
+ "invalid-asset-resource",
+ {
+ ...storedQueryResource,
+ id: "invalid-asset-resource",
+ body: "invalid query configuration",
+ },
+ ],
+ ]),
+ } as BuilderState;
+ const repaired = executeBuilderRuntimeOperation({
+ id: "assetsResources.update",
+ state: invalidQueryState,
+ input: {
+ resourceId: "invalid-asset-resource",
+ values: { query: null },
+ scopeInstanceId: "heading",
+ },
+ context,
+ });
+ expect(
+ JSON.stringify((repaired as { payload: unknown }).payload)
+ ).toContain('\\"/$resources/assets\\"');
+ });
+
test("replaces bounded fixed resource URLs without changing expressions", () => {
const resource = state.resources.get("resource");
if (resource === undefined) {
@@ -2157,6 +2388,8 @@ describe("builder runtime registry", () => {
["variables.update", {}],
["variables.delete", {}],
["variables.deleteUnused", []],
+ ["assetsResources.create", {}],
+ ["assetsResources.update", {}],
["resources.create", {}],
["resources.update", {}],
["resources.replaceText", {}],
@@ -2439,6 +2672,10 @@ describe("builder runtime registry", () => {
},
},
],
+ [
+ "assetsResources.create",
+ { name: "All assets", scopeInstanceId: "heading" },
+ ],
["resources.delete", { resourceId: "resource", force: true }],
[
"assetFolders.update",
diff --git a/packages/project-build/src/runtime/registry.ts b/packages/project-build/src/runtime/registry.ts
index a754cfae7e..d6cb2452bb 100644
--- a/packages/project-build/src/runtime/registry.ts
+++ b/packages/project-build/src/runtime/registry.ts
@@ -18,6 +18,7 @@ import { pageCopyNamespaces } from "../contracts/namespaces";
import { builderRuntimeContext, type BuilderRuntimeContext } from "./context";
import { z } from "zod";
import * as assets from "./assets";
+import * as assetResources from "./asset-resources";
import * as bindingVerification from "./binding-verification";
import * as assetFolders from "./asset-folders";
import * as components from "./components";
@@ -1696,6 +1697,70 @@ export const builderRuntimeOperations = [
scopedInstanceListInput,
({ state, input }) => data.listResources(state, input)
),
+ runtimeOperation(
+ "assetsResources.list",
+ api("list-assets-resources", "listAssetsResources"),
+ readContract(dataNamespaces),
+ assetResources.assetsResourceListInput,
+ ({ state, input }) => assetResources.listAssetsResources(state, input)
+ ),
+ runtimeOperation(
+ "assetsResources.get",
+ api("get-assets-resource", "getAssetsResource"),
+ readContract(dataNamespaces),
+ assetResources.assetsResourceGetInput,
+ ({ state, input }) => assetResources.getAssetsResource(state, input)
+ ),
+ runtimeOperation(
+ "assetsResources.create",
+ api("create-assets-resource", "createAssetsResource"),
+ mutationContract({
+ readNamespaces: [
+ "pages",
+ "instances",
+ "props",
+ ...dataNamespaces,
+ ...styleNamespaces,
+ "breakpoints",
+ ],
+ writeNamespaces: [
+ "pages",
+ "instances",
+ "props",
+ ...dataNamespaces,
+ ...styleNamespaces,
+ "breakpoints",
+ ],
+ }),
+ assetResources.assetsResourceCreateInput,
+ ({ state, input, context }) =>
+ assetResources.createAssetsResource(state, input, context)
+ ),
+ runtimeOperation(
+ "assetsResources.update",
+ api("update-assets-resource", "updateAssetsResource"),
+ mutationContract({
+ readNamespaces: [
+ "pages",
+ "instances",
+ "props",
+ ...dataNamespaces,
+ ...styleNamespaces,
+ "breakpoints",
+ ],
+ writeNamespaces: [
+ "pages",
+ "instances",
+ "props",
+ ...dataNamespaces,
+ ...styleNamespaces,
+ "breakpoints",
+ ],
+ }),
+ assetResources.assetsResourceUpdateInput,
+ ({ state, input, context }) =>
+ assetResources.updateAssetsResource(state, input, context)
+ ),
runtimeOperation(
"resources.create",
api("create-resource", "createResource"),
@@ -1808,7 +1873,7 @@ export const builderRuntimeOperations = [
"resources.delete",
api("delete-resource", "deleteResource"),
mutationContract({
- readNamespaces: [...dataNamespaces, "props"],
+ readNamespaces: ["pages", "instances", ...dataNamespaces, "props"],
writeNamespaces: [...dataNamespaces, "props"],
}),
data.resourceDeleteInput,
diff --git a/packages/project-build/src/runtime/search.ts b/packages/project-build/src/runtime/search.ts
index 03a0a49aeb..71ba3dd9ac 100644
--- a/packages/project-build/src/runtime/search.ts
+++ b/packages/project-build/src/runtime/search.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
-import { isLiteralExpression, type StyleDecl } from "@webstudio-is/sdk";
+import { isLiteralExpression } from "@webstudio-is/expression";
+import { isAssetsResource, type StyleDecl } from "@webstudio-is/sdk";
import { hasTopLevelJsonLdContext } from "@webstudio-is/sdk/runtime";
import { validateJsonLdWithSchemaOrg } from "@webstudio-is/sdk/schema-org";
import { ariaAttributes, ariaRoles } from "@webstudio-is/html-data";
@@ -1214,7 +1215,11 @@ export const analyzeProject = (
continue;
}
const resource = state.resources.get(dataSource.resourceId);
- if (resource === undefined || resource.method === "get") {
+ if (
+ resource === undefined ||
+ resource.method === "get" ||
+ isAssetsResource(resource)
+ ) {
continue;
}
matches.push({
diff --git a/packages/project-build/src/runtime/text-replacement.ts b/packages/project-build/src/runtime/text-replacement.ts
index 6a7919e74b..e289368984 100644
--- a/packages/project-build/src/runtime/text-replacement.ts
+++ b/packages/project-build/src/runtime/text-replacement.ts
@@ -10,17 +10,3 @@ export const replaceTextValue = (value: string, input: TextReplacementInput) =>
? input.replace
: value
: value.replaceAll(input.find, input.replace);
-
-export const getStaticStringLiteral = (expression: string | undefined) => {
- if (expression === undefined) {
- return;
- }
- try {
- const value = JSON.parse(expression);
- return typeof value === "string" && JSON.stringify(value) === expression
- ? value
- : undefined;
- } catch {
- return;
- }
-};
diff --git a/packages/project-build/src/schema.ts b/packages/project-build/src/schema.ts
index e6ebcaa4ce..27afab862f 100644
--- a/packages/project-build/src/schema.ts
+++ b/packages/project-build/src/schema.ts
@@ -1,4 +1,6 @@
import {
+ asset,
+ assetFolder,
breakpoint,
dataSource,
deployment,
@@ -65,7 +67,7 @@ const serializedBuildShape = {
export const serializedBuild: z.ZodObject<typeof serializedBuildShape> =
z.object(serializedBuildShape);
-const serializedBuilderState = serializedBuild
+export const serializedBuilderState = serializedBuild
.omit({
id: true,
projectId: true,
@@ -74,8 +76,14 @@ const serializedBuilderState = serializedBuild
updatedAt: true,
deployment: true,
})
- .partial();
+ .partial()
+ .extend({
+ assets: z.array(entry(asset)).optional(),
+ assetFolders: z.array(entry(assetFolder)).optional(),
+ });
-export const serializedRestorePointState = serializedBuilderState.extend({
- marketplaceProduct: marketplaceProduct.nullable().optional(),
-});
+export const serializedRestorePointState = serializedBuilderState
+ .omit({ assets: true })
+ .extend({
+ marketplaceProduct: marketplaceProduct.nullable().optional(),
+ });
diff --git a/packages/project-build/src/state/adapters.test.ts b/packages/project-build/src/state/adapters.test.ts
index 2d52ba7e75..9766f8149f 100644
--- a/packages/project-build/src/state/adapters.test.ts
+++ b/packages/project-build/src/state/adapters.test.ts
@@ -102,6 +102,28 @@ test("adapts array build data snapshots into normalized builder state", () => {
expect(state.props).toEqual(new Map(build.props));
});
+test("normalizes legacy Assets resources at every state boundary", () => {
+ const resource = {
+ id: "assets",
+ name: "Assets",
+ control: "system" as const,
+ method: "get" as const,
+ url: '"/$resources/assets"',
+ searchParams: [],
+ headers: [],
+ };
+
+ const fromSnapshot = createBuilderStateFromSnapshot({
+ resources: [[resource.id, resource]],
+ });
+ const fromBuild = createBuilderStateFromBuildData({ resources: [resource] });
+
+ expect(fromSnapshot.resources?.get(resource.id)?.method).toBe("post");
+ expect(fromSnapshot.resources?.get(resource.id)?.body).toBeDefined();
+ expect(fromBuild.resources?.get(resource.id)?.method).toBe("post");
+ expect(resource.method).toBe("get");
+});
+
test("adapts compact build snapshots into normalized builder state", () => {
const state = createBuilderStateFromCompactBuild({
pages,
diff --git a/packages/project-build/src/state/adapters.ts b/packages/project-build/src/state/adapters.ts
index 6569b58b68..16cdf6e724 100644
--- a/packages/project-build/src/state/adapters.ts
+++ b/packages/project-build/src/state/adapters.ts
@@ -2,6 +2,7 @@ import {
migratePages,
serializePages,
} from "@webstudio-is/project-migrations/pages";
+import { migrateResourcesMutable } from "@webstudio-is/project-migrations/resources";
import {
type BuilderState,
type BuilderStateValueByNamespace,
@@ -111,6 +112,12 @@ const normalizeProjectSettings = (state: BuilderState) => {
removeLegacyProjectSettingsFromPages(state.pages);
};
+const normalizeResources = (state: BuilderState) => {
+ if (state.resources !== undefined) {
+ migrateResourcesMutable(state.resources.values());
+ }
+};
+
const setClonedBuilderStateValue = <Namespace extends BuilderNamespace>(
state: BuilderState,
namespace: Namespace,
@@ -144,6 +151,7 @@ export const createBuilderStateFromStores = (
}
normalizeProjectSettings(state);
+ normalizeResources(state);
return state;
};
@@ -165,6 +173,7 @@ export const createBuilderStateFromSnapshot = (
}
normalizeProjectSettings(state);
+ normalizeResources(state);
return state;
};
diff --git a/packages/project-migrations/package.json b/packages/project-migrations/package.json
index fb62ea537f..5097c23b21 100644
--- a/packages/project-migrations/package.json
+++ b/packages/project-migrations/package.json
@@ -16,6 +16,11 @@
"webstudio": "./src/pages.ts",
"types": "./lib/types/pages.d.ts",
"import": "./lib/pages.js"
+ },
+ "./resources": {
+ "webstudio": "./src/resources.ts",
+ "types": "./lib/types/resources.d.ts",
+ "import": "./lib/resources.js"
}
},
"files": [
@@ -24,7 +29,7 @@
],
"sideEffects": false,
"scripts": {
- "build": "rm -rf lib && esbuild src/index.ts src/pages.ts --outdir=lib --bundle --format=esm --packages=external",
+ "build": "rm -rf lib && esbuild src/index.ts src/pages.ts src/resources.ts --outdir=lib --bundle --format=esm --packages=external",
"dts": "tsc --project tsconfig.dts.json",
"typecheck": "tsc --noEmit",
"test": "vitest run"
diff --git a/packages/project-migrations/src/index.ts b/packages/project-migrations/src/index.ts
index 95725808c9..5711ccff76 100644
--- a/packages/project-migrations/src/index.ts
+++ b/packages/project-migrations/src/index.ts
@@ -1,5 +1,6 @@
import type { WebstudioData } from "@webstudio-is/sdk";
import { migratePages } from "./pages";
+import { migrateResourcesMutable } from "./resources";
import { migrateStylesMutable } from "./styles";
export { migratePages, serializePages, type SerializedPages } from "./pages";
@@ -12,5 +13,6 @@ export { migratePages, serializePages, type SerializedPages } from "./pages";
*/
export const migrateWebstudioDataMutable = (data: WebstudioData) => {
data.pages = migratePages(data.pages);
+ migrateResourcesMutable(data.resources.values());
migrateStylesMutable(data.styles);
};
diff --git a/packages/project-migrations/src/resources.test.ts b/packages/project-migrations/src/resources.test.ts
new file mode 100644
index 0000000000..0ccd0964f4
--- /dev/null
+++ b/packages/project-migrations/src/resources.test.ts
@@ -0,0 +1,60 @@
+import { expect, test } from "vitest";
+import {
+ parseStructuredAssetQueryResourceBody,
+ type Resource,
+} from "@webstudio-is/sdk";
+import { migrateResourcesMutable } from "./resources";
+
+const createResource = (values: Partial<Resource> = {}): Resource => ({
+ id: "assets",
+ name: "Assets",
+ control: "system",
+ method: "get",
+ url: '"/$resources/assets"',
+ searchParams: [],
+ headers: [],
+ ...values,
+});
+
+test("migrates Assets resources to the structured query contract", () => {
+ const resources = new Map([["assets", createResource()]]);
+
+ migrateResourcesMutable(resources.values());
+ migrateResourcesMutable(resources.values());
+
+ const resource = resources.get("assets");
+ expect(resource).toMatchObject({
+ method: "post",
+ headers: [
+ {
+ name: "Content-Type",
+ value: '"application/json"',
+ },
+ ],
+ });
+ expect(parseStructuredAssetQueryResourceBody(resource?.body)).toMatchObject({
+ where: { all: [] },
+ sort: [],
+ limit: "1000",
+ offset: "0",
+ content: { mode: "none" },
+ });
+});
+
+test("leaves unrelated and already migrated resources unchanged", () => {
+ const external = createResource({
+ id: "external",
+ control: undefined,
+ url: '"https://example.com/assets"',
+ });
+ const queried = createResource({ method: "post", body: "existing" });
+ const resources = new Map([
+ [external.id, external],
+ [queried.id, queried],
+ ]);
+ const before = structuredClone(resources);
+
+ migrateResourcesMutable(resources.values());
+
+ expect(resources).toEqual(before);
+});
diff --git a/packages/project-migrations/src/resources.ts b/packages/project-migrations/src/resources.ts
new file mode 100644
index 0000000000..9931b60925
--- /dev/null
+++ b/packages/project-migrations/src/resources.ts
@@ -0,0 +1,33 @@
+import {
+ createDefaultStructuredAssetQueryResourceConfiguration,
+ createStructuredAssetQueryResourceBody,
+ hasAssetsResourceUrl,
+ type Resource,
+} from "@webstudio-is/sdk";
+import { assetResourceLimits } from "@webstudio-is/sdk/asset-resource-limits";
+
+/** Converts persisted Assets resources to the single structured-query contract. */
+export const migrateResourcesMutable = (resources: Iterable<Resource>) => {
+ for (const resource of resources) {
+ if (resource.method !== "get" || hasAssetsResourceUrl(resource) === false) {
+ continue;
+ }
+ resource.method = "post";
+ resource.headers = [
+ ...resource.headers.filter(
+ ({ name }) => name.toLowerCase() !== "content-type"
+ ),
+ {
+ name: "Content-Type",
+ value: JSON.stringify("application/json"),
+ },
+ ];
+ resource.body = createStructuredAssetQueryResourceBody({
+ ...createDefaultStructuredAssetQueryResourceConfiguration(),
+ // Queryless Assets resources returned the complete project collection.
+ // Preserve that behavior during normalization while new resources keep
+ // the smaller authoring default.
+ limit: String(assetResourceLimits.resultCount),
+ });
+ }
+};
diff --git a/packages/project/src/db/build-patch.ts b/packages/project/src/db/build-patch.ts
index 37812bad3b..5583a4ff20 100644
--- a/packages/project/src/db/build-patch.ts
+++ b/packages/project/src/db/build-patch.ts
@@ -2,7 +2,7 @@ import {
deleteAssetFoldersWithClient,
patchAssetFoldersWithClient,
patchAssets,
-} from "@webstudio-is/asset-uploader/index.server";
+} from "@webstudio-is/asset-uploader/server";
import type { Build } from "@webstudio-is/project-build";
import { loadRawBuildById } from "@webstudio-is/project-build/server";
import type { Database } from "@webstudio-is/postgrest/index.server";
diff --git a/packages/protocol/package.json b/packages/protocol/package.json
index 72f2b0804d..41ff1dda8b 100644
--- a/packages/protocol/package.json
+++ b/packages/protocol/package.json
@@ -6,7 +6,7 @@
"homepage": "https://webstudio.is",
"type": "module",
"scripts": {
- "build": "rm -rf lib && esbuild src/index.ts src/fixtures.ts src/schema.ts --outdir=lib --bundle --format=esm --conditions=webstudio",
+ "build": "rm -rf lib && esbuild src/index.ts src/fixtures.ts src/schema.ts src/asset-resource-api.ts --outdir=lib --bundle --format=esm --conditions=webstudio",
"dts": "tsc --project tsconfig.dts.json",
"test": "vitest run",
"typecheck": "tsc --noEmit"
@@ -14,12 +14,15 @@
"dependencies": {
"@emotion/hash": "^0.9.2",
"@webstudio-is/css-engine": "workspace:*",
+ "@webstudio-is/content-engine": "workspace:*",
"@webstudio-is/project-migrations": "workspace:*",
"@webstudio-is/sdk": "workspace:*",
"zod": "^4.4.3"
},
"devDependencies": {
+ "@apidevtools/swagger-parser": "^12.1.0",
"@webstudio-is/project-build": "workspace:*",
+ "@webstudio-is/query-builder": "workspace:*",
"@webstudio-is/tsconfig": "workspace:*",
"@webstudio-is/wsauth": "workspace:*",
"vitest": "^3.1.2"
@@ -42,6 +45,12 @@
"types": "./lib/types/fixtures.d.ts",
"import": "./lib/fixtures.js",
"default": "./src/fixtures.ts"
+ },
+ "./asset-resource-api": {
+ "webstudio": "./src/asset-resource-api.ts",
+ "types": "./lib/types/asset-resource-api.d.ts",
+ "import": "./lib/asset-resource-api.js",
+ "default": "./src/asset-resource-api.ts"
}
},
"files": [
diff --git a/packages/protocol/src/asset-resource-api.test.ts b/packages/protocol/src/asset-resource-api.test.ts
new file mode 100644
index 0000000000..3d739ebc48
--- /dev/null
+++ b/packages/protocol/src/asset-resource-api.test.ts
@@ -0,0 +1,447 @@
+import { describe, expect, test } from "vitest";
+import SwaggerParser from "@apidevtools/swagger-parser";
+import {
+ assetObservedFieldType,
+ assetQueryStandardFields,
+ contentEngineLimits,
+} from "@webstudio-is/content-engine";
+import { loadOpenApiQueryDefinition } from "@webstudio-is/query-builder";
+import { assetResourceLimits } from "@webstudio-is/sdk/asset-resource-limits";
+import {
+ assetFolderCreateRequest,
+ assetFolderUpdateRequest,
+ assetMetadataUpdate,
+ assetResourceApiOperations,
+ assetUploadReservationRequest,
+ createAssetQueryJsonSchema,
+ createAssetResourceOpenApi,
+} from "./asset-resource-api";
+
+const defaultCatalog = {
+ format: "webstudio-builder-asset-field-catalog" as const,
+ version: 1 as const,
+ canonicalRevision: `sha256:${"a".repeat(64)}`,
+ documentCount: 1,
+ fields: {
+ slug: {
+ queryPath: ["properties", "slug"],
+ types: ["string" as const],
+ occurrences: 1,
+ },
+ },
+};
+
+const createDocument = () =>
+ createAssetResourceOpenApi({
+ builderSessionCookieName: "__Host-_session_test",
+ querySchemaReference:
+ "https://api.example.com/rest/assets/query-schema.json?projectId=project",
+ });
+
+const loadConfiguration = (catalog = defaultCatalog) =>
+ loadOpenApiQueryDefinition({
+ document: createDocument(),
+ documentUrl: "https://api.example.com/rest/assets/openapi.json",
+ operationId: "queryAssets",
+ loadReference: async () => createAssetQueryJsonSchema({ catalog }),
+ });
+
+const resolvePointer = (document: unknown, pointer: string) => {
+ let value = document;
+ for (const segment of pointer
+ .slice(2)
+ .split("/")
+ .map((item) => item.replaceAll("~1", "/").replaceAll("~0", "~"))) {
+ if (typeof value !== "object" || value === null || !(segment in value)) {
+ return;
+ }
+ value = (value as Record<string, unknown>)[segment];
+ }
+ return value;
+};
+
+const collectLocalReferences = (value: unknown): string[] => {
+ if (Array.isArray(value)) {
+ return value.flatMap(collectLocalReferences);
+ }
+ if (typeof value !== "object" || value === null) {
+ return [];
+ }
+ return Object.entries(value).flatMap(([key, item]) =>
+ key === "$ref" && typeof item === "string"
+ ? [item]
+ : collectLocalReferences(item)
+ );
+};
+
+describe("Assets OpenAPI description", () => {
+ test("uses the canonical operation registry", () => {
+ const document = createDocument();
+
+ expect(document.openapi).toBe("3.1.1");
+ for (const operation of Object.values(assetResourceApiOperations)) {
+ const paths = document.paths as Record<
+ string,
+ Record<string, { operationId: string }>
+ >;
+ expect(paths[operation.path]?.[operation.method]?.operationId).toBe(
+ operation.operationId
+ );
+ }
+ });
+
+ test("passes independent OpenAPI validation", async () => {
+ // SwaggerParser dereferences and mutates its input. Validate an isolated
+ // JSON value so shared Zod schema internals cannot be retained by it.
+ const document = JSON.parse(JSON.stringify(createDocument()));
+ await expect(
+ SwaggerParser.validate(document as never, {
+ resolve: { external: false },
+ })
+ ).resolves.toMatchObject({ openapi: "3.1.1" });
+ });
+
+ test("contains resolvable local schema references", () => {
+ const document = createDocument();
+ const references = collectLocalReferences(document).filter((reference) =>
+ reference.startsWith("#/")
+ );
+
+ expect(references.length).toBeGreaterThan(0);
+ for (const reference of references) {
+ expect(reference.startsWith("#/"), reference).toBe(true);
+ expect(resolvePointer(document, reference), reference).toBeDefined();
+ }
+ });
+
+ test("describes stable fields and schemaless properties without a UI extension", async () => {
+ const document = createDocument();
+ const resultSchema = document.components.schemas.AssetQueryResult;
+ const previewSchema = document.components.schemas.AssetQueryPreviewResult;
+ const serialized = JSON.stringify(resultSchema);
+ const requestSchema = createAssetQueryJsonSchema({
+ catalog: defaultCatalog,
+ });
+
+ expect(serialized).toContain('"name"');
+ expect(serialized).toContain('"description"');
+ expect(serialized).toContain('"properties"');
+ expect(serialized).toContain('"additionalProperties"');
+ expect(serialized).not.toContain("__diagnostics__");
+ expect(JSON.stringify(previewSchema)).toContain("__diagnostics__");
+ expect(JSON.stringify(requestSchema)).toContain('"properties","slug"');
+ expect(JSON.stringify(document)).not.toContain("x-webstudio-query");
+
+ const filter = (await loadConfiguration()).source.controls.find(
+ (control) => control.type === "filter"
+ );
+ expect(filter).toMatchObject({
+ limits: {
+ conditions: contentEngineLimits.filterCount,
+ depth: contentEngineLimits.filterDepth,
+ },
+ });
+ });
+
+ test("uses lowercase labels for standard filter fields and operators", async () => {
+ const configuration = await loadConfiguration();
+ const standardFields = configuration.fields.filter(
+ ({ path }) => path[0] !== "properties"
+ );
+
+ expect(standardFields).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ path: ["size"], label: "size" }),
+ expect.objectContaining({ path: ["width"], label: "width" }),
+ expect.objectContaining({ path: ["height"], label: "height" }),
+ ])
+ );
+ for (const item of [...standardFields, ...configuration.operators]) {
+ expect(item.label).toBe(item.label.toLowerCase());
+ }
+ });
+
+ test("describes callable REST paths and stable share-token authentication", () => {
+ const document = createDocument();
+
+ expect(Object.keys(document.paths)).toEqual([
+ "/rest/assets",
+ "/rest/assets/uploads",
+ "/rest/assets/uploads/{name}",
+ "/rest/assets/{assetId}",
+ "/rest/assets/{assetId}/content",
+ "/rest/assets/folders",
+ "/rest/assets/folders/{folderId}",
+ "/rest/assets/query",
+ "/rest/assets/field-catalog",
+ "/rest/assets/openapi.json",
+ "/rest/assets/query-schema.json",
+ "/rest/assets/index/refresh",
+ ]);
+ expect(document.components.securitySchemes.projectToken).toMatchObject({
+ type: "apiKey",
+ in: "header",
+ name: "x-auth-token",
+ });
+ expect(document.components.securitySchemes.builderSession).toMatchObject({
+ type: "apiKey",
+ in: "cookie",
+ name: "__Host-_session_test",
+ });
+ expect(document.components.securitySchemes.csrfToken).toMatchObject({
+ type: "apiKey",
+ in: "header",
+ name: "X-CSRF-Token",
+ });
+ expect(document.security).toEqual([
+ { projectToken: [] },
+ { builderSession: [] },
+ ]);
+ expect(document["x-webstudio-limits"]).toMatchObject({
+ mutationRequestBytes: assetResourceLimits.restMutationRequestBytes,
+ filenameCharacters: assetResourceLimits.assetFilenameCharacters,
+ });
+
+ for (const operation of Object.values(assetResourceApiOperations)) {
+ const definition = (
+ document.paths as unknown as Record<
+ string,
+ Record<string, { responses: Record<number, unknown> }>
+ >
+ )[operation.path][operation.method];
+ expect(definition.responses[401], operation.operationId).toBeDefined();
+ }
+
+ const mutationForbidden =
+ document.paths[assetResourceApiOperations.updateAsset.path].patch
+ .responses[403];
+ expect(Object.keys(mutationForbidden.content)).toEqual([
+ "application/json",
+ "text/plain",
+ ]);
+ expect(
+ document.paths[assetResourceApiOperations.listAssets.path].get
+ .responses[403].content
+ ).not.toHaveProperty("text/plain");
+ expect(
+ document.paths[assetResourceApiOperations.queryAssets.path].post
+ .responses[403].content
+ ).not.toHaveProperty("text/plain");
+ expect(
+ document.paths[assetResourceApiOperations.listAssets.path].get.responses
+ ).not.toHaveProperty("413");
+ expect(
+ document.paths[assetResourceApiOperations.reserveAssetUpload.path].post
+ .responses
+ ).toHaveProperty("413");
+ });
+
+ test("describes project scope and cookie mutation CSRF requirements", () => {
+ const document = createDocument();
+ for (const operation of [
+ assetResourceApiOperations.queryAssets,
+ assetResourceApiOperations.getAssetFieldCatalog,
+ assetResourceApiOperations.getAssetResourceOpenApi,
+ ]) {
+ const definition = (
+ document.paths as unknown as Record<
+ string,
+ Record<string, { parameters?: readonly { name: string }[] }>
+ >
+ )[operation.path][operation.method];
+ expect(definition.parameters?.map(({ name }) => name)).toContain(
+ "projectId"
+ );
+ }
+
+ expect(
+ document.paths[assetResourceApiOperations.updateAsset.path].patch.security
+ ).toEqual([{ projectToken: [] }, { builderSession: [], csrfToken: [] }]);
+
+ for (const pathItem of Object.values(document.paths)) {
+ for (const operation of Object.values(pathItem)) {
+ const parameters = (
+ "parameters" in operation ? operation.parameters : []
+ ) as readonly { name: string; in: string }[];
+ const identities = parameters.map(
+ ({ name, in: location }) => `${location}:${name}`
+ );
+ expect(new Set(identities).size).toBe(identities.length);
+ }
+ }
+ });
+
+ test("describes and validates mutable asset operations", () => {
+ expect(
+ assetUploadReservationRequest.safeParse({
+ projectId: "project-1",
+ type: "file",
+ filename: "post.md",
+ }).success
+ ).toBe(true);
+ expect(assetMetadataUpdate.safeParse({}).success).toBe(false);
+ expect(
+ assetMetadataUpdate.safeParse({
+ filename: "Published post",
+ folderId: null,
+ }).success
+ ).toBe(true);
+ expect(assetFolderCreateRequest.safeParse({ name: "Blog" }).success).toBe(
+ true
+ );
+ expect(assetFolderUpdateRequest.safeParse({}).success).toBe(false);
+ expect(assetFolderUpdateRequest.safeParse({ parentId: null }).success).toBe(
+ true
+ );
+ expect(
+ assetMetadataUpdate.safeParse({
+ description: "x".repeat(
+ assetResourceLimits.assetDescriptionCharacters + 1
+ ),
+ }).success
+ ).toBe(false);
+ expect(
+ assetFolderCreateRequest.safeParse({
+ name: "x".repeat(assetResourceLimits.assetFolderNameCharacters + 1),
+ }).success
+ ).toBe(false);
+
+ const document = createDocument();
+ const uploadContent =
+ document.paths[assetResourceApiOperations.uploadAssetContent.path].post;
+ expect(uploadContent.parameters.map(({ name }) => name)).toEqual([
+ "name",
+ "projectId",
+ "type",
+ "folderId",
+ "format",
+ "width",
+ "height",
+ "force",
+ "x-webstudio-asset-description",
+ "x-webstudio-asset-meta",
+ ]);
+ expect(uploadContent.parameters[0].schema.maxLength).toBe(
+ assetResourceLimits.assetFilenameCharacters
+ );
+ expect(Object.keys(uploadContent.requestBody.content)).toEqual([
+ "application/octet-stream",
+ ]);
+ expect(
+ document.paths[assetResourceApiOperations.updateAsset.path].patch
+ .requestBody.content["application/json"].schema.$ref
+ ).toBe("#/components/schemas/AssetMetadataUpdate");
+ expect(
+ document.paths[assetResourceApiOperations.deleteAsset.path].delete
+ .responses[204]
+ ).toEqual({ description: "Asset deleted" });
+ expect(
+ document.paths[assetResourceApiOperations.downloadAssetContent.path].get
+ .responses[206]
+ ).toBeDefined();
+ expect(
+ document.paths[assetResourceApiOperations.downloadAssetContent.path].get
+ .responses[200].content
+ ).toHaveProperty("*/*");
+ expect(
+ document.paths[assetResourceApiOperations.createAssetFolder.path].post
+ .responses[201]
+ ).toBeDefined();
+ });
+
+ test("stays within the bounded API-description size", () => {
+ const bytes = new TextEncoder().encode(
+ JSON.stringify(createDocument())
+ ).byteLength;
+ expect(bytes).toBeLessThanOrEqual(assetResourceLimits.apiDescriptionBytes);
+ });
+
+ test("keeps OpenAPI bounded while a large multi-file catalog remains queryable", async () => {
+ const observedTypes = assetObservedFieldType.options;
+ const documentCount = 16;
+ const fieldCount = contentEngineLimits.frontmatterFields * documentCount;
+ const fields = Object.fromEntries(
+ Array.from({ length: fieldCount }, (_, index) => {
+ const typeMask = (index % (2 ** observedTypes.length - 1)) + 1;
+ const types = observedTypes.filter(
+ (_type, position) => (typeMask & (1 << position)) !== 0
+ );
+ const name = `field-${index}-${"x".repeat(128)}`;
+ return [
+ name,
+ {
+ queryPath: ["properties", name],
+ types: [...types].sort(),
+ occurrences: types.length,
+ ...(types.length < observedTypes.length
+ ? { optional: true as const }
+ : {}),
+ ...(types.length > 1 ? { mixed: true as const } : {}),
+ },
+ ];
+ })
+ );
+ const catalog = {
+ format: "webstudio-builder-asset-field-catalog" as const,
+ version: 1 as const,
+ canonicalRevision: `sha256:${"a".repeat(64)}`,
+ documentCount,
+ fields,
+ };
+ const document = createDocument();
+ const querySchema = createAssetQueryJsonSchema({ catalog });
+
+ expect(
+ new TextEncoder().encode(JSON.stringify(document)).byteLength
+ ).toBeLessThanOrEqual(assetResourceLimits.apiDescriptionBytes);
+ expect(
+ new TextEncoder().encode(JSON.stringify(querySchema)).byteLength
+ ).toBeLessThanOrEqual(assetResourceLimits.apiDescriptionBytes);
+ const definition = await loadOpenApiQueryDefinition({
+ document,
+ documentUrl: "https://api.example.com/rest/assets/openapi.json",
+ operationId: "queryAssets",
+ loadReference: async () => querySchema,
+ });
+ expect(
+ definition.source.controls.find(({ key }) => key === "output")
+ ).toMatchObject({
+ type: "variant",
+ config: { selection: { label: "Output", emptyOption: "base" } },
+ });
+ expect(
+ definition.source.controls.find(({ key }) => key === "content")
+ ).toMatchObject({
+ type: "variant",
+ config: { selection: { label: "Output", emptyOption: "none" } },
+ });
+ expect(definition.description).toMatch(
+ /^Autocomplete includes \d+ of 4096 observed content fields/
+ );
+ expect(definition.fields.length).toBeGreaterThan(
+ assetQueryStandardFields.length
+ );
+ expect(definition.fields.length).toBeLessThan(
+ fieldCount + assetQueryStandardFields.length
+ );
+ expect(definition.fields).toEqual(
+ expect.arrayContaining(
+ assetQueryStandardFields.map((field) =>
+ expect.objectContaining({ path: [field] })
+ )
+ )
+ );
+ expect(
+ resolvePointer(querySchema, "#/$defs/AssetQueryField")
+ ).toMatchObject({
+ anyOf: expect.arrayContaining([
+ expect.objectContaining({
+ type: "array",
+ prefixItems: [{ const: "properties" }],
+ minItems: 2,
+ maxItems: assetResourceLimits.fieldPathDepth,
+ }),
+ ]),
+ });
+ });
+});
diff --git a/packages/protocol/src/asset-resource-api.ts b/packages/protocol/src/asset-resource-api.ts
new file mode 100644
index 0000000000..77accc62f3
--- /dev/null
+++ b/packages/protocol/src/asset-resource-api.ts
@@ -0,0 +1,1339 @@
+import { z } from "zod";
+import { assetResourceLimits } from "@webstudio-is/sdk/asset-resource-limits";
+import {
+ asset,
+ assetType,
+ assetFolder,
+ assetFolderId,
+ assetFolderName,
+} from "@webstudio-is/sdk/schema";
+import {
+ assetQueryRequest,
+ assetQueryPreviewResult,
+ assetQuerySourceDefinition,
+ assetQueryResult,
+ assetResourceQueryFailure,
+ builderAssetFieldCatalog,
+ getAssetQueryOperatorsForFieldTypes,
+ type AssetObservedFieldType,
+ type AssetQueryOperator,
+} from "@webstudio-is/content-engine";
+import {
+ assetsFieldCatalogApiUrl,
+ assetsOpenApiUrl,
+ assetsApiUrl,
+ assetsFoldersApiUrl,
+ assetsIndexRefreshApiUrl,
+ assetsUploadsApiUrl,
+ assetsQueryApiUrl,
+ assetsQuerySchemaApiUrl,
+} from "@webstudio-is/sdk/runtime";
+import type { BuilderAssetFieldCatalog } from "@webstudio-is/content-engine";
+
+const assetItemApiPath = `${assetsApiUrl}/{assetId}`;
+const assetContentApiPath = `${assetItemApiPath}/content`;
+const assetFolderItemApiPath = `${assetsFoldersApiUrl}/{folderId}`;
+
+const operation = <
+ OperationId extends string,
+ Method extends string,
+ Path extends string,
+>(
+ operationId: OperationId,
+ method: Method,
+ path: Path
+) => ({
+ operationId,
+ method,
+ path,
+});
+
+export const assetResourceApiOperations = {
+ listAssets: operation("listAssets", "get", assetsApiUrl),
+ reserveAssetUpload: operation(
+ "reserveAssetUpload",
+ "post",
+ assetsUploadsApiUrl
+ ),
+ uploadAssetContent: operation(
+ "uploadAssetContent",
+ "post",
+ `${assetsUploadsApiUrl}/{name}`
+ ),
+ updateAsset: operation("updateAsset", "patch", assetItemApiPath),
+ getAsset: operation("getAsset", "get", assetItemApiPath),
+ deleteAsset: operation("deleteAsset", "delete", assetItemApiPath),
+ replaceAssetContent: operation(
+ "replaceAssetContent",
+ "put",
+ assetContentApiPath
+ ),
+ downloadAssetContent: operation(
+ "downloadAssetContent",
+ "get",
+ assetContentApiPath
+ ),
+ listAssetFolders: operation("listAssetFolders", "get", assetsFoldersApiUrl),
+ createAssetFolder: operation(
+ "createAssetFolder",
+ "post",
+ assetsFoldersApiUrl
+ ),
+ updateAssetFolder: operation(
+ "updateAssetFolder",
+ "patch",
+ assetFolderItemApiPath
+ ),
+ getAssetFolder: operation("getAssetFolder", "get", assetFolderItemApiPath),
+ deleteAssetFolder: operation(
+ "deleteAssetFolder",
+ "delete",
+ assetFolderItemApiPath
+ ),
+ queryAssets: operation("queryAssets", "post", assetsQueryApiUrl),
+ getAssetFieldCatalog: operation(
+ "getAssetFieldCatalog",
+ "get",
+ assetsFieldCatalogApiUrl
+ ),
+ getAssetResourceOpenApi: operation(
+ "getAssetResourceOpenApi",
+ "get",
+ assetsOpenApiUrl
+ ),
+ getAssetQuerySchema: operation(
+ "getAssetQuerySchema",
+ "get",
+ assetsQuerySchemaApiUrl
+ ),
+ refreshAssetIndex: operation(
+ "refreshAssetIndex",
+ "post",
+ assetsIndexRefreshApiUrl
+ ),
+} as const;
+
+export const assetUploadReservationRequest = z.strictObject({
+ projectId: z
+ .string()
+ .min(1)
+ .max(assetResourceLimits.assetIdentifierCharacters),
+ type: assetType,
+ filename: z.string().min(1).max(assetResourceLimits.assetFilenameCharacters),
+ displayFilename: z
+ .string()
+ .min(1)
+ .max(assetResourceLimits.assetFilenameCharacters)
+ .optional(),
+ description: z
+ .string()
+ .max(assetResourceLimits.assetDescriptionCharacters)
+ .optional(),
+ folderId: z
+ .string()
+ .min(1)
+ .max(assetResourceLimits.assetIdentifierCharacters)
+ .optional(),
+ contentHash: z
+ .string()
+ .regex(/^[a-f0-9]{64}$/)
+ .optional(),
+});
+
+/** Concrete query payload accepted by the Assets REST API. */
+export type AssetQueryRequestInput = z.input<typeof assetQueryRequest>;
+
+const assetUploadTicket = z.discriminatedUnion("deduplicated", [
+ z.strictObject({
+ assetId: z.string().min(1),
+ name: z.string().min(1),
+ deduplicated: z.literal(false),
+ }),
+ z.strictObject({
+ assetId: z.string().min(1),
+ name: z.string().min(1),
+ deduplicated: z.literal(true),
+ asset,
+ }),
+]);
+
+const assetUploadResult = z.strictObject({
+ uploadedAssets: z.array(asset),
+ deduplicated: z.boolean(),
+});
+export type AssetUploadResult = z.infer<typeof assetUploadResult>;
+
+const assetListResult = z.strictObject({ assets: z.array(asset) });
+
+const assetItemResult = z.strictObject({ asset });
+
+export const assetMetadataUpdate = z
+ .strictObject({
+ filename: z
+ .string()
+ .min(1)
+ .max(assetResourceLimits.assetFilenameCharacters)
+ .nullable()
+ .optional(),
+ description: z
+ .string()
+ .max(assetResourceLimits.assetDescriptionCharacters)
+ .nullable()
+ .optional(),
+ folderId: z
+ .string()
+ .min(1)
+ .max(assetResourceLimits.assetIdentifierCharacters)
+ .nullable()
+ .optional(),
+ })
+ .refine((value) => Object.keys(value).length > 0, {
+ message: "At least one asset metadata field is required",
+ });
+export type AssetMetadataUpdate = z.infer<typeof assetMetadataUpdate>;
+
+const assetFolderListResult = z.strictObject({
+ folders: z.array(assetFolder),
+});
+
+export const assetFolderCreateRequest = z.strictObject({
+ name: assetFolderName,
+ parentId: assetFolderId.optional(),
+});
+
+export const assetFolderUpdateRequest = z
+ .strictObject({
+ name: assetFolderName.optional(),
+ parentId: assetFolderId.nullable().optional(),
+ })
+ .refine((value) => Object.keys(value).length > 0, {
+ message: "At least one asset folder field is required",
+ });
+export type AssetFolderUpdateRequest = z.infer<typeof assetFolderUpdateRequest>;
+
+const assetFolderMutationResult = z.strictObject({
+ folder: assetFolder,
+});
+
+const assetRestFailure = z.strictObject({
+ errors: z.string().min(1),
+});
+
+const assetIndexRefreshResult = z.strictObject({
+ scanned: z.number().int().nonnegative(),
+ indexed: z.number().int().nonnegative(),
+ metadataUpdated: z.number().int().nonnegative(),
+ unchanged: z.number().int().nonnegative(),
+ removed: z.number().int().nonnegative(),
+ skipped: z.number().int().nonnegative(),
+ inconsistent: z.number().int().nonnegative(),
+ issues: z.array(
+ z.strictObject({
+ assetId: z.string(),
+ storageName: z.string(),
+ revision: z.string(),
+ message: z.string(),
+ })
+ ),
+});
+
+type JsonSchema = Record<string, unknown>;
+
+const rewriteLocalReferences = (value: unknown, component: string): unknown => {
+ if (Array.isArray(value)) {
+ return value.map((item) => rewriteLocalReferences(item, component));
+ }
+ if (typeof value !== "object" || value === null) {
+ return value;
+ }
+ return Object.fromEntries(
+ Object.entries(value).map(([key, item]) => [
+ key,
+ key === "$ref" && typeof item === "string" && item.startsWith("#/$defs/")
+ ? `#/components/schemas/${component}/${item.slice(2)}`
+ : rewriteLocalReferences(item, component),
+ ])
+ );
+};
+
+const toComponentSchema = (
+ component: string,
+ schema: z.ZodType,
+ io: "input" | "output"
+): JsonSchema => {
+ const { $schema: _schema, ...jsonSchema } = z.toJSONSchema(schema, {
+ target: "draft-2020-12",
+ io,
+ unrepresentable: "any",
+ });
+ return rewriteLocalReferences(jsonSchema, component) as JsonSchema;
+};
+
+const toStandaloneSchema = (
+ schema: z.ZodType,
+ io: "input" | "output"
+): JsonSchema => {
+ const { $schema: _schema, ...jsonSchema } = z.toJSONSchema(schema, {
+ target: "draft-2020-12",
+ io,
+ unrepresentable: "any",
+ });
+ return jsonSchema;
+};
+
+const inputComponentSchemas = {
+ AssetQueryRequest: assetQueryRequest,
+ AssetUploadReservationRequest: assetUploadReservationRequest,
+ AssetMetadataUpdate: assetMetadataUpdate,
+ AssetFolderCreateRequest: assetFolderCreateRequest,
+ AssetFolderUpdateRequest: assetFolderUpdateRequest,
+};
+
+const outputComponentSchemas = {
+ AssetQueryResult: assetQueryResult,
+ AssetQueryPreviewResult: assetQueryPreviewResult,
+ AssetResourceQueryFailure: assetResourceQueryFailure,
+ BuilderAssetFieldCatalog: builderAssetFieldCatalog,
+ AssetUploadTicket: assetUploadTicket,
+ AssetUploadResult: assetUploadResult,
+ AssetListResult: assetListResult,
+ AssetItemResult: assetItemResult,
+ AssetMutationResult: assetItemResult,
+ AssetRestFailure: assetRestFailure,
+ AssetIndexRefreshResult: assetIndexRefreshResult,
+ AssetFolderListResult: assetFolderListResult,
+ AssetFolderMutationResult: assetFolderMutationResult,
+};
+
+const createComponentSchemas = () =>
+ Object.fromEntries([
+ ...Object.entries(inputComponentSchemas).map(([name, schema]) => [
+ name,
+ toComponentSchema(name, schema, "input"),
+ ]),
+ ...Object.entries(outputComponentSchemas).map(([name, schema]) => [
+ name,
+ toComponentSchema(name, schema, "output"),
+ ]),
+ ]);
+
+const isObject = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null && Array.isArray(value) === false;
+
+const operatorLabels = new Map(
+ assetQuerySourceDefinition.operators.map(({ value, label }) => [value, label])
+);
+
+const queryPropertyLabels: Record<string, string> = {
+ where: "Filters",
+ sort: "Sort",
+ limit: "Limit",
+ offset: "Offset",
+ output: "Output",
+ content: "Output",
+ includeMetadata: "File metadata",
+ maxBytes: "Maximum content bytes",
+ length: "Content byte length",
+};
+
+const queryModeLabels: Record<string, string> = {
+ "output:all": "All content fields",
+ "output:base": "File metadata only",
+ "output:fields": "Selected fields",
+ "content:none": "Metadata only",
+ "content:markdown-body": "Markdown body",
+ "content:full": "Full file",
+ "content:range": "Byte range",
+};
+
+type AssetOpenApiField = {
+ path: string[];
+ label?: string;
+ types: readonly AssetObservedFieldType[];
+};
+
+const createAssetOpenApiFields = (
+ catalog?: BuilderAssetFieldCatalog
+): AssetOpenApiField[] => [
+ ...assetQuerySourceDefinition.fields,
+ ...Object.values(catalog?.fields ?? {}).flatMap((field) =>
+ field.queryPath?.[0] === "properties"
+ ? [
+ {
+ path: field.queryPath,
+ types: field.types,
+ },
+ ]
+ : []
+ ),
+];
+
+const getSchemaChoices = (value: JsonSchema) =>
+ Array.isArray(value.oneOf)
+ ? value.oneOf
+ : Array.isArray(value.anyOf)
+ ? value.anyOf
+ : undefined;
+
+const isFilterConditionUnion = (value: unknown): value is JsonSchema => {
+ if (isObject(value) === false) {
+ return false;
+ }
+ const choices = getSchemaChoices(value);
+ return (
+ choices !== undefined &&
+ choices.length > 0 &&
+ choices.every(
+ (item) =>
+ isObject(item) &&
+ isObject(item.properties) &&
+ "field" in item.properties &&
+ "operator" in item.properties &&
+ "value" in item.properties
+ )
+ );
+};
+
+const findFilterConditionUnion = (value: unknown): JsonSchema | undefined => {
+ if (isFilterConditionUnion(value)) {
+ return value;
+ }
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ const found = findFilterConditionUnion(item);
+ if (found !== undefined) {
+ return found;
+ }
+ }
+ return;
+ }
+ if (isObject(value)) {
+ for (const item of Object.values(value)) {
+ const found = findFilterConditionUnion(item);
+ if (found !== undefined) {
+ return found;
+ }
+ }
+ }
+};
+
+const decorateAssetQuerySchema = ({
+ schema,
+ fields,
+ referenceRoot = "#/components/schemas/AssetQueryRequest",
+}: {
+ schema: JsonSchema;
+ fields: readonly AssetOpenApiField[];
+ referenceRoot?: string;
+}): JsonSchema => {
+ const definitionReference = (name: string) =>
+ `${referenceRoot}/$defs/${name}`;
+ const fieldGroups = new Map<
+ string,
+ {
+ operators: AssetQueryOperator[];
+ fields: AssetOpenApiField[];
+ reference: string;
+ }
+ >();
+ for (const field of fields) {
+ const operators = getAssetQueryOperatorsForFieldTypes(field.types);
+ const key = operators.join(",");
+ const group = fieldGroups.get(key) ?? {
+ operators,
+ fields: [],
+ reference: definitionReference(`AssetQueryField${fieldGroups.size}`),
+ };
+ group.fields.push(field);
+ fieldGroups.set(key, group);
+ }
+ const allFieldsReference = definitionReference("AssetQueryField");
+ const boundedWhereReference = definitionReference(
+ `AssetQueryWhere${assetResourceLimits.filterDepth}`
+ );
+ let conditionSchema: JsonSchema | undefined;
+ const fieldDefinitions = Object.fromEntries([
+ [
+ "AssetQueryField",
+ {
+ anyOf: [
+ ...[...fieldGroups.values()].map(({ reference }) => ({
+ $ref: reference,
+ })),
+ {
+ type: "array",
+ prefixItems: [{ const: "properties" }],
+ items: { type: "string", minLength: 1 },
+ minItems: 2,
+ maxItems: assetResourceLimits.fieldPathDepth,
+ },
+ ],
+ },
+ ],
+ ...[...fieldGroups.values()].map(({ fields: groupFields }, index) => [
+ `AssetQueryField${index}`,
+ {
+ type: "array",
+ minItems: 1,
+ maxItems: assetResourceLimits.fieldPathDepth,
+ items: { type: "string", minLength: 1 },
+ oneOf: [
+ ...groupFields.flatMap((field) =>
+ field.label === undefined
+ ? []
+ : [{ const: field.path, title: field.label }]
+ ),
+ ...(() => {
+ const paths = groupFields.flatMap((field) =>
+ field.label === undefined ? [field.path] : []
+ );
+ return paths.length === 0 ? [] : [{ enum: paths }];
+ })(),
+ ],
+ },
+ ]),
+ ]);
+
+ const visit = (value: unknown, property?: string): unknown => {
+ if (Array.isArray(value)) {
+ return value.map((item) => visit(item, property));
+ }
+ if (isObject(value) === false) {
+ return value;
+ }
+ if (property === "where") {
+ const next = visit(value) as JsonSchema;
+ conditionSchema = findFilterConditionUnion(next);
+ return {
+ $ref: boundedWhereReference,
+ ...(next.default === undefined ? {} : { default: next.default }),
+ title: queryPropertyLabels.where,
+ ...(typeof next.description === "string"
+ ? { description: next.description }
+ : {}),
+ };
+ }
+ const next = Object.fromEntries(
+ Object.entries(value).map(([key, item]) => [
+ key,
+ key === "default" || key === "const" || key === "examples"
+ ? item
+ : key === "properties" && isObject(item)
+ ? Object.fromEntries(
+ Object.entries(item).map(([name, child]) => [
+ name,
+ visit(child, name),
+ ])
+ )
+ : visit(item, property),
+ ])
+ );
+ if (property !== undefined && queryPropertyLabels[property] !== undefined) {
+ next.title = queryPropertyLabels[property];
+ }
+ if (
+ (property === "field" || property === "fields") &&
+ next.type === "array" &&
+ next.minItems === 1 &&
+ isObject(next.items) &&
+ next.items.type === "string"
+ ) {
+ return {
+ $ref: allFieldsReference,
+ ...(typeof next.title === "string" ? { title: next.title } : {}),
+ };
+ }
+ if (
+ next.type === "object" &&
+ isObject(next.properties) &&
+ isObject(next.properties.mode) &&
+ typeof next.properties.mode.const === "string" &&
+ property !== undefined
+ ) {
+ next.properties.mode.title =
+ queryModeLabels[`${property}:${next.properties.mode.const}`] ??
+ next.properties.mode.const;
+ }
+ if (property === "output" && Array.isArray(next.oneOf)) {
+ next.oneOf.sort((left, right) => {
+ const getMode = (item: unknown) =>
+ isObject(item) &&
+ isObject(item.properties) &&
+ isObject(item.properties.mode) &&
+ typeof item.properties.mode.const === "string"
+ ? item.properties.mode.const
+ : "";
+ return (
+ Number(getMode(right) === "base") - Number(getMode(left) === "base")
+ );
+ });
+ }
+ if (isFilterConditionUnion(next)) {
+ const templates = getSchemaChoices(next) as Record<string, unknown>[];
+ const choices = [...fieldGroups.values()].flatMap((group) =>
+ templates.flatMap((template) => {
+ if (isObject(template.properties) === false) {
+ return [];
+ }
+ const operatorSchema = template.properties.operator;
+ if (isObject(operatorSchema) === false) {
+ return [];
+ }
+ const values = Array.isArray(operatorSchema.enum)
+ ? operatorSchema.enum
+ : [operatorSchema.const];
+ const compatible = values.filter(
+ (value): value is string =>
+ typeof value === "string" &&
+ group.operators.includes(value as AssetQueryOperator)
+ );
+ if (compatible.length === 0) {
+ return [];
+ }
+ return [
+ {
+ ...template,
+ properties: {
+ ...template.properties,
+ field: { $ref: group.reference },
+ operator: {
+ oneOf: compatible.map((value) => ({
+ const: value,
+ title:
+ operatorLabels.get(value as AssetQueryOperator) ?? value,
+ })),
+ },
+ },
+ },
+ ];
+ })
+ );
+ if (Array.isArray(next.oneOf)) {
+ next.oneOf = choices;
+ } else {
+ next.anyOf = choices;
+ }
+ }
+ return next;
+ };
+ const decorated = visit(schema) as JsonSchema;
+ conditionSchema ??= findFilterConditionUnion(decorated);
+ if (conditionSchema === undefined) {
+ throw new Error("Asset query filter schema is missing");
+ }
+ const conditionReference = definitionReference("AssetQueryCondition");
+ const whereDefinitions: Record<string, JsonSchema> = {
+ AssetQueryCondition: conditionSchema,
+ };
+ for (let depth = 0; depth <= assetResourceLimits.filterDepth; depth += 1) {
+ const choices: JsonSchema[] = [{ $ref: conditionReference }];
+ if (depth > 0) {
+ const childReference = definitionReference(`AssetQueryWhere${depth - 1}`);
+ for (const combinator of ["all", "any"]) {
+ choices.push({
+ type: "object",
+ properties: {
+ [combinator]: {
+ type: "array",
+ maxItems: assetResourceLimits.filterCount,
+ items: { $ref: childReference },
+ },
+ },
+ required: [combinator],
+ additionalProperties: false,
+ });
+ }
+ }
+ whereDefinitions[`AssetQueryWhere${depth}`] = { oneOf: choices };
+ }
+ return {
+ ...decorated,
+ $defs: {
+ ...(isObject(decorated.$defs) ? decorated.$defs : {}),
+ ...fieldDefinitions,
+ ...whereDefinitions,
+ },
+ };
+};
+
+const getSerializedBytes = (value: unknown) =>
+ new TextEncoder().encode(JSON.stringify(value)).byteLength;
+
+const findAssetQueryObjectSchema = (value: unknown): JsonSchema | undefined => {
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ const found = findAssetQueryObjectSchema(item);
+ if (found !== undefined) {
+ return found;
+ }
+ }
+ return;
+ }
+ if (isObject(value) === false) {
+ return;
+ }
+ if (
+ isObject(value.properties) &&
+ ["where", "sort", "limit", "offset", "output", "content"].every((key) =>
+ Object.hasOwn(value.properties as object, key)
+ )
+ ) {
+ return value;
+ }
+ for (const child of Object.values(value)) {
+ const found = findAssetQueryObjectSchema(child);
+ if (found !== undefined) {
+ return found;
+ }
+ }
+};
+
+const createAssetQuerySchemaForFields = (fields: AssetOpenApiField[]) => ({
+ $schema: "https://json-schema.org/draft/2020-12/schema",
+ ...decorateAssetQuerySchema({
+ schema: toStandaloneSchema(assetQueryRequest, "input"),
+ fields,
+ referenceRoot: "#",
+ }),
+});
+
+export const createAssetQueryJsonSchema = ({
+ catalog,
+}: {
+ catalog?: BuilderAssetFieldCatalog;
+}) => {
+ const fields = createAssetOpenApiFields(catalog);
+ const standardFieldCount = assetQuerySourceDefinition.fields.length;
+ const standardFields = fields.slice(0, standardFieldCount);
+ const dynamicFields = fields
+ .slice(standardFieldCount)
+ .map((field) => ({ field, key: JSON.stringify(field.path) }))
+ .sort((left, right) => left.key.localeCompare(right.key))
+ .map(({ field }) => field);
+ const createBoundedSchema = (dynamicFieldCount: number) => {
+ const schema = createAssetQuerySchemaForFields([
+ ...standardFields,
+ ...dynamicFields.slice(0, dynamicFieldCount),
+ ]);
+ if (dynamicFieldCount < dynamicFields.length) {
+ const querySchema = findAssetQueryObjectSchema(schema);
+ if (querySchema === undefined) {
+ throw new Error("Asset query schema is missing");
+ }
+ querySchema.description = `Autocomplete includes ${dynamicFieldCount} of ${dynamicFields.length} observed content fields because the field catalog exceeds the API description limit. Other content fields remain valid.`;
+ }
+ return schema;
+ };
+
+ const completeSchema = createBoundedSchema(dynamicFields.length);
+ if (
+ getSerializedBytes(completeSchema) <=
+ assetResourceLimits.apiDescriptionBytes
+ ) {
+ return completeSchema;
+ }
+
+ let minimum = 0;
+ let maximum = dynamicFields.length - 1;
+ let result = createBoundedSchema(0);
+ if (getSerializedBytes(result) > assetResourceLimits.apiDescriptionBytes) {
+ throw new Error(
+ "Base asset query schema exceeds the API description limit"
+ );
+ }
+ while (minimum <= maximum) {
+ const count = Math.floor((minimum + maximum) / 2);
+ const schema = createBoundedSchema(count);
+ if (getSerializedBytes(schema) <= assetResourceLimits.apiDescriptionBytes) {
+ result = schema;
+ minimum = count + 1;
+ } else {
+ maximum = count - 1;
+ }
+ }
+ return result;
+};
+
+const schemaResponse = (component: string, description: string) => ({
+ description,
+ content: {
+ "application/json": {
+ schema: { $ref: `#/components/schemas/${component}` },
+ },
+ },
+});
+
+const mutationForbiddenResponse = {
+ description: "Access denied or invalid CSRF token",
+ content: {
+ "application/json": {
+ schema: { $ref: "#/components/schemas/AssetRestFailure" },
+ },
+ "text/plain": { schema: { type: "string" } },
+ },
+};
+
+const errorResponses = {
+ 400: schemaResponse("AssetResourceQueryFailure", "Invalid request"),
+ 401: schemaResponse("AssetResourceQueryFailure", "Authentication required"),
+ 403: schemaResponse("AssetResourceQueryFailure", "Access denied"),
+ 409: schemaResponse("AssetResourceQueryFailure", "Stale asset index"),
+ 500: schemaResponse("AssetResourceQueryFailure", "Internal error"),
+};
+
+const restErrorResponses = {
+ 400: schemaResponse("AssetRestFailure", "Invalid request"),
+ 401: schemaResponse("AssetRestFailure", "Authentication required"),
+ 403: schemaResponse("AssetRestFailure", "Access denied"),
+ 500: schemaResponse("AssetRestFailure", "Internal error"),
+};
+
+const restNotFoundResponse = schemaResponse(
+ "AssetRestFailure",
+ "Asset or folder not found"
+);
+
+const mutationErrorResponses = {
+ ...restErrorResponses,
+ 403: mutationForbiddenResponse,
+ 404: restNotFoundResponse,
+ 409: schemaResponse("AssetRestFailure", "Asset revision conflict"),
+ 413: schemaResponse("AssetRestFailure", "Request body too large"),
+};
+
+const pathParameter = (
+ name: string,
+ description: string,
+ maxLength: number = assetResourceLimits.assetIdentifierCharacters
+) => ({
+ name,
+ in: "path",
+ required: true,
+ description,
+ schema: {
+ type: "string",
+ minLength: 1,
+ maxLength,
+ },
+});
+
+const queryParameter = (
+ name: string,
+ description: string,
+ required = false,
+ maxLength: number = assetResourceLimits.assetIdentifierCharacters
+) => ({
+ name,
+ in: "query",
+ required,
+ description,
+ schema: {
+ type: "string",
+ minLength: 1,
+ maxLength,
+ },
+});
+
+const projectIdParameter = queryParameter("projectId", "Owning project", true);
+const assetParameters = [
+ pathParameter("assetId", "Asset ID"),
+ projectIdParameter,
+];
+const assetFolderParameters = [
+ pathParameter("folderId", "Asset folder ID"),
+ projectIdParameter,
+];
+const binarySchema = { type: "string", format: "binary" } as const;
+
+/**
+ * OpenAPI is both the transport description and the sole query-authoring
+ * contract. The query UI derives its fields and controls from the operation's
+ * standard request schema; no parallel provider-specific UI contract exists.
+ */
+export const createAssetResourceOpenApi = ({
+ builderSessionCookieName,
+ querySchemaReference,
+}: {
+ builderSessionCookieName: string;
+ querySchemaReference: string;
+}) => {
+ const { AssetQueryRequest: _assetQueryRequest, ...componentSchemas } =
+ createComponentSchemas();
+ const operations = assetResourceApiOperations;
+ const mutationSecurity = [
+ { projectToken: [] },
+ { builderSession: [], csrfToken: [] },
+ ] as const;
+ const document = {
+ openapi: "3.1.1",
+ jsonSchemaDialect: "https://json-schema.org/draft/2020-12/schema",
+ info: {
+ title: "Webstudio Assets resource API",
+ version: "1.0.0",
+ description:
+ "Public project Assets API for uploads, metadata and content mutations, queries, and bounded content hydration. Project-token authentication is intended for server-to-server clients; cross-origin browser token access is not enabled by default.",
+ },
+ "x-webstudio-limits": {
+ mutationRequestBytes: assetResourceLimits.restMutationRequestBytes,
+ filenameCharacters: assetResourceLimits.assetFilenameCharacters,
+ descriptionCharacters: assetResourceLimits.assetDescriptionCharacters,
+ folderNameCharacters: assetResourceLimits.assetFolderNameCharacters,
+ },
+ paths: {
+ [operations.listAssets.path]: {
+ [operations.listAssets.method]: {
+ operationId: operations.listAssets.operationId,
+ summary: "List project assets",
+ parameters: [projectIdParameter],
+ responses: {
+ 200: schemaResponse("AssetListResult", "Project assets"),
+ ...restErrorResponses,
+ },
+ },
+ },
+ [operations.reserveAssetUpload.path]: {
+ [operations.reserveAssetUpload.method]: {
+ operationId: operations.reserveAssetUpload.operationId,
+ summary: "Reserve an asset upload",
+ security: mutationSecurity,
+ description:
+ "Supply contentHash when available so retries can reuse an existing identical asset instead of creating a duplicate reservation.",
+ requestBody: {
+ required: true,
+ content: {
+ "multipart/form-data": {
+ schema: {
+ $ref: "#/components/schemas/AssetUploadReservationRequest",
+ },
+ },
+ "application/json": {
+ schema: {
+ $ref: "#/components/schemas/AssetUploadReservationRequest",
+ },
+ },
+ },
+ },
+ responses: {
+ 200: schemaResponse("AssetUploadTicket", "Upload reservation"),
+ ...mutationErrorResponses,
+ },
+ },
+ },
+ [operations.uploadAssetContent.path]: {
+ [operations.uploadAssetContent.method]: {
+ operationId: operations.uploadAssetContent.operationId,
+ summary: "Upload asset content",
+ security: mutationSecurity,
+ description:
+ "Upload a previously reserved storage name, or perform a direct API upload by supplying projectId and type. Direct uploads may also provide the optional metadata parameters.",
+ parameters: [
+ pathParameter(
+ "name",
+ "Reserved storage name or direct-upload filename",
+ assetResourceLimits.assetFilenameCharacters
+ ),
+ queryParameter(
+ "projectId",
+ "Owning project; required for a direct API upload"
+ ),
+ {
+ name: "type",
+ in: "query",
+ required: false,
+ description: "Asset type; required for a direct API upload",
+ schema: { type: "string", enum: assetType.options },
+ },
+ queryParameter("folderId", "Destination asset folder"),
+ queryParameter(
+ "format",
+ "Detected file format override",
+ false,
+ assetResourceLimits.assetFilenameCharacters
+ ),
+ {
+ name: "width",
+ in: "query",
+ required: false,
+ description: "Image width in pixels",
+ schema: { type: "number", exclusiveMinimum: 0 },
+ },
+ {
+ name: "height",
+ in: "query",
+ required: false,
+ description: "Image height in pixels",
+ schema: { type: "number", exclusiveMinimum: 0 },
+ },
+ {
+ name: "force",
+ in: "query",
+ required: false,
+ description:
+ "Create a new asset instead of deduplicating content",
+ schema: { type: "boolean", default: false },
+ },
+ {
+ name: "x-webstudio-asset-description",
+ in: "header",
+ required: false,
+ description: "Asset description",
+ schema: {
+ type: "string",
+ maxLength: assetResourceLimits.assetDescriptionCharacters,
+ },
+ },
+ {
+ name: "x-webstudio-asset-meta",
+ in: "header",
+ required: false,
+ description: "JSON-encoded asset metadata override",
+ schema: { type: "string" },
+ },
+ ],
+ requestBody: {
+ required: true,
+ content: {
+ "application/octet-stream": {
+ schema: binarySchema,
+ },
+ },
+ },
+ responses: {
+ 200: schemaResponse("AssetUploadResult", "Uploaded asset"),
+ ...mutationErrorResponses,
+ },
+ },
+ },
+ [operations.updateAsset.path]: {
+ [operations.getAsset.method]: {
+ operationId: operations.getAsset.operationId,
+ summary: "Get an asset",
+ parameters: assetParameters,
+ responses: {
+ 200: schemaResponse("AssetItemResult", "Asset record"),
+ ...restErrorResponses,
+ 404: restNotFoundResponse,
+ },
+ },
+ [operations.updateAsset.method]: {
+ operationId: operations.updateAsset.operationId,
+ summary: "Update asset metadata or folder",
+ security: mutationSecurity,
+ parameters: assetParameters,
+ requestBody: {
+ required: true,
+ content: {
+ "application/json": {
+ schema: { $ref: "#/components/schemas/AssetMetadataUpdate" },
+ },
+ },
+ },
+ responses: {
+ 200: schemaResponse("AssetMutationResult", "Updated asset"),
+ ...mutationErrorResponses,
+ },
+ },
+ [operations.deleteAsset.method]: {
+ operationId: operations.deleteAsset.operationId,
+ summary: "Delete an asset",
+ security: mutationSecurity,
+ parameters: assetParameters,
+ responses: {
+ 204: { description: "Asset deleted" },
+ ...mutationErrorResponses,
+ },
+ },
+ },
+ [operations.replaceAssetContent.path]: {
+ [operations.downloadAssetContent.method]: {
+ operationId: operations.downloadAssetContent.operationId,
+ summary: "Download asset content",
+ description:
+ "Streams the stored file through the authenticated Assets API. A single standard HTTP byte range is supported.",
+ parameters: [
+ pathParameter("assetId", "Asset ID"),
+ projectIdParameter,
+ {
+ name: "Range",
+ in: "header",
+ required: false,
+ description: "Single byte range, for example bytes=0-1023",
+ schema: { type: "string" },
+ },
+ ],
+ responses: {
+ 200: {
+ description: "Complete asset content",
+ content: {
+ "*/*": {
+ schema: binarySchema,
+ },
+ },
+ },
+ 206: {
+ description: "Partial asset content",
+ headers: {
+ "Content-Range": { schema: { type: "string" } },
+ },
+ content: {
+ "*/*": {
+ schema: binarySchema,
+ },
+ },
+ },
+ 416: schemaResponse("AssetRestFailure", "Invalid byte range"),
+ ...restErrorResponses,
+ 404: restNotFoundResponse,
+ },
+ },
+ [operations.replaceAssetContent.method]: {
+ operationId: operations.replaceAssetContent.operationId,
+ summary: "Replace editable asset content",
+ security: mutationSecurity,
+ parameters: [
+ pathParameter("assetId", "Asset ID"),
+ projectIdParameter,
+ queryParameter(
+ "expectedName",
+ "Current immutable storage name used for conflict detection",
+ true,
+ assetResourceLimits.assetFilenameCharacters
+ ),
+ ],
+ requestBody: {
+ required: true,
+ content: {
+ "application/octet-stream": {
+ schema: binarySchema,
+ },
+ "text/markdown": { schema: { type: "string" } },
+ "application/json": { schema: {} },
+ },
+ },
+ responses: {
+ 200: schemaResponse("AssetMutationResult", "Updated asset"),
+ ...mutationErrorResponses,
+ },
+ },
+ },
+ [operations.listAssetFolders.path]: {
+ [operations.listAssetFolders.method]: {
+ operationId: operations.listAssetFolders.operationId,
+ summary: "List asset folders",
+ parameters: [projectIdParameter],
+ responses: {
+ 200: schemaResponse(
+ "AssetFolderListResult",
+ "Project asset folders"
+ ),
+ ...restErrorResponses,
+ },
+ },
+ [operations.createAssetFolder.method]: {
+ operationId: operations.createAssetFolder.operationId,
+ summary: "Create an asset folder",
+ security: mutationSecurity,
+ parameters: [projectIdParameter],
+ requestBody: {
+ required: true,
+ content: {
+ "application/json": {
+ schema: {
+ $ref: "#/components/schemas/AssetFolderCreateRequest",
+ },
+ },
+ },
+ },
+ responses: {
+ 201: schemaResponse(
+ "AssetFolderMutationResult",
+ "Created asset folder"
+ ),
+ ...mutationErrorResponses,
+ },
+ },
+ },
+ [operations.updateAssetFolder.path]: {
+ [operations.getAssetFolder.method]: {
+ operationId: operations.getAssetFolder.operationId,
+ summary: "Get an asset folder",
+ parameters: assetFolderParameters,
+ responses: {
+ 200: schemaResponse("AssetFolderMutationResult", "Asset folder"),
+ ...restErrorResponses,
+ 404: restNotFoundResponse,
+ },
+ },
+ [operations.updateAssetFolder.method]: {
+ operationId: operations.updateAssetFolder.operationId,
+ summary: "Update an asset folder",
+ security: mutationSecurity,
+ parameters: assetFolderParameters,
+ requestBody: {
+ required: true,
+ content: {
+ "application/json": {
+ schema: {
+ $ref: "#/components/schemas/AssetFolderUpdateRequest",
+ },
+ },
+ },
+ },
+ responses: {
+ 200: schemaResponse(
+ "AssetFolderMutationResult",
+ "Updated asset folder"
+ ),
+ ...mutationErrorResponses,
+ },
+ },
+ [operations.deleteAssetFolder.method]: {
+ operationId: operations.deleteAssetFolder.operationId,
+ summary: "Delete an empty asset folder",
+ security: mutationSecurity,
+ description:
+ "Returns a conflict when the folder contains nested folders or assets.",
+ parameters: assetFolderParameters,
+ responses: {
+ 204: { description: "Asset folder deleted" },
+ ...mutationErrorResponses,
+ },
+ },
+ },
+ [operations.queryAssets.path]: {
+ [operations.queryAssets.method]: {
+ operationId: operations.queryAssets.operationId,
+ summary: "Query project assets",
+ parameters: [projectIdParameter],
+ requestBody: {
+ required: true,
+ content: {
+ "application/json": {
+ schema: { $ref: querySchemaReference },
+ },
+ },
+ },
+ responses: {
+ 200: schemaResponse("AssetQueryPreviewResult", "Query preview"),
+ ...errorResponses,
+ },
+ },
+ },
+ [operations.getAssetFieldCatalog.path]: {
+ [operations.getAssetFieldCatalog.method]: {
+ operationId: operations.getAssetFieldCatalog.operationId,
+ summary: "Get observed asset fields",
+ parameters: [projectIdParameter],
+ responses: {
+ 200: schemaResponse(
+ "BuilderAssetFieldCatalog",
+ "Observed project fields"
+ ),
+ 400: errorResponses[400],
+ 401: errorResponses[401],
+ 403: errorResponses[403],
+ 500: errorResponses[500],
+ },
+ },
+ },
+ [operations.getAssetResourceOpenApi.path]: {
+ [operations.getAssetResourceOpenApi.method]: {
+ operationId: operations.getAssetResourceOpenApi.operationId,
+ summary: "Get this OpenAPI description",
+ parameters: [projectIdParameter],
+ responses: {
+ 200: {
+ description: "OpenAPI description",
+ content: {
+ "application/vnd.oai.openapi+json;version=3.1": {
+ schema: { type: "object", additionalProperties: true },
+ },
+ },
+ },
+ 400: errorResponses[400],
+ 401: errorResponses[401],
+ 403: errorResponses[403],
+ 500: errorResponses[500],
+ },
+ },
+ },
+ [operations.getAssetQuerySchema.path]: {
+ [operations.getAssetQuerySchema.method]: {
+ operationId: operations.getAssetQuerySchema.operationId,
+ summary: "Get the project Assets query schema",
+ parameters: [projectIdParameter],
+ responses: {
+ 200: {
+ description: "Project-specific Assets query JSON Schema",
+ content: {
+ "application/schema+json": {
+ schema: { type: "object", additionalProperties: true },
+ },
+ },
+ },
+ 400: errorResponses[400],
+ 401: errorResponses[401],
+ 403: errorResponses[403],
+ 500: errorResponses[500],
+ },
+ },
+ },
+ [operations.refreshAssetIndex.path]: {
+ [operations.refreshAssetIndex.method]: {
+ operationId: operations.refreshAssetIndex.operationId,
+ summary: "Repair and refresh project asset metadata",
+ security: mutationSecurity,
+ description:
+ "Re-reads missing or changed file metadata. A 503 response includes per-file issues when repair is incomplete.",
+ parameters: [projectIdParameter],
+ responses: {
+ 200: schemaResponse(
+ "AssetIndexRefreshResult",
+ "Asset metadata is synchronized"
+ ),
+ 503: schemaResponse(
+ "AssetIndexRefreshResult",
+ "Asset metadata repair is incomplete"
+ ),
+ ...mutationErrorResponses,
+ },
+ },
+ },
+ },
+ components: {
+ schemas: componentSchemas,
+ securitySchemes: {
+ projectToken: {
+ type: "apiKey",
+ in: "header",
+ name: "x-auth-token",
+ description:
+ "Webstudio project token with the permit required by the operation. The same capability token works in shared Builder sessions and API clients.",
+ },
+ builderSession: {
+ type: "apiKey",
+ in: "cookie",
+ name: builderSessionCookieName,
+ description:
+ "Authenticated Webstudio Builder session. Cookie-authenticated mutations also require the Builder CSRF token.",
+ },
+ csrfToken: {
+ type: "apiKey",
+ in: "header",
+ name: "X-CSRF-Token",
+ description:
+ "Builder CSRF token supplied by the authenticated Builder bootstrap. Required together with builderSession for mutations.",
+ },
+ },
+ },
+ security: [{ projectToken: [] }, { builderSession: [] }],
+ } as const;
+
+ const bytes = getSerializedBytes(document);
+ if (bytes > assetResourceLimits.apiDescriptionBytes) {
+ throw new Error(
+ "Asset resource OpenAPI description exceeds the byte limit"
+ );
+ }
+ return document;
+};
diff --git a/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts b/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
index 24817de9a8..1dc9088ab3 100644
--- a/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
+++ b/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
@@ -245,6 +245,787 @@ export const serverOnlyRouterOperationMetadata = {
required: ["baseVersion", "transactions"],
},
},
+ "assetQueries.validate": {
+ id: "assetQueries.validate",
+ command: "validate-asset-query",
+ method: "query",
+ path: "api.assetQueries.validate",
+ client: "validateAssetQuery",
+ permit: "view",
+ inputSchema: {
+ type: "object",
+ properties: {
+ query: {
+ type: "object",
+ properties: {
+ where: {
+ default: {
+ all: [],
+ },
+ $ref: "#/$defs/__schema2",
+ },
+ sort: {
+ default: [],
+ maxItems: 8,
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ field: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ direction: {
+ type: "string",
+ enum: ["asc", "desc"],
+ },
+ },
+ required: ["field", "direction"],
+ additionalProperties: false,
+ },
+ },
+ limit: {
+ default: 20,
+ type: "integer",
+ minimum: 0,
+ maximum: 1000,
+ },
+ offset: {
+ default: 0,
+ type: "integer",
+ minimum: 0,
+ maximum: 1000,
+ },
+ output: {
+ default: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["url"], ["width"], ["height"]],
+ },
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "all",
+ },
+ includeMetadata: {
+ default: true,
+ type: "boolean",
+ },
+ },
+ required: ["mode"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "base",
+ },
+ includeMetadata: {
+ default: true,
+ type: "boolean",
+ },
+ },
+ required: ["mode"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "fields",
+ },
+ includeMetadata: {
+ default: true,
+ type: "boolean",
+ },
+ fields: {
+ maxItems: 256,
+ type: "array",
+ items: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ },
+ },
+ required: ["mode", "fields"],
+ additionalProperties: false,
+ },
+ ],
+ },
+ content: {
+ default: {
+ mode: "none",
+ },
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "none",
+ },
+ },
+ required: ["mode"],
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "full",
+ },
+ maxBytes: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 1048576,
+ },
+ },
+ required: ["mode"],
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "range",
+ },
+ offset: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ length: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 262144,
+ },
+ },
+ required: ["mode", "offset", "length"],
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "markdown-body",
+ },
+ maxBytes: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 1048576,
+ },
+ },
+ required: ["mode"],
+ },
+ ],
+ },
+ },
+ additionalProperties: false,
+ required: [],
+ },
+ },
+ required: ["query"],
+ $defs: {
+ __schema0: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "number",
+ },
+ {
+ type: "boolean",
+ },
+ {
+ type: "null",
+ },
+ {
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ },
+ additionalProperties: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ ],
+ },
+ __schema1: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "number",
+ },
+ {
+ type: "boolean",
+ },
+ {
+ type: "null",
+ },
+ {
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema1",
+ },
+ },
+ {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ },
+ additionalProperties: {
+ $ref: "#/$defs/__schema1",
+ },
+ },
+ ],
+ },
+ __schema2: {
+ anyOf: [
+ {
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ field: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ operator: {
+ type: "string",
+ enum: [
+ "eq",
+ "ne",
+ "contains",
+ "startsWith",
+ "endsWith",
+ "gt",
+ "gte",
+ "lt",
+ "lte",
+ ],
+ },
+ value: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ required: ["field", "operator", "value"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ field: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ operator: {
+ type: "string",
+ const: "in",
+ },
+ value: {
+ maxItems: 1000,
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema1",
+ },
+ },
+ },
+ required: ["field", "operator", "value"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ field: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ operator: {
+ type: "string",
+ enum: ["exists", "isEmpty"],
+ },
+ value: {
+ type: "boolean",
+ },
+ },
+ required: ["field", "operator", "value"],
+ additionalProperties: false,
+ },
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ all: {
+ maxItems: 32,
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema2",
+ },
+ },
+ },
+ required: ["all"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ any: {
+ maxItems: 32,
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema2",
+ },
+ },
+ },
+ required: ["any"],
+ additionalProperties: false,
+ },
+ ],
+ },
+ },
+ },
+ },
+ "assetQueries.preview": {
+ id: "assetQueries.preview",
+ command: "preview-asset-query",
+ method: "query",
+ path: "api.assetQueries.preview",
+ client: "previewAssetQuery",
+ permit: "view",
+ inputSchema: {
+ type: "object",
+ properties: {
+ query: {
+ type: "object",
+ properties: {
+ where: {
+ default: {
+ all: [],
+ },
+ $ref: "#/$defs/__schema2",
+ },
+ sort: {
+ default: [],
+ maxItems: 8,
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ field: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ direction: {
+ type: "string",
+ enum: ["asc", "desc"],
+ },
+ },
+ required: ["field", "direction"],
+ additionalProperties: false,
+ },
+ },
+ limit: {
+ default: 20,
+ type: "integer",
+ minimum: 0,
+ maximum: 1000,
+ },
+ offset: {
+ default: 0,
+ type: "integer",
+ minimum: 0,
+ maximum: 1000,
+ },
+ output: {
+ default: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["url"], ["width"], ["height"]],
+ },
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "all",
+ },
+ includeMetadata: {
+ default: true,
+ type: "boolean",
+ },
+ },
+ required: ["mode"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "base",
+ },
+ includeMetadata: {
+ default: true,
+ type: "boolean",
+ },
+ },
+ required: ["mode"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "fields",
+ },
+ includeMetadata: {
+ default: true,
+ type: "boolean",
+ },
+ fields: {
+ maxItems: 256,
+ type: "array",
+ items: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ },
+ },
+ required: ["mode", "fields"],
+ additionalProperties: false,
+ },
+ ],
+ },
+ content: {
+ default: {
+ mode: "none",
+ },
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "none",
+ },
+ },
+ required: ["mode"],
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "full",
+ },
+ maxBytes: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 1048576,
+ },
+ },
+ required: ["mode"],
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "range",
+ },
+ offset: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ length: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 262144,
+ },
+ },
+ required: ["mode", "offset", "length"],
+ },
+ {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ const: "markdown-body",
+ },
+ maxBytes: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 1048576,
+ },
+ },
+ required: ["mode"],
+ },
+ ],
+ },
+ },
+ additionalProperties: false,
+ required: [],
+ },
+ indexRevision: {
+ type: "string",
+ minLength: 1,
+ maxLength: 255,
+ },
+ },
+ required: ["query"],
+ $defs: {
+ __schema0: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "number",
+ },
+ {
+ type: "boolean",
+ },
+ {
+ type: "null",
+ },
+ {
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ },
+ additionalProperties: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ ],
+ },
+ __schema1: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "number",
+ },
+ {
+ type: "boolean",
+ },
+ {
+ type: "null",
+ },
+ {
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema1",
+ },
+ },
+ {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ },
+ additionalProperties: {
+ $ref: "#/$defs/__schema1",
+ },
+ },
+ ],
+ },
+ __schema2: {
+ anyOf: [
+ {
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ field: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ operator: {
+ type: "string",
+ enum: [
+ "eq",
+ "ne",
+ "contains",
+ "startsWith",
+ "endsWith",
+ "gt",
+ "gte",
+ "lt",
+ "lte",
+ ],
+ },
+ value: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ required: ["field", "operator", "value"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ field: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ operator: {
+ type: "string",
+ const: "in",
+ },
+ value: {
+ maxItems: 1000,
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema1",
+ },
+ },
+ },
+ required: ["field", "operator", "value"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ field: {
+ minItems: 1,
+ maxItems: 9,
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ operator: {
+ type: "string",
+ enum: ["exists", "isEmpty"],
+ },
+ value: {
+ type: "boolean",
+ },
+ },
+ required: ["field", "operator", "value"],
+ additionalProperties: false,
+ },
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ all: {
+ maxItems: 32,
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema2",
+ },
+ },
+ },
+ required: ["all"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ any: {
+ maxItems: 32,
+ type: "array",
+ items: {
+ $ref: "#/$defs/__schema2",
+ },
+ },
+ },
+ required: ["any"],
+ additionalProperties: false,
+ },
+ ],
+ },
+ },
+ },
+ },
+ "assetQueries.fieldCatalog": {
+ id: "assetQueries.fieldCatalog",
+ command: "get-asset-field-catalog",
+ method: "query",
+ path: "api.assetQueries.fieldCatalog",
+ client: "getAssetFieldCatalog",
+ permit: "view",
+ inputSchema: {
+ type: "object",
+ properties: {},
+ required: [],
+ additionalProperties: true,
+ },
+ },
"publish.list": {
id: "publish.list",
command: "list-publishes",
diff --git a/packages/protocol/src/builder-api/operation-docs.test.ts b/packages/protocol/src/builder-api/operation-docs.test.ts
index 74a998ea41..d4b7c5ba00 100644
--- a/packages/protocol/src/builder-api/operation-docs.test.ts
+++ b/packages/protocol/src/builder-api/operation-docs.test.ts
@@ -66,6 +66,24 @@ test("documents direct string props for update-props", () => {
expect(docs?.description).toContain('"type": "string"');
});
+test("guides agents to keep Assets content databases small", () => {
+ const getDescription = (command: string) =>
+ publicApiOperationDocumentation.find((item) => item.command === command)
+ ?.description ?? "";
+
+ expect(getDescription("create-assets-resource")).toContain(
+ "selecting only fields the page renders"
+ );
+ expect(getDescription("create-assets-resource")).toContain(
+ "content mode none"
+ );
+ expect(getDescription("update-assets-resource")).toContain(
+ "only rendered fields"
+ );
+ expect(getDescription("preview-asset-query")).toContain("usedBytes");
+ expect(getDescription("preview-asset-query")).toContain("truncated");
+});
+
test("documents JSX insertion through the fragment field", () => {
const docs = publicApiOperationDocumentation.find(
({ command }) => command === "insert-fragment"
diff --git a/packages/protocol/src/builder-api/operation-docs.ts b/packages/protocol/src/builder-api/operation-docs.ts
index 02c9ba5511..c122eb7611 100644
--- a/packages/protocol/src/builder-api/operation-docs.ts
+++ b/packages/protocol/src/builder-api/operation-docs.ts
@@ -587,6 +587,61 @@ const curatedPublicApiOperationDocumentation = [
"webstudio list-resources --scope-instance body-id --json",
],
},
+ {
+ command: "list-assets-resources",
+ description: "List Assets system resources and their query configuration.",
+ examples: [
+ "webstudio list-assets-resources --json",
+ "webstudio list-assets-resources --scope-instance body-id --json",
+ ],
+ },
+ {
+ command: "get-assets-resource",
+ description:
+ "Inspect one Assets system resource and its query configuration.",
+ requiredOptions: ["resource", "json"],
+ examples: ["webstudio get-assets-resource --resource resource-id --json"],
+ },
+ {
+ command: "create-assets-resource",
+ description:
+ "Create a scoped Assets resource. Omit query to use the minimal default query. For an explicit query, minimize the content database by selecting only fields the page renders, keeping includeMetadata false unless required, and using content mode none unless file content is rendered. Preview concrete queries and inspect size diagnostics before saving.",
+ requiredOptions: ["input", "json"],
+ examples: [
+ "webstudio create-assets-resource --input assets-resource.json --json",
+ ],
+ },
+ {
+ command: "update-assets-resource",
+ description:
+ "Update an Assets resource. Set query to null to restore the minimal default query. Keep explicit queries storage-efficient by selecting only rendered fields, keeping includeMetadata false unless required, and loading only the necessary file content after narrow filtering.",
+ requiredOptions: ["input", "json"],
+ examples: [
+ "webstudio update-assets-resource --input assets-resource-update.json --json",
+ ],
+ },
+ {
+ command: "validate-asset-query",
+ description:
+ "Validate a structured Assets query and return its referenced dynamic fields and bounded operation counts.",
+ examples: [
+ 'webstudio validate-asset-query \'{"query":{"where":{"all":[{"field":["properties","slug"],"operator":"eq","value":"hello-world"}]},"limit":1}}\'',
+ ],
+ },
+ {
+ command: "preview-asset-query",
+ description:
+ "Run an authenticated structured Assets query against indexed metadata, optionally loading bounded file content. Returns renderable results in data and non-bindable preview statistics in __diagnostics__. Before saving a query, inspect usedBytes, maxBytes, unboundedBytes, and truncated; reduce selected fields, candidate files, or embedded content when usage approaches the limit.",
+ examples: [
+ "webstudio preview-asset-query --input asset-query-preview.json --json",
+ ],
+ },
+ {
+ command: "get-asset-field-catalog",
+ description:
+ "Get standard fields plus dynamic Markdown frontmatter and JSON fields with observed types, occurrence counts, optionality, and mixed-type state.",
+ examples: ["webstudio get-asset-field-catalog --json"],
+ },
{
command: "create-resource",
description:
diff --git a/packages/protocol/src/schema.ts b/packages/protocol/src/schema.ts
index 25ced03a48..fa8fc0befa 100644
--- a/packages/protocol/src/schema.ts
+++ b/packages/protocol/src/schema.ts
@@ -1,4 +1,5 @@
import { asset, assetFolder, page } from "@webstudio-is/sdk/schema";
+import { contentArtifactV1 } from "@webstudio-is/content-engine";
import { builderNamespaces } from "@webstudio-is/project-build/contracts";
import {
builderPatchSchema as internalBuilderPatchSchema,
@@ -73,6 +74,7 @@ export const publishedProjectBundle = projectBundle.extend({
user: z.object({ email: z.string().nullable() }).optional(),
projectDomain: z.string(),
projectTitle: z.string(),
+ assetIndex: contentArtifactV1.optional(),
});
export type PublishedProjectBundle = z.infer<typeof publishedProjectBundle>;
diff --git a/packages/query-builder-react/package.json b/packages/query-builder-react/package.json
new file mode 100644
index 0000000000..909f0b031b
--- /dev/null
+++ b/packages/query-builder-react/package.json
@@ -0,0 +1,28 @@
+{
+ "name": "@webstudio-is/query-builder-react",
+ "version": "0.0.0",
+ "description": "Webstudio query-builder UI",
+ "type": "module",
+ "private": true,
+ "scripts": {
+ "test": "vitest run",
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@webstudio-is/design-system": "workspace:*",
+ "@webstudio-is/icons": "workspace:*",
+ "@webstudio-is/query-builder": "workspace:*",
+ "react": "18.3.0-canary-14898b6a9-20240318"
+ },
+ "devDependencies": {
+ "@testing-library/react": "^16.2.0",
+ "@types/react": "^18.2.70",
+ "@types/react-dom": "^18.2.25",
+ "@webstudio-is/tsconfig": "workspace:*",
+ "react-dom": "18.3.0-canary-14898b6a9-20240318",
+ "vitest": "^3.1.2"
+ },
+ "exports": {
+ ".": "./src/index.tsx"
+ }
+}
diff --git a/packages/query-builder-react/src/index.test.tsx b/packages/query-builder-react/src/index.test.tsx
new file mode 100644
index 0000000000..8c4d167170
--- /dev/null
+++ b/packages/query-builder-react/src/index.test.tsx
@@ -0,0 +1,443 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { useState } from "react";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, test } from "vitest";
+import {
+ createStructuredQuery,
+ type QueryDefinition,
+} from "@webstudio-is/query-builder";
+import { StructuredQueryBuilder } from "./index";
+import { genericQueryCapabilities, type GenericQuery } from "./test-fixtures";
+
+const selectionCapabilities = {
+ ...genericQueryCapabilities,
+ source: {
+ ...genericQueryCapabilities.source,
+ controls: genericQueryCapabilities.source.controls.map((parameter) =>
+ parameter.type === "variant"
+ ? {
+ ...parameter,
+ schema: {
+ ...parameter.schema,
+ properties: {
+ ...parameter.schema.properties,
+ maxBytes: { type: "number" },
+ },
+ },
+ config: {
+ ...parameter.config,
+ selection: {
+ label: "Output",
+ emptyOption: "summary",
+ baseline: { key: "includeMetadata", label: "File metadata" },
+ },
+ options: parameter.config.options.map((option) =>
+ option.value === "full"
+ ? {
+ ...option,
+ defaultValue: { ...option.defaultValue, maxBytes: 64 },
+ fields: [
+ {
+ key: "maxBytes",
+ label: "Maximum bytes",
+ type: "number" as const,
+ min: 1,
+ },
+ ],
+ }
+ : option
+ ),
+ },
+ }
+ : parameter
+ ),
+ },
+} as const;
+
+const groupedSelectionCapabilities = {
+ ...selectionCapabilities,
+ source: {
+ ...selectionCapabilities.source,
+ controls: [
+ ...selectionCapabilities.source.controls,
+ {
+ type: "variant",
+ key: "content",
+ label: "File content",
+ defaultValue: { mode: "none" },
+ schema: {
+ type: "object",
+ properties: { mode: { enum: ["none", "full", "range"] } },
+ required: ["mode"],
+ additionalProperties: true,
+ },
+ config: {
+ discriminator: "mode",
+ selection: { label: "Output", emptyOption: "none" },
+ options: [
+ {
+ value: "none",
+ label: "No content",
+ defaultValue: { mode: "none" },
+ fields: [],
+ },
+ {
+ value: "full",
+ label: "Full file",
+ defaultValue: { mode: "full" },
+ fields: [],
+ },
+ {
+ value: "range",
+ label: "Byte range",
+ defaultValue: { mode: "range" },
+ fields: [],
+ },
+ ],
+ },
+ },
+ ],
+ },
+} as const;
+
+afterEach(cleanup);
+
+const QueryBuilderFixture = () => {
+ const [query, setQuery] = useState(
+ createStructuredQuery(genericQueryCapabilities) as GenericQuery
+ );
+ return (
+ <StructuredQueryBuilder
+ value={query}
+ capabilities={genericQueryCapabilities}
+ onChange={setQuery}
+ />
+ );
+};
+
+const FieldSelectionFixture = () => {
+ const [query, setQuery] = useState<GenericQuery>({
+ ...(createStructuredQuery(genericQueryCapabilities) as GenericQuery),
+ selection: { mode: "fields", includeMetadata: true, fields: [] },
+ });
+ return (
+ <StructuredQueryBuilder
+ value={query}
+ capabilities={genericQueryCapabilities}
+ onChange={setQuery}
+ />
+ );
+};
+
+const UnknownFieldSelectionFixture = () => {
+ const [query, setQuery] = useState<GenericQuery>({
+ ...(createStructuredQuery(genericQueryCapabilities) as GenericQuery),
+ selection: {
+ mode: "fields",
+ includeMetadata: true,
+ fields: [["legacy", "field"]],
+ },
+ });
+ return (
+ <StructuredQueryBuilder
+ value={query}
+ capabilities={genericQueryCapabilities}
+ onChange={setQuery}
+ />
+ );
+};
+
+const MalformedFieldSelectionFixture = () => {
+ const [query, setQuery] = useState<GenericQuery>({
+ ...(createStructuredQuery(genericQueryCapabilities) as GenericQuery),
+ selection: {
+ mode: "fields",
+ includeMetadata: true,
+ fields: [undefined, ["title"], ["invalid", 1]] as never,
+ },
+ });
+ return (
+ <StructuredQueryBuilder
+ value={query}
+ capabilities={genericQueryCapabilities}
+ onChange={setQuery}
+ />
+ );
+};
+
+const UnknownFilterAndSortFixture = () => {
+ const [query, setQuery] = useState<GenericQuery>({
+ ...(createStructuredQuery(genericQueryCapabilities) as GenericQuery),
+ where: {
+ all: [{ field: ["legacy", "filter"], operator: "eq", value: '"yes"' }],
+ },
+ sort: [{ field: ["legacy", "sort"], direction: "asc" }],
+ });
+ return (
+ <StructuredQueryBuilder
+ value={query}
+ capabilities={genericQueryCapabilities}
+ onChange={setQuery}
+ />
+ );
+};
+
+const SelectionFixture = () => {
+ const [query, setQuery] = useState<GenericQuery>({
+ ...(createStructuredQuery(selectionCapabilities) as GenericQuery),
+ selection: {
+ mode: "fields",
+ includeMetadata: true,
+ fields: [["title"]],
+ },
+ });
+ return (
+ <StructuredQueryBuilder
+ value={query}
+ capabilities={selectionCapabilities}
+ onChange={setQuery}
+ />
+ );
+};
+
+const ConfigurableSelectionFixture = () => {
+ const [query, setQuery] = useState<GenericQuery>({
+ ...(createStructuredQuery(selectionCapabilities) as GenericQuery),
+ selection: {
+ mode: "full",
+ includeMetadata: false,
+ maxBytes: 64,
+ },
+ });
+ return (
+ <StructuredQueryBuilder
+ value={query}
+ capabilities={selectionCapabilities}
+ onChange={setQuery}
+ />
+ );
+};
+
+const GroupedSelectionFixture = () => {
+ const [query, setQuery] = useState(
+ createStructuredQuery(groupedSelectionCapabilities) as GenericQuery & {
+ content: { mode: "none" | "full" | "range" };
+ }
+ );
+ return (
+ <StructuredQueryBuilder
+ value={query}
+ capabilities={groupedSelectionCapabilities}
+ onChange={setQuery}
+ />
+ );
+};
+
+describe("structured query builder", () => {
+ test("renders and edits solely from provider-neutral capabilities", () => {
+ render(<QueryBuilderFixture />);
+
+ expect(screen.getByText("Filters")).toBeTruthy();
+ expect(screen.getByText("Sort")).toBeTruthy();
+ expect(screen.getByText("Selection")).toBeTruthy();
+
+ const limit = screen.getByLabelText("Limit");
+ expect((limit as HTMLInputElement).type).toBe("number");
+ expect((limit as HTMLInputElement).step).toBe("any");
+ fireEvent.change(limit, { target: { value: "20" } });
+ expect((limit as HTMLInputElement).value).toBe("20");
+
+ const source = screen.getByLabelText("Query");
+ expect((source as HTMLTextAreaElement).value).toContain("limit: 20");
+ });
+
+ test("lets the consumer place the query source", () => {
+ render(
+ <StructuredQueryBuilder
+ value={createStructuredQuery<GenericQuery>(genericQueryCapabilities)}
+ capabilities={genericQueryCapabilities}
+ renderSource={(source) => (
+ <section aria-label="Query tab">{source}</section>
+ )}
+ onChange={() => {}}
+ />
+ );
+
+ expect(
+ screen
+ .getByLabelText("Query tab")
+ .contains(screen.getByLabelText("Query"))
+ ).toBe(true);
+ expect(screen.queryByText("Query")).toBeNull();
+ });
+
+ test("renders section labels from the provider definition", () => {
+ const capabilities: QueryDefinition<"string" | "date", "eq" | "after"> = {
+ ...genericQueryCapabilities,
+ source: {
+ ...genericQueryCapabilities.source,
+ controls: genericQueryCapabilities.source.controls.map((control) =>
+ control.type === "filter"
+ ? { ...control, label: "Conditions" }
+ : control.type === "sort"
+ ? { ...control, label: "Ordering" }
+ : control
+ ),
+ },
+ };
+ const query = createStructuredQuery<GenericQuery>(capabilities);
+
+ render(
+ <StructuredQueryBuilder
+ value={query}
+ capabilities={capabilities}
+ onChange={() => {}}
+ />
+ );
+
+ expect(screen.getByText("Conditions")).toBeTruthy();
+ expect(screen.getByText("Ordering")).toBeTruthy();
+ });
+
+ test("renders provider-defined sort directions", () => {
+ const capabilities = {
+ ...genericQueryCapabilities,
+ source: {
+ ...genericQueryCapabilities.source,
+ controls: genericQueryCapabilities.source.controls.map((control) =>
+ control.type === "sort"
+ ? {
+ ...control,
+ defaultItem: {
+ ...control.defaultItem,
+ direction: "newest",
+ },
+ directions: [
+ { value: "newest", label: "Newest first" },
+ { value: "oldest", label: "Oldest first" },
+ ],
+ }
+ : control
+ ),
+ },
+ } as const;
+ const Fixture = () => {
+ const [query, setQuery] = useState(
+ createStructuredQuery<GenericQuery>(capabilities)
+ );
+ return (
+ <StructuredQueryBuilder
+ value={query}
+ capabilities={capabilities}
+ onChange={setQuery}
+ />
+ );
+ };
+
+ render(<Fixture />);
+ fireEvent.click(screen.getByLabelText("Add query sort"));
+
+ expect(screen.getByText("Newest first")).toBeTruthy();
+ expect(
+ (screen.getByLabelText("Query") as HTMLTextAreaElement).value
+ ).toContain('direction: "newest"');
+ });
+
+ test("renders the provider description", () => {
+ const capabilities = {
+ ...genericQueryCapabilities,
+ description: "Only indexed fields appear in autocomplete.",
+ };
+
+ render(
+ <StructuredQueryBuilder
+ value={createStructuredQuery<GenericQuery>(capabilities)}
+ capabilities={capabilities}
+ onChange={() => {}}
+ />
+ );
+
+ expect(
+ screen.getByText("Only indexed fields appear in autocomplete.")
+ ).toBeTruthy();
+ });
+
+ test("edits a declarative field-list parameter", () => {
+ render(<FieldSelectionFixture />);
+
+ fireEvent.click(screen.getByLabelText("Add fields"));
+ expect(
+ (screen.getByLabelText("Query") as HTMLTextAreaElement).value
+ ).toContain('fields: [["title"]]');
+ });
+
+ test("preserves a selected field that is absent from current capabilities", () => {
+ render(<UnknownFieldSelectionFixture />);
+
+ expect(screen.getByText("legacy.field")).toBeTruthy();
+ expect(
+ (screen.getByLabelText("Query") as HTMLTextAreaElement).value
+ ).toContain('fields: [["legacy", "field"]]');
+ });
+
+ test("ignores malformed persisted field selections", () => {
+ render(<MalformedFieldSelectionFixture />);
+
+ expect(screen.getByText("Title")).toBeTruthy();
+ expect(screen.queryByText("invalid.1")).toBeNull();
+ });
+
+ test("shows configured filter and sort fields that are absent from capabilities", () => {
+ render(<UnknownFilterAndSortFixture />);
+
+ expect(screen.getByText("legacy.filter")).toBeTruthy();
+ expect(screen.getByText("legacy.sort")).toBeTruthy();
+ const source = (screen.getByLabelText("Query") as HTMLTextAreaElement)
+ .value;
+ expect(source).toContain('["legacy","filter"]');
+ expect(source).toContain('["legacy", "sort"]');
+ });
+
+ test("renders projections from a declarative Output section", () => {
+ render(<SelectionFixture />);
+
+ expect(screen.getByText("Output")).toBeTruthy();
+ expect(screen.getByText("File metadata")).toBeTruthy();
+ expect(screen.getByLabelText("Add output")).toBeTruthy();
+ expect(screen.getByText("Title")).toBeTruthy();
+ expect(
+ (screen.getByLabelText("Query") as HTMLTextAreaElement).value
+ ).toContain('fields: [["title"]]');
+ fireEvent.click(screen.getByLabelText("Delete file metadata"));
+ expect(
+ (screen.getByLabelText("Query") as HTMLTextAreaElement).value
+ ).toContain("includeMetadata: false");
+ expect(
+ (screen.getByLabelText("Delete title") as HTMLButtonElement).disabled
+ ).toBe(true);
+ });
+
+ test("edits a configurable output from its single list row", () => {
+ render(<ConfigurableSelectionFixture />);
+
+ fireEvent.click(screen.getByRole("button", { name: "Full" }));
+ expect(screen.getByText("Maximum bytes")).toBeTruthy();
+ fireEvent.change(screen.getByLabelText("Maximum bytes"), {
+ target: { value: "128" },
+ });
+ expect(
+ (screen.getByLabelText("Query") as HTMLTextAreaElement).value
+ ).toContain("maxBytes: 128");
+ });
+
+ test("groups mutually exclusive output families in the add menu", () => {
+ render(<GroupedSelectionFixture />);
+
+ fireEvent.keyDown(screen.getByLabelText("Add output"), { key: "Enter" });
+ expect(screen.getByText("Selection")).toBeTruthy();
+ expect(screen.getByText("File content")).toBeTruthy();
+ expect(screen.getByRole("separator")).toBeTruthy();
+ });
+});
diff --git a/packages/query-builder-react/src/index.tsx b/packages/query-builder-react/src/index.tsx
new file mode 100644
index 0000000000..e3172dd680
--- /dev/null
+++ b/packages/query-builder-react/src/index.tsx
@@ -0,0 +1,1218 @@
+import {
+ Fragment,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ CssValueListArrowFocus,
+ CssValueListItem,
+ Flex,
+ Grid,
+ InputField,
+ Label,
+ Popover,
+ PopoverContent,
+ PopoverTitle,
+ PopoverTrigger,
+ Select,
+ SmallIconButton,
+ Text,
+ TextArea,
+ theme,
+} from "@webstudio-is/design-system";
+import { MinusIcon, PlusIcon } from "@webstudio-is/icons";
+import {
+ createQueryCondition,
+ createQuerySort,
+ createQuerySourceCodec,
+ getCompatibleQueryOperators,
+ type QueryCondition,
+ type QueryField,
+ type QueryGroup,
+ type QuerySort,
+ type QueryDefinition,
+ type QueryFilterControl,
+ type QueryExpressionControl,
+ type QuerySortControl,
+ type QueryVariantControl,
+ type QueryWhere,
+} from "@webstudio-is/query-builder";
+import {
+ getQueryFieldKey,
+ getQueryWhereMetrics,
+} from "@webstudio-is/query-builder/runtime";
+
+export type QueryValueEditorProps = {
+ "aria-label": string;
+ value: string;
+ onChange: (value: string) => void;
+ role: "condition" | "value";
+ input: "expression" | "number";
+ min?: number;
+ max?: number;
+ exclusiveMin?: boolean;
+ exclusiveMax?: boolean;
+ integer?: boolean;
+};
+
+export type QuerySourceEditorProps = {
+ "aria-label": string;
+ value: string;
+ onChange: (value: string) => void;
+ onChangeComplete: (value: string) => void;
+};
+
+export type QueryBuilderEditors = {
+ expression: (props: QueryValueEditorProps) => ReactNode;
+ source: (props: QuerySourceEditorProps) => ReactNode;
+};
+
+type BuilderProps<
+ FieldType extends string,
+ Operator extends string,
+ Query extends Record<string, unknown>,
+> = {
+ value: Query;
+ capabilities: QueryDefinition<FieldType, Operator>;
+ editors?: Partial<QueryBuilderEditors>;
+ renderSource?: (source: ReactNode) => ReactNode;
+ sectionPaddingInline?: string;
+ onChange: (value: Query) => void;
+};
+
+type SharedProps<FieldType extends string, Operator extends string> = {
+ capabilities: QueryDefinition<FieldType, Operator>;
+ filter: QueryFilterControl<Operator>;
+ renderExpressionEditor: QueryBuilderEditors["expression"];
+ sectionPaddingInline?: string;
+};
+
+const QuerySelectionListItem = ({
+ id,
+ index,
+ label,
+ canDelete,
+ onDelete,
+ settings,
+}: {
+ id: string;
+ index: number;
+ label: string;
+ canDelete: boolean;
+ onDelete: () => void;
+ settings?: ReactNode;
+}) => {
+ const item = (
+ <CssValueListItem
+ id={id}
+ index={index}
+ type="button"
+ label={<Label>{label}</Label>}
+ buttons={
+ <SmallIconButton
+ tabIndex={-1}
+ aria-label={`Delete ${label.toLowerCase()}`}
+ disabled={canDelete === false}
+ variant="destructive"
+ icon={<MinusIcon />}
+ onClick={onDelete}
+ />
+ }
+ />
+ );
+ if (settings === undefined) {
+ return item;
+ }
+ return (
+ <Popover>
+ <PopoverTrigger asChild>{item}</PopoverTrigger>
+ <PopoverContent align="start">
+ <PopoverTitle>{label}</PopoverTitle>
+ <Grid
+ gap={2}
+ css={{ padding: theme.spacing[5], minWidth: theme.spacing[35] }}
+ >
+ {settings}
+ </Grid>
+ </PopoverContent>
+ </Popover>
+ );
+};
+
+const getField = <FieldType extends string>(
+ fields: readonly QueryField<FieldType>[],
+ path: string[]
+) => {
+ const key = getQueryFieldKey(path);
+ return (
+ fields.find((field) => getQueryFieldKey(field.path) === key) ?? {
+ path,
+ label: path.join("."),
+ types: [],
+ }
+ );
+};
+
+const getFieldSelection = <FieldType extends string>(
+ fields: readonly QueryField<FieldType>[],
+ path: string[]
+) => {
+ const selected = getField(fields, path);
+ return {
+ selected,
+ options: fields.includes(selected) ? fields : [selected, ...fields],
+ };
+};
+
+const getFieldPaths = (value: unknown) =>
+ Array.isArray(value)
+ ? value.filter(
+ (path): path is string[] =>
+ Array.isArray(path) &&
+ path.every((segment) => typeof segment === "string")
+ )
+ : [];
+
+const Condition = <FieldType extends string, Operator extends string>({
+ capabilities,
+ renderExpressionEditor,
+ condition,
+ onChange,
+ onDelete,
+}: SharedProps<FieldType, Operator> & {
+ condition: QueryCondition<string[], Operator>;
+ onChange: (condition: QueryCondition<string[], Operator>) => void;
+ onDelete: () => void;
+}) => {
+ if (capabilities.fields.length === 0) {
+ return <Text color="destructive">No query fields are available.</Text>;
+ }
+ const { selected: selectedField, options: fieldOptions } = getFieldSelection(
+ capabilities.fields,
+ condition.field
+ );
+ const compatibleOperators = getCompatibleQueryOperators(
+ selectedField.types,
+ capabilities.operators,
+ selectedField.operators
+ );
+ const selectedOperator = compatibleOperators.find(
+ (operator) => operator.value === condition.operator
+ );
+ const operators =
+ selectedOperator === undefined
+ ? [
+ {
+ value: condition.operator,
+ label: String(condition.operator),
+ types: selectedField.types,
+ input: {
+ control: "expression" as const,
+ defaultValue: condition.value,
+ },
+ },
+ ...compatibleOperators,
+ ]
+ : compatibleOperators;
+
+ return (
+ <Grid gap={1}>
+ <Grid
+ gap={1}
+ align="center"
+ css={{ gridTemplateColumns: "1fr 1fr min-content" }}
+ >
+ <Select<(typeof capabilities.fields)[number]>
+ aria-label="Query field"
+ options={fieldOptions}
+ getLabel={(field) => field.label}
+ getValue={(field) => getQueryFieldKey(field.path)}
+ value={selectedField}
+ onChange={(field) => {
+ const nextOperators = getCompatibleQueryOperators(
+ field.types,
+ capabilities.operators,
+ field.operators
+ );
+ const operator = nextOperators.some(
+ (option) => option.value === condition.operator
+ )
+ ? condition.operator
+ : nextOperators[0]?.value;
+ if (operator === undefined) {
+ return;
+ }
+ onChange({
+ ...condition,
+ field: field.path,
+ operator,
+ value:
+ operator === condition.operator
+ ? condition.value
+ : (capabilities.operators.find(
+ (item) => item.value === operator
+ )?.input.defaultValue ?? condition.value),
+ });
+ }}
+ />
+ <Select<(typeof operators)[number]>
+ aria-label="Query operator"
+ options={operators}
+ getLabel={(operator: (typeof operators)[number]) => operator.label}
+ getValue={(operator: (typeof operators)[number]) =>
+ String(operator.value)
+ }
+ value={
+ operators.find(
+ (operator) => operator.value === condition.operator
+ ) ?? operators[0]
+ }
+ onChange={(operator) => {
+ onChange({
+ ...condition,
+ operator: operator.value,
+ value: operator.input.defaultValue,
+ });
+ }}
+ />
+ <SmallIconButton
+ aria-label="Delete query condition"
+ variant="destructive"
+ icon={<MinusIcon />}
+ onClick={onDelete}
+ />
+ </Grid>
+ {(selectedOperator?.input.control ?? operators[0]?.input.control) !==
+ "none" &&
+ renderExpressionEditor({
+ "aria-label": "Query condition value",
+ value: condition.value,
+ role: "condition",
+ input: "expression",
+ onChange: (value) => onChange({ ...condition, value }),
+ })}
+ </Grid>
+ );
+};
+
+const Group = <FieldType extends string, Operator extends string>({
+ group,
+ conditionCount,
+ depth,
+ root = false,
+ onChange,
+ onDelete,
+ ...shared
+}: SharedProps<FieldType, Operator> & {
+ group: QueryGroup<string[], Operator>;
+ conditionCount: number;
+ depth: number;
+ root?: boolean;
+ onChange: (group: QueryGroup<string[], Operator>) => void;
+ onDelete?: () => void;
+}) => {
+ const combinator = "all" in group ? "all" : "any";
+ const children = "all" in group ? group.all : group.any;
+ const defaultCombinator = shared.filter.combinators[0] ?? "all";
+ const combinators: readonly ("all" | "any")[] =
+ shared.filter.combinators.includes(combinator)
+ ? shared.filter.combinators
+ : [combinator, ...shared.filter.combinators];
+ const updateChildren = (next: QueryWhere<string[], Operator>[]) =>
+ onChange(combinator === "all" ? { all: next } : { any: next });
+ const canAddCondition = conditionCount < shared.filter.limits.conditions;
+ const canAddGroup = depth < shared.filter.limits.depth;
+
+ return (
+ <Grid
+ gap={2}
+ css={{
+ ...(root
+ ? {
+ paddingInline: shared.sectionPaddingInline,
+ borderTop: `1px solid ${theme.colors.borderMain}`,
+ paddingTop: theme.spacing[7],
+ }
+ : {
+ paddingLeft: theme.spacing[3],
+ borderLeft: `1px solid ${theme.colors.borderMain}`,
+ }),
+ }}
+ >
+ <Flex justify="between" align="center" gap={1}>
+ {root ? (
+ <Label text="title">{shared.filter.label}</Label>
+ ) : (
+ <Text>Filter group</Text>
+ )}
+ <Flex gap={1} align="center">
+ <Select<"all" | "any">
+ aria-label={root ? "Query logic" : "Query group logic"}
+ options={combinators}
+ getLabel={(value: "all" | "any") =>
+ value === "all" ? "Match all" : "Match any"
+ }
+ value={combinator}
+ onChange={(value: "all" | "any") =>
+ onChange(value === "all" ? { all: children } : { any: children })
+ }
+ />
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <SmallIconButton
+ aria-label="Add query condition or group"
+ disabled={canAddCondition === false && canAddGroup === false}
+ icon={<PlusIcon />}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" sideOffset={4}>
+ <DropdownMenuItem
+ disabled={canAddCondition === false}
+ onSelect={() =>
+ updateChildren([
+ ...children,
+ createQueryCondition(shared.capabilities),
+ ])
+ }
+ >
+ {shared.filter.labels?.condition ?? "Condition"}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={canAddGroup === false}
+ onSelect={() =>
+ updateChildren([
+ ...children,
+ defaultCombinator === "all" ? { all: [] } : { any: [] },
+ ])
+ }
+ >
+ {shared.filter.labels?.conditionGroup ?? "Condition group"}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {onDelete !== undefined && (
+ <SmallIconButton
+ aria-label="Delete query group"
+ variant="destructive"
+ icon={<MinusIcon />}
+ onClick={onDelete}
+ />
+ )}
+ </Flex>
+ </Flex>
+ {children.map((child, index) =>
+ "field" in child ? (
+ <Condition
+ {...shared}
+ key={index}
+ condition={child}
+ onChange={(next) => {
+ const updated = [...children];
+ updated[index] = next;
+ updateChildren(updated);
+ }}
+ onDelete={() =>
+ updateChildren(
+ children.filter((_, position) => position !== index)
+ )
+ }
+ />
+ ) : (
+ <Group
+ {...shared}
+ key={index}
+ group={child}
+ conditionCount={conditionCount}
+ depth={depth + 1}
+ onChange={(next) => {
+ const updated = [...children];
+ updated[index] = next;
+ updateChildren(updated);
+ }}
+ onDelete={() =>
+ updateChildren(
+ children.filter((_, position) => position !== index)
+ )
+ }
+ />
+ )
+ )}
+ </Grid>
+ );
+};
+
+const Sorting = <FieldType extends string, Operator extends string>({
+ sort,
+ onChange,
+ capabilities,
+ control,
+ sectionPaddingInline,
+}: Pick<
+ SharedProps<FieldType, Operator>,
+ "capabilities" | "sectionPaddingInline"
+> & {
+ control: QuerySortControl;
+ sort: QuerySort<string[]>[];
+ onChange: (sort: QuerySort<string[]>[]) => void;
+}) => (
+ <Grid gap={2} css={{ paddingInline: sectionPaddingInline }}>
+ <Flex justify="between" align="center">
+ <Label text="title">{control.label}</Label>
+ <SmallIconButton
+ aria-label="Add query sort"
+ disabled={control.max !== undefined && sort.length >= control.max}
+ icon={<PlusIcon />}
+ onClick={() => onChange([...sort, createQuerySort(capabilities)])}
+ />
+ </Flex>
+ {sort.map((order, index) => {
+ if (capabilities.fields.length === 0) {
+ return null;
+ }
+ const { selected: selectedField, options: fieldOptions } =
+ getFieldSelection(capabilities.fields, order.field);
+ return (
+ <Grid
+ key={index}
+ gap={1}
+ align="center"
+ css={{ gridTemplateColumns: "1fr 1fr min-content" }}
+ >
+ <Select<(typeof capabilities.fields)[number]>
+ aria-label="Query sort field"
+ options={fieldOptions}
+ getLabel={(field) => field.label}
+ getValue={(field) => getQueryFieldKey(field.path)}
+ value={selectedField}
+ onChange={(field) => {
+ const next = [...sort];
+ next[index] = { ...order, field: field.path };
+ onChange(next);
+ }}
+ />
+ <Select<(typeof control.directions)[number]>
+ aria-label="Query sort direction"
+ options={control.directions}
+ getLabel={(direction) => direction.label}
+ getValue={(direction) => direction.value}
+ value={
+ control.directions.find(
+ ({ value }) => value === order.direction
+ ) ?? control.directions[0]
+ }
+ onChange={(direction) => {
+ const next = [...sort];
+ next[index] = { ...order, direction: direction.value };
+ onChange(next);
+ }}
+ />
+ <SmallIconButton
+ aria-label="Delete query sort"
+ variant="destructive"
+ icon={<MinusIcon />}
+ onClick={() =>
+ onChange(sort.filter((_, position) => position !== index))
+ }
+ />
+ </Grid>
+ );
+ })}
+ </Grid>
+);
+
+const QueryParameters = ({
+ parameters,
+ fields,
+ value,
+ sectionPaddingInline,
+ onChange,
+}: {
+ parameters: readonly QueryVariantControl[];
+ fields: readonly QueryField[];
+ value: Record<string, unknown>;
+ sectionPaddingInline?: string;
+ onChange: (key: string, value: unknown) => void;
+}) => {
+ const getCurrent = (parameter: QueryVariantControl) =>
+ typeof value[parameter.key] === "object" &&
+ value[parameter.key] !== null &&
+ Array.isArray(value[parameter.key]) === false
+ ? (value[parameter.key] as Record<string, unknown>)
+ : parameter.config.options[0]?.defaultValue;
+ const getSelected = (parameter: QueryVariantControl) => {
+ const current = getCurrent(parameter);
+ return {
+ current,
+ option: parameter.config.options.find(
+ (option) => current?.[parameter.config.discriminator] === option.value
+ ),
+ };
+ };
+ const selectionParameters = parameters.filter(
+ (parameter) => parameter.config.selection !== undefined
+ );
+ const regularParameters = parameters.filter(
+ (parameter) => parameter.config.selection === undefined
+ );
+ const selectionLabel =
+ selectionParameters[0]?.config.selection?.label ?? "Selection";
+
+ const renderNumberFields = (
+ parameter: QueryVariantControl,
+ current: Record<string, unknown>,
+ option: QueryVariantControl["config"]["options"][number]
+ ) =>
+ option.fields.map((field) =>
+ field.type === "number" ? (
+ <Grid key={field.key} gap={1}>
+ <Label>{field.label}</Label>
+ <InputField
+ aria-label={field.label}
+ type="number"
+ min={field.min}
+ max={field.max}
+ step={field.integer === true ? 1 : "any"}
+ value={
+ current[field.key] === undefined ? "" : String(current[field.key])
+ }
+ onChange={(event) =>
+ onChange(parameter.key, {
+ ...current,
+ [field.key]:
+ field.optional && event.target.value === ""
+ ? undefined
+ : Number(event.target.value),
+ })
+ }
+ />
+ </Grid>
+ ) : null
+ );
+
+ const renderRegularFields = (
+ parameter: QueryVariantControl,
+ current: Record<string, unknown>,
+ option: QueryVariantControl["config"]["options"][number]
+ ) => (
+ <Grid gap={1}>
+ {option.fields.map((control) => {
+ if (control.type === "number") {
+ return renderNumberFields(parameter, current, {
+ ...option,
+ fields: [control],
+ });
+ }
+ const paths = getFieldPaths(current[control.key]);
+ const selectedKeys = new Set(paths.map(getQueryFieldKey));
+ const available = fields.filter(
+ ({ path }) => selectedKeys.has(getQueryFieldKey(path)) === false
+ );
+ return (
+ <Grid key={control.key} gap={1}>
+ {paths.map((path, index) => {
+ const selectedField = getField(fields, path);
+ return (
+ <Grid
+ key={`${getQueryFieldKey(path)}:${index}`}
+ gap={1}
+ css={{ gridTemplateColumns: "1fr auto" }}
+ >
+ <Select<QueryField>
+ aria-label={`${control.label} ${index + 1}`}
+ options={[selectedField, ...available]}
+ getLabel={(field) => field.label}
+ getValue={(field) => getQueryFieldKey(field.path)}
+ value={selectedField}
+ onChange={(field) =>
+ onChange(parameter.key, {
+ ...current,
+ [control.key]: paths.map((value, position) =>
+ position === index ? field.path : value
+ ),
+ })
+ }
+ />
+ <SmallIconButton
+ aria-label={`Delete ${control.label.toLowerCase()}`}
+ variant="destructive"
+ icon={<MinusIcon />}
+ onClick={() =>
+ onChange(parameter.key, {
+ ...current,
+ [control.key]: paths.filter(
+ (_, position) => position !== index
+ ),
+ })
+ }
+ />
+ </Grid>
+ );
+ })}
+ {available.length > 0 &&
+ (control.max === undefined || paths.length < control.max) && (
+ <SmallIconButton
+ aria-label={`Add ${control.label.toLowerCase()}`}
+ icon={<PlusIcon />}
+ onClick={() =>
+ onChange(parameter.key, {
+ ...current,
+ [control.key]: [...paths, available[0].path],
+ })
+ }
+ />
+ )}
+ </Grid>
+ );
+ })}
+ </Grid>
+ );
+
+ const getOptionPaths = (
+ current: Record<string, unknown>,
+ option: QueryVariantControl["config"]["options"][number]
+ ) => {
+ const fieldList = option.fields.find(
+ (field) => field.type === "field-list"
+ );
+ return {
+ fieldList,
+ paths:
+ fieldList === undefined ? [] : getFieldPaths(current[fieldList.key]),
+ };
+ };
+
+ const withCurrentBaseline = (
+ parameter: QueryVariantControl,
+ current: Record<string, unknown>,
+ next: Record<string, unknown>
+ ) => {
+ const baseline = parameter.config.selection?.baseline;
+ return baseline === undefined
+ ? next
+ : { ...next, [baseline.key]: current[baseline.key] !== false };
+ };
+
+ let selectionItemCount = 0;
+ for (const parameter of selectionParameters) {
+ const { current, option } = getSelected(parameter);
+ const selection = parameter.config.selection;
+ if (
+ current === undefined ||
+ option === undefined ||
+ selection === undefined
+ ) {
+ continue;
+ }
+ if (
+ selection.baseline !== undefined &&
+ current[selection.baseline.key] !== false
+ ) {
+ selectionItemCount += 1;
+ }
+ if (option.value !== selection.emptyOption) {
+ const { fieldList, paths } = getOptionPaths(current, option);
+ selectionItemCount += fieldList === undefined ? 1 : paths.length;
+ }
+ }
+ let selectionItemIndex = 0;
+
+ const getSelectionMenuItems = (parameter: QueryVariantControl) => {
+ const { current, option: selected } = getSelected(parameter);
+ const selection = parameter.config.selection;
+ if (current === undefined || selection === undefined) {
+ return [];
+ }
+ const items: ReactNode[] = [];
+ const baseline = selection.baseline;
+ if (baseline !== undefined && current[baseline.key] === false) {
+ items.push(
+ <DropdownMenuItem
+ key={`${parameter.key}:${baseline.key}`}
+ onSelect={() =>
+ onChange(parameter.key, {
+ ...current,
+ [baseline.key]: true,
+ })
+ }
+ >
+ {baseline.label}
+ </DropdownMenuItem>
+ );
+ }
+ for (const option of parameter.config.options) {
+ if (option.value === selection.emptyOption) {
+ continue;
+ }
+ const fieldList = option.fields.find(
+ (field) => field.type === "field-list"
+ );
+ if (fieldList === undefined) {
+ items.push(
+ <DropdownMenuItem
+ key={`${parameter.key}:${option.value}`}
+ disabled={selected?.value === option.value}
+ onSelect={() =>
+ onChange(
+ parameter.key,
+ withCurrentBaseline(
+ parameter,
+ current,
+ structuredClone(option.defaultValue)
+ )
+ )
+ }
+ >
+ {option.label}
+ </DropdownMenuItem>
+ );
+ continue;
+ }
+ const paths =
+ selected?.value === option.value
+ ? getFieldPaths(current[fieldList.key])
+ : [];
+ const selectedKeys = new Set(paths.map(getQueryFieldKey));
+ for (const field of fields) {
+ items.push(
+ <DropdownMenuItem
+ key={`${parameter.key}:${option.value}:${getQueryFieldKey(field.path)}`}
+ disabled={
+ selectedKeys.has(getQueryFieldKey(field.path)) ||
+ (fieldList.max !== undefined && paths.length >= fieldList.max)
+ }
+ onSelect={() =>
+ onChange(parameter.key, {
+ ...withCurrentBaseline(
+ parameter,
+ current,
+ structuredClone(option.defaultValue)
+ ),
+ [fieldList.key]: [...paths, field.path],
+ })
+ }
+ >
+ {field.label}
+ </DropdownMenuItem>
+ );
+ }
+ }
+ return items;
+ };
+
+ return (
+ <>
+ {selectionParameters.length > 0 && (
+ <Grid
+ gap={2}
+ css={{
+ borderTop: `1px solid ${theme.colors.borderMain}`,
+ paddingTop: theme.spacing[7],
+ }}
+ >
+ <Flex
+ justify="between"
+ align="center"
+ css={{ paddingInline: sectionPaddingInline }}
+ >
+ <Label text="title">{selectionLabel}</Label>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <SmallIconButton
+ aria-label={`Add ${selectionLabel.toLowerCase()}`}
+ icon={<PlusIcon />}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" sideOffset={4}>
+ {selectionParameters.map((parameter, index) => (
+ <Fragment key={parameter.key}>
+ {index > 0 && <DropdownMenuSeparator />}
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{parameter.label}</DropdownMenuLabel>
+ {getSelectionMenuItems(parameter)}
+ </DropdownMenuGroup>
+ </Fragment>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </Flex>
+ <CssValueListArrowFocus>
+ {selectionParameters.map((parameter) => {
+ const { current, option } = getSelected(parameter);
+ const selection = parameter.config.selection;
+ if (
+ current === undefined ||
+ option === undefined ||
+ selection === undefined
+ ) {
+ return null;
+ }
+ const empty = parameter.config.options.find(
+ ({ value }) => value === selection.emptyOption
+ );
+ const { fieldList, paths } = getOptionPaths(current, option);
+ const baseline = selection.baseline;
+ const canDelete = selectionItemCount > 1;
+ return (
+ <Grid key={parameter.key} gap={1}>
+ {baseline !== undefined &&
+ current[baseline.key] !== false && (
+ <QuerySelectionListItem
+ id={`${parameter.key}:${baseline.key}`}
+ index={selectionItemIndex++}
+ label={baseline.label}
+ canDelete={canDelete}
+ onDelete={() =>
+ onChange(parameter.key, {
+ ...current,
+ [baseline.key]: false,
+ })
+ }
+ />
+ )}
+ {option.value !== selection.emptyOption &&
+ (fieldList === undefined ? (
+ <QuerySelectionListItem
+ id={`${parameter.key}:${option.value}`}
+ index={selectionItemIndex++}
+ label={option.label}
+ canDelete={canDelete}
+ onDelete={() =>
+ empty !== undefined &&
+ onChange(
+ parameter.key,
+ withCurrentBaseline(
+ parameter,
+ current,
+ structuredClone(empty.defaultValue)
+ )
+ )
+ }
+ settings={
+ option.fields.some((field) => field.type === "number")
+ ? renderNumberFields(parameter, current, option)
+ : undefined
+ }
+ />
+ ) : (
+ paths.map((path, index) => {
+ const selectedField = getField(fields, path);
+ return (
+ <QuerySelectionListItem
+ key={`${getQueryFieldKey(path)}:${index}`}
+ id={`${parameter.key}:${getQueryFieldKey(path)}:${index}`}
+ index={selectionItemIndex++}
+ label={selectedField.label}
+ canDelete={canDelete}
+ onDelete={() => {
+ const nextPaths = paths.filter(
+ (_, position) => position !== index
+ );
+ onChange(
+ parameter.key,
+ nextPaths.length === 0 && empty !== undefined
+ ? withCurrentBaseline(
+ parameter,
+ current,
+ structuredClone(empty.defaultValue)
+ )
+ : {
+ ...current,
+ [fieldList.key]: nextPaths,
+ }
+ );
+ }}
+ />
+ );
+ })
+ ))}
+ </Grid>
+ );
+ })}
+ </CssValueListArrowFocus>
+ </Grid>
+ )}
+ {regularParameters.map((parameter) => {
+ const { current, option } = getSelected(parameter);
+ if (current === undefined || option === undefined) {
+ return null;
+ }
+ return (
+ <Grid
+ key={parameter.key}
+ gap={1}
+ css={{ paddingInline: sectionPaddingInline }}
+ >
+ <Label>{parameter.label}</Label>
+ <Select<(typeof parameter.config.options)[number]>
+ aria-label={parameter.label}
+ options={parameter.config.options}
+ getLabel={(item) => item.label}
+ getValue={(item) => item.value}
+ value={option}
+ onChange={(item) =>
+ onChange(parameter.key, structuredClone(item.defaultValue))
+ }
+ />
+ {renderRegularFields(parameter, current, option)}
+ </Grid>
+ );
+ })}
+ </>
+ );
+};
+
+const defaultExpressionEditor = ({
+ "aria-label": ariaLabel,
+ value,
+ onChange,
+ input,
+ min,
+ max,
+ integer,
+}: QueryValueEditorProps) => (
+ <InputField
+ aria-label={ariaLabel}
+ type={input === "number" ? "number" : "text"}
+ min={input === "number" ? min : undefined}
+ max={input === "number" ? max : undefined}
+ step={input === "number" ? (integer === true ? 1 : "any") : undefined}
+ value={value}
+ onChange={(event) => onChange(event.target.value)}
+ />
+);
+
+const defaultSourceEditor = ({
+ "aria-label": ariaLabel,
+ value,
+ onChange,
+ onChangeComplete,
+}: QuerySourceEditorProps) => (
+ <TextArea
+ aria-label={ariaLabel}
+ value={value}
+ variant="mono"
+ onChange={onChange}
+ onBlur={(event) => onChangeComplete(event.currentTarget.value)}
+ />
+);
+
+export const StructuredQueryBuilder = <
+ FieldType extends string,
+ Operator extends string,
+ Query extends Record<string, unknown>,
+>({
+ value,
+ capabilities,
+ editors,
+ renderSource,
+ sectionPaddingInline,
+ onChange,
+}: BuilderProps<FieldType, Operator, Query>) => {
+ const sourceCodec = useMemo(
+ () => createQuerySourceCodec<FieldType, Operator, Query>(capabilities),
+ [capabilities]
+ );
+ const formatSource = sourceCodec.format;
+ const formattedSource = useMemo(() => {
+ try {
+ return formatSource(value);
+ } catch {
+ return;
+ }
+ }, [formatSource, value]);
+ const [source, setSource] = useState(formattedSource ?? "");
+ const [sourceError, setSourceError] = useState<string>();
+ const sourceInvalidRef = useRef(false);
+
+ useEffect(() => {
+ if (formattedSource === undefined || sourceInvalidRef.current) {
+ return;
+ }
+ setSource(formattedSource);
+ }, [formattedSource]);
+
+ const commit = (next: Query) => {
+ try {
+ setSource(sourceCodec.format(next));
+ setSourceError(undefined);
+ sourceInvalidRef.current = false;
+ } catch {
+ setSourceError("Complete every query field.");
+ }
+ onChange(next);
+ };
+ const commitSource = (nextSource: string) => {
+ setSource(nextSource);
+ const parsed = sourceCodec.parse(nextSource);
+ if (parsed.success) {
+ setSourceError(undefined);
+ sourceInvalidRef.current = false;
+ onChange(parsed.value);
+ } else {
+ setSourceError(parsed.message);
+ sourceInvalidRef.current = true;
+ }
+ };
+ const renderExpressionEditor = editors?.expression ?? defaultExpressionEditor;
+ const renderSourceEditor = editors?.source ?? defaultSourceEditor;
+ const sourceEditor = (
+ <>
+ {renderSourceEditor({
+ "aria-label": "Query",
+ value: source,
+ onChange: setSource,
+ onChangeComplete: commitSource,
+ })}
+ {sourceError !== undefined && (
+ <Text color="destructive">{sourceError}</Text>
+ )}
+ </>
+ );
+ return (
+ <Grid css={{ gap: theme.spacing[7] }}>
+ {capabilities.description === undefined ? null : (
+ <Text color="subtle" css={{ paddingInline: sectionPaddingInline }}>
+ {capabilities.description}
+ </Text>
+ )}
+ {capabilities.source.controls.map((control) => {
+ if (control.type === "variant") {
+ const selectionLabel = control.config.selection?.label;
+ const parameters = capabilities.source.controls.filter(
+ (candidate): candidate is QueryVariantControl =>
+ candidate.type === "variant" &&
+ (selectionLabel === undefined
+ ? candidate.key === control.key
+ : candidate.config.selection?.label === selectionLabel)
+ );
+ if (parameters[0] !== control) {
+ return null;
+ }
+ return (
+ <QueryParameters
+ key={control.key}
+ parameters={parameters}
+ fields={capabilities.fields}
+ value={value}
+ sectionPaddingInline={sectionPaddingInline}
+ onChange={(key, parameterValue) =>
+ commit({ ...value, [key]: parameterValue } as Query)
+ }
+ />
+ );
+ }
+ if (control.type === "filter") {
+ const current = value[control.key] ?? control.defaultValue;
+ const where =
+ "field" in (current as QueryWhere<string[], Operator>)
+ ? control.combinators[0] === "any"
+ ? { any: [current as QueryWhere<string[], Operator>] }
+ : { all: [current as QueryWhere<string[], Operator>] }
+ : (current as QueryGroup<string[], Operator>);
+ const metrics = getQueryWhereMetrics(where);
+ return (
+ <Group
+ key={control.key}
+ capabilities={capabilities}
+ filter={control}
+ renderExpressionEditor={renderExpressionEditor}
+ sectionPaddingInline={sectionPaddingInline}
+ group={where}
+ conditionCount={metrics.conditions}
+ depth={1}
+ root={true}
+ onChange={(next) =>
+ commit({ ...value, [control.key]: next } as Query)
+ }
+ />
+ );
+ }
+ if (control.type === "sort") {
+ return (
+ <Sorting
+ key={control.key}
+ capabilities={capabilities}
+ control={control}
+ sectionPaddingInline={sectionPaddingInline}
+ sort={
+ (value[control.key] ?? control.defaultValue) as QuerySort<
+ string[]
+ >[]
+ }
+ onChange={(next) =>
+ commit({ ...value, [control.key]: next } as Query)
+ }
+ />
+ );
+ }
+ const controlIndex = capabilities.source.controls.indexOf(control);
+ let expressionRunStart = controlIndex;
+ while (
+ capabilities.source.controls[expressionRunStart - 1]?.type ===
+ "expression"
+ ) {
+ expressionRunStart -= 1;
+ }
+ if ((controlIndex - expressionRunStart) % 2 === 1) {
+ return null;
+ }
+ const expressionControls = capabilities.source.controls
+ .slice(controlIndex, controlIndex + 2)
+ .filter(
+ (candidate): candidate is QueryExpressionControl =>
+ candidate.type === "expression"
+ );
+ if (expressionControls[0] !== control) {
+ return null;
+ }
+ return (
+ <Grid
+ key={control.key}
+ gap={2}
+ css={{
+ paddingInline: sectionPaddingInline,
+ gridTemplateColumns: `repeat(${expressionControls.length}, 1fr)`,
+ }}
+ >
+ {expressionControls.map((item) => (
+ <Grid key={item.key} gap={1}>
+ <Label>{item.label}</Label>
+ {renderExpressionEditor({
+ "aria-label": item.label,
+ value: String(value[item.key] ?? item.defaultValue),
+ role: "value",
+ input: item.input,
+ min: item.min,
+ max: item.max,
+ exclusiveMin: item.exclusiveMin,
+ exclusiveMax: item.exclusiveMax,
+ integer: item.integer,
+ onChange: (next) =>
+ commit({ ...value, [item.key]: next } as Query),
+ })}
+ </Grid>
+ ))}
+ </Grid>
+ );
+ })}
+ {renderSource === undefined ? (
+ <Grid gap={1} css={{ paddingInline: sectionPaddingInline }}>
+ <Label>Query</Label>
+ {sourceEditor}
+ </Grid>
+ ) : (
+ renderSource(sourceEditor)
+ )}
+ </Grid>
+ );
+};
diff --git a/packages/query-builder-react/src/test-fixtures.ts b/packages/query-builder-react/src/test-fixtures.ts
new file mode 100644
index 0000000000..39e0a15794
--- /dev/null
+++ b/packages/query-builder-react/src/test-fixtures.ts
@@ -0,0 +1,140 @@
+import type { QueryDefinition } from "@webstudio-is/query-builder";
+
+export const genericQueryCapabilities = {
+ version: 1,
+ fields: [
+ { path: ["title"], label: "Title", types: ["string"] },
+ { path: ["publishedAt"], label: "Published at", types: ["date"] },
+ ],
+ operators: [
+ {
+ value: "eq",
+ label: "Equals",
+ types: ["string", "date"],
+ input: { control: "expression", defaultValue: '""' },
+ },
+ {
+ value: "after",
+ label: "After",
+ types: ["date"],
+ input: { control: "expression", defaultValue: '"2026-01-01"' },
+ },
+ ],
+ source: {
+ fieldPathSchema: {
+ type: "array",
+ items: { type: "string" },
+ minItems: 1,
+ },
+ controls: [
+ {
+ type: "filter",
+ key: "where",
+ label: "Filters",
+ defaultValue: { all: [] },
+ combinators: ["all", "any"],
+ limits: { conditions: 8, depth: 3 },
+ defaultCondition: { field: ["title"], operator: "eq" },
+ },
+ {
+ type: "sort",
+ key: "sort",
+ label: "Sort",
+ defaultValue: [],
+ defaultItem: { field: ["publishedAt"], direction: "desc" },
+ directions: [
+ { value: "asc", label: "Ascending" },
+ { value: "desc", label: "Descending" },
+ ],
+ max: 2,
+ },
+ {
+ type: "expression",
+ key: "limit",
+ label: "Limit",
+ defaultValue: "10",
+ input: "number",
+ },
+ {
+ type: "expression",
+ key: "offset",
+ label: "Offset",
+ defaultValue: "0",
+ input: "number",
+ },
+ {
+ type: "variant",
+ key: "selection",
+ label: "Selection",
+ defaultValue: { mode: "summary", includeMetadata: true },
+ schema: {
+ type: "object",
+ properties: {
+ mode: { enum: ["summary", "full", "fields"] },
+ includeMetadata: { type: "boolean" },
+ fields: {
+ type: "array",
+ items: {
+ type: "array",
+ items: { type: "string" },
+ minItems: 1,
+ },
+ },
+ },
+ required: ["mode", "includeMetadata"],
+ additionalProperties: false,
+ },
+ config: {
+ discriminator: "mode",
+ options: [
+ {
+ value: "summary",
+ label: "Summary",
+ defaultValue: { mode: "summary", includeMetadata: true },
+ fields: [],
+ },
+ {
+ value: "full",
+ label: "Full",
+ defaultValue: { mode: "full", includeMetadata: true },
+ fields: [],
+ },
+ {
+ value: "fields",
+ label: "Fields",
+ defaultValue: {
+ mode: "fields",
+ includeMetadata: true,
+ fields: [],
+ },
+ fields: [
+ {
+ key: "fields",
+ label: "Fields",
+ type: "field-list",
+ max: 2,
+ },
+ ],
+ },
+ ],
+ },
+ },
+ ],
+ },
+} as const satisfies QueryDefinition<"string" | "date", "eq" | "after">;
+
+export type GenericQuery = {
+ where: import("@webstudio-is/query-builder").QueryWhere<
+ string[],
+ "eq" | "after"
+ >;
+ sort: import("@webstudio-is/query-builder").QuerySort<string[]>[];
+ limit: string;
+ offset: string;
+ selection: {
+ mode: "summary" | "full" | "fields";
+ includeMetadata: boolean;
+ fields?: string[][];
+ maxBytes?: number;
+ };
+};
diff --git a/packages/query-builder-react/tsconfig.json b/packages/query-builder-react/tsconfig.json
new file mode 100644
index 0000000000..4af22fa384
--- /dev/null
+++ b/packages/query-builder-react/tsconfig.json
@@ -0,0 +1,4 @@
+{
+ "extends": "@webstudio-is/tsconfig/base.json",
+ "include": ["src/**/*.ts", "src/**/*.tsx", "../../@types/**/*.d.ts"]
+}
diff --git a/packages/query-builder-react/vitest.config.ts b/packages/query-builder-react/vitest.config.ts
new file mode 100644
index 0000000000..45b04195bd
--- /dev/null
+++ b/packages/query-builder-react/vitest.config.ts
@@ -0,0 +1,10 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ resolve: {
+ conditions: ["webstudio", "browser", "development|production"],
+ },
+ test: {
+ setupFiles: ["@webstudio-is/design-system/test-setup"],
+ },
+});
diff --git a/packages/query-builder/package.json b/packages/query-builder/package.json
new file mode 100644
index 0000000000..4b01f60942
--- /dev/null
+++ b/packages/query-builder/package.json
@@ -0,0 +1,40 @@
+{
+ "name": "@webstudio-is/query-builder",
+ "version": "0.0.0-webstudio-version",
+ "description": "Framework-independent structured query authoring core",
+ "author": "Webstudio <[email protected]>",
+ "homepage": "https://webstudio.is",
+ "license": "AGPL-3.0-or-later",
+ "type": "module",
+ "sideEffects": false,
+ "scripts": {
+ "build": "rm -rf lib && esbuild src/index.ts src/runtime.ts --outdir=lib --bundle --format=esm --packages=external",
+ "dts": "tsc --project tsconfig.dts.json",
+ "test": "vitest run",
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@webstudio-is/expression": "workspace:*",
+ "zod": "^4.4.3"
+ },
+ "devDependencies": {
+ "@webstudio-is/tsconfig": "workspace:*",
+ "vitest": "^3.1.2"
+ },
+ "exports": {
+ ".": {
+ "webstudio": "./src/index.ts",
+ "types": "./lib/types/index.d.ts",
+ "import": "./lib/index.js"
+ },
+ "./runtime": {
+ "webstudio": "./src/runtime.ts",
+ "types": "./lib/types/runtime.d.ts",
+ "import": "./lib/runtime.js"
+ }
+ },
+ "files": [
+ "lib/**/*",
+ "!*.test.*"
+ ]
+}
diff --git a/packages/query-builder/src/capabilities.test.ts b/packages/query-builder/src/capabilities.test.ts
new file mode 100644
index 0000000000..f9852d2b6d
--- /dev/null
+++ b/packages/query-builder/src/capabilities.test.ts
@@ -0,0 +1,309 @@
+import { describe, expect, test } from "vitest";
+import { getCompatibleQueryOperators } from "./query-utils";
+import { queryDefinition } from "./schema";
+
+const capabilities = {
+ version: 1,
+ fields: [{ path: ["title"], label: "Title", types: ["string"] }],
+ operators: [
+ {
+ value: "eq",
+ label: "Equals",
+ types: ["string", "number"],
+ input: { control: "expression", defaultValue: '""' },
+ },
+ {
+ value: "contains",
+ label: "Contains",
+ types: ["string"],
+ input: { control: "expression", defaultValue: '""' },
+ },
+ {
+ value: "gt",
+ label: "Greater than",
+ types: ["number"],
+ input: { control: "expression", defaultValue: "0" },
+ },
+ ],
+ source: {
+ fieldPathSchema: {
+ type: "array",
+ items: { type: "string" },
+ minItems: 1,
+ },
+ controls: [
+ {
+ type: "filter",
+ key: "where",
+ label: "Filters",
+ defaultValue: { all: [] },
+ combinators: ["all", "any"],
+ limits: { conditions: 20, depth: 4 },
+ defaultCondition: { field: ["title"], operator: "eq" },
+ },
+ {
+ type: "sort",
+ key: "sort",
+ label: "Sort",
+ defaultValue: [],
+ defaultItem: { field: ["title"], direction: "asc" },
+ directions: [
+ { value: "asc", label: "Ascending" },
+ { value: "desc", label: "Descending" },
+ ],
+ max: 3,
+ },
+ {
+ type: "expression",
+ key: "pageSize",
+ label: "Page size",
+ defaultValue: "20",
+ input: "number",
+ },
+ ],
+ },
+} as const;
+
+describe("query capabilities", () => {
+ test("validates a provider-neutral capability document", () => {
+ expect(queryDefinition.parse(capabilities)).toEqual(capabilities);
+ });
+
+ test("rejects duplicate fields, operators, and combinators", () => {
+ expect(
+ queryDefinition.safeParse({
+ ...capabilities,
+ fields: [...capabilities.fields, capabilities.fields[0]],
+ operators: [...capabilities.operators, capabilities.operators[0]],
+ source: {
+ ...capabilities.source,
+ controls: capabilities.source.controls.map((control) =>
+ control.type === "filter"
+ ? { ...control, combinators: ["all", "all"] }
+ : control
+ ),
+ },
+ }).success
+ ).toBe(false);
+ });
+
+ test("accepts definitions without sorting", () => {
+ expect(
+ queryDefinition.safeParse({
+ ...capabilities,
+ source: {
+ ...capabilities.source,
+ controls: capabilities.source.controls.filter(
+ (control) => control.type !== "sort"
+ ),
+ },
+ }).success
+ ).toBe(true);
+ });
+
+ test("rejects inconsistent sort direction capabilities", () => {
+ const withSort = (change: Record<string, unknown>) => ({
+ ...capabilities,
+ source: {
+ ...capabilities.source,
+ controls: capabilities.source.controls.map((control) =>
+ control.type === "sort" ? { ...control, ...change } : control
+ ),
+ },
+ });
+
+ expect(
+ queryDefinition.safeParse(
+ withSort({
+ directions: [capabilities.source.controls[1].directions[1]],
+ })
+ ).success
+ ).toBe(false);
+ expect(
+ queryDefinition.safeParse(
+ withSort({
+ directions: [
+ capabilities.source.controls[1].directions[0],
+ capabilities.source.controls[1].directions[0],
+ ],
+ })
+ ).success
+ ).toBe(false);
+ });
+
+ test("rejects defaults that the declared fields and operators cannot use", () => {
+ expect(
+ queryDefinition.safeParse({
+ ...capabilities,
+ source: {
+ ...capabilities.source,
+ controls: capabilities.source.controls.map((control) =>
+ control.type === "filter"
+ ? {
+ ...control,
+ defaultCondition: {
+ field: ["missing"],
+ operator: "missing",
+ },
+ }
+ : control
+ ),
+ },
+ }).success
+ ).toBe(false);
+ });
+
+ test("rejects field-specific operators that are unavailable", () => {
+ expect(
+ queryDefinition.safeParse({
+ ...capabilities,
+ fields: [{ ...capabilities.fields[0], operators: ["missing"] }],
+ }).success
+ ).toBe(false);
+ });
+
+ test("rejects a default filter operator unsupported by its field", () => {
+ expect(
+ queryDefinition.safeParse({
+ ...capabilities,
+ fields: [{ ...capabilities.fields[0], operators: ["contains"] }],
+ }).success
+ ).toBe(false);
+ });
+
+ test("rejects defaults that are not valid expressions", () => {
+ expect(
+ queryDefinition.safeParse({
+ ...capabilities,
+ operators: [
+ {
+ ...capabilities.operators[0],
+ input: { control: "expression", defaultValue: "(" },
+ },
+ ...capabilities.operators.slice(1),
+ ],
+ source: {
+ ...capabilities.source,
+ controls: capabilities.source.controls.map((control) =>
+ control.type === "expression"
+ ? { ...control, defaultValue: "(" }
+ : control
+ ),
+ },
+ }).success
+ ).toBe(false);
+ });
+
+ test("rejects parameter controls that disagree with their JSON Schema", () => {
+ expect(
+ queryDefinition.safeParse({
+ ...capabilities,
+ source: {
+ ...capabilities.source,
+ controls: [
+ {
+ type: "variant",
+ key: "selection",
+ label: "Selection",
+ defaultValue: { mode: "invalid" },
+ schema: {
+ type: "object",
+ properties: { mode: { const: "summary" } },
+ required: ["mode"],
+ additionalProperties: false,
+ },
+ config: {
+ discriminator: "mode",
+ options: [
+ {
+ value: "summary",
+ label: "Summary",
+ defaultValue: { mode: "invalid" },
+ fields: [],
+ },
+ ],
+ },
+ },
+ ],
+ },
+ }).success
+ ).toBe(false);
+ });
+
+ test("rejects selection controls without their declared empty option", () => {
+ expect(
+ queryDefinition.safeParse({
+ ...capabilities,
+ source: {
+ ...capabilities.source,
+ controls: [
+ {
+ type: "variant",
+ key: "selection",
+ label: "Selection",
+ defaultValue: { mode: "summary" },
+ schema: true,
+ config: {
+ discriminator: "mode",
+ selection: { label: "Select", emptyOption: "missing" },
+ options: [
+ {
+ value: "summary",
+ label: "Summary",
+ defaultValue: { mode: "summary" },
+ fields: [],
+ },
+ ],
+ },
+ },
+ ],
+ },
+ }).success
+ ).toBe(false);
+ });
+
+ test("rejects selection baselines without a boolean option value", () => {
+ expect(
+ queryDefinition.safeParse({
+ ...capabilities,
+ source: {
+ ...capabilities.source,
+ controls: [
+ {
+ type: "variant",
+ key: "selection",
+ label: "Selection",
+ defaultValue: { mode: "summary" },
+ schema: true,
+ config: {
+ discriminator: "mode",
+ selection: {
+ label: "Output",
+ emptyOption: "summary",
+ baseline: { key: "includeMetadata", label: "Metadata" },
+ },
+ options: [
+ {
+ value: "summary",
+ label: "Summary",
+ defaultValue: { mode: "summary" },
+ fields: [],
+ },
+ ],
+ },
+ },
+ ],
+ },
+ }).success
+ ).toBe(false);
+ });
+
+ test("selects operators compatible with any observed field type", () => {
+ expect(
+ getCompatibleQueryOperators(
+ ["string", "number"],
+ capabilities.operators
+ ).map(({ value }) => value)
+ ).toEqual(["eq", "contains", "gt"]);
+ });
+});
diff --git a/packages/query-builder/src/index.ts b/packages/query-builder/src/index.ts
new file mode 100644
index 0000000000..f589ee4ffd
--- /dev/null
+++ b/packages/query-builder/src/index.ts
@@ -0,0 +1,5 @@
+export * from "./query-utils";
+export * from "./schema";
+export * from "./source";
+export * from "./openapi";
+export type * from "./types";
diff --git a/packages/query-builder/src/openapi.test.ts b/packages/query-builder/src/openapi.test.ts
new file mode 100644
index 0000000000..25cbedba0c
--- /dev/null
+++ b/packages/query-builder/src/openapi.test.ts
@@ -0,0 +1,715 @@
+import { describe, expect, test } from "vitest";
+import {
+ getOpenApiQueryDefinition,
+ loadOpenApiQueryDefinition,
+} from "./openapi";
+import { createQuerySourceCodec } from "./source";
+
+describe("OpenAPI query configuration", () => {
+ test("loads an external JSON Schema and resolves its local references", async () => {
+ const loaded: string[] = [];
+ const definition = await loadOpenApiQueryDefinition({
+ documentUrl: "https://api.example.com/rest/assets/openapi.json",
+ document: {
+ paths: {
+ "/assets/query": {
+ post: {
+ operationId: "queryAssets",
+ requestBody: {
+ content: {
+ "application/json": {
+ schema: { $ref: "./query-schema.json" },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ operationId: "queryAssets",
+ loadReference: async (url) => {
+ loaded.push(url);
+ return {
+ type: "object",
+ properties: {
+ query: { $ref: "#/$defs/Query" },
+ },
+ required: ["query"],
+ $defs: {
+ Query: {
+ type: "object",
+ description: "Only indexed fields appear in autocomplete.",
+ properties: {
+ limit: { type: "integer", default: 20, minimum: 1 },
+ },
+ },
+ },
+ };
+ },
+ });
+
+ expect(loaded).toEqual([
+ "https://api.example.com/rest/assets/query-schema.json",
+ ]);
+ expect(definition.description).toBe(
+ "Only indexed fields appear in autocomplete."
+ );
+ expect(definition.source.controls).toEqual([
+ expect.objectContaining({
+ key: "limit",
+ defaultValue: "20",
+ min: 1,
+ }),
+ ]);
+ });
+
+ test("resolves only own properties in local references", () => {
+ expect(() =>
+ getOpenApiQueryDefinition({
+ document: {
+ paths: {
+ "/search": {
+ get: {
+ operationId: "search",
+ parameters: [{ $ref: "#/toString" }],
+ },
+ },
+ },
+ },
+ operationId: "search",
+ })
+ ).toThrow("OpenAPI reference #/toString is missing");
+ });
+
+ test("resolves URI-encoded and array JSON Pointer segments", () => {
+ const definition = getOpenApiQueryDefinition({
+ document: {
+ paths: {
+ "/search": {
+ get: {
+ operationId: "search",
+ parameters: [
+ { $ref: "#%2Fcomponents%2Fparameters%2F0" },
+ { $ref: "#/components/by~1name/limit" },
+ ],
+ },
+ },
+ },
+ components: {
+ parameters: [
+ {
+ name: "offset",
+ in: "query",
+ schema: { type: "integer", default: 0 },
+ },
+ ],
+ "by/name": {
+ limit: {
+ name: "limit",
+ in: "query",
+ schema: { type: "integer", default: 20 },
+ },
+ },
+ },
+ },
+ operationId: "search",
+ });
+
+ expect(definition.source.controls.map(({ key }) => key)).toEqual([
+ "offset",
+ "limit",
+ ]);
+ });
+
+ test("rejects circular schema references without overflowing the stack", () => {
+ expect(() =>
+ getOpenApiQueryDefinition({
+ document: {
+ paths: {
+ "/search": {
+ get: {
+ operationId: "search",
+ parameters: [
+ {
+ name: "cursor",
+ in: "query",
+ schema: { $ref: "#/components/schemas/Cursor" },
+ },
+ ],
+ },
+ },
+ },
+ components: {
+ schemas: {
+ Cursor: { $ref: "#/components/schemas/Cursor" },
+ },
+ },
+ },
+ operationId: "search",
+ })
+ ).toThrow("Circular OpenAPI query schema references are unsupported");
+ });
+
+ test("derives differently named parameters without vendor metadata", () => {
+ const definition = getOpenApiQueryDefinition({
+ document: {
+ openapi: "3.1.1",
+ paths: {
+ "/articles": {
+ get: {
+ operationId: "searchArticles",
+ parameters: [
+ {
+ name: "perPage",
+ in: "query",
+ schema: {
+ type: "integer",
+ title: "Items per page",
+ default: 25,
+ minimum: 1,
+ },
+ },
+ {
+ $ref: "#/components/parameters/Cursor",
+ },
+ ],
+ },
+ },
+ },
+ components: {
+ parameters: {
+ Cursor: {
+ name: "cursor",
+ in: "query",
+ schema: { type: "string", default: "" },
+ },
+ },
+ },
+ },
+ operationId: "searchArticles",
+ });
+
+ expect(definition.source.controls).toEqual([
+ {
+ type: "expression",
+ key: "perPage",
+ label: "Items per page",
+ defaultValue: "25",
+ input: "number",
+ min: 1,
+ integer: true,
+ },
+ {
+ type: "expression",
+ key: "cursor",
+ label: "Cursor",
+ defaultValue: '""',
+ input: "expression",
+ },
+ ]);
+ });
+
+ test("inherits path parameters and lets operation parameters override them", () => {
+ const definition = getOpenApiQueryDefinition({
+ document: {
+ paths: {
+ "/articles": {
+ parameters: [
+ {
+ name: "limit",
+ in: "query",
+ schema: { type: "integer", default: 10 },
+ },
+ {
+ name: "locale",
+ in: "header",
+ schema: { type: "string", default: "en" },
+ },
+ ],
+ get: {
+ operationId: "searchArticles",
+ parameters: [
+ {
+ name: "limit",
+ in: "query",
+ schema: {
+ type: "integer",
+ default: 25,
+ exclusiveMinimum: 0,
+ },
+ },
+ ],
+ },
+ },
+ },
+ },
+ operationId: "searchArticles",
+ });
+
+ expect(definition.source.controls).toMatchObject([
+ { key: "limit", defaultValue: "25", min: 1 },
+ { key: "locale", defaultValue: '"en"' },
+ ]);
+ });
+
+ test("preserves exclusive numeric bounds and normalizes integer bounds", () => {
+ const definition = getOpenApiQueryDefinition({
+ document: {
+ paths: {
+ "/search": {
+ get: {
+ operationId: "search",
+ parameters: [
+ {
+ name: "score",
+ in: "query",
+ schema: {
+ type: "number",
+ minimum: 0,
+ exclusiveMinimum: 0.5,
+ maximum: 2,
+ exclusiveMaximum: 1.5,
+ },
+ },
+ {
+ name: "page",
+ in: "query",
+ schema: {
+ type: "integer",
+ minimum: 0,
+ exclusiveMinimum: 0.5,
+ maximum: 4,
+ exclusiveMaximum: 3.5,
+ },
+ },
+ {
+ name: "ratio",
+ in: "query",
+ schema: {
+ type: "number",
+ minimum: 1,
+ exclusiveMinimum: 0.5,
+ maximum: 4,
+ exclusiveMaximum: 5,
+ },
+ },
+ {
+ name: "legacyScore",
+ in: "query",
+ schema: {
+ type: "number",
+ minimum: 0,
+ exclusiveMinimum: true,
+ maximum: 2,
+ exclusiveMaximum: true,
+ },
+ },
+ {
+ name: "legacyPage",
+ in: "query",
+ schema: {
+ type: "integer",
+ minimum: 0,
+ exclusiveMinimum: true,
+ maximum: 4,
+ exclusiveMaximum: true,
+ },
+ },
+ ],
+ },
+ },
+ },
+ },
+ operationId: "search",
+ });
+
+ expect(definition.source.controls).toEqual([
+ {
+ type: "expression",
+ key: "score",
+ label: "Score",
+ defaultValue: "1",
+ input: "number",
+ min: 0.5,
+ max: 1.5,
+ exclusiveMin: true,
+ exclusiveMax: true,
+ },
+ {
+ type: "expression",
+ key: "page",
+ label: "Page",
+ defaultValue: "1",
+ input: "number",
+ min: 1,
+ max: 3,
+ integer: true,
+ },
+ {
+ type: "expression",
+ key: "ratio",
+ label: "Ratio",
+ defaultValue: "1",
+ input: "number",
+ min: 1,
+ max: 4,
+ },
+ {
+ type: "expression",
+ key: "legacyScore",
+ label: "Legacy Score",
+ defaultValue: "1",
+ input: "number",
+ min: 0,
+ max: 2,
+ exclusiveMin: true,
+ exclusiveMax: true,
+ },
+ {
+ type: "expression",
+ key: "legacyPage",
+ label: "Legacy Page",
+ defaultValue: "1",
+ input: "number",
+ min: 1,
+ max: 3,
+ integer: true,
+ },
+ ]);
+ });
+
+ test("does not invent a sort limit when OpenAPI omits maxItems", () => {
+ const definition = getOpenApiQueryDefinition({
+ document: {
+ paths: {
+ "/search": {
+ post: {
+ operationId: "search",
+ requestBody: {
+ content: {
+ "application/json": {
+ schema: {
+ type: "object",
+ properties: {
+ query: {
+ type: "object",
+ properties: {
+ sort: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ field: {
+ type: "array",
+ oneOf: [{ const: ["title"] }],
+ },
+ direction: {
+ oneOf: [
+ {
+ const: "newest",
+ title: "Newest first",
+ },
+ {
+ const: "oldest",
+ title: "Oldest first",
+ },
+ ],
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ required: ["query"],
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ operationId: "search",
+ });
+ expect(definition.source.controls).toEqual([
+ {
+ type: "sort",
+ key: "sort",
+ label: "Sort",
+ defaultValue: [],
+ defaultItem: { field: ["title"], direction: "newest" },
+ directions: [
+ { value: "newest", label: "Newest first" },
+ { value: "oldest", label: "Oldest first" },
+ ],
+ max: undefined,
+ },
+ ]);
+ const sorts = Array.from({ length: 101 }, () => ({
+ field: ["title"],
+ direction: "newest",
+ }));
+ expect(
+ createQuerySourceCodec(definition).parse(
+ `({ sort: ${JSON.stringify(sorts)} })`
+ )
+ ).toMatchObject({ success: true });
+ });
+
+ test("unwraps a single required object from a referenced request body", () => {
+ const definition = getOpenApiQueryDefinition({
+ document: {
+ paths: {
+ "/search": {
+ post: {
+ operationId: "search",
+ requestBody: {
+ content: {
+ "application/json": {
+ schema: { $ref: "#/components/schemas/SearchRequest" },
+ },
+ },
+ },
+ },
+ },
+ },
+ components: {
+ schemas: {
+ SearchRequest: {
+ type: "object",
+ properties: {
+ search: {
+ type: "object",
+ properties: {
+ page: { type: "integer", default: 1, minimum: 1 },
+ },
+ },
+ traceId: { type: "string" },
+ },
+ required: ["search"],
+ },
+ },
+ },
+ },
+ operationId: "search",
+ });
+
+ expect(definition.source.controls).toEqual([
+ {
+ type: "expression",
+ key: "page",
+ label: "Page",
+ defaultValue: "1",
+ input: "number",
+ min: 1,
+ integer: true,
+ },
+ ]);
+ });
+
+ test("does not omit required siblings of an object-valued request field", () => {
+ expect(() =>
+ getOpenApiQueryDefinition({
+ document: {
+ paths: {
+ "/search": {
+ post: {
+ operationId: "search",
+ requestBody: {
+ content: {
+ "application/json": {
+ schema: {
+ type: "object",
+ properties: {
+ search: {
+ type: "object",
+ properties: {
+ page: { type: "integer", default: 1 },
+ },
+ },
+ locale: { type: "string" },
+ },
+ required: ["search", "locale"],
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ operationId: "search",
+ })
+ ).toThrow();
+ });
+
+ test("supports array-valued field choices in variant defaults", () => {
+ const defaultValue = {
+ mode: "fields",
+ fields: [["url"], ["width"]],
+ };
+ const definition = getOpenApiQueryDefinition({
+ document: {
+ paths: {
+ "/assets": {
+ post: {
+ operationId: "queryAssets",
+ requestBody: {
+ content: {
+ "application/json": {
+ schema: {
+ type: "object",
+ properties: {
+ query: {
+ type: "object",
+ properties: {
+ output: {
+ title: "Projection",
+ default: defaultValue,
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ mode: { const: "base" },
+ },
+ required: ["mode"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ mode: { const: "fields" },
+ fields: {
+ type: "array",
+ items: {
+ type: "array",
+ minItems: 1,
+ items: { type: "string" },
+ oneOf: [
+ { const: ["url"], title: "URL" },
+ {
+ const: ["width"],
+ title: "Width",
+ },
+ ],
+ },
+ },
+ },
+ required: ["mode", "fields"],
+ additionalProperties: false,
+ },
+ ],
+ },
+ },
+ required: ["output"],
+ },
+ },
+ required: ["query"],
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ operationId: "queryAssets",
+ });
+
+ const codec = createQuerySourceCodec(definition);
+ expect(definition.source.controls).toMatchObject([
+ {
+ label: "Projection",
+ config: { selection: { label: "Projection" } },
+ },
+ ]);
+ const source = codec.format({ output: defaultValue });
+ expect(codec.parse(source)).toEqual({
+ success: true,
+ value: { output: defaultValue },
+ });
+ expect(
+ codec.parse(`({ output: { mode: "fields", fields: [["height"]] } })`)
+ .success
+ ).toBe(false);
+ });
+
+ test("renders ordinary discriminated unions as one variant instead of output selection", () => {
+ const definition = getOpenApiQueryDefinition({
+ document: {
+ paths: {
+ "/search": {
+ post: {
+ operationId: "search",
+ requestBody: {
+ content: {
+ "application/json": {
+ schema: {
+ type: "object",
+ properties: {
+ strategy: {
+ title: "Search strategy",
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ type: { const: "exact", title: "Exact" },
+ boost: {
+ $ref: "#/components/schemas/Boost",
+ },
+ },
+ required: ["type"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: { const: "fuzzy", title: "Fuzzy" },
+ distance: { type: "integer", default: 2 },
+ },
+ required: ["type", "distance"],
+ },
+ ],
+ },
+ },
+ required: ["strategy"],
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ components: {
+ schemas: {
+ Boost: { type: "number", default: 1 },
+ },
+ },
+ },
+ operationId: "search",
+ });
+
+ expect(definition.source.controls).toMatchObject([
+ {
+ type: "variant",
+ key: "strategy",
+ label: "Search strategy",
+ config: {
+ discriminator: "type",
+ selection: undefined,
+ options: [
+ {
+ value: "exact",
+ defaultValue: { type: "exact", boost: 1 },
+ fields: [{ key: "boost", type: "number" }],
+ },
+ {
+ value: "fuzzy",
+ fields: [{ key: "distance", type: "number", integer: true }],
+ },
+ ],
+ },
+ },
+ ]);
+ });
+});
diff --git a/packages/query-builder/src/openapi.ts b/packages/query-builder/src/openapi.ts
new file mode 100644
index 0000000000..a74ccd820a
--- /dev/null
+++ b/packages/query-builder/src/openapi.ts
@@ -0,0 +1,980 @@
+import { queryDefinition } from "./schema";
+import type {
+ QueryControl,
+ QueryDefinition,
+ QueryField,
+ QueryFilterControl,
+ QueryOperator,
+ QueryParameterControlField,
+} from "./types";
+import { getQueryFieldKey } from "./runtime";
+
+type JsonObject = Record<string, unknown>;
+
+const isObject = (value: unknown): value is JsonObject =>
+ typeof value === "object" && value !== null && Array.isArray(value) === false;
+
+const labelFromKey = (key: string) =>
+ `${key.slice(0, 1).toUpperCase()}${key.slice(1)}`.replaceAll(
+ /([a-z])([A-Z])/g,
+ "$1 $2"
+ );
+
+const resolvePointer = (document: JsonObject, pointer: string): unknown => {
+ if (pointer.startsWith("#") === false) {
+ throw new Error("Only local OpenAPI references are supported");
+ }
+ const fragment = decodeURIComponent(pointer.slice(1));
+ if (fragment === "") {
+ return document;
+ }
+ if (fragment.startsWith("/") === false) {
+ throw new Error("Only local OpenAPI references are supported");
+ }
+ // JSON Pointer packages commonly traverse inherited properties. Decode the
+ // small RFC 6901 grammar here so untrusted schemas can only address own JSON
+ // properties. URI fragment decoding happens before token separation.
+ let value: unknown = document;
+ for (const segment of fragment
+ .slice(1)
+ .split("/")
+ .map((item) => item.replaceAll("~1", "/").replaceAll("~0", "~"))) {
+ if (Array.isArray(value)) {
+ if (/^(0|[1-9][0-9]*)$/.test(segment) === false) {
+ throw new Error(`OpenAPI reference ${pointer} is missing`);
+ }
+ const index = Number(segment);
+ if (Number.isSafeInteger(index) === false || index >= value.length) {
+ throw new Error(`OpenAPI reference ${pointer} is missing`);
+ }
+ value = value[index];
+ continue;
+ }
+ if (isObject(value) === false || Object.hasOwn(value, segment) === false) {
+ throw new Error(`OpenAPI reference ${pointer} is missing`);
+ }
+ value = value[segment];
+ }
+ return value;
+};
+
+const resolveSchema = (
+ document: JsonObject,
+ value: unknown,
+ references = new Set<string>()
+): JsonObject => {
+ if (isObject(value) === false) {
+ throw new Error("OpenAPI schema is invalid");
+ }
+ if (typeof value.$ref !== "string") {
+ return value;
+ }
+ if (references.has(value.$ref)) {
+ throw new Error("Circular OpenAPI query schema references are unsupported");
+ }
+ const resolved = resolvePointer(document, value.$ref);
+ if (isObject(resolved) === false) {
+ throw new Error(`OpenAPI reference ${value.$ref} is not a schema`);
+ }
+ const { $ref: _ref, ...siblings } = value;
+ return resolveSchema(
+ document,
+ { ...resolved, ...siblings },
+ new Set([...references, value.$ref])
+ );
+};
+
+const getProperties = (schema: JsonObject) => {
+ if (isObject(schema.properties) === false) {
+ throw new Error("OpenAPI object properties are missing");
+ }
+ return schema.properties;
+};
+
+const getChoices = (document: JsonObject, schema: JsonObject) => {
+ if (Array.isArray(schema.oneOf)) {
+ return schema.oneOf.flatMap((item) => {
+ const choice = resolveSchema(document, item);
+ if (typeof choice.const !== "string") {
+ return [];
+ }
+ return [
+ {
+ value: choice.const,
+ label: typeof choice.title === "string" ? choice.title : choice.const,
+ },
+ ];
+ });
+ }
+ if (Array.isArray(schema.enum)) {
+ return schema.enum.flatMap((value) =>
+ typeof value === "string" ? [{ value, label: value }] : []
+ );
+ }
+ return typeof schema.const === "string"
+ ? [{ value: schema.const, label: String(schema.title ?? schema.const) }]
+ : [];
+};
+
+const getFieldChoices = (
+ document: JsonObject,
+ schema: JsonObject
+): Array<{ path: string[]; label: string }> => {
+ const resolved = resolveSchema(document, schema);
+ if (
+ Array.isArray(resolved.const) &&
+ resolved.const.every((segment) => typeof segment === "string")
+ ) {
+ return [
+ {
+ path: resolved.const,
+ label:
+ typeof resolved.title === "string"
+ ? resolved.title
+ : resolved.const.join(" / "),
+ },
+ ];
+ }
+ if (
+ Array.isArray(resolved.enum) &&
+ resolved.enum.every(
+ (value) =>
+ Array.isArray(value) &&
+ value.every((segment) => typeof segment === "string")
+ )
+ ) {
+ return resolved.enum.map((value) => ({
+ path: value as string[],
+ label: (value as string[]).join(" / "),
+ }));
+ }
+ const choices = Array.isArray(resolved.oneOf)
+ ? resolved.oneOf
+ : Array.isArray(resolved.anyOf)
+ ? resolved.anyOf
+ : undefined;
+ return choices === undefined
+ ? []
+ : choices.flatMap((choice) =>
+ isObject(choice) ? getFieldChoices(document, choice) : []
+ );
+};
+
+const getSchemaChoices = (document: JsonObject, schema: JsonObject) => {
+ const resolved = resolveSchema(document, schema);
+ const choices = Array.isArray(resolved.oneOf)
+ ? resolved.oneOf
+ : Array.isArray(resolved.anyOf)
+ ? resolved.anyOf
+ : [];
+ return choices.flatMap((choice) =>
+ isObject(choice) ? [resolveSchema(document, choice)] : []
+ );
+};
+
+const isFilterCondition = (schema: JsonObject) => {
+ if (isObject(schema.properties) === false) {
+ return false;
+ }
+ return (
+ "field" in schema.properties &&
+ "operator" in schema.properties &&
+ "value" in schema.properties
+ );
+};
+
+const getFilterSchema = (document: JsonObject, schema: JsonObject) => {
+ const choices = getSchemaChoices(document, schema);
+ const conditionUnion = choices.find((choice) => {
+ const conditions = getSchemaChoices(document, choice);
+ return conditions.length > 0 && conditions.every(isFilterCondition);
+ });
+ if (conditionUnion === undefined) {
+ return;
+ }
+ const groups = choices.flatMap((choice) => {
+ if (isObject(choice.properties) === false) {
+ return [];
+ }
+ const names = Object.keys(choice.properties);
+ if (names.length !== 1 || (names[0] !== "all" && names[0] !== "any")) {
+ return [];
+ }
+ const children = choice.properties[names[0]];
+ return isObject(children) && isObject(children.items)
+ ? [{ combinator: names[0] as "all" | "any", children }]
+ : [];
+ });
+ return { conditionUnion, groups };
+};
+
+const getFilterDepth = (
+ document: JsonObject,
+ input: JsonObject,
+ references = new Set<string>()
+): number | undefined => {
+ let schema = input;
+ let nextReferences = references;
+ if (typeof schema.$ref === "string") {
+ if (references.has(schema.$ref)) {
+ return;
+ }
+ const resolved = resolvePointer(document, schema.$ref);
+ if (isObject(resolved) === false) {
+ return;
+ }
+ const { $ref, ...siblings } = schema;
+ schema = { ...resolved, ...siblings };
+ nextReferences = new Set([...references, $ref]);
+ }
+ const filter = getFilterSchema(document, schema);
+ if (filter === undefined || filter.groups.length === 0) {
+ return 0;
+ }
+ const childDepths = filter.groups.map(({ children }) =>
+ getFilterDepth(document, children.items as JsonObject, nextReferences)
+ );
+ if (childDepths.some((depth) => depth === undefined)) {
+ return;
+ }
+ return 1 + Math.max(...(childDepths as number[]));
+};
+
+type NumberControlConstraints = {
+ min?: number;
+ max?: number;
+ exclusiveMin?: boolean;
+ exclusiveMax?: boolean;
+ integer?: boolean;
+};
+
+const getNumberControlConstraints = (
+ schema: JsonObject
+): NumberControlConstraints => {
+ const integer = schema.type === "integer";
+ const minimum =
+ typeof schema.minimum === "number" ? schema.minimum : undefined;
+ const exclusiveMinimum =
+ typeof schema.exclusiveMinimum === "number"
+ ? schema.exclusiveMinimum
+ : schema.exclusiveMinimum === true
+ ? minimum
+ : undefined;
+ const maximum =
+ typeof schema.maximum === "number" ? schema.maximum : undefined;
+ const exclusiveMaximum =
+ typeof schema.exclusiveMaximum === "number"
+ ? schema.exclusiveMaximum
+ : schema.exclusiveMaximum === true
+ ? maximum
+ : undefined;
+ if (integer) {
+ const minimums = [
+ minimum === undefined ? undefined : Math.ceil(minimum),
+ exclusiveMinimum === undefined
+ ? undefined
+ : Math.floor(exclusiveMinimum) + 1,
+ ].filter((value): value is number => value !== undefined);
+ const maximums = [
+ maximum === undefined ? undefined : Math.floor(maximum),
+ exclusiveMaximum === undefined
+ ? undefined
+ : Math.ceil(exclusiveMaximum) - 1,
+ ].filter((value): value is number => value !== undefined);
+ return {
+ min: minimums.length === 0 ? undefined : Math.max(...minimums),
+ max: maximums.length === 0 ? undefined : Math.min(...maximums),
+ integer: true as const,
+ };
+ }
+ const exclusiveMin =
+ exclusiveMinimum !== undefined &&
+ (minimum === undefined || exclusiveMinimum >= minimum);
+ const exclusiveMax =
+ exclusiveMaximum !== undefined &&
+ (maximum === undefined || exclusiveMaximum <= maximum);
+ return {
+ min: exclusiveMin ? exclusiveMinimum : minimum,
+ max: exclusiveMax ? exclusiveMaximum : maximum,
+ ...(exclusiveMin ? { exclusiveMin: true as const } : {}),
+ ...(exclusiveMax ? { exclusiveMax: true as const } : {}),
+ };
+};
+
+const isWithinNumberConstraints = (
+ value: number,
+ constraints: ReturnType<typeof getNumberControlConstraints>
+) =>
+ (constraints.integer !== true || Number.isInteger(value)) &&
+ (constraints.min === undefined ||
+ (constraints.exclusiveMin
+ ? value > constraints.min
+ : value >= constraints.min)) &&
+ (constraints.max === undefined ||
+ (constraints.exclusiveMax
+ ? value < constraints.max
+ : value <= constraints.max));
+
+const getDefaultNumber = (schema: JsonObject) => {
+ const constraints = getNumberControlConstraints(schema);
+ const candidates = [
+ 0,
+ constraints.min,
+ constraints.max,
+ constraints.min === undefined
+ ? undefined
+ : constraints.max === undefined
+ ? constraints.min + 1
+ : constraints.min + (constraints.max - constraints.min) / 2,
+ constraints.max === undefined ? undefined : constraints.max - 1,
+ ];
+ return (
+ candidates.find(
+ (value): value is number =>
+ typeof value === "number" &&
+ Number.isFinite(value) &&
+ isWithinNumberConstraints(value, constraints)
+ ) ?? 0
+ );
+};
+
+const defaultFromSchema = (
+ document: JsonObject,
+ input: JsonObject
+): unknown => {
+ const schema = resolveSchema(document, input);
+ if (schema.default !== undefined) {
+ return structuredClone(schema.default);
+ }
+ if (schema.const !== undefined) {
+ return structuredClone(schema.const);
+ }
+ if (schema.type === "array") {
+ return [];
+ }
+ if (schema.type === "boolean") {
+ return false;
+ }
+ if (schema.type === "integer" || schema.type === "number") {
+ return getDefaultNumber(schema);
+ }
+ if (schema.type === "object") {
+ const properties = isObject(schema.properties) ? schema.properties : {};
+ const required = Array.isArray(schema.required) ? schema.required : [];
+ return Object.fromEntries(
+ Object.entries(properties).flatMap(([key, child]) => {
+ if (isObject(child) === false) {
+ return [];
+ }
+ const resolved = resolveSchema(document, child);
+ return required.includes(key) ||
+ resolved.default !== undefined ||
+ resolved.const !== undefined
+ ? [[key, defaultFromSchema(document, resolved)]]
+ : [];
+ })
+ );
+ }
+ return "";
+};
+
+const createVariantValidationSchema = (
+ document: JsonObject,
+ value: unknown,
+ references = new Set<string>()
+): unknown => {
+ if (Array.isArray(value)) {
+ return value.map((item) =>
+ createVariantValidationSchema(document, item, references)
+ );
+ }
+ if (isObject(value) === false) {
+ return value;
+ }
+ if (typeof value.$ref === "string") {
+ if (references.has(value.$ref)) {
+ throw new Error(
+ "Circular OpenAPI query schema references are unsupported"
+ );
+ }
+ const resolved = resolvePointer(document, value.$ref);
+ if (isObject(resolved) === false) {
+ throw new Error(`OpenAPI reference ${value.$ref} is not a schema`);
+ }
+ const { $ref, ...siblings } = value;
+ return createVariantValidationSchema(
+ document,
+ { ...resolved, ...siblings },
+ new Set([...references, $ref])
+ );
+ }
+ const schema = Object.fromEntries(
+ Object.entries(value).map(([key, item]) => [
+ key,
+ createVariantValidationSchema(document, item, references),
+ ])
+ );
+ if (
+ schema.type === "array" &&
+ Array.isArray(schema.oneOf) &&
+ schema.oneOf.every((choice) => {
+ if (isObject(choice) === false) {
+ return false;
+ }
+ const values = Array.isArray(choice.enum) ? choice.enum : [choice.const];
+ return values.every(
+ (segments) =>
+ Array.isArray(segments) &&
+ segments.every((segment) => typeof segment === "string")
+ );
+ })
+ ) {
+ // Zod's JSON Schema converter treats an array-valued const as a list of
+ // scalar choices. Express each exact array as an equivalent tuple schema
+ // so source validation preserves the choices declared by OpenAPI.
+ return {
+ ...schema,
+ oneOf: schema.oneOf.flatMap((choice) => {
+ const values = Array.isArray((choice as JsonObject).enum)
+ ? ((choice as JsonObject).enum as string[][])
+ : [(choice as { const: string[] }).const];
+ return values.map((segments) => ({
+ type: "array",
+ prefixItems: segments.map((segment) => ({ const: segment })),
+ items: false,
+ minItems: segments.length,
+ maxItems: segments.length,
+ }));
+ }),
+ };
+ }
+ return schema;
+};
+
+const createVariantControl = ({
+ document,
+ key,
+ schema,
+}: {
+ document: JsonObject;
+ key: string;
+ schema: JsonObject;
+}): QueryControl | undefined => {
+ if (Array.isArray(schema.oneOf) === false || schema.oneOf.length === 0) {
+ return;
+ }
+ const objects = schema.oneOf.map((item) => resolveSchema(document, item));
+ const discriminator = Object.keys(getProperties(objects[0])).find((name) =>
+ objects.every((item) => {
+ const candidate = getProperties(item)[name];
+ return (
+ isObject(candidate) &&
+ typeof resolveSchema(document, candidate).const === "string"
+ );
+ })
+ );
+ if (discriminator === undefined) {
+ return;
+ }
+ const options = objects.map((item) => {
+ const properties = getProperties(item);
+ const discriminatorSchema = resolveSchema(
+ document,
+ properties[discriminator]
+ );
+ const value = discriminatorSchema.const as string;
+ const defaultValue = defaultFromSchema(document, item) as Record<
+ string,
+ unknown
+ >;
+ const fields: QueryParameterControlField[] = [];
+ for (const [name, child] of Object.entries(properties)) {
+ if (name === discriminator || isObject(child) === false) {
+ continue;
+ }
+ const childSchema = resolveSchema(document, child);
+ const items = isObject(childSchema.items)
+ ? resolveSchema(document, childSchema.items)
+ : undefined;
+ if (
+ childSchema.type === "array" &&
+ items !== undefined &&
+ getFieldChoices(document, items).length > 0
+ ) {
+ fields.push({
+ key: name,
+ label: String(childSchema.title ?? labelFromKey(name)),
+ type: "field-list",
+ max:
+ typeof childSchema.maxItems === "number"
+ ? childSchema.maxItems
+ : undefined,
+ });
+ continue;
+ }
+ if (childSchema.type === "integer" || childSchema.type === "number") {
+ fields.push({
+ key: name,
+ label: String(childSchema.title ?? labelFromKey(name)),
+ type: "number",
+ ...getNumberControlConstraints(childSchema),
+ optional: Array.isArray(item.required)
+ ? item.required.includes(name) === false
+ : true,
+ });
+ }
+ }
+ return {
+ value,
+ label: String(discriminatorSchema.title ?? value),
+ defaultValue,
+ fields,
+ };
+ });
+ const currentDefault = isObject(schema.default)
+ ? schema.default
+ : options[0]?.defaultValue;
+ if (options.length === 0) {
+ return;
+ }
+ const commonBoolean = Object.keys(getProperties(objects[0])).find(
+ (name) =>
+ name !== discriminator &&
+ objects.every((item) => getProperties(item)[name] !== undefined) &&
+ objects.every((item) => {
+ const child = getProperties(item)[name];
+ return (
+ isObject(child) && resolveSchema(document, child).type === "boolean"
+ );
+ })
+ );
+ const emptyOption = options.find(({ fields }) => fields.length === 0)?.value;
+ const isAdditiveSelection =
+ emptyOption !== undefined &&
+ options.some(({ fields }) => fields.length > 0);
+ const label = String(schema.title ?? labelFromKey(key));
+ return {
+ type: "variant",
+ key,
+ label,
+ defaultValue: currentDefault ?? options[0]?.defaultValue ?? {},
+ schema: createVariantValidationSchema(document, schema) as JsonObject,
+ config: {
+ discriminator,
+ selection:
+ isAdditiveSelection === false
+ ? undefined
+ : {
+ label,
+ emptyOption,
+ baseline:
+ commonBoolean === undefined
+ ? undefined
+ : {
+ key: commonBoolean,
+ label: String(
+ (getProperties(objects[0])[commonBoolean] as JsonObject)
+ .title ?? labelFromKey(commonBoolean)
+ ),
+ },
+ },
+ options,
+ },
+ };
+};
+
+const createDefinition = ({
+ document,
+ schema,
+}: {
+ document: JsonObject;
+ schema: JsonObject;
+}): QueryDefinition => {
+ const fields = new Map<string, QueryField>();
+ const operators = new Map<string, QueryOperator>();
+ const controls: QueryControl[] = [];
+ for (const [key, unresolved] of Object.entries(getProperties(schema))) {
+ const property = resolveSchema(document, unresolved);
+ const label = String(property.title ?? labelFromKey(key));
+ const filterSchema = getFilterSchema(document, property);
+ if (filterSchema !== undefined) {
+ const conditions = getSchemaChoices(
+ document,
+ filterSchema.conditionUnion
+ );
+ for (const condition of conditions) {
+ const properties = getProperties(condition);
+ const field = isObject(properties.field) ? properties.field : {};
+ const operator = isObject(properties.operator)
+ ? properties.operator
+ : {};
+ const fieldChoices = isObject(field)
+ ? getFieldChoices(document, field)
+ : [];
+ if (fieldChoices.length === 0) {
+ continue;
+ }
+ const supported = getChoices(document, operator);
+ for (const choice of fieldChoices) {
+ const fieldKey = getQueryFieldKey(choice.path);
+ const existing = fields.get(fieldKey);
+ fields.set(fieldKey, {
+ path: choice.path,
+ label: choice.label,
+ types: ["string"],
+ operators: [
+ ...new Set([
+ ...(existing?.operators ?? []),
+ ...supported.map(({ value }) => value),
+ ]),
+ ],
+ });
+ }
+ const valueSchema = isObject(properties.value) ? properties.value : {};
+ for (const choice of supported) {
+ operators.set(choice.value, {
+ value: choice.value,
+ label: choice.label,
+ types: ["string"],
+ input: {
+ control: valueSchema.type === "boolean" ? "none" : "expression",
+ defaultValue: JSON.stringify(
+ defaultFromSchema(document, valueSchema)
+ ),
+ },
+ });
+ }
+ }
+ const combinators = filterSchema.groups.map(
+ ({ combinator }) => combinator
+ );
+ const maximumConditions = Math.min(
+ ...filterSchema.groups.map(({ children }) =>
+ typeof children.maxItems === "number"
+ ? children.maxItems
+ : Number.MAX_SAFE_INTEGER
+ )
+ );
+ const maximumDepth = getFilterDepth(document, property);
+ const firstField = fields.values().next().value;
+ const firstOperator = firstField?.operators?.[0];
+ if (firstField !== undefined && firstOperator !== undefined) {
+ controls.push({
+ type: "filter",
+ key,
+ label,
+ defaultValue: (property.default ?? {
+ [combinators[0] ?? "all"]: [],
+ }) as QueryFilterControl["defaultValue"],
+ combinators: combinators.length > 0 ? combinators : ["all"],
+ limits: {
+ conditions: maximumConditions,
+ depth: maximumDepth ?? Number.MAX_SAFE_INTEGER,
+ },
+ defaultCondition: { field: firstField.path, operator: firstOperator },
+ });
+ }
+ continue;
+ }
+ if (property.type === "array" && isObject(property.items)) {
+ const item = resolveSchema(document, property.items);
+ const itemProperties = isObject(item.properties) ? item.properties : {};
+ const field = isObject(itemProperties.field) ? itemProperties.field : {};
+ const directions = isObject(itemProperties.direction)
+ ? getChoices(
+ document,
+ resolveSchema(document, itemProperties.direction)
+ )
+ : [];
+ const fieldChoices = isObject(field)
+ ? getFieldChoices(document, field)
+ : [];
+ if (fieldChoices.length > 0 && directions.length > 0) {
+ for (const choice of fieldChoices) {
+ const fieldKey = getQueryFieldKey(choice.path);
+ if (fields.has(fieldKey) === false) {
+ fields.set(fieldKey, {
+ path: choice.path,
+ label: choice.label,
+ types: ["string"],
+ });
+ }
+ }
+ controls.push({
+ type: "sort",
+ key,
+ label,
+ defaultValue: Array.isArray(property.default)
+ ? (property.default as never[])
+ : [],
+ defaultItem: {
+ field: fieldChoices[0].path,
+ direction: directions[0].value,
+ },
+ directions,
+ max:
+ typeof property.maxItems === "number"
+ ? property.maxItems
+ : undefined,
+ });
+ continue;
+ }
+ }
+ if (property.type === "integer" || property.type === "number") {
+ controls.push({
+ type: "expression",
+ key,
+ label,
+ defaultValue: JSON.stringify(defaultFromSchema(document, property)),
+ input: "number",
+ ...getNumberControlConstraints(property),
+ });
+ continue;
+ }
+ const variant = createVariantControl({ document, key, schema: property });
+ if (variant !== undefined) {
+ controls.push(variant);
+ }
+ }
+ return queryDefinition.parse({
+ version: 1,
+ ...(typeof schema.description === "string"
+ ? { description: schema.description }
+ : {}),
+ fields: [...fields.values()],
+ operators: [...operators.values()],
+ source: { fieldPathSchema: true, controls },
+ });
+};
+
+const findOperation = (document: JsonObject, operationId: string) => {
+ if (isObject(document.paths) === false) {
+ throw new Error("OpenAPI paths are missing");
+ }
+ for (const pathItem of Object.values(document.paths)) {
+ if (isObject(pathItem) === false) {
+ continue;
+ }
+ for (const candidate of Object.values(pathItem)) {
+ if (isObject(candidate) && candidate.operationId === operationId) {
+ return { operation: candidate, pathItem };
+ }
+ }
+ }
+ throw new Error(`OpenAPI operation ${operationId} is missing`);
+};
+
+/** Derives query authoring solely from one standard OpenAPI operation. */
+export const getOpenApiQueryDefinition = ({
+ document: input,
+ operationId,
+}: {
+ document: unknown;
+ operationId: string;
+}): QueryDefinition => {
+ if (isObject(input) === false) {
+ throw new Error("OpenAPI document is invalid");
+ }
+ const { operation, pathItem } = findOperation(input, operationId);
+ const parametersByIdentity = new Map<
+ string,
+ { key: string; schema: JsonObject }
+ >();
+ const addParameters = (items: unknown) => {
+ if (Array.isArray(items) === false) {
+ return;
+ }
+ for (const item of items) {
+ const parameter = resolveSchema(input, item);
+ if (
+ typeof parameter.name !== "string" ||
+ typeof parameter.in !== "string" ||
+ isObject(parameter.schema) === false
+ ) {
+ continue;
+ }
+ parametersByIdentity.set(`${parameter.in}\0${parameter.name}`, {
+ key: parameter.name,
+ schema: resolveSchema(input, parameter.schema),
+ });
+ }
+ };
+ addParameters(pathItem.parameters);
+ addParameters(operation.parameters);
+ const parameters = [...parametersByIdentity.values()];
+ const requestBody = isObject(operation.requestBody)
+ ? resolveSchema(input, operation.requestBody)
+ : undefined;
+ const content =
+ requestBody && isObject(requestBody.content)
+ ? requestBody.content
+ : undefined;
+ const media =
+ content && isObject(content["application/json"])
+ ? content["application/json"]
+ : undefined;
+ if (media !== undefined && isObject(media.schema)) {
+ const requestSchema = resolveSchema(input, media.schema);
+ const required = Array.isArray(requestSchema.required)
+ ? requestSchema.required.filter(
+ (item): item is string => typeof item === "string"
+ )
+ : [];
+ const properties = getProperties(requestSchema);
+ const objectKeys = required.filter((key) => {
+ const property = properties[key];
+ return (
+ isObject(property) && resolveSchema(input, property).type === "object"
+ );
+ });
+ const valuePath =
+ required.length === 1 && objectKeys.length === 1 ? [objectKeys[0]] : [];
+ const valueSchema =
+ valuePath.length === 1
+ ? resolveSchema(input, properties[valuePath[0]])
+ : requestSchema;
+ return createDefinition({ document: input, schema: valueSchema });
+ }
+ const controls: QueryControl[] = parameters.map(({ key, schema }) => ({
+ type: "expression",
+ key,
+ label: String(schema.title ?? labelFromKey(key)),
+ defaultValue: JSON.stringify(defaultFromSchema(input, schema)),
+ input:
+ schema.type === "integer" || schema.type === "number"
+ ? "number"
+ : "expression",
+ ...getNumberControlConstraints(schema),
+ }));
+ return queryDefinition.parse({
+ version: 1,
+ fields: [],
+ operators: [],
+ source: { fieldPathSchema: true, controls },
+ });
+};
+
+const getReferenceDocumentUrl = (url: URL) => {
+ const documentUrl = new URL(url);
+ documentUrl.hash = "";
+ return documentUrl.href;
+};
+
+/**
+ * Loads standard external OpenAPI/JSON Schema references and bundles them as
+ * local component schemas before deriving the query UI. Network policy stays
+ * with the caller through loadReference.
+ */
+export const loadOpenApiQueryDefinition = async ({
+ document,
+ documentUrl,
+ operationId,
+ loadReference,
+}: {
+ document: unknown;
+ documentUrl: string;
+ operationId: string;
+ loadReference: (url: string) => Promise<unknown>;
+}): Promise<QueryDefinition> => {
+ if (isObject(document) === false) {
+ throw new Error("OpenAPI document is invalid");
+ }
+ const rootUrl = getReferenceDocumentUrl(new URL(documentUrl));
+ const bundled = structuredClone(document);
+ const components = isObject(bundled.components)
+ ? bundled.components
+ : (bundled.components = {});
+ const schemas = isObject(components.schemas)
+ ? components.schemas
+ : (components.schemas = {});
+ const prefixByDocumentUrl = new Map<string, string>([[rootUrl, "#"]]);
+ const externalSchemaKeys = new Set<string>();
+
+ const createExternalPrefix = () => {
+ let index = prefixByDocumentUrl.size - 1;
+ let key = `ExternalQuerySchema${index}`;
+ while (Object.hasOwn(schemas, key)) {
+ index += 1;
+ key = `ExternalQuerySchema${index}`;
+ }
+ return `#/components/schemas/${key}`;
+ };
+
+ const rewriteReferences = async (
+ value: unknown,
+ baseUrl: string,
+ localPrefix: string
+ ): Promise<unknown> => {
+ if (Array.isArray(value)) {
+ return await Promise.all(
+ value.map((item) => rewriteReferences(item, baseUrl, localPrefix))
+ );
+ }
+ if (isObject(value) === false) {
+ return value;
+ }
+ return Object.fromEntries(
+ await Promise.all(
+ Object.entries(value).map(async ([key, item]) => {
+ if (key !== "$ref" || typeof item !== "string") {
+ return [key, await rewriteReferences(item, baseUrl, localPrefix)];
+ }
+ if (item.startsWith("#")) {
+ return [
+ key,
+ localPrefix === "#" ? item : `${localPrefix}${item.slice(1)}`,
+ ];
+ }
+ const referenceUrl = new URL(item, baseUrl);
+ const fragment = referenceUrl.hash;
+ const referenceDocumentUrl = getReferenceDocumentUrl(referenceUrl);
+ let referencePrefix = prefixByDocumentUrl.get(referenceDocumentUrl);
+ if (referencePrefix === undefined) {
+ referencePrefix = createExternalPrefix();
+ prefixByDocumentUrl.set(referenceDocumentUrl, referencePrefix);
+ const key = referencePrefix.slice("#/components/schemas/".length);
+ externalSchemaKeys.add(key);
+ // Reserve the destination before reading nested references so
+ // mutually referencing documents terminate deterministically.
+ schemas[key] = {};
+ const external = await loadReference(referenceDocumentUrl);
+ if (isObject(external) === false) {
+ throw new Error(
+ `OpenAPI reference ${referenceDocumentUrl} is invalid`
+ );
+ }
+ schemas[key] = await rewriteReferences(
+ external,
+ referenceDocumentUrl,
+ referencePrefix
+ );
+ }
+ return [
+ key,
+ fragment.length === 0
+ ? referencePrefix
+ : `${referencePrefix}${fragment.slice(1)}`,
+ ];
+ })
+ )
+ );
+ };
+
+ const resolved = await rewriteReferences(bundled, rootUrl, "#");
+ if (isObject(resolved) === false) {
+ throw new Error("OpenAPI document is invalid");
+ }
+ const resolvedComponents = isObject(resolved.components)
+ ? resolved.components
+ : (resolved.components = {});
+ const resolvedSchemas = isObject(resolvedComponents.schemas)
+ ? resolvedComponents.schemas
+ : (resolvedComponents.schemas = {});
+ for (const key of externalSchemaKeys) {
+ resolvedSchemas[key] = schemas[key];
+ }
+ return getOpenApiQueryDefinition({
+ document: resolved,
+ operationId,
+ });
+};
diff --git a/packages/query-builder/src/query-utils.test.ts b/packages/query-builder/src/query-utils.test.ts
new file mode 100644
index 0000000000..a28bfe54cc
--- /dev/null
+++ b/packages/query-builder/src/query-utils.test.ts
@@ -0,0 +1,137 @@
+import { describe, expect, test } from "vitest";
+import { z } from "zod";
+import {
+ createQueryCondition,
+ createQuerySort,
+ createStructuredQuery,
+} from "./query-utils";
+import {
+ createQueryWhereSchema,
+ evaluateQueryWhere,
+ getQueryConditions,
+ getQueryWhereMetrics,
+ mapQueryWhere,
+} from "./runtime";
+import { genericQueryCapabilities } from "./test-fixtures";
+
+const where = {
+ all: [
+ { field: ["extension"], operator: "eq", value: '"md"' },
+ {
+ any: [
+ { field: ["properties", "slug"], operator: "eq", value: "slug" },
+ { field: ["properties", "id"], operator: "eq", value: "slug" },
+ ],
+ },
+ ],
+};
+
+describe("structured query traversal", () => {
+ test("collects nested conditions", () => {
+ expect(getQueryConditions(where)).toHaveLength(3);
+ });
+
+ test("maps conditions while preserving groups", () => {
+ expect(
+ mapQueryWhere(where, (condition) => ({
+ ...condition,
+ value: condition.value.toUpperCase(),
+ }))
+ ).toEqual({
+ all: [
+ { field: ["extension"], operator: "eq", value: '"MD"' },
+ {
+ any: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "SLUG",
+ },
+ {
+ field: ["properties", "id"],
+ operator: "eq",
+ value: "SLUG",
+ },
+ ],
+ },
+ ],
+ });
+ });
+
+ test("measures condition count and group depth", () => {
+ expect(getQueryWhereMetrics(where)).toEqual({ conditions: 3, depth: 2 });
+ });
+
+ test("enforces shared query tree limits", () => {
+ const schema = createQueryWhereSchema(
+ z.strictObject({ field: z.string() }),
+ { maximumChildren: 2, maximumConditions: 2, maximumDepth: 2 }
+ );
+
+ expect(
+ schema.safeParse({
+ all: [{ field: "one" }, { any: [{ field: "two" }] }],
+ }).success
+ ).toBe(true);
+ expect(
+ schema.safeParse({
+ all: [{ field: "one" }, { field: "two" }, { field: "three" }],
+ }).success
+ ).toBe(false);
+ expect(
+ schema.safeParse({
+ all: [
+ { field: "one" },
+ { any: [{ field: "two" }, { field: "three" }] },
+ ],
+ }).success
+ ).toBe(false);
+ expect(
+ schema.safeParse({ all: [{ any: [{ all: [{ field: "one" }] }] }] })
+ .success
+ ).toBe(false);
+ });
+
+ test("evaluates nested boolean trees without discarding unknown leaves", () => {
+ const evaluate = (value: boolean | undefined) =>
+ evaluateQueryWhere(
+ {
+ all: [
+ { field: "known", value: true },
+ {
+ any: [
+ { field: "unknown", value },
+ { field: "no", value: false },
+ ],
+ },
+ ],
+ },
+ (condition) => condition.value
+ );
+
+ expect(evaluate(true)).toBe(true);
+ expect(evaluate(false)).toBe(false);
+ expect(evaluate(undefined)).toBeUndefined();
+ expect(evaluateQueryWhere({ all: [] }, () => undefined)).toBe(true);
+ expect(evaluateQueryWhere({ any: [] }, () => undefined)).toBe(false);
+ });
+
+ test("derives query, condition, parameter, and sort defaults from capabilities", () => {
+ expect(createQueryCondition(genericQueryCapabilities)).toEqual({
+ field: ["title"],
+ operator: "eq",
+ value: '""',
+ });
+ expect(createQuerySort(genericQueryCapabilities)).toEqual({
+ field: ["publishedAt"],
+ direction: "desc",
+ });
+ expect(createStructuredQuery(genericQueryCapabilities)).toEqual({
+ where: { all: [] },
+ sort: [],
+ limit: "10",
+ offset: "0",
+ selection: { mode: "summary", includeMetadata: true },
+ });
+ });
+});
diff --git a/packages/query-builder/src/query-utils.ts b/packages/query-builder/src/query-utils.ts
new file mode 100644
index 0000000000..442b63b564
--- /dev/null
+++ b/packages/query-builder/src/query-utils.ts
@@ -0,0 +1,109 @@
+import type { QueryCondition, QueryDefinition, QuerySort } from "./types";
+import { getQueryFieldKey } from "./runtime";
+
+export const addConfiguredQueryFields = <
+ FieldType extends string,
+ Operator extends string,
+>({
+ definition,
+ paths,
+ fallbackType,
+}: {
+ definition: QueryDefinition<FieldType, Operator>;
+ paths: readonly string[][];
+ fallbackType: FieldType;
+}): QueryDefinition<FieldType, Operator> => {
+ const fields = new Map(
+ definition.fields.map((field) => [getQueryFieldKey(field.path), field])
+ );
+ for (const path of paths) {
+ const key = getQueryFieldKey(path);
+ if (fields.has(key)) {
+ continue;
+ }
+ fields.set(key, {
+ path,
+ label: path.join(" / "),
+ types: [fallbackType],
+ operators: definition.operators.map(({ value }) => value),
+ });
+ }
+ return { ...definition, fields: [...fields.values()] };
+};
+
+export const getCompatibleQueryOperators = <
+ FieldType extends string,
+ Operator extends string,
+ Item extends {
+ value: Operator;
+ types: readonly FieldType[];
+ },
+>(
+ fieldTypes: readonly FieldType[],
+ operators: readonly Item[],
+ supportedOperators?: readonly string[]
+) => {
+ if (supportedOperators !== undefined) {
+ const supported = new Set(supportedOperators);
+ return operators.filter(({ value }) => supported.has(value));
+ }
+ const types = new Set(fieldTypes);
+ return operators.filter((operator) =>
+ operator.types.some((type) => types.has(type))
+ );
+};
+
+export const createQueryCondition = <
+ FieldType extends string,
+ Operator extends string,
+>(
+ capabilities: QueryDefinition<FieldType, Operator>
+): QueryCondition<string[], Operator> => {
+ const control = capabilities.source.controls.find(
+ (item) => item.type === "filter"
+ );
+ if (control === undefined) {
+ throw new Error("A filter control is required");
+ }
+ return {
+ field: [...control.defaultCondition.field],
+ operator: control.defaultCondition.operator,
+ value:
+ capabilities.operators.find(
+ ({ value }) => value === control.defaultCondition.operator
+ )?.input.defaultValue ?? "null",
+ };
+};
+
+export const createQuerySort = <
+ FieldType extends string,
+ Operator extends string,
+>(
+ capabilities: QueryDefinition<FieldType, Operator>
+): QuerySort<string[]> => {
+ const control = capabilities.source.controls.find(
+ (item) => item.type === "sort"
+ );
+ if (control === undefined) {
+ throw new Error("A sort control is required");
+ }
+ return {
+ field: [...control.defaultItem.field],
+ direction: control.defaultItem.direction,
+ };
+};
+
+export const createStructuredQuery = <
+ Query extends Record<string, unknown> = Record<string, unknown>,
+>(capabilities: {
+ source: {
+ controls: readonly { key: string; defaultValue: unknown }[];
+ };
+}): Query => {
+ return Object.fromEntries(
+ capabilities.source.controls.map(({ key, defaultValue }) => [
+ key,
+ structuredClone(defaultValue),
+ ])
+ ) as Query;
+};
diff --git a/packages/query-builder/src/runtime.ts b/packages/query-builder/src/runtime.ts
new file mode 100644
index 0000000000..4a6d94ea9d
--- /dev/null
+++ b/packages/query-builder/src/runtime.ts
@@ -0,0 +1,151 @@
+import {
+ array,
+ lazy,
+ strictObject,
+ union,
+ type ZodType,
+ type input as ZodInput,
+ type output as ZodOutput,
+} from "zod";
+import type { QueryWhereTree } from "./types";
+
+const collectQueryConditions = <Condition extends { field: unknown }>(
+ where: QueryWhereTree<Condition>
+): Condition[] => {
+ if ("field" in where) {
+ return [where];
+ }
+ return ("all" in where ? where.all : where.any).flatMap(
+ collectQueryConditions
+ );
+};
+
+export const getQueryConditions = <Condition extends { field: unknown }>(
+ where: QueryWhereTree<Condition>
+) => collectQueryConditions(where);
+
+export const mapQueryWhere = <
+ Input extends { field: unknown },
+ Output extends { field: unknown },
+>(
+ where: QueryWhereTree<Input>,
+ mapCondition: (condition: Input) => Output
+): QueryWhereTree<Output> => {
+ if ("field" in where) {
+ return mapCondition(where);
+ }
+ if ("all" in where) {
+ return {
+ all: where.all.map((child) => mapQueryWhere(child, mapCondition)),
+ };
+ }
+ return { any: where.any.map((child) => mapQueryWhere(child, mapCondition)) };
+};
+
+/** Evaluates a boolean query tree while preserving an unknown leaf result. */
+export const evaluateQueryWhere = <Condition extends { field: unknown }>(
+ where: QueryWhereTree<Condition>,
+ evaluateCondition: (condition: Condition) => boolean | undefined
+): boolean | undefined => {
+ if ("field" in where) {
+ return evaluateCondition(where);
+ }
+ const children = "all" in where ? where.all : where.any;
+ let hasUnknown = false;
+ if ("all" in where) {
+ for (const child of children) {
+ const result = evaluateQueryWhere(child, evaluateCondition);
+ if (result === false) {
+ return false;
+ }
+ hasUnknown ||= result === undefined;
+ }
+ return hasUnknown ? undefined : true;
+ }
+ for (const child of children) {
+ const result = evaluateQueryWhere(child, evaluateCondition);
+ if (result === true) {
+ return true;
+ }
+ hasUnknown ||= result === undefined;
+ }
+ return hasUnknown ? undefined : false;
+};
+
+export const getQueryFieldKey = (field: readonly string[]) =>
+ JSON.stringify(field);
+
+export const getQueryWhereMetrics = (
+ where: QueryWhereTree<{ field: unknown }>
+): { conditions: number; depth: number } => {
+ if ("field" in where) {
+ return { conditions: 1, depth: 0 };
+ }
+ const children = "all" in where ? where.all : where.any;
+ let conditions = 0;
+ let depth = 1;
+ for (const child of children) {
+ const metrics = getQueryWhereMetrics(child);
+ conditions += metrics.conditions;
+ depth = Math.max(depth, metrics.depth + 1);
+ }
+ return { conditions, depth };
+};
+
+export const createQueryWhereSchema = <
+ ConditionSchema extends ZodType<{ field: unknown }>,
+>(
+ conditionSchema: ConditionSchema,
+ options: {
+ maximumChildren?: number;
+ maximumConditions?: number;
+ maximumDepth?: number;
+ maximumConditionsMessage?: string;
+ maximumDepthMessage?: string;
+ } = {}
+) => {
+ type Input = QueryWhereTree<ZodInput<ConditionSchema>>;
+ type Output = QueryWhereTree<ZodOutput<ConditionSchema>>;
+ const createNode = (child: ZodType<Output, Input>) => {
+ const children = array(child);
+ const boundedChildren =
+ options.maximumChildren === undefined
+ ? children
+ : children.max(options.maximumChildren);
+ return union([
+ conditionSchema,
+ strictObject({ all: boundedChildren }),
+ strictObject({ any: boundedChildren }),
+ ]);
+ };
+ const node: ZodType<Output, Input> = lazy(() => createNode(node));
+ if (
+ options.maximumConditions === undefined &&
+ options.maximumDepth === undefined
+ ) {
+ return node;
+ }
+ return node.superRefine((where, context) => {
+ const { conditions, depth } = getQueryWhereMetrics(where);
+ if (
+ options.maximumConditions !== undefined &&
+ conditions > options.maximumConditions
+ ) {
+ context.addIssue({
+ code: "custom",
+ message:
+ options.maximumConditionsMessage ??
+ "Query exceeds the condition limit",
+ });
+ }
+ if (options.maximumDepth !== undefined && depth > options.maximumDepth) {
+ context.addIssue({
+ code: "custom",
+ message:
+ options.maximumDepthMessage ?? "Query exceeds the nesting limit",
+ });
+ }
+ });
+};
+
+export type { QueryWhereTree } from "./types";
diff --git a/packages/query-builder/src/schema.ts b/packages/query-builder/src/schema.ts
new file mode 100644
index 0000000000..0a59532f1e
--- /dev/null
+++ b/packages/query-builder/src/schema.ts
@@ -0,0 +1,338 @@
+import { z } from "zod";
+import { isQueryExpression } from "./source";
+import { createQueryWhereSchema, getQueryFieldKey } from "./runtime";
+import { getCompatibleQueryOperators } from "./query-utils";
+
+const fieldPath = z.array(z.string().min(1)).min(1);
+const condition = z.strictObject({
+ field: fieldPath,
+ operator: z.string().min(1),
+ value: z.string().min(1),
+});
+
+const sortItem = z.strictObject({
+ field: fieldPath,
+ direction: z.string().min(1),
+});
+const choice = z.strictObject({
+ value: z.string().min(1),
+ label: z.string().min(1),
+});
+const jsonSchema = z.union([z.boolean(), z.record(z.string(), z.json())]);
+const parameterField = z.discriminatedUnion("type", [
+ z.strictObject({
+ key: z.string().min(1),
+ label: z.string().min(1),
+ type: z.literal("number"),
+ min: z.number().optional(),
+ max: z.number().optional(),
+ exclusiveMin: z.boolean().optional(),
+ exclusiveMax: z.boolean().optional(),
+ integer: z.boolean().optional(),
+ optional: z.boolean().optional(),
+ }),
+ z.strictObject({
+ key: z.string().min(1),
+ label: z.string().min(1),
+ type: z.literal("field-list"),
+ max: z.number().int().positive().optional(),
+ }),
+]);
+const variantConfig = z.strictObject({
+ discriminator: z.string().min(1),
+ selection: z
+ .strictObject({
+ label: z.string().min(1),
+ emptyOption: z.string().min(1),
+ baseline: z
+ .strictObject({ key: z.string().min(1), label: z.string().min(1) })
+ .optional(),
+ })
+ .optional(),
+ options: z
+ .array(
+ z.strictObject({
+ value: z.string().min(1),
+ label: z.string().min(1),
+ defaultValue: z.record(z.string(), z.json()),
+ fields: z.array(parameterField),
+ })
+ )
+ .min(1),
+});
+
+const control = z.discriminatedUnion("type", [
+ z.strictObject({
+ type: z.literal("filter"),
+ key: z.string().min(1),
+ label: z.string().min(1),
+ defaultValue: createQueryWhereSchema(condition),
+ combinators: z
+ .array(z.enum(["all", "any"]))
+ .min(1)
+ .max(2),
+ limits: z.strictObject({
+ conditions: z.number().int().nonnegative(),
+ depth: z.number().int().nonnegative(),
+ }),
+ defaultCondition: condition.omit({ value: true }),
+ labels: z
+ .strictObject({
+ condition: z.string().min(1).optional(),
+ conditionGroup: z.string().min(1).optional(),
+ })
+ .optional(),
+ }),
+ z.strictObject({
+ type: z.literal("sort"),
+ key: z.string().min(1),
+ label: z.string().min(1),
+ defaultValue: z.array(sortItem),
+ defaultItem: sortItem,
+ directions: z.array(choice).min(1),
+ max: z.number().int().nonnegative().optional(),
+ }),
+ z.strictObject({
+ type: z.literal("expression"),
+ key: z.string().min(1),
+ label: z.string().min(1),
+ defaultValue: z.string().min(1),
+ input: z.enum(["number", "expression"]),
+ min: z.number().optional(),
+ max: z.number().optional(),
+ exclusiveMin: z.boolean().optional(),
+ exclusiveMax: z.boolean().optional(),
+ integer: z.boolean().optional(),
+ }),
+ z.strictObject({
+ type: z.literal("variant"),
+ key: z.string().min(1),
+ label: z.string().min(1),
+ defaultValue: z.json(),
+ schema: jsonSchema,
+ config: variantConfig,
+ }),
+]);
+
+export const queryDefinition = z
+ .strictObject({
+ version: z.literal(1),
+ description: z.string().min(1).optional(),
+ fields: z.array(
+ z.strictObject({
+ path: fieldPath,
+ label: z.string().min(1),
+ types: z.array(z.string().min(1)).min(1),
+ operators: z.array(z.string().min(1)).optional(),
+ })
+ ),
+ operators: z.array(
+ z.strictObject({
+ value: z.string().min(1),
+ label: z.string().min(1),
+ types: z.array(z.string().min(1)).min(1),
+ input: z.strictObject({
+ control: z.enum(["expression", "none"]),
+ defaultValue: z.string().min(1),
+ }),
+ })
+ ),
+ source: z.strictObject({
+ fieldPathSchema: jsonSchema,
+ controls: z.array(control).min(1),
+ }),
+ })
+ .superRefine(({ fields, operators, source }, context) => {
+ const fieldKeys = fields.map(({ path }) => getQueryFieldKey(path));
+ if (new Set(fieldKeys).size !== fieldKeys.length) {
+ context.addIssue({ code: "custom", message: "Fields must be unique" });
+ }
+ const operatorValues = operators.map(({ value }) => value);
+ if (new Set(operatorValues).size !== operatorValues.length) {
+ context.addIssue({ code: "custom", message: "Operators must be unique" });
+ }
+ for (const [index, operator] of operators.entries()) {
+ if (isQueryExpression(operator.input.defaultValue) === false) {
+ context.addIssue({
+ code: "custom",
+ message: "Operator defaults must be expressions",
+ path: ["operators", index, "input", "defaultValue"],
+ });
+ }
+ }
+ for (const [index, field] of fields.entries()) {
+ if (
+ field.operators?.some(
+ (operator) => operatorValues.includes(operator) === false
+ )
+ ) {
+ context.addIssue({
+ code: "custom",
+ message: "Field operators must be available",
+ path: ["fields", index, "operators"],
+ });
+ }
+ }
+ const keys = source.controls.map(({ key }) => key);
+ if (new Set(keys).size !== keys.length) {
+ context.addIssue({
+ code: "custom",
+ message: "Control keys must be unique",
+ });
+ }
+ for (const [index, item] of source.controls.entries()) {
+ if (
+ item.type === "expression" &&
+ isQueryExpression(item.defaultValue) === false
+ ) {
+ context.addIssue({
+ code: "custom",
+ message: "Expression defaults must be valid expressions",
+ path: ["source", "controls", index, "defaultValue"],
+ });
+ }
+ if (item.type === "filter") {
+ if (new Set(item.combinators).size !== item.combinators.length) {
+ context.addIssue({
+ code: "custom",
+ message: "Combinators must be unique",
+ });
+ }
+ if (
+ fieldKeys.includes(getQueryFieldKey(item.defaultCondition.field)) ===
+ false
+ ) {
+ context.addIssue({
+ code: "custom",
+ message: "Default filter field is unavailable",
+ });
+ }
+ if (operatorValues.includes(item.defaultCondition.operator) === false) {
+ context.addIssue({
+ code: "custom",
+ message: "Default filter operator is unavailable",
+ });
+ }
+ const defaultField = fields.find(
+ ({ path }) =>
+ getQueryFieldKey(path) ===
+ getQueryFieldKey(item.defaultCondition.field)
+ );
+ if (
+ defaultField !== undefined &&
+ getCompatibleQueryOperators(
+ defaultField.types,
+ operators,
+ defaultField.operators
+ ).some(({ value }) => value === item.defaultCondition.operator) ===
+ false
+ ) {
+ context.addIssue({
+ code: "custom",
+ message: "Default filter operator is incompatible with its field",
+ });
+ }
+ }
+ if (item.type === "sort") {
+ const directions = item.directions.map(({ value }) => value);
+ if (new Set(directions).size !== directions.length) {
+ context.addIssue({
+ code: "custom",
+ message: "Sort directions must be unique",
+ });
+ }
+ if (
+ fieldKeys.includes(getQueryFieldKey(item.defaultItem.field)) === false
+ ) {
+ context.addIssue({
+ code: "custom",
+ message: "Default sort field is unavailable",
+ });
+ }
+ if (directions.includes(item.defaultItem.direction) === false) {
+ context.addIssue({
+ code: "custom",
+ message: "Default sort direction is unavailable",
+ });
+ }
+ if (
+ item.defaultValue.some(
+ ({ field, direction }) =>
+ fieldKeys.includes(getQueryFieldKey(field)) === false ||
+ directions.includes(direction) === false
+ ) ||
+ (item.max !== undefined && item.defaultValue.length > item.max)
+ ) {
+ context.addIssue({
+ code: "custom",
+ message: "Default sort value is invalid",
+ });
+ }
+ }
+ if (item.type === "variant") {
+ let parser: z.ZodType | undefined;
+ try {
+ parser = z.fromJSONSchema(item.schema as never);
+ } catch {
+ context.addIssue({
+ code: "custom",
+ message: "Control JSON Schema is invalid",
+ });
+ }
+ if (parser?.safeParse(item.defaultValue).success === false) {
+ context.addIssue({
+ code: "custom",
+ message: "Control default does not match its schema",
+ });
+ }
+ const optionValues = item.config.options.map(({ value }) => value);
+ if (new Set(optionValues).size !== optionValues.length) {
+ context.addIssue({
+ code: "custom",
+ message: "Variant options must be unique",
+ });
+ }
+ for (const option of item.config.options) {
+ if (
+ option.defaultValue[item.config.discriminator] !== option.value ||
+ parser?.safeParse(option.defaultValue).success === false
+ ) {
+ context.addIssue({
+ code: "custom",
+ message: "Variant option default is invalid",
+ });
+ }
+ const fieldKeys = option.fields.map(({ key }) => key);
+ if (new Set(fieldKeys).size !== fieldKeys.length) {
+ context.addIssue({
+ code: "custom",
+ message: "Variant option fields must be unique",
+ });
+ }
+ }
+ const selection = item.config.selection;
+ if (
+ selection !== undefined &&
+ optionValues.includes(selection.emptyOption) === false
+ ) {
+ context.addIssue({
+ code: "custom",
+ message: "Selection empty option is unavailable",
+ });
+ }
+ if (
+ selection?.baseline !== undefined &&
+ item.config.options.some(
+ (option) =>
+ typeof option.defaultValue[selection.baseline?.key ?? ""] !==
+ "boolean"
+ )
+ ) {
+ context.addIssue({
+ code: "custom",
+ message: "Selection baseline must reference a boolean",
+ });
+ }
+ }
+ }
+ });
diff --git a/packages/query-builder/src/source.test.ts b/packages/query-builder/src/source.test.ts
new file mode 100644
index 0000000000..d237818b75
--- /dev/null
+++ b/packages/query-builder/src/source.test.ts
@@ -0,0 +1,276 @@
+import { describe, expect, test } from "vitest";
+import { createQuerySourceCodec } from "./source";
+import { genericQueryCapabilities, type GenericQuery } from "./test-fixtures";
+
+describe("structured query source", () => {
+ test("round-trips a provider-neutral query solely from capabilities", () => {
+ const codec = createQuerySourceCodec<
+ "string" | "date",
+ "eq" | "after",
+ GenericQuery
+ >(genericQueryCapabilities);
+ const query: GenericQuery = {
+ where: {
+ any: [
+ { field: ["title"], operator: "eq", value: "system.params.title" },
+ {
+ field: ["publishedAt"],
+ operator: "after",
+ value: '"2026-01-01"',
+ },
+ ],
+ },
+ sort: [{ field: ["publishedAt"], direction: "desc" }],
+ limit: "pageSize ?? 10",
+ offset: "0",
+ selection: { mode: "full", includeMetadata: true },
+ };
+
+ const source = codec.format(query);
+ expect(source.startsWith("({\n")).toBe(true);
+ expect(source.endsWith("})")).toBe(true);
+ expect(source).not.toContain("query:");
+ expect(codec.parse(source)).toEqual({ success: true, value: query });
+ });
+
+ test("validates declarative source parameters without a provider parser", () => {
+ const codec = createQuerySourceCodec<
+ "string" | "date",
+ "eq" | "after",
+ GenericQuery
+ >(genericQueryCapabilities);
+ const invalid = `({
+ where: { all: [] },
+ sort: [],
+ limit: 10,
+ offset: 0,
+ selection: { mode: "unsupported", includeMetadata: true },
+ })`;
+
+ expect(codec.parse(invalid)).toEqual({
+ success: false,
+ message: "Enter a valid selection.",
+ });
+ });
+
+ test("uses capability defaults when a newly introduced parameter is absent", () => {
+ const codec = createQuerySourceCodec<
+ "string" | "date",
+ "eq" | "after",
+ GenericQuery
+ >(genericQueryCapabilities);
+ const source = `({
+ where: { all: [] },
+ sort: [],
+ limit: 10,
+ offset: 0,
+ })`;
+
+ expect(codec.parse(source)).toEqual({
+ success: true,
+ value: {
+ where: { all: [] },
+ sort: [],
+ limit: "10",
+ offset: "0",
+ selection: { mode: "summary", includeMetadata: true },
+ },
+ });
+ });
+
+ test("rejects invalid and non-object query source", () => {
+ const codec = createQuerySourceCodec(genericQueryCapabilities);
+
+ expect(codec.parse("invalid").success).toBe(false);
+ expect(codec.parse("[]").success).toBe(false);
+ expect(codec.parse("({})").success).toBe(true);
+ });
+
+ test("uses only the controls declared by the provider", () => {
+ const capabilities = {
+ ...genericQueryCapabilities,
+ source: {
+ ...genericQueryCapabilities.source,
+ controls: [
+ {
+ type: "expression",
+ key: "pageSize",
+ label: "Page size",
+ defaultValue: "25",
+ input: "number",
+ },
+ ],
+ },
+ } as const;
+ const codec = createQuerySourceCodec(capabilities);
+ expect(codec.parse("({ pageSize: 50 })")).toEqual({
+ success: true,
+ value: { pageSize: "50" },
+ });
+ expect(codec.parse("({ limit: 50 })").success).toBe(false);
+ });
+
+ test("preserves unknown fields while validating known field operators", () => {
+ const codec = createQuerySourceCodec<
+ "string" | "date",
+ "eq" | "after",
+ GenericQuery
+ >(genericQueryCapabilities);
+ const source = (field: string, operator: string) => `({
+ where: { field: [${JSON.stringify(field)}], operator: ${JSON.stringify(operator)}, value: "value" },
+ sort: [],
+ limit: 10,
+ offset: 0,
+ })`;
+
+ expect(codec.parse(source("unknown", "eq")).success).toBe(true);
+ expect(codec.parse(source("title", "after")).success).toBe(false);
+ expect(
+ codec.parse(`({
+ where: { all: [] },
+ sort: [{ field: ["unknown"], direction: "asc" }],
+ limit: 10,
+ offset: 0,
+ })`).success
+ ).toBe(true);
+ });
+
+ test("uses provider-defined sort directions", () => {
+ const capabilities = {
+ ...genericQueryCapabilities,
+ source: {
+ ...genericQueryCapabilities.source,
+ controls: genericQueryCapabilities.source.controls.map((control) =>
+ control.type === "sort"
+ ? {
+ ...control,
+ defaultItem: {
+ ...control.defaultItem,
+ direction: "newest",
+ },
+ directions: [
+ { value: "newest", label: "Newest first" },
+ { value: "oldest", label: "Oldest first" },
+ ],
+ }
+ : control
+ ),
+ },
+ } as const;
+ const codec = createQuerySourceCodec(capabilities);
+ const source = (direction: string) => `({
+ where: { all: [] },
+ sort: [{ field: ["publishedAt"], direction: ${JSON.stringify(direction)} }],
+ limit: 10,
+ offset: 0,
+ })`;
+
+ expect(codec.parse(source("newest")).success).toBe(true);
+ expect(codec.parse(source("desc")).success).toBe(false);
+ });
+
+ test("honors the operator allowlist of a known field", () => {
+ const capabilities = {
+ ...genericQueryCapabilities,
+ fields: genericQueryCapabilities.fields.map((field) =>
+ field.path[0] === "publishedAt"
+ ? { ...field, operators: ["eq"] as const }
+ : field
+ ),
+ } as const;
+ const codec = createQuerySourceCodec<
+ "string" | "date",
+ "eq" | "after",
+ GenericQuery
+ >(capabilities);
+ const query: GenericQuery = {
+ where: {
+ field: ["publishedAt"],
+ operator: "after",
+ value: '"2026-01-01"',
+ },
+ sort: [],
+ limit: "10",
+ offset: "0",
+ selection: { mode: "summary", includeMetadata: true },
+ };
+
+ expect(
+ codec.parse(
+ codec.format({
+ ...query,
+ where: { ...query.where, operator: "eq" },
+ })
+ ).success
+ ).toBe(true);
+ expect(() => codec.format(query)).toThrow("Query condition is invalid");
+ expect(
+ codec.parse(`({
+ where: { field: ["publishedAt"], operator: "after", value: "2026-01-01" },
+ sort: [],
+ limit: 10,
+ offset: 0,
+ })`).success
+ ).toBe(false);
+ });
+
+ test("validates static number expressions while allowing dynamic values", () => {
+ const capabilities = {
+ ...genericQueryCapabilities,
+ source: {
+ ...genericQueryCapabilities.source,
+ controls: genericQueryCapabilities.source.controls.map((control) =>
+ control.type === "expression" && control.key === "limit"
+ ? { ...control, min: 1, max: 100, integer: true }
+ : control
+ ),
+ },
+ } as const;
+ const codec = createQuerySourceCodec(capabilities);
+ const source = (limit: string) => `({
+ where: { all: [] },
+ sort: [],
+ limit: ${limit},
+ offset: 0,
+ })`;
+
+ expect(codec.parse(source("20")).success).toBe(true);
+ expect(codec.parse(source("pageSize ?? 20")).success).toBe(true);
+ expect(codec.parse(source("20.5")).success).toBe(false);
+ expect(codec.parse(source("0")).success).toBe(false);
+ expect(codec.parse(source("101")).success).toBe(false);
+ expect(codec.parse(source('"20"')).success).toBe(false);
+ expect(codec.parse(source("null")).success).toBe(false);
+ });
+
+ test("validates exclusive number bounds", () => {
+ const capabilities = {
+ ...genericQueryCapabilities,
+ source: {
+ ...genericQueryCapabilities.source,
+ controls: genericQueryCapabilities.source.controls.map((control) =>
+ control.type === "expression" && control.key === "limit"
+ ? {
+ ...control,
+ min: 0.5,
+ max: 1.5,
+ exclusiveMin: true,
+ exclusiveMax: true,
+ }
+ : control
+ ),
+ },
+ } as const;
+ const codec = createQuerySourceCodec(capabilities);
+ const source = (limit: string) => `({
+ where: { all: [] },
+ sort: [],
+ limit: ${limit},
+ offset: 0,
+ })`;
+
+ expect(codec.parse(source("1")).success).toBe(true);
+ expect(codec.parse(source("0.5")).success).toBe(false);
+ expect(codec.parse(source("1.5")).success).toBe(false);
+ });
+});
diff --git a/packages/query-builder/src/source.ts b/packages/query-builder/src/source.ts
new file mode 100644
index 0000000000..0a7b74eb12
--- /dev/null
+++ b/packages/query-builder/src/source.ts
@@ -0,0 +1,389 @@
+import {
+ generateJsonExpression,
+ generateObjectExpression,
+ parseArrayExpression,
+ parseExpressionObject,
+ parseJsonExpression,
+} from "@webstudio-is/expression";
+import { z } from "zod";
+import type {
+ QueryExpressionControl,
+ QueryFilterControl,
+ QuerySortControl,
+ QuerySourceDefinition,
+ QuerySourceCodec,
+ QueryWhere,
+} from "./types";
+import { getQueryFieldKey, getQueryWhereMetrics } from "./runtime";
+import { getCompatibleQueryOperators } from "./query-utils";
+
+const createJsonSchemaParser = (schema: boolean | Record<string, unknown>) => {
+ let parser: z.ZodType;
+ try {
+ parser = z.fromJSONSchema(schema as never);
+ } catch {
+ parser = z.never();
+ }
+ return (value: unknown) => parser.safeParse(value);
+};
+
+export const isQueryExpression = (value: string) =>
+ value.trim() !== "" && parseArrayExpression(`[${value}]`)?.length === 1;
+
+const isFieldPath = (value: unknown): value is string[] =>
+ Array.isArray(value) && value.every((segment) => typeof segment === "string");
+
+const isControlExpressionValid = (
+ expression: string,
+ control: QueryExpressionControl
+) => {
+ if (isQueryExpression(expression) === false) {
+ return false;
+ }
+ if (control.input !== "number") {
+ return true;
+ }
+ const value = parseJsonExpression(expression);
+ if (value === undefined) {
+ return true;
+ }
+ return (
+ typeof value === "number" &&
+ (control.integer !== true || Number.isInteger(value)) &&
+ (control.min === undefined ||
+ (control.exclusiveMin ? value > control.min : value >= control.min)) &&
+ (control.max === undefined ||
+ (control.exclusiveMax ? value < control.max : value <= control.max))
+ );
+};
+
+const getFieldCapability = <FieldType extends string>(
+ field: readonly string[],
+ capabilities: Pick<QuerySourceDefinition<FieldType>, "fields">
+) =>
+ capabilities.fields.find(
+ ({ path }) => getQueryFieldKey(path) === getQueryFieldKey(field)
+ );
+
+const isOperatorCompatible = <
+ FieldType extends string,
+ Operator extends string,
+>({
+ field,
+ operator,
+ capabilities,
+}: {
+ field: string[];
+ operator: string;
+ capabilities: QuerySourceDefinition<FieldType, Operator>;
+}) => {
+ const operatorCapability = capabilities.operators.find(
+ ({ value }) => value === operator
+ );
+ if (operatorCapability === undefined) {
+ return false;
+ }
+ const fieldCapability = getFieldCapability(field, capabilities);
+ if (fieldCapability === undefined) {
+ return true;
+ }
+ return getCompatibleQueryOperators(
+ fieldCapability.types,
+ capabilities.operators,
+ fieldCapability.operators
+ ).includes(operatorCapability);
+};
+
+const parseWhere = <FieldType extends string, Operator extends string>({
+ expression,
+ capabilities,
+ control,
+ parseFieldPath,
+ depth = 0,
+}: {
+ expression: string;
+ capabilities: QuerySourceDefinition<FieldType, Operator>;
+ control: QueryFilterControl<Operator>;
+ parseFieldPath: ReturnType<typeof createJsonSchemaParser>;
+ depth?: number;
+}): QueryWhere<string[], Operator> | undefined => {
+ if (depth > control.limits.depth) {
+ return;
+ }
+ const fields = parseExpressionObject(expression);
+ if (fields === undefined) {
+ return;
+ }
+ const combinator = fields.has("all")
+ ? "all"
+ : fields.has("any")
+ ? "any"
+ : undefined;
+ if (combinator !== undefined) {
+ if (
+ fields.size !== 1 ||
+ control.combinators.includes(combinator) === false
+ ) {
+ return;
+ }
+ const items = parseArrayExpression(fields.get(combinator) ?? "");
+ if (items === undefined) {
+ return;
+ }
+ const children = items.map((item) =>
+ parseWhere({
+ expression: item,
+ capabilities,
+ control,
+ parseFieldPath,
+ depth: depth + 1,
+ })
+ );
+ if (children.some((child) => child === undefined)) {
+ return;
+ }
+ return combinator === "all"
+ ? { all: children as QueryWhere<string[], Operator>[] }
+ : { any: children as QueryWhere<string[], Operator>[] };
+ }
+
+ const field = parseJsonExpression(fields.get("field"));
+ const operator = parseJsonExpression(fields.get("operator"));
+ const value = fields.get("value");
+ if (
+ fields.size !== 3 ||
+ parseFieldPath(field).success === false ||
+ isFieldPath(field) === false ||
+ typeof operator !== "string" ||
+ isOperatorCompatible({
+ field,
+ operator,
+ capabilities,
+ }) === false ||
+ value === undefined ||
+ isQueryExpression(value) === false
+ ) {
+ return;
+ }
+ return { field, operator: operator as Operator, value };
+};
+
+const formatWhere = <FieldType extends string, Operator extends string>({
+ where,
+ capabilities,
+ control,
+ parseFieldPath,
+ depth = 0,
+}: {
+ where: QueryWhere<string[], Operator>;
+ capabilities: QuerySourceDefinition<FieldType, Operator>;
+ control: QueryFilterControl<Operator>;
+ parseFieldPath: ReturnType<typeof createJsonSchemaParser>;
+ depth?: number;
+}): string => {
+ if (depth > control.limits.depth) {
+ throw new Error("Query filter nesting limit was exceeded");
+ }
+ if ("field" in where === false) {
+ const combinator = "all" in where ? "all" : "any";
+ if (control.combinators.includes(combinator) === false) {
+ throw new Error("Query combinator is unsupported");
+ }
+ const children = ("all" in where ? where.all : where.any).map((child) =>
+ formatWhere({
+ where: child,
+ capabilities,
+ control,
+ parseFieldPath,
+ depth: depth + 1,
+ })
+ );
+ return generateObjectExpression(
+ new Map([[combinator, `[${children.join(",")}]`]])
+ );
+ }
+ if (
+ parseFieldPath(where.field).success === false ||
+ isOperatorCompatible({
+ field: where.field,
+ operator: where.operator,
+ capabilities,
+ }) === false ||
+ isQueryExpression(where.value) === false
+ ) {
+ throw new Error("Query condition is invalid");
+ }
+ return generateObjectExpression(
+ new Map([
+ ["field", JSON.stringify(where.field)],
+ ["operator", JSON.stringify(where.operator)],
+ ["value", where.value],
+ ])
+ );
+};
+
+export const createQuerySourceCodec = <
+ FieldType extends string,
+ Operator extends string,
+ Query extends Record<string, unknown>,
+>(
+ capabilities: QuerySourceDefinition<FieldType, Operator>
+): QuerySourceCodec<Query> => {
+ const parseFieldPath = createJsonSchemaParser(
+ capabilities.source.fieldPathSchema
+ );
+ const variantParsers = new Map(
+ capabilities.source.controls.flatMap((control) =>
+ control.type === "variant"
+ ? [[control.key, createJsonSchemaParser(control.schema)] as const]
+ : []
+ )
+ );
+ const parseSort = (value: unknown, control: QuerySortControl) => {
+ if (
+ Array.isArray(value) === false ||
+ (control.max !== undefined && value.length > control.max)
+ ) {
+ return;
+ }
+ const directions = new Set(control.directions.map(({ value }) => value));
+ const items = value.map((item) => {
+ if (
+ typeof item !== "object" ||
+ item === null ||
+ Object.keys(item).length !== 2 ||
+ !("field" in item) ||
+ !("direction" in item) ||
+ parseFieldPath(item.field).success === false ||
+ isFieldPath(item.field) === false ||
+ typeof item.direction !== "string" ||
+ directions.has(item.direction) === false
+ ) {
+ return;
+ }
+ return { field: item.field, direction: item.direction };
+ });
+ return items.some((item) => item === undefined) ? undefined : items;
+ };
+ return {
+ parse: (source) => {
+ const expressions = parseExpressionObject(source);
+ const controls = capabilities.source.controls;
+ if (
+ expressions === undefined ||
+ [...expressions.keys()].some(
+ (key) => controls.some((control) => control.key === key) === false
+ )
+ ) {
+ return { success: false, message: "Complete every query field." };
+ }
+ const value: Record<string, unknown> = {};
+ for (const control of controls) {
+ const expression =
+ expressions.get(control.key) ??
+ (control.type === "expression"
+ ? control.defaultValue
+ : generateJsonExpression(control.defaultValue));
+ if (control.type === "expression") {
+ if (isControlExpressionValid(expression, control) === false) {
+ return {
+ success: false,
+ message: `Enter a valid ${control.label.toLowerCase()}.`,
+ };
+ }
+ value[control.key] = expression;
+ continue;
+ }
+ if (control.type === "filter") {
+ const where = parseWhere({
+ expression,
+ capabilities,
+ control,
+ parseFieldPath,
+ });
+ const metrics =
+ where === undefined ? undefined : getQueryWhereMetrics(where);
+ if (
+ where === undefined ||
+ metrics === undefined ||
+ metrics.conditions > control.limits.conditions ||
+ metrics.depth > control.limits.depth
+ ) {
+ return {
+ success: false,
+ message: `Enter valid ${control.label.toLowerCase()}.`,
+ };
+ }
+ value[control.key] = where;
+ continue;
+ }
+ const parsedJson = parseJsonExpression(expression);
+ if (control.type === "sort") {
+ const sort = parseSort(parsedJson, control);
+ if (sort === undefined) {
+ return {
+ success: false,
+ message: `Enter valid ${control.label.toLowerCase()}.`,
+ };
+ }
+ value[control.key] = sort;
+ continue;
+ }
+ const parsed = variantParsers.get(control.key)?.(parsedJson);
+ if (parsed?.success !== true) {
+ return {
+ success: false,
+ message: `Enter a valid ${control.label.toLowerCase()}.`,
+ };
+ }
+ value[control.key] = parsed.data;
+ }
+ return { success: true, value: value as Query };
+ },
+ format: (query) => {
+ const fields = new Map<string, string>();
+ for (const control of capabilities.source.controls) {
+ const value =
+ query[control.key] ?? structuredClone(control.defaultValue);
+ if (control.type === "expression") {
+ if (
+ typeof value !== "string" ||
+ isControlExpressionValid(value, control) === false
+ ) {
+ throw new Error(`Query ${control.key} is invalid`);
+ }
+ fields.set(control.key, value);
+ continue;
+ }
+ if (control.type === "filter") {
+ const where = value as QueryWhere<string[], Operator>;
+ const metrics = getQueryWhereMetrics(where);
+ if (
+ metrics.conditions > control.limits.conditions ||
+ metrics.depth > control.limits.depth
+ ) {
+ throw new Error("Query filter limits were exceeded");
+ }
+ fields.set(
+ control.key,
+ formatWhere({ where, capabilities, control, parseFieldPath })
+ );
+ continue;
+ }
+ if (control.type === "sort") {
+ if (parseSort(value, control) === undefined) {
+ throw new Error(`Query ${control.key} is invalid`);
+ }
+ fields.set(control.key, generateJsonExpression(value));
+ continue;
+ }
+ const parsed = variantParsers.get(control.key)?.(value);
+ if (parsed?.success !== true) {
+ throw new Error(`Query ${control.key} is invalid`);
+ }
+ fields.set(control.key, generateJsonExpression(parsed.data));
+ }
+ return `(${generateObjectExpression(fields)})`;
+ },
+ };
+};
diff --git a/packages/query-builder/src/test-fixtures.ts b/packages/query-builder/src/test-fixtures.ts
new file mode 100644
index 0000000000..dc3f0c6c4b
--- /dev/null
+++ b/packages/query-builder/src/test-fixtures.ts
@@ -0,0 +1,136 @@
+import type { QueryDefinition } from "./types";
+
+export const genericQueryCapabilities = {
+ version: 1,
+ fields: [
+ { path: ["title"], label: "Title", types: ["string"] },
+ { path: ["publishedAt"], label: "Published at", types: ["date"] },
+ ],
+ operators: [
+ {
+ value: "eq",
+ label: "Equals",
+ types: ["string", "date"],
+ input: { control: "expression", defaultValue: '""' },
+ },
+ {
+ value: "after",
+ label: "After",
+ types: ["date"],
+ input: { control: "expression", defaultValue: '"2026-01-01"' },
+ },
+ ],
+ source: {
+ fieldPathSchema: {
+ type: "array",
+ items: { type: "string" },
+ minItems: 1,
+ },
+ controls: [
+ {
+ type: "filter",
+ key: "where",
+ label: "Filters",
+ defaultValue: { all: [] },
+ combinators: ["all", "any"],
+ limits: { conditions: 8, depth: 3 },
+ defaultCondition: { field: ["title"], operator: "eq" },
+ },
+ {
+ type: "sort",
+ key: "sort",
+ label: "Sort",
+ defaultValue: [],
+ defaultItem: { field: ["publishedAt"], direction: "desc" },
+ directions: [
+ { value: "asc", label: "Ascending" },
+ { value: "desc", label: "Descending" },
+ ],
+ max: 2,
+ },
+ {
+ type: "expression",
+ key: "limit",
+ label: "Limit",
+ defaultValue: "10",
+ input: "number",
+ },
+ {
+ type: "expression",
+ key: "offset",
+ label: "Offset",
+ defaultValue: "0",
+ input: "number",
+ },
+ {
+ type: "variant",
+ key: "selection",
+ label: "Selection",
+ defaultValue: { mode: "summary", includeMetadata: true },
+ schema: {
+ type: "object",
+ properties: {
+ mode: { enum: ["summary", "full", "fields"] },
+ includeMetadata: { type: "boolean" },
+ fields: {
+ type: "array",
+ items: {
+ type: "array",
+ items: { type: "string" },
+ minItems: 1,
+ },
+ },
+ },
+ required: ["mode", "includeMetadata"],
+ additionalProperties: false,
+ },
+ config: {
+ discriminator: "mode",
+ options: [
+ {
+ value: "summary",
+ label: "Summary",
+ defaultValue: { mode: "summary", includeMetadata: true },
+ fields: [],
+ },
+ {
+ value: "full",
+ label: "Full",
+ defaultValue: { mode: "full", includeMetadata: true },
+ fields: [],
+ },
+ {
+ value: "fields",
+ label: "Fields",
+ defaultValue: {
+ mode: "fields",
+ includeMetadata: true,
+ fields: [],
+ },
+ fields: [
+ {
+ key: "fields",
+ label: "Fields",
+ type: "field-list",
+ max: 2,
+ },
+ ],
+ },
+ ],
+ },
+ },
+ ],
+ },
+} as const satisfies QueryDefinition<"string" | "date", "eq" | "after">;
+
+export type GenericQuery = {
+ where: import("./types").QueryWhere<string[], "eq" | "after">;
+ sort: import("./types").QuerySort<string[]>[];
+ limit: string;
+ offset: string;
+ selection: {
+ mode: "summary" | "full" | "fields";
+ includeMetadata: boolean;
+ fields?: string[][];
+ };
+};
diff --git a/packages/query-builder/src/types.ts b/packages/query-builder/src/types.ts
new file mode 100644
index 0000000000..845c8aac83
--- /dev/null
+++ b/packages/query-builder/src/types.ts
@@ -0,0 +1,174 @@
+export type QueryCondition<Field = string[], Operator = string> = {
+ field: Field;
+ operator: Operator;
+ value: string;
+};
+
+export type QueryWhereTree<Condition> =
+ | Condition
+ | { all: QueryWhereTree<Condition>[] }
+ | { any: QueryWhereTree<Condition>[] };
+
+export type QueryWhere<Field = string[], Operator = string> = QueryWhereTree<
+ QueryCondition<Field, Operator>
+>;
+
+export type QueryGroup<Field = string[], Operator = string> =
+ | { all: QueryWhere<Field, Operator>[] }
+ | { any: QueryWhere<Field, Operator>[] };
+
+export type QuerySort<Field = string[]> = {
+ field: Field;
+ direction: string;
+};
+
+export type QueryField<FieldType extends string = string> = {
+ path: string[];
+ label: string;
+ types: readonly FieldType[];
+ operators?: readonly string[];
+};
+
+export type QueryOperator<
+ FieldType extends string = string,
+ Operator extends string = string,
+> = {
+ value: Operator;
+ label: string;
+ types: readonly FieldType[];
+ input: {
+ control: "expression" | "none";
+ defaultValue: string;
+ };
+};
+
+export type QueryNumberControl = {
+ key: string;
+ label: string;
+ type: "number";
+ min?: number;
+ max?: number;
+ exclusiveMin?: boolean;
+ exclusiveMax?: boolean;
+ integer?: boolean;
+ optional?: boolean;
+};
+
+export type QueryFieldListControl = {
+ key: string;
+ label: string;
+ type: "field-list";
+ max?: number;
+};
+
+export type QueryParameterControlField =
+ | QueryNumberControl
+ | QueryFieldListControl;
+
+export type QueryVariantControl = {
+ type: "variant";
+ key: string;
+ label: string;
+ defaultValue: unknown;
+ schema: boolean | Record<string, unknown>;
+ config: {
+ discriminator: string;
+ selection?: {
+ label: string;
+ emptyOption: string;
+ baseline?: {
+ key: string;
+ label: string;
+ };
+ };
+ options: readonly {
+ value: string;
+ label: string;
+ defaultValue: Record<string, unknown>;
+ fields: readonly QueryParameterControlField[];
+ }[];
+ };
+};
+
+export type QueryFilterControl<Operator extends string = string> = {
+ type: "filter";
+ key: string;
+ label: string;
+ defaultValue: QueryWhere<string[], Operator>;
+ combinators: readonly ("all" | "any")[];
+ limits: { conditions: number; depth: number };
+ defaultCondition: Omit<QueryCondition<string[], Operator>, "value">;
+ labels?: { condition?: string; conditionGroup?: string };
+};
+
+export type QuerySortControl = {
+ type: "sort";
+ key: string;
+ label: string;
+ defaultValue: QuerySort<string[]>[];
+ defaultItem: QuerySort<string[]>;
+ directions: readonly { value: string; label: string }[];
+ max?: number;
+};
+
+export type QueryExpressionControl = {
+ type: "expression";
+ key: string;
+ label: string;
+ defaultValue: string;
+ input: "number" | "expression";
+ min?: number;
+ max?: number;
+ exclusiveMin?: boolean;
+ exclusiveMax?: boolean;
+ integer?: boolean;
+};
+
+export type QueryControl<Operator extends string = string> =
+ | QueryFilterControl<Operator>
+ | QuerySortControl
+ | QueryExpressionControl
+ | QueryVariantControl;
+
+export type QueryDefinition<
+ FieldType extends string = string,
+ Operator extends string = string,
+> = {
+ version: 1;
+ description?: string;
+ fields: readonly QueryField<FieldType>[];
+ operators: readonly QueryOperator<FieldType, Operator>[];
+ source: {
+ fieldPathSchema: boolean | Record<string, unknown>;
+ controls: readonly QueryControl<Operator>[];
+ };
+};
+
+export type QuerySourceVariantControl = Pick<
+ QueryVariantControl,
+ "type" | "key" | "label" | "defaultValue" | "schema"
+>;
+
+export type QuerySourceDefinition<
+ FieldType extends string = string,
+ Operator extends string = string,
+> = Pick<QueryDefinition<FieldType, Operator>, "fields" | "operators"> & {
+ source: {
+ fieldPathSchema: boolean | Record<string, unknown>;
+ controls: readonly (
+ | QueryFilterControl<Operator>
+ | QuerySortControl
+ | QueryExpressionControl
+ | QuerySourceVariantControl
+ )[];
+ };
+};
+
+export type QuerySourceResult<Query> =
+ | { success: true; value: Query }
+ | { success: false; message: string };
+
+export type QuerySourceCodec<Query> = {
+ parse: (source: string) => QuerySourceResult<Query>;
+ format: (query: Query) => string;
+};
diff --git a/packages/query-builder/tsconfig.dts.json b/packages/query-builder/tsconfig.dts.json
new file mode 100644
index 0000000000..55fefbdc46
--- /dev/null
+++ b/packages/query-builder/tsconfig.dts.json
@@ -0,0 +1,9 @@
+{
+ "extends": "./tsconfig.json",
+ "include": ["src/index.ts"],
+ "compilerOptions": {
+ "noCheck": true,
+ "declarationDir": "lib/types",
+ "rootDir": "./src"
+ }
+}
diff --git a/packages/query-builder/tsconfig.json b/packages/query-builder/tsconfig.json
new file mode 100644
index 0000000000..ec19b304db
--- /dev/null
+++ b/packages/query-builder/tsconfig.json
@@ -0,0 +1,4 @@
+{
+ "extends": "@webstudio-is/tsconfig/base.json",
+ "include": ["src/**/*.ts", "../../@types/**/*.d.ts"]
+}
diff --git a/packages/react-sdk/package.json b/packages/react-sdk/package.json
index 22df562b54..df0829dfdd 100644
--- a/packages/react-sdk/package.json
+++ b/packages/react-sdk/package.json
@@ -31,6 +31,7 @@
},
"dependencies": {
"@webstudio-is/css-engine": "workspace:*",
+ "@webstudio-is/expression": "workspace:*",
"@webstudio-is/fonts": "workspace:*",
"@webstudio-is/icons": "workspace:^",
"@webstudio-is/image": "workspace:*",
diff --git a/packages/react-sdk/src/component-generator.ts b/packages/react-sdk/src/component-generator.ts
index e24de519a4..aa0e7f1cef 100644
--- a/packages/react-sdk/src/component-generator.ts
+++ b/packages/react-sdk/src/component-generator.ts
@@ -13,7 +13,6 @@ import {
parseComponentName,
generateExpression,
decodeDataSourceVariable,
- transpileExpression,
blockComponent,
blockTemplateComponent,
collectionComponent,
@@ -21,6 +20,7 @@ import {
getIndexesWithinAncestors,
elementComponent,
} from "@webstudio-is/sdk";
+import { transpileExpression } from "@webstudio-is/expression";
import { indexProperty, tagProperty } from "@webstudio-is/sdk/runtime";
import { isAttributeNameSafe, showAttribute } from "./props";
import { standardAttributesToReactProps } from "./__generated__/standard-attributes";
diff --git a/packages/sdk-components-react/package.json b/packages/sdk-components-react/package.json
index 95507eca34..aec2175169 100644
--- a/packages/sdk-components-react/package.json
+++ b/packages/sdk-components-react/package.json
@@ -33,6 +33,11 @@
"types": "./lib/types/hooks.d.ts",
"import": "./lib/hooks.js"
},
+ "./markdown": {
+ "webstudio": "./src/markdown.ts",
+ "types": "./lib/types/markdown.d.ts",
+ "import": "./lib/markdown.js"
+ },
"./templates": {
"webstudio": "./src/templates.ts",
"types": "./lib/types/templates.d.ts",
@@ -59,19 +64,27 @@
"@webstudio-is/sdk": "workspace:*",
"await-interaction-response": "^0.0.2",
"colord": "^2.9.3",
+ "github-slugger": "2.0.0",
+ "mdast-util-from-markdown": "2.0.3",
+ "mdast-util-frontmatter": "2.0.1",
+ "mdast-util-to-string": "4.0.0",
"micromark": "^4.0.2",
- "micromark-extension-gfm-table": "^2.1.1"
+ "micromark-extension-frontmatter": "2.0.0",
+ "micromark-extension-gfm": "^3.0.0",
+ "sanitize-html": "2.17.6"
},
"devDependencies": {
"@testing-library/dom": "^10.4.0",
"@testing-library/react": "^16.2.0",
"@types/react": "^18.2.70",
"@types/react-dom": "^18.2.25",
+ "@types/sanitize-html": "2.16.1",
"@webstudio-is/design-system": "workspace:*",
"@webstudio-is/generate-arg-types": "workspace:*",
"@webstudio-is/sdk-cli": "workspace:*",
"@webstudio-is/template": "workspace:*",
"@webstudio-is/tsconfig": "workspace:*",
+ "micromark-util-types": "2.0.2",
"nanostores": "^0.11.3",
"react": "18.3.0-canary-14898b6a9-20240318",
"react-dom": "18.3.0-canary-14898b6a9-20240318",
diff --git a/packages/sdk-components-react/src/markdown-embed.test.tsx b/packages/sdk-components-react/src/markdown-embed.test.tsx
new file mode 100644
index 0000000000..501acaea06
--- /dev/null
+++ b/packages/sdk-components-react/src/markdown-embed.test.tsx
@@ -0,0 +1,91 @@
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, test } from "vitest";
+import { MarkdownEmbed } from "./markdown-embed";
+
+describe("MarkdownEmbed", () => {
+ test("adds stable unique IDs to ATX and setext headings", () => {
+ const html = renderToStaticMarkup(
+ <MarkdownEmbed
+ code={`
+# Hello, world!
+
+Hello, world!
+-------------
+
+## **Formatted** heading
+
+## 你好
+
+## 😀
+ `}
+ />
+ );
+
+ expect(html).toContain('<h1 id="hello-world">Hello, world!</h1>');
+ expect(html).toContain('<h2 id="hello-world-1">Hello, world!</h2>');
+ expect(html).toContain(
+ '<h2 id="formatted-heading"><strong>Formatted</strong> heading</h2>'
+ );
+ expect(html).toContain('<h2 id="你好">你好</h2>');
+ expect(html).toContain('<h2 id="heading">😀</h2>');
+ });
+
+ test("renders safe embeds and removes executable HTML", () => {
+ const html = renderToStaticMarkup(
+ <MarkdownEmbed
+ code={`
+<figure class="video">
+ <iframe src="https://player.vimeo.com/video/123" title="Demo" allowfullscreen></iframe>
+ <figcaption>Demo video</figcaption>
+</figure>
+<script>alert("unsafe")</script>
+<img src="javascript:alert('unsafe')" onerror="alert('unsafe')">
+<a href="javascript:alert('unsafe')">Unsafe link</a>
+<iframe src="data:text/html,unsafe" srcdoc="<script>alert('unsafe')</script>"></iframe>
+<img src="blob:https://example.com/unsafe">
+<input type="text" value="unsafe">
+
+![Safe image](https://example.com/image.png)
+ `}
+ />
+ );
+
+ expect(html).toContain('<figure class="video">');
+ expect(html).toContain(
+ '<iframe src="https://player.vimeo.com/video/123" title="Demo" allowfullscreen></iframe>'
+ );
+ expect(html).toContain("<figcaption>Demo video</figcaption>");
+ expect(html).toContain(
+ '<img src="https://example.com/image.png" alt="Safe image" />'
+ );
+ expect(html).not.toContain("<script");
+ expect(html).not.toContain("javascript:");
+ expect(html).not.toContain("onerror");
+ expect(html).not.toContain("srcdoc");
+ expect(html).not.toContain("data:text/html");
+ expect(html).not.toContain("blob:");
+ expect(html).not.toContain('type="text"');
+ });
+
+ test("renders the complete GFM dialect", () => {
+ const html = renderToStaticMarkup(
+ <MarkdownEmbed
+ code={`~~done~~\n\n- [x] Published\n\nhttps://example.com\n\n| A | B |\n| - | - |\n| 1 | 2 |`}
+ />
+ );
+
+ expect(html).toContain("<del>done</del>");
+ expect(html).toContain('type="checkbox"');
+ expect(html).toContain('<a href="https://example.com">');
+ expect(html).toContain("<table>");
+ });
+
+ test("does not render YAML frontmatter or treat it as a heading", () => {
+ const html = renderToStaticMarkup(
+ <MarkdownEmbed code={`---\ntitle: Hidden\n---\n# Visible`} />
+ );
+
+ expect(html).toContain('<h1 id="visible">Visible</h1>');
+ expect(html).not.toContain("title: Hidden");
+ });
+});
diff --git a/packages/sdk-components-react/src/markdown-embed.tsx b/packages/sdk-components-react/src/markdown-embed.tsx
index b48574ca48..8776abc0af 100644
--- a/packages/sdk-components-react/src/markdown-embed.tsx
+++ b/packages/sdk-components-react/src/markdown-embed.tsx
@@ -1,6 +1,5 @@
-import { micromark } from "micromark";
-import { gfmTable, gfmTableHtml } from "micromark-extension-gfm-table";
import { forwardRef, useMemo, type ComponentProps } from "react";
+import { renderMarkdownHtml } from "./markdown";
type MarkdownEmbedProps = ComponentProps<"div"> & {
code: string;
@@ -15,12 +14,7 @@ export const MarkdownEmbed = /* @__PURE__ */ forwardRef<
const { code, children, ...rest } = props;
const html = useMemo(
// support data uri protocol in images
- () =>
- micromark(code ?? "", {
- allowDangerousProtocol: true,
- extensions: [gfmTable()],
- htmlExtensions: [gfmTableHtml()],
- }),
+ () => renderMarkdownHtml(code ?? ""),
[code]
);
return <div {...rest} ref={ref} dangerouslySetInnerHTML={{ __html: html }} />;
diff --git a/packages/sdk-components-react/src/markdown.ts b/packages/sdk-components-react/src/markdown.ts
new file mode 100644
index 0000000000..893448f7cf
--- /dev/null
+++ b/packages/sdk-components-react/src/markdown.ts
@@ -0,0 +1,164 @@
+import { micromark } from "micromark";
+import { gfm, gfmHtml } from "micromark-extension-gfm";
+import { frontmatter } from "micromark-extension-frontmatter";
+import { fromMarkdown } from "mdast-util-from-markdown";
+import { frontmatterFromMarkdown } from "mdast-util-frontmatter";
+import { toString } from "mdast-util-to-string";
+import GithubSlugger from "github-slugger";
+import type { HtmlExtension } from "micromark-util-types";
+import sanitizeHtml from "sanitize-html";
+
+const getHeadingIds = (markdown: string) => {
+ const slugger = new GithubSlugger();
+ const ids: string[] = [];
+ const visit = (node: unknown) => {
+ if (typeof node !== "object" || node === null) {
+ return;
+ }
+ if ("type" in node && node.type === "heading") {
+ const text = toString(node as Parameters<typeof toString>[0]);
+ ids.push(slugger.slug(text) || slugger.slug("heading"));
+ }
+ if ("children" in node && Array.isArray(node.children)) {
+ for (const child of node.children) {
+ visit(child);
+ }
+ }
+ };
+ visit(
+ fromMarkdown(markdown, {
+ extensions: [frontmatter(["yaml"])],
+ mdastExtensions: [frontmatterFromMarkdown(["yaml"])],
+ })
+ );
+ return ids;
+};
+
+const createHeadingIdsHtmlExtension = (
+ headingIds: readonly string[]
+): HtmlExtension => {
+ let headingIndex = 0;
+ const takeHeadingId = () => headingIds[headingIndex++] ?? "heading";
+ return {
+ exit: {
+ atxHeadingSequence(token) {
+ if (this.getData("headingRank") !== undefined) {
+ return;
+ }
+ const rank = this.sliceSerialize(token).length;
+ this.setData("headingRank", rank);
+ this.lineEndingIfNeeded();
+ this.tag(`<h${rank} id="${this.encode(takeHeadingId())}">`);
+ },
+ setextHeading() {
+ const value = this.resume();
+ const rank = this.getData("headingRank");
+ this.lineEndingIfNeeded();
+ this.tag(`<h${rank} id="${this.encode(takeHeadingId())}">`);
+ this.raw(value);
+ this.tag(`</h${rank}>`);
+ this.setData("slurpAllLineEndings");
+ this.setData("headingRank");
+ },
+ },
+ };
+};
+
+const sanitizeMarkdownHtml = (
+ html: string,
+ { allowBlobImages }: { allowBlobImages: boolean }
+) =>
+ sanitizeHtml(html, {
+ allowedTags: [
+ ...sanitizeHtml.defaults.allowedTags,
+ "audio",
+ "del",
+ "details",
+ "iframe",
+ "img",
+ "input",
+ "picture",
+ "source",
+ "summary",
+ "video",
+ ],
+ allowedAttributes: {
+ ...sanitizeHtml.defaults.allowedAttributes,
+ "*": [
+ "aria-*",
+ "class",
+ "data-*",
+ "dir",
+ "id",
+ "lang",
+ "role",
+ "tabindex",
+ "title",
+ ],
+ audio: ["autoplay", "controls", "loop", "muted", "preload", "src"],
+ iframe: [
+ "allow",
+ "allowfullscreen",
+ "frameborder",
+ "height",
+ "loading",
+ "referrerpolicy",
+ "src",
+ "width",
+ ],
+ img: ["alt", "height", "loading", "sizes", "src", "srcset", "width"],
+ input: ["checked", "disabled", "type"],
+ source: ["media", "sizes", "src", "srcset", "type"],
+ video: [
+ "autoplay",
+ "controls",
+ "height",
+ "loop",
+ "muted",
+ "playsinline",
+ "poster",
+ "preload",
+ "src",
+ "width",
+ ],
+ },
+ allowedSchemesByTag: {
+ audio: ["data", "http", "https"],
+ iframe: ["http", "https"],
+ img: [...(allowBlobImages ? ["blob"] : []), "data", "http", "https"],
+ source: ["data", "http", "https"],
+ video: ["data", "http", "https"],
+ },
+ allowProtocolRelative: false,
+ exclusiveFilter: ({ tag, attribs }) =>
+ tag === "input" &&
+ (attribs.type !== "checkbox" || attribs.disabled === undefined),
+ });
+
+const createGfmHtmlExtension = () => {
+ const extension = gfmHtml();
+ // GFM tag filtering escapes embedded HTML before our stricter sanitizer can
+ // inspect it. Remove only those handlers and keep every other GFM renderer;
+ // sanitizeMarkdownHtml remains the security boundary for embedded markup.
+ delete extension.exit?.htmlFlowData;
+ delete extension.exit?.htmlTextData;
+ return extension;
+};
+
+/** Shared safe renderer used by both the authoring preview and published component. */
+export const renderMarkdownHtml = (
+ markdown: string,
+ { allowBlobImages = false }: { allowBlobImages?: boolean } = {}
+) =>
+ sanitizeMarkdownHtml(
+ micromark(markdown, {
+ allowDangerousHtml: true,
+ allowDangerousProtocol: true,
+ extensions: [frontmatter(["yaml"]), gfm()],
+ htmlExtensions: [
+ createGfmHtmlExtension(),
+ createHeadingIdsHtmlExtension(getHeadingIds(markdown)),
+ ],
+ }),
+ { allowBlobImages }
+ );
diff --git a/packages/sdk/package.json b/packages/sdk/package.json
index f4c07ca762..284ecb358f 100644
--- a/packages/sdk/package.json
+++ b/packages/sdk/package.json
@@ -18,6 +18,11 @@
"types": "./lib/types/runtime.d.ts",
"import": "./lib/runtime.js"
},
+ "./asset-resource-limits": {
+ "webstudio": "./src/asset-resource-limits.ts",
+ "types": "./lib/types/asset-resource-limits.d.ts",
+ "import": "./lib/asset-resource-limits.js"
+ },
"./schema-org": {
"webstudio": "./src/schema-org.ts",
"types": "./lib/types/schema-org.d.ts",
@@ -60,17 +65,18 @@
"test": "vitest run",
"build:schema-org-data": "tsx scripts/schema-org-data.ts && oxfmt src/__generated__/schema-org-data.ts",
"build:normalize.css": "tsx --conditions=webstudio ./scripts/normalize.css.ts && oxfmt src/__generated__/normalize.css.ts",
- "build": "rm -rf lib && esbuild src/index.ts src/runtime.ts src/schema-org.ts src/link-utils.ts src/schema.ts src/__generated__/normalize.css.ts src/core-templates.tsx --outdir=lib --bundle --format=esm --packages=external",
+ "build": "rm -rf lib && esbuild src/index.ts src/runtime.ts src/asset-resource-limits.ts src/schema-org.ts src/link-utils.ts src/schema.ts src/__generated__/normalize.css.ts src/core-templates.tsx --outdir=lib --bundle --format=esm --packages=external",
"dts": "tsc --project tsconfig.dts.json"
},
"dependencies": {
+ "@webstudio-is/content-engine": "workspace:*",
+ "@webstudio-is/expression": "workspace:*",
"@emotion/hash": "^0.9.2",
"@webstudio-is/css-engine": "workspace:*",
"@webstudio-is/fonts": "workspace:*",
"@webstudio-is/icons": "workspace:*",
+ "@webstudio-is/query-builder": "workspace:*",
"@webstudio-is/wsauth": "workspace:*",
- "acorn": "^8.14.1",
- "acorn-walk": "^8.3.4",
"change-case": "^5.4.4",
"json-schema-typed": "^8.0.2",
"reserved-identifiers": "^1.0.0",
@@ -79,12 +85,12 @@
"zod": "^4.4.3"
},
"devDependencies": {
+ "@types/papaparse": "^5.5.2",
"@webstudio-is/css-data": "workspace:*",
"@webstudio-is/template": "workspace:*",
"@webstudio-is/tsconfig": "workspace:*",
"html-tags": "^4.0.0",
"papaparse": "^5.5.3",
- "@types/papaparse": "^5.5.2",
"vitest": "^3.1.2"
}
}
diff --git a/packages/sdk/src/asset-folder-hierarchy.ts b/packages/sdk/src/asset-folder-hierarchy.ts
index 9c04808514..a6770003b0 100644
--- a/packages/sdk/src/asset-folder-hierarchy.ts
+++ b/packages/sdk/src/asset-folder-hierarchy.ts
@@ -9,28 +9,32 @@ export const getAssetFolderSiblingKey = (
name: string
) => JSON.stringify([parentId ?? null, normalizeAssetFolderName(name)]);
-type AssetFolderTraversal = { path: AssetFolder[]; hasCycle: boolean };
+type AssetFolderTraversal = { path: AssetFolder[]; cycleIds: string[] };
const traverseAssetFolderAncestors = (
folders: AssetFolders,
folderId: string
): AssetFolderTraversal => {
- const path: AssetFolder[] = [];
- const visited = new Set<string>();
+ const lineage: AssetFolder[] = [];
+ const positions = new Map<string, number>();
let currentId: string | undefined = folderId;
while (currentId !== undefined) {
- if (visited.has(currentId)) {
- return { path, hasCycle: true };
+ const position = positions.get(currentId);
+ if (position !== undefined) {
+ return {
+ path: lineage.toReversed(),
+ cycleIds: lineage.slice(position).map(({ id }) => id),
+ };
}
- visited.add(currentId);
const folder = folders.get(currentId);
if (folder === undefined) {
break;
}
- path.unshift(folder);
+ positions.set(currentId, lineage.length);
+ lineage.push(folder);
currentId = folder.parentId;
}
- return { path, hasCycle: false };
+ return { path: lineage.toReversed(), cycleIds: [] };
};
export const createAssetFolderHierarchy = (folders: AssetFolders) => {
@@ -88,7 +92,8 @@ export const createAssetFolderHierarchy = (folders: AssetFolders) => {
resolveFolderId,
getPath: (folderId: string | undefined) =>
folderId === undefined ? [] : getTraversal(folderId).path,
- hasCycle: (folderId: string) => getTraversal(folderId).hasCycle,
+ getCycleIds: (folderId: string) => getTraversal(folderId).cycleIds,
+ hasCycle: (folderId: string) => getTraversal(folderId).cycleIds.length > 0,
sortByDepth,
getAggregateAssetSizes: (assets: Iterable<Asset>) => {
const sizes = new Map<string, number>();
diff --git a/packages/sdk/src/asset-folder-utils.test.ts b/packages/sdk/src/asset-folder-utils.test.ts
index e8e98aa2f5..d77b4256b9 100644
--- a/packages/sdk/src/asset-folder-utils.test.ts
+++ b/packages/sdk/src/asset-folder-utils.test.ts
@@ -39,6 +39,7 @@ describe("asset folder utilities", () => {
const cyclicHierarchy = createAssetFolderHierarchy(cyclic);
expect(cyclicHierarchy.getPath("left")).toHaveLength(2);
+ expect(cyclicHierarchy.getCycleIds("left")).toEqual(["left", "right"]);
expect(cyclicHierarchy.hasCycle("left")).toBe(true);
expect(cyclicHierarchy.sortByDepth(cyclic.values())).toHaveLength(2);
});
diff --git a/packages/sdk/src/asset-resource-config.test.ts b/packages/sdk/src/asset-resource-config.test.ts
new file mode 100644
index 0000000000..f769df73b9
--- /dev/null
+++ b/packages/sdk/src/asset-resource-config.test.ts
@@ -0,0 +1,347 @@
+import { describe, expect, test, vi } from "vitest";
+import {
+ generateObjectExpression,
+ parseExpressionObject,
+} from "@webstudio-is/expression";
+import {
+ createAssetResourceRequest,
+ createDefaultStructuredAssetQueryResourceConfiguration,
+ createReachableAssetContentCompilationPlan,
+ createStructuredAssetQueryResourceBody,
+ isAssetsResource,
+ parseStructuredAssetQueryResourceBody,
+} from "./asset-resource-config";
+import { loadResource } from "./resource-loader";
+import { assetResourceLimits } from "./asset-resource-limits";
+import type { Resource } from "./schema/resources";
+
+const createResource = (overrides: Partial<Resource> = {}): Resource => ({
+ id: "posts",
+ name: "Posts",
+ control: "system",
+ method: "post",
+ url: '"/$resources/assets"',
+ headers: [],
+ ...overrides,
+});
+
+describe("asset query resource configuration", () => {
+ test("creates defaults through the stored query codec", () => {
+ const configuration =
+ createDefaultStructuredAssetQueryResourceConfiguration();
+ expect(
+ parseStructuredAssetQueryResourceBody(
+ createStructuredAssetQueryResourceBody(configuration)
+ )
+ ).toEqual(configuration);
+ });
+
+ test("enforces runtime limits for static query expressions", () => {
+ const configuration =
+ createDefaultStructuredAssetQueryResourceConfiguration();
+
+ expect(() =>
+ createStructuredAssetQueryResourceBody({
+ ...configuration,
+ limit: String(assetResourceLimits.resultCount + 1),
+ })
+ ).toThrow("Query limit is invalid");
+ expect(() =>
+ createStructuredAssetQueryResourceBody({
+ ...configuration,
+ offset: String(assetResourceLimits.candidateDocuments + 1),
+ })
+ ).toThrow("Query offset is invalid");
+ });
+
+ test("compiles only Assets queries reachable from bindings", () => {
+ const body = createStructuredAssetQueryResourceBody({
+ where: { all: [] },
+ sort: [],
+ limit: "10",
+ offset: "0",
+ output: { mode: "base", includeMetadata: true },
+ content: { mode: "none" },
+ });
+ expect(
+ createReachableAssetContentCompilationPlan({
+ props: [
+ {
+ id: "prop",
+ instanceId: "instance",
+ name: "posts",
+ type: "resource",
+ value: "used",
+ },
+ ],
+ dataSources: [],
+ resources: [
+ createResource({ id: "used", body }),
+ createResource({ id: "unused", body }),
+ ],
+ })?.queries.map(({ id }) => id)
+ ).toEqual(["used"]);
+ expect(
+ createReachableAssetContentCompilationPlan({
+ props: [],
+ dataSources: [],
+ resources: [createResource({ id: "unused", body })],
+ })
+ ).toBeUndefined();
+ });
+
+ test("compiles static JavaScript literals instead of treating them as dynamic", () => {
+ const body = createStructuredAssetQueryResourceBody({
+ where: {
+ all: [
+ {
+ field: ["properties", "status"],
+ operator: "eq",
+ value: "'published'",
+ },
+ {
+ field: ["properties", "options"],
+ operator: "eq",
+ value: "{ featured: true }",
+ },
+ ],
+ },
+ sort: [],
+ limit: "0x14",
+ offset: "0",
+ output: { mode: "base", includeMetadata: true },
+ content: { mode: "none" },
+ });
+ const plan = createReachableAssetContentCompilationPlan({
+ props: [
+ {
+ id: "prop",
+ instanceId: "instance",
+ name: "posts",
+ type: "resource",
+ value: "posts",
+ },
+ ],
+ dataSources: [],
+ resources: [createResource({ body })],
+ });
+
+ expect(plan?.queries[0]).toMatchObject({
+ where: {
+ all: [
+ { value: { type: "literal", value: "published" } },
+ { value: { type: "literal", value: { featured: true } } },
+ ],
+ },
+ limit: { type: "literal", value: 20 },
+ });
+ });
+
+ test("rejects invalid reachable Assets query configuration", () => {
+ expect(() =>
+ createReachableAssetContentCompilationPlan({
+ props: [
+ {
+ id: "prop",
+ instanceId: "instance",
+ name: "posts",
+ type: "resource",
+ value: "posts",
+ },
+ ],
+ dataSources: [],
+ resources: [createResource({ body: "invalid" })],
+ })
+ ).toThrow('Assets resource "posts" has an invalid query configuration');
+ });
+
+ test("rejects fractional pagination values", () => {
+ expect(
+ parseStructuredAssetQueryResourceBody(`({
+ query: {
+ where: { all: [] },
+ sort: [],
+ limit: 1.5,
+ offset: 0,
+ output: { mode: "base", includeMetadata: true },
+ content: { mode: "none" },
+ },
+ })`)
+ ).toBeUndefined();
+ });
+
+ test("serializes a typed Assets query through the resource transport", async () => {
+ const fetch = vi.fn<typeof globalThis.fetch>().mockResolvedValue(
+ new Response(JSON.stringify({ ok: true }), {
+ headers: { "content-type": "application/json" },
+ })
+ );
+ const resourceRequest = createAssetResourceRequest({
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "hello-world",
+ },
+ ],
+ },
+ limit: 1,
+ },
+ indexRevision: "index-7",
+ });
+
+ await loadResource(fetch, resourceRequest, "https://example.com/blog/post");
+
+ expect(fetch).toHaveBeenCalledWith("/$resources/assets", {
+ method: "post",
+ headers: new Headers([["content-type", "application/json"]]),
+ body: JSON.stringify(resourceRequest.body),
+ });
+ });
+
+ test("only recognizes exact system Assets resource contracts", () => {
+ expect(isAssetsResource(createResource())).toBe(true);
+ expect(
+ isAssetsResource(
+ createResource({ method: "get", url: '"/$resources/assets"' })
+ )
+ ).toBe(false);
+ const configured = createResource({ url: '"/$resources/assets"' });
+ expect(isAssetsResource(configured)).toBe(true);
+ expect(isAssetsResource(createResource({ control: undefined }))).toBe(
+ false
+ );
+ expect(
+ isAssetsResource(createResource({ url: '"/$resources/other"' }))
+ ).toBe(false);
+ expect(
+ isAssetsResource(createResource({ url: ' "/$resources/assets"' }))
+ ).toBe(false);
+ });
+
+ test("round-trips typed filters with Webstudio value expressions", () => {
+ const configuration = {
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq" as const,
+ value: "$ws$dataSource$routeSlug",
+ },
+ {
+ any: [
+ {
+ field: ["properties", "draft"],
+ operator: "ne" as const,
+ value: "true",
+ },
+ {
+ field: ["properties", "id"],
+ operator: "eq" as const,
+ value: "$ws$dataSource$routeSlug",
+ },
+ ],
+ },
+ ],
+ },
+ sort: [
+ {
+ field: ["properties", "publishedAt"],
+ direction: "desc" as const,
+ },
+ ],
+ limit: "20",
+ offset: "$ws$dataSource$offset",
+ output: { mode: "all" as const, includeMetadata: true },
+ content: { mode: "none" as const },
+ };
+ const body = createStructuredAssetQueryResourceBody(configuration);
+
+ expect(parseStructuredAssetQueryResourceBody(body)).toEqual(configuration);
+ expect(body).toContain("value: $ws$dataSource$routeSlug");
+ });
+
+ test("rejects malformed structured resource bodies", () => {
+ expect(
+ parseStructuredAssetQueryResourceBody('{ "query": { "where": 1 } }')
+ ).toBeUndefined();
+ const validBody = createStructuredAssetQueryResourceBody({
+ where: { all: [] },
+ sort: [],
+ limit: "20",
+ offset: "0",
+ output: { mode: "all", includeMetadata: true },
+ content: { mode: "none" },
+ });
+ const query = parseExpressionObject(validBody)?.get("query");
+ expect(query).toBeDefined();
+ expect(
+ parseStructuredAssetQueryResourceBody(
+ generateObjectExpression(
+ new Map([
+ ["query", query ?? ""],
+ ["other", "true"],
+ ])
+ )
+ )
+ ).toBeUndefined();
+ expect(
+ parseStructuredAssetQueryResourceBody(`{
+ query: {
+ where: { all: [] },
+ sort: [],
+ limit: 20,
+ offset: 0,
+ output: { mode: "base", includeMetadata: false },
+ content: { mode: "none" },
+ },
+ }`)
+ ).toBeUndefined();
+ expect(() =>
+ createStructuredAssetQueryResourceBody({
+ where: { all: [] },
+ sort: [],
+ limit: "20",
+ offset: "0",
+ output: { mode: "base", includeMetadata: false },
+ content: { mode: "none" },
+ })
+ ).toThrow("Select at least one asset query output");
+ });
+
+ test("preserves explicit output and defaults to URL and optional image dimensions", () => {
+ expect(
+ parseStructuredAssetQueryResourceBody(`{
+ query: {
+ where: { all: [] },
+ sort: [],
+ limit: 20,
+ offset: 0,
+ output: { mode: "base" },
+ content: { mode: "none" },
+ },
+ }`)
+ ).toMatchObject({
+ output: { mode: "base", includeMetadata: true },
+ });
+ expect(
+ parseStructuredAssetQueryResourceBody(`{
+ query: {
+ where: { all: [] },
+ sort: [],
+ limit: 20,
+ offset: 0,
+ content: { mode: "none" },
+ },
+ }`)
+ ).toMatchObject({
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["url"], ["width"], ["height"]],
+ },
+ });
+ });
+});
diff --git a/packages/sdk/src/asset-resource-config.ts b/packages/sdk/src/asset-resource-config.ts
new file mode 100644
index 0000000000..cc5d217b00
--- /dev/null
+++ b/packages/sdk/src/asset-resource-config.ts
@@ -0,0 +1,217 @@
+import {
+ createQuerySourceCodec,
+ createStructuredQuery,
+} from "@webstudio-is/query-builder";
+import {
+ mapQueryWhere,
+ type QueryWhereTree,
+} from "@webstudio-is/query-builder/runtime";
+import {
+ generateObjectExpression,
+ parseExpressionObject,
+ parseJsonExpression,
+ parseStringLiteralExpression,
+} from "@webstudio-is/expression";
+import {
+ assetQueryRequest,
+ assetQuerySourceDefinition,
+ assetResourceContentOptions,
+ createContentCompilationPlan,
+ defaultAssetResourceOutputSelection,
+ hasAssetQueryOutput,
+ type AssetObservedFieldType,
+ type AssetQueryRequestInput,
+ type AssetQueryFieldPath,
+ type AssetQueryFilter,
+ type AssetQuerySort,
+ type AssetResourceContentOptions,
+ type AssetResourceOutputSelection,
+ type ContentCompilationPlan,
+ type ContentCompilationQuery,
+ type ContentCompilationWhere,
+} from "@webstudio-is/content-engine";
+import { assetsResourceUrl } from "./resource-loader";
+import type { Resource, ResourceRequest } from "./schema/resources";
+import type { Prop } from "./schema/props";
+import type { DataSource } from "./schema/data-sources";
+
+export const createAssetResourceRequest = (
+ request: AssetQueryRequestInput
+): ResourceRequest => ({
+ name: "assets",
+ control: "system",
+ method: "post",
+ url: assetsResourceUrl,
+ searchParams: [],
+ headers: [{ name: "content-type", value: "application/json" }],
+ body: assetQueryRequest.parse(request),
+});
+
+export const hasAssetsResourceUrl = (
+ resource: Pick<Resource, "control" | "url">
+) =>
+ resource.control === "system" &&
+ parseStringLiteralExpression(resource.url) === assetsResourceUrl;
+
+export const isAssetsResource = (
+ resource: Pick<Resource, "control" | "method" | "url">
+) => resource.method === "post" && hasAssetsResourceUrl(resource);
+
+export type StructuredAssetQueryFilterBinding = {
+ field: AssetQueryFieldPath;
+ operator: AssetQueryFilter["operator"];
+ value: string;
+};
+
+export type StructuredAssetQueryWhereBinding =
+ QueryWhereTree<StructuredAssetQueryFilterBinding>;
+
+export type StructuredAssetQueryResourceConfiguration = {
+ where: StructuredAssetQueryWhereBinding;
+ sort: AssetQuerySort[];
+ limit: string;
+ offset: string;
+ output: AssetResourceOutputSelection;
+ content: AssetResourceContentOptions;
+};
+
+const toContentCompilationWhere = (
+ where: StructuredAssetQueryWhereBinding
+): ContentCompilationWhere =>
+ mapQueryWhere(where, (condition) => {
+ const value = parseJsonExpression(condition.value);
+ if (value !== undefined) {
+ return {
+ field: condition.field,
+ operator: condition.operator,
+ value: {
+ type: "literal" as const,
+ value,
+ },
+ };
+ }
+ return {
+ field: condition.field,
+ operator: condition.operator,
+ value: { type: "dynamic" as const },
+ };
+ });
+
+const toContentCompilationInteger = (expression: string) => {
+ const value = parseJsonExpression(expression);
+ if (Number.isSafeInteger(value) && Number(value) >= 0) {
+ return { type: "literal", value } as const;
+ }
+ return { type: "dynamic" } as const;
+};
+
+const createAssetContentCompilationQuery = ({
+ resourceId,
+ configuration,
+}: {
+ resourceId: string;
+ configuration: StructuredAssetQueryResourceConfiguration;
+}): ContentCompilationQuery => ({
+ id: resourceId,
+ where: toContentCompilationWhere(configuration.where),
+ sort: configuration.sort,
+ limit: toContentCompilationInteger(configuration.limit),
+ offset: toContentCompilationInteger(configuration.offset),
+ output: configuration.output,
+ content: configuration.content,
+});
+
+export const createReachableAssetContentCompilationPlan = ({
+ props,
+ dataSources,
+ resources,
+}: {
+ props: Iterable<Prop>;
+ dataSources: Iterable<DataSource>;
+ resources: Iterable<Resource>;
+}): ContentCompilationPlan | undefined => {
+ const reachableResourceIds = new Set<string>();
+ for (const prop of props) {
+ if (prop.type === "resource") {
+ reachableResourceIds.add(prop.value);
+ }
+ }
+ for (const dataSource of dataSources) {
+ if (dataSource.type === "resource") {
+ reachableResourceIds.add(dataSource.resourceId);
+ }
+ }
+ const queries = [];
+ for (const resource of resources) {
+ if (
+ reachableResourceIds.has(resource.id) === false ||
+ isAssetsResource(resource) === false
+ ) {
+ continue;
+ }
+ const configuration = parseStructuredAssetQueryResourceBody(resource.body);
+ if (configuration === undefined) {
+ throw new Error(
+ `Assets resource ${JSON.stringify(resource.id)} has an invalid query configuration`
+ );
+ }
+ queries.push(
+ createAssetContentCompilationQuery({
+ resourceId: resource.id,
+ configuration,
+ })
+ );
+ }
+ return createContentCompilationPlan(queries);
+};
+
+const assetQuerySourceCodec = createQuerySourceCodec<
+ AssetObservedFieldType,
+ AssetQueryFilter["operator"],
+ StructuredAssetQueryResourceConfiguration
+>(assetQuerySourceDefinition);
+
+export const createDefaultStructuredAssetQueryResourceConfiguration = () =>
+ createStructuredQuery<StructuredAssetQueryResourceConfiguration>(
+ assetQuerySourceDefinition
+ );
+
+export const parseStructuredAssetQueryResourceBody = (
+ body: string | undefined
+): StructuredAssetQueryResourceConfiguration | undefined => {
+ const request = parseExpressionObject(body ?? "");
+ if (request === undefined) {
+ return;
+ }
+ const query = request.get("query");
+ if (request.size !== 1 || query === undefined) {
+ return;
+ }
+ const parsed = assetQuerySourceCodec.parse(query);
+ if (parsed.success === false || hasAssetQueryOutput(parsed.value) === false) {
+ return;
+ }
+ return parsed.value;
+};
+
+export const createStructuredAssetQueryResourceBody = ({
+ where,
+ sort,
+ limit,
+ offset,
+ output = defaultAssetResourceOutputSelection,
+ content,
+}: StructuredAssetQueryResourceConfiguration) => {
+ if (hasAssetQueryOutput({ output, content }) === false) {
+ throw new Error("Select at least one asset query output");
+ }
+ const query = assetQuerySourceCodec.format({
+ where,
+ sort,
+ limit,
+ offset,
+ output,
+ content: assetResourceContentOptions.parse(content),
+ });
+ return generateObjectExpression(new Map([["query", query]]));
+};
diff --git a/packages/sdk/src/asset-resource-limits.ts b/packages/sdk/src/asset-resource-limits.ts
new file mode 100644
index 0000000000..92a30449dc
--- /dev/null
+++ b/packages/sdk/src/asset-resource-limits.ts
@@ -0,0 +1,12 @@
+import { contentEngineLimits } from "@webstudio-is/content-engine/limits";
+
+/** Webstudio Assets API limits plus the shared content-engine limits. */
+export const assetResourceLimits = {
+ ...contentEngineLimits,
+ restMutationRequestBytes: 64 * 1024,
+ assetFilenameCharacters: 512,
+ assetDescriptionCharacters: 4096,
+ assetFolderNameCharacters: 256,
+ assetIdentifierCharacters: 256,
+ apiDescriptionBytes: 512 * 1024,
+} as const;
diff --git a/packages/sdk/src/expression.test.ts b/packages/sdk/src/expression.test.ts
index 0aa421acd7..3a232a7b41 100644
--- a/packages/sdk/src/expression.test.ts
+++ b/packages/sdk/src/expression.test.ts
@@ -1,839 +1,27 @@
-import { describe, expect, test } from "vitest";
-import { parseExpressionAt } from "acorn";
+import { expect, test } from "vitest";
import {
- type Diagnostic,
decodeDataVariableId,
encodeDataVariableId,
executeExpression,
- isLiteralExpression,
- lintExpression,
- transpileExpression,
- getExpressionIdentifiers,
- parseObjectExpression,
- generateObjectExpression,
SYSTEM_VARIABLE_ID,
- allowedArrayMethods,
- allowedStringMethods,
} from "./expression";
-describe("lint expression", () => {
- const error = (from: number, to: number, message: string): Diagnostic => ({
- from,
- to,
- severity: "error",
- message,
- });
-
- const warn = (from: number, to: number, message: string): Diagnostic => ({
- from,
- to,
- severity: "warning",
- message,
- });
-
- test("forbid empty expression", () => {
- expect(lintExpression({ expression: `` })).toEqual([
- error(0, 0, `Expression cannot be empty`),
- ]);
- expect(lintExpression({ expression: ` ` })).toEqual([
- error(0, 0, `Expression cannot be empty`),
- ]);
- });
-
- test("output parse error as diagnostic", () => {
- expect(lintExpression({ expression: `a + ` })).toEqual([
- error(4, 4, "Unexpected token"),
- ]);
- expect(lintExpression({ expression: `"string" + a)` })).toEqual([
- error(13, 13, "Unexpected token"),
- ]);
- });
-
- test("restrict expression syntax", () => {
- expect(lintExpression({ expression: `var a = 1` })).toEqual([
- error(0, 0, "Unexpected token"),
- ]);
- });
-
- test("lint whole expression instead of only first valid part", () => {
- expect(
- lintExpression({ expression: `a""`, availableVariables: new Set(["a"]) })
- ).toEqual([error(1, 1, `Unexpected token`)]);
- expect(
- lintExpression({
- expression: `/movie/{{CollectionItem['title']}}\n`,
- availableVariables: new Set([""]),
- })
- ).toEqual([error(7, 7, `Unexpected token`)]);
- });
-
- test("supports accessing variable fields", () => {
- expect(
- lintExpression({
- expression: `a.b.c`,
- availableVariables: new Set(["a"]),
- })
- ).toEqual([]);
- });
-
- test("supports literals", () => {
- expect(
- lintExpression({
- expression: `"" + 0 + true + [] + {}`,
- })
- ).toEqual([]);
- });
-
- test("supports ternary operator", () => {
- expect(
- lintExpression({
- expression: `true ? false : true`,
- })
- ).toEqual([]);
- });
-
- test("supports template literals", () => {
- expect(
- lintExpression({
- expression: "`my ${1} template ${'2'}`",
- })
- ).toEqual([]);
- expect(
- lintExpression({
- expression: "`my template",
- })
- ).toEqual([error(1, 1, "Unterminated template")]);
- });
-
- test("supports parentheses", () => {
- expect(
- lintExpression({
- expression: "(1 + 1) * 2",
- })
- ).toEqual([]);
- });
-
- test("forbid assignment until enabled", () => {
- expect(
- lintExpression({
- expression: ` a = 1`,
- availableVariables: new Set(["a"]),
- })
- ).toEqual([error(1, 6, "Assignment is supported only inside actions")]);
- expect(
- lintExpression({
- expression: ` a = 1`,
- allowAssignment: true,
- availableVariables: new Set(["a"]),
- })
- ).toEqual([]);
- });
-
- test("lint member assignment targets", () => {
- expect(
- lintExpression({
- expression: ` a[b].c = d`,
- allowAssignment: true,
- availableVariables: new Set(["a", "b", "d"]),
- })
- ).toEqual([]);
- expect(
- lintExpression({
- expression: ` a.b = c`,
- allowAssignment: true,
- availableVariables: new Set(["c"]),
- })
- ).toEqual([warn(1, 2, `"a" is not defined in the scope`)]);
- });
-
- test("lint assignment operators and targets", () => {
- const assignmentExpressions = [
- ` a = b`,
- ` a += b`,
- ` a -= b`,
- ` a *= b`,
- ` a /= b`,
- ` a %= b`,
- ` a **= b`,
- ` a ||= b`,
- ` a &&= b`,
- ` a ??= b`,
- ` a.b = c`,
- ` a[b] = c`,
- ` a[b].c = d`,
- ` a.b[c.d].e ??= f.g`,
- ];
-
- for (const expression of assignmentExpressions) {
- expect(
- lintExpression({
- expression,
- allowAssignment: true,
- availableVariables: new Set(["a", "b", "c", "d", "f"]),
- })
- ).toEqual([]);
- }
- });
-
- test("forbid destructuring assignment", () => {
- expect(
- lintExpression({
- expression: ` ({ a } = b)`,
- allowAssignment: true,
- availableVariables: new Set(["b"]),
- })
- ).toEqual([error(2, 7, "Destructuring assignment is not supported")]);
- expect(
- lintExpression({
- expression: ` [a] = b`,
- allowAssignment: true,
- availableVariables: new Set(["b"]),
- })
- ).toEqual([error(1, 4, "Destructuring assignment is not supported")]);
- expect(
- lintExpression({
- expression: ` ({ nested: a } = b)`,
- allowAssignment: true,
- availableVariables: new Set(["b"]),
- })
- ).toEqual([error(2, 15, "Destructuring assignment is not supported")]);
- });
-
- test("forbid unavailable variables", () => {
- expect(
- lintExpression({ expression: ` a = b + 1`, allowAssignment: true })
- ).toEqual([
- warn(5, 6, `"b" is not defined in the scope`),
- warn(1, 2, `"a" is not defined in the scope`),
- ]);
- expect(
- lintExpression({
- expression: ` a = b + 1`,
- allowAssignment: true,
- availableVariables: new Set(["a", "b"]),
- })
- ).toEqual([]);
- });
-
- test(`forbid "this" keyword`, () => {
- expect(lintExpression({ expression: ` this.name` })).toEqual([
- error(1, 5, `"this" keyword is not supported`),
- ]);
- });
-
- test("forbid functions", () => {
- expect(
- lintExpression({
- expression: ` function(){} + (() => {}) + fn()`,
- availableVariables: new Set(["fn"]),
- })
- ).toEqual([
- error(1, 13, "Functions are not supported"),
- error(17, 25, "Functions are not supported"),
- error(29, 33, `"fn" function is not supported`),
- ]);
- });
-
- test("forbid increment and decrement", () => {
- expect(
- lintExpression({
- expression: ` ++i + --j`,
- availableVariables: new Set(["j", "i"]),
- })
- ).toEqual([
- error(1, 4, "Increment and decrement are not supported"),
- error(7, 10, "Increment and decrement are not supported"),
- ]);
- });
-
- test("forbid sequence expression", () => {
- expect(lintExpression({ expression: ` 1, 2, 3` })).toEqual([
- error(1, 8, "Only single expression is supported"),
- ]);
- });
-
- test(`forbid "yield" keyword`, () => {
- expect(lintExpression({ expression: ` yield 1` })).toEqual([
- error(1, 1, `The keyword 'yield' is reserved`),
- ]);
- });
-
- test("forbid tagged template", () => {
- expect(
- lintExpression({
- expression: " tag`hello`",
- availableVariables: new Set(["tag"]),
- })
- ).toEqual([error(1, 11, "Tagged template is not supported")]);
- });
-
- test("forbid classes", () => {
- expect(
- lintExpression({
- expression: ` class {} + new MyClass()`,
- availableVariables: new Set(["MyClass"]),
- })
- ).toEqual([
- error(1, 9, "Classes are not supported"),
- error(12, 25, "Classes are not supported"),
- ]);
- });
-
- test("forbid imports", () => {
- expect(
- lintExpression({ expression: ` import("") + import.meta.url` })
- ).toEqual([
- error(1, 11, "Imports are not supported"),
- error(14, 25, "Imports are not supported"),
- ]);
- });
-
- test(`forbid "await" keyword`, () => {
- expect(lintExpression({ expression: ` await 1` })).toEqual([
- error(1, 8, `"await" keyword is not supported`),
- ]);
- });
-
- test.each([
- "toLowerCase",
- "replace",
- "split",
- "at",
- "slice",
- "endsWith",
- "includes",
- "startsWith",
- "toString",
- "toUpperCase",
- "toLocaleLowerCase",
- "toLocaleUpperCase",
- ])("allow safe string method: %s", (method) => {
- expect(
- lintExpression({
- expression: `title.${method}()`,
- availableVariables: new Set(["title"]),
- })
- ).toEqual([]);
- });
-
- test.each(["at", "includes", "join", "slice", "toString"])(
- "allow safe array method: %s",
- (method) => {
- expect(
- lintExpression({
- expression: `arr.${method}()`,
- availableVariables: new Set(["arr"]),
- })
- ).toEqual([]);
- }
- );
-
- test("allow supported methods on known native-compatible receivers", () => {
- expect(
- lintExpression({
- expression: `title.split("").toString()`,
- availableVariables: new Set(["title"]),
- variableValues: new Map([["title", "Test"]]),
- })
- ).toEqual([]);
- expect(
- lintExpression({
- expression: `arr.join("").split("").toString()`,
- availableVariables: new Set(["arr"]),
- variableValues: new Map([["arr", ["T", "e", "s", "t"]]]),
- })
- ).toEqual([]);
- expect(
- lintExpression({
- expression: `count.toString() + flag.toString() + object.toString()`,
- availableVariables: new Set(["count", "flag", "object"]),
- variableValues: new Map<string, unknown>([
- ["count", 2],
- ["flag", true],
- ["object", {}],
- ]),
- })
- ).toEqual([]);
- expect(
- lintExpression({
- expression: `title.replace("e", "a").toLowerCase()`,
- availableVariables: new Set(["title"]),
- })
- ).toEqual([]);
- expect(
- lintExpression({
- expression: `arr.join("").toLowerCase()`,
- availableVariables: new Set(["arr"]),
- })
- ).toEqual([]);
- });
-
- test("forbid supported method names on known native-incompatible receivers", () => {
- expect(
- lintExpression({
- expression: `arr.split()`,
- availableVariables: new Set(["arr"]),
- variableValues: new Map([["arr", []]]),
- }).map((diagnostic) => diagnostic.message)
- ).toEqual([`"split" function is not supported`]);
- expect(
- lintExpression({
- expression: `title.join()`,
- availableVariables: new Set(["title"]),
- variableValues: new Map([["title", "Test"]]),
- }).map((diagnostic) => diagnostic.message)
- ).toEqual([`"join" function is not supported`]);
- expect(
- lintExpression({
- expression: `[1, 2, 3].toLowerCase()`,
- }).map((diagnostic) => diagnostic.message)
- ).toEqual([`"toLowerCase" function is not supported`]);
- expect(
- lintExpression({
- expression: `"Test".join()`,
- }).map((diagnostic) => diagnostic.message)
- ).toEqual([`"join" function is not supported`]);
- expect(
- lintExpression({
- expression: `title.split("").toLowerCase()`,
- availableVariables: new Set(["title"]),
- }).map((diagnostic) => diagnostic.message)
- ).toEqual([`"toLowerCase" function is not supported`]);
- expect(
- lintExpression({
- expression: `arr.join("").join()`,
- availableVariables: new Set(["arr"]),
- }).map((diagnostic) => diagnostic.message)
- ).toEqual([`"join" function is not supported`]);
- expect(
- lintExpression({
- expression: `null.toString() + undefined.toString()`,
- }).map((diagnostic) => diagnostic.message)
- ).toEqual([
- `"toString" function is not supported`,
- `"undefined" is not defined in the scope`,
- `"toString" function is not supported`,
- ]);
- });
-
- test("allow chained string methods", () => {
- expect(
- lintExpression({
- expression: `title.toLowerCase().replace(" ", "-").split("-")`,
- availableVariables: new Set(["title"]),
- })
- ).toEqual([]);
- });
-
- test("forbid unsafe method calls", () => {
- expect(
- lintExpression({
- expression: `arr.pop()`,
- availableVariables: new Set(["arr"]),
- })
- ).toEqual([error(0, 9, `"pop" function is not supported`)]);
- expect(
- lintExpression({
- expression: `obj.push(1)`,
- availableVariables: new Set(["obj"]),
- })
- ).toEqual([error(0, 11, `"push" function is not supported`)]);
- });
-
- test("forbid standalone function calls", () => {
- expect(
- lintExpression({
- expression: `func()`,
- availableVariables: new Set(["func"]),
- })
- ).toEqual([error(0, 6, `"func" function is not supported`)]);
- });
-});
-
-test("check simple literals", () => {
- expect(isLiteralExpression(`""`)).toEqual(true);
- expect(isLiteralExpression(`''`)).toEqual(true);
- expect(isLiteralExpression(`0`)).toEqual(true);
- expect(isLiteralExpression(`true`)).toEqual(true);
- expect(isLiteralExpression(`[]`)).toEqual(true);
- expect(isLiteralExpression(`{}`)).toEqual(true);
- expect(isLiteralExpression(`undefined`)).toEqual(true);
- expect(isLiteralExpression(`"" + ""`)).toEqual(false);
- expect(isLiteralExpression(`{}.field`)).toEqual(false);
- expect(isLiteralExpression(`variable`)).toEqual(false);
-});
-
-test("check complex objects and arrays", () => {
- expect(isLiteralExpression(`[1, 2, 3]`)).toEqual(true);
- expect(isLiteralExpression(`[1, 2, variable]`)).toEqual(false);
- expect(isLiteralExpression(`[...variable]`)).toEqual(false);
- expect(isLiteralExpression(`{ param: 0 }`)).toEqual(true);
- expect(isLiteralExpression(`{ "param": 0 }`)).toEqual(true);
- expect(isLiteralExpression(`{ param: variable }`)).toEqual(false);
- expect(isLiteralExpression(`{ ["param"]: 0 }`)).toEqual(true);
- expect(isLiteralExpression(`{ [variable]: 0 }`)).toEqual(false);
- expect(isLiteralExpression(`{ ...variable }`)).toEqual(false);
-});
-
-describe("get expression identifiers", () => {
- test("find all identifiers", () => {
- expect(getExpressionIdentifiers("a = b * c.d")).toEqual(
- new Set(["a", "b", "c"])
- );
- });
-
- test("find identifiers in assignment targets", () => {
- expect(getExpressionIdentifiers("a[b].c = d.e")).toEqual(
- new Set(["a", "b", "d"])
- );
- expect(getExpressionIdentifiers("a.b[c.d].e ??= f.g")).toEqual(
- new Set(["a", "c", "f"])
- );
- });
-
- test("deduplicate identifiers", () => {
- expect(getExpressionIdentifiers("a = a + b")).toEqual(new Set(["a", "b"]));
- });
-
- test("not fail when invalid syntax", () => {
- expect(getExpressionIdentifiers("")).toEqual(new Set());
- expect(getExpressionIdentifiers("a = a +")).toEqual(new Set());
- });
-});
-
-describe("transpile expression", () => {
- const expectTranspiledExpressionToMatchNative = (expression: string) => {
- const nativeResult = new Function(`return (${expression})`)();
- const transpiledResult = new Function(
- `return (${transpileExpression({ expression, executable: true })})`
- )();
- expect(transpiledResult).toEqual(nativeResult);
- };
-
- test("preserve spaces and parentheses", () => {
- expect(
- transpileExpression({ expression: " 1 + (2 + 3) ", executable: true })
- ).toEqual(" 1 + (2 + 3) ");
- });
-
- test("add optional chaining with dot syntax", () => {
- expect(
- transpileExpression({ expression: "a.b . c", executable: true })
- ).toEqual("a?.b ?. c");
- });
-
- test("add optional chaining with computed", () => {
- expect(
- transpileExpression({ expression: "a['b'] [c]", executable: true })
- ).toEqual("a?.['b'] ?.[c]");
- });
-
- test("skip optional chaining", () => {
- expect(
- transpileExpression({ expression: "a?.['b']?.c", executable: true })
- ).toEqual("a?.['b']?.c");
- });
-
- test("skip optional chaining in assignment targets", () => {
- expect(
- transpileExpression({ expression: "a.b = c.d", executable: true })
- ).toEqual("a.b = c?.d");
- expect(
- transpileExpression({ expression: "a[b.c].d = e.f", executable: true })
- ).toEqual("a[b?.c].d = e?.f");
- });
-
- test("skip optional chaining in assignment targets for all assignment operators", () => {
- const operators = [
- "=",
- "+=",
- "-=",
- "*=",
- "/=",
- "%=",
- "**=",
- "||=",
- "&&=",
- "??=",
- ];
-
- for (const operator of operators) {
- const expression = `a.b ${operator} c.d`;
- const transpiled = transpileExpression({ expression, executable: true });
- expect(transpiled).toEqual(`a.b ${operator} c?.d`);
- expect(() =>
- parseExpressionAt(transpiled, 0, { ecmaVersion: "latest" })
- ).not.toThrow();
- }
- });
-
- test("transpile executable assignment expressions", () => {
- const cases = [
- ["a.b = c.d", "a.b = c?.d"],
- ["a[b] = c.d", "a[b] = c?.d"],
- ["a[b.c] = d.e", "a[b?.c] = d?.e"],
- ["a[b.c].d = e.f", "a[b?.c].d = e?.f"],
- ["a.b[c.d].e ??= f.g", "a.b[c?.d].e ??= f?.g"],
- ] as const;
-
- for (const [expression, expected] of cases) {
- const transpiled = transpileExpression({ expression, executable: true });
- expect(transpiled).toEqual(expected);
- expect(() =>
- parseExpressionAt(transpiled, 0, { ecmaVersion: "latest" })
- ).not.toThrow();
- }
- });
-
- test("replace variable", () => {
- expect(
- transpileExpression({
- expression: "(a + c) * b",
- replaceVariable: (identifier) => identifier + "_1",
- })
- ).toEqual("(a_1 + c_1) * b_1");
- expect(
- transpileExpression({
- expression: "a = c",
- replaceVariable: (identifier) => identifier + "_1",
- })
- ).toEqual("a_1 = c_1");
- });
-
- test("skip identifiers in nested member expressions", () => {
- const identifiers: string[] = [];
- const transpiled = transpileExpression({
- expression: "a.b + c.d * e[f]",
- replaceVariable: (identifier) => {
- identifiers.push(identifier);
- return identifier + "_1";
- },
- });
- expect(identifiers).toEqual(["a", "c", "e", "f"]);
- expect(transpiled).toEqual("a_1.b + c_1.d * e_1[f_1]");
- });
-
- test("inform identifier is an assignee", () => {
- const replaceVariable = (identifier: string, assignee: boolean) => {
- const suffix = assignee ? "_assignee" : "_assigner";
- return identifier + suffix;
- };
-
- const cases = [
- ["a = b", "a_assignee = b_assigner"],
- ["a += b", "a_assignee += b_assigner"],
- ["a ||= b", "a_assignee ||= b_assigner"],
- ["a ??= b", "a_assignee ??= b_assigner"],
- ["a.b = c", "a_assignee.b = c_assigner"],
- ["a[b] = c", "a_assignee[b_assigner] = c_assigner"],
- ["a[b].c = d", "a_assignee[b_assigner].c = d_assigner"],
- ["a.b[c.d].e ??= f.g", "a_assignee.b[c_assigner.d].e ??= f_assigner.g"],
- ] as const;
-
- for (const [expression, expected] of cases) {
- expect(transpileExpression({ expression, replaceVariable })).toEqual(
- expected
- );
- }
- });
-
- test("transpile object literal without changes", () => {
- expect(
- transpileExpression({
- expression: `{ ...name }`,
- })
- ).toEqual(`{ ...name }`);
- });
-
- test("output more readable syntax error", () => {
- let errorString = "";
- try {
- transpileExpression({ expression: `` });
- } catch (error) {
- errorString = (error as Error).message;
- }
- expect(errorString).toEqual(`Unexpected token (1:0) in ""`);
- });
-
- test("transpile string methods with optional chaining", () => {
- expect(
- transpileExpression({
- expression: "title.toLowerCase()",
- executable: true,
- })
- ).toEqual("title?.toLowerCase?.()");
- expect(
- transpileExpression({
- expression: "user.name.replace(' ', '-')",
- executable: true,
- })
- ).toEqual("user?.name?.replace?.(' ', '-')");
- expect(
- transpileExpression({
- expression: "data.title.split('-')",
- executable: true,
- })
- ).toEqual("data?.title?.split?.('-')");
- });
-
- test("preserve native behavior for all supported string methods", () => {
- const expressionsByMethod = {
- at: `"Hello".at(1)`,
- endsWith: `"Hello".endsWith("lo")`,
- includes: `"Hello".includes("ell")`,
- replace: `"Hello".replace("l", "x")`,
- slice: `"Hello".slice(1, 4)`,
- split: `"Hello".split("l")`,
- startsWith: `"Hello".startsWith("He")`,
- toLocaleLowerCase: `"Hello".toLocaleLowerCase()`,
- toLocaleUpperCase: `"Hello".toLocaleUpperCase()`,
- toLowerCase: `"Hello".toLowerCase()`,
- toString: `"Hello".toString()`,
- toUpperCase: `"Hello".toUpperCase()`,
- };
-
- expect(new Set(Object.keys(expressionsByMethod))).toEqual(
- allowedStringMethods
- );
- for (const expression of Object.values(expressionsByMethod)) {
- expectTranspiledExpressionToMatchNative(expression);
- }
- expectTranspiledExpressionToMatchNative(`"Test".split(2).toString()`);
- });
-
- test("preserve native behavior for all supported array methods", () => {
- const expressionsByMethod = {
- at: `["a", "b", "c"].at(1)`,
- includes: `["a", "b", "c"].includes("b")`,
- join: `["a", "b", "c"].join("-")`,
- slice: `["a", "b", "c"].slice(1, 3)`,
- toString: `["a", "b", "c"].toString()`,
- };
-
- expect(new Set(Object.keys(expressionsByMethod))).toEqual(
- allowedArrayMethods
- );
- for (const expression of Object.values(expressionsByMethod)) {
- expectTranspiledExpressionToMatchNative(expression);
- }
- });
-
- test("transpile chained string methods with optional chaining", () => {
- expect(
- transpileExpression({
- expression: "title.toLowerCase().replace(/\\s+/g, '-')",
- executable: true,
- })
- ).toEqual("title?.toLowerCase?.()?.replace?.(/\\s+/g, '-')");
- expect(
- transpileExpression({
- expression: "user.name.toLowerCase().replace(' ', '-').split('-')",
- executable: true,
- })
- ).toEqual("user?.name?.toLowerCase?.()?.replace?.(' ', '-')?.split?.('-')");
- });
-
- test("transpile array methods with optional chaining", () => {
- expect(
- transpileExpression({
- expression: "items.map(item => item.id)",
- executable: true,
- })
- ).toEqual("items?.map?.(item => item?.id)");
- });
-
- test("transpile nested method calls with optional chaining", () => {
- expect(
- transpileExpression({
- expression: "obj.method().prop.anotherMethod()",
- executable: true,
- })
- ).toEqual("obj?.method?.()?.prop?.anotherMethod?.()");
- });
-
- test("preserve existing optional chaining", () => {
- expect(
- transpileExpression({
- expression: "obj?.method?.()",
- executable: true,
- })
- ).toEqual("obj?.method?.()");
- expect(
- transpileExpression({
- expression: "obj?.prop?.method?.()",
- executable: true,
- })
- ).toEqual("obj?.prop?.method?.()");
- });
-});
-
-describe("object expression transformations", () => {
- test("parse object expression", () => {
- expect(parseObjectExpression(`{ a: 0, b: "", c: $c + 1 }`)).toEqual(
- new Map([
- ["a", `0`],
- ["b", `""`],
- ["c", `$c + 1`],
- ])
- );
- });
-
- test("parse unsupported syntax", () => {
- expect(parseObjectExpression(``)).toEqual(new Map());
- expect(parseObjectExpression(`0`)).toEqual(new Map());
- expect(parseObjectExpression(`{ a: 0, ...spread }`)).toEqual(
- new Map([["a", "0"]])
- );
- expect(parseObjectExpression(`{ a: 0, [b]: 0 }`)).toEqual(
- new Map([["a", "0"]])
- );
- expect(parseObjectExpression(`{ "a-b": 0 }`)).toEqual(
- new Map([["a-b", "0"]])
- );
- });
-
- test("generate object expression", () => {
- expect(
- generateObjectExpression(
- new Map([
- ["a", `0`],
- ["b-c", `""`],
- ["d", `$d`],
- ])
- )
- ).toMatchInlineSnapshot(`
- "{
- "a": 0,
- "b-c": "",
- "d": $d,
- }"
- `);
- });
-
- test("generate empty object expression", () => {
- expect(generateObjectExpression(new Map())).toMatchInlineSnapshot(`
- "{
- }"
- `);
- });
-});
-
-test("encode/decode variable names", () => {
+test("encode and decode Webstudio data variable names", () => {
expect(encodeDataVariableId("my--id")).toEqual(
"$ws$dataSource$my__DASH____DASH__id"
);
expect(decodeDataVariableId(encodeDataVariableId("my--id"))).toEqual(
"my--id"
);
- expect(decodeDataVariableId("myVarName")).toEqual(undefined);
+ expect(decodeDataVariableId("myVarName")).toBeUndefined();
expect(encodeDataVariableId(SYSTEM_VARIABLE_ID)).toEqual("$ws$system");
expect(
decodeDataVariableId(encodeDataVariableId(SYSTEM_VARIABLE_ID))
).toEqual(SYSTEM_VARIABLE_ID);
});
-test("execute expression", () => {
- expect(executeExpression(undefined)).toEqual(undefined);
+test("execute a static Webstudio expression", () => {
+ expect(executeExpression(undefined)).toBeUndefined();
expect(executeExpression("1 + 1")).toEqual(2);
- expect(executeExpression("someVariable + 1")).toEqual(undefined);
+ expect(executeExpression("someVariable + 1")).toBeUndefined();
});
diff --git a/packages/sdk/src/expression.ts b/packages/sdk/src/expression.ts
index 87293e0521..51ce6d86a4 100644
--- a/packages/sdk/src/expression.ts
+++ b/packages/sdk/src/expression.ts
@@ -1,12 +1,4 @@
-import {
- type Expression,
- type Identifier,
- type MemberExpression,
- type Pattern,
- parse,
- parseExpressionAt,
-} from "acorn";
-import { simple } from "acorn-walk";
+import { transpileExpression } from "@webstudio-is/expression";
import type { DataSource, DataSources } from "./schema/data-sources";
import type { Scope } from "./scope";
import { ROOT_INSTANCE_ID } from "./instances-utils";
@@ -20,633 +12,10 @@ export const systemParameter: DataSource = {
name: "system",
};
-export type Diagnostic = {
- from: number;
- to: number;
- severity: "error" | "hint" | "info" | "warning";
- message: string;
-};
-
-type ExpressionVisitor = {
- [K in Expression["type"]]: (node: Extract<Expression, { type: K }>) => void;
-};
-
-type AssignmentTargetKind = "binding" | "memberObject";
-
-const walkAssignmentTarget = (
- node: Pattern,
- visitor: {
- Identifier?: (node: Identifier, kind: AssignmentTargetKind) => void;
- MemberExpression?: (node: MemberExpression) => void;
- UnsupportedPattern?: (node: Pattern) => void;
- }
-) => {
- if (node.type === "Identifier") {
- visitor.Identifier?.(node, "binding");
- return;
- }
-
- if (node.type === "MemberExpression") {
- visitor.MemberExpression?.(node);
- const { object } = node;
- if (object.type === "Identifier") {
- visitor.Identifier?.(object, "memberObject");
- } else if (object.type === "MemberExpression") {
- walkAssignmentTarget(object, visitor);
- }
- return;
- }
-
- visitor.UnsupportedPattern?.(node);
-};
-
-export type VariableValues =
- | ReadonlyMap<Identifier["name"], unknown>
- | Readonly<Record<Identifier["name"], unknown>>;
-
-export type ExpressionValueKind =
- | "array"
- | "bigint"
- | "boolean"
- | "nullish"
- | "number"
- | "object"
- | "string"
- | "unknown";
-
-const stringMethodReturnKindByName = new Map<string, ExpressionValueKind>([
- ["toLowerCase", "string"],
- ["replace", "string"],
- ["split", "array"],
- ["slice", "string"],
- ["at", "unknown"],
- ["endsWith", "boolean"],
- ["includes", "boolean"],
- ["startsWith", "boolean"],
- ["toString", "string"],
- ["toUpperCase", "string"],
- ["toLocaleLowerCase", "string"],
- ["toLocaleUpperCase", "string"],
-]);
-
-const arrayMethodReturnKindByName = new Map<string, ExpressionValueKind>([
- ["at", "unknown"],
- ["includes", "boolean"],
- ["join", "string"],
- ["slice", "array"],
- ["toString", "string"],
-]);
-
-export const allowedStringMethods = new Set(
- stringMethodReturnKindByName.keys()
-);
-
-export const allowedArrayMethods = new Set(arrayMethodReturnKindByName.keys());
-
-const getVariableValue = (
- variableValues: undefined | VariableValues,
- name: Identifier["name"]
-) => {
- if (variableValues === undefined) {
- return;
- }
- const maybeMap = variableValues as Partial<ReadonlyMap<string, unknown>>;
- if (
- typeof maybeMap.has === "function" &&
- typeof maybeMap.get === "function"
- ) {
- if (maybeMap.has(name)) {
- return { value: maybeMap.get(name) };
- }
- return;
- }
- const record = variableValues as Readonly<Record<string, unknown>>;
- if (Object.hasOwn(record, name)) {
- return { value: record[name] };
- }
-};
-
-const getValueKind = (value: unknown): ExpressionValueKind => {
- if (Array.isArray(value)) {
- return "array";
- }
- if (value === undefined || value === null) {
- return "nullish";
- }
- switch (typeof value) {
- case "bigint":
- return "bigint";
- case "boolean":
- return "boolean";
- case "number":
- return "number";
- case "string":
- return "string";
- case "object":
- return "object";
- default:
- return "unknown";
- }
-};
-
-const getMethodReturnKind = (
- receiverKind: ExpressionValueKind,
- methodName: string
-): ExpressionValueKind => {
- if (receiverKind === "array") {
- return arrayMethodReturnKindByName.get(methodName) ?? "unknown";
- }
- if (receiverKind === "string") {
- return stringMethodReturnKindByName.get(methodName) ?? "unknown";
- }
- if (receiverKind === "unknown") {
- const stringReturnKind = stringMethodReturnKindByName.get(methodName);
- const arrayReturnKind = arrayMethodReturnKindByName.get(methodName);
- if (stringReturnKind && arrayReturnKind === undefined) {
- return stringReturnKind;
- }
- if (arrayReturnKind && stringReturnKind === undefined) {
- return arrayReturnKind;
- }
- if (stringReturnKind === arrayReturnKind) {
- return stringReturnKind ?? "unknown";
- }
- return "unknown";
- }
- return methodName === "toString" ? "string" : "unknown";
-};
-
-const isMethodSupported = (
- receiverKind: ExpressionValueKind,
- methodName: string
-) => {
- if (receiverKind === "unknown") {
- return (
- allowedStringMethods.has(methodName) ||
- allowedArrayMethods.has(methodName)
- );
- }
- if (receiverKind === "string") {
- return stringMethodReturnKindByName.has(methodName);
- }
- if (receiverKind === "array") {
- return arrayMethodReturnKindByName.has(methodName);
- }
- if (receiverKind === "nullish") {
- return false;
- }
- return methodName === "toString";
-};
-
-const getExpressionNodeValueKind = (
- node: Expression,
- variableValues: undefined | VariableValues
-): ExpressionValueKind => {
- if (node.type === "Identifier") {
- if (node.name === "undefined") {
- return "nullish";
- }
- const variable = getVariableValue(variableValues, node.name);
- return variable ? getValueKind(variable.value) : "unknown";
- }
- if (node.type === "Literal") {
- return getValueKind(node.value);
- }
- if (node.type === "ArrayExpression") {
- return "array";
- }
- if (node.type === "ObjectExpression") {
- return "object";
- }
- if (node.type === "TemplateLiteral") {
- return "string";
- }
- if (
- node.type === "ChainExpression" ||
- node.type === "ParenthesizedExpression"
- ) {
- return getExpressionNodeValueKind(node.expression, variableValues);
- }
- if (
- node.type === "CallExpression" &&
- node.callee.type === "MemberExpression" &&
- node.callee.object.type !== "Super" &&
- node.callee.property.type === "Identifier"
- ) {
- const receiverKind = getExpressionNodeValueKind(
- node.callee.object,
- variableValues
- );
- const methodName = node.callee.property.name;
- if (isMethodSupported(receiverKind, methodName)) {
- return getMethodReturnKind(receiverKind, methodName);
- }
- }
- return "unknown";
-};
-
-export const getExpressionValueKind = ({
- expression,
- variableValues,
-}: {
- expression: string;
- variableValues?: VariableValues;
-}): ExpressionValueKind => {
- try {
- const node = parseExpressionAt(expression, 0, { ecmaVersion: "latest" });
- return getExpressionNodeValueKind(node, variableValues);
- } catch {
- return "unknown";
- }
-};
-
-export const lintExpression = ({
- expression,
- availableVariables = new Set(),
- allowAssignment = false,
- variableValues,
-}: {
- expression: string;
- availableVariables?: Set<Identifier["name"]>;
- allowAssignment?: boolean;
- variableValues?: VariableValues;
-}): Diagnostic[] => {
- const diagnostics: Diagnostic[] = [];
- const addMessage = (
- message: string,
- severity: "error" | "warning" = "error"
- ) => {
- return (node: { start: number; end: number }) => {
- diagnostics.push({
- // tune error position after wrapping expression with parentheses
- from: node.start - 1,
- to: node.end - 1,
- severity,
- message: message,
- });
- };
- };
- // allow empty expression
- if (expression.trim().length === 0) {
- diagnostics.push({
- from: 0,
- to: 0,
- severity: "error",
- message: "Expression cannot be empty",
- });
- return diagnostics;
- }
- try {
- // wrap expression with parentheses to force acorn parse whole expression
- // instead of just first valid part
- const root = parse(`(${expression})`, {
- ecmaVersion: "latest",
- // support parsing import to forbid explicitly
- sourceType: "module",
- });
-
- simple(root, {
- Identifier(node) {
- if (availableVariables.has(node.name) === false) {
- addMessage(
- `"${node.name}" is not defined in the scope`,
- "warning"
- )(node);
- }
- },
- Literal() {},
- ArrayExpression() {},
- ObjectExpression() {},
- UnaryExpression() {},
- BinaryExpression() {},
- LogicalExpression() {},
- MemberExpression() {},
- ConditionalExpression() {},
- TemplateLiteral() {},
- ChainExpression() {},
- ParenthesizedExpression() {},
- AssignmentExpression(node) {
- if (allowAssignment === false) {
- addMessage("Assignment is supported only inside actions")(node);
- return;
- }
- walkAssignmentTarget(node.left, {
- Identifier(node, kind) {
- if (kind !== "binding") {
- return;
- }
- if (availableVariables.has(node.name) === false) {
- addMessage(
- `"${node.name}" is not defined in the scope`,
- "warning"
- )(node);
- }
- },
- UnsupportedPattern: addMessage(
- "Destructuring assignment is not supported"
- ),
- });
- },
- // parser forbids to yield inside module
- YieldExpression() {},
- ThisExpression: addMessage(`"this" keyword is not supported`),
- FunctionExpression: addMessage("Functions are not supported"),
- UpdateExpression: addMessage("Increment and decrement are not supported"),
- CallExpression(node) {
- let calleeName;
- if (node.callee.type === "MemberExpression") {
- if (node.callee.property.type === "Identifier") {
- const methodName = node.callee.property.name;
- const receiverKind =
- node.callee.object.type === "Super"
- ? "unknown"
- : getExpressionNodeValueKind(
- node.callee.object,
- variableValues
- );
- if (isMethodSupported(receiverKind, methodName)) {
- return;
- }
- calleeName = methodName;
- }
- } else if (node.callee.type === "Identifier") {
- calleeName = node.callee.name;
- }
- if (calleeName) {
- addMessage(`"${calleeName}" function is not supported`)(node);
- } else {
- addMessage("Functions are not supported")(node);
- }
- },
- NewExpression: addMessage("Classes are not supported"),
- SequenceExpression: addMessage(`Only single expression is supported`),
- ArrowFunctionExpression: addMessage("Functions are not supported"),
- TaggedTemplateExpression: addMessage("Tagged template is not supported"),
- ClassExpression: addMessage("Classes are not supported"),
- MetaProperty: addMessage("Imports are not supported"),
- AwaitExpression: addMessage(`"await" keyword is not supported`),
- ImportExpression: addMessage("Imports are not supported"),
- } satisfies ExpressionVisitor);
- } catch (error) {
- const castedError = error as { message: string; pos: number };
- diagnostics.push({
- // tune error position after wrapping expression with parentheses
- from: castedError.pos - 1,
- to: castedError.pos - 1,
- severity: "error",
- // trim auto generated error location
- // to not conflict with tuned position
- message: castedError.message.replaceAll(/\s+\(\d+:\d+\)$/g, ""),
- });
- }
- return diagnostics;
-};
-
-const isLiteralNode = (node: Expression): boolean => {
- if (node.type === "Identifier" && node.name === "undefined") {
- return true;
- }
- if (node.type === "Literal") {
- return true;
- }
- if (node.type === "ArrayExpression") {
- return node.elements.every((node) => {
- if (node === null || node.type === "SpreadElement") {
- return false;
- }
- return isLiteralNode(node);
- });
- }
- if (node.type === "ObjectExpression") {
- return node.properties.every((property) => {
- if (property.type === "SpreadElement") {
- return false;
- }
- const key = property.key;
- const isIdentifierKey =
- key.type === "Identifier" && property.computed === false;
- const isLiteralKey = key.type === "Literal";
- return (isLiteralKey || isIdentifierKey) && isLiteralNode(property.value);
- });
- }
- return false;
-};
-
-/**
- * check whether provided expression is a literal value
- * like "", 0 or { param: "value" }
- * which does not depends on any variable
- */
-export const isLiteralExpression = (expression: string) => {
- try {
- const node = parseExpressionAt(expression, 0, { ecmaVersion: "latest" });
- return isLiteralNode(node);
- } catch {
- // treat invalid expression as non-literal
- return false;
- }
-};
-
-export const getExpressionIdentifiers = (expression: string) => {
- const identifiers = new Set<string>();
- try {
- const root = parseExpressionAt(expression, 0, { ecmaVersion: "latest" });
- simple(root, {
- Identifier: (node) => identifiers.add(node.name),
- AssignmentExpression(node) {
- walkAssignmentTarget(node.left, {
- Identifier: (node) => identifiers.add(node.name),
- });
- },
- });
- } catch {
- // empty block
- }
- return identifiers;
-};
-
-/**
- * transpile expression into executable one
- *
- * add optional chaining operator to every member expression
- * to access any field without runtime errors
- *
- * replace variable names if necessary
- */
-export const transpileExpression = ({
- expression,
- executable = false,
- replaceVariable,
-}: {
- expression: string;
- executable?: boolean;
- replaceVariable?: (
- identifier: string,
- assignee: boolean
- ) => string | undefined | void;
-}) => {
- let root;
- try {
- root = parseExpressionAt(expression, 0, { ecmaVersion: "latest" });
- } catch (error) {
- const message = (error as Error).message;
- // throw new error to trace error in our code instead of acorn
- throw Error(`${message} in ${JSON.stringify(expression)}`);
- }
- const assignmentTargetMemberRanges: [start: number, end: number][] = [];
- if (executable) {
- simple(root, {
- AssignmentExpression(node) {
- walkAssignmentTarget(node.left, {
- MemberExpression(node) {
- assignmentTargetMemberRanges.push([node.start, node.end]);
- },
- });
- },
- });
- }
- const replacements: [start: number, end: number, fragment: string][] = [];
- const replacementIndexByRange = new Map<string, number>();
- const addReplacement = (
- start: number,
- end: number,
- fragment: string,
- { replaceExisting = false }: { replaceExisting?: boolean } = {}
- ) => {
- const range = `${start}:${end}`;
- const existingIndex = replacementIndexByRange.get(range);
- if (existingIndex !== undefined) {
- if (replaceExisting) {
- replacements[existingIndex] = [start, end, fragment];
- }
- return;
- }
- replacementIndexByRange.set(range, replacements.length);
- replacements.push([start, end, fragment]);
- };
- const replaceIdentifier = (node: Identifier, assignee: boolean) => {
- const newName = replaceVariable?.(node.name, assignee);
- if (newName) {
- addReplacement(node.start, node.end, newName, {
- replaceExisting: assignee,
- });
- }
- };
- simple(root, {
- Identifier: (node) => replaceIdentifier(node, false),
- AssignmentExpression(node) {
- walkAssignmentTarget(node.left, {
- Identifier: (node) => replaceIdentifier(node, true),
- });
- },
- MemberExpression(node) {
- if (executable === false || node.optional) {
- return;
- }
- if (
- assignmentTargetMemberRanges.some(
- ([start, end]) => start === node.start && end === node.end
- )
- ) {
- return;
- }
- // a . b -> a ?. b
- if (node.computed === false) {
- const dotIndex = expression.indexOf(".", node.object.end);
- addReplacement(dotIndex, dotIndex, "?");
- }
- // a [b] -> a ?.[b]
- if (node.computed === true) {
- const dotIndex = expression.indexOf("[", node.object.end);
- addReplacement(dotIndex, dotIndex, "?.");
- }
- },
- CallExpression(node) {
- if (executable === false || node.optional) {
- return;
- }
- // Add optional chaining to method calls: obj.method() -> obj?.method?.()
- if (node.callee.type === "MemberExpression") {
- // Find the opening parenthesis after the method name
- const openParenIndex = expression.indexOf("(", node.callee.end);
- if (openParenIndex !== -1) {
- addReplacement(openParenIndex, openParenIndex, "?.");
- }
- }
- },
- });
- // order from the latest to the first insertion to not break other positions
- replacements.sort(([leftStart], [rightStart]) => rightStart - leftStart);
- for (const [start, end, fragment] of replacements) {
- const before = expression.slice(0, start);
- const after = expression.slice(end);
- expression = before + fragment + after;
- }
- return expression;
-};
-
-/**
- * parse object expression into key value map
- * where each value is expression
- */
-export const parseObjectExpression = (expression: string) => {
- const map = new Map<string, string>();
- let root;
- try {
- root = parseExpressionAt(expression, 0, { ecmaVersion: "latest" });
- } catch (error) {
- return map;
- }
- if (root.type !== "ObjectExpression") {
- return map;
- }
- for (const property of root.properties) {
- if (property.type === "SpreadElement") {
- continue;
- }
- if (property.computed) {
- continue;
- }
- let key;
- if (property.key.type === "Identifier") {
- key = property.key.name;
- } else if (
- property.key.type === "Literal" &&
- typeof property.key.value === "string"
- ) {
- key = property.key.value;
- } else {
- continue;
- }
- const valueExpression = expression.slice(
- property.value.start,
- property.value.end
- );
- map.set(key, valueExpression);
- }
- return map;
-};
-
-/**
- * generate key value map into object expression
- * after updating individual value expressions
- */
-export const generateObjectExpression = (map: Map<string, string>) => {
- let generated = "{\n";
- for (const [key, valueExpression] of map) {
- const keyExpression = JSON.stringify(key);
- generated += ` ${keyExpression}: ${valueExpression},\n`;
- }
- generated += `}`;
- return generated;
-};
-
const dataSourceVariablePrefix = "$ws$dataSource$";
-// data source id is generated with nanoid which has "-" in alphabeta
-// here "-" is encoded with "__DASH__' in variable name
-// https://github.com/ai/nanoid/blob/047686abad8f15aff05f3a2eeedb7c98b6847392/url-alphabet/index.js
-
+// Data source ids use nanoid's URL alphabet, which contains dashes. Encode
+// dashes so the persisted id can be embedded in a valid JavaScript identifier.
export const encodeDataVariableId = (id: string) => {
if (id === SYSTEM_VARIABLE_ID) {
return "$ws$system";
@@ -678,8 +47,8 @@ export const generateExpression = ({
dataSources: DataSources;
usedDataSources: DataSources;
scope: Scope;
-}) => {
- return transpileExpression({
+}) =>
+ transpileExpression({
expression,
executable: true,
replaceVariable: (identifier) => {
@@ -689,22 +58,19 @@ export const generateExpression = ({
dep = systemParameter;
}
if (dep) {
- usedDataSources?.set(dep.id, dep);
+ usedDataSources.set(dep.id, dep);
return scope.getName(dep.id, dep.name);
}
return "undefined";
},
});
-};
-/**
- * edge case utility for "statoc" expression without variables
- */
+/** Execute a static expression generated and controlled by Webstudio. */
export const executeExpression = (expression: undefined | string) => {
try {
const fn = new Function(`return (${expression})`);
return fn();
} catch {
- // empty block
+ // Invalid and non-static expressions have no value here.
}
};
diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts
index 241e4669c6..bb6026f48a 100644
--- a/packages/sdk/src/index.ts
+++ b/packages/sdk/src/index.ts
@@ -1,4 +1,5 @@
export * from "./schema/assets";
+export * from "./schema/asset-resource";
export * from "./schema/asset-folders";
export * from "./schema/pages";
export * from "./schema/instances";
@@ -17,6 +18,7 @@ export * from "./schema/component-meta";
export * from "./assets";
export * from "./asset-folder-hierarchy";
export * from "./asset-folder-normalization";
+export * from "./asset-resource-config";
export * from "./core-metas";
export * from "./instances-utils";
export * from "./page-utils";
diff --git a/packages/sdk/src/page-meta-generator.ts b/packages/sdk/src/page-meta-generator.ts
index 50f05ebda6..82398859e7 100644
--- a/packages/sdk/src/page-meta-generator.ts
+++ b/packages/sdk/src/page-meta-generator.ts
@@ -3,7 +3,10 @@ import type { DataSources } from "./schema/data-sources";
import type { Page } from "./schema/pages";
import { type Scope, createScope } from "./scope";
import { generateExpression, SYSTEM_VARIABLE_ID } from "./expression";
-import { parseExpressionAt } from "acorn";
+import {
+ isValidExpression,
+ parseStaticMemberPath,
+} from "@webstudio-is/expression";
export type PageMeta = {
title: string;
@@ -20,22 +23,15 @@ export type PageMeta = {
const normalizeStringExpression = (expression: string) => {
const trimmedExpression = expression.trim();
- try {
- const parsedExpression = parseExpressionAt(trimmedExpression, 0, {
- ecmaVersion: "latest",
- });
- if (parsedExpression.end === trimmedExpression.length) {
- if (
- parsedExpression.type === "Identifier" &&
- trimmedExpression !== "undefined" &&
- trimmedExpression.includes("$ws$") === false
- ) {
- return JSON.stringify(expression);
- }
- return expression;
+ if (isValidExpression(trimmedExpression)) {
+ if (
+ parseStaticMemberPath(trimmedExpression)?.length === 1 &&
+ trimmedExpression !== "undefined" &&
+ trimmedExpression.includes("$ws$") === false
+ ) {
+ return JSON.stringify(expression);
}
- } catch {
- // Plain text from older synced bundles is not a valid expression.
+ return expression;
}
if (trimmedExpression.includes("$ws$")) {
return expression;
diff --git a/packages/sdk/src/page-utils.ts b/packages/sdk/src/page-utils.ts
index fd24b9c5e3..93d0a285e8 100644
--- a/packages/sdk/src/page-utils.ts
+++ b/packages/sdk/src/page-utils.ts
@@ -152,20 +152,20 @@ export const getPagePath = (id: Folder["id"] | Page["id"], pages: Pages) => {
return paths.reverse().join("/").replace(/\/+/g, "/");
};
+/** Checks page-level sitemap settings independently of its concrete path. */
+export const isPageEligibleForSitemap = (page: Page) =>
+ (page.meta.documentType ?? "html") === "html" &&
+ // A dynamic expression cannot be evaluated without its resource data, so it
+ // remains eligible just as it did for static sitemap generation.
+ executeExpression(page.meta.excludePageFromSearch) !== true;
+
export const getStaticSiteMapXml = (pages: Pages, updatedAt: string) => {
const allPages = getPublishablePages(pages);
- return (
- allPages
- .filter((page) => (page.meta.documentType ?? "html") === "html")
- // ignore pages with excludePageFromSearch bound to variables
- // because there is no data from cms available at build time
- .filter(
- (page) => executeExpression(page.meta.excludePageFromSearch) !== true
- )
- .filter((page) => false === isPathnamePattern(page.path))
- .map((page) => ({
- path: getPagePath(page.id, pages),
- lastModified: updatedAt.split("T")[0],
- }))
- );
+ return allPages
+ .filter(isPageEligibleForSitemap)
+ .filter((page) => false === isPathnamePattern(page.path))
+ .map((page) => ({
+ path: getPagePath(page.id, pages),
+ lastModified: updatedAt.split("T")[0],
+ }));
};
diff --git a/packages/sdk/src/resource-loader.test.ts b/packages/sdk/src/resource-loader.test.ts
index 1d11d305a9..0cd17708be 100644
--- a/packages/sdk/src/resource-loader.test.ts
+++ b/packages/sdk/src/resource-loader.test.ts
@@ -1,8 +1,39 @@
-import { describe, expect, test, beforeEach, vi, type Mock } from "vitest";
+import {
+ afterEach,
+ describe,
+ expect,
+ test,
+ beforeEach,
+ vi,
+ type Mock,
+} from "vitest";
-import { loadResource } from "./resource-loader";
+import {
+ assetsUploadsApiUrl,
+ getAssetApiUrl,
+ getAssetContentApiUrl,
+ getAssetFolderApiUrl,
+ getAssetUploadApiUrl,
+ getResourceCacheKey,
+ isLocalResource,
+ loadResource,
+} from "./resource-loader";
import type { ResourceRequest } from "./schema/resources";
+test("builds canonical Assets command URLs", () => {
+ expect(assetsUploadsApiUrl).toBe("/rest/assets/uploads");
+ expect(getAssetUploadApiUrl("folder/name.png")).toBe(
+ "/rest/assets/uploads/folder%2Fname.png"
+ );
+ expect(getAssetContentApiUrl("asset/id")).toBe(
+ "/rest/assets/asset%2Fid/content"
+ );
+ expect(getAssetApiUrl("asset/id")).toBe("/rest/assets/asset%2Fid");
+ expect(getAssetFolderApiUrl("folder/id")).toBe(
+ "/rest/assets/folders/folder%2Fid"
+ );
+});
+
// Mock the fetch function
describe("loadResource", () => {
@@ -13,6 +44,11 @@ describe("loadResource", () => {
vi.clearAllMocks();
});
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
test("should successfully fetch a resource and return a JSON response", async () => {
const mockResponse = new Response(JSON.stringify({ key: "value" }), {
status: 200,
@@ -75,6 +111,101 @@ describe("loadResource", () => {
});
});
+ test("exposes Assets query results as an ID-keyed resource value", async () => {
+ mockFetch.mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ data: {
+ items: [
+ { id: "second", name: "Second" },
+ { id: "first", name: "First" },
+ ],
+ totalCount: 5,
+ hasMore: true,
+ },
+ __diagnostics__: { scope: "query-preview" },
+ })
+ )
+ );
+
+ const result = await loadResource(mockFetch, {
+ name: "assets",
+ url: "/$resources/assets",
+ searchParams: [],
+ method: "post",
+ headers: [],
+ body: {},
+ });
+
+ expect(result).toEqual({
+ ok: true,
+ status: 200,
+ statusText: "",
+ data: {
+ second: { name: "Second" },
+ first: { name: "First" },
+ },
+ meta: { totalCount: 5, hasMore: true },
+ __diagnostics__: { scope: "query-preview" },
+ });
+ expect(Object.keys(result.data)).toEqual(["second", "first"]);
+ });
+
+ test("retains ID in Assets values only when selected", async () => {
+ mockFetch.mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ items: [{ id: "asset", name: "Asset" }],
+ totalCount: 1,
+ hasMore: false,
+ })
+ )
+ );
+
+ const result = await loadResource(mockFetch, {
+ name: "assets",
+ url: "/$resources/assets",
+ searchParams: [],
+ method: "post",
+ headers: [],
+ body: {
+ query: {
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["id"]],
+ },
+ },
+ },
+ });
+
+ expect(result.data).toEqual({ asset: { id: "asset", name: "Asset" } });
+ });
+
+ test("does not reshape arbitrary POST resources", async () => {
+ const collection = {
+ items: [{ id: "item" }],
+ totalCount: 1,
+ hasMore: false,
+ };
+ mockFetch.mockResolvedValue(new Response(JSON.stringify(collection)));
+
+ await expect(
+ loadResource(
+ mockFetch,
+ {
+ name: "posts",
+ url: "/api/posts",
+ searchParams: [],
+ method: "post",
+ headers: [],
+ body: {},
+ },
+ "https://example.com"
+ )
+ ).resolves.toMatchObject({ data: collection });
+ });
+
test("should fetch resource with search params", async () => {
const mockResponse = new Response(JSON.stringify({ key: "value" }), {
status: 200,
@@ -104,6 +235,192 @@ describe("loadResource", () => {
);
});
+ test("resolves a root-relative URL against the request origin", async () => {
+ mockFetch.mockResolvedValue(new Response("ok"));
+ const resourceRequest: ResourceRequest = {
+ name: "resource",
+ url: "/api/posts",
+ searchParams: [{ name: "tag", value: "news" }],
+ method: "get",
+ headers: [],
+ };
+
+ await loadResource(
+ mockFetch,
+ resourceRequest,
+ "https://example.com/blog/post"
+ );
+
+ expect(mockFetch).toHaveBeenCalledWith(
+ "https://example.com/api/posts?tag=news",
+ {
+ method: "get",
+ headers: new Headers(),
+ }
+ );
+ });
+
+ test("resolves a path-relative URL against the request origin", async () => {
+ mockFetch.mockResolvedValue(new Response("ok"));
+ const resourceRequest: ResourceRequest = {
+ name: "resource",
+ url: "api/posts",
+ searchParams: [],
+ method: "get",
+ headers: [],
+ };
+
+ await loadResource(
+ mockFetch,
+ resourceRequest,
+ "https://example.com/blog/post"
+ );
+
+ expect(mockFetch).toHaveBeenCalledWith("https://example.com/api/posts", {
+ method: "get",
+ headers: new Headers(),
+ });
+ });
+
+ test("does not intercept an external URL that resembles a local resource", () => {
+ expect(
+ isLocalResource("https://example.com/$resources/assets", "assets")
+ ).toBe(false);
+ expect(isLocalResource("//$resources/assets", "assets")).toBe(false);
+ expect(isLocalResource("//example.com/$resources/assets", "assets")).toBe(
+ false
+ );
+ });
+
+ test("matches only the exact Assets resource path", () => {
+ expect(isLocalResource("/$resources/assets", "assets")).toBe(true);
+ expect(isLocalResource("/$resources/assets/query", "assets")).toBe(false);
+ });
+
+ test("keeps a local resource relative while resolving ordinary URLs", async () => {
+ mockFetch.mockResolvedValue(new Response("ok"));
+ await loadResource(
+ mockFetch,
+ {
+ name: "assets",
+ url: "/$resources/assets",
+ searchParams: [{ name: "page", value: 1 }],
+ method: "get",
+ headers: [],
+ },
+ "https://example.com/blog/post"
+ );
+
+ expect(mockFetch).toHaveBeenCalledWith(
+ "/$resources/assets?page=1",
+ expect.any(Object)
+ );
+ });
+
+ test("returns a structured cancellation failure", async () => {
+ const controller = new AbortController();
+ controller.abort();
+ mockFetch.mockImplementation((_input, init) => {
+ if (init?.signal?.aborted) {
+ return Promise.reject(new DOMException("Aborted", "AbortError"));
+ }
+ return Promise.resolve(new Response("unexpected"));
+ });
+ const resourceRequest: ResourceRequest = {
+ name: "resource",
+ url: "https://example.com/resource",
+ searchParams: [],
+ method: "get",
+ headers: [],
+ };
+
+ await expect(
+ loadResource(mockFetch, resourceRequest, undefined, {
+ signal: controller.signal,
+ })
+ ).resolves.toEqual({
+ ok: false,
+ data: {
+ ok: false,
+ error: {
+ code: "REQUEST_CANCELLED",
+ message: "Resource request was cancelled",
+ retryable: false,
+ },
+ },
+ status: 499,
+ statusText: "Resource request was cancelled",
+ });
+ });
+
+ test("aborts at the deadline and returns a structured timeout", async () => {
+ vi.useFakeTimers();
+ mockFetch.mockImplementation(
+ (_input, init) =>
+ new Promise((_resolve, reject) => {
+ init?.signal?.addEventListener("abort", () => {
+ reject(new DOMException("Aborted", "AbortError"));
+ });
+ })
+ );
+ const resourceRequest: ResourceRequest = {
+ name: "resource",
+ url: "https://example.com/resource",
+ searchParams: [],
+ method: "get",
+ headers: [],
+ };
+
+ const pending = loadResource(mockFetch, resourceRequest, undefined, {
+ timeoutMs: 100,
+ });
+ await vi.advanceTimersByTimeAsync(100);
+
+ await expect(pending).resolves.toEqual({
+ ok: false,
+ data: {
+ ok: false,
+ error: {
+ code: "REQUEST_TIMEOUT",
+ message: "Resource request exceeded 100ms",
+ retryable: true,
+ },
+ },
+ status: 504,
+ statusText: "Resource request exceeded 100ms",
+ });
+ });
+
+ test("returns a safe structured network failure", async () => {
+ const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});
+ mockFetch.mockRejectedValue(new Error("secret upstream detail"));
+ const resourceRequest: ResourceRequest = {
+ name: "resource",
+ url: "https://example.com/resource",
+ searchParams: [],
+ method: "get",
+ headers: [],
+ };
+
+ await expect(loadResource(mockFetch, resourceRequest)).resolves.toEqual({
+ ok: false,
+ data: {
+ ok: false,
+ error: {
+ code: "NETWORK_ERROR",
+ message: "Resource request failed",
+ retryable: true,
+ },
+ },
+ status: 502,
+ statusText: "Resource request failed",
+ });
+ expect(errorLog).toHaveBeenCalledWith("Resource request failed");
+ expect(errorLog).not.toHaveBeenCalledWith(
+ expect.stringContaining("secret upstream detail")
+ );
+ });
+
test("should fetch resource with JSON search params", async () => {
const mockResponse = new Response(JSON.stringify({ key: "value" }), {
status: 200,
@@ -156,4 +473,74 @@ describe("loadResource", () => {
]),
});
});
+ test("loads configured Assets queries on the standard endpoint", async () => {
+ mockFetch.mockResolvedValue(Response.json({ ok: true }));
+
+ await loadResource(mockFetch, {
+ name: "Posts",
+ control: "system",
+ url: "/$resources/assets",
+ searchParams: [],
+ method: "post",
+ headers: [{ name: "content-type", value: "application/json" }],
+ body: { query: { where: { all: [] }, limit: 20, offset: 0 } },
+ });
+
+ expect(mockFetch).toHaveBeenCalledWith("/$resources/assets", {
+ method: "post",
+ headers: new Headers([["content-type", "application/json"]]),
+ body: JSON.stringify({
+ query: { where: { all: [] }, limit: 20, offset: 0 },
+ }),
+ });
+ });
+});
+
+describe("getResourceCacheKey", () => {
+ test("separates structured Assets queries and index revisions", async () => {
+ const createRequest = (body: Record<string, unknown>) =>
+ new Request("https://example.com/$resources/assets", {
+ method: "POST",
+ headers: { "cache-control": "public, max-age=60" },
+ body: JSON.stringify(body),
+ });
+ const base = {
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "first",
+ },
+ ],
+ },
+ sort: [{ field: ["createdAt"], direction: "desc" }],
+ limit: 1,
+ offset: 0,
+ output: { mode: "all", includeMetadata: true },
+ content: { mode: "none" },
+ },
+ indexRevision: "index-1",
+ };
+ const requests = [
+ base,
+ { ...base, query: { ...base.query, limit: 2 } },
+ {
+ ...base,
+ query: {
+ ...base.query,
+ content: { mode: "markdown-body", maxBytes: 1024 },
+ },
+ },
+ { ...base, indexRevision: "index-2" },
+ ];
+ const keys = await Promise.all(
+ requests.map(
+ async (body) => (await getResourceCacheKey(createRequest(body))).href
+ )
+ );
+
+ expect(new Set(keys).size).toBe(requests.length);
+ });
});
diff --git a/packages/sdk/src/resource-loader.ts b/packages/sdk/src/resource-loader.ts
index 7aa7a7cd18..ce191315cf 100644
--- a/packages/sdk/src/resource-loader.ts
+++ b/packages/sdk/src/resource-loader.ts
@@ -8,7 +8,15 @@ const LOCAL_RESOURCE_PREFIX = "$resources";
* Prevents fetch cycles by prefixing local resources.
*/
export const isLocalResource = (pathname: string, resourceName?: string) => {
- const segments = pathname.split("/").filter(Boolean);
+ const pathEnd = [pathname.indexOf("?"), pathname.indexOf("#")]
+ .filter((index) => index !== -1)
+ .reduce((first, index) => Math.min(first, index), pathname.length);
+ const path = pathname.slice(0, pathEnd);
+ if (path.startsWith("//")) {
+ return false;
+ }
+ const normalizedPath = path.startsWith("/") ? path.slice(1) : path;
+ const segments = normalizedPath.split("/");
if (resourceName === undefined) {
return segments[0] === LOCAL_RESOURCE_PREFIX;
@@ -21,23 +29,152 @@ export const sitemapResourceUrl = `/${LOCAL_RESOURCE_PREFIX}/sitemap.xml`;
export const currentDateResourceUrl = `/${LOCAL_RESOURCE_PREFIX}/current-date`;
export const assetsResourceUrl = `/${LOCAL_RESOURCE_PREFIX}/assets`;
+// Direct HTTP endpoints described by the Assets OpenAPI document. These are
+// separate from the virtual System resource URLs above, which are resolved
+// only inside Builder's batched resource loader.
+export const assetsApiUrl = "/rest/assets";
+export const assetsUploadsApiUrl = `${assetsApiUrl}/uploads`;
+export const assetsFoldersApiUrl = `${assetsApiUrl}/folders`;
+export const getAssetUploadApiUrl = (name: string) =>
+ `${assetsUploadsApiUrl}/${encodeURIComponent(name)}`;
+export const getAssetContentApiUrl = (assetId: string) =>
+ `${assetsApiUrl}/${encodeURIComponent(assetId)}/content`;
+export const getAssetApiUrl = (assetId: string) =>
+ `${assetsApiUrl}/${encodeURIComponent(assetId)}`;
+export const getAssetFolderApiUrl = (folderId: string) =>
+ `${assetsFoldersApiUrl}/${encodeURIComponent(folderId)}`;
+export const assetsQueryApiUrl = `${assetsApiUrl}/query`;
+export const assetsIndexRefreshApiUrl = `${assetsApiUrl}/index/refresh`;
+export const assetsFieldCatalogApiUrl = `${assetsApiUrl}/field-catalog`;
+export const assetsOpenApiUrl = `${assetsApiUrl}/openapi.json`;
+export const assetsQuerySchemaApiUrl = `${assetsApiUrl}/query-schema.json`;
+
+export type ResourceLoadOptions = {
+ signal?: AbortSignal;
+ timeoutMs?: number;
+};
+
+export const isAssetsResourceRequest = (request: ResourceRequest) =>
+ request.method === "post" && isLocalResource(request.url, "assets");
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null && Array.isArray(value) === false;
+
+// Assets expose one ID-keyed resource contract. Query execution uses an array
+// internally for ordering and pagination.
+const includesAssetId = (body: unknown) => {
+ if (isRecord(body) === false || isRecord(body.query) === false) {
+ return false;
+ }
+ const { output } = body.query;
+ if (isRecord(output) === false) {
+ return false;
+ }
+ if (output.includeMetadata === true) {
+ return true;
+ }
+ return (
+ output.mode === "fields" &&
+ Array.isArray(output.fields) &&
+ output.fields.some(
+ (field) => Array.isArray(field) && field.length === 1 && field[0] === "id"
+ )
+ );
+};
+
+const formatAssetsResourceResult = (value: unknown, body: unknown) => {
+ const preview =
+ isRecord(value) && isRecord(value.data) ? value.data : undefined;
+ const collection = preview ?? value;
+ if (
+ isRecord(collection) === false ||
+ Array.isArray(collection.items) === false ||
+ typeof collection.totalCount !== "number" ||
+ typeof collection.hasMore !== "boolean"
+ ) {
+ return;
+ }
+ const includeId = includesAssetId(body);
+ const diagnostics = isRecord(value) ? value.__diagnostics__ : undefined;
+ const entries: Array<[string, Record<string, unknown>]> = [];
+ for (const item of collection.items) {
+ if (isRecord(item) === false || typeof item.id !== "string") {
+ return;
+ }
+ const { id, ...fields } = item;
+ entries.push([id, includeId ? item : fields]);
+ }
+ return {
+ data: Object.fromEntries(entries),
+ meta: {
+ totalCount: collection.totalCount,
+ hasMore: collection.hasMore,
+ },
+ ...(preview === undefined || diagnostics === undefined
+ ? {}
+ : { __diagnostics__: diagnostics }),
+ };
+};
+
+const transportFailure = ({
+ code,
+ message,
+ retryable,
+ status,
+}: {
+ code: "REQUEST_CANCELLED" | "REQUEST_TIMEOUT" | "NETWORK_ERROR";
+ message: string;
+ retryable: boolean;
+ status: number;
+}) => ({
+ ok: false,
+ data: { ok: false, error: { code, message, retryable } },
+ status,
+ statusText: message,
+});
+
export const loadResource = async (
customFetch: typeof fetch,
- resourceRequest: ResourceRequest
+ resourceRequest: ResourceRequest,
+ baseUrl?: string | URL,
+ options: ResourceLoadOptions = {}
) => {
+ const controller = new AbortController();
+ let didTimeout = false;
+ const cancel = () => controller.abort(options.signal?.reason);
+ if (options.signal?.aborted) {
+ cancel();
+ } else {
+ options.signal?.addEventListener("abort", cancel, { once: true });
+ }
+ const timeoutId =
+ options.timeoutMs === undefined
+ ? undefined
+ : setTimeout(() => {
+ didTimeout = true;
+ controller.abort();
+ }, options.timeoutMs);
+
try {
const { method, searchParams, headers, body } = resourceRequest;
let href = resourceRequest.url;
try {
// cloudflare workers fail when fetching url contains spaces
// even though new URL suppose to trim them on parsing by spec
- const url = new URL(resourceRequest.url.trim());
+ const sourceUrl = resourceRequest.url.trim();
+ const local = isLocalResource(sourceUrl);
+ const resolutionBase = local
+ ? new URL("https://webstudio.local")
+ : baseUrl === undefined
+ ? undefined
+ : new URL("/", baseUrl);
+ const url = new URL(sourceUrl, resolutionBase);
if (searchParams) {
for (const { name, value } of searchParams) {
url.searchParams.append(name, serializeValue(value));
}
}
- href = url.href;
+ href = local ? `${url.pathname}${url.search}` : url.href;
} catch {
// empty block
}
@@ -51,6 +188,9 @@ export const loadResource = async (
method,
headers: requestHeaders,
};
+ if (options.signal !== undefined || options.timeoutMs !== undefined) {
+ requestInit.signal = controller.signal;
+ }
if (method !== "get" && body !== undefined) {
requestInit.body = serializeValue(body);
}
@@ -66,39 +206,69 @@ export const loadResource = async (
}
if (!response.ok) {
- console.error(
- `Failed to load resource: ${href} - ${response.status}: ${JSON.stringify(data).slice(0, 300)}`
- );
+ console.error(`Failed to load resource request: ${response.status}`);
}
- return {
+ const result = {
ok: response.ok,
status: response.status,
statusText: response.statusText,
data,
};
+ if (response.ok && isAssetsResourceRequest(resourceRequest)) {
+ const formatted = formatAssetsResourceResult(data, resourceRequest.body);
+ if (formatted !== undefined) {
+ return { ...result, ...formatted };
+ }
+ }
+ return result;
} catch (error) {
- console.error(error);
- const message = (error as unknown as Error).message;
- return {
- ok: false,
- data: undefined,
- status: 500,
- statusText: message,
- };
+ if (didTimeout) {
+ return transportFailure({
+ code: "REQUEST_TIMEOUT",
+ message: `Resource request exceeded ${options.timeoutMs}ms`,
+ retryable: true,
+ status: 504,
+ });
+ }
+ if (options.signal?.aborted) {
+ return transportFailure({
+ code: "REQUEST_CANCELLED",
+ message: "Resource request was cancelled",
+ retryable: false,
+ status: 499,
+ });
+ }
+ console.error("Resource request failed");
+ return transportFailure({
+ code: "NETWORK_ERROR",
+ message: "Resource request failed",
+ retryable: true,
+ status: 502,
+ });
+ } finally {
+ if (timeoutId !== undefined) {
+ clearTimeout(timeoutId);
+ }
+ options.signal?.removeEventListener("abort", cancel);
}
};
export const loadResources = async (
customFetch: typeof fetch,
- requests: Map<string, ResourceRequest>
+ requests: Map<string, ResourceRequest>,
+ baseUrl?: string | URL,
+ options?: ResourceLoadOptions
) => {
return Object.fromEntries(
await Promise.all(
Array.from(
requests,
async ([name, request]) =>
- [name, await loadResource(customFetch, request)] as const
+ [
+ name,
+ await loadResource(customFetch, request, baseUrl, options),
+ ] as const
)
)
);
@@ -109,7 +279,7 @@ export const loadResources = async (
* put hash of method and body into url
* to support for example graphql queries
*/
-const getCacheKey = async (request: Request) => {
+export const getResourceCacheKey = async (request: Request) => {
const url = new URL(request.url);
const method = request.method;
const body = await request.clone().text();
@@ -133,7 +303,7 @@ export const cachedFetch = async (
return fetch(input, init);
}
const cache = await caches.open(namespace);
- const cacheKey = await getCacheKey(request);
+ const cacheKey = await getResourceCacheKey(request);
let response = await cache.match(cacheKey);
if (response) {
// avoid mutating cached response
diff --git a/packages/sdk/src/resources-generator.test.tsx b/packages/sdk/src/resources-generator.test.tsx
index f5724d554d..8adae1255d 100644
--- a/packages/sdk/src/resources-generator.test.tsx
+++ b/packages/sdk/src/resources-generator.test.tsx
@@ -67,6 +67,37 @@ test("generate resources loader", () => {
`);
});
+test("generates a configured Assets request on the standard endpoint", () => {
+ const generated = generateResources({
+ scope: createScope(),
+ page: { rootInstanceId: "body" } as Page,
+ dataSources: toMap([
+ {
+ id: "postsVariable",
+ scopeInstanceId: "body",
+ type: "resource",
+ name: "Posts",
+ resourceId: "postsResource",
+ },
+ ]),
+ resources: toMap([
+ {
+ id: "postsResource",
+ name: "Posts",
+ control: "system" as const,
+ url: '"/$resources/assets"',
+ method: "post" as const,
+ headers: [],
+ body: "{ query: { where: { all: [] }, limit: 20, offset: 0 } }",
+ },
+ ]),
+ props: new Map(),
+ });
+
+ expect(generated).toContain('url: "/$resources/assets"');
+ expect(generated).not.toContain('resourceId: "postsResource"');
+});
+
test("generate variable and use in resources loader", () => {
expect(
generateResources({
diff --git a/packages/sdk/src/schema.ts b/packages/sdk/src/schema.ts
index 2cd612b327..2a921b57c7 100644
--- a/packages/sdk/src/schema.ts
+++ b/packages/sdk/src/schema.ts
@@ -2,6 +2,7 @@
// API contracts should import domain models from this file instead of the
// package root so they do not pull SDK runtime helpers into API consumers.
export * from "./schema/assets";
+export * from "./schema/asset-resource";
export * from "./schema/asset-folders";
export * from "./schema/breakpoints";
export * from "./schema/data-sources";
diff --git a/packages/sdk/src/schema/asset-folders.ts b/packages/sdk/src/schema/asset-folders.ts
index 1daa687560..48a460e28a 100644
--- a/packages/sdk/src/schema/asset-folders.ts
+++ b/packages/sdk/src/schema/asset-folders.ts
@@ -1,15 +1,20 @@
import { z } from "zod";
+import { assetResourceLimits } from "../asset-resource-limits";
import {
createAssetFolderHierarchy,
getAssetFolderSiblingKey,
} from "../asset-folder-hierarchy";
-export const assetFolderId = z.string().min(1);
+export const assetFolderId = z
+ .string()
+ .min(1)
+ .max(assetResourceLimits.assetIdentifierCharacters);
export const assetFolderName = z
.string()
.trim()
- .min(1, "Folder name can't be empty");
+ .min(1, "Folder name can't be empty")
+ .max(assetResourceLimits.assetFolderNameCharacters);
export const assetFolderIssue = {
idMismatch: "Folder id must match its record key",
diff --git a/packages/sdk/src/schema/asset-resource.test.ts b/packages/sdk/src/schema/asset-resource.test.ts
new file mode 100644
index 0000000000..81c937b8fd
--- /dev/null
+++ b/packages/sdk/src/schema/asset-resource.test.ts
@@ -0,0 +1,202 @@
+import { describe, expect, test } from "vitest";
+import { assetQueryResourceConfigurationInput } from "./asset-resource";
+import {
+ assetFileDocument,
+ builderAssetFieldCatalog,
+} from "@webstudio-is/content-engine";
+
+const document = {
+ _id: "asset-1",
+ _type: "asset.file" as const,
+ name: "hello-world.md",
+ path: "blog/hello-world.md",
+ key: "hello-world",
+ folderId: "blog-folder",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 4280,
+ revision: "sha256:content-hash",
+ contentRef: "asset-1/sha256:content-hash",
+ properties: {
+ title: "Hello world",
+ draft: false,
+ author: { name: "Oleg" },
+ tags: ["news", "release"],
+ },
+ excerpt: "The beginning of the article...",
+};
+
+describe("assetFileDocument", () => {
+ test("accepts a schema-less Markdown document", () => {
+ expect(assetFileDocument.parse(document)).toEqual(document);
+ });
+
+ test("accepts a root asset without optional Markdown fields", () => {
+ const {
+ excerpt: _excerpt,
+ folderId: _folderId,
+ ...rootDocument
+ } = document;
+
+ expect(assetFileDocument.parse(rootDocument)).toEqual(rootDocument);
+ });
+
+ test.each([
+ "/blog/post.md",
+ "blog/../post.md",
+ "./post.md",
+ "blog//post.md",
+ "blog\\post.md",
+ ])("rejects unsafe path %s", (path) => {
+ expect(assetFileDocument.safeParse({ ...document, path }).success).toBe(
+ false
+ );
+ });
+
+ test("rejects non-JSON frontmatter values", () => {
+ expect(
+ assetFileDocument.safeParse({
+ ...document,
+ properties: { publishedAt: new Date() },
+ }).success
+ ).toBe(false);
+ });
+});
+
+describe("builderAssetFieldCatalog", () => {
+ test("accepts the compact versioned Builder representation", () => {
+ const catalog = {
+ format: "webstudio-builder-asset-field-catalog" as const,
+ version: 1 as const,
+ canonicalRevision: `sha256:${"a".repeat(64)}`,
+ documentCount: 2,
+ fields: {
+ name: { types: ["string" as const], occurrences: 2 },
+ "properties.title": {
+ types: ["number" as const, "string" as const],
+ occurrences: 1,
+ optional: true as const,
+ mixed: true as const,
+ },
+ },
+ };
+ expect(builderAssetFieldCatalog.parse(catalog)).toEqual(catalog);
+ });
+
+ test("rejects invalid revisions and non-compact false flags", () => {
+ expect(
+ builderAssetFieldCatalog.safeParse({
+ format: "webstudio-builder-asset-field-catalog",
+ version: 1,
+ canonicalRevision: "revision-1",
+ documentCount: 0,
+ fields: {},
+ }).success
+ ).toBe(false);
+ expect(
+ builderAssetFieldCatalog.safeParse({
+ format: "webstudio-builder-asset-field-catalog",
+ version: 1,
+ canonicalRevision: `sha256:${"a".repeat(64)}`,
+ documentCount: 1,
+ fields: {
+ name: {
+ types: ["string"],
+ occurrences: 1,
+ optional: false,
+ },
+ },
+ }).success
+ ).toBe(false);
+ });
+
+ test("rejects contradictory occurrence, optional, and mixed metadata", () => {
+ const base = {
+ format: "webstudio-builder-asset-field-catalog",
+ version: 1,
+ canonicalRevision: `sha256:${"a".repeat(64)}`,
+ documentCount: 1,
+ };
+ expect(
+ builderAssetFieldCatalog.safeParse({
+ ...base,
+ fields: {
+ name: { types: ["string"], occurrences: 2 },
+ },
+ }).success
+ ).toBe(false);
+ expect(
+ builderAssetFieldCatalog.safeParse({
+ ...base,
+ documentCount: 2,
+ fields: {
+ name: { types: ["string"], occurrences: 1 },
+ },
+ }).success
+ ).toBe(false);
+ expect(
+ builderAssetFieldCatalog.safeParse({
+ ...base,
+ fields: {
+ name: { types: ["string", "number"], occurrences: 1 },
+ },
+ }).success
+ ).toBe(false);
+ });
+});
+
+describe("assetQueryResourceConfigurationInput", () => {
+ test("accepts JSON filter literals and bounded numeric pagination literals", () => {
+ expect(
+ assetQueryResourceConfigurationInput.safeParse({
+ where: {
+ all: [
+ {
+ field: ["properties", "draft"],
+ operator: "ne",
+ value: { type: "literal", value: true },
+ },
+ ],
+ },
+ limit: { type: "literal", value: 20 },
+ offset: { type: "literal", value: 0 },
+ }).success
+ ).toBe(true);
+ });
+
+ test("rejects non-JSON literals and invalid numeric pagination literals", () => {
+ expect(
+ assetQueryResourceConfigurationInput.safeParse({
+ where: {
+ all: [
+ {
+ field: ["properties", "publishedAt"],
+ operator: "eq",
+ value: { type: "literal", value: new Date() },
+ },
+ ],
+ },
+ }).success
+ ).toBe(false);
+ expect(
+ assetQueryResourceConfigurationInput.safeParse({
+ limit: { type: "literal", value: "20" },
+ }).success
+ ).toBe(false);
+ });
+
+ test("rejects filter trees beyond the nesting limit", () => {
+ let where: unknown = {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "hello",
+ };
+ for (let depth = 0; depth < 9; depth += 1) {
+ where = { all: [where] };
+ }
+
+ expect(
+ assetQueryResourceConfigurationInput.safeParse({ where }).success
+ ).toBe(false);
+ });
+});
diff --git a/packages/sdk/src/schema/asset-resource.ts b/packages/sdk/src/schema/asset-resource.ts
new file mode 100644
index 0000000000..e35a3bd996
--- /dev/null
+++ b/packages/sdk/src/schema/asset-resource.ts
@@ -0,0 +1,123 @@
+import { z } from "zod";
+import {
+ createQueryWhereSchema,
+ type QueryWhereTree,
+} from "@webstudio-is/query-builder/runtime";
+import { isQueryExpression } from "@webstudio-is/query-builder";
+import {
+ assetQueryFieldPath,
+ assetQueryOperators,
+ assetQuerySort,
+ defaultAssetResourceOutputSelection,
+ assetResourceContentOptions,
+ assetResourceOutputSelection,
+ type AssetQueryFieldPath,
+ type AssetQueryFilter,
+} from "@webstudio-is/content-engine";
+import { assetResourceLimits } from "../asset-resource-limits";
+
+const assetQueryLiteral = <Schema extends z.ZodType>(value: Schema) =>
+ z.strictObject({ type: z.literal("literal"), value });
+
+const assetQueryExpression = z
+ .string()
+ .refine(isQueryExpression, "Asset query expression is invalid");
+
+export const assetQueryFilterValueExpression = z.union([
+ assetQueryExpression,
+ assetQueryLiteral(z.json()),
+]);
+
+export type AssetQueryFilterValueExpression = z.infer<
+ typeof assetQueryFilterValueExpression
+>;
+
+export type AssetQueryWhereExpression = QueryWhereTree<{
+ field: AssetQueryFieldPath;
+ operator: AssetQueryFilter["operator"];
+ value: AssetQueryFilterValueExpression;
+}>;
+
+export const assetQueryWhereExpression: z.ZodType<
+ AssetQueryWhereExpression,
+ AssetQueryWhereExpression
+> = createQueryWhereSchema(
+ z.strictObject({
+ field: assetQueryFieldPath.describe(
+ 'Indexed file field path, for example ["extension"] or ["properties", "slug"].'
+ ),
+ operator: z.enum(assetQueryOperators),
+ value: assetQueryFilterValueExpression.describe(
+ 'A Webstudio expression, or { type: "literal", value: <JSON value> } for fixed data.'
+ ),
+ }),
+ {
+ maximumChildren: assetResourceLimits.filterCount,
+ maximumConditions: assetResourceLimits.filterCount,
+ maximumDepth: assetResourceLimits.filterDepth,
+ maximumConditionsMessage: "Asset query exceeds the filter limit",
+ maximumDepthMessage: "Asset query exceeds the filter nesting limit",
+ }
+);
+
+export const assetQueryLimitExpression = z.union([
+ assetQueryExpression,
+ assetQueryLiteral(
+ z.number().int().nonnegative().max(assetResourceLimits.resultCount)
+ ),
+]);
+
+export const assetQueryOffsetExpression = z.union([
+ assetQueryExpression,
+ assetQueryLiteral(
+ z.number().int().nonnegative().max(assetResourceLimits.candidateDocuments)
+ ),
+]);
+
+export const assetQueryResourceConfigurationInput = z.strictObject({
+ where: assetQueryWhereExpression
+ .describe(
+ "A boolean filter tree. Use { all: [...] } for AND and { any: [...] } for OR; leaves contain field, operator, and value."
+ )
+ .default({ all: [] }),
+ sort: z.array(assetQuerySort).max(assetResourceLimits.sortCount).default([]),
+ limit: assetQueryLimitExpression
+ .describe(
+ 'A Webstudio expression, or { type: "literal", value: number } for a fixed result limit.'
+ )
+ .default(String(assetResourceLimits.defaultResultCount)),
+ offset: assetQueryOffsetExpression
+ .describe(
+ 'A Webstudio expression, or { type: "literal", value: number } for a fixed result offset.'
+ )
+ .default("0"),
+ output: assetResourceOutputSelection.default(
+ defaultAssetResourceOutputSelection
+ ),
+ content: assetResourceContentOptions.default({ mode: "none" }),
+});
+
+export const assetQueryResourceConfigurationPatchInput = z.strictObject({
+ where: assetQueryResourceConfigurationInput.shape.where
+ .removeDefault()
+ .optional(),
+ sort: assetQueryResourceConfigurationInput.shape.sort
+ .removeDefault()
+ .optional(),
+ limit: assetQueryResourceConfigurationInput.shape.limit
+ .removeDefault()
+ .optional(),
+ offset: assetQueryResourceConfigurationInput.shape.offset
+ .removeDefault()
+ .optional(),
+ output: assetQueryResourceConfigurationInput.shape.output
+ .removeDefault()
+ .optional(),
+ content: assetQueryResourceConfigurationInput.shape.content
+ .removeDefault()
+ .optional(),
+});
+
+export type AssetQueryResourceConfigurationInput = z.input<
+ typeof assetQueryResourceConfigurationInput
+>;
diff --git a/packages/sdk/src/schema/assets.ts b/packages/sdk/src/schema/assets.ts
index 4ced5970c3..18b0d57344 100644
--- a/packages/sdk/src/schema/assets.ts
+++ b/packages/sdk/src/schema/assets.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
import { assetFolderId } from "./asset-folders";
-import { fontFormat, fontMeta } from "@webstudio-is/fonts";
+import { fontFormat, fontMeta, fontMetaUpdate } from "@webstudio-is/fonts";
const assetId = z.string();
@@ -33,6 +33,12 @@ export const imageMeta = z.object({
});
export type ImageMeta = z.infer<typeof imageMeta>;
+export const assetMetaUpdate = z.union([
+ fontMetaUpdate,
+ imageMeta.partial().strict(),
+ z.object({}).strict(),
+]);
+
export const imageAsset = z.object({
...baseAsset,
format: z.string(),
diff --git a/packages/sdk/src/schema/data-sources.test.ts b/packages/sdk/src/schema/data-sources.test.ts
index aed6f9b8ae..e0739e2dd2 100644
--- a/packages/sdk/src/schema/data-sources.test.ts
+++ b/packages/sdk/src/schema/data-sources.test.ts
@@ -1,5 +1,5 @@
import { expect, test } from "vitest";
-import { dataSource } from "./data-sources";
+import { dataSource, dataSourceVariableValue } from "./data-sources";
test("normalizes legacy json data variables without value", () => {
expect(
@@ -16,3 +16,18 @@ test("normalizes legacy json data variables without value", () => {
value: { type: "json", value: null },
});
});
+
+test("requires new arrays to use json variables", () => {
+ expect(
+ dataSourceVariableValue.safeParse({
+ type: "string[]",
+ value: ["news", "product"],
+ }).success
+ ).toBe(false);
+ expect(
+ dataSourceVariableValue.parse({
+ type: "json",
+ value: ["news", "product"],
+ })
+ ).toEqual({ type: "json", value: ["news", "product"] });
+});
diff --git a/packages/sdk/src/schema/data-sources.ts b/packages/sdk/src/schema/data-sources.ts
index cc279069a9..d33d02b207 100644
--- a/packages/sdk/src/schema/data-sources.ts
+++ b/packages/sdk/src/schema/data-sources.ts
@@ -2,30 +2,34 @@ import { z } from "zod";
const dataSourceId = z.string();
+const numberDataSourceVariableValue = z.object({
+ type: z.literal("number"),
+ // initial value of variable store
+ value: z.number(),
+});
+
+const stringDataSourceVariableValue = z.object({
+ type: z.literal("string"),
+ value: z.string(),
+});
+
+const booleanDataSourceVariableValue = z.object({
+ type: z.literal("boolean"),
+ value: z.boolean(),
+});
+
+const jsonDataSourceVariableValue = z
+ .object({
+ type: z.literal("json"),
+ value: z.unknown().optional(),
+ })
+ .transform((value) => ({ ...value, value: value.value ?? null }));
+
export const dataSourceVariableValue = z.union([
- z.object({
- type: z.literal("number"),
- // initial value of variable store
- value: z.number(),
- }),
- z.object({
- type: z.literal("string"),
- value: z.string(),
- }),
- z.object({
- type: z.literal("boolean"),
- value: z.boolean(),
- }),
- z.object({
- type: z.literal("string[]"),
- value: z.array(z.string()),
- }),
- z
- .object({
- type: z.literal("json"),
- value: z.unknown().optional(),
- })
- .transform((value) => ({ ...value, value: value.value ?? null })),
+ numberDataSourceVariableValue,
+ stringDataSourceVariableValue,
+ booleanDataSourceVariableValue,
+ jsonDataSourceVariableValue,
]);
export const dataSource = z.union([
diff --git a/packages/trpc-interface/src/context/router.server.test.ts b/packages/trpc-interface/src/context/router.server.test.ts
index d16b36aa33..d73f15c1e7 100644
--- a/packages/trpc-interface/src/context/router.server.test.ts
+++ b/packages/trpc-interface/src/context/router.server.test.ts
@@ -79,3 +79,35 @@ test("includes structured validation issues in formatted tRPC errors", async ()
},
});
});
+
+test("does not classify a domain not-found error as API incompatibility", async () => {
+ const appRouter = router({
+ fail: procedure.query(() => {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ cause: Object.assign(new Error("Index was not found"), {
+ webstudioCode: "ASSET_RESOURCE_INDEX_NOT_FOUND",
+ }),
+ });
+ }),
+ });
+
+ const response = await fetchRequestHandler({
+ endpoint: "/trpc",
+ req: new Request("http://localhost/trpc/fail"),
+ router: appRouter,
+ createContext,
+ });
+
+ expect(response.status).toBe(404);
+ const body = await response.json();
+ expect(body).toMatchObject({
+ error: {
+ data: {
+ code: "NOT_FOUND",
+ webstudioCode: "ASSET_RESOURCE_INDEX_NOT_FOUND",
+ },
+ },
+ });
+ expect(JSON.stringify(body)).not.toContain("apiCompatibility");
+});
diff --git a/packages/trpc-interface/src/context/router.server.ts b/packages/trpc-interface/src/context/router.server.ts
index 37774ce58c..7cc557cecc 100644
--- a/packages/trpc-interface/src/context/router.server.ts
+++ b/packages/trpc-interface/src/context/router.server.ts
@@ -30,15 +30,17 @@ export const {
} = initTRPC.context<AppContext>().create({
errorFormatter({ shape, error, ctx }) {
const target = ctx?.apiClient.type;
+ const webstudioCode = getWebstudioErrorCode(error.cause);
const payload =
getApiCompatibilityPayload(error.cause) ??
- (error.code === "NOT_FOUND" && (target === "browser" || target === "cli")
+ (error.code === "NOT_FOUND" &&
+ webstudioCode === undefined &&
+ (target === "browser" || target === "cli")
? createApiCompatibilityPayload({
reason: "apiProcedureNotFound",
target,
})
: undefined);
- const webstudioCode = getWebstudioErrorCode(error.cause);
const issues = getValidationIssues(error.cause);
if (
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 8783e67f89..9953c92a29 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -55,7 +55,7 @@ importers:
'@storybook/react-vite':
specifier: ^8.6.4
'@types/node':
specifier: ^22.13.10
version: 22.13.10
@@ -94,7 +94,7 @@ importers:
version: 7.0.2
vite:
specifier: 6.3.4
apps/builder:
dependencies:
@@ -232,13 +232,16 @@ importers:
version: 66.6.8
'@vercel/remix':
specifier: 2.15.3
'@webstudio-is/asset-uploader':
specifier: workspace:*
version: link:../../packages/asset-uploader
'@webstudio-is/authorization-token':
specifier: workspace:*
version: link:../../packages/authorization-token
+ '@webstudio-is/content-engine':
+ specifier: workspace:0.0.0-webstudio-version
+ version: link:../../packages/content-engine
'@webstudio-is/css-data':
specifier: workspace:*
version: link:../../packages/css-data
@@ -254,6 +257,9 @@ importers:
'@webstudio-is/domain':
specifier: workspace:*
version: link:../../packages/domain
+ '@webstudio-is/expression':
+ specifier: workspace:*
+ version: link:../../packages/expression
'@webstudio-is/feature-flags':
specifier: workspace:*
version: link:../../packages/feature-flags
@@ -290,6 +296,12 @@ importers:
'@webstudio-is/protocol':
specifier: workspace:*
version: link:../../packages/protocol
+ '@webstudio-is/query-builder':
+ specifier: workspace:*
+ version: link:../../packages/query-builder
+ '@webstudio-is/query-builder-react':
+ specifier: workspace:*
+ version: link:../../packages/query-builder-react
'@webstudio-is/react-sdk':
specifier: workspace:*
version: link:../../packages/react-sdk
@@ -389,6 +401,9 @@ importers:
pretty-bytes:
specifier: ^6.1.1
version: 6.1.1
+ range-parser:
+ specifier: ^1.2.1
+ version: 1.2.1
react:
specifier: 18.3.0-canary-14898b6a9-20240318
version: 18.3.0-canary-14898b6a9-20240318
@@ -449,7 +464,7 @@ importers:
devDependencies:
'@remix-run/dev':
specifier: ^2.16.5
'@types/debug':
specifier: ^4.1.12
version: 4.1.12
@@ -459,6 +474,9 @@ importers:
'@types/express':
specifier: ^4.17.21
version: 4.17.21
+ '@types/range-parser':
+ specifier: ^1.2.7
+ version: 1.2.7
'@types/react':
specifier: ^18.2.70
version: 18.2.79
@@ -500,22 +518,22 @@ importers:
version: 7.0.2
vite:
specifier: 6.3.4
vitest:
specifier: ^3.1.2
fixtures/react-router-cloudflare:
dependencies:
'@cloudflare/vite-plugin':
specifier: ^1.1.0
'@react-router/dev':
specifier: ^7.5.3
'@react-router/fs-routes':
specifier: ^7.5.3
'@react-router/node':
specifier: ^7.5.3
@@ -560,7 +578,7 @@ importers:
vite:
specifier: 6.3.4
webstudio:
specifier: workspace:*
version: link:../../packages/cli
@@ -582,10 +600,10 @@ importers:
dependencies:
'@react-router/dev':
specifier: ^7.5.3
'@react-router/fs-routes':
specifier: ^7.5.3
'@react-router/node':
specifier: ^7.5.3
@@ -636,7 +654,7 @@ importers:
vite:
specifier: 6.3.4
webstudio:
specifier: workspace:*
version: link:../../packages/cli
@@ -655,13 +673,13 @@ importers:
dependencies:
'@netlify/vite-plugin-react-router':
specifier: ^1.0.1
'@react-router/dev':
specifier: ^7.5.3
'@react-router/fs-routes':
specifier: ^7.5.3
'@react-router/node':
specifier: ^7.5.3
@@ -706,7 +724,7 @@ importers:
vite:
specifier: 6.3.4
webstudio:
specifier: workspace:*
version: link:../../packages/cli
@@ -725,10 +743,10 @@ importers:
dependencies:
'@react-router/dev':
specifier: ^7.5.3
'@react-router/fs-routes':
specifier: ^7.5.3
'@react-router/node':
specifier: ^7.5.3
@@ -737,7 +755,7 @@ importers:
'@vercel/react-router':
specifier: ^1.1.0
'@webstudio-is/image':
specifier: workspace:*
version: link:../../packages/image
@@ -776,7 +794,7 @@ importers:
vite:
specifier: 6.3.4
webstudio:
specifier: workspace:*
version: link:../../packages/cli
@@ -825,7 +843,7 @@ importers:
version: 18.3.0-canary-14898b6a9-20240318([email protected])
vike:
specifier: ^0.4.229
devDependencies:
'@types/react':
specifier: ^18.2.70
@@ -835,13 +853,13 @@ importers:
version: 18.2.25
'@vitejs/plugin-react':
specifier: ^4.4.1
typescript:
specifier: 7.0.2
version: 7.0.2
vite:
specifier: 6.3.4
webstudio:
specifier: workspace:*
version: link:../../packages/cli
@@ -880,7 +898,7 @@ importers:
version: 18.3.0-canary-14898b6a9-20240318([email protected])
vike:
specifier: ^0.4.229
devDependencies:
'@types/react':
specifier: ^18.2.70
@@ -890,13 +908,13 @@ importers:
version: 18.2.25
'@vitejs/plugin-react':
specifier: ^4.4.1
typescript:
specifier: 7.0.2
version: 7.0.2
vite:
specifier: 6.3.4
webstudio:
specifier: workspace:*
version: link:../../packages/cli
@@ -966,7 +984,7 @@ importers:
version: 4.20240701.0
'@remix-run/dev':
specifier: 2.16.5
'@types/react':
specifier: ^18.2.70
version: 18.2.79
@@ -981,7 +999,7 @@ importers:
version: 7.0.2
vite:
specifier: 6.3.4
wrangler:
specifier: ^3.63.2
version: 3.63.2(@cloudflare/[email protected])
@@ -993,10 +1011,10 @@ importers:
version: 2.14.4
'@react-router/dev':
specifier: ^7.5.3
'@react-router/fs-routes':
specifier: ^7.5.3
'@react-router/node':
specifier: ^7.5.3
@@ -1041,7 +1059,7 @@ importers:
vite:
specifier: 6.3.4
webstudio:
specifier: workspace:*
version: link:../../packages/cli
@@ -1067,6 +1085,9 @@ importers:
'@smithy/signature-v4':
specifier: ^5.1.3
version: 5.1.3
+ '@webstudio-is/content-engine':
+ specifier: workspace:*
+ version: link:../content-engine
'@webstudio-is/fonts':
specifier: workspace:*
version: link:../fonts
@@ -1106,7 +1127,7 @@ importers:
version: 2.13.2(@types/[email protected])([email protected])
vitest:
specifier: ^3.1.2
zod:
specifier: ^4.4.3
version: 4.4.3
@@ -1137,7 +1158,7 @@ importers:
version: 4.37.0
vitest:
specifier: ^3.1.2
packages/cli:
dependencies:
@@ -1228,16 +1249,16 @@ importers:
devDependencies:
'@cloudflare/vite-plugin':
specifier: ^1.1.0
'@netlify/vite-plugin-react-router':
specifier: ^1.0.1
'@react-router/dev':
specifier: ^7.5.3
'@react-router/fs-routes':
specifier: ^7.5.3
'@react-router/node':
specifier: ^7.5.3
@@ -1252,7 +1273,7 @@ importers:
version: 2.16.5(@cloudflare/[email protected])([email protected])
'@remix-run/dev':
specifier: ^2.16.5
'@remix-run/node':
specifier: ^2.16.5
version: 2.16.5([email protected])
@@ -1276,13 +1297,19 @@ importers:
version: 17.0.33
'@vercel/react-router':
specifier: ^1.1.0
'@vitejs/plugin-react':
specifier: ^4.4.1
+ '@webstudio-is/content-engine':
+ specifier: workspace:*
+ version: link:../content-engine
'@webstudio-is/css-engine':
specifier: workspace:*
version: link:../css-engine
+ '@webstudio-is/expression':
+ specifier: workspace:*
+ version: link:../expression
'@webstudio-is/fonts':
specifier: workspace:*
version: link:../fonts
@@ -1292,6 +1319,9 @@ importers:
'@webstudio-is/project-build':
specifier: workspace:*
version: link:../project-build
+ '@webstudio-is/query-builder':
+ specifier: workspace:*
+ version: link:../query-builder
'@webstudio-is/react-sdk':
specifier: workspace:*
version: link:../react-sdk
@@ -1363,17 +1393,57 @@ importers:
version: 7.0.2
vike:
specifier: ^0.4.229
vite:
specifier: 6.3.4
vitest:
specifier: ^3.1.2
wrangler:
specifier: ^3.63.2
version: 3.63.2(@cloudflare/[email protected])
+ packages/content-engine:
+ dependencies:
+ '@webstudio-is/expression':
+ specifier: workspace:*
+ version: link:../expression
+ '@webstudio-is/query-builder':
+ specifier: workspace:*
+ version: link:../query-builder
+ canonicalize:
+ specifier: 3.0.0
+ version: 3.0.0
+ micromark:
+ specifier: 4.0.2
+ version: 4.0.2
+ micromark-util-decode-string:
+ specifier: 2.0.1
+ version: 2.0.1
+ remark-parse:
+ specifier: 10.0.2
+ version: 10.0.2
+ unified:
+ specifier: 10.1.2
+ version: 10.1.2
+ yaml:
+ specifier: 2.9.0
+ version: 2.9.0
+ zod:
+ specifier: ^4.4.3
+ version: 4.4.3
+ devDependencies:
+ '@webstudio-is/tsconfig':
+ specifier: workspace:*
+ version: link:../tsconfig
+ esbuild:
+ specifier: ^0.25.3
+ version: 0.25.3
+ vitest:
+ specifier: ^3.1.2
+
packages/css-data:
dependencies:
'@webstudio-is/css-engine':
@@ -1409,7 +1479,7 @@ importers:
version: 7.0.2
vitest:
specifier: ^3.1.2
zod:
specifier: ^4.4.3
version: 4.4.3
@@ -1449,7 +1519,7 @@ importers:
version: 18.3.0-canary-14898b6a9-20240318([email protected])
vitest:
specifier: ^3.1.2
packages/dashboard:
dependencies:
@@ -1480,7 +1550,7 @@ importers:
version: 2.13.2(@types/[email protected])([email protected])
vitest:
specifier: ^3.1.2
packages/design-system:
dependencies:
@@ -1643,7 +1713,7 @@ importers:
version: 18.3.0-canary-14898b6a9-20240318([email protected])
vitest:
specifier: ^3.1.2
zod:
specifier: ^4.4.3
version: 4.4.3
@@ -1683,7 +1753,26 @@ importers:
version: 2.13.2(@types/[email protected])([email protected])
vitest:
specifier: ^3.1.2
+
+ packages/expression:
+ dependencies:
+ acorn:
+ specifier: ^8.14.1
+ version: 8.17.0
+ acorn-walk:
+ specifier: ^8.3.4
+ version: 8.3.5
+ devDependencies:
+ '@vitest/coverage-v8':
+ specifier: 3.1.2
+ version: 3.1.2(@vitest/[email protected])([email protected])
+ '@webstudio-is/tsconfig':
+ specifier: workspace:*
+ version: link:../tsconfig
+ vitest:
+ specifier: ^3.1.2
packages/feature-flags:
devDependencies:
@@ -1698,7 +1787,7 @@ importers:
version: link:../tsconfig
vitest:
specifier: ^3.1.2
zod:
specifier: ^4.4.3
version: 4.4.3
@@ -1782,7 +1871,7 @@ importers:
version: link:../tsconfig
vitest:
specifier: ^3.1.2
packages/icons:
devDependencies:
@@ -1843,7 +1932,7 @@ importers:
version: 18.3.0-canary-14898b6a9-20240318([email protected])
vitest:
specifier: ^3.1.2
packages/multiplayer-protocol:
devDependencies:
@@ -1852,7 +1941,7 @@ importers:
version: link:../tsconfig
vitest:
specifier: ^3.1.2
packages/plans:
dependencies:
@@ -1868,7 +1957,7 @@ importers:
version: link:../tsconfig
vitest:
specifier: ^3.1.2
packages/postgrest:
dependencies:
@@ -1884,7 +1973,7 @@ importers:
version: 2.13.2(@types/[email protected])([email protected])
vitest:
specifier: ^3.1.2
packages/prisma-client:
dependencies:
@@ -1907,6 +1996,9 @@ importers:
prisma:
specifier: 5.12.1
version: 5.12.1
+ vitest:
+ specifier: ^3.1.2
zod:
specifier: ^4.4.3
version: 4.4.3
@@ -1967,7 +2059,7 @@ importers:
version: 2.13.2(@types/[email protected])([email protected])
vitest:
specifier: ^3.1.2
packages/project-build:
dependencies:
@@ -1980,12 +2072,18 @@ importers:
'@webstudio-is/authorization-token':
specifier: workspace:*
version: link:../authorization-token
+ '@webstudio-is/content-engine':
+ specifier: workspace:*
+ version: link:../content-engine
'@webstudio-is/css-data':
specifier: workspace:*
version: link:../css-data
'@webstudio-is/css-engine':
specifier: workspace:*
version: link:../css-engine
+ '@webstudio-is/expression':
+ specifier: workspace:*
+ version: link:../expression
'@webstudio-is/fonts':
specifier: workspace:*
version: link:../fonts
@@ -2001,6 +2099,9 @@ importers:
'@webstudio-is/project-migrations':
specifier: workspace:*
version: link:../project-migrations
+ '@webstudio-is/query-builder':
+ specifier: workspace:*
+ version: link:../query-builder
'@webstudio-is/react-sdk':
specifier: workspace:*
version: link:../react-sdk
@@ -2079,7 +2180,7 @@ importers:
version: link:../tsconfig
vitest:
specifier: ^3.1.2
packages/project-migrations:
dependencies:
@@ -2107,13 +2208,16 @@ importers:
version: 7.0.2
vitest:
specifier: ^3.1.2
packages/protocol:
dependencies:
'@emotion/hash':
specifier: ^0.9.2
version: 0.9.2
+ '@webstudio-is/content-engine':
+ specifier: workspace:*
+ version: link:../content-engine
'@webstudio-is/css-engine':
specifier: workspace:*
version: link:../css-engine
@@ -2127,9 +2231,15 @@ importers:
specifier: ^4.4.3
version: 4.4.3
devDependencies:
+ '@apidevtools/swagger-parser':
+ specifier: ^12.1.0
+ version: 12.1.0([email protected])
'@webstudio-is/project-build':
specifier: workspace:*
version: link:../project-build
+ '@webstudio-is/query-builder':
+ specifier: workspace:*
+ version: link:../query-builder
'@webstudio-is/tsconfig':
specifier: workspace:*
version: link:../tsconfig
@@ -2138,13 +2248,66 @@ importers:
version: link:../wsauth
vitest:
specifier: ^3.1.2
+
+ packages/query-builder:
+ dependencies:
+ '@webstudio-is/expression':
+ specifier: workspace:*
+ version: link:../expression
+ zod:
+ specifier: ^4.4.3
+ version: 4.4.3
+ devDependencies:
+ '@webstudio-is/tsconfig':
+ specifier: workspace:*
+ version: link:../tsconfig
+ vitest:
+ specifier: ^3.1.2
+
+ packages/query-builder-react:
+ dependencies:
+ '@webstudio-is/design-system':
+ specifier: workspace:*
+ version: link:../design-system
+ '@webstudio-is/icons':
+ specifier: workspace:*
+ version: link:../icons
+ '@webstudio-is/query-builder':
+ specifier: workspace:*
+ version: link:../query-builder
+ react:
+ specifier: 18.3.0-canary-14898b6a9-20240318
+ version: 18.3.0-canary-14898b6a9-20240318
+ devDependencies:
+ '@testing-library/react':
+ specifier: ^16.2.0
+ '@types/react':
+ specifier: ^18.2.70
+ version: 18.2.79
+ '@types/react-dom':
+ specifier: ^18.2.25
+ version: 18.2.25
+ '@webstudio-is/tsconfig':
+ specifier: workspace:*
+ version: link:../tsconfig
+ react-dom:
+ specifier: 18.3.0-canary-14898b6a9-20240318
+ version: 18.3.0-canary-14898b6a9-20240318([email protected])
+ vitest:
+ specifier: ^3.1.2
packages/react-sdk:
dependencies:
'@webstudio-is/css-engine':
specifier: workspace:*
version: link:../css-engine
+ '@webstudio-is/expression':
+ specifier: workspace:*
+ version: link:../expression
'@webstudio-is/fonts':
specifier: workspace:*
version: link:../fonts
@@ -2193,7 +2356,7 @@ importers:
version: 7.0.2
vitest:
specifier: ^3.1.2
zod:
specifier: ^4.4.3
version: 4.4.3
@@ -2203,24 +2366,27 @@ importers:
'@emotion/hash':
specifier: ^0.9.2
version: 0.9.2
+ '@webstudio-is/content-engine':
+ specifier: workspace:*
+ version: link:../content-engine
'@webstudio-is/css-engine':
specifier: workspace:*
version: link:../css-engine
+ '@webstudio-is/expression':
+ specifier: workspace:*
+ version: link:../expression
'@webstudio-is/fonts':
specifier: workspace:*
version: link:../fonts
'@webstudio-is/icons':
specifier: workspace:*
version: link:../icons
+ '@webstudio-is/query-builder':
+ specifier: workspace:*
+ version: link:../query-builder
'@webstudio-is/wsauth':
specifier: workspace:*
version: link:../wsauth
- acorn:
- specifier: ^8.14.1
- version: 8.14.1
- acorn-walk:
- specifier: ^8.3.4
- version: 8.3.4
change-case:
specifier: ^5.4.4
version: 5.4.4
@@ -2260,7 +2426,7 @@ importers:
version: 5.5.3
vitest:
specifier: ^3.1.2
packages/sdk-cli:
dependencies:
@@ -2285,7 +2451,7 @@ importers:
version: link:../tsconfig
vitest:
specifier: ^3.1.2
packages/sdk-components-animation:
dependencies:
@@ -2322,7 +2488,7 @@ importers:
version: 18.2.25
'@vitest/browser':
specifier: ^3.0.8
'@webstudio-is/css-data':
specifier: workspace:*
version: link:../css-data
@@ -2361,7 +2527,7 @@ importers:
version: 4.37.0
vitest:
specifier: ^3.1.2
zod:
specifier: ^4.4.3
version: 4.4.3
@@ -2389,12 +2555,30 @@ importers:
colord:
specifier: ^2.9.3
version: 2.9.3
+ github-slugger:
+ specifier: 2.0.0
+ version: 2.0.0
+ mdast-util-from-markdown:
+ specifier: 2.0.3
+ version: 2.0.3
+ mdast-util-frontmatter:
+ specifier: 2.0.1
+ version: 2.0.1
+ mdast-util-to-string:
+ specifier: 4.0.0
+ version: 4.0.0
micromark:
specifier: ^4.0.2
version: 4.0.2
- micromark-extension-gfm-table:
- specifier: ^2.1.1
- version: 2.1.1
+ micromark-extension-frontmatter:
+ specifier: 2.0.0
+ version: 2.0.0
+ micromark-extension-gfm:
+ specifier: ^3.0.0
+ version: 3.0.0
+ sanitize-html:
+ specifier: 2.17.6
+ version: 2.17.6
devDependencies:
'@testing-library/dom':
specifier: ^10.4.0
@@ -2408,6 +2592,9 @@ importers:
'@types/react-dom':
specifier: ^18.2.25
version: 18.2.25
+ '@types/sanitize-html':
+ specifier: 2.16.1
+ version: 2.16.1
'@webstudio-is/design-system':
specifier: workspace:*
version: link:../design-system
@@ -2423,6 +2610,9 @@ importers:
'@webstudio-is/tsconfig':
specifier: workspace:*
version: link:../tsconfig
+ micromark-util-types:
+ specifier: 2.0.2
+ version: 2.0.2
nanostores:
specifier: ^0.11.3
version: 0.11.3
@@ -2434,7 +2624,7 @@ importers:
version: 18.3.0-canary-14898b6a9-20240318([email protected])
vitest:
specifier: ^3.1.2
packages/sdk-components-react-radix:
dependencies:
@@ -2587,7 +2777,7 @@ importers:
version: 18.3.0-canary-14898b6a9-20240318([email protected])
vitest:
specifier: ^3.1.2
packages/sdk-components-registry:
dependencies:
@@ -2621,7 +2811,7 @@ importers:
version: 18.3.0-canary-14898b6a9-20240318([email protected])
vitest:
specifier: ^3.1.2
packages/sync-client:
dependencies:
@@ -2649,7 +2839,7 @@ importers:
version: link:../tsconfig
vitest:
specifier: ^3.1.2
packages/template:
dependencies:
@@ -2674,7 +2864,7 @@ importers:
version: link:../tsconfig
vitest:
specifier: ^3.1.2
packages/trpc-interface:
dependencies:
@@ -2705,7 +2895,7 @@ importers:
version: link:../tsconfig
vitest:
specifier: ^3.1.2
packages/tsconfig: {}
@@ -2720,7 +2910,7 @@ importers:
version: link:../tsconfig
vitest:
specifier: ^3.1.2
packages:
@@ -2732,6 +2922,22 @@ packages:
resolution: {integrity: sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==}
engines: {node: '>=6.0.0'}
+ '@apidevtools/[email protected]':
+ resolution: {integrity: sha512-Oc96zvmxx1fqoSEdUmfmvvb59/KDOnUoJ7s2t7bISyAn0XEz57LCCw8k2Y4Pf3mwKaZLMciESALORLgfe2frCw==}
+ engines: {node: '>= 16'}
+
+ '@apidevtools/[email protected]':
+ resolution: {integrity: sha512-Zc1AlqrJlX3SlpupFGpiLi2EbteyP7fXmUOGup6/DnkRgjP9bgMM/ag+n91rsv0U1Gpz0H3VILA/o3bW7Ua6BQ==}
+ engines: {node: '>=10'}
+
+ '@apidevtools/[email protected]':
+ resolution: {integrity: sha512-QAkD5kK2b1WfjDS/UQn/qQkbwF31uqRjPTrsCs5ZG9BQGAkjwvqGFjjPqAuzac/IYzpPtRzjCP1WrTuAIjMrXg==}
+
+ '@apidevtools/[email protected]':
+ resolution: {integrity: sha512-e5mJoswsnAX0jG+J09xHFYQXb/bUc5S3pLpMxUuRUA2H8T2kni3yEoyz2R3Dltw5f4A6j6rPNMpWTK+iVDFlng==}
+ peerDependencies:
+ openapi-types: '>=7'
+
'@atlaskit/[email protected]':
resolution: {integrity: sha512-E52y8/0BTTf4ai6BJyFYgdVHFgQ1AES33KvAVQpZ41jMkoukLIq6UoCudOXku7xs3qoPygQdpC+vitVUuEFJXw==}
@@ -6296,6 +6502,9 @@ packages:
resolution: {integrity: sha512-XISRgDJ2Tc5q4TRqvgJtzsRkFYNJzZrhTdtMoGVBttwzzQJkPnS3WWTFc7kuDRoPtPakl+T+OfdEUjYJj7Jbow==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-n9wjs8bCOTyN/ynwD8s/nTcTreIHB1vf31vhLMGqUPNHaweKC4/fAl4Dj+hUlCTKYgm4P3k83fmiFfzkZ6sgMA==}
+
resolution: {integrity: sha512-Uqt8rPBE8SY0RK8JB1EzVOIZ32uqy8HwdxCnoCOsYrvnswqmFZ/k+9Ikidlk/ImhsdvBsloHbAlewb2IEBV/Og==}
@@ -6625,6 +6834,14 @@ packages:
resolution: {integrity: sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-mv00Te6nmYbRp5DCwclxtt7yV/joXJPGS7nM+97GdxvuttCOfgI3K4U25zboyeX0O+myI8ERluxQe5wljMmVIw==}
+ peerDependencies:
+ ajv: ^8.5.0
+ peerDependenciesMeta:
+ ajv:
+ optional: true
+
resolution: {integrity: sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==}
peerDependencies:
@@ -6888,6 +7105,9 @@ packages:
resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-HpX65o1Hnr9HH25ojC1YGs7HCQLq0GCOibSaWER0eNpgJ/Z1MZv2mTc7+xh6WOPxbRVcmgbv4hGU+uSQ/2xFZQ==}
+
resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==}
engines: {node: '>=6'}
@@ -6898,6 +7118,11 @@ packages:
resolution: {integrity: sha512-MMHtuAz9Ys840zAY5F4k6fV5GaivZ9sPk+nz0mY+GYVzRBnYkN0mpqkSR92oWRQ19yQWo4HvBV/FnC16AJX8MA==}
+ resolution: {integrity: sha512-yYLfHyDMIXRyRqsKBRLX023riFLpXY2YOfdtqKXZRZy9qsfOJ9U+4F9YZL7MEzL5+ziN2x2nlBvY/Voi3EBljA==}
+ engines: {node: '>=18'}
+ hasBin: true
+
resolution: {integrity: sha512-XKxXAC3HVPv7r674zP0VC3RTXz+/JKhfyw94ljvF80yynK6VkTnqE3jMuN8b3dUVmmc43TjyxjW4KTsmB3c86g==}
@@ -7239,6 +7464,9 @@ packages:
resolution: {integrity: sha512-fRHTG8g/Gif+kSh50gaGEdToemgfj74aRX3swtiouboip5JDLAyDE9F11nHMIcvOaXeOC6D7SpNhi7uFyB7Uww==}
+ resolution: {integrity: sha512-98IT+HOahAisibz/yjKbzuOBwYcjJ7BCLPzARyHiyEBmRz4fatF+KPJszEHXsGYjUG234aH/cOjW1wwTbKUZlA==}
+
resolution: {integrity: sha512-8pYCQiL9Xdcg0UPSD3d+0KMlOjp+KGU5EPwYddgzQ7DATsg4fuUDjQtsYLmWjnk2obnNHgV3vE2Y4jejSOJVBQ==}
engines: {node: '>=10'}
@@ -7391,9 +7619,17 @@ packages:
resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==}
+ resolution: {integrity: sha512-4MEa38/QexBob6gFNwu+EGdWvhJ1OKuNwdYY3Y3NyeWDQfnGeDYQUDfIRzWu5B5gsv03so2Uxd28YC6zrsx3Lw==}
+ engines: {node: '>=20.19.0'}
+
resolution: {integrity: sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==}
+ resolution: {integrity: sha512-umCQid3jKbDmVjx8jGaW7uUykm4DEUeyV21hPxNMo2nV955DhUThwqyOIDtreepP31hl84X7G5U9ZfsWvIB3Pg==}
+ engines: {node: '>=20.19.0'}
+
resolution: {integrity: sha512-A2is4PLG+eeSfoTMA95/s4pvAoSo2mKtiM5jlHkAVewmiO8ISFTFKZjH7UAM1Atli/OT/7JHOrJRJiMKUZKYBw==}
engines: {node: '>=12'}
@@ -7403,9 +7639,20 @@ packages:
resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==}
engines: {node: '>= 4'}
+ resolution: {integrity: sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg==}
+ engines: {node: '>=20.19.0'}
+
resolution: {integrity: sha512-z08c1l761iKhDFtfXO04C7kTdPBLi41zwOZl00WS8b5eiaebNpY00HKbztwBq+e3vyqWNwWF3mP9YLUeqIrF+Q==}
+ resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==}
+
+ resolution: {integrity: sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA==}
+ engines: {node: '>=20.19.0'}
+
resolution: {integrity: sha512-tE7ztYzXHIeyvc7N+hR3oi7FIbf/NIjVP9hmAt3yMXzrQ072/fpjGLx2GxNxGxUl5V73MEqYzioOMoVhGMJ5cA==}
engines: {node: '>=10'}
@@ -7482,6 +7729,14 @@ packages:
resolution: {integrity: sha512-aKstq2TDOndCn4diEyp9Uq/Flu2i1GlLkc6XIDQSDMuaFE3OPW5OphLCyQ5SpSJZTb4reN+kTcYru5yIfXoRPw==}
engines: {node: '>=0.12'}
+ resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==}
+ engines: {node: '>=0.12'}
+
+ resolution: {integrity: sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==}
+ engines: {node: '>=20.19.0'}
+
resolution: {integrity: sha512-ufH4h0JdumikGIHuVQjP6uKJMG00Yv7Av0ZsBvM7PicejO8e9eRAxXKUdIHqoo1ZqogFrquDmmP63x3T0djHlQ==}
@@ -7565,6 +7820,10 @@ packages:
resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==}
engines: {node: '>=6.0'}
@@ -7914,6 +8173,9 @@ packages:
resolution: {integrity: sha512-ZCuZCnlqNzjb4QprAzXKdpp/gh6KTxSJuw3IBsPnV/7fV4NxC9ckB+vPTt8w7fJA0TaSD7c55BR47JD6MEDyDw==}
+ resolution: {integrity: sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw==}
+
resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==}
engines: {node: '>= 6'}
@@ -8048,6 +8310,13 @@ packages:
resolution: {integrity: sha512-KM1SNmemQtsD+OTInZTYKZNbyPzzVrjMR2Iz1Np+Y+bcxUh0dgKF4NtylJVkGZRLe3NklHizJ5k1Vd3ug1uTPA==}
engines: {node: '>=18.20'}
+ resolution: {integrity: sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==}
+
+ resolution: {integrity: sha512-Tz7u1i95/g2x2jz81+x0FBVhBhY5aRTvD3tXXdFaljuNdzDLJ8UGNRrTcj2cgQvAg3iW/h77Fz15nLW0L0CrZw==}
+ engines: {node: '>=20.19.0'}
+
resolution: {integrity: sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==}
engines: {node: '>= 0.8'}
@@ -8276,6 +8545,10 @@ packages:
resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==}
+ engines: {node: '>=0.10.0'}
+
resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==}
@@ -8455,6 +8728,9 @@ packages:
resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-mU6WRz5EusL9ZZuiZ5SO4Y6C0P9PAUR9iwdb6bzj4KDihm28DiHFw+/yk9DBH4f+Pv1wuzQ4e2jV3oQ7mkIqvw==}
+
resolution: {integrity: sha512-Dxc5SCG4kB+wF+Rh55ism3SuecOKeOtCtGHFGKd6pj2QKVojtjkxGTQPMt7//2z5rMSue4R+hmRM0pCEZflupA==}
@@ -8684,6 +8960,9 @@ packages:
resolution: {integrity: sha512-JjA2OjxRqAa8wEG8hloD0uTU0kdn8kbtOWpPP94NBkfAlbxn4S8gCGf/9DwFtEeGPXrDcNXdiDjVaRdUFqYokw==}
+ resolution: {integrity: sha512-LRqI9+wdgC25P0URIJY9vwocIzCcksduHQ9OF2joxQoyTNVduwLAFUzjoopuRJbJAReaKrNQKAZKL3uCMugWJA==}
+
resolution: {integrity: sha512-xIPmR5ReJDu/DHH1OoIT1HkuybIfRGYRywC+gJtI7qHjCJp/M9jrmBEJW22O8lskDWm562BX2W8TiAwRTb0rKA==}
@@ -8777,6 +9056,9 @@ packages:
resolution: {integrity: sha512-m2UH9a7n3W8VAH9JO9y01APpPKmNNNs71P0RbknEmYSaZU5Ghogv38BYO94AI5Xw6OYfxZRdHZZ2nYjs/Z+SZQ==}
+ resolution: {integrity: sha512-C4AkuM3dA58cgZha7zVnuVxBhDsbttIMiytjgsM2XbHAB2faRVaHRle40558FBN+DJcrLNCoqG5mlrpdU4cRtg==}
+
resolution: {integrity: sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==}
@@ -9282,6 +9564,9 @@ packages:
resolution: {integrity: sha512-762C9BNlJPbjjlWZi4WYK9iM2tAVAv0uUp1UmI34vb0CN5T2mjB/qM6RYBmNKMh/dN9fC+bxqPwWJZUTWW052A==}
+ resolution: {integrity: sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw==}
+
resolution: {integrity: sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==}
engines: {node: '>=10'}
@@ -9385,6 +9670,9 @@ packages:
resolution: {integrity: sha512-kBeTUtcj+SkyfaW4+KBe0HtsloBJ/mKTPoxpVdA57GZiPerREsUWJOhVj9anXweFiJkm5y8FG1sxFZkZ0SN6wg==}
+ resolution: {integrity: sha512-/2qh0lav6CmI15FzA3i/2Bzk2zCgQhGMkvhOhKNcBVQ1ldgpbfiNTVslmooUmWJcADi1f1kIeynbDRVzNlfR6Q==}
+
resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==}
@@ -10052,6 +10340,10 @@ packages:
resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}
+ resolution: {integrity: sha512-M4bo9tfv1yfhQZZKkc6dL07ALrGJtfvNOuhX3hU9AVPR/uPQ+nKOJBqTYc7LfMQblTW04mtSWDJWEyLvygJsLA==}
+ engines: {node: '>=22.12.0'}
+
resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==}
engines: {node: '>=v12.22.7'}
@@ -11130,9 +11422,10 @@ packages:
resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==}
- resolution: {integrity: sha512-e0WHiYql7+9wr4cWMx3TVQrNwejKaEe7/rHNmQmqRjazfOP5W8PB6Jpebb5o6fIapbz9o9+2ipcaTM2ZwDI6lw==}
- engines: {node: '>= 14'}
+ resolution: {integrity: sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==}
+ engines: {node: '>= 14.6'}
+ hasBin: true
resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==}
@@ -11207,6 +11500,25 @@ snapshots:
'@jridgewell/gen-mapping': 0.3.5
'@jridgewell/trace-mapping': 0.3.25
+ '@apidevtools/[email protected]':
+ dependencies:
+ '@types/json-schema': 7.0.15
+ js-yaml: 4.1.0
+
+ '@apidevtools/[email protected]': {}
+
+ '@apidevtools/[email protected]': {}
+
+ dependencies:
+ '@apidevtools/json-schema-ref-parser': 14.0.1
+ '@apidevtools/openapi-schemas': 2.1.0
+ '@apidevtools/swagger-methods': 3.0.2
+ ajv: 8.20.0
+ ajv-draft-04: 1.0.0([email protected])
+ call-me-maybe: 1.0.2
+ openapi-types: 12.1.3
+
'@atlaskit/[email protected]':
dependencies:
'@atlaskit/pragmatic-drag-and-drop': 1.7.4
@@ -11976,7 +12288,7 @@ snapshots:
optionalDependencies:
workerd: 1.20250428.0
dependencies:
'@cloudflare/unenv-preset': 2.3.1([email protected])([email protected])
'@hattip/adapter-node': 0.0.49
@@ -11986,7 +12298,7 @@ snapshots:
picocolors: 1.1.1
tinyglobby: 0.2.13
unenv: 2.0.0-rc.15
wrangler: 3.63.2(@cloudflare/[email protected])
ws: 8.18.0
transitivePeerDependencies:
@@ -11995,7 +12307,7 @@ snapshots:
- utf-8-validate
- workerd
dependencies:
'@cloudflare/unenv-preset': 2.3.1([email protected])([email protected])
'@hattip/adapter-node': 0.0.49
@@ -12005,7 +12317,7 @@ snapshots:
picocolors: 1.1.1
tinyglobby: 0.2.13
unenv: 2.0.0-rc.15
wrangler: 4.14.1
ws: 8.18.0
transitivePeerDependencies:
@@ -12692,12 +13004,12 @@ snapshots:
'@istanbuljs/[email protected]': {}
dependencies:
glob: 10.3.3
magic-string: 0.27.0
react-docgen-typescript: 2.2.2([email protected])
optionalDependencies:
typescript: 7.0.2
@@ -13062,12 +13374,12 @@ snapshots:
nanostores: 0.11.3
react: 18.3.0-canary-14898b6a9-20240318
dependencies:
isbot: 5.1.25
transitivePeerDependencies:
- react
- react-dom
@@ -14121,7 +14433,7 @@ snapshots:
react: 18.3.0-canary-14898b6a9-20240318
react-dom: 18.3.0-canary-14898b6a9-20240318([email protected])
dependencies:
'@babel/core': 7.29.7
'@babel/generator': 7.29.7
@@ -14150,8 +14462,8 @@ snapshots:
semver: 7.7.1
set-cookie-parser: 2.7.2
valibot: 0.41.0([email protected])
optionalDependencies:
typescript: 7.0.2
@@ -14172,7 +14484,7 @@ snapshots:
- tsx
- yaml
dependencies:
'@babel/core': 7.29.7
'@babel/generator': 7.29.7
@@ -14201,8 +14513,8 @@ snapshots:
semver: 7.7.1
set-cookie-parser: 2.7.2
valibot: 0.41.0([email protected])
optionalDependencies:
typescript: 7.0.2
@@ -14231,16 +14543,16 @@ snapshots:
optionalDependencies:
typescript: 7.0.2
dependencies:
minimatch: 9.0.4
optionalDependencies:
typescript: 7.0.2
dependencies:
minimatch: 9.0.4
optionalDependencies:
typescript: 7.0.2
@@ -14313,7 +14625,7 @@ snapshots:
optionalDependencies:
typescript: 7.0.2
dependencies:
'@babel/core': 7.26.10
'@babel/generator': 7.27.0
@@ -14330,7 +14642,7 @@ snapshots:
'@remix-run/router': 1.23.0
'@remix-run/server-runtime': 2.16.5([email protected])
'@types/mdx': 2.0.13
- '@vanilla-extract/integration': 6.5.0(@types/[email protected])([email protected])([email protected])([email protected])
arg: 5.0.2
cacache: 17.1.4
chalk: 4.1.2
@@ -14370,12 +14682,12 @@ snapshots:
tar-fs: 2.1.1
tsconfig-paths: 4.2.0
valibot: 0.41.0([email protected])
ws: 7.5.10
optionalDependencies:
'@remix-run/serve': 2.16.5([email protected])
typescript: 7.0.2
wrangler: 3.63.2(@cloudflare/[email protected])
transitivePeerDependencies:
- '@types/node'
@@ -14396,7 +14708,7 @@ snapshots:
- utf-8-validate
- yaml
dependencies:
'@babel/core': 7.26.10
'@babel/generator': 7.27.0
@@ -14413,7 +14725,7 @@ snapshots:
'@remix-run/router': 1.23.0
'@remix-run/server-runtime': 2.16.5([email protected])
'@types/mdx': 2.0.13
- '@vanilla-extract/integration': 6.5.0(@types/[email protected])([email protected])([email protected])([email protected])
arg: 5.0.2
cacache: 17.1.4
chalk: 4.1.2
@@ -14453,12 +14765,12 @@ snapshots:
tar-fs: 2.1.1
tsconfig-paths: 4.2.0
valibot: 0.41.0([email protected])
ws: 7.5.10
optionalDependencies:
'@remix-run/serve': 2.16.5([email protected])
typescript: 7.0.2
wrangler: 3.63.2(@cloudflare/[email protected])
transitivePeerDependencies:
- '@types/node'
@@ -14780,13 +15092,13 @@ snapshots:
storybook: 8.6.4([email protected])
ts-dedent: 2.2.0
dependencies:
'@storybook/csf-plugin': 8.6.4([email protected]([email protected]))
browser-assert: 1.2.1
storybook: 8.6.4([email protected])
ts-dedent: 2.2.0
dependencies:
@@ -14834,11 +15146,11 @@ snapshots:
react-dom: 18.3.0-canary-14898b6a9-20240318([email protected])
storybook: 8.6.4([email protected])
dependencies:
- '@joshwooding/vite-plugin-react-docgen-typescript': 0.5.0([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected]))
'@rollup/pluginutils': 5.1.4([email protected])
find-up: 5.0.0
magic-string: 0.30.17
@@ -14848,7 +15160,7 @@ snapshots:
resolve: 1.22.8
storybook: 8.6.4([email protected])
tsconfig-paths: 4.2.0
transitivePeerDependencies:
- rollup
- supports-color
@@ -15105,6 +15417,10 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ htmlparser2: 10.1.0
+
dependencies:
'@types/mime': 1.3.5
@@ -15235,7 +15551,7 @@ snapshots:
transitivePeerDependencies:
- babel-plugin-macros
dependencies:
'@babel/core': 7.26.10
'@babel/plugin-syntax-typescript': 7.24.1(@babel/[email protected])
@@ -15248,8 +15564,8 @@ snapshots:
lodash: 4.17.21
mlly: 1.7.4
outdent: 0.8.0
transitivePeerDependencies:
- '@types/node'
- babel-plugin-macros
@@ -15267,9 +15583,9 @@ snapshots:
'@vanilla-extract/[email protected]': {}
dependencies:
'@vercel/static-config': 3.0.0
isbot: 5.1.25
@@ -15277,9 +15593,9 @@ snapshots:
react-dom: 18.3.0-canary-14898b6a9-20240318([email protected])
ts-morph: 12.0.0
dependencies:
'@vercel/static-config': 3.0.0
isbot: 5.1.25
@@ -15287,9 +15603,9 @@ snapshots:
react-dom: 18.3.0-canary-14898b6a9-20240318([email protected])
ts-morph: 12.0.0
dependencies:
'@remix-run/node': 2.16.5([email protected])
'@remix-run/server-runtime': 2.16.5([email protected])
'@vercel/static-config': 3.0.0
@@ -15304,27 +15620,27 @@ snapshots:
json-schema-to-ts: 1.6.4
ts-morph: 12.0.0
dependencies:
'@babel/core': 7.26.10
'@babel/plugin-transform-react-jsx-self': 7.25.9(@babel/[email protected])
'@babel/plugin-transform-react-jsx-source': 7.25.9(@babel/[email protected])
'@types/babel__core': 7.20.5
react-refresh: 0.17.0
transitivePeerDependencies:
- supports-color
dependencies:
'@testing-library/dom': 10.4.0
'@testing-library/user-event': 14.6.1(@testing-library/[email protected])
'@vitest/utils': 3.1.2
magic-string: 0.30.21
sirv: 3.0.1
tinyrainbow: 2.0.0
ws: 8.21.0
optionalDependencies:
playwright: 1.50.1
@@ -15348,9 +15664,9 @@ snapshots:
std-env: 3.9.0
test-exclude: 7.0.1
tinyrainbow: 2.0.0
optionalDependencies:
transitivePeerDependencies:
- supports-color
@@ -15361,14 +15677,14 @@ snapshots:
chai: 5.2.0
tinyrainbow: 2.0.0
dependencies:
'@vitest/spy': 3.1.2
estree-walker: 3.0.3
magic-string: 0.30.17
optionalDependencies:
'@vitest/[email protected]':
dependencies:
@@ -15452,7 +15768,6 @@ snapshots:
dependencies:
acorn: 8.17.0
- optional: true
@@ -15472,6 +15787,10 @@ snapshots:
clean-stack: 2.2.0
indent-string: 4.0.0
+ optionalDependencies:
+ ajv: 8.20.0
+
optionalDependencies:
ajv: 8.20.0
@@ -15762,12 +16081,16 @@ snapshots:
call-bind-apply-helpers: 1.0.2
get-intrinsic: 1.3.0
+
+
dependencies:
debug: 4.4.3
@@ -16092,6 +16415,8 @@ snapshots:
+
dependencies:
mimic-fn: 3.1.0
@@ -16193,8 +16518,16 @@ snapshots:
domhandler: 5.0.3
entities: 4.5.0
+ dependencies:
+ domelementtype: 3.0.0
+ domhandler: 6.0.1
+ entities: 8.0.0
+
+
dependencies:
webidl-conversions: 7.0.0
@@ -16204,12 +16537,28 @@ snapshots:
dependencies:
domelementtype: 2.3.0
+ dependencies:
+ domelementtype: 3.0.0
+
dependencies:
dom-serializer: 2.0.0
domelementtype: 2.3.0
domhandler: 5.0.3
+ dependencies:
+ dom-serializer: 2.0.0
+ domelementtype: 2.3.0
+ domhandler: 5.0.3
+
+ dependencies:
+ dom-serializer: 3.1.1
+ domelementtype: 3.0.0
+ domhandler: 6.0.1
+
dependencies:
is-obj: 2.0.0
@@ -16275,6 +16624,10 @@ snapshots:
+
+
dependencies:
react: 18.3.0-canary-14898b6a9-20240318
@@ -16459,6 +16812,8 @@ snapshots:
+
dependencies:
esprima: 4.0.1
@@ -16915,6 +17270,8 @@ snapshots:
dependencies:
resolve-pkg-maps: 1.0.0
+
dependencies:
is-glob: 4.0.3
@@ -17075,6 +17432,20 @@ snapshots:
+ dependencies:
+ domelementtype: 2.3.0
+ domhandler: 5.0.3
+ domutils: 3.2.2
+ entities: 7.0.1
+
+ dependencies:
+ domelementtype: 3.0.0
+ domhandler: 6.0.1
+ domutils: 4.0.2
+ entities: 8.0.0
+
dependencies:
depd: 2.0.0
@@ -17301,6 +17672,8 @@ snapshots:
+
optional: true
@@ -17472,6 +17845,10 @@ snapshots:
+ dependencies:
+ dayjs: 1.11.21
+
@@ -17737,6 +18114,17 @@ snapshots:
mdast-util-to-markdown: 1.5.0
micromark-extension-frontmatter: 1.1.1
+ dependencies:
+ '@types/mdast': 4.0.4
+ devlop: 1.1.0
+ escape-string-regexp: 5.0.0
+ mdast-util-from-markdown: 2.0.3
+ mdast-util-to-markdown: 2.1.2
+ micromark-extension-frontmatter: 2.0.0
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
'@types/estree-jsx': 1.0.0
@@ -17925,6 +18313,13 @@ snapshots:
micromark-util-symbol: 1.1.0
micromark-util-types: 1.1.0
+ dependencies:
+ fault: 2.0.1
+ micromark-util-character: 2.1.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
dependencies:
micromark-util-character: 2.1.1
@@ -18326,7 +18721,7 @@ snapshots:
dependencies:
'@cspotcode/source-map-support': 0.8.1
acorn: 8.17.0
- acorn-walk: 8.3.4
+ acorn-walk: 8.3.5
capnp-ts: 0.7.0
exit-hook: 2.2.1
glob-to-regexp: 0.4.1
@@ -18624,6 +19019,8 @@ snapshots:
transitivePeerDependencies:
- debug
+
dependencies:
bl: 4.1.0
@@ -18764,6 +19161,8 @@ snapshots:
+
dependencies:
entities: 6.0.0
@@ -18873,7 +19272,7 @@ snapshots:
dependencies:
lilconfig: 2.1.0
- yaml: 2.2.1
+ yaml: 2.9.0
optionalDependencies:
postcss: 8.5.3
@@ -19440,6 +19839,16 @@ snapshots:
+ dependencies:
+ deepmerge: 4.3.1
+ escape-string-regexp: 4.0.0
+ htmlparser2: 12.0.0
+ is-plain-object: 5.0.0
+ launder: 1.7.1
+ parse-srcset: 1.0.2
+ postcss: 8.5.16
+
dependencies:
xmlchars: 2.2.0
@@ -20300,7 +20709,7 @@ snapshots:
unist-util-stringify-position: 3.0.3
vfile-message: 3.1.3
dependencies:
'@brillout/import': 0.2.6
'@brillout/json-serializer': 0.5.15
@@ -20319,15 +20728,15 @@ snapshots:
source-map-support: 0.5.21
tinyglobby: 0.2.13
optionalDependencies:
dependencies:
cac: 6.7.14
debug: 4.4.3
pathe: 1.1.2
picocolors: 1.1.1
transitivePeerDependencies:
- '@types/node'
- jiti
@@ -20342,13 +20751,13 @@ snapshots:
- tsx
- yaml
dependencies:
cac: 6.7.14
debug: 4.4.3
es-module-lexer: 1.6.0
pathe: 1.1.2
transitivePeerDependencies:
- '@types/node'
- jiti
@@ -20363,13 +20772,13 @@ snapshots:
- tsx
- yaml
dependencies:
cac: 6.7.14
debug: 4.4.0
es-module-lexer: 1.6.0
pathe: 2.0.3
transitivePeerDependencies:
- '@types/node'
- jiti
@@ -20384,7 +20793,7 @@ snapshots:
- tsx
- yaml
dependencies:
esbuild: 0.25.3
fdir: 6.5.0([email protected])
@@ -20398,11 +20807,12 @@ snapshots:
jiti: 2.4.2
lightningcss: 1.31.1
tsx: 4.19.3
+ yaml: 2.9.0
dependencies:
'@vitest/expect': 3.1.2
'@vitest/pretty-format': 3.1.2
'@vitest/runner': 3.1.2
'@vitest/snapshot': 3.1.2
@@ -20419,13 +20829,13 @@ snapshots:
tinyglobby: 0.2.13
tinypool: 1.0.2
tinyrainbow: 2.0.0
why-is-node-running: 2.3.0
optionalDependencies:
'@types/debug': 4.1.12
'@types/node': 22.13.10
jsdom: 20.0.3
transitivePeerDependencies:
- jiti
@@ -20655,7 +21065,7 @@ snapshots:
diff --git a/vite.sdk-components.config.ts b/vite.sdk-components.config.ts
index 8577244470..4a2346e1f7 100644
--- a/vite.sdk-components.config.ts
+++ b/vite.sdk-components.config.ts
@@ -1,28 +1,43 @@
import { defineConfig } from "vite";
-import { existsSync } from "node:fs";
+import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
const hasPrivateFolders = existsSync(
path.join(process.cwd(), "private-src", "README.md")
);
-const maybeEntry = (entry: string) => {
- return existsSync(path.join(process.cwd(), entry)) ? entry : undefined;
+
+type ExportConditions = {
+ webstudio?: string;
+ "webstudio-private"?: string;
};
+const packageJson = JSON.parse(
+ readFileSync(path.join(process.cwd(), "package.json"), "utf8")
+) as { exports: Record<string, ExportConditions> };
+
+const entries = Object.values(packageJson.exports).map((conditions) => {
+ const entry = conditions.webstudio;
+ if (entry === undefined) {
+ throw new Error('Package export is missing the "webstudio" condition');
+ }
+ if (hasPrivateFolders && conditions["webstudio-private"] !== undefined) {
+ return conditions["webstudio-private"];
+ }
+ if (hasPrivateFolders && entry === "./src/components.ts") {
+ return "./private-src/components.ts";
+ }
+ return entry;
+});
+
const isBareImport = (id: string) =>
- id.startsWith("@") || id.includes(".") === false;
+ id.startsWith("\0") === false &&
+ id.startsWith(".") === false &&
+ path.isAbsolute(id) === false;
export default defineConfig({
build: {
lib: {
- entry: [
- maybeEntry("src/index.ts"),
- hasPrivateFolders ? "private-src/components.ts" : "src/components.ts",
- "src/metas.ts",
- "src/hooks.ts",
- "src/templates.ts",
- ].filter((entry) => entry !== undefined),
- formats: ["es"],
+ entry: entries,
},
rollupOptions: {
external: isBareImport,
@@ -30,12 +45,14 @@ export default defineConfig({
{
preserveModules: true,
preserveModulesRoot: "src",
+ format: "es",
dir: "lib",
},
hasPrivateFolders
? {
preserveModules: true,
preserveModulesRoot: "private-src",
+ format: "es",
dir: "lib",
}
: undefined,