Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
feat: validate page path (#2681)
Bogdan Chadkin42063e0d7918
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/settings.tsx b/apps/builder/app/builder/features/sidebar-left/panels/pages/settings.tsxindex 8dcdb7270e..2664b4b8b1 100644--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/settings.tsx+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/settings.tsx@@ -35,6 +35,8 @@ import {Separator,Text,ScrollArea,+ rawTheme,+ Flex,} from "@webstudio-is/design-system";import {ChevronDoubleLeftIcon,@@ -43,6 +45,7 @@ import {CheckMarkIcon,LinkIcon,HomeIcon,+ HelpIcon,} from "@webstudio-is/icons";import { useIds } from "~/shared/form-utils";import { Header, HeaderSuffixSpacer } from "../../header";@@ -72,7 +75,11 @@ import { SocialPreview } from "./social-preview";import { useEffectEvent } from "~/builder/features/ai/hooks/effect-event";import { CustomMetadata } from "./custom-metadata";import env from "~/shared/env";-import { compilePathnamePattern, parsePathnamePattern } from "./url-pattern";+import {+ compilePathnamePattern,+ parsePathnamePattern,+ validatePathnamePattern,+} from "./url-pattern";const fieldDefaultValues = {name: "Untitled",@@ -171,13 +178,16 @@ const validateValues = (if (parsedResult.success === false) {return parsedResult.error.formErrors.fieldErrors;}- if (- pages !== undefined &&- values.path !== undefined &&- isPathUnique(pages, pageId, values.path) === false- ) {- errors.path = errors.path ?? [];- errors.path.push("All paths must be unique");+ if (pages !== undefined && values.path !== undefined) {+ if (isPathUnique(pages, pageId, values.path) === false) {+ errors.path = errors.path ?? [];+ errors.path.push("All paths must be unique");+ }+ const messages = validatePathnamePattern(values.path);+ if (messages.length > 0) {+ errors.path = errors.path ?? [];+ errors.path.push(...messages);+ }}return errors;};@@ -374,7 +384,22 @@ const FormFields = ({{values.isHomePage === false && (<Grid gap={1}>- <Label htmlFor={fieldIds.path}>Path</Label>+ <Label htmlFor={fieldIds.path}>+ <Flex align="center" css={{ gap: theme.spacing[3] }}>+ Path+ <Tooltip+ content={+ "The path can include dynamic parameters like :name, which could be made optional using :name?, or have a wildcard such as /* or /:name* to store whole remaining part at the end of the URL."+ }+ variant="wrapped"+ >+ <HelpIcon+ color={rawTheme.colors.foregroundSubtle}+ tabIndex={0}+ />+ </Tooltip>+ </Flex>+ </Label><InputErrorsTooltip errors={errors.path}><InputFieldtabIndex={1}diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/url-pattern.test.ts b/apps/builder/app/builder/features/sidebar-left/panels/pages/url-pattern.test.tsindex ae39b6a28d..798ced8c99 100644--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/url-pattern.test.ts+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/url-pattern.test.ts@@ -1,5 +1,9 @@import { expect, test } from "@jest/globals";-import { compilePathnamePattern, parsePathnamePattern } from "./url-pattern";+import {+ compilePathnamePattern,+ parsePathnamePattern,+ validatePathnamePattern,+} from "./url-pattern";test("parse keys from pathname pattern", () => {expect(parsePathnamePattern("/blog/:id/:date")).toEqual(["id", "date"]);@@ -66,3 +70,73 @@ test("ignore compiling empty values", () => {})).toEqual("/blog/*/:slug");});++test("validate invalid pattern", () => {+ expect(validatePathnamePattern("/:name*?")).toEqual([+ `Invalid path pattern '/:name*?'`,+ ]);+});++test("validate named groups", () => {+ expect(validatePathnamePattern("/:name")).toEqual([]);+ expect(validatePathnamePattern("/:name/last")).toEqual([]);+});++test("validate named groups with optional modifier", () => {+ expect(validatePathnamePattern("/:name?")).toEqual([]);+ expect(validatePathnamePattern("/:name?/last")).toEqual([]);+});++test('validate "one or more" named group modifier', () => {+ expect(validatePathnamePattern("/:name+/:slug+")).toEqual([+ "Dynamic parameters ':name+', ':slug+' shouldn't have the + modifier.",+ ]);+});++test('validate "zero or more" named group modifier', () => {+ expect(validatePathnamePattern("/:name*")).toEqual([]);+ expect(validatePathnamePattern("/:name*/:another*/:slug*")).toEqual([+ "':name*', ':another*' should end the path.",+ ]);+});++test("validate wildcard groups", () => {+ expect(validatePathnamePattern("/*")).toEqual([]);+ expect(validatePathnamePattern("/*?/*?")).toEqual([+ `Optional wildcard '*?' is not allowed.`,+ ]);+ expect(validatePathnamePattern("/*/*")).toEqual([+ `Wildcard '*' should end the path.`,+ ]);+ expect(validatePathnamePattern("/*/last")).toEqual([+ `Wildcard '*' should end the path.`,+ ]);+ expect(validatePathnamePattern("/*?/*/last")).toEqual([+ `Optional wildcard '*?' is not allowed.`,+ `Wildcard '*' should end the path.`,+ ]);+});++test("forbid wildcard group with static parts before", () => {+ expect(validatePathnamePattern("/blog-*")).toEqual([+ `Static parts cannot be mixed with dynamic parameters at 'blog-*'.`,+ ]);+});++test(`forbid named group with "zero or more" modifier and static parts before`, () => {+ expect(validatePathnamePattern("/blog-:slug*")).toEqual([+ `Static parts cannot be mixed with dynamic parameters at 'blog-:slug*'.`,+ ]);+});++test(`forbid named group with static parts before or after`, () => {+ expect(validatePathnamePattern("/prefix-:id")).toEqual([+ `Static parts cannot be mixed with dynamic parameters at 'prefix-:id'.`,+ ]);+ expect(validatePathnamePattern("/:id-suffix")).toEqual([+ `Static parts cannot be mixed with dynamic parameters at ':id-suffix'.`,+ ]);+ expect(validatePathnamePattern("/prefix-:id-suffix")).toEqual([+ `Static parts cannot be mixed with dynamic parameters at 'prefix-:id-suffix'.`,+ ]);+});diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/url-pattern.ts b/apps/builder/app/builder/features/sidebar-left/panels/pages/url-pattern.tsindex 3c27a47df1..593fa8f3f3 100644--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/url-pattern.ts+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/url-pattern.ts@@ -15,7 +15,6 @@ export const parsePathnamePattern = (pathname: string) => {const indexRegex = /^\d+$/;-// @todo prevent replacing with empty strigsexport const compilePathnamePattern = (pathname: string,values: Record<string, string>@@ -38,3 +37,79 @@ export const compilePathnamePattern = (}return pathname;};++export const validatePathnamePattern = (pathname: string) => {+ try {+ new URLPattern(pathname, baseUrl);+ } catch {+ return [`Invalid path pattern '${pathname}'`];+ }++ const messages: string[] = [];++ // allowed syntax+ // :name - group without modifiers+ // :name? - group with optional modifier+ // :name* - group with zero or more modifier in the end+ // * - wildcard group in the end++ // fobid :name+ everywhere+ const namedGroupsWithPlus = Array.from(pathname.matchAll(/:\w+\+/g)).flat();+ if (namedGroupsWithPlus.length > 0) {+ const list = namedGroupsWithPlus.map((item) => `'${item}'`).join(", ");+ messages.push(`Dynamic parameters ${list} shouldn't have the + modifier.`);+ }++ // :name* in the middle+ const namedGroupsWithAsterisk = Array.from(+ // skip matching in the end of string+ pathname.matchAll(/:\w+\*(?!$)/g)+ ).flat();+ if (namedGroupsWithAsterisk.length > 0) {+ const list = namedGroupsWithAsterisk.map((item) => `'${item}'`).join(", ");+ messages.push(`${list} should end the path.`);+ }++ // *? everywhere+ const wildcardGroupsWithQuestion = Array.from(+ pathname.matchAll(/\*\?/g)+ ).flat();+ if (wildcardGroupsWithQuestion.length > 0) {+ messages.push(`Optional wildcard '*?' is not allowed.`);+ }++ // * in the middle+ const wildcardGroups = Array.from(+ // skip matching with :name before *+ // skip matching with ? after *+ // skip matching with * in the end+ pathname.matchAll(/(?<!:\w+)\*(?!\?)(?!$)/g)+ ).flat();+ if (wildcardGroups.length > 0) {+ messages.push(`Wildcard '*' should end the path.`);+ }++ // show segment errors only when syntax is valid+ if (messages.length > 0) {+ return messages;+ }++ for (const segment of pathname.split("/")) {+ const group = segment.match(/(?<group>:\w+(\*|\?)?)/)?.groups?.group;+ if (group) {+ if (group.length !== segment.length) {+ messages.push(+ `Static parts cannot be mixed with dynamic parameters at '${segment}'.`+ );+ }+ } else if (segment.includes("*")) {+ if (segment.length > 1) {+ messages.push(+ `Static parts cannot be mixed with dynamic parameters at '${segment}'.`+ );+ }+ }+ }++ return messages;+};diff --git a/packages/sdk/src/schema/pages.ts b/packages/sdk/src/schema/pages.tsindex 1696817516..2e3dca2759 100644--- a/packages/sdk/src/schema/pages.ts+++ b/packages/sdk/src/schema/pages.ts@@ -52,8 +52,8 @@ export const PagePath = z.refine((path) => path.endsWith("/") === false, "Can't end with a /").refine((path) => path.includes("//") === false, "Can't contain repeating /").refine(- (path) => /^[-_a-z0-9*:\\/]*$/.test(path),- "Only a-z, 0-9, -, _, /, : and * are allowed"+ (path) => /^[-_a-z0-9*:?\\/]*$/.test(path),+ "Only a-z, 0-9, -, _, /, :, ? and * are allowed").refine(// We use /s for our system stuff like /s/css or /s/uploads