Skip to content

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

fix: optimize CLI import for large data amount (#5831)

Oleg Isonen82c3d83fd1c5
diff --git a/apps/builder/app/builder/features/marketplace/templates.tsx b/apps/builder/app/builder/features/marketplace/templates.tsx
index 05cbbdfa27..ac336436f9 100644
--- a/apps/builder/app/builder/features/marketplace/templates.tsx
+++ b/apps/builder/app/builder/features/marketplace/templates.tsx
@@ -21,7 +21,7 @@ import { ChevronLeftIcon, ExternalLinkIcon } from "@webstudio-is/icons";
import {
elementComponent,
getAllPages,
- Instance,
+ type Instance,
ROOT_FOLDER_ID,
type Asset,
type Page,
diff --git a/apps/builder/app/builder/features/pages/folder-settings.tsx b/apps/builder/app/builder/features/pages/folder-settings.tsx
index 4c4c69e744..eaefd988f0 100644
--- a/apps/builder/app/builder/features/pages/folder-settings.tsx
+++ b/apps/builder/app/builder/features/pages/folder-settings.tsx
@@ -17,8 +17,9 @@ import {
} from "@webstudio-is/design-system";
import { InfoCircleIcon, TrashIcon } from "@webstudio-is/icons";
import {
- Folder,
- Pages,
+ type Folder,
+ folder,
+ type Pages,
ROOT_FOLDER_ID,
findParentFolderByChildId,
getFolderById,
@@ -37,11 +38,11 @@ import { useDraftValue } from "~/builder/shared/use-draft-value";
import { copyFolder } from "~/shared/copy-paste/copy-paste";
import { PageItemActionsDropdown } from "./page-item-actions";
-const Values = Folder.pick({ name: true, slug: true }).extend({
+const folderValues = folder.pick({ name: true, slug: true }).extend({
parentFolderId: z.string(),
});
-type Values = z.infer<typeof Values>;
+type Values = z.infer<typeof folderValues>;
type FieldName = keyof Values;
@@ -64,7 +65,7 @@ const validateValues = (
values: Values,
folderId?: Folder["id"]
): Errors => {
- const parsedResult = Values.safeParse(values);
+ const parsedResult = folderValues.safeParse(values);
const errors: Errors = {};
if (parsedResult.success === false) {
return parsedResult.error.formErrors.fieldErrors;
diff --git a/apps/builder/app/builder/features/pages/page-settings/section-custom-metadata.tsx b/apps/builder/app/builder/features/pages/page-settings/section-custom-metadata.tsx
index bec9b4fdfa..6853bed173 100644
--- a/apps/builder/app/builder/features/pages/page-settings/section-custom-metadata.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings/section-custom-metadata.tsx
@@ -4,7 +4,7 @@ import { CustomMetadata } from "../custom-metadata";
import { computeExpression } from "~/shared/data-variables";
import type { Errors, OnChange, Values } from "./shared";
-const CustomMetadataValues = z.object({
+const customMetadataValues = z.object({
customMetas: z
.array(
z.object({
@@ -19,7 +19,7 @@ export const validateCustomMetadataSection = (
values: Values,
variableValues: Map<string, unknown>
): Errors => {
- const parsedResult = CustomMetadataValues.safeParse({
+ const parsedResult = customMetadataValues.safeParse({
customMetas: values.customMetas.map((item) => ({
property: item.property,
content: computeExpression(item.content, variableValues),
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 a316d703fe..9642568cf3 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
@@ -18,10 +18,10 @@ import {
theme,
} from "@webstudio-is/design-system";
import {
- HomePagePath,
- PageName,
- PagePath,
- ProjectNewRedirectPath,
+ homePagePath,
+ pageName,
+ pagePath,
+ projectNewRedirectPath,
documentTypes,
getPagePath,
isLiteralExpression,
@@ -45,23 +45,23 @@ import type { Errors, OnChange, Values } from "./shared";
// 2xx, 3xx, 4xx, 5xx
const statusRegex = /^[2345]\d\d$/;
-const Status = z
+const status = z
.number()
.refine(
(value) => statusRegex.test(String(value)),
"Status code expects 2xx, 3xx, 4xx or 5xx"
);
-const GeneralValues = z.object({
- name: PageName,
- path: PagePath,
- status: Status.optional(),
- redirect: z.optional(ProjectNewRedirectPath.or(z.literal(""))),
+const generalValues = z.object({
+ name: pageName,
+ path: pagePath,
+ status: status.optional(),
+ redirect: z.optional(projectNewRedirectPath.or(z.literal(""))),
documentType: z.optional(z.enum(documentTypes)),
});
-const HomePageGeneralValues = GeneralValues.extend({
- path: HomePagePath,
+const homePageGeneralValues = generalValues.extend({
+ path: homePagePath,
});
const computePageRoute = (values: Values, pages: Pages) => {
@@ -94,8 +94,8 @@ export const validateGeneralSection = ({
documentType: values.documentType,
};
- const Validator = values.isHomePage ? HomePageGeneralValues : GeneralValues;
- const parsedResult = Validator.safeParse(computedValues);
+ const validator = values.isHomePage ? homePageGeneralValues : generalValues;
+ const parsedResult = validator.safeParse(computedValues);
const errors: Errors = {};
if (parsedResult.success === false) {
Object.assign(errors, parsedResult.error.formErrors.fieldErrors);
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 bde1b9c155..05c46f368f 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
@@ -12,7 +12,7 @@ import {
TextArea,
theme,
} from "@webstudio-is/design-system";
-import { isLiteralExpression, PageTitle } from "@webstudio-is/sdk";
+import { isLiteralExpression, pageTitle } from "@webstudio-is/sdk";
import {
BindingControl,
BindingPopover,
@@ -24,27 +24,27 @@ import { $pageRootScope } from "../page-utils";
import { SearchPreview } from "../search-preview";
import { usePageUrl, type Errors, type OnChange, type Values } from "./shared";
-const EmptyString = z.string().refine((string) => string === "");
+const emptyString = z.string().refine((string) => string === "");
-const Language = z
+const language = z
.string()
.refine(
(value) => bcp47.parse(value).language !== null,
"The language is invalid"
);
-const SearchValues = z.object({
- title: PageTitle,
+const searchValues = z.object({
+ title: pageTitle,
description: z.string().optional(),
excludePageFromSearch: z.boolean().optional(),
- language: Language.or(EmptyString),
+ language: language.or(emptyString),
});
export const validateSearchSection = (
values: Values,
variableValues: Map<string, unknown>
): Errors => {
- const parsedResult = SearchValues.safeParse({
+ const parsedResult = searchValues.safeParse({
title:
computeExpression(values.title, variableValues) ??
"exclude from validation",
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 36e8c0e182..e1d9b4a52e 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
@@ -21,7 +21,7 @@ import { ImageInfo } from "../image-info";
import { SocialPreview } from "../social-preview";
import { usePageUrl, type Errors, type OnChange, type Values } from "./shared";
-const SocialImageValues = z.object({
+const socialImageValues = z.object({
socialImageUrl: z.string().optional(),
});
@@ -29,7 +29,7 @@ export const validateSocialImageSection = (
values: Values,
variableValues: Map<string, unknown>
): Errors => {
- const parsedResult = SocialImageValues.safeParse({
+ const parsedResult = socialImageValues.safeParse({
socialImageUrl: computeExpression(values.socialImageUrl, variableValues),
});
return parsedResult.success ? {} : parsedResult.error.formErrors.fieldErrors;
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 6242b50ff9..32391c90e7 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
@@ -11,7 +11,7 @@ import { computeExpression } from "~/shared/data-variables";
import { $pageRootScope } from "../page-utils";
import type { Errors, OnChange, Values } from "./shared";
-const TextContentValues = z.object({
+const textContentValues = z.object({
content: z.string().optional(),
});
@@ -23,7 +23,7 @@ export const validateTextContentSection = (
return {};
}
- const parsedResult = TextContentValues.safeParse({
+ const parsedResult = textContentValues.safeParse({
content: computeExpression(values.content, variableValues),
});
diff --git a/apps/builder/app/builder/features/pages/page-utils.test.ts b/apps/builder/app/builder/features/pages/page-utils.test.ts
index 8754bd04af..7dbdc3ef9a 100644
--- a/apps/builder/app/builder/features/pages/page-utils.test.ts
+++ b/apps/builder/app/builder/features/pages/page-utils.test.ts
@@ -12,7 +12,7 @@ import {
type Instance,
type Page,
SYSTEM_VARIABLE_ID,
- Resource,
+ type Resource,
type Pages,
type WebstudioData,
} from "@webstudio-is/sdk";
diff --git a/apps/builder/app/builder/features/pages/page-utils.ts b/apps/builder/app/builder/features/pages/page-utils.ts
index 9b60fee855..274d26bf45 100644
--- a/apps/builder/app/builder/features/pages/page-utils.ts
+++ b/apps/builder/app/builder/features/pages/page-utils.ts
@@ -6,7 +6,7 @@ import {
type PageTemplate,
type Folder,
type WebstudioData,
- Pages,
+ type Pages,
findPageByIdOrPath,
getPagePath,
findParentFolderByChildId,
@@ -268,7 +268,7 @@ export const deletePageMutable = (pageId: Page["id"], data: WebstudioData) => {
if ($selectedPage.get()?.id === pageId) {
selectPage(pages.homePageId);
}
- const rootInstanceId = findPageByIdOrPath(pageId, pages)?.rootInstanceId;
+ const rootInstanceId = findPageByIdOrPath(pageId, data.pages)?.rootInstanceId;
if (rootInstanceId !== undefined) {
deleteInstanceMutable(
data,
@@ -276,12 +276,12 @@ export const deletePageMutable = (pageId: Page["id"], data: WebstudioData) => {
);
}
pages.pages.delete(pageId);
- cleanupChildRefsMutable(pageId, pages.folders);
+ cleanupChildRefsMutable(pageId, data.pages.folders);
};
/**
* Deletes folder and child folders.
- * Doesn't delete pages, only returns pageIds.
+ * Doesn't delete only returns pageIds.
*/
export const deleteFolderWithChildrenMutable = (
folderId: Folder["id"],
diff --git a/apps/builder/app/builder/features/pages/template-settings.tsx b/apps/builder/app/builder/features/pages/template-settings.tsx
index fc88cb17d3..bb34d7fcac 100644
--- a/apps/builder/app/builder/features/pages/template-settings.tsx
+++ b/apps/builder/app/builder/features/pages/template-settings.tsx
@@ -4,8 +4,8 @@ import { useState, type JSX } from "react";
import { useStore } from "@nanostores/react";
import {
type PageTemplate,
- PageName,
- PageTitle,
+ pageName,
+ pageTitle,
elementComponent,
type Page,
type Pages,
@@ -43,13 +43,13 @@ import { useDraftValue } from "~/builder/shared/use-draft-value";
import { copyTemplate } from "~/shared/copy-paste/copy-paste";
import { PageItemActionsDropdown } from "./page-item-actions";
-const TemplateValues = z.object({
- name: PageName,
- title: PageTitle,
+const templateValues = z.object({
+ name: pageName,
+ title: pageTitle,
});
const validateTemplateValues = (values: Values): Errors => {
- const result = TemplateValues.safeParse(values);
+ const result = templateValues.safeParse(values);
if (result.success) {
return {};
}
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 5ac840c150..7056c27dc1 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
@@ -19,7 +19,11 @@ import {
NestedInputButton,
theme,
} from "@webstudio-is/design-system";
-import { isLiteralExpression, Resource, type Prop } from "@webstudio-is/sdk";
+import {
+ isLiteralExpression,
+ type Resource,
+ type Prop,
+} from "@webstudio-is/sdk";
import {
BindingControl,
BindingPopover,
diff --git a/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-keyframes.tsx b/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-keyframes.tsx
index ad36ea42ed..38cdef351a 100644
--- a/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-keyframes.tsx
+++ b/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-keyframes.tsx
@@ -1,6 +1,6 @@
import { Fragment, useId, useMemo, useRef, useState } from "react";
import {
- StyleValue,
+ type StyleValue,
toValue,
type CssProperty,
} from "@webstudio-is/css-engine";
diff --git a/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-panel-content.tsx b/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-panel-content.tsx
index f549bacd69..d746b070f8 100644
--- a/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-panel-content.tsx
+++ b/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-panel-content.tsx
@@ -13,18 +13,16 @@ import {
} from "@webstudio-is/design-system";
import { keywordValues } from "@webstudio-is/css-data";
-import type {
- DurationUnitValue,
- RangeUnitValue,
- IterationsUnitValue,
- ScrollAnimation,
- ViewAnimation,
-} from "@webstudio-is/sdk";
import {
- durationUnitValueSchema,
- rangeUnitValueSchema,
- scrollAnimationSchema,
- viewAnimationSchema,
+ type DurationUnitValue,
+ durationUnitValue,
+ type RangeUnitValue,
+ rangeUnitValue,
+ type IterationsUnitValue,
+ type ScrollAnimation,
+ scrollAnimation,
+ type ViewAnimation,
+ viewAnimation,
} from "@webstudio-is/sdk";
import {
CssValueInput,
@@ -214,7 +212,7 @@ const RangeValueInput = ({
property="margin-left" /* allows negative values */
disabled={disabled}
onValidate={(styleValue) => {
- const parsedValue = rangeUnitValueSchema.safeParse(styleValue);
+ const parsedValue = rangeUnitValue.safeParse(styleValue);
return parsedValue.success
? { success: true, data: parsedValue.data }
: { success: false };
@@ -268,7 +266,7 @@ const DurationInput = ({
if (rawValue.toLowerCase() === "auto") {
return { success: true, data: undefined };
}
- const parsedValue = durationUnitValueSchema.safeParse(styleValue);
+ const parsedValue = durationUnitValue.safeParse(styleValue);
return parsedValue.success
? { success: true, data: parsedValue.data }
: { success: false };
@@ -475,9 +473,7 @@ export const AnimationPanelContent = ({
const isRangeStartEnabled = value.timing.delay === undefined;
const isIterationsEnabled = value.timing.duration !== undefined;
- const animationSchema = isScrollAnimation
- ? scrollAnimationSchema
- : viewAnimationSchema;
+ const animation = isScrollAnimation ? scrollAnimation : viewAnimation;
const handleChange = (rawValue: unknown, isEphemeral: boolean) => {
if (rawValue === undefined) {
@@ -485,7 +481,7 @@ export const AnimationPanelContent = ({
return;
}
- const parsedValue = animationSchema.safeParse(rawValue);
+ const parsedValue = animation.safeParse(rawValue);
if (parsedValue.success) {
onChange(parsedValue.data, isEphemeral);
diff --git a/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-section.tsx b/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-section.tsx
index 22019064c2..437492b11b 100644
--- a/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-section.tsx
+++ b/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-section.tsx
@@ -15,14 +15,12 @@ import {
FloatingPanel,
IconButton,
} from "@webstudio-is/design-system";
-import type {
- AnimationAction,
- AnimationActionScroll,
- InsetUnitValue,
-} from "@webstudio-is/sdk";
import {
- animationActionSchema,
- insetUnitValueSchema,
+ type AnimationAction,
+ type AnimationActionScroll,
+ animationAction,
+ type InsetUnitValue,
+ insetUnitValue,
RANGE_UNITS,
} from "@webstudio-is/sdk";
import {
@@ -139,7 +137,7 @@ const InsetValueInput = ({
return;
}
- const parsedResult = insetUnitValueSchema.safeParse(styleValue);
+ const parsedResult = insetUnitValue.safeParse(styleValue);
if (parsedResult.success) {
onChange(parsedResult.data, true);
@@ -176,7 +174,7 @@ const InsetValueInput = ({
handleEphemeralChange(value);
}}
onChangeComplete={(event) => {
- const parsedValue = insetUnitValueSchema.safeParse(event.value);
+ const parsedValue = insetUnitValue.safeParse(event.value);
if (parsedValue.success) {
onChange(parsedValue.data, false);
setIntermediateValue(undefined);
@@ -360,7 +358,7 @@ const AnimationConfigButton = forwardRef<
});
export const AnimationSection = ({
- animationAction,
+ animationAction: animationActionProp,
onChange,
isAnimationEnabled,
selectedBreakpointId,
@@ -373,7 +371,7 @@ export const AnimationSection = ({
) => boolean | undefined;
selectedBreakpointId: string;
}) => {
- const { prop } = animationAction;
+ const { prop } = animationActionProp;
const value: AnimationAction =
prop?.type === "animationAction" ? prop.value : defaultActionValue;
@@ -384,7 +382,7 @@ export const AnimationSection = ({
return;
}
- const parsedValue = animationActionSchema.safeParse(value);
+ const parsedValue = animationAction.safeParse(value);
if (parsedValue.success) {
onChange(parsedValue.data, isEphemeral);
return;
diff --git a/apps/builder/app/builder/features/settings-panel/props-section/animation/animations-select.tsx b/apps/builder/app/builder/features/settings-panel/props-section/animation/animations-select.tsx
index b57b7ab0dd..a009b15609 100644
--- a/apps/builder/app/builder/features/settings-panel/props-section/animation/animations-select.tsx
+++ b/apps/builder/app/builder/features/settings-panel/props-section/animation/animations-select.tsx
@@ -35,8 +35,8 @@ import {
PlusIcon,
} from "@webstudio-is/icons";
import {
- scrollAnimationSchema,
- viewAnimationSchema,
+ scrollAnimation,
+ viewAnimation,
type AnimationAction,
type ScrollAnimation,
type ViewAnimation,
@@ -79,7 +79,7 @@ const serialize = (animations: (ScrollAnimation | ViewAnimation)[]) => {
const parseViewAnimations = (text: string): ViewAnimation[] => {
const data = JSON.parse(text);
const parsed = z
- .object({ [clipboardNamespace]: z.array(viewAnimationSchema) })
+ .object({ [clipboardNamespace]: z.array(viewAnimation) })
.parse(data);
return parsed[clipboardNamespace];
};
@@ -87,7 +87,7 @@ const parseViewAnimations = (text: string): ViewAnimation[] => {
const parseScrollAnimations = (text: string): ScrollAnimation[] => {
const data = JSON.parse(text);
const parsed = z
- .object({ [clipboardNamespace]: z.array(scrollAnimationSchema) })
+ .object({ [clipboardNamespace]: z.array(scrollAnimation) })
.parse(data);
return parsed[clipboardNamespace];
};
diff --git a/apps/builder/app/builder/features/settings-panel/props-section/animation/set-css-property.ts b/apps/builder/app/builder/features/settings-panel/props-section/animation/set-css-property.ts
index 4784e8ba2d..a5906a1d90 100644
--- a/apps/builder/app/builder/features/settings-panel/props-section/animation/set-css-property.ts
+++ b/apps/builder/app/builder/features/settings-panel/props-section/animation/set-css-property.ts
@@ -2,7 +2,7 @@ import { nanoid } from "nanoid";
import type { CssProperty, StyleValue } from "@webstudio-is/css-engine";
import {
getStyleDeclKey,
- StyleDecl,
+ type StyleDecl,
type Breakpoints,
type Instance,
type Styles,
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 092ace9292..c7c64b570a 100644
--- a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
@@ -12,8 +12,9 @@ import {
} from "react";
import { useStore } from "@nanostores/react";
import {
- DataSources,
- Resource,
+ type DataSources,
+ type Resource,
+ resource,
type DataSource,
type Page,
type PageTemplate,
@@ -88,7 +89,7 @@ export const parseResource = ({
const searchParamValues = formData.getAll("search-param-value") as string[];
const headerNames = formData.getAll("header-name") as string[];
const headerValues = formData.getAll("header-value") as string[];
- return Resource.parse({
+ return resource.parse({
id,
control,
name: name ?? formData.get("name"),
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 f5c57a2e42..b424499a5e 100644
--- a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
@@ -47,7 +47,7 @@ import {
transpileExpression,
lintExpression,
SYSTEM_VARIABLE_ID,
- ResourceRequest,
+ resourceRequest,
} from "@webstudio-is/sdk";
import {
ExpressionEditor,
@@ -695,18 +695,18 @@ const VariablePreview = ({
computedValue = variable ? variableValues.get(variable.id) : undefined;
} else {
// try to load current resource or saved one
- let resourceRequest = ResourceRequest.safeParse(variableValue).data;
- if (!resourceRequest && variable?.type === "resource") {
+ let parsedResourceRequest = resourceRequest.safeParse(variableValue).data;
+ if (!parsedResourceRequest && variable?.type === "resource") {
const resource = resources.get(variable.resourceId);
if (resource) {
- resourceRequest = computeResourceRequest(
+ parsedResourceRequest = computeResourceRequest(
resource,
resourceScope.variableValues
);
}
}
- if (resourceRequest) {
- computedValue = resourcesCache.get(getResourceKey(resourceRequest));
+ if (parsedResourceRequest) {
+ computedValue = resourcesCache.get(getResourceKey(parsedResourceRequest));
}
}
const extensions = useMemo(() => [javascript({}), foldGutterExtension], []);
diff --git a/apps/builder/app/builder/features/style-panel/controls/position/position-control.tsx b/apps/builder/app/builder/features/style-panel/controls/position/position-control.tsx
index 0718ba5c06..8ca27780c9 100644
--- a/apps/builder/app/builder/features/style-panel/controls/position/position-control.tsx
+++ b/apps/builder/app/builder/features/style-panel/controls/position/position-control.tsx
@@ -4,8 +4,9 @@ import {
propertyDescriptions,
} from "@webstudio-is/css-data";
import {
- TupleValue,
- TupleValueItem,
+ type TupleValue,
+ tupleValue,
+ tupleValueItem,
type StyleValue,
type CssProperty,
} from "@webstudio-is/css-engine";
@@ -37,15 +38,15 @@ const toTuple = (
valueX?: StyleValue | string,
valueY?: StyleValue | string
) => {
- const parsedValue = TupleValue.safeParse(valueX);
+ const parsedValue = tupleValue.safeParse(valueX);
if (parsedValue.success) {
return parsedValue.data;
}
const parsedValueX = valueX
- ? TupleValueItem.parse(valueX)
+ ? tupleValueItem.parse(valueX)
: ({ type: "unit", value: 0, unit: "px" } as const);
- const parsedValueY = valueY ? TupleValueItem.parse(valueY) : parsedValueX;
+ const parsedValueY = valueY ? tupleValueItem.parse(valueY) : parsedValueX;
return {
type: "tuple" as const,
diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-size.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-size.tsx
index 7c527849de..1d4285ca88 100644
--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-size.tsx
+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-size.tsx
@@ -3,8 +3,8 @@ import { toValue } from "@webstudio-is/css-engine";
import { keywordValues, propertyDescriptions } from "@webstudio-is/css-data";
import {
type StyleValue,
- TupleValue,
- TupleValueItem,
+ tupleValue,
+ tupleValueItem,
} from "@webstudio-is/css-engine";
import { CssValueInputContainer } from "../../shared/css-value-input";
import type { SetValue } from "../../shared/use-style-data";
@@ -35,13 +35,13 @@ const toTuple = (
valueX?: StyleValue | string,
valueY?: StyleValue | string
) => {
- const parsedValue = TupleValue.safeParse(valueX);
+ const parsedValue = tupleValue.safeParse(valueX);
if (parsedValue.success) {
return parsedValue.data;
}
- const parsedValueX = valueX ? TupleValueItem.parse(valueX) : autoKeyword;
- const parsedValueY = valueY ? TupleValueItem.parse(valueY) : parsedValueX;
+ const parsedValueX = valueX ? tupleValueItem.parse(valueX) : autoKeyword;
+ const parsedValueY = valueY ? tupleValueItem.parse(valueY) : parsedValueX;
return {
type: "tuple" as const,
diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-thumbnail.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-thumbnail.tsx
index b332e32628..cb33c12ca4 100644
--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-thumbnail.tsx
+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-thumbnail.tsx
@@ -3,7 +3,7 @@ import type { Assets } from "@webstudio-is/sdk";
import { Image as WebstudioImage, wsImageLoader } from "@webstudio-is/image";
import { styled, theme } from "@webstudio-is/design-system";
import {
- StyleValue,
+ type StyleValue,
toValue,
type CssProperty,
} from "@webstudio-is/css-engine";
diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/gradient-utils.ts b/apps/builder/app/builder/features/style-panel/sections/backgrounds/gradient-utils.ts
index 4082bd1448..7795a05305 100644
--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/gradient-utils.ts
+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/gradient-utils.ts
@@ -1,6 +1,6 @@
import { clamp } from "@react-aria/utils";
import {
- ColorValue,
+ type ColorValue,
toValue,
type CssProperty,
type KeywordValue,
diff --git a/apps/builder/app/builder/features/style-panel/sections/position/inset-control.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/position/inset-control.stories.tsx
index ea229ff6c3..af6317ff88 100644
--- a/apps/builder/app/builder/features/style-panel/sections/position/inset-control.stories.tsx
+++ b/apps/builder/app/builder/features/style-panel/sections/position/inset-control.stories.tsx
@@ -1,6 +1,6 @@
import type { Meta } from "@storybook/react";
import { Box, StorySection, theme } from "@webstudio-is/design-system";
-import { getStyleDeclKey, StyleDecl } from "@webstudio-is/sdk";
+import { getStyleDeclKey, type StyleDecl } from "@webstudio-is/sdk";
import { createDefaultPages } from "@webstudio-is/project-build";
import { InsetControl } from "./inset-control";
import { registerContainers } from "~/shared/sync/sync-stores";
diff --git a/apps/builder/app/builder/features/style-panel/sections/transforms/transform-and-perspective-origin.tsx b/apps/builder/app/builder/features/style-panel/sections/transforms/transform-and-perspective-origin.tsx
index 9beb94554a..803958f803 100644
--- a/apps/builder/app/builder/features/style-panel/sections/transforms/transform-and-perspective-origin.tsx
+++ b/apps/builder/app/builder/features/style-panel/sections/transforms/transform-and-perspective-origin.tsx
@@ -5,10 +5,10 @@ import {
} from "@webstudio-is/css-data";
import { Flex, Grid, PositionGrid } from "@webstudio-is/design-system";
import {
- KeywordValue,
- StyleValue,
- TupleValue,
- UnitValue,
+ type KeywordValue,
+ type StyleValue,
+ type TupleValue,
+ type UnitValue,
type CssProperty,
} from "@webstudio-is/css-engine";
import { useMemo } from "react";
diff --git a/apps/builder/app/builder/features/style-panel/sections/transforms/transform-utils.ts b/apps/builder/app/builder/features/style-panel/sections/transforms/transform-utils.ts
index 56e6df3044..4c07cc4b99 100644
--- a/apps/builder/app/builder/features/style-panel/sections/transforms/transform-utils.ts
+++ b/apps/builder/app/builder/features/style-panel/sections/transforms/transform-utils.ts
@@ -1,7 +1,7 @@
import { parseCssValue } from "@webstudio-is/css-data";
import {
- FunctionValue,
- StyleValue,
+ type FunctionValue,
+ type StyleValue,
toValue,
type TupleValue,
} from "@webstudio-is/css-engine";
diff --git a/apps/builder/app/builder/features/style-panel/sections/transitions/transitions.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/transitions/transitions.stories.tsx
index 0209d6af05..c78a149a4e 100644
--- a/apps/builder/app/builder/features/style-panel/sections/transitions/transitions.stories.tsx
+++ b/apps/builder/app/builder/features/style-panel/sections/transitions/transitions.stories.tsx
@@ -1,5 +1,5 @@
import { Box, StorySection, theme } from "@webstudio-is/design-system";
-import { getStyleDeclKey, StyleDecl } from "@webstudio-is/sdk";
+import { getStyleDeclKey, type StyleDecl } from "@webstudio-is/sdk";
import { $selectedBreakpointId } from "~/shared/nano-states";
import { $breakpoints } from "~/shared/sync/data-stores";
import {
diff --git a/apps/builder/app/builder/features/style-panel/shared/filter-content.tsx b/apps/builder/app/builder/features/style-panel/shared/filter-content.tsx
index 712bb0e41c..98491671ba 100644
--- a/apps/builder/app/builder/features/style-panel/shared/filter-content.tsx
+++ b/apps/builder/app/builder/features/style-panel/shared/filter-content.tsx
@@ -2,7 +2,7 @@ import {
type InvalidValue,
type TupleValue,
toValue,
- StyleValue,
+ type StyleValue,
} from "@webstudio-is/css-engine";
import {
Flex,
diff --git a/apps/builder/app/builder/shared/client-settings/settings.ts b/apps/builder/app/builder/shared/client-settings/settings.ts
index 03c1536acf..63c332bd3d 100644
--- a/apps/builder/app/builder/shared/client-settings/settings.ts
+++ b/apps/builder/app/builder/shared/client-settings/settings.ts
@@ -2,7 +2,7 @@ import { atom } from "nanostores";
import { z } from "zod";
import { sidebarPanelNames } from "~/builder/sidebar-left/types";
-const Settings = z.object({
+const userSettings = z.object({
navigatorLayout: z.enum(["docked", "undocked"]).default("undocked"),
stylePanelMode: z.enum(["default", "focus", "advanced"]).default("default"),
sidebarPanelWidths: z
@@ -11,9 +11,9 @@ const Settings = z.object({
lastDashboardSearch: z.string().default(""),
});
-export type Settings = z.infer<typeof Settings>;
+export type Settings = z.infer<typeof userSettings>;
-const defaultSettings = Settings.parse({});
+const defaultSettings = userSettings.parse({});
const namespace = "__webstudio_user_settings__";
@@ -30,7 +30,7 @@ const read = (): Settings => {
}
try {
- return Settings.parse(JSON.parse(settingsString));
+ return userSettings.parse(JSON.parse(settingsString));
} catch (error) {
if (error instanceof Error) {
console.error({
diff --git a/apps/builder/app/canvas/shared/styles.ts b/apps/builder/app/canvas/shared/styles.ts
index a4f17e22e1..b7b7c4fa24 100644
--- a/apps/builder/app/canvas/shared/styles.ts
+++ b/apps/builder/app/canvas/shared/styles.ts
@@ -2,7 +2,7 @@ import { useLayoutEffect } from "react";
import { computed } from "nanostores";
import { useStore } from "@nanostores/react";
import {
- Instance,
+ type Instance,
ROOT_INSTANCE_ID,
getStyleDeclKey,
descendantComponent,
@@ -17,7 +17,7 @@ import { inflatedAttribute, idAttribute } from "@webstudio-is/react-sdk";
import { INFLATE_PADDING } from "~/canvas/inflator";
import { isPseudoElement, parseMediaCondition } from "@webstudio-is/css-data";
import {
- StyleValue,
+ type StyleValue,
type MediaRuleOptions,
type StyleSheetRegular,
type TransformValue,
diff --git a/apps/builder/app/dashboard/projects/project-dialogs.tsx b/apps/builder/app/dashboard/projects/project-dialogs.tsx
index 2659c7d04f..e565b37455 100644
--- a/apps/builder/app/dashboard/projects/project-dialogs.tsx
+++ b/apps/builder/app/dashboard/projects/project-dialogs.tsx
@@ -17,7 +17,7 @@ import {
theme,
} from "@webstudio-is/design-system";
import { PlusIcon } from "@webstudio-is/icons";
-import { Title } from "@webstudio-is/project";
+import { projectTitle } from "@webstudio-is/project";
import { builderUrl } from "~/shared/router-utils";
import { ShareProjectContainer } from "~/shared/share-project";
import { trpcClient } from "~/shared/trpc/trpc-client";
@@ -141,7 +141,7 @@ const useCreateProject = (workspaceId?: string) => {
const [errors, setErrors] = useState<string>();
const handleSubmit = ({ title }: { title: string }) => {
- const parsed = Title.safeParse(title);
+ const parsed = projectTitle.safeParse(title);
const errors =
"error" in parsed
? parsed.error?.issues.map((issue) => issue.message).join("\n")
@@ -217,7 +217,7 @@ const useRenameProject = ({
const revalidator = useRevalidator();
const handleSubmit = ({ title }: { title: string }) => {
- const parsed = Title.safeParse(title);
+ const parsed = projectTitle.safeParse(title);
const errors =
"error" in parsed
? parsed.error?.issues.map((issue) => issue.message).join("\n")
diff --git a/apps/builder/app/env/env.server.ts b/apps/builder/app/env/env.server.ts
index 1599cae10f..2154f59264 100644
--- a/apps/builder/app/env/env.server.ts
+++ b/apps/builder/app/env/env.server.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
-const envSchema = z.object({
+const environment = z.object({
// Authentication
DEV_LOGIN: z.string().optional(),
GH_CLIENT_ID: z.string().optional(),
@@ -119,7 +119,7 @@ const rawEnv = {
VERCEL_URL: process.env.VERCEL_URL,
};
-const parseResult = envSchema.safeParse(rawEnv);
+const parseResult = environment.safeParse(rawEnv);
if (!parseResult.success) {
console.error("Invalid environment variables:", parseResult.error.format());
diff --git a/apps/builder/app/routes-tests/rest-assets-name.server.test.ts b/apps/builder/app/routes-tests/rest-assets-name.server.test.ts
new file mode 100644
index 0000000000..412f244fad
--- /dev/null
+++ b/apps/builder/app/routes-tests/rest-assets-name.server.test.ts
@@ -0,0 +1,133 @@
+import { afterEach, expect, test, vi } from "vitest";
+import { RESIZABLE_IMAGE_MIME_TYPES } from "@webstudio-is/sdk";
+import { __testing__ } from "../routes/rest.assets_.$name";
+
+const {
+ getAssetInfoFallback,
+ getBrowserAssetFormat,
+ getBrowserUploadBody,
+ parseAssetType,
+} = __testing__;
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+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",
+ });
+
+ await expect(
+ new Response(
+ await getBrowserUploadBody(request, "application/octet-stream")
+ ).text()
+ ).resolves.toBe("raw file");
+});
+
+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" },
+ });
+
+ await expect(
+ new Response(await getBrowserUploadBody(request, "application/json")).text()
+ ).resolves.toBe(JSON.stringify({ value: 1 }));
+});
+
+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" },
+ });
+
+ await expect(
+ new Response(await getBrowserUploadBody(request, "application/json")).text()
+ ).resolves.toBe("remote image");
+ expect(fetch).toHaveBeenCalledWith("https://example.com/image.png", {
+ method: "GET",
+ headers: { Accept: RESIZABLE_IMAGE_MIME_TYPES.join(",") },
+ });
+});
+
+test("reports browser URL image fetch failures", async () => {
+ vi.stubGlobal(
+ "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" },
+ });
+
+ await expect(
+ getBrowserUploadBody(request, "application/json")
+ ).rejects.toThrow(
+ "An error occurred while fetching the image at https://example.com/image.png: not found"
+ );
+});
+
+test("preserves browser asset format detection", () => {
+ expect(
+ getBrowserAssetFormat({
+ contentType: "application/font-woff",
+ name: "font.woff",
+ })
+ ).toBeUndefined();
+ expect(
+ getBrowserAssetFormat({
+ contentType: "application/octet-stream",
+ name: "video.mp4",
+ })
+ ).toBe("mp4");
+ expect(() =>
+ getBrowserAssetFormat({
+ contentType: "script/javascript",
+ name: "script.unknown",
+ })
+ ).toThrow('MIME type "script/*" is not allowed');
+});
+
+test("accepts only stored asset types for API uploads", () => {
+ expect(parseAssetType("image")).toBe("image");
+ expect(parseAssetType("font")).toBe("font");
+ expect(parseAssetType("file")).toBe("file");
+ expect(parseAssetType("video")).toBeUndefined();
+ expect(parseAssetType(null)).toBeUndefined();
+});
+
+test("uses image metadata fallback only when complete", () => {
+ expect(
+ getAssetInfoFallback({
+ format: "png",
+ searchParams: new URLSearchParams({
+ width: "10",
+ height: "20",
+ }),
+ })
+ ).toEqual({ width: 10, height: 20, format: "png" });
+ expect(
+ getAssetInfoFallback({
+ format: undefined,
+ searchParams: new URLSearchParams({
+ width: "10",
+ height: "20",
+ }),
+ })
+ ).toBeUndefined();
+ expect(
+ getAssetInfoFallback({
+ format: "png",
+ searchParams: new URLSearchParams({
+ width: "10",
+ }),
+ })
+ ).toBeUndefined();
+});
diff --git a/apps/builder/app/routes/_ui.error.tsx b/apps/builder/app/routes/_ui.error.tsx
index 8a48b8f916..b942548471 100644
--- a/apps/builder/app/routes/_ui.error.tsx
+++ b/apps/builder/app/routes/_ui.error.tsx
@@ -9,7 +9,7 @@ import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
import { isBuilder } from "~/shared/router-utils";
export { ErrorBoundary } from "~/shared/error/error-boundary";
-const SessionError = z.object({
+const sessionError = z.object({
message: z.string(),
description: z.string().optional(),
});
@@ -82,7 +82,7 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
const rawError = session.get(sessionErrorKey);
- const parsedError = SessionError.safeParse(rawError);
+ const parsedError = sessionError.safeParse(rawError);
const error = parsedError.success
? parsedError.data
diff --git a/apps/builder/app/routes/cgi.image.$.ts b/apps/builder/app/routes/cgi.image.$.ts
index 1fc518ba5e..8fc2c035ef 100644
--- a/apps/builder/app/routes/cgi.image.$.ts
+++ b/apps/builder/app/routes/cgi.image.$.ts
@@ -9,7 +9,7 @@ import env from "~/env/env.server";
import { getImageNameAndType } from "~/builder/shared/assets/asset-utils";
import { fileUploadPath } from "~/shared/asset-client";
-const ImageParams = z.object({
+const imageParams = z.object({
width: z.string().transform((value) => Math.round(parseFloat(value))),
height: z.optional(
z.string().transform((value) => Math.round(parseFloat(value)))
@@ -58,7 +58,7 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
rawParameters.fit = fit;
}
- const imageParameters = ImageParams.parse(rawParameters);
+ const imageParameters = imageParams.parse(rawParameters);
// Allow direct image access, and from the same origin
const refererRawUrl = request.headers.get("referer");
diff --git a/apps/builder/app/routes/oauth.ws.authorize.tsx b/apps/builder/app/routes/oauth.ws.authorize.tsx
index 2398dbc636..0ffed93a3e 100644
--- a/apps/builder/app/routes/oauth.ws.authorize.tsx
+++ b/apps/builder/app/routes/oauth.ws.authorize.tsx
@@ -50,7 +50,7 @@ const createOauthError =
*
* https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.1
*/
-const OAuthParams = z.object({
+const oAuthParams = z.object({
// Ensure that the response_type is valid and supported by the authorization server (e.g., code for the authorization code grant type).
response_type: z.literal("code"),
redirect_uri: z.string().url(),
@@ -69,7 +69,7 @@ const OAuthParams = z.object({
code_challenge_method: z.literal("S256"),
});
-const OAuthRedirectUri = z.object({
+const oAuthRedirectUri = z.object({
redirect_uri: z.string().url(),
});
@@ -97,7 +97,7 @@ export const loader: LoaderFunction = async ({ request }) => {
const url = new URL(request.url);
const searchParams = Object.fromEntries(url.searchParams);
- const parsedRedirect = OAuthRedirectUri.safeParse(searchParams);
+ const parsedRedirect = oAuthRedirectUri.safeParse(searchParams);
if (false === parsedRedirect.success) {
debug("redirect_uri not provided in query params");
@@ -138,7 +138,7 @@ export const loader: LoaderFunction = async ({ request }) => {
let oauthError = createOauthError(redirect_uri, searchParams.state);
- const parsedOAuthParams = OAuthParams.safeParse(searchParams);
+ const parsedOAuthParams = oAuthParams.safeParse(searchParams);
if (false === parsedOAuthParams.success) {
debug(fromError(parsedOAuthParams.error).toString());
@@ -159,14 +159,14 @@ export const loader: LoaderFunction = async ({ request }) => {
return oauthError("unauthorized_client", "Client is not registered");
}
- const oAuthParams = parsedOAuthParams.data;
+ const oauthParamsData = parsedOAuthParams.data;
const sessionData = await authenticator.isAuthenticated(request);
if (sessionData) {
const isAuthorized = await isUserAuthorizedForProject(
sessionData.userId,
- oAuthParams.scope.projectId
+ oauthParamsData.scope.projectId
);
// scope: Ensure the requested scope is valid, authorized, and within the permissions granted to the client.
@@ -184,7 +184,7 @@ export const loader: LoaderFunction = async ({ request }) => {
compareUrls(
new URL(redirect_uri).origin,
builderUrl({
- projectId: oAuthParams.scope.projectId,
+ projectId: oauthParamsData.scope.projectId,
origin: getAuthorizationServerOrigin(request.url),
})
)
@@ -207,23 +207,23 @@ export const loader: LoaderFunction = async ({ request }) => {
const code = await createCodeToken(
{
userId: sessionData.userId,
- projectId: oAuthParams.scope.projectId,
- codeChallenge: oAuthParams.code_challenge,
+ projectId: oauthParamsData.scope.projectId,
+ codeChallenge: oauthParamsData.code_challenge,
},
env.AUTH_WS_CLIENT_SECRET,
{ maxAge: 1000 * 60 * 5 }
);
- const redirectUri = new URL(oAuthParams.redirect_uri);
+ const redirectUri = new URL(oauthParamsData.redirect_uri);
redirectUri.search = "";
redirectUri.searchParams.set("code", code);
// state: If present, store the state parameter to return it unchanged in the response
- redirectUri.searchParams.set("state", oAuthParams.state);
+ redirectUri.searchParams.set("state", oauthParamsData.state);
const bloomFilter = await session.readLoginSessionBloomFilter(request);
- bloomFilter.add(oAuthParams.scope.projectId);
+ bloomFilter.add(oauthParamsData.scope.projectId);
return session.writeLoginSessionBloomFilter(
request,
diff --git a/apps/builder/app/routes/oauth.ws.token.ts b/apps/builder/app/routes/oauth.ws.token.ts
index 4983d23f72..f7e0b9f962 100644
--- a/apps/builder/app/routes/oauth.ws.token.ts
+++ b/apps/builder/app/routes/oauth.ws.token.ts
@@ -21,7 +21,7 @@ import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";
*
* https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.3
*/
-const TokenRequest = z.object({
+const tokenRequest = z.object({
// Check that the grant_type parameter is present and is one of the supported values
grant_type: z.literal("authorization_code"),
code: z.string(),
@@ -89,7 +89,7 @@ export const action = async ({ request }: ActionFunctionArgs) => {
const jsonBody = Object.fromEntries((await request.formData()).entries());
- const parsedBody = TokenRequest.safeParse(jsonBody);
+ const parsedBody = tokenRequest.safeParse(jsonBody);
if (false === parsedBody.success) {
debug(fromError(parsedBody.error).toString());
diff --git a/apps/builder/app/routes/rest.$.ts b/apps/builder/app/routes/rest.$.ts
index 8c0b5b74c7..b721cfb850 100644
--- a/apps/builder/app/routes/rest.$.ts
+++ b/apps/builder/app/routes/rest.$.ts
@@ -1,12 +1,12 @@
import type { LoaderFunctionArgs } from "@remix-run/server-runtime";
import {
- ApiCompatibilityTarget,
+ apiCompatibilityTarget,
apiClientHeader,
createApiCompatibilityPayload,
} from "@webstudio-is/trpc-interface/api-compatibility";
const getTarget = (request: Request) => {
- const client = ApiCompatibilityTarget.safeParse(
+ const client = apiCompatibilityTarget.safeParse(
request.headers.get(apiClientHeader)
);
if (client.success) {
diff --git a/apps/builder/app/routes/rest.assets_.$name.tsx b/apps/builder/app/routes/rest.assets_.$name.tsx
index b6f24be941..34f546e002 100644
--- a/apps/builder/app/routes/rest.assets_.$name.tsx
+++ b/apps/builder/app/routes/rest.assets_.$name.tsx
@@ -1,11 +1,18 @@
import { z } from "zod";
import { json, type ActionFunctionArgs } from "@remix-run/server-runtime";
-import { uploadFile } from "@webstudio-is/asset-uploader/index.server";
+import {
+ uploadFile,
+ type UploadErrorCleanup,
+} from "@webstudio-is/asset-uploader/index.server";
import {
isAllowedMimeCategory,
RESIZABLE_IMAGE_MIME_TYPES,
ALLOWED_FILE_TYPES,
+ type Asset,
+ assetType,
} from "@webstudio-is/sdk";
+import type { Database } from "@webstudio-is/postgrest/index.server";
+import { isAssetFileName } from "@webstudio-is/protocol";
import type { AssetActionResponse } from "~/builder/shared/assets";
import { createAssetClient } from "~/shared/asset-client";
import { createContext } from "~/shared/context.server";
@@ -13,128 +20,298 @@ 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 { assertProjectBuildPermit } from "~/services/project-import.server";
-const UrlBody = z.object({
+const urlBody = z.object({
url: z.string(),
});
-export const action = async (props: ActionFunctionArgs) => {
- preventCrossOriginCookie(props.request);
- await checkCsrf(props.request);
+const parseAssetType = (value: string | null) => {
+ const result = assetType.safeParse(value);
+ return result.success ? result.data : undefined;
+};
- const { request, params } = props;
+type AssetInfoFallback =
+ | { width: number; height: number; format: string }
+ | undefined;
+type FileRow = Database["public"]["Tables"]["File"]["Row"];
- // await new Promise((resolve) => setTimeout(resolve, 20000));
+const getAssetInfoFallback = ({
+ format,
+ searchParams,
+}: {
+ format: string | undefined;
+ searchParams: URLSearchParams;
+}) => {
+ const width = Number.parseInt(searchParams.get("width") ?? "", 10);
+ const height = Number.parseInt(searchParams.get("height") ?? "", 10);
+ if (
+ Number.isFinite(width) === false ||
+ Number.isFinite(height) === false ||
+ format === undefined
+ ) {
+ return;
+ }
+ return { width, height, format };
+};
- if (params.name === undefined) {
- throw new Error("Name is undefined");
+const reserveAssetUpload = async ({
+ context,
+ name,
+ projectId,
+ type,
+}: {
+ context: Awaited<ReturnType<typeof createContext>>;
+ name: string;
+ projectId: string;
+ type: Asset["type"];
+}): Promise<UploadErrorCleanup> => {
+ const existingFile = await context.postgrest.client
+ .from("File")
+ .select("*")
+ .eq("name", name)
+ .maybeSingle();
+ if (existingFile.error) {
+ throw existingFile.error;
}
- try {
- if (request.method === "POST" && request.body !== null) {
- let body = request.body;
-
- const contentType = request.headers.get("Content-Type");
-
- // Check if this is a request to download from URL (has url field in JSON body)
- // vs uploading a JSON file directly (JSON file content in body)
- if (contentType?.includes("application/json")) {
- const jsonBody = await request.json();
- const urlParse = UrlBody.safeParse(jsonBody);
-
- // Only fetch from URL if the body has a valid url field
- if (urlParse.success) {
- const { url } = urlParse.data;
-
- const imageRequest = await fetch(url, {
- method: "GET",
- headers: {
- Accept: RESIZABLE_IMAGE_MIME_TYPES.join(","),
- },
- });
-
- if (false === imageRequest.ok) {
- const error = await imageRequest.text();
- const errors = `An error occurred while fetching the image at ${url}: ${error.slice(0, 500)}`;
- throw new Error(errors);
- }
-
- if (imageRequest.body === null) {
- throw new Error(
- `An error occurred while fetching the image at ${url}: Image body is null`
- );
- }
-
- body = imageRequest.body;
- } else {
- // This is a JSON file being uploaded, use the JSON content as body
- body = new Blob([JSON.stringify(jsonBody)], {
- type: "application/json",
- }).stream();
- }
+ const fileRow = {
+ name,
+ status: "UPLOADING" as const,
+ format: type,
+ size: 0,
+ uploaderProjectId: projectId,
+ isDeleted: false,
+ createdAt: new Date().toISOString(),
+ };
+ const onUploadError = createUploadErrorCleanup(existingFile.data, name);
+
+ const upsertFile = await context.postgrest.client
+ .from("File")
+ .upsert(fileRow, { onConflict: "name" });
+ if (upsertFile.error) {
+ throw upsertFile.error;
+ }
+
+ return onUploadError;
+};
+
+const createUploadErrorCleanup =
+ (previousFile: FileRow | null, name: string): UploadErrorCleanup =>
+ async (_name, context) => {
+ if (previousFile) {
+ const restoreFile = await context.postgrest.client
+ .from("File")
+ .update(previousFile)
+ .eq("name", name);
+ if (restoreFile.error) {
+ throw restoreFile.error;
}
+ return;
+ }
- const url = new URL(request.url);
+ const deleteFile = await context.postgrest.client
+ .from("File")
+ .delete()
+ .eq("name", name);
+ if (deleteFile.error) {
+ throw deleteFile.error;
+ }
+ };
- // Get file extension from filename
- const fileExtension = params.name.split(".").pop()?.toLowerCase();
+const createAssetUploadResponse = async ({
+ body,
+ context,
+ name,
+ assetInfoFallback,
+ onUploadError,
+}: {
+ body: ReadableStream<Uint8Array>;
+ context: Awaited<ReturnType<typeof createContext>>;
+ name: string;
+ assetInfoFallback: AssetInfoFallback;
+ onUploadError?: UploadErrorCleanup;
+}) => {
+ const asset = await uploadFile(
+ name,
+ body,
+ createAssetClient(),
+ context,
+ assetInfoFallback,
+ onUploadError
+ );
+ return json({ uploadedAssets: [asset] } satisfies AssetActionResponse, {
+ headers: privateNoStoreResponseHeaders,
+ });
+};
+
+const getBrowserUploadBody = async (
+ request: Request,
+ contentType: string | null
+) => {
+ let body = request.body;
+ if (body === null) {
+ throw new Error("Asset body is empty");
+ }
+
+ // Check if this is a request to download from URL (has url field in JSON body)
+ // vs uploading a JSON file directly (JSON file content in body)
+ if (contentType?.includes("application/json")) {
+ const jsonBody = await request.json();
+ const urlParse = urlBody.safeParse(jsonBody);
- // Use the file extension to determine the correct MIME type
- // This handles cases where browsers send legacy MIME types (e.g., application/font-woff instead of font/woff)
- const correctMimeType = fileExtension
- ? ALLOWED_FILE_TYPES[fileExtension as keyof typeof ALLOWED_FILE_TYPES]
- : contentType?.split(";")[0];
+ // Only fetch from URL if the body has a valid url field
+ if (urlParse.success) {
+ const { url } = urlParse.data;
+
+ const imageRequest = await fetch(url, {
+ method: "GET",
+ headers: {
+ Accept: RESIZABLE_IMAGE_MIME_TYPES.join(","),
+ },
+ });
- const contentTypeArr = correctMimeType?.split("/") ?? [];
+ if (false === imageRequest.ok) {
+ const error = await imageRequest.text();
+ const errors = `An error occurred while fetching the image at ${url}: ${error.slice(0, 500)}`;
+ throw new Error(errors);
+ }
- // Validate MIME type against allowed categories
- const mimeCategory = contentTypeArr[0];
- if (
- mimeCategory &&
- correctMimeType &&
- !isAllowedMimeCategory(mimeCategory)
- ) {
- throw new Error(`MIME type "${mimeCategory}/*" is not allowed`);
+ if (imageRequest.body === null) {
+ throw new Error(
+ `An error occurred while fetching the image at ${url}: Image body is null`
+ );
}
- const format =
- contentTypeArr[0] === "video" ? contentTypeArr[1] : undefined;
+ body = imageRequest.body;
+ } else {
+ // This is a JSON file being uploaded, use the JSON content as body
+ body = new Blob([JSON.stringify(jsonBody)], {
+ type: "application/json",
+ }).stream();
+ }
+ }
+
+ return body;
+};
+
+const getBrowserAssetFormat = ({
+ contentType,
+ name,
+}: {
+ contentType: string | null;
+ name: string;
+}) => {
+ // Get file extension from filename
+ const fileExtension = name.split(".").pop()?.toLowerCase();
+
+ // Use the file extension to determine the correct MIME type
+ // This handles cases where browsers send legacy MIME types (e.g., application/font-woff instead of font/woff)
+ const correctMimeType =
+ ALLOWED_FILE_TYPES[fileExtension as keyof typeof ALLOWED_FILE_TYPES] ??
+ contentType?.split(";")[0];
+
+ const contentTypeArr = correctMimeType?.split("/") ?? [];
- const width = url.searchParams.has("width")
- ? Number.parseInt(url.searchParams.get("width")!, 10)
- : undefined;
- const height = url.searchParams.has("height")
- ? Number.parseInt(url.searchParams.get("height")!, 10)
- : undefined;
+ // Validate MIME type against allowed categories
+ const mimeCategory = contentTypeArr[0];
+ if (mimeCategory && correctMimeType && !isAllowedMimeCategory(mimeCategory)) {
+ throw new Error(`MIME type "${mimeCategory}/*" is not allowed`);
+ }
+
+ return contentTypeArr[0] === "video" ? contentTypeArr[1] : undefined;
+};
- const assetInfoFallback =
- height !== undefined && width !== undefined && format !== undefined
- ? { width, height, format }
- : undefined;
+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 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 context = await createContext(request);
- const asset = await uploadFile(
- params.name,
- body,
- createAssetClient(),
+ await assertProjectBuildPermit({ ctx: context, projectId });
+ const onUploadError = await reserveAssetUpload({
context,
- assetInfoFallback
- );
- return json({ uploadedAssets: [asset] } satisfies AssetActionResponse, {
- headers: privateNoStoreResponseHeaders,
+ name: params.name,
+ projectId,
+ type: assetType,
+ });
+ return await createAssetUploadResponse({
+ body: request.body,
+ context,
+ name: params.name,
+ assetInfoFallback,
+ onUploadError,
});
}
+
+ 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 }
);
}
+};
- return json({ errors: "Method not allowed" } satisfies AssetActionResponse, {
- status: 405,
- headers: privateNoStoreResponseHeaders,
- });
+export const __testing__ = {
+ getAssetInfoFallback,
+ getBrowserAssetFormat,
+ getBrowserUploadBody,
+ parseAssetType,
};
diff --git a/apps/builder/app/routes/rest.resources-loader.ts b/apps/builder/app/routes/rest.resources-loader.ts
index c682001dfa..1d35d0bf49 100644
--- a/apps/builder/app/routes/rest.resources-loader.ts
+++ b/apps/builder/app/routes/rest.resources-loader.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
import { type ActionFunctionArgs, data, json } from "@remix-run/server-runtime";
-import { ResourceRequest } from "@webstudio-is/sdk";
+import { type ResourceRequest, resourceRequest } from "@webstudio-is/sdk";
import { isLocalResource, loadResource } from "@webstudio-is/sdk/runtime";
import { loader as siteMapLoader } from "../shared/$resources/sitemap.xml.server";
import { loader as currentDateLoader } from "../shared/$resources/current-date.server";
@@ -48,7 +48,7 @@ export const action = async ({ request }: ActionFunctionArgs) => {
const output = await Promise.all(
requestList.data.map(async (item) => {
- const resource = ResourceRequest.safeParse(item);
+ const resource = resourceRequest.safeParse(item);
if (resource.success === false) {
return [
getResourceKey(item as ResourceRequest),
diff --git a/apps/builder/app/routes/rest.staged-upload.tsx b/apps/builder/app/routes/rest.staged-upload.tsx
new file mode 100644
index 0000000000..873c70dcfa
--- /dev/null
+++ b/apps/builder/app/routes/rest.staged-upload.tsx
@@ -0,0 +1,13 @@
+import type {
+ ActionFunctionArgs,
+ LoaderFunctionArgs,
+} from "@remix-run/server-runtime";
+import { handleStagedUploadRequest } from "~/services/staged-upload.server";
+
+export const loader = async ({ request }: LoaderFunctionArgs) => {
+ return await handleStagedUploadRequest(request);
+};
+
+export const action = async ({ request }: ActionFunctionArgs) => {
+ return await handleStagedUploadRequest(request);
+};
diff --git a/apps/builder/app/routes/rest.staged-upload_.$id.tsx b/apps/builder/app/routes/rest.staged-upload_.$id.tsx
new file mode 100644
index 0000000000..ab3b99edac
--- /dev/null
+++ b/apps/builder/app/routes/rest.staged-upload_.$id.tsx
@@ -0,0 +1 @@
+export { action, loader } from "./rest.staged-upload";
diff --git a/apps/builder/app/services/build-router.server.test.ts b/apps/builder/app/services/build-router.server.test.ts
new file mode 100644
index 0000000000..42cc93a7bc
--- /dev/null
+++ b/apps/builder/app/services/build-router.server.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, test, vi } from "vitest";
+import { createPublishedProjectBundleFixture } from "@webstudio-is/protocol/fixtures";
+import { __testing__ } from "./build-router.server";
+
+const { createImportProjectBundleHandler } = __testing__;
+
+describe("build router project bundle import", () => {
+ test("imports staged project bundle data and removes the upload", async () => {
+ const data = createPublishedProjectBundleFixture();
+ const importPublishedProjectBundle = vi.fn().mockResolvedValue({
+ version: 2,
+ });
+ const readStagedUploadText = vi
+ .fn()
+ .mockResolvedValue(JSON.stringify(data));
+ const removeStagedUpload = vi.fn().mockResolvedValue(undefined);
+ const handler = createImportProjectBundleHandler({
+ importPublishedProjectBundle,
+ readStagedUploadText,
+ removeStagedUpload,
+ });
+ const ctx = { context: true } as never;
+
+ await expect(
+ handler({
+ ctx,
+ input: {
+ ignoreVersionCheck: true,
+ projectId: "project-id",
+ uploadId: "upload-id",
+ },
+ })
+ ).resolves.toEqual({ version: 2 });
+
+ expect(readStagedUploadText).toHaveBeenCalledWith({
+ projectId: "project-id",
+ uploadId: "upload-id",
+ });
+ expect(importPublishedProjectBundle).toHaveBeenCalledWith({
+ ctx,
+ data,
+ ignoreVersionCheck: true,
+ projectId: "project-id",
+ });
+ expect(removeStagedUpload).toHaveBeenCalledWith("upload-id");
+ });
+
+ test("removes staged upload when staged data is invalid", async () => {
+ const importPublishedProjectBundle = vi.fn();
+ const readStagedUploadText = vi.fn().mockResolvedValue("{");
+ const removeStagedUpload = vi.fn().mockResolvedValue(undefined);
+ const handler = createImportProjectBundleHandler({
+ importPublishedProjectBundle,
+ readStagedUploadText,
+ removeStagedUpload,
+ });
+
+ await expect(
+ handler({
+ ctx: {} as never,
+ input: {
+ projectId: "project-id",
+ uploadId: "upload-id",
+ },
+ })
+ ).rejects.toThrow();
+
+ expect(importPublishedProjectBundle).not.toHaveBeenCalled();
+ expect(removeStagedUpload).toHaveBeenCalledWith("upload-id");
+ });
+
+ test("keeps direct project bundle import unchanged", async () => {
+ const data = createPublishedProjectBundleFixture();
+ const importPublishedProjectBundle = vi.fn().mockResolvedValue({
+ version: 3,
+ });
+ const readStagedUploadText = vi.fn();
+ const removeStagedUpload = vi.fn();
+ const handler = createImportProjectBundleHandler({
+ importPublishedProjectBundle,
+ readStagedUploadText,
+ removeStagedUpload,
+ });
+ const ctx = { context: true } as never;
+
+ await expect(
+ handler({
+ ctx,
+ input: {
+ data,
+ projectId: "project-id",
+ },
+ })
+ ).resolves.toEqual({ version: 3 });
+
+ expect(importPublishedProjectBundle).toHaveBeenCalledWith({
+ ctx,
+ data,
+ ignoreVersionCheck: undefined,
+ projectId: "project-id",
+ });
+ expect(readStagedUploadText).not.toHaveBeenCalled();
+ expect(removeStagedUpload).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/builder/app/services/build-router.server.ts b/apps/builder/app/services/build-router.server.ts
index 6b8b0074a9..1f99d95d87 100644
--- a/apps/builder/app/services/build-router.server.ts
+++ b/apps/builder/app/services/build-router.server.ts
@@ -23,8 +23,9 @@ import { loadDevBuildByProjectId } from "@webstudio-is/project-build/index.serve
import { serializePages } from "@webstudio-is/project-migrations/pages";
import { loadAssetsByProject } from "@webstudio-is/asset-uploader/index.server";
import {
- checkProjectBuildPermissionInputSchema,
- importProjectBundleInputSchema,
+ checkProjectBuildPermissionInput,
+ importProjectBundleInput,
+ publishedProjectBundle,
} from "@webstudio-is/protocol";
import {
loadPublishedProjectBundleByBuildId,
@@ -33,7 +34,59 @@ import {
import {
assertProjectBuildPermit,
importPublishedProjectBundle,
-} from "./project-bundle-import.server";
+} from "./project-import.server";
+import {
+ readStagedUploadText,
+ removeStagedUpload,
+} from "./staged-upload.server";
+
+type ImportProjectBundleDependencies = {
+ importPublishedProjectBundle: typeof importPublishedProjectBundle;
+ readStagedUploadText: typeof readStagedUploadText;
+ removeStagedUpload: typeof removeStagedUpload;
+};
+
+const createImportProjectBundleHandler =
+ ({
+ importPublishedProjectBundle,
+ readStagedUploadText,
+ removeStagedUpload,
+ }: ImportProjectBundleDependencies) =>
+ async ({
+ ctx,
+ input,
+ }: {
+ ctx: AppContext;
+ input: z.infer<typeof importProjectBundleInput>;
+ }) => {
+ if (input.uploadId !== undefined) {
+ try {
+ const text = await readStagedUploadText({
+ projectId: input.projectId,
+ uploadId: input.uploadId,
+ });
+ return await importPublishedProjectBundle({
+ ctx,
+ data: publishedProjectBundle.parse(JSON.parse(text)),
+ ignoreVersionCheck: input.ignoreVersionCheck,
+ projectId: input.projectId,
+ });
+ } finally {
+ await removeStagedUpload(input.uploadId).catch(console.error);
+ }
+ }
+
+ if (input.data === undefined) {
+ throw new Error("Project bundle data is required.");
+ }
+
+ return await importPublishedProjectBundle({
+ ctx,
+ data: input.data,
+ ignoreVersionCheck: input.ignoreVersionCheck,
+ projectId: input.projectId,
+ });
+ };
const patchEntryInput = z.object({
seq: z.number().optional(),
@@ -152,22 +205,18 @@ export const buildRouter = router({
}),
checkProjectBuildPermission: procedure
- .input(checkProjectBuildPermissionInputSchema)
+ .input(checkProjectBuildPermissionInput)
.query(async ({ ctx, input }) => {
await assertProjectBuildPermit({ ctx, projectId: input.projectId });
}),
- importProjectBundle: procedure
- .input(importProjectBundleInputSchema)
- .mutation(async ({ ctx, input }) => {
- return await importPublishedProjectBundle({
- ctx,
- assetFiles: input.assetFiles,
- data: input.data,
- ignoreVersionCheck: input.ignoreVersionCheck,
- projectId: input.projectId,
- });
- }),
+ importProjectBundle: procedure.input(importProjectBundleInput).mutation(
+ createImportProjectBundleHandler({
+ importPublishedProjectBundle,
+ readStagedUploadText,
+ removeStagedUpload,
+ })
+ ),
createCollabToken: procedure
.input(
@@ -264,3 +313,7 @@ export const buildRouter = router({
}
}),
});
+
+export const __testing__ = {
+ createImportProjectBundleHandler,
+};
diff --git a/apps/builder/app/services/project-bundle-import.server.test.ts b/apps/builder/app/services/project-import.server.test.ts
similarity index 54%
rename from apps/builder/app/services/project-bundle-import.server.test.ts
rename to apps/builder/app/services/project-import.server.test.ts
index 87947200f4..433490fa10 100644
--- a/apps/builder/app/services/project-bundle-import.server.test.ts
+++ b/apps/builder/app/services/project-import.server.test.ts
@@ -1,4 +1,3 @@
-import { Buffer } from "node:buffer";
import { beforeEach, describe, expect, test, vi } from "vitest";
import {
createImageAssetFixture,
@@ -9,7 +8,17 @@ import { type PublishedProjectBundle } from "@webstudio-is/protocol";
import {
__testing__,
importPublishedProjectBundle,
-} from "./project-bundle-import.server";
+} from "./project-import.server";
+
+const {
+ assertBundleVersion,
+ assertImportedAssetFilesUploaded,
+ assertImportedAssetNames,
+ assertProjectBuildPermit,
+ createBuildImportUpdate,
+ createImportedAssetRows,
+ getImportedPreviewImageAssetId,
+} = __testing__;
const createData = (
overrides: Partial<PublishedProjectBundle> = {}
@@ -73,22 +82,30 @@ const createData = (
const createPostgrestClient = (
calls: string[],
- options: { existingFileNames?: string[] } = {}
+ options: {
+ existingFileNames?: string[];
+ fileFilters?: [string, string][];
+ } = {}
) => ({
from: (table: string) => {
if (table === "File") {
+ const selectFiles = {
+ eq: (column: string, value: string) => {
+ options.fileFilters?.push([column, value]);
+ return selectFiles;
+ },
+ in: async () => {
+ calls.push("files-select");
+ return {
+ data: (options.existingFileNames ?? []).map((name) => ({
+ name,
+ })),
+ error: undefined,
+ };
+ },
+ };
return {
- select: () => ({
- in: async () => {
- calls.push("files-select");
- return {
- data: (options.existingFileNames ?? []).map((name) => ({
- name,
- })),
- error: undefined,
- };
- },
- }),
+ select: () => selectFiles,
update: () => ({
in: async () => {
calls.push("files-restore");
@@ -148,28 +165,22 @@ const createPostgrestClient = (
});
describe("build import helpers", () => {
- const createAssetClient = vi.fn();
const hasProjectPermit = vi.fn();
const loadDevBuildByProjectId = vi.fn();
- const uploadImportedAssetFiles = vi.fn();
beforeEach(() => {
vi.clearAllMocks();
- createAssetClient.mockReturnValue({ uploadFile: vi.fn() });
hasProjectPermit.mockResolvedValue(true);
loadDevBuildByProjectId.mockResolvedValue({
id: "target-build",
projectId: "target-project",
version: 3,
});
- uploadImportedAssetFiles.mockResolvedValue(undefined);
});
test("rejects missing synced data version with compatibility message", () => {
expect(() =>
- __testing__.assertBundleVersion(
- {} as Pick<PublishedProjectBundle, "bundleVersion">
- )
+ assertBundleVersion({} as Pick<PublishedProjectBundle, "bundleVersion">)
).toThrow("Sync with a compatible API/CLI version");
});
@@ -177,7 +188,7 @@ describe("build import helpers", () => {
hasProjectPermit.mockResolvedValue(false);
await expect(
- __testing__.assertProjectBuildPermit({
+ assertProjectBuildPermit({
ctx: {} as never,
hasProjectPermit,
projectId: "target-project",
@@ -190,7 +201,7 @@ describe("build import helpers", () => {
});
test("serializes imported build data into compact build columns", () => {
- const update = __testing__.createBuildImportUpdate({
+ const update = createBuildImportUpdate({
data: createData(),
lastTransactionId: "import-tx",
updatedAt: "2024-02-01T00:00:00.000Z",
@@ -223,18 +234,16 @@ describe("build import helpers", () => {
});
test("uses imported home social image only when corresponding asset exists", () => {
- expect(__testing__.getImportedPreviewImageAssetId(createData())).toBe(
- "asset-1"
- );
+ expect(getImportedPreviewImageAssetId(createData())).toBe("asset-1");
expect(
- __testing__.getImportedPreviewImageAssetId(createData({ assets: [] }))
+ getImportedPreviewImageAssetId(createData({ assets: [] }))
).toBeNull();
});
test("remaps imported asset rows to destination project", () => {
expect(
- __testing__.createImportedAssetRows({
+ createImportedAssetRows({
assets: [
createData().assets[0],
{
@@ -264,55 +273,30 @@ describe("build import helpers", () => {
]);
});
- test("creates imported file rows from asset metadata", () => {
- expect(
- __testing__.createImportedFileRows({
- assets: [createData().assets[0]],
- projectId: "destination-project",
- })
- ).toEqual([
- {
- name: "image.png",
- status: "UPLOADED",
- format: "png",
- size: 100,
- meta: JSON.stringify({ width: 100, height: 100 }),
- createdAt: "2024-01-01T00:00:00.000Z",
- uploaderProjectId: "destination-project",
- isDeleted: false,
- },
- ]);
- });
-
- test("updates the build before replacing existing asset rows", async () => {
+ test("updates the build before replacing asset rows", async () => {
const calls: string[] = [];
- uploadImportedAssetFiles.mockImplementation(async () => {
- calls.push("asset-files-upload");
- });
await importPublishedProjectBundle(
{
- assetFiles: [{ name: "image.png", data: "aGVsbG8=" }],
ctx: {
postgrest: {
- client: createPostgrestClient(calls),
+ client: createPostgrestClient(calls, {
+ existingFileNames: ["image.png"],
+ }),
},
} as never,
data: createData(),
projectId: "target-project",
},
{
- createAssetClient,
hasProjectPermit,
loadDevBuildByProjectId,
- uploadImportedAssetFiles,
}
);
expect(calls).toEqual([
"files-select",
- "asset-files-upload",
- "files-insert",
+ "files-restore",
"build-update",
"project-preview-reset",
"assets-delete",
@@ -336,17 +320,15 @@ describe("build import helpers", () => {
projectId: "target-project",
},
{
- createAssetClient,
hasProjectPermit,
loadDevBuildByProjectId,
- uploadImportedAssetFiles,
}
);
expect(calls).toContain("build-update");
});
- test("rejects import with assets when asset files are missing", async () => {
+ test("rejects import with assets when uploaded file rows are missing", async () => {
await expect(
importPublishedProjectBundle(
{
@@ -359,83 +341,44 @@ describe("build import helpers", () => {
projectId: "target-project",
},
{
- createAssetClient,
hasProjectPermit,
loadDevBuildByProjectId,
- uploadImportedAssetFiles,
}
)
- ).rejects.toThrow("Imported asset files are required.");
- });
-
- test("uploads missing imported asset files before creating file rows", async () => {
- const calls: string[] = [];
- uploadImportedAssetFiles.mockImplementation(async () => {
- calls.push("asset-files-upload");
- });
-
- await importPublishedProjectBundle(
- {
- assetFiles: [{ name: "image.png", data: "aGVsbG8=" }],
- ctx: {
- postgrest: {
- client: createPostgrestClient(calls),
- },
- } as never,
- data: createData(),
- projectId: "target-project",
- },
- {
- createAssetClient,
- hasProjectPermit,
- loadDevBuildByProjectId,
- uploadImportedAssetFiles,
- }
- );
-
- expect(uploadImportedAssetFiles).toHaveBeenCalledWith({
- assetClient: expect.objectContaining({
- uploadFile: expect.any(Function),
- }),
- assetFiles: [{ name: "image.png", data: "aGVsbG8=" }],
- assets: createData().assets,
- });
- expect(calls.indexOf("files-select")).toBeLessThan(
- calls.indexOf("asset-files-upload")
- );
- expect(calls.indexOf("asset-files-upload")).toBeLessThan(
- calls.indexOf("files-insert")
- );
+ ).rejects.toThrow('Imported asset files are missing: ["image.png"]');
});
- test("loads existing imported file rows by global file name", async () => {
+ test("requires uploaded destination file rows for imported assets", async () => {
const calls: string[] = [];
+ const fileFilters: [string, string][] = [];
await expect(
- __testing__.loadExistingImportedAssetFileNames({
+ assertImportedAssetFilesUploaded({
assets: createData().assets,
ctx: {
postgrest: {
client: createPostgrestClient(calls, {
existingFileNames: ["image.png"],
+ fileFilters,
}),
},
} as never,
+ projectId: "target-project",
})
- ).resolves.toEqual(new Set(["image.png"]));
+ ).resolves.toBeUndefined();
- expect(calls).toEqual(["files-select"]);
+ expect(calls).toEqual(["files-select", "files-restore"]);
+ expect(fileFilters).toEqual([
+ ["status", "UPLOADED"],
+ ["uploaderProjectId", "target-project"],
+ ]);
});
- test("restores imported file rows by global file name", async () => {
+ test("makes imported file rows visible", async () => {
const calls: string[] = [];
- uploadImportedAssetFiles.mockImplementation(async () => {
- calls.push("asset-files-upload");
- });
await importPublishedProjectBundle(
{
- assetFiles: [{ name: "image.png", data: "aGVsbG8=" }],
ctx: {
postgrest: {
client: createPostgrestClient(calls, {
@@ -447,110 +390,17 @@ describe("build import helpers", () => {
projectId: "target-project",
},
{
- createAssetClient,
hasProjectPermit,
loadDevBuildByProjectId,
- uploadImportedAssetFiles,
}
);
expect(calls).toContain("files-restore");
});
- test("uploads imported asset files even when file rows already exist", async () => {
- const calls: string[] = [];
-
- await importPublishedProjectBundle(
- {
- assetFiles: [{ name: "image.png", data: "aGVsbG8=" }],
- ctx: {
- postgrest: {
- client: createPostgrestClient(calls, {
- existingFileNames: ["image.png"],
- }),
- },
- } as never,
- data: createData(),
- projectId: "target-project",
- },
- {
- createAssetClient,
- hasProjectPermit,
- loadDevBuildByProjectId,
- uploadImportedAssetFiles,
- }
- );
-
- expect(uploadImportedAssetFiles).toHaveBeenCalledWith({
- assetClient: expect.objectContaining({
- uploadFile: expect.any(Function),
- }),
- assetFiles: [{ name: "image.png", data: "aGVsbG8=" }],
- assets: createData().assets,
- });
- expect(calls).not.toContain("files-insert");
- });
-
- test("uploads imported asset file bytes through asset client", async () => {
- type AssetClient = ReturnType<
- typeof import("~/shared/asset-client").createAssetClient
- >;
- const uploadFile = vi.fn<AssetClient["uploadFile"]>(async () => ({
- format: "png",
- meta: { width: 100, height: 100 },
- size: 5,
- }));
-
- await __testing__.uploadImportedAssetFiles({
- assetClient: { uploadFile },
- assetFiles: [{ name: "image.png", data: "aGVsbG8=" }],
- assets: createData().assets,
- });
-
- expect(uploadFile).toHaveBeenCalledWith(
- "image.png",
- "image",
- expect.anything(),
- { width: 100, height: 100, format: "png" }
- );
- const stream = uploadFile.mock.calls[0][2] as AsyncIterable<Uint8Array>;
- const chunks: Uint8Array[] = [];
- for await (const chunk of stream) {
- chunks.push(chunk);
- }
- expect(Buffer.concat(chunks).toString("utf8")).toBe("hello");
- });
-
- test("rejects partial imported asset file payloads", () => {
- expect(() =>
- __testing__.assertAssetFilesMatchAssets({
- assetFiles: [],
- assets: createData().assets,
- })
- ).toThrow("Imported asset file is missing: image.png");
- });
-
- test("rejects missing imported asset file payload", () => {
- expect(() =>
- __testing__.assertAssetFilesMatchAssets({
- assetFiles: undefined,
- assets: createData().assets,
- })
- ).toThrow("Imported asset files are required.");
- });
-
- test("rejects imported asset files not present in data assets", () => {
- expect(() =>
- __testing__.assertAssetFilesMatchAssets({
- assetFiles: [{ name: "other.png", data: "aGVsbG8=" }],
- assets: createData().assets,
- })
- ).toThrow("Imported asset file does not exist in data assets: other.png");
- });
-
test("rejects imported asset names with path separators", () => {
expect(() =>
- __testing__.assertImportedAssetNames([
+ assertImportedAssetNames([
{ ...createData().assets[0], name: "../image.png" },
])
).toThrow("Imported asset name is invalid: ../image.png");
@@ -558,7 +408,7 @@ describe("build import helpers", () => {
test("rejects duplicated imported asset names", () => {
expect(() =>
- __testing__.assertImportedAssetNames([
+ assertImportedAssetNames([
createData().assets[0],
{ ...createData().assets[0], id: "asset-2" },
])
@@ -567,7 +417,7 @@ describe("build import helpers", () => {
test("rejects duplicated imported asset ids", () => {
expect(() =>
- __testing__.assertImportedAssetNames([
+ assertImportedAssetNames([
createData().assets[0],
{ ...createData().assets[0], name: "other.png" },
])
@@ -576,30 +426,7 @@ describe("build import helpers", () => {
test("rejects empty imported asset ids", () => {
expect(() =>
- __testing__.assertImportedAssetNames([
- { ...createData().assets[0], id: "" },
- ])
+ assertImportedAssetNames([{ ...createData().assets[0], id: "" }])
).toThrow("Imported asset id is invalid.");
});
-
- test("rejects duplicated imported asset file payloads", () => {
- expect(() =>
- __testing__.assertAssetFilesMatchAssets({
- assetFiles: [
- { name: "image.png", data: "aGVsbG8=" },
- { name: "image.png", data: "aGVsbG8=" },
- ],
- assets: createData().assets,
- })
- ).toThrow("Imported asset file is duplicated: image.png");
- });
-
- test("rejects invalid imported asset file data", () => {
- expect(() =>
- __testing__.assertAssetFilesMatchAssets({
- assetFiles: [{ name: "image.png", data: "not base64" }],
- assets: createData().assets,
- })
- ).toThrow("Imported asset file data is invalid: image.png");
- });
});
diff --git a/apps/builder/app/services/project-bundle-import.server.ts b/apps/builder/app/services/project-import.server.ts
similarity index 65%
rename from apps/builder/app/services/project-bundle-import.server.ts
rename to apps/builder/app/services/project-import.server.ts
index 952414fc31..5c76f4b8b2 100644
--- a/apps/builder/app/services/project-bundle-import.server.ts
+++ b/apps/builder/app/services/project-import.server.ts
@@ -1,4 +1,3 @@
-import { Buffer } from "node:buffer";
import {
AuthorizationError,
authorizeProject,
@@ -13,14 +12,12 @@ import { serializeStyles } from "@webstudio-is/project-build/styles.server";
import { serializeStyleSourceSelections } from "@webstudio-is/project-build/style-source-selections.server";
import {
isAssetFileName,
- isAssetFileDataString,
+ getMissingImportedAssetFilesMessage,
getBundleVersionMismatchMessage,
bundleVersion,
- type AssetFileData,
type PublishedProjectBundle,
type ProjectBundle,
} from "@webstudio-is/protocol";
-import { createAssetClient } from "~/shared/asset-client";
import {
getHomePage,
type Asset,
@@ -103,39 +100,6 @@ const getImportedPreviewImageAssetId = (data: ProjectBundle) => {
return importedAssetIds.has(socialImageAssetId) ? socialImageAssetId : null;
};
-const createImportedFileRows = ({
- assets,
- projectId,
-}: {
- assets: Asset[];
- projectId: string;
-}) =>
- assets.map((asset) => ({
- name: asset.name,
- status: "UPLOADED" as const,
- format: asset.format,
- size: asset.size,
- meta: JSON.stringify(asset.meta),
- createdAt: asset.createdAt,
- uploaderProjectId: projectId,
- isDeleted: false,
- }));
-
-const toByteStream = async function* (data: Uint8Array) {
- yield data;
-};
-
-const getAssetInfoFallback = (asset: Asset) => {
- if (asset.type !== "image") {
- return;
- }
- return {
- width: asset.meta.width,
- height: asset.meta.height,
- format: asset.format,
- };
-};
-
const assertImportedAssetNames = (assets: Asset[]) => {
const assetIds = new Set<string>();
const assetNames = new Set<string>();
@@ -158,83 +122,28 @@ const assertImportedAssetNames = (assets: Asset[]) => {
}
};
-const assertAssetFilesMatchAssets = ({
- assetFiles,
- assets,
-}: {
- assetFiles: AssetFileData[] | undefined;
- assets: Asset[];
-}) => {
+const assertImportedAssets = (assets: Asset[]) => {
assertImportedAssetNames(assets);
-
- if (assetFiles === undefined) {
- if (assets.length > 0) {
- throw new Error("Imported asset files are required.");
- }
- return;
- }
-
- const assetNames = new Set(assets.map((asset) => asset.name));
- const assetFilesByName = new Map<string, AssetFileData>();
-
- for (const assetFile of assetFiles) {
- if (isAssetFileDataString(assetFile.data) === false) {
- throw new Error(`Imported asset file data is invalid: ${assetFile.name}`);
- }
- if (assetFilesByName.has(assetFile.name)) {
- throw new Error(`Imported asset file is duplicated: ${assetFile.name}`);
- }
- if (assetNames.has(assetFile.name) === false) {
- throw new Error(
- `Imported asset file does not exist in data assets: ${assetFile.name}`
- );
- }
- assetFilesByName.set(assetFile.name, assetFile);
- }
-
- for (const assetName of assetNames) {
- if (assetFilesByName.has(assetName) === false) {
- throw new Error(`Imported asset file is missing: ${assetName}`);
- }
- }
};
-const uploadImportedAssetFiles = async ({
- assetClient,
- assetFiles,
- assets,
-}: {
- assetClient: ReturnType<typeof createAssetClient>;
- assetFiles: AssetFileData[];
- assets: Asset[];
-}) => {
- const assetsByName = new Map(assets.map((asset) => [asset.name, asset]));
-
- for (const assetFile of assetFiles) {
- const asset = assetsByName.get(assetFile.name)!;
- await assetClient.uploadFile(
- asset.name,
- asset.type,
- toByteStream(Buffer.from(assetFile.data, "base64")),
- getAssetInfoFallback(asset)
- );
- }
-};
-
-const loadExistingImportedAssetFileNames = async ({
+const assertImportedAssetFilesUploaded = async ({
assets,
ctx,
+ projectId,
}: {
assets: Asset[];
ctx: AppContext;
+ projectId: string;
}) => {
if (assets.length === 0) {
- return new Set<string>();
+ return;
}
const files = await ctx.postgrest.client
.from("File")
.select("name")
+ .eq("status", "UPLOADED")
+ .eq("uploaderProjectId", projectId)
.in(
"name",
assets.map((asset) => asset.name)
@@ -244,51 +153,29 @@ const loadExistingImportedAssetFileNames = async ({
throw files.error;
}
- return new Set((files.data ?? []).map((file) => file.name));
-};
-
-const ensureImportedAssetFiles = async ({
- assets,
- ctx,
- existingFileNames,
- projectId,
-}: {
- assets: Asset[];
- ctx: AppContext;
- existingFileNames: Set<string>;
- projectId: string;
-}) => {
- if (assets.length === 0) {
- return;
- }
-
+ const existingFileNames = new Set(
+ (files.data ?? []).map((file) => file.name)
+ );
const missingAssets = assets.filter(
(asset) => existingFileNames.has(asset.name) === false
);
+ if (missingAssets.length > 0) {
+ throw new Error(
+ getMissingImportedAssetFilesMessage(
+ missingAssets.map((asset) => asset.name)
+ )
+ );
+ }
if (existingFileNames.size > 0) {
- const restoreFiles = await ctx.postgrest.client
+ const visibleFiles = await ctx.postgrest.client
.from("File")
.update({ isDeleted: false })
.in("name", Array.from(existingFileNames));
- if (restoreFiles.error) {
- throw restoreFiles.error;
+ if (visibleFiles.error) {
+ throw visibleFiles.error;
}
}
-
- if (missingAssets.length === 0) {
- return;
- }
-
- const insertedFiles = await ctx.postgrest.client.from("File").insert(
- createImportedFileRows({
- assets: missingAssets,
- projectId,
- })
- );
- if (insertedFiles.error) {
- throw insertedFiles.error;
- }
};
const replaceProjectAssetRows = async ({
@@ -363,23 +250,19 @@ const updateProjectPreviewImage = async ({
export const importPublishedProjectBundle = async (
{
- assetFiles,
ctx,
data,
ignoreVersionCheck = false,
projectId,
}: {
- assetFiles?: AssetFileData[];
ctx: AppContext;
data: PublishedProjectBundle;
ignoreVersionCheck?: boolean;
projectId: string;
},
dependencies = {
- createAssetClient,
hasProjectPermit: authorizeProject.hasProjectPermit,
loadDevBuildByProjectId,
- uploadImportedAssetFiles,
}
) => {
if (ignoreVersionCheck === false) {
@@ -395,25 +278,11 @@ export const importPublishedProjectBundle = async (
const build = await dependencies.loadDevBuildByProjectId(ctx, projectId);
const nextVersion = build.version + 1;
- assertAssetFilesMatchAssets({ assetFiles, assets: data.assets });
-
- const existingFileNames = await loadExistingImportedAssetFileNames({
- assets: data.assets,
- ctx,
- });
-
- if (assetFiles !== undefined && assetFiles.length > 0) {
- await dependencies.uploadImportedAssetFiles({
- assetClient: dependencies.createAssetClient(),
- assetFiles,
- assets: data.assets,
- });
- }
+ assertImportedAssets(data.assets);
- await ensureImportedAssetFiles({
+ await assertImportedAssetFilesUploaded({
assets: data.assets,
ctx,
- existingFileNames,
projectId,
});
@@ -455,12 +324,10 @@ export const importPublishedProjectBundle = async (
export const __testing__ = {
assertProjectBuildPermit,
assertBundleVersion,
- createImportedFileRows,
createImportedAssetRows,
createBuildImportUpdate,
getImportedPreviewImageAssetId,
assertImportedAssetNames,
- assertAssetFilesMatchAssets,
- loadExistingImportedAssetFileNames,
- uploadImportedAssetFiles,
+ assertImportedAssets,
+ assertImportedAssetFilesUploaded,
};
diff --git a/apps/builder/app/services/staged-upload.server.test.ts b/apps/builder/app/services/staged-upload.server.test.ts
new file mode 100644
index 0000000000..5bbc265ab4
--- /dev/null
+++ b/apps/builder/app/services/staged-upload.server.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, test } from "vitest";
+import {
+ maxProjectBundleSize,
+ stagedUploadPath,
+ stagedUploadProjectIdHeader,
+} from "@webstudio-is/protocol";
+import { __testing__ } from "./staged-upload.server";
+
+const { createStagedUploadServer, createStagedUploadStore } = __testing__;
+
+const createRequest = (headers: Record<string, string> = {}) =>
+ new Request(new URL(stagedUploadPath, "https://example.com"), { headers });
+
+const createServer = () => {
+ const calls: string[] = [];
+ const server = createStagedUploadServer({
+ datastore: {} as never,
+ createContext: async () => ({ context: true }) as never,
+ assertProjectBuildPermit: async ({ ctx, projectId }) => {
+ calls.push(`${projectId}:${JSON.stringify(ctx)}`);
+ },
+ });
+ return { calls, server };
+};
+
+describe("staged upload server", () => {
+ test("uses project bundle upload limits", () => {
+ const { server } = createServer();
+
+ expect(server.options.path).toBe(stagedUploadPath);
+ expect(server.options.maxSize).toBe(maxProjectBundleSize);
+ expect(server.options.allowedHeaders).toContain(
+ stagedUploadProjectIdHeader
+ );
+ });
+
+ test("requires auth token before accepting upload requests", async () => {
+ const { server } = createServer();
+
+ await expect(
+ server.options.onIncomingRequest?.(
+ createRequest({ [stagedUploadProjectIdHeader]: "project" }) as never,
+ ""
+ )
+ ).rejects.toThrow("Auth token is required.");
+ });
+
+ test("rejects empty upload authorization headers", async () => {
+ const { server } = createServer();
+
+ await expect(
+ server.options.onIncomingRequest?.(
+ createRequest({
+ "x-auth-token": " ",
+ [stagedUploadProjectIdHeader]: "project",
+ }) as never,
+ ""
+ )
+ ).rejects.toThrow("Auth token is required.");
+
+ await expect(
+ server.options.onIncomingRequest?.(
+ createRequest({
+ "x-auth-token": "token",
+ [stagedUploadProjectIdHeader]: " ",
+ }) as never,
+ ""
+ )
+ ).rejects.toThrow("Project id is required.");
+ });
+
+ test("checks build permission for upload requests", async () => {
+ const { calls, server } = createServer();
+
+ await server.options.onIncomingRequest?.(
+ createRequest({
+ "x-auth-token": "token",
+ [stagedUploadProjectIdHeader]: "project",
+ }) as never,
+ ""
+ );
+
+ expect(calls).toEqual(['project:{"context":true}']);
+ });
+
+ test("requires upload metadata to match the request project", async () => {
+ const { server } = createServer();
+
+ await expect(
+ server.options.onUploadCreate?.(
+ createRequest({
+ "x-auth-token": "token",
+ [stagedUploadProjectIdHeader]: "project",
+ }) as never,
+ {
+ metadata: { projectId: "other-project" },
+ } as never
+ )
+ ).rejects.toThrow("Upload project id does not match request project id.");
+ });
+
+ test("rejects partial object storage configuration", () => {
+ expect(() =>
+ createStagedUploadStore({
+ S3_ACCESS_KEY_ID: "",
+ S3_BUCKET: undefined,
+ S3_ENDPOINT: "https://example.com",
+ S3_REGION: undefined,
+ S3_SECRET_ACCESS_KEY: undefined,
+ })
+ ).toThrow(
+ "Staged upload storage is missing required environment variables: S3_REGION, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_BUCKET"
+ );
+ });
+
+ test("disables object tags for S3-compatible upload storage", () => {
+ const store = createStagedUploadStore({
+ S3_ACCESS_KEY_ID: "access-key",
+ S3_BUCKET: "bucket",
+ S3_ENDPOINT: "https://example.com",
+ S3_REGION: "auto",
+ S3_SECRET_ACCESS_KEY: "secret-key",
+ });
+
+ expect(store).toHaveProperty("useTags", false);
+ });
+});
diff --git a/apps/builder/app/services/staged-upload.server.ts b/apps/builder/app/services/staged-upload.server.ts
new file mode 100644
index 0000000000..40fdf0a08b
--- /dev/null
+++ b/apps/builder/app/services/staged-upload.server.ts
@@ -0,0 +1,179 @@
+import * as path from "node:path";
+import { FileStore } from "@tus/file-store";
+import { S3Store } from "@tus/s3-store";
+import { Server, type DataStore, type Upload } from "@tus/server";
+import {
+ maxProjectBundleSize,
+ stagedUploadPath,
+ stagedUploadProjectIdHeader,
+} from "@webstudio-is/protocol";
+import env from "~/env/env.server";
+import { createContext } from "~/shared/context.server";
+import { assertProjectBuildPermit as defaultAssertProjectBuildPermit } from "./project-import.server";
+
+const stagedUploadExpiration = 60 * 60 * 1000;
+const authTokenHeader = "x-auth-token";
+const localUploadDirectory = path.join(process.cwd(), ".webstudio", "uploads");
+const s3Env = [
+ "S3_ENDPOINT",
+ "S3_REGION",
+ "S3_ACCESS_KEY_ID",
+ "S3_SECRET_ACCESS_KEY",
+ "S3_BUCKET",
+] as const;
+type StagedUploadStorageEnv = Pick<typeof env, (typeof s3Env)[number]>;
+
+type ReadableDataStore = DataStore & {
+ read(
+ uploadId: string
+ ): NodeJS.ReadableStream | Promise<NodeJS.ReadableStream>;
+};
+
+type StagedUploadServerDependencies = {
+ assertProjectBuildPermit?: typeof defaultAssertProjectBuildPermit;
+ createContext?: typeof createContext;
+ datastore?: DataStore;
+};
+
+const createStagedUploadStore = (
+ environment: StagedUploadStorageEnv = env
+): DataStore => {
+ const getEnvValue = (name: (typeof s3Env)[number]) => {
+ const value = environment[name]?.trim();
+ return value === "" ? undefined : value;
+ };
+ const isS3Configured = s3Env.some((name) => getEnvValue(name) !== undefined);
+ if (isS3Configured) {
+ const missingEnv = s3Env.filter((name) => getEnvValue(name) === undefined);
+ if (missingEnv.length > 0) {
+ throw new Error(
+ `Staged upload storage is missing required environment variables: ${missingEnv.join(", ")}`
+ );
+ }
+ const endpoint = getEnvValue("S3_ENDPOINT");
+ const region = getEnvValue("S3_REGION");
+ const accessKeyId = getEnvValue("S3_ACCESS_KEY_ID");
+ const secretAccessKey = getEnvValue("S3_SECRET_ACCESS_KEY");
+ const bucket = getEnvValue("S3_BUCKET");
+ if (
+ endpoint === undefined ||
+ region === undefined ||
+ accessKeyId === undefined ||
+ secretAccessKey === undefined ||
+ bucket === undefined
+ ) {
+ throw new Error("Staged upload storage is not configured.");
+ }
+ return new S3Store({
+ expirationPeriodInMilliseconds: stagedUploadExpiration,
+ partSize: 8 * 1024 * 1024,
+ useTags: false,
+ s3ClientConfig: {
+ endpoint,
+ region,
+ bucket,
+ credentials: {
+ accessKeyId,
+ secretAccessKey,
+ },
+ },
+ });
+ }
+
+ return new FileStore({
+ directory: localUploadDirectory,
+ expirationPeriodInMilliseconds: stagedUploadExpiration,
+ });
+};
+
+const assertUploadProject = (upload: Upload, projectId: string) => {
+ if (upload.metadata?.projectId !== projectId) {
+ throw new Error("Staged upload does not belong to this project.");
+ }
+};
+
+const getRequiredHeader = (request: Request, name: string, label: string) => {
+ const value = request.headers.get(name)?.trim();
+ if (value === undefined || value === "") {
+ throw new Error(`${label} is required.`);
+ }
+ return value;
+};
+
+const getUploadProjectId = (request: Request) =>
+ getRequiredHeader(request, stagedUploadProjectIdHeader, "Project id");
+
+const assertAuthorizedUploadRequest = async (
+ request: Request,
+ {
+ assertProjectBuildPermit = defaultAssertProjectBuildPermit,
+ createContext: createRequestContext = createContext,
+ }: StagedUploadServerDependencies
+) => {
+ getRequiredHeader(request, authTokenHeader, "Auth token");
+
+ const projectId = getUploadProjectId(request);
+ const context = await createRequestContext(request);
+ await assertProjectBuildPermit({ ctx: context, projectId });
+};
+
+const createStagedUploadServer = (
+ dependencies: StagedUploadServerDependencies = {}
+) =>
+ new Server({
+ path: stagedUploadPath,
+ datastore: dependencies.datastore ?? createStagedUploadStore(),
+ maxSize: maxProjectBundleSize,
+ relativeLocation: false,
+ respectForwardedHeaders: true,
+ allowedHeaders: [authTokenHeader, stagedUploadProjectIdHeader],
+ async onIncomingRequest(request) {
+ await assertAuthorizedUploadRequest(
+ request as unknown as Request,
+ dependencies
+ );
+ },
+ async onUploadCreate(request, upload) {
+ const projectId = getUploadProjectId(request as unknown as Request);
+ if (upload.metadata?.projectId !== projectId) {
+ throw new Error("Upload project id does not match request project id.");
+ }
+ return { metadata: { ...upload.metadata, projectId } };
+ },
+ });
+
+const stagedUploadServer = createStagedUploadServer();
+
+export const handleStagedUploadRequest = async (request: Request) => {
+ return await stagedUploadServer.handleWeb(request);
+};
+
+const readText = async (stream: NodeJS.ReadableStream) => {
+ const chunks: Buffer[] = [];
+ for await (const chunk of stream) {
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
+ }
+ return Buffer.concat(chunks).toString("utf8");
+};
+
+export const readStagedUploadText = async ({
+ projectId,
+ uploadId,
+}: {
+ projectId: string;
+ uploadId: string;
+}) => {
+ const datastore = stagedUploadServer.datastore as ReadableDataStore;
+ const upload = await datastore.getUpload(uploadId);
+ assertUploadProject(upload, projectId);
+ return await readText(await datastore.read(uploadId));
+};
+
+export const removeStagedUpload = async (uploadId: string) => {
+ await stagedUploadServer.datastore.remove(uploadId);
+};
+
+export const __testing__ = {
+ createStagedUploadStore,
+ createStagedUploadServer,
+};
diff --git a/apps/builder/app/services/token.server.ts b/apps/builder/app/services/token.server.ts
index 1729d0729b..560e33988a 100644
--- a/apps/builder/app/services/token.server.ts
+++ b/apps/builder/app/services/token.server.ts
@@ -72,13 +72,13 @@ export const verifyChallenge = async (
return base64Hash === codeChallenge;
};
-const CodeTokenPayload = z.object({
+const codeTokenPayload = z.object({
userId: z.string(),
projectId: z.string(),
codeChallenge: z.string(),
});
-type CodeTokenPayload = z.infer<typeof CodeTokenPayload>;
+type CodeTokenPayload = z.infer<typeof codeTokenPayload>;
/**
* JWT is used because it includes a signature check and expiration,
@@ -127,17 +127,17 @@ export const readCodeToken = async (
const token = await jwt.decode(jwtToken);
- const parsedToken = CodeTokenPayload.parse(token.payload);
+ const parsedToken = codeTokenPayload.parse(token.payload);
return parsedToken;
};
-const AccessTokenPayload = z.object({
+const accessTokenPayload = z.object({
userId: z.string(),
projectId: z.string(),
});
-type AccessTokenPayload = z.infer<typeof AccessTokenPayload>;
+type AccessTokenPayload = z.infer<typeof accessTokenPayload>;
/**
* JWT is used because it includes a signature check and expiration,
@@ -172,7 +172,7 @@ export const readAccessToken = async (
const token = jwt.decode(accessToken);
- const parsedToken = AccessTokenPayload.parse(token.payload);
+ const parsedToken = accessTokenPayload.parse(token.payload);
return parsedToken;
};
diff --git a/apps/builder/app/services/user-router.server.ts b/apps/builder/app/services/user-router.server.ts
index 2fca6e99c2..d680232646 100644
--- a/apps/builder/app/services/user-router.server.ts
+++ b/apps/builder/app/services/user-router.server.ts
@@ -2,12 +2,12 @@ import { z } from "zod";
import { procedure, router } from "@webstudio-is/trpc-interface/index.server";
import {
updateUserProjectsTags,
- userProjectTagSchema,
+ userProjectTag,
} from "../shared/db/user.server";
export const userRouter = router({
updateProjectsTags: procedure
- .input(z.object({ tags: z.array(userProjectTagSchema) }))
+ .input(z.object({ tags: z.array(userProjectTag) }))
.mutation(async ({ input, ctx }) => {
return await updateUserProjectsTags(input, ctx);
}),
diff --git a/apps/builder/app/services/workspace-router.server.ts b/apps/builder/app/services/workspace-router.server.ts
index 79120286df..ce2e7743e1 100644
--- a/apps/builder/app/services/workspace-router.server.ts
+++ b/apps/builder/app/services/workspace-router.server.ts
@@ -10,8 +10,8 @@ import { roles } from "@webstudio-is/trpc-interface/authorize";
import { getExtraPaidSeats } from "@webstudio-is/plans/index.server";
import env from "~/env/env.server";
-const Name = z.string().min(2).max(100);
-const Relation = z.enum(roles);
+const name = z.string().min(2).max(100);
+const relation = z.enum(roles);
/**
* Tells the payment worker to count members and adjust Stripe seats.
@@ -54,7 +54,7 @@ const syncSeats = async (workspaceId: string, delta = 0): Promise<void> => {
export const workspaceRouter = router({
create: procedure
- .input(z.object({ name: Name }))
+ .input(z.object({ name: name }))
.mutation(async ({ input, ctx }) => {
try {
const workspace = await workspaceApi.create(
@@ -68,7 +68,7 @@ export const workspaceRouter = router({
}),
rename: procedure
- .input(z.object({ workspaceId: z.string(), name: Name }))
+ .input(z.object({ workspaceId: z.string(), name: name }))
.mutation(async ({ input, ctx }) => {
try {
const workspace = await workspaceApi.rename(input, ctx);
@@ -114,7 +114,7 @@ export const workspaceRouter = router({
z.object({
workspaceId: z.string(),
email: z.string().email(),
- relation: Relation,
+ relation: relation,
})
)
.mutation(async ({ input, ctx }) => {
@@ -230,7 +230,7 @@ export const workspaceRouter = router({
z.object({
workspaceId: z.string(),
memberUserId: z.string(),
- relation: Relation,
+ relation: relation,
})
)
.mutation(async ({ input, ctx }) => {
diff --git a/apps/builder/app/shared/asset-client.ts b/apps/builder/app/shared/asset-client.ts
index 50d50abf44..0f00154d08 100644
--- a/apps/builder/app/shared/asset-client.ts
+++ b/apps/builder/app/shared/asset-client.ts
@@ -1,5 +1,5 @@
import * as path from "node:path";
-import { MaxSize } from "@webstudio-is/asset-uploader";
+import { maxSize } from "@webstudio-is/asset-uploader";
import {
createFsClient,
createS3Client,
@@ -9,7 +9,7 @@ import env from "~/env/env.server";
export const fileUploadPath = "public/cgi/asset";
export const createAssetClient = () => {
- const maxUploadSize = MaxSize.parse(env.MAX_UPLOAD_SIZE);
+ const maxUploadSize = maxSize.parse(env.MAX_UPLOAD_SIZE);
if (
env.S3_ENDPOINT !== undefined &&
env.S3_REGION !== undefined &&
diff --git a/apps/builder/app/shared/clone-project.tsx b/apps/builder/app/shared/clone-project.tsx
index bde27f9748..17c9bcec78 100644
--- a/apps/builder/app/shared/clone-project.tsx
+++ b/apps/builder/app/shared/clone-project.tsx
@@ -14,7 +14,7 @@ import {
DialogActions,
toast,
} from "@webstudio-is/design-system";
-import { Title, type Project } from "@webstudio-is/project";
+import { projectTitle, type Project } from "@webstudio-is/project";
import { nativeClient } from "./trpc/trpc-client";
import { useEffectEvent } from "./hook-utils/effect-event";
@@ -31,7 +31,7 @@ const useCloneProjectWithDialog = ({
const [errors, setErrors] = useState<string>();
const handleSubmit = async ({ title }: { title: string }) => {
- const parsed = Title.safeParse(title);
+ const parsed = projectTitle.safeParse(title);
const errors =
"error" in parsed
? parsed.error?.issues.map((issue) => issue.message).join("\n")
@@ -102,7 +102,7 @@ const CloneProjectView = ({
}}
gap="1"
>
- <Label>Project title</Label>
+ <Label>Project Title</Label>
<InputField
name="title"
defaultValue={title}
diff --git a/apps/builder/app/shared/context.server.ts b/apps/builder/app/shared/context.server.ts
index 6765d9e531..94aaeb24a8 100644
--- a/apps/builder/app/shared/context.server.ts
+++ b/apps/builder/app/shared/context.server.ts
@@ -17,7 +17,7 @@ import type { BloomFilter } from "~/services/bloom-filter.server";
import { isBuilder, isCanvas } from "./router-utils";
import { parseBuilderUrl } from "@webstudio-is/http-client";
import {
- ApiClient,
+ apiClient,
apiClientHeader,
apiClientVersionHeader,
} from "@webstudio-is/trpc-interface/api-compatibility";
@@ -186,7 +186,7 @@ const createTrpcCache = () => {
};
const createApiClientContext = (request: Request): AppContext["apiClient"] => {
- const client = ApiClient.safeParse(request.headers.get(apiClientHeader));
+ const client = apiClient.safeParse(request.headers.get(apiClientHeader));
if (client.success === false) {
return {
type: "unknown",
diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.ts
index 2a5d97ee0f..30a8af1270 100644
--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts
@@ -17,9 +17,9 @@ import { shallowEqual } from "shallow-equal";
import { z } from "zod";
import { toast } from "@webstudio-is/design-system";
import {
- Instance,
- Instances,
- WebstudioFragment,
+ type Instance,
+ type Instances,
+ webstudioFragment,
findTreeInstanceIdsExcludingSlotDescendants,
isComponentDetachable,
portalComponent,
@@ -38,11 +38,11 @@ import { breakpointPasteLimitWarning } from "../breakpoints";
const version = "@webstudio/instance/v0.1";
-const InstanceData = WebstudioFragment.extend({
+const instanceData = webstudioFragment.extend({
instanceSelector: z.array(z.string()),
});
-type InstanceData = z.infer<typeof InstanceData>;
+type InstanceData = z.infer<typeof instanceData>;
const getTreeData = (instanceSelector: InstanceSelector) => {
const instances = $instances.get();
@@ -70,11 +70,11 @@ const stringify = (data: InstanceData) => {
return JSON.stringify({ [version]: data });
};
-const ClipboardData = z.object({ [version]: InstanceData });
+const clipboard = z.object({ [version]: instanceData });
const parse = (clipboardData: string): InstanceData | undefined => {
try {
- const data = ClipboardData.parse(JSON.parse(clipboardData));
+ const data = clipboard.parse(JSON.parse(clipboardData));
return data[version];
} catch {
return;
diff --git a/apps/builder/app/shared/copy-paste/plugin-page.ts b/apps/builder/app/shared/copy-paste/plugin-page.ts
index 59a4526edc..83d9c0584b 100644
--- a/apps/builder/app/shared/copy-paste/plugin-page.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-page.ts
@@ -3,7 +3,8 @@ import { updateWebstudioData } from "../instance-utils/data";
import { z } from "zod";
import { toast } from "@webstudio-is/design-system";
import {
- WebstudioFragment,
+ type WebstudioFragment,
+ webstudioFragment,
findPageByIdOrPath,
findParentFolderByChildId,
type Folder,
@@ -40,33 +41,33 @@ type FolderData = Omit<FolderCopyData, "children"> & {
children: Array<PageData | FolderData>;
};
-const PageData: z.ZodType<PageData> = z.object({
+const pageData: z.ZodType<PageData> = z.object({
type: z.literal("page"),
page: z.custom<Page>(),
- rootFragment: WebstudioFragment,
- bodyFragment: WebstudioFragment,
+ rootFragment: webstudioFragment,
+ bodyFragment: webstudioFragment,
});
-const TemplateData: z.ZodType<TemplateData> = z.object({
+const templateData: z.ZodType<TemplateData> = z.object({
type: z.literal("template"),
template: z.custom<PageTemplate>(),
- rootFragment: WebstudioFragment,
- bodyFragment: WebstudioFragment,
+ rootFragment: webstudioFragment,
+ bodyFragment: webstudioFragment,
});
-const FolderData: z.ZodType<FolderData> = z.lazy(() =>
+const folderData: z.ZodType<FolderData> = z.lazy(() =>
z.object({
type: z.literal("folder"),
folder: z.custom<Folder>(),
- children: z.array(z.union([PageData, FolderData])),
+ children: z.array(z.union([pageData, folderData])),
})
);
-const ClipboardItem = z.union([PageData, TemplateData, FolderData]);
+const clipboardItem = z.union([pageData, templateData, folderData]);
-type ClipboardItem = z.infer<typeof ClipboardItem>;
+type ClipboardItem = z.infer<typeof clipboardItem>;
-const ClipboardData = z.object({ [version]: ClipboardItem });
+const clipboard = z.object({ [version]: clipboardItem });
const stringify = (data: ClipboardItem) => {
return JSON.stringify({ [version]: data });
@@ -74,7 +75,7 @@ const stringify = (data: ClipboardItem) => {
const parse = (clipboardData: string): ClipboardItem | undefined => {
try {
- const data = ClipboardData.parse(JSON.parse(clipboardData));
+ const data = clipboard.parse(JSON.parse(clipboardData));
return data[version];
} catch {
return;
diff --git a/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx
index 6e7d860d96..428c1cdc5b 100644
--- a/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx
+++ b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx
@@ -17,7 +17,7 @@ import { $registeredComponentMetas } from "../../nano-states";
import { $breakpoints } from "~/shared/sync/data-stores";
import { $project, $styleSources, $styles } from "~/shared/sync/data-stores";
import invariant from "tiny-invariant";
-import { WfData } from "./schema";
+import { wfData } from "./schema";
const { toWebstudioFragment } = __testing__;
@@ -3025,7 +3025,7 @@ describe("Styles", () => {
});
test("background images", async () => {
- const input = WfData.parse({
+ const input = wfData.parse({
type: "@webflow/XscpData",
payload: {
nodes: [
@@ -3183,7 +3183,7 @@ describe("Styles", () => {
});
test("@raw webflow custom properties", async () => {
- const input = WfData.parse({
+ const input = wfData.parse({
type: "@webflow/XscpData",
payload: {
nodes: [
@@ -3226,7 +3226,7 @@ describe("Styles", () => {
});
test("append transparent color when background-clip is used", async () => {
- const input = WfData.parse({
+ const input = wfData.parse({
type: "@webflow/XscpData",
payload: {
nodes: [
diff --git a/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.ts b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.ts
index 2815305ff7..97d807e29f 100644
--- a/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.ts
@@ -7,7 +7,8 @@ import { insertWebstudioFragmentCopy } from "../../instance-utils/fragment";
import { updateWebstudioData } from "../../instance-utils/data";
import { $project } from "~/shared/sync/data-stores";
import {
- WfData,
+ type WfData,
+ wfData,
wfNodeTypes,
type WfNode,
type WfStyle,
@@ -129,7 +130,7 @@ const parse = (clipboardData: string) => {
console.info(message);
}
- const result = WfData.safeParse(data);
+ const result = wfData.safeParse(data);
if (result.success) {
const unpasedTypes = new Set<string>();
diff --git a/apps/builder/app/shared/copy-paste/plugin-webflow/schema.ts b/apps/builder/app/shared/copy-paste/plugin-webflow/schema.ts
index b6b00f8f7e..f2d9e47297 100644
--- a/apps/builder/app/shared/copy-paste/plugin-webflow/schema.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-webflow/schema.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
-const Attr = z
+const attr = z
.object({ id: z.string(), role: z.string(), href: z.string() })
.partial();
@@ -14,8 +14,8 @@ const styleProperty = z.string();
const styleValue = z.unknown();
-const WfNodeData = z.object({
- attr: Attr.optional(),
+const wfNodeData = z.object({
+ attr: attr.optional(),
xattr: z.array(z.object({ name: z.string(), value: z.string() })).optional(),
visibility: z
.object({
@@ -33,23 +33,23 @@ const WfNodeData = z.object({
.optional(),
});
-const WfBaseNode = z.object({
+const wfBaseNode = z.object({
_id: z.string(),
tag: z.string(),
children: z.array(z.string()),
classes: z.array(z.string()),
- data: WfNodeData.optional(),
- attr: Attr.optional(),
+ data: wfNodeData.optional(),
+ attr: attr.optional(),
});
-const WfTextNode = z.object({
+const wfTextNode = z.object({
_id: z.string(),
v: z.string(),
text: z.boolean(),
});
-const WfLinkData = WfNodeData.extend({
- attr: Attr.optional(),
+const wfLinkData = wfNodeData.extend({
+ attr: attr.optional(),
block: z.enum(["inline", "block", ""]).optional(),
button: z.boolean().optional(),
link: z.union([
@@ -129,10 +129,10 @@ export const wfNodeTypes = [
"LightboxWrapper",
] as const;
-const WfElementNode = z.union([
- WfBaseNode.extend({
+const wfElementNode = z.union([
+ wfBaseNode.extend({
type: z.enum(["Icon"]),
- data: WfNodeData.extend({
+ data: wfNodeData.extend({
widget: z
.object({
type: z.string(),
@@ -142,70 +142,72 @@ const WfElementNode = z.union([
}),
}),
- WfBaseNode.extend({ type: z.enum(["LightboxWrapper"]) }),
- WfBaseNode.extend({ type: z.enum(["NavbarMenu"]) }),
- WfBaseNode.extend({ type: z.enum(["NavbarContainer"]) }),
+ wfBaseNode.extend({ type: z.enum(["LightboxWrapper"]) }),
+ wfBaseNode.extend({ type: z.enum(["NavbarMenu"]) }),
+ wfBaseNode.extend({ type: z.enum(["NavbarContainer"]) }),
- WfBaseNode.extend({ type: z.enum(["NavbarWrapper"]) }),
+ wfBaseNode.extend({ type: z.enum(["NavbarWrapper"]) }),
- WfBaseNode.extend({
+ wfBaseNode.extend({
type: z.enum(["NavbarBrand"]),
- data: WfLinkData,
+ data: wfLinkData,
}),
- WfBaseNode.extend({
+ wfBaseNode.extend({
type: z.enum(["NavbarLink"]),
- data: WfLinkData,
+ data: wfLinkData,
}),
- WfBaseNode.extend({ type: z.enum(["NavbarButton"]) }),
+ wfBaseNode.extend({ type: z.enum(["NavbarButton"]) }),
- WfBaseNode.extend({ type: z.enum(["Heading"]) }),
- WfBaseNode.extend({
+ wfBaseNode.extend({ type: z.enum(["Heading"]) }),
+ wfBaseNode.extend({
type: z.enum(["Block"]),
- data: WfNodeData.extend({
- attr: Attr.optional(),
- text: z.boolean().optional(),
- }).optional(),
+ data: wfNodeData
+ .extend({
+ attr: attr.optional(),
+ text: z.boolean().optional(),
+ })
+ .optional(),
}),
- WfBaseNode.extend({ type: z.enum(["List"]) }),
- WfBaseNode.extend({ type: z.enum(["ListItem"]) }),
- WfBaseNode.extend({
+ wfBaseNode.extend({ type: z.enum(["List"]) }),
+ wfBaseNode.extend({ type: z.enum(["ListItem"]) }),
+ wfBaseNode.extend({
type: z.enum(["Link"]),
- data: WfLinkData,
+ data: wfLinkData,
}),
- WfBaseNode.extend({ type: z.enum(["Paragraph"]) }),
- WfBaseNode.extend({ type: z.enum(["Blockquote"]) }),
- WfBaseNode.extend({ type: z.enum(["RichText"]) }),
- WfBaseNode.extend({ type: z.enum(["Strong"]) }),
- WfBaseNode.extend({ type: z.enum(["Emphasized"]) }),
- WfBaseNode.extend({ type: z.enum(["Superscript"]) }),
- WfBaseNode.extend({ type: z.enum(["Subscript"]) }),
- WfBaseNode.extend({ type: z.enum(["Section"]) }),
- WfBaseNode.extend({ type: z.enum(["BlockContainer"]) }),
- WfBaseNode.extend({ type: z.enum(["Container"]) }),
- WfBaseNode.extend({ type: z.enum(["Layout"]) }),
- WfBaseNode.extend({ type: z.enum(["Cell"]) }),
- WfBaseNode.extend({ type: z.enum(["VFlex"]) }),
- WfBaseNode.extend({ type: z.enum(["HFlex"]) }),
- WfBaseNode.extend({ type: z.enum(["Grid"]) }),
- WfBaseNode.extend({ type: z.enum(["Row"]) }),
- WfBaseNode.extend({ type: z.enum(["Column"]) }),
- WfBaseNode.extend({
+ wfBaseNode.extend({ type: z.enum(["Paragraph"]) }),
+ wfBaseNode.extend({ type: z.enum(["Blockquote"]) }),
+ wfBaseNode.extend({ type: z.enum(["RichText"]) }),
+ wfBaseNode.extend({ type: z.enum(["Strong"]) }),
+ wfBaseNode.extend({ type: z.enum(["Emphasized"]) }),
+ wfBaseNode.extend({ type: z.enum(["Superscript"]) }),
+ wfBaseNode.extend({ type: z.enum(["Subscript"]) }),
+ wfBaseNode.extend({ type: z.enum(["Section"]) }),
+ wfBaseNode.extend({ type: z.enum(["BlockContainer"]) }),
+ wfBaseNode.extend({ type: z.enum(["Container"]) }),
+ wfBaseNode.extend({ type: z.enum(["Layout"]) }),
+ wfBaseNode.extend({ type: z.enum(["Cell"]) }),
+ wfBaseNode.extend({ type: z.enum(["VFlex"]) }),
+ wfBaseNode.extend({ type: z.enum(["HFlex"]) }),
+ wfBaseNode.extend({ type: z.enum(["Grid"]) }),
+ wfBaseNode.extend({ type: z.enum(["Row"]) }),
+ wfBaseNode.extend({ type: z.enum(["Column"]) }),
+ wfBaseNode.extend({
type: z.enum(["CodeBlock"]),
- data: WfNodeData.extend({
- attr: Attr.optional(),
+ data: wfNodeData.extend({
+ attr: attr.optional(),
language: z.string().optional(),
code: z.string(),
}),
}),
- WfBaseNode.extend({
+ wfBaseNode.extend({
type: z.enum(["HtmlEmbed"]),
v: z.string(),
}),
- WfBaseNode.extend({
+ wfBaseNode.extend({
type: z.enum(["Image"]),
- data: WfNodeData.extend({
- attr: Attr.extend({
+ data: wfNodeData.extend({
+ attr: attr.extend({
alt: z.string().optional(),
loading: z.enum(["lazy", "eager", "auto"]),
src: z.string(),
@@ -214,31 +216,31 @@ const WfElementNode = z.union([
}),
}),
}),
- WfBaseNode.extend({ type: z.enum(["FormWrapper"]) }),
- WfBaseNode.extend({
+ wfBaseNode.extend({ type: z.enum(["FormWrapper"]) }),
+ wfBaseNode.extend({
type: z.enum(["FormForm"]),
- data: WfNodeData.extend({
- attr: Attr.extend({
+ data: wfNodeData.extend({
+ attr: attr.extend({
action: z.string(),
method: z.string(),
name: z.string(),
}),
}),
}),
- WfBaseNode.extend({ type: z.enum(["FormSuccessMessage"]) }),
- WfBaseNode.extend({ type: z.enum(["FormErrorMessage"]) }),
- WfBaseNode.extend({
+ wfBaseNode.extend({ type: z.enum(["FormSuccessMessage"]) }),
+ wfBaseNode.extend({ type: z.enum(["FormErrorMessage"]) }),
+ wfBaseNode.extend({
type: z.enum(["FormButton"]),
- data: WfNodeData.extend({
- attr: Attr.extend({
+ data: wfNodeData.extend({
+ attr: attr.extend({
value: z.string(),
}),
}),
}),
- WfBaseNode.extend({
+ wfBaseNode.extend({
type: z.enum(["FormTextInput"]),
- data: WfNodeData.extend({
- attr: Attr.extend({
+ data: wfNodeData.extend({
+ attr: attr.extend({
name: z.string(),
maxlength: z.number(),
placeholder: z.string(),
@@ -249,10 +251,10 @@ const WfElementNode = z.union([
}),
}),
}),
- WfBaseNode.extend({
+ wfBaseNode.extend({
type: z.enum(["FormTextarea"]),
- data: WfNodeData.extend({
- attr: Attr.extend({
+ data: wfNodeData.extend({
+ attr: attr.extend({
name: z.string(),
maxlength: z.number(),
placeholder: z.string(),
@@ -261,22 +263,22 @@ const WfElementNode = z.union([
}),
}),
}),
- WfBaseNode.extend({
+ wfBaseNode.extend({
type: z.enum(["FormBlockLabel"]),
- data: WfNodeData.extend({
- attr: Attr.extend({
+ data: wfNodeData.extend({
+ attr: attr.extend({
for: z.string().optional(),
}),
}),
}),
- WfBaseNode.extend({
+ wfBaseNode.extend({
type: z.enum(["FormCheckboxWrapper"]),
}),
- WfBaseNode.extend({
+ wfBaseNode.extend({
type: z.enum(["FormCheckboxInput"]),
- data: WfNodeData.extend({
- attr: Attr.extend({
+ data: wfNodeData.extend({
+ attr: attr.extend({
type: z.enum(["checkbox"]),
name: z.string(),
required: z.boolean(),
@@ -284,16 +286,16 @@ const WfElementNode = z.union([
}),
}),
}),
- WfBaseNode.extend({
+ wfBaseNode.extend({
type: z.enum(["FormInlineLabel"]),
}),
- WfBaseNode.extend({
+ wfBaseNode.extend({
type: z.enum(["FormRadioWrapper"]),
}),
- WfBaseNode.extend({
+ wfBaseNode.extend({
type: z.enum(["FormRadioInput"]),
- data: WfNodeData.extend({
- attr: Attr.extend({
+ data: wfNodeData.extend({
+ attr: attr.extend({
type: z.enum(["radio"]),
name: z.string(),
required: z.boolean(),
@@ -301,10 +303,10 @@ const WfElementNode = z.union([
}),
}),
}),
- WfBaseNode.extend({
+ wfBaseNode.extend({
type: z.enum(["FormSelect"]),
- data: WfNodeData.extend({
- attr: Attr.extend({
+ data: wfNodeData.extend({
+ attr: attr.extend({
name: z.string(),
required: z.boolean(),
multiple: z.boolean(),
@@ -319,21 +321,21 @@ const WfElementNode = z.union([
}),
}),
}),
- WfBaseNode.extend({ type: z.enum(["LineBreak"]) }),
- WfBaseNode.extend({ type: z.enum(["Span"]) }),
+ wfBaseNode.extend({ type: z.enum(["LineBreak"]) }),
+ wfBaseNode.extend({ type: z.enum(["Span"]) }),
]);
-export type WfElementNode = z.infer<typeof WfElementNode>;
+export type WfElementNode = z.infer<typeof wfElementNode>;
[...wfNodeTypes] as const satisfies WfElementNode["type"][];
//@todo verify the other way around too
//(typeof WfElementNode)["type"] satisfies typeof wfNodeTypes[number]
-const WfNode = z.union([WfElementNode, WfTextNode]);
-export type WfNode = z.infer<typeof WfNode>;
+const wfNode = z.union([wfElementNode, wfTextNode]);
+export type WfNode = z.infer<typeof wfNode>;
-const WfStyle = z.object({
+const wfStyle = z.object({
_id: z.string(),
type: z.enum(["class"]),
name: z.string(),
@@ -346,9 +348,9 @@ const WfStyle = z.object({
.optional(),
children: z.array(z.string()).optional(),
});
-export type WfStyle = z.infer<typeof WfStyle>;
+export type WfStyle = z.infer<typeof wfStyle>;
-const WfErrorAssetVariant = z.object({
+const wfErrorAssetVariant = z.object({
origFileName: z.string(),
fileName: z.string(),
format: z.string(),
@@ -360,7 +362,7 @@ const WfErrorAssetVariant = z.object({
_id: z.string(),
});
-const WfAssetVariant = z.object({
+const wfAssetVariant = z.object({
origFileName: z.string(),
fileName: z.string(),
format: z.string(),
@@ -372,7 +374,7 @@ const WfAssetVariant = z.object({
s3Url: z.string().url(),
});
-const WfAsset = z.object({
+const wfAsset = z.object({
cdnUrl: z.string().url(),
siteId: z.string(),
width: z.number().optional(),
@@ -381,7 +383,7 @@ const WfAsset = z.object({
createdOn: z.string(),
origFileName: z.string(),
fileHash: z.string(),
- variants: z.array(z.union([WfAssetVariant, WfErrorAssetVariant])).optional(),
+ variants: z.array(z.union([wfAssetVariant, wfErrorAssetVariant])).optional(),
mimeType: z.string(),
s3Url: z.string().url(),
thumbUrl: z.string().optional(),
@@ -390,15 +392,15 @@ const WfAsset = z.object({
fileSize: z.number(),
});
-export type WfAsset = z.infer<typeof WfAsset>;
+export type WfAsset = z.infer<typeof wfAsset>;
-export const WfData = z.object({
+export const wfData = z.object({
type: z.literal("@webflow/XscpData"),
payload: z.object({
// Using WfBaseNode here just so we can skip a node with unknown node.type.
- nodes: z.array(z.union([WfNode, WfBaseNode])),
- styles: z.array(WfStyle),
- assets: z.array(WfAsset),
+ nodes: z.array(z.union([wfNode, wfBaseNode])),
+ styles: z.array(wfStyle),
+ assets: z.array(wfAsset),
}),
});
-export type WfData = z.infer<typeof WfData>;
+export type WfData = z.infer<typeof wfData>;
diff --git a/apps/builder/app/shared/data-variables.ts b/apps/builder/app/shared/data-variables.ts
index 1c67a0cd25..c0606fc89d 100644
--- a/apps/builder/app/shared/data-variables.ts
+++ b/apps/builder/app/shared/data-variables.ts
@@ -7,7 +7,7 @@ import {
type Resource,
type Resources,
type WebstudioData,
- Pages,
+ type Pages,
ROOT_INSTANCE_ID,
SYSTEM_VARIABLE_ID,
collectionComponent,
@@ -361,7 +361,7 @@ const traverseExpressions = ({
resources,
update,
}: {
- startingInstanceId: Instance["id"];
+ startingInstanceId: undefined | Instance["id"];
pages: undefined | Pages;
instances: Instances;
props: Props;
@@ -375,10 +375,13 @@ const traverseExpressions = ({
}) => {
const pagesList = pages ? getAllPages(pages) : [];
- let instanceIds = findTreeInstanceIdsExcludingSlotDescendants(
- instances,
- startingInstanceId
- );
+ let instanceIds =
+ startingInstanceId === undefined
+ ? new Set(instances.keys())
+ : findTreeInstanceIdsExcludingSlotDescendants(
+ instances,
+ startingInstanceId
+ );
for (const page of pagesList) {
// global variables can be accessed on all pages and inside of slots
if (startingInstanceId === ROOT_INSTANCE_ID) {
@@ -492,7 +495,6 @@ const traverseExpressions = ({
};
export const findUnsetVariableNames = ({
- startingInstanceId,
instances,
props,
dataSources,
@@ -506,7 +508,7 @@ export const findUnsetVariableNames = ({
}) => {
const unsetVariables = new Set<DataSource["name"]>();
traverseExpressions({
- startingInstanceId,
+ startingInstanceId: undefined,
pages: undefined,
instances,
props,
diff --git a/apps/builder/app/shared/db/user.server.ts b/apps/builder/app/shared/db/user.server.ts
index 46dbe6af92..6fe4a93d8b 100644
--- a/apps/builder/app/shared/db/user.server.ts
+++ b/apps/builder/app/shared/db/user.server.ts
@@ -150,12 +150,12 @@ export const createOrLoginWithDev = async (
return newUser;
};
-export const userProjectTagSchema = z.object({
+export const userProjectTag = z.object({
id: z.string(),
label: z.string().min(1).max(100),
});
-export type ProjectTag = z.infer<typeof userProjectTagSchema>;
+export type ProjectTag = z.infer<typeof userProjectTag>;
export const updateUserProjectsTags = async (
{ tags }: { tags: ProjectTag[] },
diff --git a/apps/builder/app/shared/entri/entri-api.server.ts b/apps/builder/app/shared/entri/entri-api.server.ts
index 044308f14a..ce9d0dbd67 100644
--- a/apps/builder/app/shared/entri/entri-api.server.ts
+++ b/apps/builder/app/shared/entri/entri-api.server.ts
@@ -1,7 +1,7 @@
import { z } from "zod";
import env from "~/env/env.server";
-const EntryResponse = z.object({
+const entryResponse = z.object({
auth_token: z.string(),
});
@@ -16,7 +16,7 @@ const getEntriToken = async () => {
throw new Error(`ENTRI_SECRET is not defined`);
}
- const entryResponse = await fetch("https://api.goentri.com/token", {
+ const response = await fetch("https://api.goentri.com/token", {
method: "POST",
body: JSON.stringify({
// These values come from the Entri dashboard
@@ -29,12 +29,12 @@ const getEntriToken = async () => {
},
});
- if (entryResponse.ok === false) {
- throw new Error(`Entri API error: ${await entryResponse.text()}`);
+ if (response.ok === false) {
+ throw new Error(`Entri API error: ${await response.text()}`);
}
- const entryJson = await entryResponse.json();
- const responseData = EntryResponse.parse(entryJson);
+ const entryJson = await response.json();
+ const responseData = entryResponse.parse(entryJson);
return {
token: responseData.auth_token,
diff --git a/apps/builder/app/shared/error/error-parse.ts b/apps/builder/app/shared/error/error-parse.ts
index 188d4d5e9e..d4b189a98d 100644
--- a/apps/builder/app/shared/error/error-parse.ts
+++ b/apps/builder/app/shared/error/error-parse.ts
@@ -3,7 +3,7 @@ import { z } from "zod";
// Currently, we have multiple error formats, and not all of them are covered here.
// We should consolidate these formats into a single, unified format for consistency.
-const PageError = z.union([
+const pageError = z.union([
z.string().transform((message) => ({ message, description: undefined })),
z
.object({
@@ -38,7 +38,7 @@ export const parseError = (
}
if (isRouteErrorResponse(error)) {
- const parsed = PageError.safeParse(error.data);
+ const parsed = pageError.safeParse(error.data);
if (parsed.success) {
return {
@@ -56,7 +56,7 @@ export const parseError = (
};
}
- const parsed = PageError.safeParse(error);
+ const parsed = pageError.safeParse(error);
if (parsed.success) {
return {
message: parsed.data.message,
diff --git a/apps/builder/app/shared/html.ts b/apps/builder/app/shared/html.ts
index 8d8ee11aac..a31373da18 100644
--- a/apps/builder/app/shared/html.ts
+++ b/apps/builder/app/shared/html.ts
@@ -7,12 +7,12 @@ import {
type WebstudioFragment,
type Instance,
elementComponent,
- Prop,
+ type Prop,
tags,
- StyleDecl,
- Breakpoint,
- StyleSource,
- StyleSourceSelection,
+ type StyleDecl,
+ type Breakpoint,
+ type StyleSource,
+ type StyleSourceSelection,
} from "@webstudio-is/sdk";
import { ariaAttributes, attributesByTag } from "@webstudio-is/html-data";
import {
diff --git a/apps/builder/app/shared/logout.client.tsx b/apps/builder/app/shared/logout.client.tsx
index 1f9a58de8b..999f796844 100644
--- a/apps/builder/app/shared/logout.client.tsx
+++ b/apps/builder/app/shared/logout.client.tsx
@@ -87,7 +87,7 @@ export type LogoutPageProps = {
logoutUrls: string[];
};
-const LogoutResponse = z.object({
+const logoutResponse = z.object({
redirectTo: z.string(),
});
@@ -110,7 +110,7 @@ export const LogoutPage = (props: LogoutPageProps) => {
}
const data = await response.json();
- const parsedData = LogoutResponse.safeParse(data);
+ const parsedData = logoutResponse.safeParse(data);
if (false === parsedData.success) {
throw {
diff --git a/apps/builder/app/shared/marketplace/db.server.ts b/apps/builder/app/shared/marketplace/db.server.ts
index 30bf5413bf..416bdd1e64 100644
--- a/apps/builder/app/shared/marketplace/db.server.ts
+++ b/apps/builder/app/shared/marketplace/db.server.ts
@@ -1,4 +1,4 @@
-import { MarketplaceProduct } from "@webstudio-is/project-build";
+import { marketplaceProduct } from "@webstudio-is/project-build";
import type { MarketplaceOverviewItem } from "./types";
import {
loadApprovedProdBuildByProjectId,
@@ -42,7 +42,7 @@ export const getItems = async (
if (product.marketplaceProduct === null || product.projectId === null) {
continue;
}
- const parsedProduct = MarketplaceProduct.safeParse(
+ const parsedProduct = marketplaceProduct.safeParse(
parseConfig(product.marketplaceProduct)
);
diff --git a/apps/builder/app/shared/nano-states/props.test.tsx b/apps/builder/app/shared/nano-states/props.test.tsx
index d59b50bbff..5d8f177eaf 100644
--- a/apps/builder/app/shared/nano-states/props.test.tsx
+++ b/apps/builder/app/shared/nano-states/props.test.tsx
@@ -3,10 +3,10 @@ import { cleanStores } from "nanostores";
import { createDefaultPages } from "@webstudio-is/project-build";
import { setEnv } from "@webstudio-is/feature-flags";
import {
- DataSource,
+ type DataSource,
type Instance,
ROOT_INSTANCE_ID,
- Resource,
+ type Resource,
SYSTEM_VARIABLE_ID,
collectionComponent,
} from "@webstudio-is/sdk";
diff --git a/apps/builder/app/shared/project-settings/section-general.tsx b/apps/builder/app/shared/project-settings/section-general.tsx
index 88b2931a97..a13e1ddaab 100644
--- a/apps/builder/app/shared/project-settings/section-general.tsx
+++ b/apps/builder/app/shared/project-settings/section-general.tsx
@@ -46,7 +46,7 @@ const defaultMetaSettings: ProjectMeta = {
code: "",
};
-const Email = z.string().email();
+const emailAddress = z.string().email();
const validateContactEmail = (
contactEmail: string,
@@ -63,7 +63,9 @@ const validateContactEmail = (
}
return `Only ${maxContactEmailsPerProject} emails are allowed.`;
}
- if (emails.every((email) => Email.safeParse(email).success) === false) {
+ if (
+ emails.every((email) => emailAddress.safeParse(email).success) === false
+ ) {
return "Contact email is invalid.";
}
};
diff --git a/apps/builder/app/shared/project-settings/section-marketplace.tsx b/apps/builder/app/shared/project-settings/section-marketplace.tsx
index bb75115dd3..fb13dc4af4 100644
--- a/apps/builder/app/shared/project-settings/section-marketplace.tsx
+++ b/apps/builder/app/shared/project-settings/section-marketplace.tsx
@@ -19,7 +19,8 @@ import {
import { Image, wsImageLoader } from "@webstudio-is/image";
import { useState } from "react";
import {
- MarketplaceProduct,
+ type MarketplaceProduct,
+ marketplaceProduct,
marketplaceCategories,
} from "@webstudio-is/project-build";
import { ImageControl } from "./image-control";
@@ -29,7 +30,7 @@ import {
$project,
} from "~/shared/sync/data-stores";
import { useIds } from "~/shared/form-utils";
-import { MarketplaceApprovalStatus } from "@webstudio-is/project";
+import type { MarketplaceApprovalStatus } from "@webstudio-is/project";
import { serverSyncStore } from "~/shared/sync/sync-stores";
import { trpcClient } from "~/shared/trpc/trpc-client";
import { rightPanelWidth, sectionSpacing } from "./utils";
@@ -62,7 +63,7 @@ const defaultMarketplaceProduct: Partial<MarketplaceProduct> = {
};
const validate = (data: MarketplaceProduct) => {
- const parsedResult = MarketplaceProduct.safeParse(data);
+ const parsedResult = marketplaceProduct.safeParse(data);
if (parsedResult.success === false) {
return parsedResult.error.formErrors.fieldErrors;
}
diff --git a/apps/builder/app/shared/project-settings/section-redirects.tsx b/apps/builder/app/shared/project-settings/section-redirects.tsx
index 87bb05aef1..eeaf102ad1 100644
--- a/apps/builder/app/shared/project-settings/section-redirects.tsx
+++ b/apps/builder/app/shared/project-settings/section-redirects.tsx
@@ -31,7 +31,7 @@ import {
UploadIcon,
} from "@webstudio-is/icons";
import { ImportRedirectsDialog } from "./import-redirects-dialog";
-import { RedirectSourcePath, ProjectNewRedirectPath } from "@webstudio-is/sdk";
+import { redirectSourcePath, projectNewRedirectPath } from "@webstudio-is/sdk";
import type { PageRedirect } from "@webstudio-is/sdk";
import { useRef, useState } from "react";
import { flushSync } from "react-dom";
@@ -71,7 +71,7 @@ const validateFromPath = (
redirects: Array<PageRedirect>,
existingPaths: Set<string>
): ValidationResult => {
- const fromPathValidationResult = RedirectSourcePath.safeParse(fromPath);
+ const fromPathValidationResult = redirectSourcePath.safeParse(fromPath);
if (fromPathValidationResult.success) {
if (hasNamedSplat(fromPath)) {
@@ -125,7 +125,7 @@ const unsupportedTargetParamMessage =
"Target route params must match params from the source path";
const validateToPath = (toPath: string, fromPath?: string): string[] => {
- const toPathValidationResult = ProjectNewRedirectPath.safeParse(toPath);
+ const toPathValidationResult = projectNewRedirectPath.safeParse(toPath);
if (toPathValidationResult.success === false) {
return toPathValidationResult.error.format()._errors;
}
diff --git a/apps/builder/app/shared/redirects/redirect-parsers.ts b/apps/builder/app/shared/redirects/redirect-parsers.ts
index 6d9543c474..3a614ae243 100644
--- a/apps/builder/app/shared/redirects/redirect-parsers.ts
+++ b/apps/builder/app/shared/redirects/redirect-parsers.ts
@@ -1,5 +1,5 @@
import Papa from "papaparse";
-import { ProjectNewRedirectPath, RedirectSourcePath } from "@webstudio-is/sdk";
+import { projectNewRedirectPath, redirectSourcePath } from "@webstudio-is/sdk";
import {
getRedirectSourceSearchIndex,
hasInvalidLocalTargetParams,
@@ -298,7 +298,7 @@ const normalizeRecord = (
const normalizedTo = normalizePath(to);
// Validate source path
- const sourceValidationResult = RedirectSourcePath.safeParse(normalizedFrom);
+ const sourceValidationResult = redirectSourcePath.safeParse(normalizedFrom);
if (sourceValidationResult.success === false) {
return {
skipped: {
@@ -330,7 +330,7 @@ const normalizeRecord = (
}
// Validate target path
- const targetValidationResult = ProjectNewRedirectPath.safeParse(normalizedTo);
+ const targetValidationResult = projectNewRedirectPath.safeParse(normalizedTo);
if (targetValidationResult.success === false) {
return {
skipped: {
diff --git a/apps/builder/package.json b/apps/builder/package.json
index 7289946dd5..3f30ee4aff 100644
--- a/apps/builder/package.json
+++ b/apps/builder/package.json
@@ -58,6 +58,9 @@
"@trpc/client": "^10.45.2",
"@trpc/server": "^10.45.2",
"@tsndr/cloudflare-worker-jwt": "^2.5.3",
+ "@tus/file-store": "^2.1.0",
+ "@tus/s3-store": "^2.0.4",
+ "@tus/server": "^2.4.1",
"@unocss/core": "66.6.8",
"@vercel/remix": "2.15.3",
"@webstudio-is/protocol": "workspace:*",
diff --git a/fixtures/react-router-cloudflare/.webstudio/data.json b/fixtures/react-router-cloudflare/.webstudio/data.json
index fa42e3680a..89e31b6e40 100644
--- a/fixtures/react-router-cloudflare/.webstudio/data.json
+++ b/fixtures/react-router-cloudflare/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-0.0.0-a6dad953",
+ "bundleVersion": "bundle-a6dad953",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/react-router-cloudflare/app/extension.ts b/fixtures/react-router-cloudflare/app/extension.ts
index bffd05d48e..376906309b 100644
--- a/fixtures/react-router-cloudflare/app/extension.ts
+++ b/fixtures/react-router-cloudflare/app/extension.ts
@@ -1,4 +1,4 @@
-import { ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequest } from "@webstudio-is/sdk";
declare module "react-router" {
interface AppLoadContext {
diff --git a/fixtures/react-router-docker/.webstudio/data.json b/fixtures/react-router-docker/.webstudio/data.json
index fa42e3680a..89e31b6e40 100644
--- a/fixtures/react-router-docker/.webstudio/data.json
+++ b/fixtures/react-router-docker/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-0.0.0-a6dad953",
+ "bundleVersion": "bundle-a6dad953",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/react-router-docker/app/extension.ts b/fixtures/react-router-docker/app/extension.ts
index bffd05d48e..376906309b 100644
--- a/fixtures/react-router-docker/app/extension.ts
+++ b/fixtures/react-router-docker/app/extension.ts
@@ -1,4 +1,4 @@
-import { ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequest } from "@webstudio-is/sdk";
declare module "react-router" {
interface AppLoadContext {
diff --git a/fixtures/react-router-netlify/.webstudio/data.json b/fixtures/react-router-netlify/.webstudio/data.json
index fa42e3680a..89e31b6e40 100644
--- a/fixtures/react-router-netlify/.webstudio/data.json
+++ b/fixtures/react-router-netlify/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-0.0.0-a6dad953",
+ "bundleVersion": "bundle-a6dad953",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/react-router-netlify/app/extension.ts b/fixtures/react-router-netlify/app/extension.ts
index bffd05d48e..376906309b 100644
--- a/fixtures/react-router-netlify/app/extension.ts
+++ b/fixtures/react-router-netlify/app/extension.ts
@@ -1,4 +1,4 @@
-import { ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequest } from "@webstudio-is/sdk";
declare module "react-router" {
interface AppLoadContext {
diff --git a/fixtures/react-router-vercel/.webstudio/data.json b/fixtures/react-router-vercel/.webstudio/data.json
index fa42e3680a..89e31b6e40 100644
--- a/fixtures/react-router-vercel/.webstudio/data.json
+++ b/fixtures/react-router-vercel/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-0.0.0-a6dad953",
+ "bundleVersion": "bundle-a6dad953",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/react-router-vercel/app/extension.ts b/fixtures/react-router-vercel/app/extension.ts
index bffd05d48e..376906309b 100644
--- a/fixtures/react-router-vercel/app/extension.ts
+++ b/fixtures/react-router-vercel/app/extension.ts
@@ -1,4 +1,4 @@
-import { ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequest } from "@webstudio-is/sdk";
declare module "react-router" {
interface AppLoadContext {
diff --git a/fixtures/ssg-cloudflare-pages/.webstudio/data.json b/fixtures/ssg-cloudflare-pages/.webstudio/data.json
index 60d774896f..1f3647d2f8 100644
--- a/fixtures/ssg-cloudflare-pages/.webstudio/data.json
+++ b/fixtures/ssg-cloudflare-pages/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-0.0.0-a6dad953",
+ "bundleVersion": "bundle-a6dad953",
"build": {
"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json b/fixtures/ssg-netlify-by-project-id/.webstudio/data.json
index 6c0bd92dba..26969dd2e6 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-0.0.0-a6dad953",
+ "bundleVersion": "bundle-a6dad953",
"build": {
"id": "8f0fdff2-e76b-4f86-9203-ea7df5f1143c",
"projectId": "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e",
diff --git a/fixtures/webstudio-cloudflare-template/.webstudio/data.json b/fixtures/webstudio-cloudflare-template/.webstudio/data.json
index 60d774896f..1f3647d2f8 100644
--- a/fixtures/webstudio-cloudflare-template/.webstudio/data.json
+++ b/fixtures/webstudio-cloudflare-template/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-0.0.0-a6dad953",
+ "bundleVersion": "bundle-a6dad953",
"build": {
"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/webstudio-cloudflare-template/app/extension.ts b/fixtures/webstudio-cloudflare-template/app/extension.ts
index 3345c28d98..8e885b92f7 100644
--- a/fixtures/webstudio-cloudflare-template/app/extension.ts
+++ b/fixtures/webstudio-cloudflare-template/app/extension.ts
@@ -1,7 +1,7 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { AppLoadContext } from "@remix-run/server-runtime";
-import { ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequest } from "@webstudio-is/sdk";
declare module "@remix-run/server-runtime" {
interface AppLoadContext {
diff --git a/fixtures/webstudio-features/.webstudio/data.json b/fixtures/webstudio-features/.webstudio/data.json
index 2fff004310..913a4d65db 100644
--- a/fixtures/webstudio-features/.webstudio/data.json
+++ b/fixtures/webstudio-features/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-0.0.0-a6dad953",
+ "bundleVersion": "bundle-a6dad953",
"build": {
"id": "1b66ee06-8ea5-4420-9a0e-e0d3a67aca32",
"projectId": "cddc1d44-af37-4cb6-a430-d300cf6f932d",
diff --git a/fixtures/webstudio-features/app/extension.ts b/fixtures/webstudio-features/app/extension.ts
index bffd05d48e..376906309b 100644
--- a/fixtures/webstudio-features/app/extension.ts
+++ b/fixtures/webstudio-features/app/extension.ts
@@ -1,4 +1,4 @@
-import { ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequest } from "@webstudio-is/sdk";
declare module "react-router" {
interface AppLoadContext {
diff --git a/packages/asset-uploader/src/asset-patch-core.ts b/packages/asset-uploader/src/asset-patch-core.ts
index 03a979199e..1517cb31e0 100644
--- a/packages/asset-uploader/src/asset-patch-core.ts
+++ b/packages/asset-uploader/src/asset-patch-core.ts
@@ -1,5 +1,5 @@
import { type Patch, applyPatches } from "immer";
-import { type Asset, Assets } from "@webstudio-is/sdk";
+import { type Asset, assets } from "@webstudio-is/sdk";
import type { Client } from "@webstudio-is/postgrest/index.server";
import { formatAsset } from "./utils/format-asset";
@@ -117,17 +117,17 @@ export const patchAssetsWithClient = async (
patches: Array<Patch>
): Promise<void> => {
const assetsList = await loadAssetsByProjectWithClient(projectId, client);
- const assets = new Map<Asset["id"], Asset>();
+ const assetsMap = new Map<Asset["id"], Asset>();
for (const asset of assetsList) {
- assets.set(asset.id, asset);
+ assetsMap.set(asset.id, asset);
}
- const patchedAssets = applyPatches(assets, patches);
+ const patchedAssets = applyPatches(assetsMap, patches);
// validate assets without recreating objects
// we expect referencial equality to find updated assets
- Assets.parse(patchedAssets);
+ assets.parse(patchedAssets);
const deletedAssetIds: Asset["id"][] = [];
- for (const assetId of assets.keys()) {
+ for (const assetId of assetsMap.keys()) {
if (patchedAssets.has(assetId) === false) {
deletedAssetIds.push(assetId);
}
@@ -136,7 +136,7 @@ export const patchAssetsWithClient = async (
await deleteAssetsWithClient({ projectId, ids: deletedAssetIds }, client);
}
- for (const asset of assets.values()) {
+ for (const asset of assetsMap.values()) {
const patchedAsset = patchedAssets.get(asset.id);
if (asset !== patchedAsset && patchedAsset) {
const { filename, description } = patchedAsset;
@@ -151,7 +151,7 @@ export const patchAssetsWithClient = async (
const addedAssets: Asset[] = [];
for (const [assetId, asset] of patchedAssets) {
- if (assets.has(assetId) === false) {
+ if (assetsMap.has(assetId) === false) {
addedAssets.push(asset);
}
}
diff --git a/packages/asset-uploader/src/schema.ts b/packages/asset-uploader/src/schema.ts
index 6cc085f651..1bcc749889 100644
--- a/packages/asset-uploader/src/schema.ts
+++ b/packages/asset-uploader/src/schema.ts
@@ -2,7 +2,7 @@ import { z } from "zod";
import { MAX_UPLOAD_SIZE } from "./constants";
import { toBytes } from "./utils/to-bytes";
-export const MaxSize: z.ZodEffects<
+export const maxSize: z.ZodEffects<
z.ZodDefault<z.ZodString>,
number,
string | undefined
@@ -12,7 +12,7 @@ export const MaxSize: z.ZodEffects<
// user inputs the max value in mb and we transform it to bytes
.transform(toBytes);
-export const MaxAssets: z.ZodEffects<
+export const maxAssets: z.ZodEffects<
z.ZodDefault<z.ZodString>,
number,
string | undefined
diff --git a/packages/asset-uploader/src/upload.test.ts b/packages/asset-uploader/src/upload.test.ts
index 304fb4a915..0bbc079885 100644
--- a/packages/asset-uploader/src/upload.test.ts
+++ b/packages/asset-uploader/src/upload.test.ts
@@ -7,7 +7,7 @@ import {
testContext,
} from "@webstudio-is/postgrest/testing";
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
-import { createUploadName } from "./upload";
+import { createUploadName, uploadFile } from "./upload";
const server = createTestServer();
@@ -276,3 +276,56 @@ describe("createUploadName", () => {
expect(attemptedFileUpdate).toBe(false);
});
});
+
+describe("uploadFile", () => {
+ test("uses custom failed upload cleanup without deleting asset rows", async () => {
+ let customCleanupCalled = false;
+ let assetDeleted = false;
+ let fileDeleted = false;
+
+ server.use(
+ db.get("File", () =>
+ json({
+ name: "existing.png",
+ format: "image",
+ size: 0,
+ status: "UPLOADING",
+ uploaderProjectId: "project-1",
+ isDeleted: false,
+ meta: "{}",
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ })
+ ),
+ db.delete("Asset", () => {
+ assetDeleted = true;
+ return empty({ status: 204 });
+ }),
+ db.delete("File", () => {
+ fileDeleted = true;
+ return empty({ status: 204 });
+ })
+ );
+
+ await expect(
+ uploadFile(
+ "existing.png",
+ new Blob(["asset"]).stream(),
+ {
+ uploadFile: async () => {
+ throw new Error("Storage upload failed");
+ },
+ },
+ createContext(),
+ undefined,
+ async () => {
+ customCleanupCalled = true;
+ }
+ )
+ ).rejects.toThrow("Storage upload failed");
+
+ expect(customCleanupCalled).toBe(true);
+ expect(assetDeleted).toBe(false);
+ expect(fileDeleted).toBe(false);
+ });
+});
diff --git a/packages/asset-uploader/src/upload.ts b/packages/asset-uploader/src/upload.ts
index 19569ccca9..c6d5969bcb 100644
--- a/packages/asset-uploader/src/upload.ts
+++ b/packages/asset-uploader/src/upload.ts
@@ -19,6 +19,11 @@ type UploadData = {
const UPLOADING_STALE_TIMEOUT = 1000 * 60 * 30; // 30 minutes
+export type UploadErrorCleanup = (
+ name: string,
+ context: AppContext
+) => Promise<void>;
+
export const createUploadName = async (
data: UploadData,
context: AppContext
@@ -157,7 +162,8 @@ export const uploadFile = async (
context: AppContext,
assetInfoFallback:
| { width: number; height: number; format: string }
- | undefined
+ | undefined,
+ onUploadError?: UploadErrorCleanup
): Promise<Asset> => {
let file = await context.postgrest.client
.from("File")
@@ -204,8 +210,12 @@ export const uploadFile = async (
file: file.data,
});
} catch (error) {
- await context.postgrest.client.from("Asset").delete().eq("name", name);
- await context.postgrest.client.from("File").delete().eq("name", name);
+ if (onUploadError) {
+ await onUploadError(name, context);
+ } else {
+ await context.postgrest.client.from("Asset").delete().eq("name", name);
+ await context.postgrest.client.from("File").delete().eq("name", name);
+ }
throw error;
}
diff --git a/packages/asset-uploader/src/utils/format-asset.ts b/packages/asset-uploader/src/utils/format-asset.ts
index 2b9bf44b42..bd74c0fb93 100644
--- a/packages/asset-uploader/src/utils/format-asset.ts
+++ b/packages/asset-uploader/src/utils/format-asset.ts
@@ -1,5 +1,5 @@
-import { type FontFormat, FontMeta, FONT_FORMATS } from "@webstudio-is/fonts";
-import { type Asset, ImageMeta, detectAssetType } from "@webstudio-is/sdk";
+import { type FontFormat, fontMeta, FONT_FORMATS } from "@webstudio-is/fonts";
+import { type Asset, imageMeta, detectAssetType } from "@webstudio-is/sdk";
export const formatAsset = ({
assetId,
@@ -35,7 +35,7 @@ export const formatAsset = ({
type: "font",
createdAt: file.createdAt,
format: file.format as FontFormat,
- meta: FontMeta.parse(parsedMeta),
+ meta: fontMeta.parse(parsedMeta),
};
}
@@ -61,7 +61,7 @@ export const formatAsset = ({
type: "image",
format: file.format,
createdAt: file.createdAt,
- meta: ImageMeta.parse(parsedMeta),
+ meta: imageMeta.parse(parsedMeta),
};
}
diff --git a/packages/asset-uploader/src/utils/get-asset-data.ts b/packages/asset-uploader/src/utils/get-asset-data.ts
index 3ac52d657d..8f266b7548 100644
--- a/packages/asset-uploader/src/utils/get-asset-data.ts
+++ b/packages/asset-uploader/src/utils/get-asset-data.ts
@@ -1,7 +1,7 @@
import { z } from "zod";
-import { imageMeta } from "image-meta";
-import { FontMeta } from "@webstudio-is/fonts";
-import { ImageMeta, validateFileName } from "@webstudio-is/sdk";
+import { imageMeta as parseImageMeta } from "image-meta";
+import { type FontMeta, fontMeta } from "@webstudio-is/fonts";
+import { type ImageMeta, imageMeta, validateFileName } from "@webstudio-is/sdk";
import { getFontData } from "./font-data";
export type AssetData = {
@@ -10,10 +10,10 @@ export type AssetData = {
meta: ImageMeta | FontMeta | object;
};
-export const AssetData: z.ZodType<AssetData> = z.object({
+export const assetData: z.ZodType<AssetData> = z.object({
size: z.number(),
format: z.string(),
- meta: z.union([ImageMeta, FontMeta, z.object({})]),
+ meta: z.union([imageMeta, fontMeta, z.object({})]),
});
type BaseAssetOptions = {
@@ -35,7 +35,7 @@ export const getAssetData = async (
if (options.type === "image") {
let image: undefined | { format: string; width: number; height: number };
try {
- const parsed = imageMeta(Buffer.from(options.data));
+ const parsed = parseImageMeta(Buffer.from(options.data));
if (parsed.type) {
image = {
format: parsed.type,
diff --git a/packages/authorization-token/src/trpc/authorization-tokens-router.ts b/packages/authorization-token/src/trpc/authorization-tokens-router.ts
index 21a85904e1..86c86bc4fa 100644
--- a/packages/authorization-token/src/trpc/authorization-tokens-router.ts
+++ b/packages/authorization-token/src/trpc/authorization-tokens-router.ts
@@ -7,7 +7,7 @@ import type { Database } from "@webstudio-is/postgrest/index.server";
type Relation =
Database["public"]["Tables"]["AuthorizationToken"]["Row"]["relation"];
-const TokenProjectRelation = z.enum([
+const tokenProjectRelation = z.enum([
"viewers",
"editors",
"builders",
@@ -15,7 +15,7 @@ const TokenProjectRelation = z.enum([
]);
// Check DB types are compatible with zod types
-type TokenRelation = z.infer<typeof TokenProjectRelation>;
+type TokenRelation = z.infer<typeof tokenProjectRelation>;
true satisfies IsEqual<TokenRelation, Relation>;
export const authorizationTokenRouter = router({
@@ -32,7 +32,7 @@ export const authorizationTokenRouter = router({
.input(
z.object({
projectId: z.string(),
- relation: TokenProjectRelation,
+ relation: tokenProjectRelation,
name: z.string(),
})
)
@@ -65,7 +65,7 @@ export const authorizationTokenRouter = router({
projectId: z.string(),
token: z.string(),
name: z.string(),
- relation: TokenProjectRelation,
+ relation: tokenProjectRelation,
canClone: z.boolean(),
canCopy: z.boolean(),
canPublish: z.boolean(),
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 491c149e9a..25a885b2b4 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -47,6 +47,7 @@
"picocolors": "^1.1.1",
"reserved-identifiers": "^1.0.0",
"tinyexec": "^0.3.2",
+ "tus-js-client": "^4.3.1",
"warn-once": "^0.1.1",
"yargs": "^17.7.2",
"zod": "^3.24.2"
diff --git a/packages/cli/src/asset-files.test.ts b/packages/cli/src/asset-files.test.ts
index 1e3d6871bf..1888d98960 100644
--- a/packages/cli/src/asset-files.test.ts
+++ b/packages/cli/src/asset-files.test.ts
@@ -10,7 +10,11 @@ import {
import { join } from "node:path";
import { tmpdir } from "node:os";
import type { Asset } from "@webstudio-is/sdk";
-import { getLocalAssetPath, materializeAssetFile } from "./asset-files";
+import {
+ getLocalAssetPath,
+ materializeAssetFile,
+ uploadAssetFiles,
+} from "./asset-files";
const originalCwd = process.cwd();
let tempDir: string;
@@ -26,6 +30,12 @@ const asset = {
meta: { width: 1, height: 1 },
} satisfies Asset;
+const otherAsset = {
+ ...asset,
+ id: "asset-2",
+ name: "other.png",
+} satisfies Asset;
+
beforeEach(async () => {
tempDir = await mkdtemp(join(tmpdir(), "webstudio-assets-"));
process.chdir(tempDir);
@@ -122,3 +132,102 @@ test("fails clearly when asset download response has no body", async () => {
await expect(access("public/assets/image.png")).rejects.toThrow();
await expect(access("public/assets/image.png.tmp")).rejects.toThrow();
});
+
+test("uploads assets as binary requests", async () => {
+ await mkdir(".webstudio/assets", { recursive: true });
+ await writeFile(".webstudio/assets/image.png", "synced", "utf8");
+ const fetch = vi.fn(
+ async () =>
+ new Response(JSON.stringify({ ok: true }), {
+ headers: { "content-type": "application/json" },
+ })
+ );
+ globalThis.fetch = fetch;
+
+ await uploadAssetFiles({
+ assets: [asset],
+ authToken: "token",
+ origin: "https://apps.webstudio.is",
+ projectId: "project-1",
+ });
+
+ expect(fetch).toHaveBeenCalledOnce();
+ const [, init] = fetch.mock.calls[0] as unknown as [URL, RequestInit];
+ expect(init.body).toBeInstanceOf(Blob);
+ await expect((init.body as Blob).text()).resolves.toBe("synced");
+});
+
+test("retries failed asset uploads once", async () => {
+ await mkdir(".webstudio/assets", { recursive: true });
+ await writeFile(".webstudio/assets/image.png", "synced", "utf8");
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ errors: "Temporary failure" }), {
+ headers: { "content-type": "application/json" },
+ })
+ )
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ ok: true }), {
+ headers: { "content-type": "application/json" },
+ })
+ );
+ globalThis.fetch = fetch;
+
+ await uploadAssetFiles({
+ assets: [asset],
+ authToken: "token",
+ origin: "https://apps.webstudio.is",
+ projectId: "project-1",
+ });
+
+ expect(fetch).toHaveBeenCalledTimes(2);
+});
+
+test("reports all asset uploads that fail after retry", async () => {
+ await mkdir(".webstudio/assets", { recursive: true });
+ await writeFile(".webstudio/assets/image.png", "synced", "utf8");
+ await writeFile(".webstudio/assets/other.png", "other", "utf8");
+ const fetch = vi.fn(
+ async () =>
+ new Response(JSON.stringify({ errors: "Upload failed" }), {
+ headers: { "content-type": "application/json" },
+ })
+ );
+ globalThis.fetch = fetch;
+
+ let message = "";
+ try {
+ await uploadAssetFiles({
+ assets: [asset, otherAsset],
+ authToken: "token",
+ origin: "https://apps.webstudio.is",
+ projectId: "project-1",
+ });
+ } catch (error) {
+ message = error instanceof Error ? error.message : String(error);
+ }
+
+ expect(message).toContain("Failed to upload assets:");
+ expect(message).toContain("image.png: Upload failed");
+ expect(message).toContain("other.png: Upload failed");
+ expect(fetch).toHaveBeenCalledTimes(4);
+});
+
+test("reports missing local asset files with upload failures", async () => {
+ let message = "";
+ try {
+ await uploadAssetFiles({
+ assets: [asset],
+ authToken: "token",
+ origin: "https://apps.webstudio.is",
+ projectId: "project-1",
+ });
+ } catch (error) {
+ message = error instanceof Error ? error.message : String(error);
+ }
+
+ expect(message).toContain("Failed to upload assets:");
+ expect(message).toContain("image.png:");
+ expect(message).toContain("no such file or directory");
+});
diff --git a/packages/cli/src/asset-files.ts b/packages/cli/src/asset-files.ts
index 257344129a..8b9e2ab07f 100644
--- a/packages/cli/src/asset-files.ts
+++ b/packages/cli/src/asset-files.ts
@@ -5,7 +5,8 @@ import { pipeline } from "node:stream/promises";
import pLimit from "p-limit";
import { getAssetUrl, type Asset } from "@webstudio-is/sdk";
import { createFolderIfNotExists, isFileExists } from "./fs-utils";
-import { isAssetFileName, type AssetFileData } from "@webstudio-is/protocol";
+import { uploadAsset } from "@webstudio-is/http-client";
+import { isAssetFileName } from "@webstudio-is/protocol";
export const LOCAL_ASSETS_DIR = ".webstudio/assets";
@@ -39,6 +40,17 @@ const runAssetTasks = async ({
);
};
+const formatError = (error: unknown) =>
+ error instanceof Error ? error.message : String(error);
+
+const retryOnce = async (task: () => Promise<void>) => {
+ try {
+ await task();
+ } catch {
+ await task();
+ }
+};
+
export const getLocalAssetPath = (
assetName: string,
assetsDirectory = LOCAL_ASSETS_DIR
@@ -182,22 +194,56 @@ export const materializeAssetFiles = async ({
});
};
-export const loadAssetFiles = async ({
+export const uploadAssetFiles = async ({
assets,
assetsDirectory = LOCAL_ASSETS_DIR,
+ authToken,
+ headers,
+ origin,
+ projectId,
}: {
assets: Asset[];
assetsDirectory?: string;
-}): Promise<AssetFileData[]> => {
- const files: AssetFileData[] = [];
+ authToken: string;
+ headers?: Record<string, string | undefined>;
+ origin: string;
+ projectId: string;
+}): Promise<void> => {
+ const failedUploads: { asset: Asset; error: unknown }[] = [];
+
+ await runAssetTasks({
+ assets,
+ operation: "uploading",
+ task: async (asset) => {
+ try {
+ const file = await readFile(
+ getLocalAssetPath(asset.name, assetsDirectory)
+ );
+ const upload = async () => {
+ await uploadAsset({
+ authToken,
+ headers,
+ origin,
+ projectId,
+ upload: {
+ asset,
+ data: new Blob([new Uint8Array(file)]),
+ },
+ });
+ };
+
+ await retryOnce(upload);
+ } catch (error) {
+ failedUploads.push({ asset, error });
+ }
+ },
+ });
- for (const asset of assets) {
- const data = await readFile(
- getLocalAssetPath(asset.name, assetsDirectory),
- "base64"
+ if (failedUploads.length > 0) {
+ throw new Error(
+ `Failed to upload assets: ${failedUploads
+ .map(({ asset, error }) => `${asset.name}: ${formatError(error)}`)
+ .join("; ")}`
);
- files.push({ name: asset.name, data });
}
-
- return files;
};
diff --git a/packages/cli/src/commands/import.test.ts b/packages/cli/src/commands/import.test.ts
index f7ac22d3d0..3d2eeebd30 100644
--- a/packages/cli/src/commands/import.test.ts
+++ b/packages/cli/src/commands/import.test.ts
@@ -10,7 +10,6 @@ import {
createPublishedProjectBundleFixture,
} from "@webstudio-is/protocol/fixtures";
import { loadJSONFile } from "../fs-utils";
-import { loadAssetFiles } from "../asset-files";
import {
createAuthConfigContentFromBundle,
LOCAL_AUTH_FILE,
@@ -44,11 +43,12 @@ const indicator = {
};
const checkProjectBuildPermission = vi.fn();
const importProjectBundle = vi.fn();
+const uploadAssetFiles = vi.fn();
const promptText = vi.fn();
const dependencies = {
checkProjectBuildPermission,
importProjectBundle,
- loadAssetFiles,
+ uploadAssetFiles,
loadJSONFile,
text: promptText,
isInteractive: false,
@@ -75,8 +75,10 @@ beforeEach(async () => {
await mkdir(".webstudio", { recursive: true });
checkProjectBuildPermission.mockResolvedValue(undefined);
importProjectBundle.mockResolvedValue({ version: 1 });
+ uploadAssetFiles.mockResolvedValue(undefined);
promptText.mockResolvedValue(destinationShareLink);
checkProjectBuildPermission.mockClear();
+ uploadAssetFiles.mockClear();
promptText.mockClear();
log.info.mockClear();
indicator.start.mockClear();
@@ -99,12 +101,9 @@ test("imports local synced data into destination project", async () => {
expect(importProjectBundle).toHaveBeenCalledWith({
...destinationRequest,
data: createSyncedData(),
- assetFiles: [],
ignoreVersionCheck: undefined,
});
- expect(indicator.stop).toHaveBeenCalledWith(
- "Project bundle imported successfully"
- );
+ expect(indicator.stop).toHaveBeenCalledWith("Project imported successfully");
expect(indicator.message).toHaveBeenCalledWith(
"Reading .webstudio/data.json"
);
@@ -189,6 +188,22 @@ test("requires destination share link before running non-interactive command", a
);
});
+test("parses skip-assets flag", async () => {
+ const parser = importOptions(
+ makeCLI([])
+ .exitProcess(false)
+ .fail((message, error) => {
+ throw error ?? new Error(message);
+ }) as CommonYargsArgv
+ );
+
+ expect(
+ parser.parse(["--to", destinationShareLink, "--skip-assets"])
+ ).toMatchObject({
+ skipAssets: true,
+ });
+});
+
test("stops with sync instruction when local data is missing", async () => {
await expect(
importProject(
@@ -282,12 +297,9 @@ test("imports old local data when version check is explicitly ignored", async ()
expect.objectContaining({
ignoreVersionCheck: true,
data: createSyncedData({ bundleVersion: undefined }),
- assetFiles: [],
})
);
- expect(indicator.stop).toHaveBeenCalledWith(
- "Project bundle imported successfully"
- );
+ expect(indicator.stop).toHaveBeenCalledWith("Project imported successfully");
});
test("stops before API request when ignored-version data is missing assets", async () => {
@@ -356,18 +368,95 @@ test("passes version-check bypass to target API", async () => {
);
});
-test("loads local asset files for import", async () => {
+test("uploads local asset files before import", async () => {
+ await mkdir(".webstudio/assets", { recursive: true });
+ await writeSyncedData({
+ assets: [imageAsset],
+ });
+ await writeFile(".webstudio/assets/image.png", "hello", "utf8");
+
+ await importProject({ to: destinationShareLink }, dependencies);
+
+ expect(uploadAssetFiles).toHaveBeenCalledWith({
+ ...destinationRequest,
+ assets: [imageAsset],
+ });
+ expect(importProjectBundle).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: createSyncedData({ assets: [imageAsset] }),
+ })
+ );
+});
+
+test("re-uploads missing asset files reported by import API", async () => {
await mkdir(".webstudio/assets", { recursive: true });
await writeSyncedData({
assets: [imageAsset],
});
await writeFile(".webstudio/assets/image.png", "hello", "utf8");
+ importProjectBundle
+ .mockRejectedValueOnce(
+ new Error("Imported asset files are missing: image.png")
+ )
+ .mockResolvedValueOnce({ version: 1 });
await importProject({ to: destinationShareLink }, dependencies);
+ expect(uploadAssetFiles).toHaveBeenNthCalledWith(1, {
+ ...destinationRequest,
+ assets: [imageAsset],
+ });
+ expect(uploadAssetFiles).toHaveBeenNthCalledWith(2, {
+ ...destinationRequest,
+ assets: [imageAsset],
+ });
+ expect(importProjectBundle).toHaveBeenCalledTimes(2);
+ expect(indicator.message).toHaveBeenCalledWith(
+ "Re-uploading 1 missing assets"
+ );
+ expect(indicator.stop).toHaveBeenCalledWith("Project imported successfully");
+});
+
+test("does not retry unknown missing asset files", async () => {
+ await mkdir(".webstudio/assets", { recursive: true });
+ await writeSyncedData({
+ assets: [imageAsset],
+ });
+ await writeFile(".webstudio/assets/image.png", "hello", "utf8");
+ importProjectBundle.mockRejectedValueOnce(
+ new Error("Imported asset files are missing: unknown.png")
+ );
+
+ await expect(
+ importProject({ to: destinationShareLink }, dependencies)
+ ).rejects.toThrow("Handled CLI error");
+
+ expect(uploadAssetFiles).toHaveBeenCalledTimes(1);
+ expect(importProjectBundle).toHaveBeenCalledTimes(1);
+ expect(indicator.stop).toHaveBeenCalledWith(
+ "Imported asset files are missing: unknown.png",
+ 2
+ );
+});
+
+test("imports without uploading assets when requested", async () => {
+ await writeSyncedData({
+ assets: [imageAsset],
+ });
+
+ await importProject(
+ {
+ to: destinationShareLink,
+ skipAssets: true,
+ },
+ dependencies
+ );
+
+ expect(uploadAssetFiles).not.toHaveBeenCalled();
+ expect(log.info).toHaveBeenCalledWith("Skipped asset upload and asset rows");
expect(importProjectBundle).toHaveBeenCalledWith(
expect.objectContaining({
- assetFiles: [{ name: "image.png", data: "aGVsbG8=" }],
+ data: createSyncedData({ assets: [] }),
})
);
});
@@ -495,11 +584,11 @@ test("stops before API request when current local data is missing published meta
);
});
-test("stops before reading asset files when destination permission check fails", async () => {
+test("stops before uploading asset files when destination permission check fails", async () => {
await writeSyncedData({
assets: [imageAsset],
});
- const loadAssetFiles = vi.fn();
+ const uploadAssetFiles = vi.fn();
checkProjectBuildPermission.mockRejectedValue(
new Error("You don't have permission to build this project")
);
@@ -511,13 +600,13 @@ test("stops before reading asset files when destination permission check fails",
},
{
...dependencies,
- loadAssetFiles,
+ uploadAssetFiles,
}
)
).rejects.toThrow("Handled CLI error");
expect(checkProjectBuildPermission).toHaveBeenCalledWith(destinationRequest);
- expect(loadAssetFiles).not.toHaveBeenCalled();
+ expect(uploadAssetFiles).not.toHaveBeenCalled();
expect(importProjectBundle).not.toHaveBeenCalled();
expect(indicator.stop).toHaveBeenCalledWith(
"You don't have permission to build this project",
@@ -550,3 +639,24 @@ test("prints import command in CLI compatibility guidance", async () => {
2
);
});
+
+test("forwards oversized project bundle import error", async () => {
+ await writeSyncedData();
+ importProjectBundle.mockRejectedValue(
+ new Error("Project bundle is too large to import. Maximum size is 20 MiB.")
+ );
+
+ await expect(
+ importProject(
+ {
+ to: destinationShareLink,
+ },
+ dependencies
+ )
+ ).rejects.toThrow("Handled CLI error");
+
+ expect(indicator.stop).toHaveBeenCalledWith(
+ "Project bundle is too large to import. Maximum size is 20 MiB.",
+ 2
+ );
+});
diff --git a/packages/cli/src/commands/import.ts b/packages/cli/src/commands/import.ts
index 63b366d221..4715bdfca8 100644
--- a/packages/cli/src/commands/import.ts
+++ b/packages/cli/src/commands/import.ts
@@ -4,7 +4,8 @@ import { cancel, isCancel, log, spinner, text } from "@clack/prompts";
import {
getBundleVersion,
getBundleVersionMismatchMessage,
- publishedProjectBundleSchema,
+ parseMissingImportedAssetFilesMessage,
+ publishedProjectBundle,
bundleVersion,
} from "@webstudio-is/protocol";
import {
@@ -14,7 +15,7 @@ import {
import { LOCAL_DATA_FILE } from "../config";
import { loadJSONFile } from "../fs-utils";
import { HandledCliError } from "../errors";
-import { loadAssetFiles } from "../asset-files";
+import { uploadAssetFiles } from "../asset-files";
import { LOCAL_AUTH_FILE, validateAuthConfigFile } from "../auth-config";
import { apiCompatibilityHeaders, stopSpinnerWithError } from "./api";
import { parseShareLink, validateShareLink } from "./link";
@@ -27,7 +28,7 @@ import type {
type ImportProjectDependencies = {
checkProjectBuildPermission: typeof checkProjectBuildPermission;
importProjectBundle: typeof importProjectBundle;
- loadAssetFiles: typeof loadAssetFiles;
+ uploadAssetFiles: typeof uploadAssetFiles;
loadJSONFile: typeof loadJSONFile;
text: typeof text;
isInteractive: boolean;
@@ -41,7 +42,7 @@ const isInteractiveTerminal = () =>
const defaultDependencies: ImportProjectDependencies = {
checkProjectBuildPermission,
importProjectBundle,
- loadAssetFiles,
+ uploadAssetFiles,
loadJSONFile,
text,
isInteractive: isInteractiveTerminal(),
@@ -58,6 +59,7 @@ const invalidProjectBundleMessage =
const invalidAuthConfigMessage =
"Project bundle auth config is invalid. Please run webstudio prebuild before importing.";
const invalidDestinationMessage = "Destination share link is invalid.";
+const maxMissingAssetImportRetries = 5;
export const importOptions = (yargs: CommonYargsArgv) =>
yargs
@@ -70,6 +72,11 @@ export const importOptions = (yargs: CommonYargsArgv) =>
describe:
"Import data without a compatible data version; import may fail if source and target API data formats differ",
})
+ .option("skip-assets", {
+ type: "boolean",
+ describe:
+ "Import project data without uploading or importing asset files; referenced assets may be missing in the target project",
+ })
.check((options) => {
if (options.to === undefined && isInteractiveTerminal() === false) {
return missingDestinationMessage;
@@ -79,7 +86,7 @@ export const importOptions = (yargs: CommonYargsArgv) =>
type ImportOptions = Pick<
Partial<StrictYargsOptionsToInterface<typeof importOptions>>,
- "ignoreVersionCheck"
+ "ignoreVersionCheck" | "skipAssets"
> & {
to?: string;
};
@@ -126,7 +133,7 @@ export const importProject = async (
);
throw new HandledCliError();
}
- const parsedData = publishedProjectBundleSchema.safeParse(data);
+ const parsedData = publishedProjectBundle.safeParse(data);
if (parsedData.success === false) {
importing.stop(
`${invalidProjectBundleMessage} Invalid fields: ${formatZodIssues(
@@ -211,34 +218,29 @@ export const importProject = async (
throw new HandledCliError();
}
- importing.message(`Reading ${importData.assets.length} local asset files`);
- let assetFiles;
- try {
- assetFiles = await dependencies.loadAssetFiles({
- assets: importData.assets,
- });
- } catch (error) {
- importing.stop(
- error instanceof Error
- ? `Unable to read project bundle asset files: ${error.message}`
- : "Unable to read project bundle asset files",
- 2
- );
- throw new HandledCliError();
+ if (options.skipAssets === true) {
+ dependencies.log.info("Skipped asset upload and asset rows");
+ } else {
+ importing.message(`Uploading ${importData.assets.length} assets`);
+ try {
+ await dependencies.uploadAssetFiles({
+ assets: importData.assets,
+ ...destinationRequest,
+ });
+ } catch (error) {
+ importing.stop(
+ error instanceof Error
+ ? `Unable to upload assets: ${error.message}`
+ : "Unable to upload assets",
+ 2
+ );
+ throw new HandledCliError();
+ }
}
- importing.message(
- `Waiting for API response while importing into ${destination.projectId}`
- );
-
- try {
- await dependencies.importProjectBundle({
- ...destinationRequest,
- data: importData,
- assetFiles,
- ignoreVersionCheck: options.ignoreVersionCheck,
- });
- } catch (error) {
+ const dataToImport =
+ options.skipAssets === true ? { ...importData, assets: [] } : importData;
+ const stopImportWithError = (error: unknown): never => {
stopSpinnerWithError(
importing,
error,
@@ -246,7 +248,53 @@ export const importProject = async (
"import"
);
throw new HandledCliError();
- }
+ };
+
+ for (let attempt = 0; attempt <= maxMissingAssetImportRetries; attempt += 1) {
+ importing.message(
+ `Waiting for API response while importing into ${destination.projectId}`
+ );
- importing.stop("Project bundle imported successfully");
+ try {
+ await dependencies.importProjectBundle({
+ ...destinationRequest,
+ data: dataToImport,
+ ignoreVersionCheck: options.ignoreVersionCheck,
+ });
+ importing.stop("Project imported successfully");
+ return;
+ } catch (error) {
+ const missingAssetNames =
+ options.skipAssets === true
+ ? undefined
+ : parseMissingImportedAssetFilesMessage(error);
+ const assetNames = missingAssetNames ?? [];
+ if (assetNames.length === 0 || attempt === maxMissingAssetImportRetries) {
+ stopImportWithError(error);
+ }
+
+ const missingAssets = importData.assets.filter((asset) =>
+ assetNames.includes(asset.name)
+ );
+ if (missingAssets.length !== assetNames.length) {
+ stopImportWithError(error);
+ }
+
+ importing.message(`Re-uploading ${missingAssets.length} missing assets`);
+ try {
+ await dependencies.uploadAssetFiles({
+ assets: missingAssets,
+ ...destinationRequest,
+ });
+ } catch (uploadError) {
+ importing.stop(
+ uploadError instanceof Error
+ ? `Unable to upload missing assets: ${uploadError.message}`
+ : "Unable to upload missing assets",
+ 2
+ );
+ throw new HandledCliError();
+ }
+ }
+ }
};
diff --git a/packages/cli/src/commands/sync.ts b/packages/cli/src/commands/sync.ts
index 41613f685a..89183174c4 100644
--- a/packages/cli/src/commands/sync.ts
+++ b/packages/cli/src/commands/sync.ts
@@ -5,7 +5,7 @@ import pc from "picocolors";
import { spinner } from "@clack/prompts";
import {
bundleVersion,
- publishedProjectBundleSchema,
+ publishedProjectBundle,
type PublishedProjectBundle,
} from "@webstudio-is/protocol";
import {
@@ -51,7 +51,7 @@ const defaultDependencies: SyncDependencies = {
};
const toLocalProjectBundle = (project: PublishedProjectBundle) => {
- const normalizedProject = publishedProjectBundleSchema.parse(project);
+ const normalizedProject = publishedProjectBundle.parse(project);
const {
assets,
build,
diff --git a/packages/cli/src/config.ts-expect.ts b/packages/cli/src/config.ts-expect.ts
index 604a0f10e5..b00478b00e 100644
--- a/packages/cli/src/config.ts-expect.ts
+++ b/packages/cli/src/config.ts-expect.ts
@@ -1,5 +1,5 @@
import { expectType, type TypeEqual } from "ts-expect";
-import { Templates } from "@webstudio-is/sdk";
+import type { Templates } from "@webstudio-is/sdk";
import { PROJECT_TEMPLATES } from "./config";
// We must ensure the validated template type always matches the CLI-supported templates.
diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.ts
index 442725bc23..92d087880f 100644
--- a/packages/cli/src/prebuild.ts
+++ b/packages/cli/src/prebuild.ts
@@ -41,7 +41,7 @@ import {
toRuntimeAsset,
} from "@webstudio-is/sdk";
import { migratePages } from "@webstudio-is/project-migrations/pages";
-import { publishedProjectBundleSchema } from "@webstudio-is/protocol";
+import { publishedProjectBundle } from "@webstudio-is/protocol";
import { createAuthConfigResources, LOCAL_AUTH_FILE } from "./auth-config";
import { LOCAL_DATA_FILE } from "./config";
import {
@@ -265,7 +265,7 @@ export const prebuild = async (options: {
`Project bundle is missing, please make sure the project is synced.`
);
}
- const parsedSiteData = publishedProjectBundleSchema.safeParse(loadedSiteData);
+ 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)}`
diff --git a/packages/cli/templates/defaults/app/extension.ts b/packages/cli/templates/defaults/app/extension.ts
index 3345c28d98..8e885b92f7 100644
--- a/packages/cli/templates/defaults/app/extension.ts
+++ b/packages/cli/templates/defaults/app/extension.ts
@@ -1,7 +1,7 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { AppLoadContext } from "@remix-run/server-runtime";
-import { ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequest } from "@webstudio-is/sdk";
declare module "@remix-run/server-runtime" {
interface AppLoadContext {
diff --git a/packages/cli/templates/react-router/app/extension.ts b/packages/cli/templates/react-router/app/extension.ts
index bffd05d48e..376906309b 100644
--- a/packages/cli/templates/react-router/app/extension.ts
+++ b/packages/cli/templates/react-router/app/extension.ts
@@ -1,4 +1,4 @@
-import { ResourceRequest } from "@webstudio-is/sdk";
+import type { ResourceRequest } from "@webstudio-is/sdk";
declare module "react-router" {
interface AppLoadContext {
diff --git a/packages/css-data/src/property-parsers/linear-gradient.ts b/packages/css-data/src/property-parsers/linear-gradient.ts
index 59ccf6e630..815407935d 100644
--- a/packages/css-data/src/property-parsers/linear-gradient.ts
+++ b/packages/css-data/src/property-parsers/linear-gradient.ts
@@ -3,7 +3,7 @@ import { cssTryParseValue } from "../parse-css-value";
import {
type UnitValue,
toValue,
- KeywordValue,
+ type KeywordValue,
type VarValue,
} from "@webstudio-is/css-engine";
import {
diff --git a/packages/css-engine/src/core/merger.ts b/packages/css-engine/src/core/merger.ts
index bb470d7e81..c71046b17c 100644
--- a/packages/css-engine/src/core/merger.ts
+++ b/packages/css-engine/src/core/merger.ts
@@ -1,4 +1,4 @@
-import { StyleValue, TupleValue, TupleValueItem } from "../schema";
+import type { StyleValue, TupleValue, TupleValueItem } from "../schema";
import { cssWideKeywords } from "../css";
import type { StyleMap } from "./rules";
import { toValue } from "./to-value";
diff --git a/packages/css-engine/src/schema.ts b/packages/css-engine/src/schema.ts
index bdd28ac69f..ddb3f8b99c 100644
--- a/packages/css-engine/src/schema.ts
+++ b/packages/css-engine/src/schema.ts
@@ -14,47 +14,47 @@ export type CssProperty = HyphenatedProperty | CustomProperty;
export type CssStyleMap = Map<CssProperty, StyleValue>;
-const Unit = z.string() as z.ZodType<GeneratedUnit | "number">;
+const unit = z.string() as z.ZodType<GeneratedUnit | "number">;
-export type Unit = z.infer<typeof Unit>;
+export type Unit = z.infer<typeof unit>;
-export const UnitValue = z.object({
+export const unitValue = z.object({
type: z.literal("unit"),
- unit: Unit,
+ unit: unit,
value: z.number(),
hidden: z.boolean().optional(),
});
-export type UnitValue = z.infer<typeof UnitValue>;
+export type UnitValue = z.infer<typeof unitValue>;
-export const KeywordValue = z.object({
+export const keywordValue = z.object({
type: z.literal("keyword"),
// @todo use exact type
value: z.string(),
hidden: z.boolean().optional(),
});
-export type KeywordValue = z.infer<typeof KeywordValue>;
+export type KeywordValue = z.infer<typeof keywordValue>;
/**
* Valid unparsed css value
**/
-export const UnparsedValue = z.object({
+export const unparsedValue = z.object({
type: z.literal("unparsed"),
value: z.string(),
// For the builder we want to be able to hide background-image
hidden: z.boolean().optional(),
});
-export type UnparsedValue = z.infer<typeof UnparsedValue>;
+export type UnparsedValue = z.infer<typeof unparsedValue>;
-const FontFamilyValue = z.object({
+const fontFamilyValue = z.object({
type: z.literal("fontFamily"),
value: z.array(z.string()),
hidden: z.boolean().optional(),
});
-export type FontFamilyValue = z.infer<typeof FontFamilyValue>;
+export type FontFamilyValue = z.infer<typeof fontFamilyValue>;
-const RgbValue = z.object({
+const rgbValue = z.object({
type: z.literal("rgb"),
r: z.number(),
g: z.number(),
@@ -62,7 +62,7 @@ const RgbValue = z.object({
alpha: z.number(),
hidden: z.boolean().optional(),
});
-export type RgbValue = z.infer<typeof RgbValue>;
+export type RgbValue = z.infer<typeof rgbValue>;
// Explicit type declaration needed to break the ColorValue ↔ VarValue ↔ VarFallback cycle.
// VarValue (defined later) may appear as the alpha channel value.
@@ -89,7 +89,7 @@ export type ColorValue = {
hidden?: boolean;
};
-export const ColorValue: z.ZodType<ColorValue> = z.object({
+export const colorValue: z.ZodType<ColorValue> = z.object({
type: z.literal("color"),
// all these color spaces are defined by design tokens specification
colorSpace: z.union([
@@ -110,13 +110,13 @@ export const ColorValue: z.ZodType<ColorValue> = z.object({
z.literal("xyz-d50"),
]),
components: z.tuple([z.number(), z.number(), z.number()]),
- alpha: z.union([z.number(), z.lazy(() => VarValue) as z.ZodType<VarValue>]),
+ alpha: z.union([z.number(), z.lazy(() => varValue) as z.ZodType<VarValue>]),
hidden: z.boolean().optional(),
});
-export type FunctionValue = z.infer<typeof FunctionValue>;
+export type FunctionValue = z.infer<typeof functionValue>;
-export const FunctionValue: z.ZodType<{
+export const functionValue: z.ZodType<{
type: "function";
name: string;
args: StyleValue;
@@ -124,11 +124,11 @@ export const FunctionValue: z.ZodType<{
}> = z.object({
type: z.literal("function"),
name: z.string(),
- args: z.lazy(() => StyleValue),
+ args: z.lazy(() => styleValue),
hidden: z.boolean().optional(),
});
-export const ImageValue = z.object({
+export const imageValue = z.object({
type: z.literal("image"),
value: z.union([
z.object({ type: z.literal("asset"), value: z.string() }),
@@ -140,44 +140,44 @@ export const ImageValue = z.object({
hidden: z.boolean().optional(),
});
-export type ImageValue = z.infer<typeof ImageValue>;
+export type ImageValue = z.infer<typeof imageValue>;
// initial value of custom properties
// https://www.w3.org/TR/css-variables-1/#guaranteed-invalid
-export const GuaranteedInvalidValue = z.object({
+export const guaranteedInvalidValue = z.object({
type: z.literal("guaranteedInvalid"),
hidden: z.boolean().optional(),
});
-export type GuaranteedInvalidValue = z.infer<typeof GuaranteedInvalidValue>;
+export type GuaranteedInvalidValue = z.infer<typeof guaranteedInvalidValue>;
// We want to be able to render the invalid value
// and show it is invalid visually, without saving it to the db
-export const InvalidValue = z.object({
+export const invalidValue = z.object({
type: z.literal("invalid"),
value: z.string(),
hidden: z.boolean().optional(),
});
-export type InvalidValue = z.infer<typeof InvalidValue>;
+export type InvalidValue = z.infer<typeof invalidValue>;
/**
* Use GuaranteedInvalidValue if you need a temp placeholder before user enters a value
* @deprecated
*/
-const UnsetValue = z.object({
+const unsetValue = z.object({
type: z.literal("unset"),
value: z.literal(""),
hidden: z.boolean().optional(),
});
-export type UnsetValue = z.infer<typeof UnsetValue>;
-
-export const VarFallback = z.union([
- UnparsedValue,
- KeywordValue,
- UnitValue,
- ColorValue,
- RgbValue,
+export type UnsetValue = z.infer<typeof unsetValue>;
+
+export const varFallback = z.union([
+ unparsedValue,
+ keywordValue,
+ unitValue,
+ colorValue,
+ rgbValue,
]);
-export type VarFallback = z.infer<typeof VarFallback>;
+export type VarFallback = z.infer<typeof varFallback>;
export const toVarFallback = (
styleValue: StyleValue,
@@ -196,89 +196,89 @@ export const toVarFallback = (
return { type: "unparsed", value: toValue(styleValue, transformValue) };
};
-const VarValue = z.object({
+const varValue = z.object({
type: z.literal("var"),
value: z.string(),
- fallback: VarFallback.optional(),
+ fallback: varFallback.optional(),
hidden: z.boolean().optional(),
});
-export type VarValue = z.infer<typeof VarValue>;
-
-export const TupleValueItem = z.union([
- UnitValue,
- KeywordValue,
- UnparsedValue,
- ImageValue,
- ColorValue,
- RgbValue,
- FunctionValue,
- VarValue,
+export type VarValue = z.infer<typeof varValue>;
+
+export const tupleValueItem = z.union([
+ unitValue,
+ keywordValue,
+ unparsedValue,
+ imageValue,
+ colorValue,
+ rgbValue,
+ functionValue,
+ varValue,
]);
-export type TupleValueItem = z.infer<typeof TupleValueItem>;
+export type TupleValueItem = z.infer<typeof tupleValueItem>;
-export const TupleValue = z.object({
+export const tupleValue = z.object({
type: z.literal("tuple"),
- value: z.array(TupleValueItem),
+ value: z.array(tupleValueItem),
hidden: z.boolean().optional(),
});
-export type TupleValue = z.infer<typeof TupleValue>;
+export type TupleValue = z.infer<typeof tupleValue>;
-export const ShadowValue = z.object({
+export const shadowValue = z.object({
type: z.literal("shadow"),
hidden: z.boolean().optional(),
position: z.union([z.literal("inset"), z.literal("outset")]),
- offsetX: z.union([UnitValue, VarValue]),
- offsetY: z.union([UnitValue, VarValue]),
- blur: z.union([UnitValue, VarValue]).optional(),
- spread: z.union([UnitValue, VarValue]).optional(),
- color: z.union([ColorValue, RgbValue, KeywordValue, VarValue]).optional(),
+ offsetX: z.union([unitValue, varValue]),
+ offsetY: z.union([unitValue, varValue]),
+ blur: z.union([unitValue, varValue]).optional(),
+ spread: z.union([unitValue, varValue]).optional(),
+ color: z.union([colorValue, rgbValue, keywordValue, varValue]).optional(),
});
-export type ShadowValue = z.infer<typeof ShadowValue>;
-
-const LayerValueItem = z.union([
- UnitValue,
- KeywordValue,
- UnparsedValue,
- ImageValue,
- TupleValue,
- ShadowValue,
- ColorValue,
- RgbValue,
- InvalidValue,
- FunctionValue,
- VarValue,
+export type ShadowValue = z.infer<typeof shadowValue>;
+
+const layerValueItem = z.union([
+ unitValue,
+ keywordValue,
+ unparsedValue,
+ imageValue,
+ tupleValue,
+ shadowValue,
+ colorValue,
+ rgbValue,
+ invalidValue,
+ functionValue,
+ varValue,
]);
-export type LayerValueItem = z.infer<typeof LayerValueItem>;
+export type LayerValueItem = z.infer<typeof layerValueItem>;
// To support background layers https://developer.mozilla.org/en-US/docs/Web/CSS/background
// and similar comma separated css properties
// InvalidValue used in case of asset not found
-export const LayersValue = z.object({
+export const layersValue = z.object({
type: z.literal("layers"),
- value: z.array(LayerValueItem),
+ value: z.array(layerValueItem),
hidden: z.boolean().optional(),
});
-export type LayersValue = z.infer<typeof LayersValue>;
-
-export const StyleValue = z.union([
- ImageValue,
- LayersValue,
- UnitValue,
- KeywordValue,
- FontFamilyValue,
- ColorValue,
- RgbValue,
- UnparsedValue,
- TupleValue,
- FunctionValue,
- GuaranteedInvalidValue,
- InvalidValue,
- UnsetValue,
- VarValue,
- ShadowValue,
+export type LayersValue = z.infer<typeof layersValue>;
+
+export const styleValue = z.union([
+ imageValue,
+ layersValue,
+ unitValue,
+ keywordValue,
+ fontFamilyValue,
+ colorValue,
+ rgbValue,
+ unparsedValue,
+ tupleValue,
+ functionValue,
+ guaranteedInvalidValue,
+ invalidValue,
+ unsetValue,
+ varValue,
+ shadowValue,
]);
-export type StyleValue = z.infer<typeof StyleValue>;
+export type StyleValue = z.infer<typeof styleValue>;
diff --git a/packages/domain/src/trpc/domain.ts b/packages/domain/src/trpc/domain.ts
index 4333af2a19..9c8b3efc9f 100644
--- a/packages/domain/src/trpc/domain.ts
+++ b/packages/domain/src/trpc/domain.ts
@@ -13,7 +13,7 @@ import {
getProjectOwnerId,
AuthorizationError,
} from "@webstudio-is/trpc-interface/index.server";
-import { Templates } from "@webstudio-is/sdk";
+import { templates } from "@webstudio-is/sdk";
import { db } from "../db";
import { isDomainUsingCloudflareNameservers } from "../rdap";
@@ -69,7 +69,7 @@ export const domainRouter = router({
z.object({
projectId: z.string(),
destination: z.literal("static"),
- templates: z.array(Templates),
+ templates: z.array(templates),
}),
])
)
diff --git a/packages/fonts/src/schema.ts b/packages/fonts/src/schema.ts
index d354e81ef1..316f8204e3 100644
--- a/packages/fonts/src/schema.ts
+++ b/packages/fonts/src/schema.ts
@@ -1,14 +1,14 @@
import { z } from "zod";
import { FONT_STYLES } from "./constants";
-export const FontFormat = z.union([
+export const fontFormat = z.union([
z.literal("ttf"),
z.literal("woff"),
z.literal("woff2"),
]);
-export type FontFormat = z.infer<typeof FontFormat>;
+export type FontFormat = z.infer<typeof fontFormat>;
-const AxisName = z.enum([
+const axisName = z.enum([
"wght",
"wdth",
"slnt",
@@ -25,8 +25,8 @@ const AxisName = z.enum([
"YTFI",
]);
-const VariationAxes = z.record(
- AxisName,
+const variationAxes = z.record(
+ axisName,
z.object({
name: z.string(),
min: z.number(),
@@ -35,21 +35,21 @@ const VariationAxes = z.record(
})
);
-export type VariationAxes = z.infer<typeof VariationAxes>;
+export type VariationAxes = z.infer<typeof variationAxes>;
-export const FontMetaStatic = z.object({
+export const fontMetaStatic = z.object({
family: z.string(),
style: z.enum(FONT_STYLES),
weight: z.number(),
});
-export type FontMetaStatic = z.infer<typeof FontMetaStatic>;
+export type FontMetaStatic = z.infer<typeof fontMetaStatic>;
-const FontMetaVariable = z.object({
+const fontMetaVariable = z.object({
family: z.string(),
- variationAxes: VariationAxes,
+ variationAxes: variationAxes,
});
-export const FontMeta = z.union([FontMetaStatic, FontMetaVariable]);
+export const fontMeta = z.union([fontMetaStatic, fontMetaVariable]);
-export type FontMeta = z.infer<typeof FontMeta>;
+export type FontMeta = z.infer<typeof fontMeta>;
diff --git a/packages/generate-arg-types/src/arg-types.ts b/packages/generate-arg-types/src/arg-types.ts
index b8c609a8e5..e925bb7d62 100644
--- a/packages/generate-arg-types/src/arg-types.ts
+++ b/packages/generate-arg-types/src/arg-types.ts
@@ -1,5 +1,5 @@
import type { PropItem } from "react-docgen-typescript";
-import { PropMeta } from "@webstudio-is/sdk";
+import { type PropMeta, propMeta } from "@webstudio-is/sdk";
export type FilterPredicate = (prop: PropItem) => boolean;
@@ -74,7 +74,7 @@ export const getArgType = (propItem: PropItem): PropMeta | undefined => {
if (type === "number" && typeof value === "string") {
value = Number(value);
}
- return PropMeta.parse({
+ return propMeta.parse({
type,
required: propItem.required,
control,
diff --git a/packages/html-data/bin/aria.ts b/packages/html-data/bin/aria.ts
index b886626e1b..fa9563cdae 100644
--- a/packages/html-data/bin/aria.ts
+++ b/packages/html-data/bin/aria.ts
@@ -4,7 +4,7 @@ import {
coreMetas,
createScope,
elementComponent,
- Prop,
+ type Prop,
type Instance,
type Instances,
type Props,
diff --git a/packages/http-client/package.json b/packages/http-client/package.json
index f0b9489f13..7a2e6ba964 100644
--- a/packages/http-client/package.json
+++ b/packages/http-client/package.json
@@ -13,7 +13,8 @@
},
"dependencies": {
"@trpc/client": "^10.45.2",
- "@webstudio-is/protocol": "workspace:*"
+ "@webstudio-is/protocol": "workspace:*",
+ "tus-js-client": "^4.3.1"
},
"devDependencies": {
"@webstudio-is/tsconfig": "workspace:*",
diff --git a/packages/http-client/src/index.test.ts b/packages/http-client/src/index.test.ts
index bdaf08721e..e41c86b085 100644
--- a/packages/http-client/src/index.test.ts
+++ b/packages/http-client/src/index.test.ts
@@ -1,5 +1,17 @@
-import { expect, test } from "vitest";
-import { parseBuilderUrl } from "./index";
+import { createServer, type IncomingMessage } from "node:http";
+import { afterEach, expect, test, vi } from "vitest";
+import { stagedUploadPath } from "@webstudio-is/protocol";
+import {
+ importProjectBundle,
+ loadProjectBundleByProjectId,
+ parseBuilderUrl,
+ uploadAsset,
+ type PublishedProjectBundle,
+} from "./index";
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
test("parseBuilderUrl wstd.dev", async () => {
expect(
@@ -92,3 +104,242 @@ test("parseBuilderUrl apps.webstudio.is", async () => {
}
`);
});
+
+test("reports non-json api responses", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response("<html>\n<h1>Request Entity Too Large</h1>", {
+ status: 413,
+ statusText: "Payload Too Large",
+ headers: {
+ "content-type": "text/html",
+ },
+ })
+ )
+ );
+
+ let message;
+ try {
+ await loadProjectBundleByProjectId({
+ authToken: "token",
+ origin:
+ "https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb.apps.webstudio.is",
+ projectId: "090e6e14-ae50-4b2e-bd22-71733cec05bb",
+ });
+ } catch (error) {
+ message = error instanceof Error ? error.message : String(error);
+ }
+
+ expect(message).toContain(
+ "API returned text/html instead of JSON from https://apps.webstudio.is/trpc"
+ );
+ expect(message).toContain("HTTP status: 413 Payload Too Large.");
+ expect(message).toContain(
+ "Response preview: <html> <h1>Request Entity Too Large</h1>"
+ );
+ expect(message).toContain("The request may be too large for the API.");
+});
+
+test("uploads assets as binary requests", async () => {
+ const fetch = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ ok: true }), {
+ headers: {
+ "content-type": "application/json",
+ },
+ })
+ );
+ vi.stubGlobal("fetch", fetch);
+
+ const file = new Uint8Array([1, 2, 3]);
+ await uploadAsset({
+ authToken: "token",
+ origin: "https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb.apps.webstudio.is",
+ projectId: "090e6e14-ae50-4b2e-bd22-71733cec05bb",
+ upload: {
+ asset: {
+ id: "asset-id",
+ projectId: "source-project",
+ type: "image",
+ name: "image.png",
+ filename: "image.png",
+ format: "png",
+ size: 3,
+ meta: { width: 10, height: 20 },
+ createdAt: "2024-01-01T00:00:00.000Z",
+ },
+ data: file,
+ },
+ });
+
+ 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&width=10&height=20&format=png"
+ );
+ expect(init.method).toBe("POST");
+ expect(init.body).toBe(file);
+ expect(init.headers).toBeInstanceOf(Headers);
+ expect((init.headers as Headers).get("x-auth-token")).toBe("token");
+ expect((init.headers as Headers).get("content-type")).toBe(
+ "application/octet-stream"
+ );
+});
+
+test("reports asset upload errors", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ errors: "Upload failed" }), {
+ headers: {
+ "content-type": "application/json",
+ },
+ })
+ )
+ );
+
+ await expect(
+ uploadAsset({
+ authToken: "token",
+ origin:
+ "https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb.apps.webstudio.is",
+ projectId: "090e6e14-ae50-4b2e-bd22-71733cec05bb",
+ upload: {
+ asset: {
+ id: "asset-id",
+ projectId: "source-project",
+ type: "file",
+ name: "document.pdf",
+ format: "pdf",
+ size: 3,
+ meta: {},
+ createdAt: "2024-01-01T00:00:00.000Z",
+ },
+ data: new Uint8Array([1, 2, 3]),
+ },
+ })
+ ).rejects.toThrow("Upload failed");
+});
+
+const readRequestBody = async (request: IncomingMessage) => {
+ const chunks = [];
+ for await (const chunk of request) {
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
+ }
+ return Buffer.concat(chunks);
+};
+
+test("imports project bundle through staged upload", async () => {
+ const uploadChunks: Buffer[] = [];
+ let trpcBody: unknown;
+
+ const server = createServer(async (request, response) => {
+ const url = new URL(request.url ?? "/", "http://localhost");
+
+ if (request.method === "POST" && url.pathname === stagedUploadPath) {
+ response.writeHead(201, {
+ Location: `http://${request.headers.host}${stagedUploadPath}/upload-id`,
+ "Tus-Resumable": "1.0.0",
+ });
+ response.end();
+ return;
+ }
+
+ if (
+ request.method === "PATCH" &&
+ url.pathname === `${stagedUploadPath}/upload-id`
+ ) {
+ uploadChunks.push(await readRequestBody(request));
+ response.writeHead(204, {
+ "Tus-Resumable": "1.0.0",
+ "Upload-Offset": String(
+ uploadChunks.reduce((size, chunk) => size + chunk.byteLength, 0)
+ ),
+ });
+ response.end();
+ return;
+ }
+
+ if (
+ request.method === "POST" &&
+ url.pathname === "/trpc/build.importProjectBundle"
+ ) {
+ trpcBody = JSON.parse((await readRequestBody(request)).toString("utf8"));
+ response.writeHead(200, { "content-type": "application/json" });
+ response.end(JSON.stringify([{ result: { data: { version: 2 } } }]));
+ return;
+ }
+
+ response.writeHead(404);
+ response.end();
+ });
+
+ await new Promise<void>((resolve) => {
+ server.listen(0, "127.0.0.1", resolve);
+ });
+
+ try {
+ const address = server.address();
+ if (address === null || typeof address === "string") {
+ throw new Error("Server address is unavailable");
+ }
+
+ await expect(
+ importProjectBundle({
+ authToken: "token",
+ origin: `http://127.0.0.1:${address.port}`,
+ projectId: "project-id",
+ data: {
+ largeContent: "x".repeat(3 * 1024 * 1024 + 1),
+ } as unknown as PublishedProjectBundle,
+ })
+ ).resolves.toEqual({ version: 2 });
+ } finally {
+ await new Promise<void>((resolve, reject) => {
+ server.close((error) => (error ? reject(error) : resolve()));
+ });
+ }
+
+ expect(uploadChunks).toHaveLength(2);
+ expect(JSON.stringify(trpcBody)).toContain('"uploadId":"upload-id"');
+ expect(JSON.stringify(trpcBody)).not.toContain("largeContent");
+});
+
+test("rejects project bundles over the import size limit", async () => {
+ let requestCount = 0;
+ const server = createServer((_request, response) => {
+ requestCount += 1;
+ response.writeHead(500);
+ response.end();
+ });
+
+ await new Promise<void>((resolve) => {
+ server.listen(0, "127.0.0.1", resolve);
+ });
+
+ try {
+ const address = server.address();
+ if (address === null || typeof address === "string") {
+ throw new Error("Server address is unavailable");
+ }
+
+ await expect(
+ importProjectBundle({
+ authToken: "token",
+ origin: `http://127.0.0.1:${address.port}`,
+ projectId: "project-id",
+ data: {
+ largeContent: "x".repeat(20 * 1024 * 1024),
+ } as unknown as PublishedProjectBundle,
+ })
+ ).rejects.toThrow(
+ "Project bundle is too large to import. Maximum size is 20 MiB."
+ );
+ } finally {
+ await new Promise<void>((resolve, reject) => {
+ server.close((error) => (error ? reject(error) : resolve()));
+ });
+ }
+
+ expect(requestCount).toBe(0);
+});
diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.ts
index f4201199f7..6ba09b9fbd 100644
--- a/packages/http-client/src/index.ts
+++ b/packages/http-client/src/index.ts
@@ -1,26 +1,85 @@
import { createTRPCUntypedClient, httpBatchLink } from "@trpc/client";
+import { Upload } from "tus-js-client";
import {
- importProjectBundleResultSchema,
- publishedProjectBundleSchema,
- type AssetFileData,
+ importProjectBundleResult,
+ publishedProjectBundle,
+ maxProjectBundleSize,
+ stagedUploadPath,
+ stagedUploadProjectIdHeader,
type ImportProjectBundleResult,
type PublishedProjectBundle,
} from "@webstudio-is/protocol";
-export {
- getBundleVersion,
- isAssetFileDataString,
- bundleVersion,
-} from "@webstudio-is/protocol";
+export { getBundleVersion, bundleVersion } from "@webstudio-is/protocol";
export type {
- AssetFileData,
PublishedProjectBundle,
ProjectBundle,
} from "@webstudio-is/protocol";
-const createTrpcClient = (
- origin: string,
- headers: Record<string, string | undefined>
+const maxResponsePreviewLength = 500;
+
+const getResponsePreview = async (response: Response) => {
+ try {
+ const text = await response.clone().text();
+ return text.replace(/\s+/g, " ").trim().slice(0, maxResponsePreviewLength);
+ } catch {
+ return "";
+ }
+};
+
+const createApiResponseErrorMessage = async (
+ request: RequestInfo | URL,
+ response: Response
) => {
+ const contentType = response.headers.get("content-type") ?? "unknown";
+ const status = `${response.status} ${response.statusText}`.trim();
+ const url =
+ typeof request === "string" || request instanceof URL
+ ? request.toString()
+ : request.url;
+ const preview = await getResponsePreview(response);
+ const hint =
+ response.status === 413
+ ? "The request may be too large for the API."
+ : undefined;
+
+ return [
+ `API returned ${contentType} instead of JSON from ${url}.`,
+ `HTTP status: ${status}.`,
+ preview === "" ? undefined : `Response preview: ${preview}`,
+ hint,
+ ]
+ .filter(Boolean)
+ .join("\n");
+};
+
+const fetchJsonResponse: typeof fetch = async (request, init) => {
+ const response = await fetch(request, init);
+ const contentType = response.headers.get("content-type");
+
+ if (contentType?.includes("json") !== true) {
+ throw new Error(await createApiResponseErrorMessage(request, response));
+ }
+
+ return response;
+};
+
+const createHeaders = (headers: Record<string, string | undefined>) => {
+ return new Headers(createHeadersObject(headers));
+};
+
+const createHeadersObject = (headers: Record<string, string | undefined>) => {
+ const result: Record<string, string> = {};
+ for (const [name, value] of Object.entries(headers)) {
+ if (value !== undefined) {
+ result[name] = value;
+ }
+ }
+ return result;
+};
+
+type RequestHeaders = Record<string, string | undefined>;
+
+const createTrpcClient = (origin: string, headers: RequestHeaders) => {
const { sourceOrigin } = parseBuilderUrl(origin);
const url = new URL("/trpc", sourceOrigin);
@@ -29,6 +88,7 @@ const createTrpcClient = (
httpBatchLink({
url: url.href,
headers,
+ fetch: fetchJsonResponse,
}),
],
});
@@ -37,18 +97,95 @@ const createTrpcClient = (
const createAuthTrpcClient = (params: {
origin: string;
authToken: string;
- headers?: Record<string, string | undefined>;
+ headers?: RequestHeaders;
}) =>
createTrpcClient(params.origin, {
...params.headers,
"x-auth-token": params.authToken,
});
+type AuthProjectParams = {
+ projectId: string;
+ origin: string;
+ authToken: string;
+ headers?: RequestHeaders;
+};
+
+const stagedUploadChunkSize = 3 * 1024 * 1024;
+
+const formatMebibytes = (bytes: number) =>
+ `${Math.round(bytes / 1024 / 1024)} MiB`;
+
+type Asset = PublishedProjectBundle["assets"][number];
+type BinaryAssetData = Blob | ArrayBuffer | ArrayBufferView<ArrayBuffer>;
+
+type AssetUpload = {
+ asset: Asset;
+ data: BinaryAssetData;
+};
+
+const getAssetUploadUrl = ({
+ asset,
+ origin,
+ projectId,
+}: {
+ asset: Asset;
+ origin: string;
+ projectId: string;
+}) => {
+ const { sourceOrigin } = parseBuilderUrl(origin);
+ const url = new URL(
+ `/rest/assets/${encodeURIComponent(asset.name)}`,
+ sourceOrigin
+ );
+ url.searchParams.set("projectId", projectId);
+ url.searchParams.set("type", asset.type);
+ if (asset.type === "image") {
+ url.searchParams.set("width", String(asset.meta.width));
+ url.searchParams.set("height", String(asset.meta.height));
+ url.searchParams.set("format", asset.format);
+ }
+ return url;
+};
+
+export const uploadAsset = async (
+ params: AuthProjectParams & {
+ upload: AssetUpload;
+ }
+): Promise<void> => {
+ const { authToken, headers, origin, projectId, upload } = params;
+ const response = await fetchJsonResponse(
+ getAssetUploadUrl({
+ asset: upload.asset,
+ origin,
+ projectId,
+ }),
+ {
+ method: "POST",
+ body: upload.data,
+ headers: createHeaders({
+ ...headers,
+ "x-auth-token": authToken,
+ "content-type": "application/octet-stream",
+ }),
+ }
+ );
+ const result = await response.json();
+ if (
+ typeof result === "object" &&
+ result !== null &&
+ "errors" in result &&
+ typeof result.errors === "string"
+ ) {
+ throw new Error(result.errors);
+ }
+};
+
export const loadProjectBundleByBuildId = async (
params: {
buildId: string;
origin: string;
- headers?: Record<string, string | undefined>;
+ headers?: RequestHeaders;
} & (
| {
serviceToken: string;
@@ -56,7 +193,7 @@ export const loadProjectBundleByBuildId = async (
| { authToken: string }
)
): Promise<PublishedProjectBundle> => {
- const headers: Record<string, string | undefined> =
+ const headers: RequestHeaders =
"serviceToken" in params
? { Authorization: params.serviceToken }
: { "x-auth-token": params.authToken };
@@ -67,30 +204,24 @@ export const loadProjectBundleByBuildId = async (
}).query("build.loadProjectBundleByBuildId", {
buildId: params.buildId,
});
- return publishedProjectBundleSchema.parse(data);
+ return publishedProjectBundle.parse(data);
};
-export const loadProjectBundleByProjectId = async (params: {
- projectId: string;
- origin: string;
- authToken: string;
- headers?: Record<string, string | undefined>;
-}): Promise<PublishedProjectBundle> => {
+export const loadProjectBundleByProjectId = async (
+ params: AuthProjectParams
+): Promise<PublishedProjectBundle> => {
const data = await createAuthTrpcClient(params).query(
"build.loadProjectBundleByProjectId",
{
projectId: params.projectId,
}
);
- return publishedProjectBundleSchema.parse(data);
+ return publishedProjectBundle.parse(data);
};
-export const checkProjectBuildPermission = async (params: {
- projectId: string;
- origin: string;
- authToken: string;
- headers?: Record<string, string | undefined>;
-}): Promise<void> => {
+export const checkProjectBuildPermission = async (
+ params: AuthProjectParams
+): Promise<void> => {
await createAuthTrpcClient(params).query(
"build.checkProjectBuildPermission",
{
@@ -99,25 +230,76 @@ export const checkProjectBuildPermission = async (params: {
);
};
-export const importProjectBundle = async (params: {
- projectId: string;
- origin: string;
- authToken: string;
- data: PublishedProjectBundle;
- assetFiles?: AssetFileData[];
- ignoreVersionCheck?: boolean;
- headers?: Record<string, string | undefined>;
-}): Promise<ImportProjectBundleResult> => {
+const getUploadIdFromUrl = (uploadUrl: string | null) => {
+ if (uploadUrl === null) {
+ throw new Error("Project bundle upload did not return an upload URL.");
+ }
+
+ const { pathname } = new URL(uploadUrl);
+ const uploadId = pathname.split("/").filter(Boolean).at(-1);
+ if (uploadId === undefined) {
+ throw new Error("Project bundle upload did not return an upload id.");
+ }
+
+ return decodeURIComponent(uploadId);
+};
+
+const uploadProjectBundleData = async (
+ params: AuthProjectParams & {
+ data: PublishedProjectBundle;
+ }
+) => {
+ const { sourceOrigin } = parseBuilderUrl(params.origin);
+ const endpoint = new URL(stagedUploadPath, sourceOrigin);
+ const data = JSON.stringify(params.data);
+ if (new TextEncoder().encode(data).byteLength > maxProjectBundleSize) {
+ throw new Error(
+ `Project bundle is too large to import. Maximum size is ${formatMebibytes(maxProjectBundleSize)}.`
+ );
+ }
+ const file =
+ typeof Buffer === "undefined"
+ ? new Blob([data], { type: "application/json" })
+ : Buffer.from(data);
+
+ return await new Promise<string>((resolve, reject) => {
+ const upload = new Upload(file, {
+ endpoint: endpoint.href,
+ chunkSize: stagedUploadChunkSize,
+ retryDelays: [0, 1000],
+ removeFingerprintOnSuccess: true,
+ storeFingerprintForResuming: false,
+ headers: createHeadersObject({
+ ...params.headers,
+ "x-auth-token": params.authToken,
+ [stagedUploadProjectIdHeader]: params.projectId,
+ }),
+ metadata: {
+ projectId: params.projectId,
+ },
+ onError: reject,
+ onSuccess: () => resolve(getUploadIdFromUrl(upload.url)),
+ });
+ upload.start();
+ });
+};
+
+export const importProjectBundle = async (
+ params: AuthProjectParams & {
+ data: PublishedProjectBundle;
+ ignoreVersionCheck?: boolean;
+ }
+): Promise<ImportProjectBundleResult> => {
+ const uploadId = await uploadProjectBundleData(params);
const result = await createAuthTrpcClient(params).mutation(
"build.importProjectBundle",
{
projectId: params.projectId,
- data: params.data,
- assetFiles: params.assetFiles,
+ uploadId,
ignoreVersionCheck: params.ignoreVersionCheck,
}
);
- return importProjectBundleResultSchema.parse(result);
+ return importProjectBundleResult.parse(result);
};
// For easier detecting the builder URL
diff --git a/packages/plans/src/index.ts b/packages/plans/src/index.ts
index 0bceedf784..acd139397e 100644
--- a/packages/plans/src/index.ts
+++ b/packages/plans/src/index.ts
@@ -1,5 +1,5 @@
export {
- PlanFeaturesSchema,
+ planFeatures,
defaultPlanFeatures,
parsePlansEnv,
} from "./plan-features";
diff --git a/packages/plans/src/plan-client.server.ts b/packages/plans/src/plan-client.server.ts
index 1ce09f6890..51f33ea49f 100644
--- a/packages/plans/src/plan-client.server.ts
+++ b/packages/plans/src/plan-client.server.ts
@@ -1,7 +1,7 @@
import type { Client } from "@webstudio-is/postgrest/index.server";
import {
type PlanFeatures,
- PlanFeaturesSchema,
+ planFeatures,
defaultPlanFeatures,
parsePlansEnv,
type Purchase,
@@ -23,7 +23,7 @@ type PlanInfo = {
};
export const parseProductMeta = (meta: unknown): Partial<PlanFeatures> => {
- const result = PlanFeaturesSchema.partial().safeParse(meta);
+ const result = planFeatures.partial().safeParse(meta);
return result.success ? result.data : {};
};
diff --git a/packages/plans/src/plan-features.ts b/packages/plans/src/plan-features.ts
index 9122c06dc5..2397b01998 100644
--- a/packages/plans/src/plan-features.ts
+++ b/packages/plans/src/plan-features.ts
@@ -5,7 +5,7 @@ import { z } from "zod";
* (e.g. product.meta JSON blobs). Only known keys of the correct type
* are kept — anything else is silently stripped.
*/
-export const PlanFeaturesSchema = z.object({
+export const planFeatures = z.object({
canDownloadAssets: z.boolean(),
canRestoreBackups: z.boolean(),
allowAdditionalPermissions: z.boolean(),
@@ -23,10 +23,10 @@ export const PlanFeaturesSchema = z.object({
maxSeatsPerWorkspace: z.number().nonnegative(),
});
-export type PlanFeatures = z.infer<typeof PlanFeaturesSchema>;
+export type PlanFeatures = z.infer<typeof planFeatures>;
// Compile-time guard: all PlanFeatures values must be boolean or number.
-// If a new field with a different type is added to PlanFeaturesSchema, this line will error.
+// If a new field with a different type is added to planFeatures, this line will error.
type _AssertBooleanOrNumber =
PlanFeatures extends Record<string, boolean | number> ? true : never;
const _checkPlanFeaturesValueTypes: _AssertBooleanOrNumber = true;
@@ -57,7 +57,7 @@ export type Purchase = {
subscriptionId?: string;
};
-const PricesSchema = z.record(z.string(), z.string());
+const prices = z.record(z.string(), z.string());
/** A parsed plan entry with resolved features and price IDs keyed by billing cycle */
export type PlanConfig = {
@@ -69,7 +69,7 @@ export type PlanConfig = {
/**
* Parse the PLANS env variable (JSON array of {name, extends?, features, prices?}).
* - features is partial when extends is used; the parent plan fills in the rest.
- * - The final merged features are validated against the full PlanFeaturesSchema.
+ * - The final merged features are validated against the full planFeatures.
* - Invalid entries are skipped with a console.error.
* - An extends reference to an unknown plan name throws an error.
* Returns a Map of plan name → { name, features, prices }.
@@ -102,9 +102,9 @@ export const parsePlansEnv = (raw: string): Map<string, PlanConfig> => {
console.error("Invalid PLANS entry (extends must be a string):", item);
return [];
}
- const featuresResult = PlanFeaturesSchema.partial().safeParse(
- "features" in item ? item.features : {}
- );
+ const featuresResult = planFeatures
+ .partial()
+ .safeParse("features" in item ? item.features : {});
if (!featuresResult.success) {
console.error(
`Invalid PLANS entry "${item.name}" features:`,
@@ -112,7 +112,7 @@ export const parsePlansEnv = (raw: string): Map<string, PlanConfig> => {
);
return [];
}
- const pricesResult = PricesSchema.safeParse(
+ const pricesResult = prices.safeParse(
"prices" in item ? item.prices : {}
);
if (!pricesResult.success) {
@@ -150,7 +150,7 @@ export const parsePlansEnv = (raw: string): Map<string, PlanConfig> => {
entry.extends === undefined
? defaultPlanFeatures
: { ...defaultPlanFeatures, ...byName.get(entry.extends)! };
- const result = PlanFeaturesSchema.safeParse({
+ const result = planFeatures.safeParse({
...parentFeatures,
...entry.features,
});
diff --git a/packages/prisma-client/prisma/migrations/20220909124542_builds-data/migration.ts b/packages/prisma-client/prisma/migrations/20220909124542_builds-data/migration.ts
index 0d4d7c0aa3..190b1fcdae 100644
--- a/packages/prisma-client/prisma/migrations/20220909124542_builds-data/migration.ts
+++ b/packages/prisma-client/prisma/migrations/20220909124542_builds-data/migration.ts
@@ -1,9 +1,9 @@
import { PrismaClient, Prisma } from "./client";
import { z } from "zod";
-const TreeHistory = z.array(z.string());
+const treeHistory = z.array(z.string());
-const Page = z.object({
+const page = z.object({
id: z.string(),
name: z.string(),
path: z.string(),
@@ -12,9 +12,9 @@ const Page = z.object({
treeId: z.string(),
});
-const Pages = z.object({
- homePage: Page,
- pages: z.array(Page),
+const pages = z.object({
+ homePage: page,
+ pages: z.array(page),
});
export default () => {
@@ -34,16 +34,16 @@ export default () => {
(project) =>
project.devTreeId === tree.id ||
project.prodTreeId === tree.id ||
- TreeHistory.parse(JSON.parse(project.prodTreeIdHistory)).includes(
- tree.id
- )
+ treeHistory
+ .parse(JSON.parse(project.prodTreeIdHistory))
+ .includes(tree.id)
);
if (project === undefined) {
continue;
}
- const pages = Pages.parse({
+ const pages = pages.parse({
homePage: {
id: crypto.randomUUID(),
name: "Home",
diff --git a/packages/prisma-client/prisma/migrations/20220915144008_breakpoints-build_data/migration.ts b/packages/prisma-client/prisma/migrations/20220915144008_breakpoints-build_data/migration.ts
index a0b07eb61f..0e3321a438 100644
--- a/packages/prisma-client/prisma/migrations/20220915144008_breakpoints-build_data/migration.ts
+++ b/packages/prisma-client/prisma/migrations/20220915144008_breakpoints-build_data/migration.ts
@@ -1,7 +1,7 @@
import { PrismaClient } from "./client";
import { z } from "zod";
-const Page = z.object({
+const page = z.object({
id: z.string(),
name: z.string(),
path: z.string(),
@@ -10,9 +10,9 @@ const Page = z.object({
treeId: z.string(),
});
-const Pages = z.object({
- homePage: Page,
- pages: z.array(Page),
+const pages = z.object({
+ homePage: page,
+ pages: z.array(page),
});
export default () => {
@@ -27,7 +27,7 @@ export default () => {
const buildsParsed = builds.map((build) => ({
id: build.id,
- pages: Pages.parse(JSON.parse(build.pages)),
+ pages: pages.parse(JSON.parse(build.pages)),
}));
// await Promise.all(
diff --git a/packages/prisma-client/prisma/migrations/20221201075120_user-props/migration.ts b/packages/prisma-client/prisma/migrations/20221201075120_user-props/migration.ts
index c6d8f0ee4d..20422d6a12 100644
--- a/packages/prisma-client/prisma/migrations/20221201075120_user-props/migration.ts
+++ b/packages/prisma-client/prisma/migrations/20221201075120_user-props/migration.ts
@@ -7,7 +7,7 @@ const baseUserProps = {
required: z.optional(z.boolean()),
};
-export const UserDbProp = z.discriminatedUnion("type", [
+export const userDbProp = z.discriminatedUnion("type", [
z.object({
...baseUserProps,
type: z.literal("number"),
@@ -31,10 +31,10 @@ export const UserDbProp = z.discriminatedUnion("type", [
}),
]);
-const UserDbProps = z.array(UserDbProp);
-type UserDbProp = z.infer<typeof UserDbProp>;
+const userDbProps = z.array(userDbProp);
+type UserDbProp = z.infer<typeof userDbProp>;
-const OutdatedProp = z.object({
+const outdatedProp = z.object({
...baseUserProps,
value: z.optional(z.union([z.string(), z.number(), z.boolean()])),
asset_id: z.optional(z.string()),
@@ -42,7 +42,7 @@ const OutdatedProp = z.object({
type: z.optional(z.string()),
});
-const OutdatedProps = z.array(OutdatedProp);
+const outdatedProps = z.array(outdatedProp);
export default () => {
const client = new PrismaClient({
@@ -63,7 +63,7 @@ export default () => {
for (const instanceProps of allInstanceProps) {
const rawProps = JSON.parse(instanceProps.props);
- const props = OutdatedProps.parse(rawProps);
+ const props = outdatedProps.parse(rawProps);
const newProps: UserDbProp[] = [];
@@ -71,7 +71,7 @@ export default () => {
for (const prop of props) {
if (prop.type != null) {
- const dbProp = UserDbProp.parse(prop);
+ const dbProp = userDbProp.parse(prop);
newProps.push(dbProp);
continue;
}
@@ -143,7 +143,7 @@ export default () => {
if (need_update) {
await prisma.instanceProps.update({
where: { id: instanceProps.id },
- data: { props: JSON.stringify(UserDbProps.parse(newProps)) },
+ data: { props: JSON.stringify(userDbProps.parse(newProps)) },
});
}
}
diff --git a/packages/prisma-client/prisma/migrations/20230228222541_convert-image-style/migration.ts b/packages/prisma-client/prisma/migrations/20230228222541_convert-image-style/migration.ts
index f5e3af32e1..536d95edae 100644
--- a/packages/prisma-client/prisma/migrations/20230228222541_convert-image-style/migration.ts
+++ b/packages/prisma-client/prisma/migrations/20230228222541_convert-image-style/migration.ts
@@ -1,74 +1,74 @@
import { z } from "zod";
import { PrismaClient } from "./client";
-const Unit = z.string();
+const unit = z.string();
-type Unit = z.infer<typeof Unit>;
+type Unit = z.infer<typeof unit>;
-const UnitValue = z.object({
+const unitValue = z.object({
type: z.literal("unit"),
- unit: Unit,
+ unit: unit,
value: z.number(),
});
-type UnitValue = z.infer<typeof UnitValue>;
+type UnitValue = z.infer<typeof unitValue>;
-const KeywordValue = z.object({
+const keywordValue = z.object({
type: z.literal("keyword"),
// @todo use exact type
value: z.string(),
});
-type KeywordValue = z.infer<typeof KeywordValue>;
+type KeywordValue = z.infer<typeof keywordValue>;
/**
* Valid unparsed css value
**/
-const UnparsedValue = z.object({
+const unparsedValue = z.object({
type: z.literal("unparsed"),
value: z.string(),
});
-const FontFamilyValue = z.object({
+const fontFamilyValue = z.object({
type: z.literal("fontFamily"),
value: z.array(z.string()),
});
-type FontFamilyValue = z.infer<typeof FontFamilyValue>;
+type FontFamilyValue = z.infer<typeof fontFamilyValue>;
-const RgbValue = z.object({
+const rgbValue = z.object({
type: z.literal("rgb"),
r: z.number(),
g: z.number(),
b: z.number(),
alpha: z.number(),
});
-type RgbValue = z.infer<typeof RgbValue>;
+type RgbValue = z.infer<typeof rgbValue>;
-const ImageValue = z.object({
+const imageValue = z.object({
type: z.literal("image"),
value: z.array(z.object({ type: z.literal("asset"), value: z.unknown() })),
});
-type ImageValue = z.infer<typeof ImageValue>;
+type ImageValue = z.infer<typeof imageValue>;
// We want to be able to render the invalid value
// and show it is invalid visually, without saving it to the db
-const InvalidValue = z.object({
+const invalidValue = z.object({
type: z.literal("invalid"),
value: z.string(),
});
-type InvalidValue = z.infer<typeof InvalidValue>;
+type InvalidValue = z.infer<typeof invalidValue>;
-const UnsetValue = z.object({
+const unsetValue = z.object({
type: z.literal("unset"),
value: z.literal(""),
});
-type UnsetValue = z.infer<typeof UnsetValue>;
+type UnsetValue = z.infer<typeof unsetValue>;
-const ArrayValue = z.object({
+const arrayValue = z.object({
type: z.literal("array"),
- value: z.array(z.union([UnitValue, KeywordValue, UnparsedValue, ImageValue])),
+ value: z.array(z.union([unitValue, keywordValue, unparsedValue, imageValue])),
});
-type ArrayValue = z.infer<typeof ArrayValue>;
+type ArrayValue = z.infer<typeof arrayValue>;
const validStaticValueTypes = [
"unit",
@@ -84,44 +84,44 @@ const validStaticValueTypes = [
* Shared zod types with DB types.
* ImageValue in DB has a different type
*/
-const SharedStaticStyleValue = z.union([
- UnitValue,
- KeywordValue,
- FontFamilyValue,
- RgbValue,
- UnparsedValue,
- ArrayValue,
+const sharedStaticStyleValue = z.union([
+ unitValue,
+ keywordValue,
+ fontFamilyValue,
+ rgbValue,
+ unparsedValue,
+ arrayValue,
]);
-const ValidStaticStyleValue = z.union([ImageValue, SharedStaticStyleValue]);
+const validStaticStyleValue = z.union([imageValue, sharedStaticStyleValue]);
-type ValidStaticStyleValue = z.infer<typeof ValidStaticStyleValue>;
+type ValidStaticStyleValue = z.infer<typeof validStaticStyleValue>;
-const VarValue = z.object({
+const varValue = z.object({
type: z.literal("var"),
value: z.string(),
- fallbacks: z.array(ValidStaticStyleValue),
+ fallbacks: z.array(validStaticStyleValue),
});
-type VarValue = z.infer<typeof VarValue>;
+type VarValue = z.infer<typeof varValue>;
-const StyleValue = z.union([
- ValidStaticStyleValue,
- InvalidValue,
- UnsetValue,
- VarValue,
+const styleValue = z.union([
+ validStaticStyleValue,
+ invalidValue,
+ unsetValue,
+ varValue,
]);
/**
* Shared types with DB types
*/
-const SharedStyleValue = z.union([
- SharedStaticStyleValue,
- InvalidValue,
- UnsetValue,
- VarValue,
+const sharedStyleValue = z.union([
+ sharedStaticStyleValue,
+ invalidValue,
+ unsetValue,
+ varValue,
]);
-const StoredImageValue = z.object({
+const storedImageValue = z.object({
type: z.literal("image"),
value: z.union([
z.object({ type: z.literal("asset"), value: z.string() }),
@@ -129,15 +129,15 @@ const StoredImageValue = z.object({
]),
});
-const StoredStyleDecl = z.object({
+const storedStyleDecl = z.object({
styleSourceId: z.string(),
breakpointId: z.string(),
// @todo can't figure out how to make property to be enum
property: z.string(),
- value: z.union([StoredImageValue, SharedStyleValue]),
+ value: z.union([storedImageValue, sharedStyleValue]),
});
-type StoredStyleDecl = z.infer<typeof StoredStyleDecl>;
+type StoredStyleDecl = z.infer<typeof storedStyleDecl>;
// NOTE ON IMPORTS:
//
diff --git a/packages/prisma-client/prisma/migrations/20230301134408_convert-background-to-layers/migration.ts b/packages/prisma-client/prisma/migrations/20230301134408_convert-background-to-layers/migration.ts
index 506fb0ac8f..246b61924e 100644
--- a/packages/prisma-client/prisma/migrations/20230301134408_convert-background-to-layers/migration.ts
+++ b/packages/prisma-client/prisma/migrations/20230301134408_convert-background-to-layers/migration.ts
@@ -1,129 +1,129 @@
import { z } from "zod";
import { PrismaClient } from "./client";
-const Unit = z.string();
+const unit = z.string();
-type Unit = z.infer<typeof Unit>;
+type Unit = z.infer<typeof unit>;
-const UnitValue = z.object({
+const unitValue = z.object({
type: z.literal("unit"),
- unit: Unit,
+ unit: unit,
value: z.number(),
});
-type UnitValue = z.infer<typeof UnitValue>;
+type UnitValue = z.infer<typeof unitValue>;
-const KeywordValue = z.object({
+const keywordValue = z.object({
type: z.literal("keyword"),
// @todo use exact type
value: z.string(),
});
-type KeywordValue = z.infer<typeof KeywordValue>;
+type KeywordValue = z.infer<typeof keywordValue>;
/**
* Valid unparsed css value
**/
-const UnparsedValue = z.object({
+const unparsedValue = z.object({
type: z.literal("unparsed"),
value: z.string(),
});
-const FontFamilyValue = z.object({
+const fontFamilyValue = z.object({
type: z.literal("fontFamily"),
value: z.array(z.string()),
});
-type FontFamilyValue = z.infer<typeof FontFamilyValue>;
+type FontFamilyValue = z.infer<typeof fontFamilyValue>;
-const RgbValue = z.object({
+const rgbValue = z.object({
type: z.literal("rgb"),
r: z.number(),
g: z.number(),
b: z.number(),
alpha: z.number(),
});
-type RgbValue = z.infer<typeof RgbValue>;
+type RgbValue = z.infer<typeof rgbValue>;
-const ImageValue = z.object({
+const imageValue = z.object({
type: z.literal("image"),
value: z.object({ type: z.literal("asset"), value: z.unknown() }),
});
-type ImageValue = z.infer<typeof ImageValue>;
+type ImageValue = z.infer<typeof imageValue>;
// We want to be able to render the invalid value
// and show it is invalid visually, without saving it to the db
-const InvalidValue = z.object({
+const invalidValue = z.object({
type: z.literal("invalid"),
value: z.string(),
});
-type InvalidValue = z.infer<typeof InvalidValue>;
+type InvalidValue = z.infer<typeof invalidValue>;
-const UnsetValue = z.object({
+const unsetValue = z.object({
type: z.literal("unset"),
value: z.literal(""),
});
-type UnsetValue = z.infer<typeof UnsetValue>;
+type UnsetValue = z.infer<typeof unsetValue>;
/**
* Shared zod types with DB types.
* ImageValue in DB has a different type
*/
-const SharedStaticStyleValue = z.union([
- UnitValue,
- KeywordValue,
- FontFamilyValue,
- RgbValue,
- UnparsedValue,
+const sharedStaticStyleValue = z.union([
+ unitValue,
+ keywordValue,
+ fontFamilyValue,
+ rgbValue,
+ unparsedValue,
]);
-const ValidStaticStyleValue = z.union([ImageValue, SharedStaticStyleValue]);
+const validStaticStyleValue = z.union([imageValue, sharedStaticStyleValue]);
-type ValidStaticStyleValue = z.infer<typeof ValidStaticStyleValue>;
+type ValidStaticStyleValue = z.infer<typeof validStaticStyleValue>;
-const VarValue = z.object({
+const varValue = z.object({
type: z.literal("var"),
value: z.string(),
- fallbacks: z.array(ValidStaticStyleValue),
+ fallbacks: z.array(validStaticStyleValue),
});
-type VarValue = z.infer<typeof VarValue>;
+type VarValue = z.infer<typeof varValue>;
/**
* Shared types with DB types
*/
-const SharedStyleValue = z.union([
- SharedStaticStyleValue,
- InvalidValue,
- UnsetValue,
- VarValue,
+const sharedStyleValue = z.union([
+ sharedStaticStyleValue,
+ invalidValue,
+ unsetValue,
+ varValue,
]);
-const StoredImageValue = z.object({
+const storedImageValue = z.object({
type: z.literal("image"),
value: z.object({ type: z.literal("asset"), value: z.string() }),
});
-const StoredLayersValue = z.object({
+const storedLayersValue = z.object({
type: z.literal("layers"),
value: z.array(
z.union([
- UnitValue,
- KeywordValue,
- UnparsedValue,
- StoredImageValue,
- InvalidValue,
+ unitValue,
+ keywordValue,
+ unparsedValue,
+ storedImageValue,
+ invalidValue,
])
),
});
-export const StoredStyleDecl = z.object({
+export const storedStyleDecl = z.object({
styleSourceId: z.string(),
breakpointId: z.string(),
// @todo can't figure out how to make property to be enum
property: z.string(),
- value: z.union([StoredImageValue, StoredLayersValue, SharedStyleValue]),
+ value: z.union([storedImageValue, storedLayersValue, sharedStyleValue]),
});
-type StoredStyleDecl = z.infer<typeof StoredStyleDecl>;
+type StoredStyleDecl = z.infer<typeof storedStyleDecl>;
const layeredBackgroundProps = [
"backgroundAttachment",
diff --git a/packages/project-build/src/schema.ts b/packages/project-build/src/schema.ts
index 0398676751..742b778747 100644
--- a/packages/project-build/src/schema.ts
+++ b/packages/project-build/src/schema.ts
@@ -1,22 +1,22 @@
import {
- Breakpoint,
- DataSource,
- Deployment,
- Instance,
- Prop,
- Resource,
- StyleDecl,
- StyleSource,
- StyleSourceSelection,
+ breakpoint,
+ dataSource,
+ deployment,
+ instance,
+ prop,
+ resource,
+ styleDecl,
+ styleSource,
+ styleSourceSelection,
} from "@webstudio-is/sdk/schema";
import {
- SerializedPagesSchema,
+ serializedPages,
type SerializedPages,
} from "@webstudio-is/project-migrations/pages";
import { z } from "zod";
import type { Build } from "./types";
-const entrySchema = <Value extends z.ZodTypeAny>(value: Value) =>
+const entry = <Value extends z.ZodTypeAny>(value: Value) =>
z.tuple([z.string(), value]);
type SchemaShape<Value extends object> = {
@@ -33,19 +33,19 @@ const serializedBuildShape: SchemaShape<SerializedBuild> = {
version: z.number(),
createdAt: z.string(),
updatedAt: z.string(),
- pages: SerializedPagesSchema,
- breakpoints: z.array(entrySchema(Breakpoint)),
- styles: z.array(entrySchema(StyleDecl)),
- styleSources: z.array(entrySchema(StyleSource)),
- styleSourceSelections: z.array(entrySchema(StyleSourceSelection)),
- props: z.array(entrySchema(Prop)),
- instances: z.array(entrySchema(Instance)),
- dataSources: z.array(entrySchema(DataSource)),
- resources: z.array(entrySchema(Resource)),
- deployment: Deployment.optional(),
+ pages: serializedPages,
+ breakpoints: z.array(entry(breakpoint)),
+ styles: z.array(entry(styleDecl)),
+ styleSources: z.array(entry(styleSource)),
+ styleSourceSelections: z.array(entry(styleSourceSelection)),
+ props: z.array(entry(prop)),
+ instances: z.array(entry(instance)),
+ dataSources: z.array(entry(dataSource)),
+ resources: z.array(entry(resource)),
+ deployment: deployment.optional(),
};
// Canonical project-build schema entrypoint for API-facing serialized builds.
// API packages compose this schema; they should not copy or maintain it.
-export const SerializedBuildSchema: z.ZodObject<typeof serializedBuildShape> =
+export const serializedBuild: z.ZodObject<typeof serializedBuildShape> =
z.object(serializedBuildShape);
diff --git a/packages/project-build/src/shared/marketplace.ts b/packages/project-build/src/shared/marketplace.ts
index dafb412a11..ed6c14d281 100644
--- a/packages/project-build/src/shared/marketplace.ts
+++ b/packages/project-build/src/shared/marketplace.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
-export const MarketplaceProduct = z.object({
+export const marketplaceProduct = z.object({
category: z.union([
z.literal("sectionTemplates"),
z.literal("pageTemplates"),
@@ -17,7 +17,7 @@ export const MarketplaceProduct = z.object({
issues: z.union([z.string().max(200).url().trim().optional(), z.literal("")]),
description: z.string().trim().min(10).max(1000),
});
-export type MarketplaceProduct = z.infer<typeof MarketplaceProduct>;
+export type MarketplaceProduct = z.infer<typeof marketplaceProduct>;
export const marketplaceCategories = new Map<
MarketplaceProduct["category"],
diff --git a/packages/project-build/src/shared/pages-utils.ts b/packages/project-build/src/shared/pages-utils.ts
index df7cfaa70a..a38732f555 100644
--- a/packages/project-build/src/shared/pages-utils.ts
+++ b/packages/project-build/src/shared/pages-utils.ts
@@ -3,8 +3,8 @@ import {
type Pages,
type Folder,
ROOT_FOLDER_ID,
- Instance,
- DataSource,
+ type Instance,
+ type DataSource,
} from "@webstudio-is/sdk";
export const createRootFolder = (
diff --git a/packages/project-migrations/src/pages.ts b/packages/project-migrations/src/pages.ts
index aa7d6ea0da..cb588896f2 100644
--- a/packages/project-migrations/src/pages.ts
+++ b/packages/project-migrations/src/pages.ts
@@ -1,11 +1,15 @@
import {
- CompilerSettings,
- Folder,
- Page,
- PageTemplate,
- ProjectMeta,
- PageRedirect,
- Pages,
+ compilerSettings,
+ type Folder,
+ folder,
+ type Page,
+ page,
+ type PageTemplate,
+ pageTemplate,
+ projectMeta,
+ pageRedirect,
+ type Pages,
+ pages,
} from "@webstudio-is/sdk/schema";
import { isRootFolder, ROOT_FOLDER_ID } from "@webstudio-is/sdk";
import { z } from "zod";
@@ -28,21 +32,21 @@ export type SerializedPages = Omit<
folders: Folder[];
};
-export const SerializedPagesSchema: z.ZodType<
+export const serializedPages: z.ZodType<
SerializedPages,
z.ZodTypeDef,
unknown
> = z.object({
- meta: ProjectMeta.optional(),
- compiler: CompilerSettings.optional(),
- redirects: z.array(PageRedirect).optional(),
+ meta: projectMeta.optional(),
+ compiler: compilerSettings.optional(),
+ redirects: z.array(pageRedirect).optional(),
homePageId: z.string(),
rootFolderId: z.string(),
- pages: z.array(Page),
+ pages: z.array(page),
pageTemplates: z
- .union([z.array(PageTemplate), z.record(PageTemplate)])
+ .union([z.array(pageTemplate), z.record(pageTemplate)])
.optional(),
- folders: z.array(Folder),
+ folders: z.array(folder),
});
type MigratablePages = Omit<Pages, "pages" | "pageTemplates" | "folders"> & {
@@ -110,8 +114,8 @@ const removeOrphanFolderChildren = (
return nextFolders;
};
-export const serializePages = (pages: Pages): SerializedPages => {
- const parsedPages = Pages.parse(pages);
+export const serializePages = (pagesData: Pages): SerializedPages => {
+ const parsedPages = pages.parse(pagesData);
return {
meta: parsedPages.meta,
compiler: parsedPages.compiler,
@@ -127,14 +131,14 @@ export const serializePages = (pages: Pages): SerializedPages => {
};
};
-export const migratePages = (pages: unknown): Pages => {
+export const migratePages = (pagesData: unknown): Pages => {
if (
- isSerializedPages(pages) &&
- pages.pages instanceof Map &&
- pages.folders instanceof Map
+ isSerializedPages(pagesData) &&
+ pagesData.pages instanceof Map &&
+ pagesData.folders instanceof Map
) {
- const currentPages = pages as Pages;
- const result = Pages.safeParse(currentPages);
+ const currentPages = pagesData as Pages;
+ const result = pages.safeParse(currentPages);
if (result.success && currentPages.pageTemplates !== undefined) {
return currentPages;
}
@@ -148,34 +152,34 @@ export const migratePages = (pages: unknown): Pages => {
};
}
- if (isSerializedPages(pages)) {
- const nextPages = toMap<Page>(pages.pages, normalizePage);
- const nextFolders = toMap<Folder>(pages.folders);
+ if (isSerializedPages(pagesData)) {
+ const nextPages = toMap<Page>(pagesData.pages, normalizePage);
+ const nextFolders = toMap<Folder>(pagesData.folders);
return {
- meta: pages.meta,
- compiler: pages.compiler,
- redirects: pages.redirects,
- homePageId: pages.homePageId,
- rootFolderId: pages.rootFolderId,
+ meta: pagesData.meta,
+ compiler: pagesData.compiler,
+ redirects: pagesData.redirects,
+ homePageId: pagesData.homePageId,
+ rootFolderId: pagesData.rootFolderId,
pages: nextPages,
pageTemplates:
- pages.pageTemplates === undefined
+ pagesData.pageTemplates === undefined
? new Map()
- : toMap<PageTemplate>(pages.pageTemplates),
+ : toMap<PageTemplate>(pagesData.pageTemplates),
folders: removeOrphanFolderChildren(nextPages, nextFolders),
};
}
- if (isLegacyPages(pages) === false) {
+ if (isLegacyPages(pagesData) === false) {
throw new Error("Pages data has unsupported shape.");
}
const homePage: Page = {
- ...normalizePage(pages.homePage),
+ ...normalizePage(pagesData.homePage),
path: "",
};
const nextPages: Pages["pages"] = new Map([[homePage.id, homePage]]);
- for (const page of pages.pages) {
+ for (const page of pagesData.pages) {
if (page.id === homePage.id) {
continue;
}
@@ -183,13 +187,13 @@ export const migratePages = (pages: unknown): Pages => {
}
const nextFolders: Pages["folders"] = new Map();
- for (const folder of pages.folders ?? []) {
+ for (const folder of pagesData.folders ?? []) {
nextFolders.set(folder.id, { ...folder, children: [...folder.children] });
}
const rootFolder =
Array.from(nextFolders.values()).find(isRootFolder) ??
- pages.folders?.[0] ??
+ pagesData.folders?.[0] ??
({
id: ROOT_FOLDER_ID,
name: "Root",
@@ -218,7 +222,7 @@ export const migratePages = (pages: unknown): Pages => {
const referencedIds = new Set(
Array.from(nextFolders.values()).flatMap((folder) => folder.children)
);
- for (const page of pages.pages) {
+ for (const page of pagesData.pages) {
if (page.id !== homePage.id && referencedIds.has(page.id) === false) {
nextRootFolder.children.push(page.id);
referencedIds.add(page.id);
@@ -226,9 +230,9 @@ export const migratePages = (pages: unknown): Pages => {
}
return {
- meta: pages.meta,
- compiler: pages.compiler,
- redirects: pages.redirects,
+ meta: pagesData.meta,
+ compiler: pagesData.compiler,
+ redirects: pagesData.redirects,
homePageId: homePage.id,
rootFolderId: rootFolder.id,
pages: nextPages,
diff --git a/packages/project/src/content-mode-permissions.ts b/packages/project/src/content-mode-permissions.ts
index 3c7445c91c..9b4595aca9 100644
--- a/packages/project/src/content-mode-permissions.ts
+++ b/packages/project/src/content-mode-permissions.ts
@@ -1,12 +1,12 @@
import type { Patch } from "immer";
import {
- Instance as InstanceSchema,
- InstanceChild as InstanceChildSchema,
- Prop as PropSchema,
- StyleDecl as StyleDeclSchema,
- StyleSource as StyleSourceSchema,
- StyleSourceSelection as StyleSourceSelectionSchema,
- PagePath,
+ instance,
+ instanceChild,
+ prop,
+ styleDecl,
+ styleSource,
+ styleSourceSelection,
+ pagePath,
blockComponent,
blockTemplateComponent,
getHtmlTagsFromProps,
@@ -71,7 +71,7 @@ const contentModePageFields = new Set(["name", "path", "title"]);
export const isContentModePagePath = (value: unknown) =>
typeof value === "string" &&
- (value === "" || PagePath.safeParse(value).success) &&
+ (value === "" || pagePath.safeParse(value).success) &&
isPathnamePattern(value) === false &&
value.includes(":") === false &&
value.includes("*") === false;
@@ -389,16 +389,16 @@ const isContentModePropPatchValue = ({
expectedPropId: Prop["id"];
value: unknown;
}) => {
- const prop = PropSchema.safeParse(value);
- if (prop.success === false) {
+ const parsedProp = prop.safeParse(value);
+ if (parsedProp.success === false) {
return false;
}
- if (prop.data.id !== expectedPropId) {
+ if (parsedProp.data.id !== expectedPropId) {
return false;
}
- const instance = capabilities.instances.get(prop.data.instanceId);
+ const instance = capabilities.instances.get(parsedProp.data.instanceId);
if (instance === undefined) {
return false;
}
@@ -409,7 +409,7 @@ const isContentModePropPatchValue = ({
return isContentModePropForInstance({
capabilities,
instance,
- prop: prop.data,
+ prop: parsedProp.data,
});
};
@@ -427,8 +427,11 @@ const validatePropPatch = (
}
if (patch.op === "remove" && patch.path.length === 1) {
- const prop = capabilities.props.get(propId);
- if (prop && context.removedEditableInstanceIds.has(prop.instanceId)) {
+ const existingProp = capabilities.props.get(propId);
+ if (
+ existingProp &&
+ context.removedEditableInstanceIds.has(existingProp.instanceId)
+ ) {
capabilities.editablePropIds.delete(propId);
capabilities.props.delete(propId);
return { success: true };
@@ -441,15 +444,18 @@ const validatePropPatch = (
capabilities.props.delete(propId);
return { success: true };
}
- const prop = capabilities.props.get(propId);
+ const existingProp = capabilities.props.get(propId);
if (
- prop &&
+ existingProp &&
patch.path.length === 2 &&
patch.path[1] === "value" &&
(patch.op === "add" || patch.op === "replace") &&
- PropSchema.safeParse({ ...prop, value: patch.value }).success
+ prop.safeParse({ ...existingProp, value: patch.value }).success
) {
- capabilities.props.set(propId, { ...prop, value: patch.value } as Prop);
+ capabilities.props.set(propId, {
+ ...existingProp,
+ value: patch.value,
+ } as Prop);
return { success: true };
}
}
@@ -534,7 +540,7 @@ const hasOnlyContentModePageMeta = (meta: Record<string, unknown>) => {
};
const isInstanceChild = (value: unknown) =>
- InstanceChildSchema.safeParse(value).success;
+ instanceChild.safeParse(value).success;
const isInstanceChildren = (value: unknown) =>
Array.isArray(value) && value.every(isInstanceChild);
@@ -784,11 +790,11 @@ const validateInstancePatch = (
}
if (patch.path.length === 1 && patch.op === "replace") {
- const instance = InstanceSchema.safeParse(patch.value);
+ const parsedInstance = instance.safeParse(patch.value);
if (
- instance.success &&
- instance.data.id === instanceId &&
- hasOnlyAllowedContentModeChildReferences(context, instance.data)
+ parsedInstance.success &&
+ parsedInstance.data.id === instanceId &&
+ hasOnlyAllowedContentModeChildReferences(context, parsedInstance.data)
) {
return context.editableInstanceIds.has(instanceId)
? { success: true }
@@ -804,16 +810,16 @@ const validateInstancePatch = (
patch.op === "add" &&
context.addedInstanceIds.has(instanceId)
) {
- const instance = InstanceSchema.safeParse(patch.value);
+ const parsedInstance = instance.safeParse(patch.value);
if (
- instance.success &&
- instance.data.id === instanceId &&
+ parsedInstance.success &&
+ parsedInstance.data.id === instanceId &&
context.editableInstanceIds.has(instanceId) &&
- hasOnlyAllowedContentModeChildReferences(context, instance.data)
+ hasOnlyAllowedContentModeChildReferences(context, parsedInstance.data)
) {
return { success: true };
}
- if (instance.success && instance.data.id === instanceId) {
+ if (parsedInstance.success && parsedInstance.data.id === instanceId) {
return {
success: false,
error: "Instance patch is outside content roots.",
@@ -848,13 +854,13 @@ const validateInstancePatchShape = (
}
if (patch.path.length === 1 && patch.op === "replace") {
- const instance = InstanceSchema.safeParse(patch.value);
+ const parsedInstance = instance.safeParse(patch.value);
const currentInstance = capabilities.instances.get(instanceId);
if (
- instance.success &&
- instance.data.id === instanceId &&
+ parsedInstance.success &&
+ parsedInstance.data.id === instanceId &&
currentInstance !== undefined &&
- hasSameInstanceMetadata(currentInstance, instance.data)
+ hasSameInstanceMetadata(currentInstance, parsedInstance.data)
) {
return { success: true };
}
@@ -865,8 +871,8 @@ const validateInstancePatchShape = (
patch.op === "add" &&
capabilities.instances.has(instanceId) === false
) {
- const instance = InstanceSchema.safeParse(patch.value);
- if (instance.success && instance.data.id === instanceId) {
+ const parsedInstance = instance.safeParse(patch.value);
+ if (parsedInstance.success && parsedInstance.data.id === instanceId) {
return { success: true };
}
}
@@ -923,7 +929,7 @@ const validateStyleSourceSelectionPatch = (
};
}
- const selection = StyleSourceSelectionSchema.safeParse(patch.value);
+ const selection = styleSourceSelection.safeParse(patch.value);
if (selection.success === false) {
return {
success: false,
@@ -1125,11 +1131,11 @@ const validateStyleSourcePatch = (
};
}
- const styleSource = StyleSourceSchema.safeParse(patch.value);
+ const parsedStyleSource = styleSource.safeParse(patch.value);
if (
- styleSource.success === false ||
- styleSource.data.type !== "local" ||
- styleSource.data.id !== styleSourceId
+ parsedStyleSource.success === false ||
+ parsedStyleSource.data.type !== "local" ||
+ parsedStyleSource.data.id !== styleSourceId
) {
return {
success: false,
@@ -1138,7 +1144,7 @@ const validateStyleSourcePatch = (
}
context.addedLocalStyleSourceIds.add(styleSourceId);
- context.capabilities.styleSources.set(styleSourceId, styleSource.data);
+ context.capabilities.styleSources.set(styleSourceId, parsedStyleSource.data);
return { success: true };
};
@@ -1252,12 +1258,13 @@ const validateStylePatch = (
};
}
- const styleDecl = StyleDeclSchema.safeParse(patch.value);
+ const parsedStyleDecl = styleDecl.safeParse(patch.value);
if (
- styleDecl.success === false ||
- getStyleDeclKey(styleDecl.data as StyleDecl) !== styleDeclKey ||
- context.selectedLocalStyleSourceIds.has(styleDecl.data.styleSourceId) ===
- false
+ parsedStyleDecl.success === false ||
+ getStyleDeclKey(parsedStyleDecl.data as StyleDecl) !== styleDeclKey ||
+ context.selectedLocalStyleSourceIds.has(
+ parsedStyleDecl.data.styleSourceId
+ ) === false
) {
return {
success: false,
@@ -1267,7 +1274,8 @@ const validateStylePatch = (
}
if (
context.capabilities.breakpoints !== undefined &&
- context.capabilities.breakpoints.has(styleDecl.data.breakpointId) === false
+ context.capabilities.breakpoints.has(parsedStyleDecl.data.breakpointId) ===
+ false
) {
return {
success: false,
@@ -1276,8 +1284,8 @@ const validateStylePatch = (
};
}
- context.styledLocalStyleSourceIds.add(styleDecl.data.styleSourceId);
- context.capabilities.styles.set(styleDeclKey, styleDecl.data);
+ context.styledLocalStyleSourceIds.add(parsedStyleDecl.data.styleSourceId);
+ context.capabilities.styles.set(styleDeclKey, parsedStyleDecl.data);
return { success: true };
};
diff --git a/packages/project/src/db/build-patch-core.ts b/packages/project/src/db/build-patch-core.ts
index 31801cac22..dee6661f71 100644
--- a/packages/project/src/db/build-patch-core.ts
+++ b/packages/project/src/db/build-patch-core.ts
@@ -1,25 +1,35 @@
import { applyPatches, enableMapSet, enablePatches, type Patch } from "immer";
import {
- Breakpoints,
+ type Breakpoints,
+ breakpoints,
type Breakpoint,
- DataSources,
+ type DataSources,
+ dataSources,
type DataSource,
- Instances,
+ type Instances,
+ instances,
type Instance,
- Pages,
- Props,
+ type Pages,
+ pages,
+ type Props,
+ props,
type Prop,
- Resources,
+ type Resources,
+ resources,
type Resource,
- StyleSourceSelections,
- StyleSources,
+ type StyleSourceSelections,
+ styleSourceSelections,
+ type StyleSources,
+ styleSources,
type StyleSource,
- Styles,
+ type Styles,
+ styles,
getHomePage,
} from "@webstudio-is/sdk";
import {
findCycles,
- MarketplaceProduct,
+ type MarketplaceProduct,
+ marketplaceProduct,
parsePages,
serializePages,
parseStyleSourceSelections,
@@ -295,68 +305,68 @@ export const createBuildPatchUpdate = async ({
};
if (buildData.pages) {
- const pages = buildData.pages;
- update.pages = serializePages(Pages.parse(pages));
+ const pagesData = buildData.pages;
+ update.pages = serializePages(pages.parse(pagesData));
}
if (buildData.breakpoints) {
- const breakpoints = buildData.breakpoints;
- validateTouchedMap(Breakpoints, breakpoints, touchedBreakpoints);
- update.breakpoints = serializeData<Breakpoint>(breakpoints);
+ const breakpointsData = buildData.breakpoints;
+ validateTouchedMap(breakpoints, breakpointsData, touchedBreakpoints);
+ update.breakpoints = serializeData<Breakpoint>(breakpointsData);
}
if (buildData.instances) {
- const instances = buildData.instances;
- validateTouchedMap(Instances, instances, touchedInstances);
- update.instances = serializeData<Instance>(instances);
+ const instancesData = buildData.instances;
+ validateTouchedMap(instances, instancesData, touchedInstances);
+ update.instances = serializeData<Instance>(instancesData);
}
if (buildData.props) {
- const props = buildData.props;
- validateTouchedMap(Props, props, touchedProps);
- update.props = serializeData<Prop>(props);
+ const propsData = buildData.props;
+ validateTouchedMap(props, propsData, touchedProps);
+ update.props = serializeData<Prop>(propsData);
}
if (buildData.dataSources) {
- const dataSources = buildData.dataSources;
- validateTouchedMap(DataSources, dataSources, touchedDataSources);
- update.dataSources = serializeData<DataSource>(dataSources);
+ const dataSourcesData = buildData.dataSources;
+ validateTouchedMap(dataSources, dataSourcesData, touchedDataSources);
+ update.dataSources = serializeData<DataSource>(dataSourcesData);
}
if (buildData.resources) {
- const resources = buildData.resources;
- validateTouchedMap(Resources, resources, touchedResources);
- update.resources = serializeData<Resource>(resources);
+ const resourcesData = buildData.resources;
+ validateTouchedMap(resources, resourcesData, touchedResources);
+ update.resources = serializeData<Resource>(resourcesData);
}
if (buildData.styleSources) {
- const styleSources = buildData.styleSources;
- validateTouchedMap(StyleSources, styleSources, touchedStyleSources);
- update.styleSources = serializeData<StyleSource>(styleSources);
+ const styleSourcesData = buildData.styleSources;
+ validateTouchedMap(styleSources, styleSourcesData, touchedStyleSources);
+ update.styleSources = serializeData<StyleSource>(styleSourcesData);
}
if (buildData.styleSourceSelections) {
- const styleSourceSelections = buildData.styleSourceSelections;
+ const styleSourceSelectionsData = buildData.styleSourceSelections;
validateTouchedMap(
- StyleSourceSelections,
styleSourceSelections,
+ styleSourceSelectionsData,
touchedStyleSourceSelections
);
update.styleSourceSelections = serializeStyleSourceSelections(
- styleSourceSelections
+ styleSourceSelectionsData
);
}
if (buildData.styles) {
- const styles = buildData.styles;
- validateTouchedMap(Styles, styles, touchedStyles);
- update.styles = serializeStyles(styles);
+ const stylesData = buildData.styles;
+ validateTouchedMap(styles, stylesData, touchedStyles);
+ update.styles = serializeStyles(stylesData);
}
if (buildData.marketplaceProduct) {
- const marketplaceProduct = buildData.marketplaceProduct;
+ const marketplaceProductData = buildData.marketplaceProduct;
update.marketplaceProduct = serializeConfig<MarketplaceProduct>(
- MarketplaceProduct.parse(marketplaceProduct)
+ marketplaceProduct.parse(marketplaceProductData)
);
}
diff --git a/packages/project/src/db/notification.ts b/packages/project/src/db/notification.ts
index 1e63b0929a..ed774bb866 100644
--- a/packages/project/src/db/notification.ts
+++ b/packages/project/src/db/notification.ts
@@ -7,8 +7,10 @@ import {
type NotificationType,
type NotificationStatus,
NOTIFICATION_TTL_MS,
- WorkspaceInvitePayload,
- ProjectTransferPayload,
+ type WorkspaceInvitePayload,
+ workspaceInvitePayload,
+ type ProjectTransferPayload,
+ projectTransferPayload,
} from "../shared/notification-schema";
import { roleLabels } from "@webstudio-is/trpc-interface/authorize";
@@ -246,12 +248,12 @@ export const list = async (context: AppContext) => {
for (const n of result.data) {
if (n.type === "workspaceInvite") {
- const parsed = WorkspaceInvitePayload.safeParse(n.payload);
+ const parsed = workspaceInvitePayload.safeParse(n.payload);
if (parsed.success) {
parsedInvites.set(n.id, parsed.data);
}
} else if (n.type === "projectTransfer") {
- const parsed = ProjectTransferPayload.safeParse(n.payload);
+ const parsed = projectTransferPayload.safeParse(n.payload);
if (parsed.success) {
parsedTransfers.set(n.id, parsed.data);
}
@@ -511,7 +513,7 @@ const performAcceptSideEffect = async ({
context: AppContext;
}) => {
if (notification.type === "workspaceInvite") {
- const parseResult = WorkspaceInvitePayload.safeParse(notification.payload);
+ const parseResult = workspaceInvitePayload.safeParse(notification.payload);
if (parseResult.success === false) {
throw new Error("Invalid workspace invite payload");
}
@@ -561,7 +563,7 @@ const performAcceptSideEffect = async ({
throw new Error("You cannot accept your own transfer request");
}
- const parseResult = ProjectTransferPayload.safeParse(notification.payload);
+ const parseResult = projectTransferPayload.safeParse(notification.payload);
if (parseResult.success === false) {
throw new Error("Invalid project transfer payload");
}
diff --git a/packages/project/src/db/project.ts b/packages/project/src/db/project.ts
index 5d50606c87..ed71a16230 100644
--- a/packages/project/src/db/project.ts
+++ b/packages/project/src/db/project.ts
@@ -6,8 +6,8 @@ import {
getPlanFeaturesByOwnerId,
} from "@webstudio-is/trpc-interface/index.server";
import { createBuild } from "@webstudio-is/project-build/index.server";
-import { Title } from "../shared/project-schema";
-import { MarketplaceApprovalStatus } from "../shared/marketplace-schema";
+import { projectTitle } from "../shared/project-schema";
+import type { MarketplaceApprovalStatus } from "../shared/marketplace-schema";
import { generateDomain, validateProjectDomain } from "./project-domain";
import type { SetNonNullable } from "type-fest";
@@ -87,7 +87,7 @@ export const create = async (
{ title, workspaceId }: { title: string; workspaceId?: string },
context: AppContext
) => {
- Title.parse(title);
+ projectTitle.parse(title);
if (context.authorization.type !== "user") {
throw new AuthorizationError("Only logged in users can create a project");
@@ -257,7 +257,7 @@ export const rename = async (
},
context: AppContext
) => {
- Title.parse(title);
+ projectTitle.parse(title);
await assertEditPermission(projectId, context);
diff --git a/packages/project/src/shared/marketplace-schema.ts b/packages/project/src/shared/marketplace-schema.ts
index fd2ba8e0b0..3bc72e2c29 100644
--- a/packages/project/src/shared/marketplace-schema.ts
+++ b/packages/project/src/shared/marketplace-schema.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
-export const MarketplaceApprovalStatus = z.enum([
+export const marketplaceApprovalStatus = z.enum([
"UNLISTED",
"PENDING",
"APPROVED",
@@ -8,5 +8,5 @@ export const MarketplaceApprovalStatus = z.enum([
]);
export type MarketplaceApprovalStatus = z.infer<
- typeof MarketplaceApprovalStatus
+ typeof marketplaceApprovalStatus
>;
diff --git a/packages/project/src/shared/notification-schema.ts b/packages/project/src/shared/notification-schema.ts
index 92cf235ec2..42587141ac 100644
--- a/packages/project/src/shared/notification-schema.ts
+++ b/packages/project/src/shared/notification-schema.ts
@@ -19,16 +19,16 @@ export type NotificationStatus = (typeof notificationStatuses)[number];
/** Notifications expire after this many milliseconds (7 days). */
export const NOTIFICATION_TTL_MS = 7 * 24 * 60 * 60 * 1000;
-export const WorkspaceInvitePayload = z.object({
+export const workspaceInvitePayload = z.object({
workspaceId: z.string(),
relation: z.enum(roles),
});
-export type WorkspaceInvitePayload = z.infer<typeof WorkspaceInvitePayload>;
+export type WorkspaceInvitePayload = z.infer<typeof workspaceInvitePayload>;
-export const ProjectTransferPayload = z.object({
+export const projectTransferPayload = z.object({
projectId: z.string(),
targetWorkspaceId: z.string().optional(),
});
-export type ProjectTransferPayload = z.infer<typeof ProjectTransferPayload>;
+export type ProjectTransferPayload = z.infer<typeof projectTransferPayload>;
diff --git a/packages/project/src/shared/project-schema.ts b/packages/project/src/shared/project-schema.ts
index 10cc3b19ae..01a599053c 100644
--- a/packages/project/src/shared/project-schema.ts
+++ b/packages/project/src/shared/project-schema.ts
@@ -2,7 +2,7 @@ import { z } from "zod";
const MIN_TITLE_LENGTH = 2;
-export const Title = z
+export const projectTitle = z
.string()
.refine(
(val) => val.length >= MIN_TITLE_LENGTH,
diff --git a/packages/project/src/trpc/project-router.ts b/packages/project/src/trpc/project-router.ts
index 6f4a441815..cf3702b19a 100644
--- a/packages/project/src/trpc/project-router.ts
+++ b/packages/project/src/trpc/project-router.ts
@@ -8,14 +8,14 @@ import {
createErrorResponse,
getProjectOwnerId,
} from "@webstudio-is/trpc-interface/index.server";
-import { Title } from "../shared/project-schema";
-import { MarketplaceApprovalStatus } from "../shared/marketplace-schema";
+import { projectTitle } from "../shared/project-schema";
+import { marketplaceApprovalStatus } from "../shared/marketplace-schema";
export const projectRouter = router({
rename: procedure
.input(
z.object({
- title: Title,
+ title: projectTitle,
projectId: z.string(),
})
)
@@ -47,7 +47,9 @@ export const projectRouter = router({
}),
create: procedure
- .input(z.object({ title: Title, workspaceId: z.string().optional() }))
+ .input(
+ z.object({ title: projectTitle, workspaceId: z.string().optional() })
+ )
.mutation(async ({ input, ctx }) => {
return await projectApi.create(input, ctx);
}),
@@ -56,7 +58,7 @@ export const projectRouter = router({
.input(
z.object({
projectId: z.string(),
- marketplaceApprovalStatus: MarketplaceApprovalStatus,
+ marketplaceApprovalStatus: marketplaceApprovalStatus,
})
)
.mutation(async ({ input, ctx }) => {
diff --git a/packages/project/src/trpc/workspace-router.ts b/packages/project/src/trpc/workspace-router.ts
index bbe6adc32a..d520de0d4a 100644
--- a/packages/project/src/trpc/workspace-router.ts
+++ b/packages/project/src/trpc/workspace-router.ts
@@ -8,12 +8,12 @@ import {
} from "@webstudio-is/trpc-interface/index.server";
import { roles } from "@webstudio-is/trpc-interface/authorize";
-const Name = z.string().min(2).max(100);
-const Relation = z.enum(roles);
+const name = z.string().min(2).max(100);
+const relation = z.enum(roles);
export const workspaceRouter = router({
create: procedure
- .input(z.object({ name: Name }))
+ .input(z.object({ name: name }))
.mutation(async ({ input, ctx }) => {
try {
const workspace = await workspaceApi.create(
@@ -27,7 +27,7 @@ export const workspaceRouter = router({
}),
rename: procedure
- .input(z.object({ workspaceId: z.string(), name: Name }))
+ .input(z.object({ workspaceId: z.string(), name: name }))
.mutation(async ({ input, ctx }) => {
try {
const workspace = await workspaceApi.rename(input, ctx);
@@ -73,7 +73,7 @@ export const workspaceRouter = router({
z.object({
workspaceId: z.string(),
email: z.string().email(),
- relation: Relation,
+ relation: relation,
})
)
.mutation(async ({ input, ctx }) => {
@@ -99,7 +99,7 @@ export const workspaceRouter = router({
z.object({
workspaceId: z.string(),
memberUserId: z.string(),
- relation: Relation,
+ relation: relation,
})
)
.mutation(async ({ input, ctx }) => {
diff --git a/packages/protocol/src/contract-version.test.ts b/packages/protocol/src/contract-version.test.ts
index c1c7061421..da00513e7c 100644
--- a/packages/protocol/src/contract-version.test.ts
+++ b/packages/protocol/src/contract-version.test.ts
@@ -24,13 +24,13 @@ const createLengthRefinement = ({
);
const versionForRefinement = (refinement: StringRefinement) =>
- createContractVersion(z.string().superRefine(refinement), "1");
+ createContractVersion(z.string().superRefine(refinement));
describe("contract version", () => {
test("changes when schema shape changes", () => {
- expect(
- createContractVersion(z.object({ value: z.string() }), "1")
- ).not.toBe(createContractVersion(z.object({ value: z.number() }), "1"));
+ expect(createContractVersion(z.object({ value: z.string() }))).not.toBe(
+ createContractVersion(z.object({ value: z.number() }))
+ );
});
test("changes when explicit refinement contract changes", () => {
@@ -61,8 +61,7 @@ describe("contract version", () => {
message: "Must be at least 2 characters",
});
}
- }),
- "1"
+ })
)
).toBe(
createContractVersion(
@@ -73,33 +72,22 @@ describe("contract version", () => {
message: "Must be at least 3 characters",
});
}
- }),
- "1"
+ })
)
);
});
- test("changes when package version changes", () => {
- const schema = z.object({ value: z.string() });
-
- expect(createContractVersion(schema, "1.0.0")).not.toBe(
- createContractVersion(schema, "1.0.1")
- );
- });
-
test("changes when extra schemas change", () => {
const schema = z.object({ value: z.string() });
expect(
- createContractVersion(schema, "1", [z.object({ auth: z.literal(1) })])
+ createContractVersion(schema, [z.object({ auth: z.literal(1) })])
).not.toBe(
- createContractVersion(schema, "1", [z.object({ auth: z.literal(2) })])
+ createContractVersion(schema, [z.object({ auth: z.literal(2) })])
);
});
- test("uses short bundle package version", () => {
- expect(
- createContractVersion(z.string(), "0.0.0-webstudio-version")
- ).toMatch(/^bundle-0\.0\.0-[0-9a-f]{8}$/);
+ test("uses only the bundle contract hash", () => {
+ expect(createContractVersion(z.string())).toMatch(/^bundle-[0-9a-f]{8}$/);
});
});
diff --git a/packages/protocol/src/contract-version.ts b/packages/protocol/src/contract-version.ts
index 602c19d1b5..33200bec21 100644
--- a/packages/protocol/src/contract-version.ts
+++ b/packages/protocol/src/contract-version.ts
@@ -197,10 +197,8 @@ const stableStringify = (value: unknown): string => {
export const createContractVersion = (
schema: z.ZodTypeAny,
- version: string,
additionalSchemas: z.ZodTypeAny[] = []
) => {
- const bundlePackageVersion = version.replace(/-webstudio-version$/, "");
let hash = 0x811c9dc5;
for (const char of stableStringify({
additionalSchemas: additionalSchemas.map((schema) =>
@@ -211,5 +209,5 @@ export const createContractVersion = (
hash ^= char.charCodeAt(0);
hash = Math.imul(hash, 0x01000193);
}
- return `bundle-${bundlePackageVersion}-${(hash >>> 0).toString(16).padStart(8, "0")}` as const;
+ return `bundle-${(hash >>> 0).toString(16).padStart(8, "0")}` as const;
};
diff --git a/packages/protocol/src/fixture-projects.test.ts b/packages/protocol/src/fixture-projects.test.ts
index 37959d00cd..0cc2fc27c5 100644
--- a/packages/protocol/src/fixture-projects.test.ts
+++ b/packages/protocol/src/fixture-projects.test.ts
@@ -2,7 +2,7 @@ import { existsSync, readdirSync, readFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, test } from "vitest";
-import { bundleVersion, publishedProjectBundleSchema } from "./schema";
+import { bundleVersion, publishedProjectBundle } from "./schema";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
const fixturesRoot = join(root, "fixtures");
@@ -42,9 +42,7 @@ describe("fixture project bundles", () => {
test.each(fixtureDataFiles)(
"$fixtureName has current bundle-compatible data",
({ dataFile }) => {
- const data = publishedProjectBundleSchema.parse(
- readFixtureData(dataFile)
- );
+ const data = publishedProjectBundle.parse(readFixtureData(dataFile));
expect(data.bundleVersion).toBe(bundleVersion);
}
@@ -53,9 +51,7 @@ describe("fixture project bundles", () => {
test.each(fixtureDataFiles)(
"$fixtureName asset records point at fixture files",
({ dataFile, fixtureDirectory }) => {
- const data = publishedProjectBundleSchema.parse(
- readFixtureData(dataFile)
- );
+ const data = publishedProjectBundle.parse(readFixtureData(dataFile));
const missingAssetFiles = data.assets
.map((asset) => asset.name)
.filter(
diff --git a/packages/protocol/src/schema.test.ts b/packages/protocol/src/schema.test.ts
index 47371dd649..2069a38481 100644
--- a/packages/protocol/src/schema.test.ts
+++ b/packages/protocol/src/schema.test.ts
@@ -1,20 +1,21 @@
import { describe, expect, test } from "vitest";
import {
isAssetFileName,
- isAssetFileDataString,
+ getMissingImportedAssetFilesMessage,
+ parseMissingImportedAssetFilesMessage,
getBundleVersionMismatchMessage,
- importProjectBundleInputSchema,
- publishedProjectBundleSchema,
+ importProjectBundleInput,
+ publishedProjectBundle,
bundleVersion,
+ stagedUploadPath,
+ stagedUploadProjectIdHeader,
} from "./schema";
import { createPublishedProjectBundleFixture } from "./fixtures";
describe("project bundle contract", () => {
- test("validates base64 asset file data", () => {
- expect(isAssetFileDataString("aGVsbG8=")).toBe(true);
- expect(isAssetFileDataString("")).toBe(true);
- expect(isAssetFileDataString("not base64")).toBe(false);
- expect(isAssetFileDataString("a===")).toBe(false);
+ test("defines staged upload transport details", () => {
+ expect(stagedUploadPath).toBe("/rest/staged-upload");
+ expect(stagedUploadProjectIdHeader).toBe("x-webstudio-project-id");
});
test("validates asset file names", () => {
@@ -26,9 +27,35 @@ describe("project bundle contract", () => {
expect(isAssetFileName("folder\\image.png")).toBe(false);
});
+ test("formats and parses missing imported asset file messages", () => {
+ const message = getMissingImportedAssetFilesMessage([
+ "image.png",
+ "font,latin.woff2",
+ ]);
+
+ expect(message).toBe(
+ 'Imported asset files are missing: ["image.png","font,latin.woff2"]'
+ );
+ expect(parseMissingImportedAssetFilesMessage(new Error(message))).toEqual([
+ "image.png",
+ "font,latin.woff2",
+ ]);
+ expect(
+ parseMissingImportedAssetFilesMessage("Other error")
+ ).toBeUndefined();
+ });
+
+ test("parses already-deployed comma-separated missing asset messages", () => {
+ expect(
+ parseMissingImportedAssetFilesMessage(
+ new Error("Imported asset files are missing: image.png, font.woff2")
+ )
+ ).toEqual(["image.png", "font.woff2"]);
+ });
+
test("preserves published project metadata", () => {
expect(
- publishedProjectBundleSchema.parse(
+ publishedProjectBundle.parse(
createPublishedProjectBundleFixture({
user: { email: "[email protected]" },
})
@@ -44,7 +71,7 @@ describe("project bundle contract", () => {
const data = createPublishedProjectBundleFixture();
delete (data as Partial<typeof data>).projectTitle;
- expect(() => publishedProjectBundleSchema.parse(data)).toThrow();
+ expect(() => publishedProjectBundle.parse(data)).toThrow();
});
test("requires published project bundle when importing", () => {
@@ -52,15 +79,59 @@ describe("project bundle contract", () => {
delete (data as Partial<typeof data>).projectTitle;
expect(() =>
- importProjectBundleInputSchema.parse({
+ importProjectBundleInput.parse({
projectId: "project",
data,
})
).toThrow();
});
+ test("accepts staged upload id when importing", () => {
+ expect(
+ importProjectBundleInput.parse({
+ projectId: "project",
+ uploadId: "upload",
+ })
+ ).toEqual({
+ projectId: "project",
+ uploadId: "upload",
+ });
+ });
+
+ test("requires non-empty project and upload ids when importing", () => {
+ expect(() =>
+ importProjectBundleInput.parse({
+ projectId: "",
+ uploadId: "upload",
+ })
+ ).toThrow();
+
+ expect(() =>
+ importProjectBundleInput.parse({
+ projectId: "project",
+ uploadId: "",
+ })
+ ).toThrow();
+ });
+
+ test("requires exactly one project bundle import source", () => {
+ expect(() =>
+ importProjectBundleInput.parse({
+ projectId: "project",
+ })
+ ).toThrow("Provide either project bundle data or an upload id");
+
+ expect(() =>
+ importProjectBundleInput.parse({
+ projectId: "project",
+ data: createPublishedProjectBundleFixture(),
+ uploadId: "upload",
+ })
+ ).toThrow("Provide either project bundle data or an upload id");
+ });
+
test("generates the current bundle version", () => {
- expect(bundleVersion).toMatch(/^bundle-0\.0\.0-[0-9a-f]{8}$/);
+ expect(bundleVersion).toMatch(/^bundle-[0-9a-f]{8}$/);
});
test("formats project bundle version mismatch messages", () => {
diff --git a/packages/protocol/src/schema.ts b/packages/protocol/src/schema.ts
index bd51dce214..68f3fcd33f 100644
--- a/packages/protocol/src/schema.ts
+++ b/packages/protocol/src/schema.ts
@@ -1,108 +1,103 @@
-import { Asset, Page } from "@webstudio-is/sdk/schema";
-import { SerializedBuildSchema } from "@webstudio-is/project-build/schema";
-import { wsAuthConfigSchema } from "@webstudio-is/wsauth/schema";
+import { asset, page } from "@webstudio-is/sdk/schema";
+import { serializedBuild } from "@webstudio-is/project-build/schema";
+import { wsAuthConfig } from "@webstudio-is/wsauth/schema";
import { z } from "zod";
-import { version } from "../package.json";
import { createContractVersion } from "./contract-version";
-// Bundle owns the assembled external project import/export format.
+// Protocol owns the assembled external project import/export format.
// Domain schemas stay owned by their packages (sdk, project-build, etc.) and
// are imported through schema-only entrypoints to avoid duplicating model
-// definitions or pulling non-schema runtime code into bundle consumers.
+// definitions or pulling non-schema runtime code into protocol consumers.
-export const assetFileDataPattern = /^[A-Za-z0-9+/]*={0,2}$/;
+export const maxProjectBundleSize = 20 * 1024 * 1024;
+export const stagedUploadPath = "/rest/staged-upload";
+export const stagedUploadProjectIdHeader = "x-webstudio-project-id";
-export const isAssetFileDataString = (value: string) => {
- if (value.length % 4 !== 0) {
- return false;
- }
- if (assetFileDataPattern.test(value) === false) {
- return false;
- }
- const paddingIndex = value.indexOf("=");
- return paddingIndex === -1 || paddingIndex >= value.length - 2;
-};
-
-const assertAssetFileDataString: z.RefinementEffect<string>["refinement"] =
- Object.assign(
- (value: string, context: z.RefinementCtx) => {
- if (isAssetFileDataString(value)) {
- return;
- }
- context.addIssue({
- code: z.ZodIssueCode.custom,
- message: "Invalid asset file data",
- });
- },
- {
- contract: {
- encoding: "base64",
- length: "multiple-of-4",
- padding: "only-last-two-characters",
- pattern: assetFileDataPattern,
- },
- }
- );
-
-const assetFileNameSchema = z
+const assetFileName = z
.string()
.min(1)
.regex(/^(?!\.{1,2}$)[^/\\]+$/);
export const isAssetFileName = (value: string) =>
- assetFileNameSchema.safeParse(value).success;
+ assetFileName.safeParse(value).success;
-export const assetFileDataSchema = z.object({
- name: assetFileNameSchema,
- data: z.string().superRefine(assertAssetFileDataString),
-});
-export type AssetFileData = z.infer<typeof assetFileDataSchema>;
+const missingImportedAssetFilesPrefix = "Imported asset files are missing: ";
+
+export const getMissingImportedAssetFilesMessage = (assetNames: string[]) =>
+ `${missingImportedAssetFilesPrefix}${JSON.stringify(assetNames)}`;
+
+export const parseMissingImportedAssetFilesMessage = (error: unknown) => {
+ const message = error instanceof Error ? error.message : String(error);
+ const start = message.indexOf(missingImportedAssetFilesPrefix);
+ if (start === -1) {
+ return;
+ }
+ const data = message.slice(start + missingImportedAssetFilesPrefix.length);
+ try {
+ const names = JSON.parse(data);
+ if (
+ Array.isArray(names) &&
+ names.every((name) => typeof name === "string")
+ ) {
+ return names;
+ }
+ } catch {
+ // Support already-deployed API responses using the previous comma-separated
+ // format. New responses use JSON so valid filenames can contain commas.
+ }
+ return data
+ .split(",")
+ .map((name) => name.trim())
+ .filter((name) => name !== "");
+};
-export const projectBundleSchema = z.object({
- page: Page,
- pages: z.array(Page),
- build: SerializedBuildSchema,
- assets: z.array(Asset),
+export const projectBundle = z.object({
+ page,
+ pages: z.array(page),
+ build: serializedBuild,
+ assets: z.array(asset),
origin: z.string().optional(),
});
-export type ProjectBundle = z.infer<typeof projectBundleSchema>;
+export type ProjectBundle = z.infer<typeof projectBundle>;
-export const publishedProjectBundleSchema = projectBundleSchema.extend({
+export const publishedProjectBundle = projectBundle.extend({
bundleVersion: z.union([z.string(), z.number()]).optional(),
user: z.object({ email: z.string().nullable() }).optional(),
projectDomain: z.string(),
projectTitle: z.string(),
});
-export type PublishedProjectBundle = z.infer<
- typeof publishedProjectBundleSchema
->;
+export type PublishedProjectBundle = z.infer<typeof publishedProjectBundle>;
-export const importProjectBundleInputSchema = z.object({
- projectId: z.string(),
- data: publishedProjectBundleSchema,
- assetFiles: z.array(assetFileDataSchema).optional(),
- ignoreVersionCheck: z.boolean().optional(),
-});
-export type ImportProjectBundleInput = z.infer<
- typeof importProjectBundleInputSchema
->;
+export const importProjectBundleInput = z
+ .object({
+ projectId: z.string().min(1),
+ data: publishedProjectBundle.optional(),
+ uploadId: z.string().min(1).optional(),
+ ignoreVersionCheck: z.boolean().optional(),
+ })
+ .refine(
+ ({ data, uploadId }) => (data === undefined) !== (uploadId === undefined),
+ {
+ message: "Provide either project bundle data or an upload id",
+ path: ["data"],
+ }
+ );
+export type ImportProjectBundleInput = z.infer<typeof importProjectBundleInput>;
-export const importProjectBundleResultSchema = z.object({
+export const importProjectBundleResult = z.object({
version: z.number(),
});
export type ImportProjectBundleResult = z.infer<
- typeof importProjectBundleResultSchema
+ typeof importProjectBundleResult
>;
-export const checkProjectBuildPermissionInputSchema = z.object({
- projectId: z.string(),
+export const checkProjectBuildPermissionInput = z.object({
+ projectId: z.string().min(1),
});
-export const bundleVersion = createContractVersion(
- publishedProjectBundleSchema,
- version,
- [wsAuthConfigSchema]
-);
+export const bundleVersion = createContractVersion(publishedProjectBundle, [
+ wsAuthConfig,
+]);
export const getBundleVersion = (data: unknown) => {
if (typeof data !== "object" || data === null) {
diff --git a/packages/react-sdk/src/component-generator.test.tsx b/packages/react-sdk/src/component-generator.test.tsx
index 2c1e1327b3..1b4a19bcdc 100644
--- a/packages/react-sdk/src/component-generator.test.tsx
+++ b/packages/react-sdk/src/component-generator.test.tsx
@@ -6,7 +6,7 @@ import {
elementComponent,
ROOT_INSTANCE_ID,
SYSTEM_VARIABLE_ID,
- WsComponentMeta,
+ type WsComponentMeta,
} from "@webstudio-is/sdk";
import {
$,
diff --git a/packages/sdk/src/core-templates.tsx b/packages/sdk/src/core-templates.tsx
index 0727bc632a..b70c01ec52 100644
--- a/packages/sdk/src/core-templates.tsx
+++ b/packages/sdk/src/core-templates.tsx
@@ -116,7 +116,7 @@ const blockMeta: TemplateMeta = {
<ws.element ws:label="List Item" ws:tag="li">
In Content mode, you can edit any direct child instances that were
pre-added to the Content Block, as well as add new instances
- predefined in Templates.
+ predefined in templates.
</ws.element>
<ws.element ws:label="List Item" ws:tag="li">
To predefine instances for insertion in Content mode, switch to Design
diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts
index 8da3bc83ff..864dae0440 100644
--- a/packages/sdk/src/index.ts
+++ b/packages/sdk/src/index.ts
@@ -47,12 +47,12 @@ export type {
} from "./schema/animation-schema";
export {
- animationActionSchema,
- scrollAnimationSchema,
- viewAnimationSchema,
- rangeUnitValueSchema,
- animationKeyframeSchema,
- insetUnitValueSchema,
- durationUnitValueSchema,
+ animationAction,
+ scrollAnimation,
+ viewAnimation,
+ rangeUnitValue,
+ animationKeyframe,
+ insetUnitValue,
+ durationUnitValue,
RANGE_UNITS,
} from "./schema/animation-schema";
diff --git a/packages/sdk/src/router-paths.test.ts b/packages/sdk/src/router-paths.test.ts
index da3fc9794d..3222d728ef 100644
--- a/packages/sdk/src/router-paths.test.ts
+++ b/packages/sdk/src/router-paths.test.ts
@@ -10,29 +10,29 @@
*/
import { describe, test, expect } from "vitest";
-import { ProjectNewRedirectPath, RedirectSourcePath } from "./schema/pages";
+import { projectNewRedirectPath, redirectSourcePath } from "./schema/pages";
import {
REDIRECT_SOURCE_INVALID_PATHS,
REDIRECT_SOURCE_VALID_PATHS,
} from "./router-path-test-data";
describe("Router path validation consistency", () => {
- describe("RedirectSourcePath schema - valid paths", () => {
+ describe("redirectSourcePath schema - valid paths", () => {
test.each(REDIRECT_SOURCE_VALID_PATHS)("accepts: %s", (path) => {
- const result = RedirectSourcePath.safeParse(path);
+ const result = redirectSourcePath.safeParse(path);
expect(result.success).toBe(true);
});
});
- describe("RedirectSourcePath schema - invalid paths", () => {
+ describe("redirectSourcePath schema - invalid paths", () => {
test.each(REDIRECT_SOURCE_INVALID_PATHS)("rejects: %s", (path) => {
- const result = RedirectSourcePath.safeParse(path);
+ const result = redirectSourcePath.safeParse(path);
expect(result.success).toBe(false);
});
});
- describe("ProjectNewRedirectPath schema - valid paths", () => {
- // ProjectNewRedirectPath is more permissive (allows / and external URLs)
+ describe("projectNewRedirectPath schema - valid paths", () => {
+ // projectNewRedirectPath is more permissive (allows / and external URLs)
const validTargetPaths = [
"/",
"/about",
@@ -42,7 +42,7 @@ describe("Router path validation consistency", () => {
];
test.each(validTargetPaths)("accepts: %s", (path) => {
- const result = ProjectNewRedirectPath.safeParse(path);
+ const result = projectNewRedirectPath.safeParse(path);
expect(result.success).toBe(true);
});
});
diff --git a/packages/sdk/src/schema/animation-schema.ts b/packages/sdk/src/schema/animation-schema.ts
index ccc537f16e..65be40757c 100644
--- a/packages/sdk/src/schema/animation-schema.ts
+++ b/packages/sdk/src/schema/animation-schema.ts
@@ -1,4 +1,4 @@
-import { StyleValue } from "@webstudio-is/css-engine";
+import { styleValue } from "@webstudio-is/css-engine";
import { z } from "zod";
// Helper for creating union of string literals from array
@@ -57,13 +57,13 @@ export const RANGE_UNITS = [
"dvmax",
] as const;
-export const rangeUnitSchema = literalUnion(RANGE_UNITS);
+export const rangeUnit = literalUnion(RANGE_UNITS);
-export const rangeUnitValueSchema = z.union([
+export const rangeUnitValue = z.union([
z.object({
type: z.literal("unit"),
value: z.number(),
- unit: rangeUnitSchema,
+ unit: rangeUnit,
}),
z.object({
type: z.literal("unparsed"),
@@ -76,13 +76,13 @@ export const rangeUnitValueSchema = z.union([
]);
export const TIME_UNITS = ["ms", "s"] as const;
-const timeUnitSchema = literalUnion(TIME_UNITS);
+const timeUnit = literalUnion(TIME_UNITS);
-export const durationUnitValueSchema = z.union([
+export const durationUnitValue = z.union([
z.object({
type: z.literal("unit"),
value: z.number(),
- unit: timeUnitSchema,
+ unit: timeUnit,
}),
z.object({
type: z.literal("var"),
@@ -90,11 +90,11 @@ export const durationUnitValueSchema = z.union([
}),
]);
-const iterationsUnitValueSchema = z.union([z.number(), z.literal("infinite")]);
+const iterationsUnitValue = z.union([z.number(), z.literal("infinite")]);
// view-timeline-inset
-export const insetUnitValueSchema = z.union([
- rangeUnitValueSchema,
+export const insetUnitValue = z.union([
+ rangeUnitValue,
z.object({
type: z.literal("keyword"),
value: z.literal("auto"),
@@ -103,16 +103,16 @@ export const insetUnitValueSchema = z.union([
// @todo: Fix Keyframe Styles
// Can we use CssStyleMap for this? This type ends up not enforcing kebab case like.
-export const keyframeStylesSchema = z.record(StyleValue);
+export const keyframeStyles = z.record(styleValue);
// Animation Keyframe
-export const animationKeyframeSchema = z.object({
+export const animationKeyframe = z.object({
offset: z.number().optional(),
- styles: keyframeStylesSchema,
+ styles: keyframeStyles,
});
// Keyframe Effect Options
-export const keyframeEffectOptionsSchema = z.object({
+export const keyframeEffectOptions = z.object({
easing: z.string().optional(),
fill: z
.union([
@@ -122,31 +122,25 @@ export const keyframeEffectOptionsSchema = z.object({
z.literal("both"),
])
.optional(), // FillMode
- duration: durationUnitValueSchema.optional(),
- delay: durationUnitValueSchema.optional(),
- iterations: iterationsUnitValueSchema.optional(),
+ duration: durationUnitValue.optional(),
+ delay: durationUnitValue.optional(),
+ iterations: iterationsUnitValue.optional(),
});
// Scroll Named Range
-export const scrollNamedRangeSchema = z.union([
- z.literal("start"),
- z.literal("end"),
-]);
+export const scrollNamedRange = z.union([z.literal("start"), z.literal("end")]);
// Scroll Range Value
-export const scrollRangeValueSchema = z.tuple([
- scrollNamedRangeSchema,
- rangeUnitValueSchema,
-]);
+export const scrollRangeValue = z.tuple([scrollNamedRange, rangeUnitValue]);
// Scroll Range Options
-export const scrollRangeOptionsSchema = z.object({
- rangeStart: scrollRangeValueSchema.optional(),
- rangeEnd: scrollRangeValueSchema.optional(),
+export const scrollRangeOptions = z.object({
+ rangeStart: scrollRangeValue.optional(),
+ rangeEnd: scrollRangeValue.optional(),
});
// Animation Axis
-export const animationAxisSchema = z.union([
+export const animationAxis = z.union([
z.literal("block"),
z.literal("inline"),
z.literal("x"),
@@ -154,7 +148,7 @@ export const animationAxisSchema = z.union([
]);
// View Named Range
-export const viewNamedRangeSchema = z.union([
+export const viewNamedRange = z.union([
z.literal("contain"),
z.literal("cover"),
z.literal("entry"),
@@ -164,15 +158,12 @@ export const viewNamedRangeSchema = z.union([
]);
// View Range Value
-export const viewRangeValueSchema = z.tuple([
- viewNamedRangeSchema,
- rangeUnitValueSchema,
-]);
+export const viewRangeValue = z.tuple([viewNamedRange, rangeUnitValue]);
// View Range Options
-export const viewRangeOptionsSchema = z.object({
- rangeStart: viewRangeValueSchema.optional(),
- rangeEnd: viewRangeValueSchema.optional(),
+export const viewRangeOptions = z.object({
+ rangeStart: viewRangeValue.optional(),
+ rangeEnd: viewRangeValue.optional(),
});
const baseAnimation = z.object({
@@ -181,75 +172,74 @@ const baseAnimation = z.object({
enabled: z
.array(z.tuple([z.string().describe("breakpointId"), z.boolean()]))
.optional(),
- keyframes: z.array(animationKeyframeSchema),
+ keyframes: z.array(animationKeyframe),
});
-export const scrollAnimationSchema = baseAnimation.merge(
+export const scrollAnimation = baseAnimation.merge(
z.object({
- timing: keyframeEffectOptionsSchema.merge(scrollRangeOptionsSchema),
+ timing: keyframeEffectOptions.merge(scrollRangeOptions),
})
);
// Scroll Action
-export const scrollActionSchema = z.object({
+export const scrollAction = z.object({
type: z.literal("scroll"),
source: z
.union([z.literal("closest"), z.literal("nearest"), z.literal("root")])
.optional(),
- axis: animationAxisSchema.optional(),
- animations: z.array(scrollAnimationSchema),
+ axis: animationAxis.optional(),
+ animations: z.array(scrollAnimation),
isPinned: z.boolean().optional(),
debug: z.boolean().optional(),
});
-export const viewAnimationSchema = baseAnimation.merge(
+export const viewAnimation = baseAnimation.merge(
z.object({
- timing: keyframeEffectOptionsSchema.merge(viewRangeOptionsSchema),
+ timing: keyframeEffectOptions.merge(viewRangeOptions),
})
);
// View Action
-export const viewActionSchema = z.object({
+export const viewAction = z.object({
type: z.literal("view"),
subject: z.string().optional(),
- axis: animationAxisSchema.optional(),
- animations: z.array(viewAnimationSchema),
+ axis: animationAxis.optional(),
+ animations: z.array(viewAnimation),
- insetStart: insetUnitValueSchema.optional(),
+ insetStart: insetUnitValue.optional(),
- insetEnd: insetUnitValueSchema.optional(),
+ insetEnd: insetUnitValue.optional(),
isPinned: z.boolean().optional(),
debug: z.boolean().optional(),
});
// Animation Action
-export const animationActionSchema = z.discriminatedUnion("type", [
- scrollActionSchema,
- viewActionSchema,
+export const animationAction = z.discriminatedUnion("type", [
+ scrollAction,
+ viewAction,
]);
// Helper function to check if a value is a valid range unit
export const isRangeUnit = (
value: unknown
-): value is z.infer<typeof rangeUnitSchema> =>
- rangeUnitSchema.safeParse(value).success;
+): value is z.infer<typeof rangeUnit> => rangeUnit.safeParse(value).success;
// Type exports
-export type RangeUnit = z.infer<typeof rangeUnitSchema>;
-export type RangeUnitValue = z.infer<typeof rangeUnitValueSchema>;
-export type DurationUnitValue = z.infer<typeof durationUnitValueSchema>;
-export type IterationsUnitValue = z.infer<typeof iterationsUnitValueSchema>;
-export type TimeUnit = z.infer<typeof timeUnitSchema>;
-export type KeyframeStyles = z.infer<typeof keyframeStylesSchema>;
-export type AnimationKeyframe = z.infer<typeof animationKeyframeSchema>;
-export type ScrollNamedRange = z.infer<typeof scrollNamedRangeSchema>;
-export type ScrollRangeValue = z.infer<typeof scrollRangeValueSchema>;
-export type ViewNamedRange = z.infer<typeof viewNamedRangeSchema>;
-export type ViewRangeValue = z.infer<typeof viewRangeValueSchema>;
-export type AnimationActionScroll = z.infer<typeof scrollActionSchema>;
-export type AnimationActionView = z.infer<typeof viewActionSchema>;
-export type AnimationAction = z.infer<typeof animationActionSchema>;
-export type ScrollAnimation = z.infer<typeof scrollAnimationSchema>;
-export type ViewAnimation = z.infer<typeof viewAnimationSchema>;
-export type InsetUnitValue = z.infer<typeof insetUnitValueSchema>;
+export type RangeUnit = z.infer<typeof rangeUnit>;
+export type RangeUnitValue = z.infer<typeof rangeUnitValue>;
+export type DurationUnitValue = z.infer<typeof durationUnitValue>;
+export type IterationsUnitValue = z.infer<typeof iterationsUnitValue>;
+export type TimeUnit = z.infer<typeof timeUnit>;
+export type KeyframeStyles = z.infer<typeof keyframeStyles>;
+export type AnimationKeyframe = z.infer<typeof animationKeyframe>;
+export type ScrollNamedRange = z.infer<typeof scrollNamedRange>;
+export type ScrollRangeValue = z.infer<typeof scrollRangeValue>;
+export type ViewNamedRange = z.infer<typeof viewNamedRange>;
+export type ViewRangeValue = z.infer<typeof viewRangeValue>;
+export type AnimationActionScroll = z.infer<typeof scrollAction>;
+export type AnimationActionView = z.infer<typeof viewAction>;
+export type AnimationAction = z.infer<typeof animationAction>;
+export type ScrollAnimation = z.infer<typeof scrollAnimation>;
+export type ViewAnimation = z.infer<typeof viewAnimation>;
+export type InsetUnitValue = z.infer<typeof insetUnitValue>;
diff --git a/packages/sdk/src/schema/assets.ts b/packages/sdk/src/schema/assets.ts
index 607f1e3596..1f2c8afc22 100644
--- a/packages/sdk/src/schema/assets.ts
+++ b/packages/sdk/src/schema/assets.ts
@@ -1,10 +1,10 @@
import { z } from "zod";
-import { FontFormat, FontMeta } from "@webstudio-is/fonts";
+import { fontFormat, fontMeta } from "@webstudio-is/fonts";
-const AssetId = z.string();
+const assetId = z.string();
const baseAsset = {
- id: AssetId,
+ id: assetId,
projectId: z.string(),
size: z.number(),
name: z.string(),
@@ -13,38 +13,41 @@ const baseAsset = {
createdAt: z.string(),
};
-export const FontAsset = z.object({
+export const assetType = z.enum(["font", "image", "file"]);
+export type AssetType = z.infer<typeof assetType>;
+
+export const fontAsset = z.object({
...baseAsset,
- format: FontFormat,
- meta: FontMeta,
- type: z.literal("font"),
+ format: fontFormat,
+ meta: fontMeta,
+ type: z.literal(assetType.enum.font),
});
-export type FontAsset = z.infer<typeof FontAsset>;
+export type FontAsset = z.infer<typeof fontAsset>;
-export const ImageMeta = z.object({
+export const imageMeta = z.object({
width: z.number(),
height: z.number(),
});
-export type ImageMeta = z.infer<typeof ImageMeta>;
+export type ImageMeta = z.infer<typeof imageMeta>;
-export const ImageAsset = z.object({
+export const imageAsset = z.object({
...baseAsset,
format: z.string(),
- meta: ImageMeta,
- type: z.literal("image"),
+ meta: imageMeta,
+ type: z.literal(assetType.enum.image),
});
-export type ImageAsset = z.infer<typeof ImageAsset>;
+export type ImageAsset = z.infer<typeof imageAsset>;
-export const FileAsset = z.object({
+export const fileAsset = z.object({
...baseAsset,
format: z.string(),
meta: z.object({}),
- type: z.literal("file"),
+ type: z.literal(assetType.enum.file),
});
-export type FileAsset = z.infer<typeof FileAsset>;
+export type FileAsset = z.infer<typeof fileAsset>;
-export const Asset = z.union([FontAsset, ImageAsset, FileAsset]);
-export type Asset = z.infer<typeof Asset>;
+export const asset = z.union([fontAsset, imageAsset, fileAsset]);
+export type Asset = z.infer<typeof asset>;
-export const Assets = z.map(AssetId, Asset);
-export type Assets = z.infer<typeof Assets>;
+export const assets = z.map(assetId, asset);
+export type Assets = z.infer<typeof assets>;
diff --git a/packages/sdk/src/schema/breakpoints.test.ts b/packages/sdk/src/schema/breakpoints.test.ts
index 1669d89cb2..e66a04eec7 100644
--- a/packages/sdk/src/schema/breakpoints.test.ts
+++ b/packages/sdk/src/schema/breakpoints.test.ts
@@ -1,10 +1,10 @@
import { describe, expect, test } from "vitest";
-import { Breakpoint } from "./breakpoints";
+import { breakpoint } from "./breakpoints";
describe("Breakpoint schema", () => {
test("accepts valid width-based breakpoints", () => {
expect(() =>
- Breakpoint.parse({
+ breakpoint.parse({
id: "1",
label: "Desktop",
minWidth: 1024,
@@ -12,7 +12,7 @@ describe("Breakpoint schema", () => {
).not.toThrow();
expect(() =>
- Breakpoint.parse({
+ breakpoint.parse({
id: "2",
label: "Mobile",
maxWidth: 767,
@@ -20,7 +20,7 @@ describe("Breakpoint schema", () => {
).not.toThrow();
expect(() =>
- Breakpoint.parse({
+ breakpoint.parse({
id: "3",
label: "Base",
})
@@ -29,7 +29,7 @@ describe("Breakpoint schema", () => {
test("accepts valid custom condition breakpoints", () => {
expect(() =>
- Breakpoint.parse({
+ breakpoint.parse({
id: "1",
label: "Portrait",
condition: "orientation:portrait",
@@ -37,7 +37,7 @@ describe("Breakpoint schema", () => {
).not.toThrow();
expect(() =>
- Breakpoint.parse({
+ breakpoint.parse({
id: "2",
label: "Hover",
condition: "hover:hover",
@@ -45,7 +45,7 @@ describe("Breakpoint schema", () => {
).not.toThrow();
expect(() =>
- Breakpoint.parse({
+ breakpoint.parse({
id: "3",
label: "Dark Mode",
condition: "prefers-color-scheme:dark",
@@ -54,14 +54,14 @@ describe("Breakpoint schema", () => {
});
test("normalizes empty condition to undefined", () => {
- const result = Breakpoint.parse({
+ const result = breakpoint.parse({
id: "1",
label: "Test",
condition: "",
});
expect(result.condition).toBeUndefined();
- const result2 = Breakpoint.parse({
+ const result2 = breakpoint.parse({
id: "2",
label: "Test",
condition: " ",
@@ -71,7 +71,7 @@ describe("Breakpoint schema", () => {
test("rejects breakpoint with both condition and width", () => {
expect(() =>
- Breakpoint.parse({
+ breakpoint.parse({
id: "1",
label: "Invalid",
condition: "orientation:portrait",
@@ -80,7 +80,7 @@ describe("Breakpoint schema", () => {
).toThrow();
expect(() =>
- Breakpoint.parse({
+ breakpoint.parse({
id: "2",
label: "Invalid",
condition: "hover:hover",
@@ -89,7 +89,7 @@ describe("Breakpoint schema", () => {
).toThrow();
expect(() =>
- Breakpoint.parse({
+ breakpoint.parse({
id: "3",
label: "Invalid",
condition: "hover:hover",
@@ -100,7 +100,7 @@ describe("Breakpoint schema", () => {
});
test("allows breakpoint with both minWidth and maxWidth when min < max", () => {
- const result = Breakpoint.parse({
+ const result = breakpoint.parse({
id: "1",
label: "Tablet range",
minWidth: 768,
@@ -113,7 +113,7 @@ describe("Breakpoint schema", () => {
test("rejects breakpoint with minWidth >= maxWidth", () => {
expect(() =>
- Breakpoint.parse({
+ breakpoint.parse({
id: "1",
label: "Invalid",
minWidth: 1024,
@@ -122,7 +122,7 @@ describe("Breakpoint schema", () => {
).toThrow();
expect(() =>
- Breakpoint.parse({
+ breakpoint.parse({
id: "2",
label: "Invalid",
minWidth: 768,
@@ -132,7 +132,7 @@ describe("Breakpoint schema", () => {
});
test("preserves valid condition values", () => {
- const result = Breakpoint.parse({
+ const result = breakpoint.parse({
id: "1",
label: "Portrait",
condition: "orientation:portrait",
@@ -143,7 +143,7 @@ describe("Breakpoint schema", () => {
});
test("handles complex conditions", () => {
- const result = Breakpoint.parse({
+ const result = breakpoint.parse({
id: "1",
label: "Complex",
condition: "orientation:portrait and hover:hover",
diff --git a/packages/sdk/src/schema/breakpoints.ts b/packages/sdk/src/schema/breakpoints.ts
index 4f59644c1e..92429c6593 100644
--- a/packages/sdk/src/schema/breakpoints.ts
+++ b/packages/sdk/src/schema/breakpoints.ts
@@ -1,10 +1,10 @@
import { z } from "zod";
-const BreakpointId = z.string();
+const breakpointId = z.string();
-export const Breakpoint = z
+export const breakpoint = z
.object({
- id: BreakpointId,
+ id: breakpointId,
label: z.string(),
minWidth: z.number().optional(),
maxWidth: z.number().optional(),
@@ -29,11 +29,11 @@ export const Breakpoint = z
return true;
}, "Width-based (minWidth/maxWidth) and condition are mutually exclusive, and minWidth must be less than maxWidth");
-export type Breakpoint = z.infer<typeof Breakpoint>;
+export type Breakpoint = z.infer<typeof breakpoint>;
-export const Breakpoints = z.map(BreakpointId, Breakpoint);
+export const breakpoints = z.map(breakpointId, breakpoint);
-export type Breakpoints = z.infer<typeof Breakpoints>;
+export type Breakpoints = z.infer<typeof breakpoints>;
export const initialBreakpoints: Array<Breakpoint> = [
{ id: "placeholder", label: "Base" },
diff --git a/packages/sdk/src/schema/component-meta.ts b/packages/sdk/src/schema/component-meta.ts
index 0a1b679c8a..ee63eaf4fd 100644
--- a/packages/sdk/src/schema/component-meta.ts
+++ b/packages/sdk/src/schema/component-meta.ts
@@ -1,18 +1,18 @@
import { z } from "zod";
import type { HtmlTags } from "html-tags";
import type { Simplify } from "type-fest";
-import { StyleValue, type CssProperty } from "@webstudio-is/css-engine";
-import { PropMeta } from "./prop-meta";
+import { styleValue, type CssProperty } from "@webstudio-is/css-engine";
+import { propMeta } from "./prop-meta";
-export const PresetStyleDecl = z.object({
+export const presetStyleDecl = z.object({
// State selector, e.g. :hover
state: z.optional(z.string()),
property: z.string(),
- value: StyleValue,
+ value: styleValue,
});
export type PresetStyleDecl = Simplify<
- Omit<z.infer<typeof PresetStyleDecl>, "property"> & {
+ Omit<z.infer<typeof presetStyleDecl>, "property"> & {
property: CssProperty;
}
>;
@@ -37,23 +37,23 @@ export const componentCategories = [
"internal",
] as const;
-export const ComponentState = z.object({
+export const componentState = z.object({
selector: z.string(),
label: z.string(),
});
-export type ComponentState = z.infer<typeof ComponentState>;
+export type ComponentState = z.infer<typeof componentState>;
/**
* rich-text - can be edited as rich text
* instance - other instances accepted
* ComponentName - accept specific components with none category
*/
-const ComponentContent = z.string() as z.ZodType<
+const componentContent = z.string() as z.ZodType<
"instance" | "rich-text" | (string & {})
>;
-export const ContentModel = z.object({
+export const contentModel = z.object({
/*
* instance - accepted by any parent with "instance" in children categories
* none - accepted by parents with this component name in children categories
@@ -62,18 +62,18 @@ export const ContentModel = z.object({
/**
* enforce direct children of category or components
*/
- children: z.array(ComponentContent),
+ children: z.array(componentContent),
/**
* enforce descendants of category or components
*/
- descendants: z.array(ComponentContent).optional(),
+ descendants: z.array(componentContent).optional(),
});
-export type ContentModel = z.infer<typeof ContentModel>;
+export type ContentModel = z.infer<typeof contentModel>;
-export const WsComponentMeta = z.object({
+export const wsComponentMeta = z.object({
category: z.enum(componentCategories).optional(),
- contentModel: ContentModel.optional(),
+ contentModel: contentModel.optional(),
// when this field is specified component receives
// prop with index of same components withiin specified ancestor
// important to automatically enumerate collections without
@@ -82,16 +82,16 @@ export const WsComponentMeta = z.object({
label: z.optional(z.string()),
description: z.string().optional(),
icon: z.string().optional(),
- presetStyle: z.optional(z.record(z.string(), z.array(PresetStyleDecl))),
- states: z.optional(z.array(ComponentState)),
+ presetStyle: z.optional(z.record(z.string(), z.array(presetStyleDecl))),
+ states: z.optional(z.array(componentState)),
order: z.number().optional(),
// properties and html attributes that will be always visible in properties panel
initialProps: z.array(z.string()).optional(),
- props: z.record(PropMeta).optional(),
+ props: z.record(propMeta).optional(),
});
export type WsComponentMeta = Omit<
- z.infer<typeof WsComponentMeta>,
+ z.infer<typeof wsComponentMeta>,
"presetStyle"
> & {
presetStyle?: PresetStyle;
diff --git a/packages/sdk/src/schema/data-sources.ts b/packages/sdk/src/schema/data-sources.ts
index 660c809d7e..c65b1e42a0 100644
--- a/packages/sdk/src/schema/data-sources.ts
+++ b/packages/sdk/src/schema/data-sources.ts
@@ -1,8 +1,8 @@
import { z } from "zod";
-const DataSourceId = z.string();
+const dataSourceId = z.string();
-export const DataSourceVariableValue = z.union([
+export const dataSourceVariableValue = z.union([
z.object({
type: z.literal("number"),
// initial value of variable store
@@ -26,10 +26,10 @@ export const DataSourceVariableValue = z.union([
}),
]);
-export const DataSource = z.union([
+export const dataSource = z.union([
z.object({
type: z.literal("variable"),
- id: DataSourceId,
+ id: dataSourceId,
// The instance should always be specified for variables,
// however, there was a bug in the embed template
// which produced variables without an instance
@@ -37,25 +37,25 @@ export const DataSource = z.union([
// if we make it required
scopeInstanceId: z.string().optional(),
name: z.string(),
- value: DataSourceVariableValue,
+ value: dataSourceVariableValue,
}),
z.object({
type: z.literal("parameter"),
- id: DataSourceId,
+ id: dataSourceId,
scopeInstanceId: z.string().optional(),
name: z.string(),
}),
z.object({
type: z.literal("resource"),
- id: DataSourceId,
+ id: dataSourceId,
scopeInstanceId: z.string().optional(),
name: z.string(),
resourceId: z.string(),
}),
]);
-export type DataSource = z.infer<typeof DataSource>;
+export type DataSource = z.infer<typeof dataSource>;
-export const DataSources = z.map(DataSourceId, DataSource);
+export const dataSources = z.map(dataSourceId, dataSource);
-export type DataSources = z.infer<typeof DataSources>;
+export type DataSources = z.infer<typeof dataSources>;
diff --git a/packages/sdk/src/schema/deployment.ts b/packages/sdk/src/schema/deployment.ts
index 39907018f0..da19971011 100644
--- a/packages/sdk/src/schema/deployment.ts
+++ b/packages/sdk/src/schema/deployment.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
-export const Templates = z.enum([
+export const templates = z.enum([
"docker",
"vercel",
"netlify",
@@ -9,15 +9,15 @@ export const Templates = z.enum([
"ssg-vercel",
]);
-export type Templates = z.infer<typeof Templates>;
+export type Templates = z.infer<typeof templates>;
-export const Deployment = z.union([
+export const deployment = z.union([
z.object({
destination: z.literal("static"),
name: z.string(),
assetsDomain: z.string(),
// Must be validated very strictly
- templates: z.array(Templates),
+ templates: z.array(templates),
}),
z.object({
destination: z.literal("saas").optional(),
@@ -31,4 +31,4 @@ export const Deployment = z.union([
}),
]);
-export type Deployment = z.infer<typeof Deployment>;
+export type Deployment = z.infer<typeof deployment>;
diff --git a/packages/sdk/src/schema/instances.ts b/packages/sdk/src/schema/instances.ts
index 7e8db4a486..788d583d55 100644
--- a/packages/sdk/src/schema/instances.ts
+++ b/packages/sdk/src/schema/instances.ts
@@ -1,40 +1,40 @@
import { z } from "zod";
-export const TextChild = z.object({
+export const textChild = z.object({
type: z.literal("text"),
value: z.string(),
placeholder: z.boolean().optional(),
});
-export type TextChild = z.infer<typeof TextChild>;
+export type TextChild = z.infer<typeof textChild>;
-const InstanceId = z.string();
+const instanceId = z.string();
-export const IdChild = z.object({
+export const idChild = z.object({
type: z.literal("id"),
- value: InstanceId,
+ value: instanceId,
});
-export type IdChild = z.infer<typeof IdChild>;
+export type IdChild = z.infer<typeof idChild>;
-export const ExpressionChild = z.object({
+export const expressionChild = z.object({
type: z.literal("expression"),
value: z.string(),
});
-export type ExpressionChild = z.infer<typeof ExpressionChild>;
+export type ExpressionChild = z.infer<typeof expressionChild>;
-export const InstanceChild = z.union([IdChild, TextChild, ExpressionChild]);
+export const instanceChild = z.union([idChild, textChild, expressionChild]);
-export const Instance = z.object({
+export const instance = z.object({
type: z.literal("instance"),
- id: InstanceId,
+ id: instanceId,
component: z.string(),
tag: z.string().optional(),
label: z.string().optional(),
- children: z.array(InstanceChild),
+ children: z.array(instanceChild),
});
-export type Instance = z.infer<typeof Instance>;
+export type Instance = z.infer<typeof instance>;
-export const Instances = z.map(InstanceId, Instance);
+export const instances = z.map(instanceId, instance);
-export type Instances = z.infer<typeof Instances>;
+export type Instances = z.infer<typeof instances>;
diff --git a/packages/sdk/src/schema/pages.test.ts b/packages/sdk/src/schema/pages.test.ts
index 6d28e8917b..c0a8c2c7bf 100644
--- a/packages/sdk/src/schema/pages.test.ts
+++ b/packages/sdk/src/schema/pages.test.ts
@@ -1,11 +1,11 @@
import { describe, expect, test } from "vitest";
import {
documentTypes,
- RedirectSourcePath,
- PageAuth,
- PagePath,
- Pages,
- ProjectNewRedirectPath,
+ redirectSourcePath,
+ pageAuth,
+ pagePath,
+ pages,
+ projectNewRedirectPath,
} from "./pages";
const validPages = {
@@ -39,7 +39,7 @@ const validPages = {
test("validates home page id references an existing page", () => {
expect(
- Pages.safeParse({
+ pages.safeParse({
...validPages,
homePageId: "missing",
}).error?.issues
@@ -55,7 +55,7 @@ test("validates home page id references an existing page", () => {
test("validates root folder id references an existing folder", () => {
expect(
- Pages.safeParse({
+ pages.safeParse({
...validPages,
rootFolderId: "missing",
}).error?.issues
@@ -69,7 +69,7 @@ test("validates root folder id references an existing folder", () => {
test("validates home page path is empty", () => {
expect(
- Pages.safeParse({
+ pages.safeParse({
...validPages,
pages: new Map(validPages.pages).set("home", {
...validPages.pages.get("home")!,
@@ -86,7 +86,7 @@ test("validates home page path is empty", () => {
test("validates non-home page path is not empty", () => {
expect(
- Pages.safeParse({
+ pages.safeParse({
...validPages,
pages: new Map(validPages.pages).set("other", {
id: "other",
@@ -112,7 +112,7 @@ test("validates non-home page path is not empty", () => {
test("supports text document type", () => {
expect(documentTypes).toContain("text");
expect(
- Pages.safeParse({
+ pages.safeParse({
...validPages,
pages: new Map(validPages.pages).set("text", {
id: "text",
@@ -132,7 +132,7 @@ test("supports text document type", () => {
test("validates page id matches its record key", () => {
expect(
- Pages.safeParse({
+ pages.safeParse({
...validPages,
pages: new Map(validPages.pages).set("home", {
...validPages.pages.get("home")!,
@@ -151,7 +151,7 @@ test("validates page id matches its record key", () => {
test("validates folder id matches its record key", () => {
expect(
- Pages.safeParse({
+ pages.safeParse({
...validPages,
folders: new Map(validPages.folders).set("root", {
...validPages.folders.get("root")!,
@@ -168,7 +168,7 @@ test("validates folder id matches its record key", () => {
test("validates folder children reference existing pages or folders", () => {
expect(
- Pages.safeParse({
+ pages.safeParse({
...validPages,
folders: new Map(validPages.folders).set("root", {
...validPages.folders.get("root")!,
@@ -185,7 +185,7 @@ test("validates folder children reference existing pages or folders", () => {
test("validates root folder starts with home page", () => {
expect(
- Pages.safeParse({
+ pages.safeParse({
...validPages,
pages: new Map(validPages.pages).set("other", {
id: "other",
@@ -210,7 +210,7 @@ test("validates root folder starts with home page", () => {
test("validates root folder is not nested", () => {
expect(
- Pages.safeParse({
+ pages.safeParse({
...validPages,
folders: new Map(validPages.folders).set("folder", {
id: "folder",
@@ -230,7 +230,7 @@ test("validates root folder is not nested", () => {
describe("PageAuth", () => {
test("accepts basic auth metadata", () => {
expect(
- PageAuth.parse({
+ pageAuth.parse({
method: "basic",
login: "admin",
password: "secret",
@@ -244,7 +244,7 @@ describe("PageAuth", () => {
test("normalizes legacy basic auth metadata", () => {
expect(
- PageAuth.parse({
+ pageAuth.parse({
type: "basic",
login: "admin",
password: "secret",
@@ -258,7 +258,7 @@ describe("PageAuth", () => {
test("rejects invalid basic auth metadata", () => {
expect(
- PageAuth.safeParse({
+ pageAuth.safeParse({
method: "basic",
login: "admin:root",
password: "secret phrase",
@@ -280,7 +280,7 @@ describe("PageAuth", () => {
test("validates children are registered in only one folder", () => {
expect(
- Pages.safeParse({
+ pages.safeParse({
...validPages,
folders: new Map(validPages.folders).set("folder", {
id: "folder",
@@ -299,7 +299,7 @@ test("validates children are registered in only one folder", () => {
test("validates folders do not contain cycles", () => {
expect(
- Pages.safeParse({
+ pages.safeParse({
...validPages,
folders: new Map([
...validPages.folders,
@@ -333,51 +333,51 @@ test("validates folders do not contain cycles", () => {
);
});
-describe("RedirectSourcePath", () => {
+describe("redirectSourcePath", () => {
describe("basic validation", () => {
test("accepts valid path", () => {
- expect(RedirectSourcePath.safeParse("/about").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/blog/post").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/about").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/blog/post").success).toBe(true);
});
test("rejects empty string", () => {
- const result = RedirectSourcePath.safeParse("");
+ const result = redirectSourcePath.safeParse("");
expect(result.success).toBe(false);
});
test("rejects just a slash", () => {
- const result = RedirectSourcePath.safeParse("/");
+ const result = redirectSourcePath.safeParse("/");
expect(result.success).toBe(false);
});
test("must start with /", () => {
- const result = RedirectSourcePath.safeParse("about");
+ const result = redirectSourcePath.safeParse("about");
expect(result.success).toBe(false);
});
test("accepts trailing slash", () => {
- const result = RedirectSourcePath.safeParse("/about/");
+ const result = redirectSourcePath.safeParse("/about/");
expect(result.success).toBe(true);
});
test("accepts repeated slashes inside the path", () => {
- const result = RedirectSourcePath.safeParse("/about//page");
+ const result = redirectSourcePath.safeParse("/about//page");
expect(result.success).toBe(true);
});
test("rejects protocol-relative paths", () => {
- const result = RedirectSourcePath.safeParse("//example.com/path");
+ const result = redirectSourcePath.safeParse("//example.com/path");
expect(result.success).toBe(false);
});
test("rejects /s prefix (reserved)", () => {
- expect(RedirectSourcePath.safeParse("/s").success).toBe(false);
- expect(RedirectSourcePath.safeParse("/s/css").success).toBe(false);
+ expect(redirectSourcePath.safeParse("/s").success).toBe(false);
+ expect(redirectSourcePath.safeParse("/s/css").success).toBe(false);
});
test("rejects /build prefix (reserved)", () => {
- expect(RedirectSourcePath.safeParse("/build").success).toBe(false);
- expect(RedirectSourcePath.safeParse("/build/main.js").success).toBe(
+ expect(redirectSourcePath.safeParse("/build").success).toBe(false);
+ expect(redirectSourcePath.safeParse("/build/main.js").success).toBe(
false
);
});
@@ -385,29 +385,29 @@ describe("RedirectSourcePath", () => {
describe("special characters", () => {
test("accepts wildcards", () => {
- expect(RedirectSourcePath.safeParse("/blog/*").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/blog/*").success).toBe(true);
});
test("accepts dynamic segments", () => {
- expect(RedirectSourcePath.safeParse("/:slug").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/blog/:id").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/:slug").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/blog/:id").success).toBe(true);
});
test("accepts optional segments", () => {
- expect(RedirectSourcePath.safeParse("/:id?").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/:id?").success).toBe(true);
});
test("accepts query strings", () => {
- expect(RedirectSourcePath.safeParse("/search?q=test").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/search?q=test").success).toBe(true);
expect(
- RedirectSourcePath.safeParse("/path?url=https://example.com/a?b=c")
+ redirectSourcePath.safeParse("/path?url=https://example.com/a?b=c")
.success
).toBe(true);
});
test("accepts URL-encoded characters", () => {
- expect(RedirectSourcePath.safeParse("/hello%20world").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/%E6%B8%AF%E8%81%9E").success).toBe(
+ expect(redirectSourcePath.safeParse("/hello%20world").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/%E6%B8%AF%E8%81%9E").success).toBe(
true
);
});
@@ -415,124 +415,124 @@ describe("RedirectSourcePath", () => {
describe("browser-requestable characters", () => {
test("accepts spaces", () => {
- expect(RedirectSourcePath.safeParse("/hello world").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/path with spaces").success).toBe(
+ expect(redirectSourcePath.safeParse("/hello world").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/path with spaces").success).toBe(
true
);
});
test("accepts characters browsers encode in paths", () => {
- expect(RedirectSourcePath.safeParse("/path<script>").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/path>other").success).toBe(true);
- expect(RedirectSourcePath.safeParse('/path"quote').success).toBe(true);
- expect(RedirectSourcePath.safeParse("/path{test}").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/path|other").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/path[0]").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/path`backtick").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/path<script>").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/path>other").success).toBe(true);
+ expect(redirectSourcePath.safeParse('/path"quote').success).toBe(true);
+ expect(redirectSourcePath.safeParse("/path{test}").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/path|other").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/path[0]").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/path`backtick").success).toBe(true);
});
test("rejects backslash because URL parsers normalize it to slash", () => {
- expect(RedirectSourcePath.safeParse("/path\\other").success).toBe(false);
+ expect(redirectSourcePath.safeParse("/path\\other").success).toBe(false);
});
test("rejects control characters", () => {
- expect(RedirectSourcePath.safeParse("/line\nfeed").success).toBe(false);
- expect(RedirectSourcePath.safeParse("/tab\tfeed").success).toBe(false);
+ expect(redirectSourcePath.safeParse("/line\nfeed").success).toBe(false);
+ expect(redirectSourcePath.safeParse("/tab\tfeed").success).toBe(false);
});
});
describe("non-Latin characters (Unicode/UTF-8)", () => {
test("accepts Chinese characters (Simplified)", () => {
- expect(RedirectSourcePath.safeParse("/关于我们").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/产品/手机").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/新闻").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/关于我们").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/产品/手机").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/新闻").success).toBe(true);
});
test("accepts Chinese characters (Traditional)", () => {
- expect(RedirectSourcePath.safeParse("/關於我們").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/港聞").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/繁體中文").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/關於我們").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/港聞").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/繁體中文").success).toBe(true);
});
test("accepts Japanese characters (Hiragana)", () => {
- expect(RedirectSourcePath.safeParse("/こんにちは").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/ブログ/記事").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/こんにちは").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/ブログ/記事").success).toBe(true);
});
test("accepts Japanese characters (Katakana)", () => {
- expect(RedirectSourcePath.safeParse("/カテゴリ").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/カテゴリ").success).toBe(true);
});
test("accepts Japanese characters (Kanji)", () => {
- expect(RedirectSourcePath.safeParse("/日本語").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/東京").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/日本語").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/東京").success).toBe(true);
});
test("accepts Korean characters (Hangul)", () => {
- expect(RedirectSourcePath.safeParse("/한국어").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/블로그/포스트").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/서울").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/한국어").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/블로그/포스트").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/서울").success).toBe(true);
});
test("accepts Cyrillic characters", () => {
- expect(RedirectSourcePath.safeParse("/привет").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/о-нас").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/блог/статья").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/привет").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/о-нас").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/блог/статья").success).toBe(true);
});
test("accepts Arabic characters", () => {
- expect(RedirectSourcePath.safeParse("/مرحبا").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/عن-الشركة").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/مرحبا").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/عن-الشركة").success).toBe(true);
});
test("accepts Hebrew characters", () => {
- expect(RedirectSourcePath.safeParse("/שלום").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/אודות").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/שלום").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/אודות").success).toBe(true);
});
test("accepts Thai characters", () => {
- expect(RedirectSourcePath.safeParse("/สวัสดี").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/เกี่ยวกับเรา").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/สวัสดี").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/เกี่ยวกับเรา").success).toBe(true);
});
test("accepts Greek characters", () => {
- expect(RedirectSourcePath.safeParse("/γεια").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/σχετικά").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/γεια").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/σχετικά").success).toBe(true);
});
test("accepts mixed Latin and non-Latin characters", () => {
- expect(RedirectSourcePath.safeParse("/blog/关于").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/news/港聞").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/category/日本語").success).toBe(
+ expect(redirectSourcePath.safeParse("/blog/关于").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/news/港聞").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/category/日本語").success).toBe(
true
);
});
test("accepts European characters with diacritics", () => {
- expect(RedirectSourcePath.safeParse("/über-uns").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/café").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/niño").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/naïve").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/résumé").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/über-uns").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/café").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/niño").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/naïve").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/résumé").success).toBe(true);
});
test("accepts emoji characters", () => {
- expect(RedirectSourcePath.safeParse("/🎉").success).toBe(true);
- expect(RedirectSourcePath.safeParse("/hello-🌍").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/🎉").success).toBe(true);
+ expect(redirectSourcePath.safeParse("/hello-🌍").success).toBe(true);
});
});
});
-describe("PagePath", () => {
+describe("pagePath", () => {
describe("path length validation", () => {
test("accepts a path of exactly 255 characters", () => {
const path = "/" + "a".repeat(254);
- expect(PagePath.safeParse(path).success).toBe(true);
+ expect(pagePath.safeParse(path).success).toBe(true);
});
test("rejects a path exceeding 255 characters", () => {
const path = "/" + "a".repeat(255);
- const result = PagePath.safeParse(path);
+ const result = pagePath.safeParse(path);
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error.issues[0].message).toBe(
@@ -543,30 +543,30 @@ describe("PagePath", () => {
});
});
-describe("ProjectNewRedirectPath", () => {
+describe("projectNewRedirectPath", () => {
test("accepts relative paths", () => {
- expect(ProjectNewRedirectPath.safeParse("/about").success).toBe(true);
- expect(ProjectNewRedirectPath.safeParse("/").success).toBe(true);
+ expect(projectNewRedirectPath.safeParse("/about").success).toBe(true);
+ expect(projectNewRedirectPath.safeParse("/").success).toBe(true);
});
test("accepts absolute URLs", () => {
expect(
- ProjectNewRedirectPath.safeParse("https://example.com/page").success
+ projectNewRedirectPath.safeParse("https://example.com/page").success
).toBe(true);
});
test("accepts non-Latin character paths", () => {
- expect(ProjectNewRedirectPath.safeParse("/关于我们").success).toBe(true);
- expect(ProjectNewRedirectPath.safeParse("/日本語").success).toBe(true);
- expect(ProjectNewRedirectPath.safeParse("/한국어").success).toBe(true);
+ expect(projectNewRedirectPath.safeParse("/关于我们").success).toBe(true);
+ expect(projectNewRedirectPath.safeParse("/日本語").success).toBe(true);
+ expect(projectNewRedirectPath.safeParse("/한국어").success).toBe(true);
});
test("rejects empty string", () => {
- expect(ProjectNewRedirectPath.safeParse("").success).toBe(false);
+ expect(projectNewRedirectPath.safeParse("").success).toBe(false);
});
test("rejects truly invalid URLs", () => {
- expect(ProjectNewRedirectPath.safeParse("http://[invalid").success).toBe(
+ expect(projectNewRedirectPath.safeParse("http://[invalid").success).toBe(
false
);
});
diff --git a/packages/sdk/src/schema/pages.ts b/packages/sdk/src/schema/pages.ts
index 7f6dbf52c3..481fc24304 100644
--- a/packages/sdk/src/schema/pages.ts
+++ b/packages/sdk/src/schema/pages.ts
@@ -10,34 +10,34 @@ export type System = {
const MIN_TITLE_LENGTH = 2;
-export const PageId = z.string();
-export const FolderId = z.string();
+export const pageId = z.string();
+export const folderId = z.string();
-export const FolderName = z
+export const folderName = z
.string()
.refine((value) => value.trim() !== "", "Can't be empty");
-const Slug = z
+const slug = z
.string()
.refine(
(path) => /^[-a-z0-9]*$/.test(path),
"Only a-z, 0-9 and - are allowed"
);
-export const Folder = z.object({
- id: FolderId,
- name: FolderName,
- slug: Slug,
- children: z.array(z.union([FolderId, PageId])),
+export const folder = z.object({
+ id: folderId,
+ name: folderName,
+ slug: slug,
+ children: z.array(z.union([folderId, pageId])),
});
-export type Folder = z.infer<typeof Folder>;
+export type Folder = z.infer<typeof folder>;
-export const PageName = z
+export const pageName = z
.string()
.refine((value) => value.trim() !== "", "Can't be empty");
-export const PageTitle = z
+export const pageTitle = z
.string()
.refine(
(val) => val.length >= MIN_TITLE_LENGTH,
@@ -46,7 +46,7 @@ export const PageTitle = z
export const documentTypes = ["html", "xml", "text"] as const;
-const BasicAuthFields = {
+const basicAuthFields = {
login: z.string(),
password: z.string(),
};
@@ -70,17 +70,17 @@ const validateBasicAuthFields = (
}
};
-const PageBasicAuth = z
+const pageBasicAuth = z
.object({
method: z.literal("basic"),
- ...BasicAuthFields,
+ ...basicAuthFields,
})
.superRefine(validateBasicAuthFields);
-const LegacyPageBasicAuth = z
+const legacyPageBasicAuth = z
.object({
type: z.literal("basic"),
- ...BasicAuthFields,
+ ...basicAuthFields,
})
.superRefine(validateBasicAuthFields)
.transform(({ login, password }) => ({
@@ -89,13 +89,13 @@ const LegacyPageBasicAuth = z
password,
}));
-export const PageAuth = z.union([PageBasicAuth, LegacyPageBasicAuth]);
-export type PageAuth = z.infer<typeof PageAuth>;
+export const pageAuth = z.union([pageBasicAuth, legacyPageBasicAuth]);
+export type PageAuth = z.infer<typeof pageAuth>;
const commonPageFields = {
- id: PageId,
- name: PageName,
- title: PageTitle,
+ id: pageId,
+ name: pageName,
+ title: pageTitle,
history: z.optional(z.array(z.string())),
rootInstanceId: z.string(),
systemDataSourceId: z.string().optional(),
@@ -110,7 +110,7 @@ const commonPageFields = {
redirect: z.string().optional(),
documentType: z.optional(z.enum(documentTypes)),
content: z.string().optional(),
- auth: PageAuth.optional(),
+ auth: pageAuth.optional(),
custom: z
.array(
z.object({
@@ -129,11 +129,11 @@ const commonPageFields = {
),
} as const;
-export const HomePagePath = z
+export const homePagePath = z
.string()
.refine((path) => path === "", "Home page path must be empty");
-const DefaultPagePage = z
+const defaultPagePath = z
.string()
.refine((path) => path !== "", "Can't be empty")
.refine((path) => path !== "/", "Can't be just a /")
@@ -156,7 +156,7 @@ const DefaultPagePage = z
)
.refine((path) => path.length <= 255, "Path can't exceed 255 characters");
-export const RedirectSourcePath = z
+export const redirectSourcePath = z
.string()
.refine((path) => path !== "", "Can't be empty")
.refine((path) => path !== "/", "Can't be just a /")
@@ -189,28 +189,28 @@ export const RedirectSourcePath = z
"/build prefix is reserved for the system"
);
-export const PagePath = DefaultPagePage.refine(
+export const pagePath = defaultPagePath.refine(
(path) => path === "" || path.startsWith("/"),
"Must start with a / or a full URL e.g. https://website.org"
);
-export const Page = z.object({
+export const page = z.object({
...commonPageFields,
- path: z.union([HomePagePath, PagePath]),
+ path: z.union([homePagePath, pagePath]),
});
-export const PageTemplate = z.object({
- id: PageId,
- name: PageName,
- title: PageTitle,
+export const pageTemplate = z.object({
+ id: pageId,
+ name: pageName,
+ title: pageTitle,
rootInstanceId: z.string(),
systemDataSourceId: z.string().optional(),
meta: commonPageFields.meta,
});
-export type PageTemplate = z.infer<typeof PageTemplate>;
+export type PageTemplate = z.infer<typeof pageTemplate>;
-export const ProjectMeta = z.object({
+export const projectMeta = z.object({
// All fields are optional to ensure consistency and allow for the addition of new fields without requiring migration
siteName: z.string().optional(),
contactEmail: z.string().optional(),
@@ -218,9 +218,9 @@ export const ProjectMeta = z.object({
code: z.string().optional(),
auth: z.string().optional(),
});
-export type ProjectMeta = z.infer<typeof ProjectMeta>;
+export type ProjectMeta = z.infer<typeof projectMeta>;
-export const ProjectNewRedirectPath = z
+export const projectNewRedirectPath = z
.string()
.min(1, "Path is required")
.refine((data) => {
@@ -234,32 +234,32 @@ export const ProjectNewRedirectPath = z
}
}, "Must be a valid URL");
-export const PageRedirect = z.object({
- old: RedirectSourcePath,
- new: ProjectNewRedirectPath,
+export const pageRedirect = z.object({
+ old: redirectSourcePath,
+ new: projectNewRedirectPath,
status: z.enum(["301", "302"]).optional(),
});
-export type PageRedirect = z.infer<typeof PageRedirect>;
+export type PageRedirect = z.infer<typeof pageRedirect>;
-export const CompilerSettings = z.object({
+export const compilerSettings = z.object({
// All fields are optional to ensure consistency and allow for the addition of new fields without requiring migration
atomicStyles: z.boolean().optional(),
});
-export type CompilerSettings = z.infer<typeof CompilerSettings>;
+export type CompilerSettings = z.infer<typeof compilerSettings>;
-export type Page = z.infer<typeof Page>;
+export type Page = z.infer<typeof page>;
-export const Pages = z
+export const pages = z
.object({
- meta: ProjectMeta.optional(),
- compiler: CompilerSettings.optional(),
- redirects: z.array(PageRedirect).optional(),
- homePageId: PageId,
- rootFolderId: FolderId,
- pages: z.map(PageId, Page),
- pageTemplates: z.map(PageId, PageTemplate).optional(),
+ meta: projectMeta.optional(),
+ compiler: compilerSettings.optional(),
+ redirects: z.array(pageRedirect).optional(),
+ homePageId: pageId,
+ rootFolderId: folderId,
+ pages: z.map(pageId, page),
+ pageTemplates: z.map(pageId, pageTemplate).optional(),
folders: z
- .map(FolderId, Folder)
+ .map(folderId, folder)
.refine((folders) => folders.size > 0, "Folders can't be empty"),
})
.superRefine((pages, context) => {
@@ -405,4 +405,4 @@ export const Pages = z
}
});
-export type Pages = z.infer<typeof Pages>;
+export type Pages = z.infer<typeof pages>;
diff --git a/packages/sdk/src/schema/prop-meta.ts b/packages/sdk/src/schema/prop-meta.ts
index c7eaadf33e..d68dc1123b 100644
--- a/packages/sdk/src/schema/prop-meta.ts
+++ b/packages/sdk/src/schema/prop-meta.ts
@@ -17,7 +17,7 @@ const common = {
contentMode: z.boolean().optional(),
};
-const Tag = z.object({
+const tag = z.object({
...common,
control: z.literal("tag"),
type: z.literal("string"),
@@ -25,21 +25,21 @@ const Tag = z.object({
options: z.array(z.string()),
});
-const Number = z.object({
+const number = z.object({
...common,
control: z.literal("number"),
type: z.literal("number"),
defaultValue: z.number().optional(),
});
-const Range = z.object({
+const range = z.object({
...common,
control: z.literal("range"),
type: z.literal("number"),
defaultValue: z.number().optional(),
});
-const Text = z.object({
+const text = z.object({
...common,
control: z.literal("text"),
type: z.literal("string"),
@@ -51,14 +51,14 @@ const Text = z.object({
rows: z.number().optional(),
});
-const Resource = z.object({
+const resource = z.object({
...common,
control: z.literal("resource"),
type: z.literal("resource"),
defaultValue: z.string().optional(),
});
-const Code = z.object({
+const code = z.object({
...common,
control: z.literal("code"),
type: z.literal("string"),
@@ -66,28 +66,28 @@ const Code = z.object({
defaultValue: z.string().optional(),
});
-const CodeText = z.object({
+const codeText = z.object({
...common,
control: z.literal("codetext"),
type: z.literal("string"),
defaultValue: z.string().optional(),
});
-const Color = z.object({
+const color = z.object({
...common,
control: z.literal("color"),
type: z.literal("string"),
defaultValue: z.string().optional(),
});
-const Boolean = z.object({
+const boolean = z.object({
...common,
control: z.literal("boolean"),
type: z.literal("boolean"),
defaultValue: z.boolean().optional(),
});
-const Radio = z.object({
+const radio = z.object({
...common,
control: z.literal("radio"),
type: z.literal("string"),
@@ -95,7 +95,7 @@ const Radio = z.object({
options: z.array(z.string()),
});
-const InlineRadio = z.object({
+const inlineRadio = z.object({
...common,
control: z.literal("inline-radio"),
type: z.literal("string"),
@@ -103,7 +103,7 @@ const InlineRadio = z.object({
options: z.array(z.string()),
});
-const Select = z.object({
+const select = z.object({
...common,
control: z.literal("select"),
type: z.literal("string"),
@@ -111,7 +111,7 @@ const Select = z.object({
options: z.array(z.string()),
});
-const TimeZone = z.object({
+const timeZone = z.object({
...common,
control: z.literal("timeZone"),
type: z.literal("string"),
@@ -119,7 +119,7 @@ const TimeZone = z.object({
options: z.array(z.string()),
});
-const Check = z.object({
+const check = z.object({
...common,
control: z.literal("check"),
type: z.literal("string[]"),
@@ -127,7 +127,7 @@ const Check = z.object({
options: z.array(z.string()),
});
-const InlineCheck = z.object({
+const inlineCheck = z.object({
...common,
control: z.literal("inline-check"),
type: z.literal("string[]"),
@@ -135,7 +135,7 @@ const InlineCheck = z.object({
options: z.array(z.string()),
});
-const MultiSelect = z.object({
+const multiSelect = z.object({
...common,
control: z.literal("multi-select"),
type: z.literal("string[]"),
@@ -143,7 +143,7 @@ const MultiSelect = z.object({
options: z.array(z.string()),
});
-const File = z.object({
+const file = z.object({
...common,
control: z.literal("file"),
type: z.literal("string"),
@@ -152,14 +152,14 @@ const File = z.object({
accept: z.string().optional(),
});
-const Url = z.object({
+const url = z.object({
...common,
control: z.literal("url"),
type: z.literal("string"),
defaultValue: z.string().optional(),
});
-const Json = z.object({
+const json = z.object({
...common,
control: z.literal("json"),
type: z.literal("json"),
@@ -167,7 +167,7 @@ const Json = z.object({
});
// we neither generate date nor support it in props panel, listed here for completeness
-const Date = z.object({
+const date = z.object({
...common,
control: z.literal("date"),
@@ -177,51 +177,51 @@ const Date = z.object({
defaultValue: z.string().optional(),
});
-const Action = z.object({
+const action = z.object({
...common,
control: z.literal("action"),
type: z.literal("action"),
defaultValue: z.undefined().optional(),
});
-const TextContent = z.object({
+const textContent = z.object({
...common,
control: z.literal("textContent"),
type: z.literal("string"),
defaultValue: z.string().optional(),
});
-const AnimationAction = z.object({
+const animationAction = z.object({
...common,
control: z.literal("animationAction"),
type: z.literal("animationAction"),
defaultValue: z.undefined().optional(),
});
-export const PropMeta = z.union([
- Tag,
- Number,
- Range,
- Text,
- Resource,
- Code,
- CodeText,
- Color,
- Boolean,
- Radio,
- InlineRadio,
- Select,
- TimeZone,
- MultiSelect,
- Check,
- InlineCheck,
- File,
- Url,
- Json,
- Date,
- Action,
- TextContent,
- AnimationAction,
+export const propMeta = z.union([
+ tag,
+ number,
+ range,
+ text,
+ resource,
+ code,
+ codeText,
+ color,
+ boolean,
+ radio,
+ inlineRadio,
+ select,
+ timeZone,
+ multiSelect,
+ check,
+ inlineCheck,
+ file,
+ url,
+ json,
+ date,
+ action,
+ textContent,
+ animationAction,
]);
-export type PropMeta = z.infer<typeof PropMeta>;
+export type PropMeta = z.infer<typeof propMeta>;
diff --git a/packages/sdk/src/schema/props.ts b/packages/sdk/src/schema/props.ts
index a17cbf5212..648bf14c93 100644
--- a/packages/sdk/src/schema/props.ts
+++ b/packages/sdk/src/schema/props.ts
@@ -1,16 +1,16 @@
import { z } from "zod";
-import { animationActionSchema } from "./animation-schema";
+import { animationAction } from "./animation-schema";
-const PropId = z.string();
+const propId = z.string();
const baseProp = {
- id: PropId,
+ id: propId,
instanceId: z.string(),
name: z.string(),
required: z.optional(z.boolean()),
};
-export const Prop = z.union([
+export const prop = z.union([
z.object({
...baseProp,
type: z.literal("number"),
@@ -84,12 +84,12 @@ export const Prop = z.union([
z.object({
...baseProp,
type: z.literal("animationAction"),
- value: animationActionSchema,
+ value: animationAction,
}),
]);
-export type Prop = z.infer<typeof Prop>;
+export type Prop = z.infer<typeof prop>;
-export const Props = z.map(PropId, Prop);
+export const props = z.map(propId, prop);
-export type Props = z.infer<typeof Props>;
+export type Props = z.infer<typeof props>;
diff --git a/packages/sdk/src/schema/resources.ts b/packages/sdk/src/schema/resources.ts
index a22b0a0134..521559256c 100644
--- a/packages/sdk/src/schema/resources.ts
+++ b/packages/sdk/src/schema/resources.ts
@@ -1,19 +1,19 @@
import { z } from "zod";
-const ResourceId = z.string();
+const resourceId = z.string();
-const Method = z.union([
+const method = z.union([
z.literal("get"),
z.literal("post"),
z.literal("put"),
z.literal("delete"),
]);
-export const Resource = z.object({
- id: ResourceId,
+export const resource = z.object({
+ id: resourceId,
name: z.string(),
control: z.optional(z.union([z.literal("system"), z.literal("graphql")])),
- method: Method,
+ method: method,
// expression
url: z.string(),
searchParams: z
@@ -36,12 +36,12 @@ export const Resource = z.object({
body: z.optional(z.string()),
});
-export type Resource = z.infer<typeof Resource>;
+export type Resource = z.infer<typeof resource>;
// evaluated variant of resource
-export const ResourceRequest = z.object({
+export const resourceRequest = z.object({
name: z.string(),
- method: Method,
+ method: method,
url: z.string(),
searchParams: z.array(
z.object({
@@ -60,8 +60,8 @@ export const ResourceRequest = z.object({
body: z.optional(z.unknown()),
});
-export type ResourceRequest = z.infer<typeof ResourceRequest>;
+export type ResourceRequest = z.infer<typeof resourceRequest>;
-export const Resources = z.map(ResourceId, Resource);
+export const resources = z.map(resourceId, resource);
-export type Resources = z.infer<typeof Resources>;
+export type Resources = z.infer<typeof resources>;
diff --git a/packages/sdk/src/schema/style-source-selections.ts b/packages/sdk/src/schema/style-source-selections.ts
index 8ae7fde10a..26af347c63 100644
--- a/packages/sdk/src/schema/style-source-selections.ts
+++ b/packages/sdk/src/schema/style-source-selections.ts
@@ -1,16 +1,16 @@
import { z } from "zod";
-const InstanceId = z.string();
+const instanceId = z.string();
-const StyleSourceId = z.string();
+const styleSourceId = z.string();
-export const StyleSourceSelection = z.object({
- instanceId: InstanceId,
- values: z.array(StyleSourceId),
+export const styleSourceSelection = z.object({
+ instanceId: instanceId,
+ values: z.array(styleSourceId),
});
-export type StyleSourceSelection = z.infer<typeof StyleSourceSelection>;
+export type StyleSourceSelection = z.infer<typeof styleSourceSelection>;
-export const StyleSourceSelections = z.map(InstanceId, StyleSourceSelection);
+export const styleSourceSelections = z.map(instanceId, styleSourceSelection);
-export type StyleSourceSelections = z.infer<typeof StyleSourceSelections>;
+export type StyleSourceSelections = z.infer<typeof styleSourceSelections>;
diff --git a/packages/sdk/src/schema/style-sources.test.ts b/packages/sdk/src/schema/style-sources.test.ts
index 8a29c75d03..e81f52f25b 100644
--- a/packages/sdk/src/schema/style-sources.test.ts
+++ b/packages/sdk/src/schema/style-sources.test.ts
@@ -1,10 +1,10 @@
import { describe, expect, test } from "vitest";
-import { StyleSource } from "./style-sources";
+import { styleSource } from "./style-sources";
describe("StyleSource", () => {
test("parses unlocked tokens without locked field", () => {
expect(
- StyleSource.parse({
+ styleSource.parse({
id: "token",
type: "token",
name: "Token",
@@ -18,7 +18,7 @@ describe("StyleSource", () => {
test("parses locked tokens", () => {
expect(
- StyleSource.parse({
+ styleSource.parse({
id: "token",
type: "token",
name: "Token",
diff --git a/packages/sdk/src/schema/style-sources.ts b/packages/sdk/src/schema/style-sources.ts
index f9c78a5dd8..bd6d4a69f8 100644
--- a/packages/sdk/src/schema/style-sources.ts
+++ b/packages/sdk/src/schema/style-sources.ts
@@ -1,25 +1,25 @@
import { z } from "zod";
-const StyleSourceId = z.string();
+const styleSourceId = z.string();
-const StyleSourceToken = z.object({
+const styleSourceToken = z.object({
type: z.literal("token"),
- id: StyleSourceId,
+ id: styleSourceId,
name: z.string(),
locked: z.boolean().optional(),
});
-export type StyleSourceToken = z.infer<typeof StyleSourceToken>;
+export type StyleSourceToken = z.infer<typeof styleSourceToken>;
-const StyleSourceLocal = z.object({
+const styleSourceLocal = z.object({
type: z.literal("local"),
- id: StyleSourceId,
+ id: styleSourceId,
});
-export const StyleSource = z.union([StyleSourceToken, StyleSourceLocal]);
+export const styleSource = z.union([styleSourceToken, styleSourceLocal]);
-export type StyleSource = z.infer<typeof StyleSource>;
+export type StyleSource = z.infer<typeof styleSource>;
-export const StyleSources = z.map(StyleSourceId, StyleSource);
+export const styleSources = z.map(styleSourceId, styleSource);
-export type StyleSources = z.infer<typeof StyleSources>;
+export type StyleSources = z.infer<typeof styleSources>;
diff --git a/packages/sdk/src/schema/styles.ts b/packages/sdk/src/schema/styles.ts
index 8c4574be4b..2bcf64a1e4 100644
--- a/packages/sdk/src/schema/styles.ts
+++ b/packages/sdk/src/schema/styles.ts
@@ -1,14 +1,14 @@
import { z } from "zod";
-import { type StyleProperty, StyleValue } from "@webstudio-is/css-engine";
+import { type StyleProperty, styleValue } from "@webstudio-is/css-engine";
import type { Simplify } from "type-fest";
-const StyleDeclRaw = z.object({
+const styleDeclRaw = z.object({
styleSourceId: z.string(),
breakpointId: z.string(),
state: z.optional(z.string()),
// @todo can't figure out how to make property to be enum
property: z.string(),
- value: StyleValue,
+ value: styleValue,
listed: z
.boolean()
.optional()
@@ -16,11 +16,11 @@ const StyleDeclRaw = z.object({
});
export type StyleDecl = Simplify<
- Omit<z.infer<typeof StyleDeclRaw>, "property"> & {
+ Omit<z.infer<typeof styleDeclRaw>, "property"> & {
property: StyleProperty;
}
>;
-export const StyleDecl = StyleDeclRaw as z.ZodType<StyleDecl>;
+export const styleDecl = styleDeclRaw as z.ZodType<StyleDecl>;
export type StyleDeclKey = string;
@@ -32,6 +32,6 @@ export const getStyleDeclKey = (
}:${styleDecl.state ?? ""}`;
};
-export const Styles = z.map(z.string(), StyleDecl);
+export const styles = z.map(z.string(), styleDecl);
export type Styles = Map<string, StyleDecl>;
diff --git a/packages/sdk/src/schema/webstudio.ts b/packages/sdk/src/schema/webstudio.ts
index 43f5bf0772..3107071d44 100644
--- a/packages/sdk/src/schema/webstudio.ts
+++ b/packages/sdk/src/schema/webstudio.ts
@@ -1,36 +1,36 @@
import { z } from "zod";
-import { Asset, Assets } from "./assets";
-import { DataSource, DataSources } from "./data-sources";
-import { Resource, Resources } from "./resources";
-import { Instance, InstanceChild, Instances } from "./instances";
-import { Prop, Props } from "./props";
-import { Breakpoint, Breakpoints } from "./breakpoints";
+import { asset, type Assets } from "./assets";
+import { dataSource, type DataSources } from "./data-sources";
+import { resource, type Resources } from "./resources";
+import { instance, instanceChild, type Instances } from "./instances";
+import { prop, type Props } from "./props";
+import { breakpoint, type Breakpoints } from "./breakpoints";
import {
- StyleSourceSelection,
- StyleSourceSelections,
+ styleSourceSelection,
+ type StyleSourceSelections,
} from "./style-source-selections";
-import { StyleSource, StyleSources } from "./style-sources";
-import { StyleDecl, Styles } from "./styles";
-import { Pages } from "./pages";
+import { styleSource, type StyleSources } from "./style-sources";
+import { styleDecl, type Styles } from "./styles";
+import type { Pages } from "./pages";
/**
* transferrable and insertable part of webstudio data
* may contain reusable parts like tokens and custom components
*/
-export const WebstudioFragment = z.object({
- children: z.array(InstanceChild),
- instances: z.array(Instance),
- assets: z.array(Asset),
- dataSources: z.array(DataSource),
- resources: z.array(Resource),
- props: z.array(Prop),
- breakpoints: z.array(Breakpoint),
- styleSourceSelections: z.array(StyleSourceSelection),
- styleSources: z.array(StyleSource),
- styles: z.array(StyleDecl),
+export const webstudioFragment = z.object({
+ children: z.array(instanceChild),
+ instances: z.array(instance),
+ assets: z.array(asset),
+ dataSources: z.array(dataSource),
+ resources: z.array(resource),
+ props: z.array(prop),
+ breakpoints: z.array(breakpoint),
+ styleSourceSelections: z.array(styleSourceSelection),
+ styleSources: z.array(styleSource),
+ styles: z.array(styleDecl),
});
-export type WebstudioFragment = z.infer<typeof WebstudioFragment>;
+export type WebstudioFragment = z.infer<typeof webstudioFragment>;
/**
* all persisted webstudio data in normalized format
diff --git a/packages/trpc-interface/src/api-compatibility.ts b/packages/trpc-interface/src/api-compatibility.ts
index 82eab2fd3a..b51b26bcdc 100644
--- a/packages/trpc-interface/src/api-compatibility.ts
+++ b/packages/trpc-interface/src/api-compatibility.ts
@@ -5,13 +5,13 @@ export const apiCompatibilityErrorType = "webstudioApiCompatibilityError";
export const apiClientHeader = "x-webstudio-client";
export const apiClientVersionHeader = "x-webstudio-client-version";
-export const ApiCompatibilityTarget = z.enum(["browser", "cli"]);
-export type ApiCompatibilityTarget = z.infer<typeof ApiCompatibilityTarget>;
+export const apiCompatibilityTarget = z.enum(["browser", "cli"]);
+export type ApiCompatibilityTarget = z.infer<typeof apiCompatibilityTarget>;
-export const ApiClient = z.enum(["browser", "cli", "service"]);
-export type ApiClient = z.infer<typeof ApiClient>;
+export const apiClient = z.enum(["browser", "cli", "service"]);
+export type ApiClient = z.infer<typeof apiClient>;
-const ApiCompatibilityAction = z.discriminatedUnion("type", [
+const apiCompatibilityAction = z.discriminatedUnion("type", [
z.object({
type: z.literal("reloadBrowser"),
}),
@@ -20,15 +20,15 @@ const ApiCompatibilityAction = z.discriminatedUnion("type", [
}),
]);
-export const ApiCompatibilityPayload = z.object({
+export const apiCompatibilityPayload = z.object({
type: z.literal(apiCompatibilityErrorType),
reason: z.enum(["apiRouteNotFound", "apiProcedureNotFound"]),
- target: ApiCompatibilityTarget,
+ target: apiCompatibilityTarget,
message: z.string(),
- action: ApiCompatibilityAction,
+ action: apiCompatibilityAction,
});
-export type ApiCompatibilityPayload = z.infer<typeof ApiCompatibilityPayload>;
+export type ApiCompatibilityPayload = z.infer<typeof apiCompatibilityPayload>;
export const createApiCompatibilityPayload = ({
reason,
@@ -67,7 +67,7 @@ export const getApiCompatibilityPayload = (
value: unknown,
seen: WeakSet<object>
): ApiCompatibilityPayload | undefined => {
- const parsed = ApiCompatibilityPayload.safeParse(value);
+ const parsed = apiCompatibilityPayload.safeParse(value);
if (parsed.success) {
return parsed.data;
}
diff --git a/packages/trpc-interface/src/shared/deployment.ts b/packages/trpc-interface/src/shared/deployment.ts
index 9508fc034a..36cd3754e5 100644
--- a/packages/trpc-interface/src/shared/deployment.ts
+++ b/packages/trpc-interface/src/shared/deployment.ts
@@ -2,7 +2,7 @@ import { z } from "zod";
import { router, procedure } from "./trpc";
// Has corresponding type in saas
-export const PublishInput = z.object({
+export const publishInput = z.object({
// used to load build data from the builder with build.loadProjectBundleByBuildId
buildId: z.string(),
builderOrigin: z.string(),
@@ -15,11 +15,11 @@ export const PublishInput = z.object({
logProjectName: z.string(),
});
-export const UnpublishInput = z.object({
+export const unpublishInput = z.object({
domain: z.string(),
});
-export const Output = z.discriminatedUnion("success", [
+export const output = z.discriminatedUnion("success", [
z.object({
success: z.literal(true),
}),
@@ -35,8 +35,8 @@ export const Output = z.discriminatedUnion("success", [
**/
export const deploymentRouter = router({
publish: procedure
- .input(PublishInput)
- .output(Output)
+ .input(publishInput)
+ .output(output)
.mutation(() => {
return {
success: false,
@@ -44,8 +44,8 @@ export const deploymentRouter = router({
};
}),
unpublish: procedure
- .input(UnpublishInput)
- .output(Output)
+ .input(unpublishInput)
+ .output(output)
.mutation(() => {
return {
success: false,
diff --git a/packages/trpc-interface/src/shared/domain.ts b/packages/trpc-interface/src/shared/domain.ts
index 9951eb29c8..a6fe861b1c 100644
--- a/packages/trpc-interface/src/shared/domain.ts
+++ b/packages/trpc-interface/src/shared/domain.ts
@@ -5,8 +5,8 @@
import { z } from "zod";
import { router, procedure } from "./trpc";
-const CreateInput = z.object({ domain: z.string(), txtRecord: z.string() });
-const Input = z.object({ domain: z.string() });
+const createInput = z.object({ domain: z.string(), txtRecord: z.string() });
+const input = z.object({ domain: z.string() });
const createOutput = <T extends z.ZodType>(data: T) =>
z.discriminatedUnion("success", [
@@ -33,7 +33,7 @@ export const domainRouter = router({
* Verify TXT record and add custom domain entry to DNS
*/
create: procedure
- .input(CreateInput)
+ .input(createInput)
.output(createOutput(z.optional(z.undefined())))
.mutation(async ({ input }) => {
const record = dnsTxtEntries.get(input.domain);
@@ -55,7 +55,7 @@ export const domainRouter = router({
}),
refresh: procedure
- .input(Input)
+ .input(input)
.output(createOutput(z.optional(z.undefined())))
.mutation(async () => {
return { success: true };
@@ -64,7 +64,7 @@ export const domainRouter = router({
* Get status of verified domain
*/
getStatus: procedure
- .input(Input)
+ .input(input)
.output(
createOutput(
z.discriminatedUnion("status", [
diff --git a/packages/wsauth/src/schema.ts b/packages/wsauth/src/schema.ts
index bc67d28455..3821d0394b 100644
--- a/packages/wsauth/src/schema.ts
+++ b/packages/wsauth/src/schema.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
-export const basicAuthInputSchema = z.union([
+export const basicAuthInput = z.union([
z.object({
method: z.literal("basic"),
login: z.string(),
@@ -13,10 +13,10 @@ export const basicAuthInputSchema = z.union([
}),
]);
-export type BasicAuthInput = z.infer<typeof basicAuthInputSchema>;
+export type BasicAuthInput = z.infer<typeof basicAuthInput>;
-export const wsAuthConfigSchema = z.object({
+export const wsAuthConfig = z.object({
version: z.literal(1),
- routes: z.record(basicAuthInputSchema),
+ routes: z.record(basicAuthInput),
});
-export type WsAuthConfig = z.infer<typeof wsAuthConfigSchema>;
+export type WsAuthConfig = z.infer<typeof wsAuthConfig>;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 97bc9fd007..1280bc708b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -214,6 +214,15 @@ importers:
'@tsndr/cloudflare-worker-jwt':
specifier: ^2.5.3
version: 2.5.3
+ '@tus/file-store':
+ specifier: ^2.1.0
+ version: 2.1.0
+ '@tus/s3-store':
+ specifier: ^2.0.4
+ version: 2.0.4
+ '@tus/server':
+ specifier: ^2.4.1
+ version: 2.4.1
'@unocss/core':
specifier: 66.6.8
version: 66.6.8
@@ -611,7 +620,7 @@ importers:
version: 1.15.1
ipx:
specifier: ^3.0.3
- version: 3.0.3
+ version: 3.0.3([email protected])
isbot:
specifier: ^5.1.25
version: 5.1.25
@@ -1173,6 +1182,9 @@ importers:
tinyexec:
specifier: ^0.3.2
version: 0.3.2
+ tus-js-client:
+ specifier: ^4.3.1
+ version: 4.3.1
warn-once:
specifier: ^0.1.1
version: 0.1.1
@@ -1272,7 +1284,7 @@ importers:
version: 1.15.1
ipx:
specifier: ^3.0.3
- version: 3.0.3
+ version: 3.0.3([email protected])
isbot:
specifier: ^5.1.25
version: 5.1.25
@@ -1696,6 +1708,9 @@ importers:
'@webstudio-is/protocol':
specifier: workspace:*
version: link:../protocol
+ tus-js-client:
+ specifier: ^4.3.1
+ version: 4.3.1
devDependencies:
'@webstudio-is/tsconfig':
specifier: workspace:*
@@ -2519,17 +2534,113 @@ packages:
'@atlaskit/[email protected]':
resolution: {integrity: sha512-lZHnO9BJdHPKnwB0uvVUCyDnIhL+WAHzXQ2EXX0qacogOsnvIUiCgY0BLKhBqTCWln3/f/Ox5jU54MKO6ayh9A==}
+ '@aws-crypto/[email protected]':
+ resolution: {integrity: sha512-nLbCWqQNgUiwwtFsen1AdzAtvuLRsQS8rYgMuxCrdKf9kOssamGLuPwyTY9wyYblNr9+1XM8v6zoDTPPSIeANg==}
+ engines: {node: '>=16.0.0'}
+
+ '@aws-crypto/[email protected]':
+ resolution: {integrity: sha512-+iWb8qaHLYKrNvGRbiYRHSdKRWhto5XlZUEBwDjYNf+ly5SVYG6zEoYIdxvf5R3zyeP16w4PLBn3rH1xc74Rag==}
+
+ '@aws-crypto/[email protected]':
+ resolution: {integrity: sha512-OH6lveCFfcDjX4dbAvCFSYUjJZjDr/3XJ3xHtjn3Oj5b9RjojQo8npoLeA/bNwkOkrSQ0wgrHzXk4tDRxGKJeg==}
+
+ '@aws-crypto/[email protected]':
+ resolution: {integrity: sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw==}
+
'@aws-crypto/[email protected]':
resolution: {integrity: sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA==}
engines: {node: '>=16.0.0'}
+ '@aws-crypto/[email protected]':
+ resolution: {integrity: sha512-iAvUotm021kM33eCdNfwIN//F77/IADDSs58i+MDaOqFrVjZo9bAal0NK7HurRuWLLpF1iLX7gbWrjHjeo+YFg==}
+
'@aws-crypto/[email protected]':
resolution: {integrity: sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ==}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-v0U9S7gBIme3OTgt1LdbAF4RpvavCc+4GK1+1xqAcqtbrHsEhjQo6R45LKcjhs/+WrRJij1Y0Gztw7QPAIeUfA==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-h1A6nIl1YX6Y45enGsTK7ef3ZrOnBiQJ1qF5R2K/nMWfsu6A9mc2Y5T66nxerABzyjjyyvign3MrzafnFoQKmA==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-MiWR/uWjxjFXGzrE0Ghc5lWxUxzHsUWFhV+OX7M4cR9SrmrnZs6TXavnCWnzzdwJeFri34xQo81rvGNzK3c4BQ==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-liB3yQNHCM9k/gu/w36XHMKPluT7HTlnGUhRbBGSISDQkcr/Sy1zsZabiuvQj8WG5yW573u9RehrBvvnIQ9OEQ==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-XET0H2oofciJ5lMRWNIvRjAP7Q3wv2XT+JtJJEdhPWUMwe3TvQ9qcxonpu7vXmNngncvFpi4E2It+Tamas/naA==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-IAmc61hbgQiHht9U3x0tnRwz0lzdwOwD/i9voRgdJrKamF+JtmrBOsW9GwB7mfFonNWOWL4qARWYrF8veEMe3w==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-hBBkANo3cDn+h2qxxzER4a+J8JCO9o9Z/YYmU7iky6AcaarX5RRdRcHNC6SLdwY0vAXQygn6soUbDqPn3GghaA==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-OyCLVmSI7pZO8hxwNVX6pXhTVlJqRBTp+ijdEfJSUj0RyjHnF602OfAarOzGq6wkGodeFkYBt8MmJ6A6ycRgWw==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-C8h36lBuC/RnBSsjlO+dn6xZm3KbAl5vpJaVPAfQnMmz2/OISmKOc8XZcqMQgO2ADwBYNRMM6Kf3vz9G/TulMQ==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-1FkOz74Ea5QGS9jtIoXp55T/IkSS3spv+nLTT07fRY/+T5xmEOqaYBVIaEmX4zTNvbV6g2lrtlaVKWEoNyJt3w==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-g2BoECD1q01kTPByi56+VLVvdWDzMkKIcr77qixpqH0okw2t0U5CoPv+6S8v/D1Y2Wa6QKKtn6XAtDzP+Kfpvg==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-qMgQSPemQq2/eW/e/0+SpY4kYR5L7dUgBiVdEc5bd+ztHNv07ZMYiI+sTiir3TgKndFfglSw/VFi7oZJ6bZ63g==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-GDfDQ0gwLFRKN9gWIKcmVrHJ3e7XagnY7N1LLzMVNgnOnuY7f/ALgmy3CuBjosWD95T/Z6e+gs1IeWmLPkyLKQ==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-gO93ZPsI2bxeFZD42f1/qjDw6FAZkNZcKRO94LIiT03fzOmcJ9e/tunxjVjA1Rl69ClmVJzz8H3G9CdKef10PA==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-6L/VWs+Wch2stHemCGTmUNqKLMzURxQDK5boNG3Jn3kAOp71meDUuS5sbObpEvFxHDq0uWeSLFDNSYsjNt+Dlg==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-pv80IzgGW4RnXWtft692chZOM9i6PhebVsLCcnaM4dBEPZva2fE6FXAHs76G7Rc7s3yGyX/68G0nZMrUy+Vmpg==}
+ engines: {node: '>=20.0.0'}
+
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-9rTvUJIAj5d3//U5FDPWGJ1nFJLuWb30vugGOrWk7aNZ6y9tuA3PI7Cc9dP8WEXKVyK1vuuk8rSFP2iqXnlgrw==}
engines: {node: '>=16.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-pEHZqRkAlHfnfAU9tK+WpKv/gBNjGJrHMgA3A0iYRGyswBS2t0pfez+lWlwktb3Bqa0ovh7w/QJTFwp3fDxLNg==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-uUbMs1cBZPafD0ohUj6EwNf0fPZ534NvBxHox4hjX+0Rxq5paSYUem7+hi833pYrzrcnBATKIYpR02MDXT5M9g==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-SzE4Pgyl+hDF+BuyuzxUSpwnuUu9lJuO1YGgteG89/4Qv0+2IQiVQqdbPV32IozLvXWQChPQcdkk/sKvb1QHiQ==}
+ engines: {node: '>=20.0.0'}
+
+ resolution: {integrity: sha512-iY8yvjE0y651BixKNPgmv1WrQc+GZ142sb0z4gYnChDDY2YqI4P/jsSopBWrKfAt7LOJAkOXt7rC/hms+WclQQ==}
+ engines: {node: '>=18.0.0'}
+
resolution: {integrity: sha512-RJlIHRueQgwWitWgF8OdFYGZX328Ax5BCemNGlqHfplnRT9ESi8JkFlvaVYbS+UubVY6dpv87Fs2u5M29iNFVQ==}
engines: {node: '>=6.9.0'}
@@ -3942,6 +4053,9 @@ packages:
'@types/node':
optional: true
+ '@ioredis/[email protected]':
+ resolution: {integrity: sha512-UmeW7z4LfctwoQ5wkhVzgq8tXkreED2xZGpX+Bg+zA+WJFZCT6c062AfCK/Dfk81xZnnwdhJCUMkitihRaoC2Q==}
+
'@isaacs/[email protected]':
resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==}
engines: {node: '>=12'}
@@ -5242,6 +5356,18 @@ packages:
peerDependencies:
react: 18.3.0-canary-14898b6a9-20240318
+ '@redis/[email protected]':
+ resolution: {integrity: sha512-7aPGWeqA3uFm43o19umzdl16CEjK/JQGtSXVPevplTaOU3VJA/rseBC1QvYUz9lLDIMBimc4SW/zrW4S89BaCA==}
+ engines: {node: '>= 18.19.0'}
+ peerDependencies:
+ '@node-rs/xxhash': ^1.1.0
+ '@opentelemetry/api': '>=1 <2'
+ peerDependenciesMeta:
+ '@node-rs/xxhash':
+ optional: true
+ '@opentelemetry/api':
+ optional: true
+
'@remix-run/[email protected]':
resolution: {integrity: sha512-d0m1oQZLNLnHNtPIblsbVo0L4TVDiWDk0FYPfo4hlLeBPz236X9VLDzQYIMDJen43j9B8LzJtr9MgnyVg7evDg==}
engines: {node: '>=18.0.0'}
@@ -5467,6 +5593,23 @@ packages:
'@rushstack/[email protected]':
resolution: {integrity: sha512-poBtnumLuWmwmhCEkVAgynWgtnF9Kygekxyp4qtQUSbBrkuyPQTL85c8Cva1YfoUpOdOXxezMAkUt0n5SNKGqw==}
+ '@shopify/[email protected]':
+ resolution: {integrity: sha512-LxonkiWEu12FbZhuOMhsdocpxCqm7By8C/2U9QgNuEoXUx2iMrlXjJv3p93RwfNC6TrdlNRo17gRer1z1309VQ==}
+ engines: {node: '>=18.12.0'}
+ deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
+
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-mLUktFAn+Pa2agl1J7VgtYNFWCX8/b4GMJSK1hCu4YCvtBfM6F8Os3EP4ry+DFFlXOf3wyvlgXhuUdFoy52D3g==}
+ engines: {node: '>=18.0.0'}
+
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-18UMDMyrAbDcpmL1gLUA7ww0fRTcdCrSjSJOi2Sbld+tVjwD/pW+OAwjlScFLR7vvBnhZrIPQ7kVuTf1mnJLug==}
+ engines: {node: '>=18.0.0'}
+
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-Ei/UK/QMhq0rKaMqGPlOAkE2yS9DZeYmZdk1RAKc3vp3zxgleZHZyBLlZv8yLsxljX4svCRuMTD6u3LLIcU4Bg==}
+ engines: {node: '>=18.0.0'}
+
'@smithy/[email protected]':
resolution: {integrity: sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==}
engines: {node: '>=14.0.0'}
@@ -5475,6 +5618,10 @@ packages:
resolution: {integrity: sha512-saYhF8ZZNoJDTvJBEWgeBccCg+yvp1CX+ed12yORU3NilJScfc6gfch2oVb4QgxZrGUx3/ZJlb+c/dJbyupxlw==}
engines: {node: '>=18.0.0'}
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-wfl1uwrAqMH9/pi4kqBo5LBcFwrJLxuDLqL7p7qNcJIFcyZDUc6pzhYk4CYv+DP7fIUpQCZumwNnkhPKS52osQ==}
+ engines: {node: '>=18.0.0'}
+
'@smithy/[email protected]':
resolution: {integrity: sha512-fCJd2ZR7D22XhDY0l+92pUag/7je2BztPRQ01gU5bMChcyI0rlly7QFibnYHzcxDvccMjlpM/Q1ev8ceRIb48w==}
engines: {node: '>=18.0.0'}
@@ -5483,10 +5630,18 @@ packages:
resolution: {integrity: sha512-mARDSXSEgllNzMw6N+mC+r1AQlEBO3meEAkR/UlfAgnMzJUB3goRBWgip1EAMG99wh36MDqzo86SfIX5Y+VEaw==}
engines: {node: '>=18.0.0'}
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-7xHpmPY4rt0IOmeAA8EfjgEH8isT+587TCdy9H6a7d4OMi5CQ0oEHhWllunvPu4j4Cq0vTFwdxXN/kABWPjdyA==}
+ engines: {node: '>=18.0.0'}
+
'@smithy/[email protected]':
resolution: {integrity: sha512-XKLcLXZY7sUQgvvWyeaL/qwNPp6V3dWcUjqrQKjSb+tzYiCy340R/c64LV5j+Tnb2GhmunEX0eou+L+m2hJNYA==}
engines: {node: '>=16.0.0'}
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-Z5TAOxygoFvybJV3igo5SloFflSokHx2hu1eFA+DxDTcn+FtKxUSui+rbTRG1pAafMA888Z3MVvCWUuvCrTXjg==}
+ engines: {node: '>=18.0.0'}
+
'@smithy/[email protected]':
resolution: {integrity: sha512-QO4zghLxiQ5W9UZmX2Lo0nta2PuE1sSrXUYDoaB6HMR762C0P7v/HEPHf6ZdglTVssJG1bsrSBxdc3quvDSihw==}
engines: {node: '>=18.0.0'}
@@ -5677,6 +5832,22 @@ packages:
resolution: {integrity: sha512-zbdvjRG86y/ObiBgTJrzBC39t2FcaeGwB6AV7VO4LvHKJNyZvLYRbKT68eaoJhnJldyHhs7yZ69neRVdUd9knA==}
+ resolution: {integrity: sha512-RW/aYO2pp0L4AVG6NebPL+Q9FKKtDXF2+skBq3NbOMOEoxWFHSCgtzIX1pBPezFdZDwqdZMIlx+NQGQYYp6/3Q==}
+ engines: {node: '>=20.19.0'}
+
+ resolution: {integrity: sha512-hDksmufDo1U339CwbJI+uhT/nevCCEG220rxoxoZfF9qLaD0V+JKRC6kCQo5dSIQ5X/dLgxW/KBIMWMpHizS/Q==}
+ engines: {node: '>=20.19.0'}
+
+ resolution: {integrity: sha512-WShIwCqtthAL0x++f/VCF6ZpbULjRIYLPumQoOYNHa4NVMxW1pDBAKsNE3Y+rnVTzOttEumIXD1WDNRsIf7x7Q==}
+ engines: {node: '>=20.19.0'}
+
+ resolution: {integrity: sha512-BPom8lVwR4fkk1EynPeQwuN0e5bH2gBphwt69uF5rS4wRD2N7IyHDPqdjcAY0I7gNEWfUitPyDodywbD4r7dEQ==}
+ engines: {node: '>=20.19.0'}
+
resolution: {integrity: sha512-veQTnWP+1D/xbxVrPC3zHnCZRjSrKfhbMUlEA43iMZLu7EsnTtkJklIuwrCPbOi8YkvDQAiW05VQQFvvz9oieQ==}
@@ -6158,6 +6329,9 @@ packages:
resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==}
+ resolution: {integrity: sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==}
+
resolution: {integrity: sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==}
@@ -6317,6 +6491,14 @@ packages:
resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-rwHwUfXL40Chm1r08yrhU3qpUvdVlgkKNeyeGPOxnW8/SyVDvgRaed/Uz54AqWNaTCAThlj6QAs3TZcKI0xDEw==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==}
+ engines: {node: '>=0.10.0'}
+
resolution: {integrity: sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg==}
peerDependencies:
@@ -6350,6 +6532,9 @@ packages:
resolution: {integrity: sha512-erNRLao/Y3Fv54qUa0LBB+//Uf3YwMUmdJinN20yMXm9zdKKqH9wt7R9IIVZ+K7ShzfpLV/Zg8+VyrBJYB4lpg==}
engines: {node: '>=0.1.90'}
+ resolution: {integrity: sha512-C8ikRNRMygCwaTx+Ek3Yr+OuZzgZjduCOfSQBjbM8V3MfgcjSTeto/GXP6PAwKvJz/v15b7GHZvx5rOlczFw/Q==}
+
resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==}
engines: {node: '>= 0.8'}
@@ -6486,6 +6671,9 @@ packages:
resolution: {integrity: sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==}
+ resolution: {integrity: sha512-p6JFxJc3M4OTD2li2qaHkDCw9SfMw82Ldr6OC9Je1aXiGfhx2W8p3GaoeaGrPJTUN9NirTM/KTxHWMUdR1rsUg==}
+
resolution: {integrity: sha512-ND9qDTLc6diwj+Xe5cdAgVTbLVdXbtxTJRXRhli8Mowuaan+0EJOtdqJ0QCHNSSPyoXGx9HX2/VMnKeC34AChA==}
@@ -6581,6 +6769,10 @@ packages:
resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==}
engines: {node: '>=0.4.0'}
+ resolution: {integrity: sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==}
+ engines: {node: '>=0.10'}
+
resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}
engines: {node: '>= 0.8'}
@@ -7256,6 +7448,10 @@ packages:
resolution: {integrity: sha512-7NXolsK4CAS5+xvdj5OMMbI962hU/wvwoxk+LWR9Ek9bVtyuuYScDN6eS0rUm6TxApFpw7CX1o4uJzcd4AyD3Q==}
+ resolution: {integrity: sha512-ehuGcf94bQXhfagULNXrJdfnWO38v070jxSx/qE87Kjzmu2fU7ro5EFAb+OPituLqgfyuQaym5DlrNydW2sJ9A==}
+ engines: {node: '>=12.22.0'}
+
resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==}
engines: {node: '>= 0.10'}
@@ -7443,6 +7639,9 @@ packages:
resolution: {integrity: sha512-rg9zJN+G4n2nfJl5MW3BMygZX56zKPNVEYYqq7adpmMh4Jn2QNEwhvQlFy6jPVdcod7txZtKHWnyZiA3a0zP7A==}
hasBin: true
+ resolution: {integrity: sha512-hNngCeKxIUQiEUN3GPJOkz4wF/YvdUdbNL9hsBcMQTkKzboD7T/q3OYOuuPZLUE6dBxSGpwhk5mwuDud7JVAow==}
+
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
@@ -7523,12 +7722,36 @@ packages:
resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-nqB9M+wITz0BX/Q2xg6fQ8mLkyfF7MU7eE+MNBNjTHFKeKaZAPEzEg+E8LWxKWf1DQVflNEn9N49yAuqKh2mWQ==}
+
+ resolution: {integrity: sha512-SwcRIbyxnN6CFEEK4K1y+zuApvWdpQdBHM/swxP962s8HIxPO3alBH5t3m/dl+f4CMUug6sJb7Pww8d13/9WSw==}
+
+ resolution: {integrity: sha512-Ja1YevpHZctlI5beLA7oc5KNDhGcPixFhcqSiORHNsp/1QTv7amAXzw+gu4YOvErqVlMVyIJGgtzeepCnnur0A==}
+
+ resolution: {integrity: sha512-GTkC6YMprrJZCYU3zcqZj+jkXkrXzq3IPBcF/fIPpNEAB4hZEtXU8zp/RwKOvZl43NUmwDbyRk3+ZTbeRdEBXA==}
+
+ resolution: {integrity: sha512-O0pWuFSK6x4EXhM1dhZ8gchNtG7JMqBtrHdoUFUWXD7dJnNSUze1GuyQr5sOs0aCvgGeI3o/OJW8f4ca7FDxmQ==}
+
+ resolution: {integrity: sha512-SXL66C731p0xPDC5LZg4wI5H+dJo/EO4KTqOMwLYCH3+FmmfAKJEZCm6ohGpI+T1xwsDsJCfL4OnhorllvlTPQ==}
+
resolution: {integrity: sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==}
resolution: {integrity: sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==}
+ resolution: {integrity: sha512-wIkUCfVKpVsWo3JSZlc+8MB5it+2AN5W8J7YVMST30UrvcQNZ1Okbj+rbVniijTWE6FGYy4XJq/rHkas8qJMLQ==}
+
+ resolution: {integrity: sha512-IRt7cfTtHy6f1aRVA5n7kT8rgN3N1nH6MOWLcHfpWG2SH19E3JksLK38MktLxZDhlAjCP9jpIXkOnRXlu6oByQ==}
+
resolution: {integrity: sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==}
@@ -7984,6 +8207,9 @@ packages:
typescript:
optional: true
+ resolution: {integrity: sha512-J1XDiAmmNpRCBfIWJv+n0ymC4ABcf/Pl+5YvC5B/D2f/2+8PtHvCNxMPKiQcZyi922Hq69J2YOpb1pTywfifyw==}
+
resolution: {integrity: sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==}
hasBin: true
@@ -8422,6 +8648,9 @@ packages:
resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==}
+ resolution: {integrity: sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==}
+
resolution: {integrity: sha512-kma4U7AFCTwpqq5twzC1YVIDXSqg6qQK6JN0smOw8fgRy1OkMi0CYSzFmsy6dnqSenamAtj0CyXMUJ1Mf6oROg==}
@@ -8617,6 +8846,14 @@ packages:
resolution: {integrity: sha512-Hx/BGIbwj+Des3+xy5uAtAbdCyqK9y9wbBcDFDYanLS9JnMqf7OeF87HQwUimE87OEc72mr6tkKUKMBBL+hF9Q==}
engines: {node: '>= 4'}
+ resolution: {integrity: sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==}
+ engines: {node: '>=4'}
+
+ resolution: {integrity: sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==}
+ engines: {node: '>=4'}
+
resolution: {integrity: sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==}
@@ -8815,6 +9052,9 @@ packages:
resolution: {integrity: sha512-RVnVQxTXuerk653XfuliOxBP81Sf0+qfQE73LIYKcyMYHG94AuH0kgrQpRDuTZnSmjpysHmzxJXKNfa6PjFhyQ==}
+ resolution: {integrity: sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==}
+
resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==}
engines: {node: '>= 0.4'}
@@ -8906,6 +9146,11 @@ packages:
resolution: {integrity: sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==}
+ resolution: {integrity: sha512-43yM4luKfCJamyCMhrUeHUPOrf8TdZe7kN8s5zayZCH5OeprYqi49Aso5ZvHXR4aB+DHaRNO/diNFgZSMNG8Xw==}
+ engines: {node: '>=20.16.0'}
+ hasBin: true
+
resolution: {integrity: sha512-bSf16tAFkGeRlUNDjXu8FzaMQt6g2HZJrun7mtMbIPOddxt3GLMSz5VWUWcqTJUPfLEaDIepGxv+bYQW49596A==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
@@ -8916,6 +9161,9 @@ packages:
resolution: {integrity: sha512-Kpij9riA+UNg7TnphqjH7/CzctQ/owJGNbFkfEeve4Z4uxT5+JapVLFXcsurIfN34gnTWZNJ/f7NMG0E8JDzTw==}
+ resolution: {integrity: sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==}
+
resolution: {integrity: sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==}
engines: {node: '>= 0.8'}
@@ -9168,6 +9416,10 @@ packages:
resolution: {integrity: sha512-FHncC10WpBd2eOmGwpmQsWLDoK4cqsA/UT/GqNoaKOQnT8uzhtCbg3EoUDMvqpOSAI0S26mr0rkjzbOO6S3v1g==}
+ resolution: {integrity: sha512-ZLeYmjrkaU1fUsKbIi8JML52uAocjEZtBx4DKjRrqzrZa0O4MYwT6db+oqePlspV+FxXJAyFBc/L5gwUi2OFsg==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==}
engines: {node: '>=10'}
@@ -9857,23 +10109,240 @@ snapshots:
bind-event-listener: 3.0.0
raf-schd: 4.0.3
+ '@aws-crypto/[email protected]':
+ dependencies:
+ '@aws-crypto/util': 5.2.0
+ '@aws-sdk/types': 3.973.13
+ tslib: 2.8.1
+
+ '@aws-crypto/[email protected]':
+ dependencies:
+ '@aws-crypto/util': 5.2.0
+ '@aws-sdk/types': 3.973.13
+ tslib: 2.8.1
+
+ '@aws-crypto/[email protected]':
+ dependencies:
+ '@aws-crypto/supports-web-crypto': 5.2.0
+ '@aws-crypto/util': 5.2.0
+ '@aws-sdk/types': 3.973.13
+ '@aws-sdk/util-locate-window': 3.965.8
+ '@smithy/util-utf8': 2.3.0
+ tslib: 2.8.1
+
+ '@aws-crypto/[email protected]':
+ dependencies:
+ '@aws-crypto/sha256-js': 5.2.0
+ '@aws-crypto/supports-web-crypto': 5.2.0
+ '@aws-crypto/util': 5.2.0
+ '@aws-sdk/types': 3.973.13
+ '@aws-sdk/util-locate-window': 3.965.8
+ '@smithy/util-utf8': 2.3.0
+ tslib: 2.8.1
+
'@aws-crypto/[email protected]':
dependencies:
'@aws-crypto/util': 5.2.0
'@aws-sdk/types': 3.696.0
tslib: 2.8.1
+ '@aws-crypto/[email protected]':
+ dependencies:
+ tslib: 2.8.1
+
'@aws-crypto/[email protected]':
dependencies:
'@aws-sdk/types': 3.696.0
'@smithy/util-utf8': 2.3.0
tslib: 2.8.1
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-crypto/crc32': 5.2.0
+ '@aws-crypto/crc32c': 5.2.0
+ '@aws-crypto/util': 5.2.0
+ '@aws-sdk/core': 3.974.23
+ '@aws-sdk/types': 3.973.13
+ '@smithy/core': 3.26.0
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-crypto/sha1-browser': 5.2.0
+ '@aws-crypto/sha256-browser': 5.2.0
+ '@aws-crypto/sha256-js': 5.2.0
+ '@aws-sdk/core': 3.974.23
+ '@aws-sdk/credential-provider-node': 3.972.58
+ '@aws-sdk/middleware-flexible-checksums': 3.974.33
+ '@aws-sdk/middleware-sdk-s3': 3.972.54
+ '@aws-sdk/signature-v4-multi-region': 3.996.35
+ '@aws-sdk/types': 3.973.13
+ '@smithy/core': 3.26.0
+ '@smithy/fetch-http-handler': 5.5.2
+ '@smithy/node-http-handler': 4.8.2
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/types': 3.973.13
+ '@aws-sdk/xml-builder': 3.972.31
+ '@aws/lambda-invoke-store': 0.2.4
+ '@smithy/core': 3.26.0
+ '@smithy/signature-v4': 5.5.2
+ '@smithy/types': 4.15.0
+ bowser: 2.14.1
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.974.23
+ '@aws-sdk/types': 3.973.13
+ '@smithy/core': 3.26.0
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.974.23
+ '@aws-sdk/types': 3.973.13
+ '@smithy/core': 3.26.0
+ '@smithy/fetch-http-handler': 5.5.2
+ '@smithy/node-http-handler': 4.8.2
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.974.23
+ '@aws-sdk/credential-provider-env': 3.972.49
+ '@aws-sdk/credential-provider-http': 3.972.51
+ '@aws-sdk/credential-provider-login': 3.972.55
+ '@aws-sdk/credential-provider-process': 3.972.49
+ '@aws-sdk/credential-provider-sso': 3.972.55
+ '@aws-sdk/credential-provider-web-identity': 3.972.55
+ '@aws-sdk/nested-clients': 3.997.23
+ '@aws-sdk/types': 3.973.13
+ '@smithy/core': 3.26.0
+ '@smithy/credential-provider-imds': 4.4.2
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.974.23
+ '@aws-sdk/nested-clients': 3.997.23
+ '@aws-sdk/types': 3.973.13
+ '@smithy/core': 3.26.0
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/credential-provider-env': 3.972.49
+ '@aws-sdk/credential-provider-http': 3.972.51
+ '@aws-sdk/credential-provider-ini': 3.972.56
+ '@aws-sdk/credential-provider-process': 3.972.49
+ '@aws-sdk/credential-provider-sso': 3.972.55
+ '@aws-sdk/credential-provider-web-identity': 3.972.55
+ '@aws-sdk/types': 3.973.13
+ '@smithy/core': 3.26.0
+ '@smithy/credential-provider-imds': 4.4.2
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.974.23
+ '@aws-sdk/types': 3.973.13
+ '@smithy/core': 3.26.0
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.974.23
+ '@aws-sdk/nested-clients': 3.997.23
+ '@aws-sdk/token-providers': 3.1074.0
+ '@aws-sdk/types': 3.973.13
+ '@smithy/core': 3.26.0
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.974.23
+ '@aws-sdk/nested-clients': 3.997.23
+ '@aws-sdk/types': 3.973.13
+ '@smithy/core': 3.26.0
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/checksums': 3.1000.8
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.974.23
+ '@aws-sdk/signature-v4-multi-region': 3.996.35
+ '@aws-sdk/types': 3.973.13
+ '@smithy/core': 3.26.0
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-crypto/sha256-browser': 5.2.0
+ '@aws-crypto/sha256-js': 5.2.0
+ '@aws-sdk/core': 3.974.23
+ '@aws-sdk/signature-v4-multi-region': 3.996.35
+ '@aws-sdk/types': 3.973.13
+ '@smithy/core': 3.26.0
+ '@smithy/fetch-http-handler': 5.5.2
+ '@smithy/node-http-handler': 4.8.2
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/types': 3.973.13
+ '@smithy/signature-v4': 5.5.2
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.974.23
+ '@aws-sdk/nested-clients': 3.997.23
+ '@aws-sdk/types': 3.973.13
+ '@smithy/core': 3.26.0
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
'@aws-sdk/[email protected]':
dependencies:
'@smithy/types': 3.7.1
tslib: 2.8.1
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
+ '@aws/[email protected]': {}
+
dependencies:
'@babel/helper-validator-identifier': 7.25.9
@@ -10970,6 +11439,9 @@ snapshots:
optionalDependencies:
'@types/node': 22.13.10
+ '@ioredis/[email protected]':
+ optional: true
+
'@isaacs/[email protected]':
dependencies:
string-width: 5.1.2
@@ -12436,6 +12908,11 @@ snapshots:
dependencies:
react: 18.3.0-canary-14898b6a9-20240318
+ '@redis/[email protected]':
+ dependencies:
+ cluster-key-slot: 1.1.2
+ optional: true
+
dependencies:
'@cloudflare/workers-types': 4.20240701.0
@@ -12801,6 +13278,26 @@ snapshots:
colors: 1.2.5
string-argv: 0.3.1
+ '@shopify/[email protected]': {}
+
+ '@smithy/[email protected]':
+ dependencies:
+ '@aws-crypto/crc32': 5.2.0
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
+ '@smithy/[email protected]':
+ dependencies:
+ '@smithy/core': 3.26.0
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
+ '@smithy/[email protected]':
+ dependencies:
+ '@smithy/core': 3.26.0
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
'@smithy/[email protected]':
dependencies:
tslib: 2.8.1
@@ -12809,6 +13306,12 @@ snapshots:
dependencies:
tslib: 2.8.1
+ '@smithy/[email protected]':
+ dependencies:
+ '@smithy/core': 3.26.0
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
'@smithy/[email protected]':
dependencies:
'@smithy/types': 4.3.2
@@ -12825,10 +13328,20 @@ snapshots:
'@smithy/util-utf8': 4.0.0
tslib: 2.8.1
+ '@smithy/[email protected]':
+ dependencies:
+ '@smithy/core': 3.26.0
+ '@smithy/types': 4.15.0
+ tslib: 2.8.1
+
'@smithy/[email protected]':
dependencies:
tslib: 2.8.1
+ '@smithy/[email protected]':
+ dependencies:
+ tslib: 2.8.1
+
'@smithy/[email protected]':
dependencies:
tslib: 2.8.1
@@ -13047,6 +13560,44 @@ snapshots:
'@tsndr/[email protected]': {}
+ dependencies:
+ '@tus/utils': 0.7.0
+ debug: 4.4.3
+ optionalDependencies:
+ '@redis/client': 5.12.1
+ transitivePeerDependencies:
+ - '@node-rs/xxhash'
+ - '@opentelemetry/api'
+ - supports-color
+
+ dependencies:
+ '@aws-sdk/client-s3': 3.1075.0
+ '@shopify/semaphore': 3.1.0
+ '@tus/utils': 0.7.0
+ debug: 4.4.3
+ multistream: 4.1.0
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@tus/utils': 0.7.0
+ debug: 4.4.3
+ lodash.throttle: 4.1.1
+ set-cookie-parser: 2.7.2
+ srvx: 0.11.17
+ optionalDependencies:
+ '@redis/client': 5.12.1
+ ioredis: 5.11.1
+ transitivePeerDependencies:
+ - '@node-rs/xxhash'
+ - '@opentelemetry/api'
+ - supports-color
+
+ '@tus/[email protected]': {}
+
dependencies:
'@types/estree': 1.0.7
@@ -13632,6 +14183,8 @@ snapshots:
+
dependencies:
balanced-match: 1.0.2
@@ -13811,6 +14364,12 @@ snapshots:
+ optional: true
+
+ optional: true
+
dependencies:
'@radix-ui/react-compose-refs': 1.1.1(@types/[email protected])([email protected])
@@ -13847,6 +14406,11 @@ snapshots:
+ dependencies:
+ custom-error-instance: 2.1.1
+ lodash.uniqby: 4.5.0
+
dependencies:
delayed-stream: 1.0.0
@@ -13967,6 +14531,8 @@ snapshots:
+
@@ -14029,6 +14595,9 @@ snapshots:
+ optional: true
+
@@ -14897,9 +15466,22 @@ snapshots:
+ dependencies:
+ '@ioredis/commands': 1.10.0
+ cluster-key-slot: 1.1.1
+ debug: 4.4.3
+ denque: 2.1.0
+ redis-errors: 1.2.0
+ redis-parser: 3.0.0
+ standard-as-callback: 2.1.0
+ transitivePeerDependencies:
+ - supports-color
+ optional: true
+
dependencies:
'@fastify/accept-negotiator': 2.0.1
citty: 0.1.6
@@ -14915,7 +15497,7 @@ snapshots:
sharp: 0.33.5
svgo: 3.3.2
ufo: 1.5.4
- unstorage: 1.15.0
+ unstorage: 1.15.0([email protected])
xss: 1.0.15
transitivePeerDependencies:
- '@azure/app-configuration'
@@ -15085,6 +15667,8 @@ snapshots:
+
@@ -15190,10 +15774,36 @@ snapshots:
dependencies:
p-locate: 5.0.0
+ dependencies:
+ lodash._stringtopath: 4.8.0
+
+
+ dependencies:
+ lodash._createset: 4.0.3
+ lodash._root: 3.0.1
+
+
+
+ dependencies:
+ lodash._basetostring: 4.12.0
+
+
+ dependencies:
+ lodash._baseiteratee: 4.7.0
+ lodash._baseuniq: 4.6.0
+
@@ -15952,6 +16562,11 @@ snapshots:
transitivePeerDependencies:
- '@types/node'
+ dependencies:
+ once: 1.4.0
+ readable-stream: 3.6.2
+
@@ -16355,6 +16970,12 @@ snapshots:
object-assign: 4.1.1
react-is: 16.13.1
+ dependencies:
+ graceful-fs: 4.2.10
+ retry: 0.12.0
+ signal-exit: 3.0.7
+
@@ -16392,8 +17013,7 @@ snapshots:
dependencies:
side-channel: 1.0.6
- optional: true
@@ -16564,6 +17184,14 @@ snapshots:
tiny-invariant: 1.3.3
tslib: 2.8.1
+ optional: true
+
+ dependencies:
+ redis-errors: 1.2.0
+ optional: true
+
@@ -16630,7 +17258,7 @@ snapshots:
dependencies:
'@remix-run/server-runtime': 2.16.5([email protected])
- debug: 4.4.0
+ debug: 4.4.3
uuid: 9.0.1
transitivePeerDependencies:
@@ -16663,8 +17291,7 @@ snapshots:
- optional: true
@@ -16799,6 +17426,8 @@ snapshots:
+
dependencies:
define-data-property: 1.1.4
@@ -16904,6 +17533,8 @@ snapshots:
+
dependencies:
minipass: 7.0.4
@@ -16915,6 +17546,9 @@ snapshots:
as-table: 1.0.55
get-source: 2.0.12
+ optional: true
+
@@ -17155,6 +17789,16 @@ snapshots:
+ dependencies:
+ buffer-from: 1.1.2
+ combine-errors: 3.0.3
+ is-stream: 2.0.1
+ js-base64: 3.7.8
+ lodash.throttle: 4.1.1
+ proper-lockfile: 4.1.2
+ url-parse: 1.5.10
+
@@ -17290,7 +17934,7 @@ snapshots:
acorn: 8.16.0
webpack-virtual-modules: 0.6.2
dependencies:
anymatch: 3.1.3
chokidar: 4.0.3
@@ -17300,6 +17944,8 @@ snapshots:
node-fetch-native: 1.6.6
ofetch: 1.4.1
ufo: 1.5.4
+ optionalDependencies:
+ ioredis: 5.11.1
@@ -17331,7 +17977,6 @@ snapshots:
dependencies:
querystringify: 2.2.0
requires-port: 1.0.0
- optional: true