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: Fix published redirect generation (#5825)

Oleg Isonenb67524bc0969
diff --git a/apps/builder/app/builder/features/pages/page-settings/page-settings.test.ts b/apps/builder/app/builder/features/pages/page-settings/page-settings.test.ts
index 8f6400538b..811aa4b2a7 100644
--- a/apps/builder/app/builder/features/pages/page-settings/page-settings.test.ts
+++ b/apps/builder/app/builder/features/pages/page-settings/page-settings.test.ts
@@ -287,6 +287,21 @@ describe("validateValues", () => {
expect(xmlErrors.language).toBeUndefined();
expect(xmlErrors.content).toBeUndefined();
});
+
+ test("allows redirect on the home page", () => {
+ const errors = validateValues(
+ createPages(),
+ homePage.id,
+ createValues({
+ isHomePage: true,
+ path: "/",
+ redirect: `"/test"`,
+ }),
+ new Map()
+ );
+
+ expect(errors.redirect).toBeUndefined();
+ });
});
describe("auth form values", () => {
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 dd181b45a6..a316d703fe 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
@@ -23,6 +23,7 @@ import {
PagePath,
ProjectNewRedirectPath,
documentTypes,
+ getPagePath,
isLiteralExpression,
type Page,
type Pages,
@@ -63,6 +64,17 @@ const HomePageGeneralValues = GeneralValues.extend({
path: HomePagePath,
});
+const computePageRoute = (values: Values, pages: Pages) => {
+ if (values.isHomePage) {
+ return "/";
+ }
+ const foldersPath = getPagePath(values.parentFolderId, pages);
+ return [foldersPath, values.path]
+ .filter(Boolean)
+ .join("/")
+ .replace(/\/+/g, "/");
+};
+
export const validateGeneralSection = ({
pages,
pageId,
@@ -117,7 +129,11 @@ export const validateGeneralSection = ({
) {
const existingRedirects = pages.redirects ?? [];
if (
- wouldCreateLoop(values.path, computedValues.redirect, existingRedirects)
+ wouldCreateLoop(
+ computePageRoute(values, pages),
+ computedValues.redirect,
+ existingRedirects
+ )
) {
errors.redirect = errors.redirect ?? [];
errors.redirect.push(LOOP_ERROR);
diff --git a/apps/builder/app/shared/project-settings/import-redirects-dialog.test.ts b/apps/builder/app/shared/project-settings/import-redirects-dialog.test.ts
new file mode 100644
index 0000000000..5b7a34f21b
--- /dev/null
+++ b/apps/builder/app/shared/project-settings/import-redirects-dialog.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, test } from "vitest";
+import { __testing__ } from "./import-redirects-dialog";
+
+const { splitDuplicateRedirects, splitRedirectsForMergeMode } = __testing__;
+
+describe("splitDuplicateRedirects", () => {
+ test("skips redirects that duplicate existing sources after normalization", () => {
+ const result = splitDuplicateRedirects(
+ [
+ { old: "/%C3%BCber", new: "/new" },
+ { old: "/fresh", new: "/fresh-new" },
+ ],
+ [{ old: "/über" }]
+ );
+
+ expect(result.unique).toEqual([{ old: "/fresh", new: "/fresh-new" }]);
+ expect(result.duplicates).toEqual([{ old: "/%C3%BCber", new: "/new" }]);
+ });
+
+ test("skips duplicate sources within the imported batch", () => {
+ const result = splitDuplicateRedirects(
+ [
+ { old: "/old#one", new: "/one" },
+ { old: "/old#two", new: "/two" },
+ { old: "/path?x=1", new: "/query-one" },
+ { old: "/path?x=2", new: "/query-two" },
+ ],
+ []
+ );
+
+ expect(result.unique).toEqual([
+ { old: "/old#one", new: "/one" },
+ { old: "/path?x=1", new: "/query-one" },
+ { old: "/path?x=2", new: "/query-two" },
+ ]);
+ expect(result.duplicates).toEqual([{ old: "/old#two", new: "/two" }]);
+ });
+});
+
+describe("splitRedirectsForMergeMode", () => {
+ test("add mode skips redirects that duplicate existing sources", () => {
+ const result = splitRedirectsForMergeMode(
+ [
+ { old: "/%C3%BCber", new: "/new" },
+ { old: "/fresh", new: "/fresh-new" },
+ ],
+ [{ old: "/über" }],
+ "add"
+ );
+
+ expect(result.unique).toEqual([{ old: "/fresh", new: "/fresh-new" }]);
+ expect(result.duplicates).toEqual([{ old: "/%C3%BCber", new: "/new" }]);
+ });
+
+ test("replace mode ignores existing redirects but skips duplicate imported sources", () => {
+ const result = splitRedirectsForMergeMode(
+ [
+ { old: "/%C3%BCber", new: "/new" },
+ { old: "/old#one", new: "/one" },
+ { old: "/old#two", new: "/two" },
+ ],
+ [{ old: "/über" }],
+ "replace"
+ );
+
+ expect(result.unique).toEqual([
+ { old: "/%C3%BCber", new: "/new" },
+ { old: "/old#one", new: "/one" },
+ ]);
+ expect(result.duplicates).toEqual([{ old: "/old#two", new: "/two" }]);
+ });
+});
diff --git a/apps/builder/app/shared/project-settings/import-redirects-dialog.tsx b/apps/builder/app/shared/project-settings/import-redirects-dialog.tsx
index 83e0c61f86..392e96b9fa 100644
--- a/apps/builder/app/shared/project-settings/import-redirects-dialog.tsx
+++ b/apps/builder/app/shared/project-settings/import-redirects-dialog.tsx
@@ -27,6 +27,7 @@ import {
type SkippedLine,
} from "~/shared/redirects/redirect-parsers";
import { detectLoopsInBatch } from "~/shared/redirects/redirect-loop-detection";
+import { normalizeRedirectSource } from "~/shared/redirects/redirect-source";
type ImportStep = "input" | "preview";
type MergeMode = "add" | "replace";
@@ -42,6 +43,45 @@ const ACCEPTED_EXTENSIONS = [".csv", ".json", ".txt", ".htaccess"];
const formatSupportsText = `Supports: CSV, JSON, Netlify _redirects, Apache .htaccess`;
+const splitDuplicateRedirects = <Redirect extends { old: string }>(
+ redirects: Redirect[],
+ existingRedirects: Array<{ old: string }>
+) => {
+ const seenSources = new Set(
+ existingRedirects.map((redirect) => normalizeRedirectSource(redirect.old))
+ );
+ const unique: Redirect[] = [];
+ const duplicates: Redirect[] = [];
+
+ for (const redirect of redirects) {
+ const source = normalizeRedirectSource(redirect.old);
+ if (seenSources.has(source)) {
+ duplicates.push(redirect);
+ continue;
+ }
+ seenSources.add(source);
+ unique.push(redirect);
+ }
+
+ return { unique, duplicates };
+};
+
+const splitRedirectsForMergeMode = <Redirect extends { old: string }>(
+ redirects: Redirect[],
+ existingRedirects: Array<{ old: string }>,
+ mergeMode: MergeMode
+) => {
+ return splitDuplicateRedirects(
+ redirects,
+ mergeMode === "add" ? existingRedirects : []
+ );
+};
+
+export const __testing__ = {
+ splitDuplicateRedirects,
+ splitRedirectsForMergeMode,
+};
+
export const ImportRedirectsDialog = ({
isOpen,
onOpenChange,
@@ -150,10 +190,11 @@ export const ImportRedirectsDialog = ({
status: r.status === 301 ? "301" : "302",
}));
- // Find duplicates with existing redirects
- const existingPaths = new Set(existingRedirects.map((r) => r.old));
- const duplicates = newRedirects.filter((r) => existingPaths.has(r.old));
- const uniqueNew = newRedirects.filter((r) => !existingPaths.has(r.old));
+ const { unique: uniqueNew, duplicates } = splitRedirectsForMergeMode(
+ newRedirects,
+ existingRedirects,
+ mergeMode
+ );
if (mergeMode === "add") {
// Detect loops with existing redirects
@@ -176,14 +217,17 @@ export const ImportRedirectsDialog = ({
);
} else {
// Replace all - detect loops within the new set
- const { valid, looped } = detectLoopsInBatch(newRedirects, []);
+ const { valid, looped } = detectLoopsInBatch(uniqueNew, []);
const loopCount = looped.length;
onImport(valid, "replace");
+ const skippedParts = [
+ duplicates.length > 0 &&
+ `${duplicates.length} duplicate${duplicates.length !== 1 ? "s" : ""}`,
+ loopCount > 0 && `${loopCount} loop${loopCount !== 1 ? "s" : ""}`,
+ ].filter(Boolean);
const skippedMessage =
- loopCount > 0
- ? ` (${loopCount} loop${loopCount !== 1 ? "s" : ""} skipped)`
- : "";
+ skippedParts.length > 0 ? ` (${skippedParts.join(", ")} skipped)` : "";
toast.success(
`Replaced all redirects with ${valid.length} new redirect${valid.length !== 1 ? "s" : ""}${skippedMessage}`
);
@@ -192,13 +236,10 @@ export const ImportRedirectsDialog = ({
handleOpenChange(false);
};
- // Count duplicates for display
- const existingPaths = new Set(existingRedirects.map((r) => r.old));
- const duplicateRedirects = parsedRedirects.filter((r) =>
- existingPaths.has(r.old)
- );
+ const { unique: uniqueRedirects, duplicates: duplicateRedirects } =
+ splitRedirectsForMergeMode(parsedRedirects, existingRedirects, mergeMode);
const duplicateCount = duplicateRedirects.length;
- const uniqueCount = parsedRedirects.length - duplicateCount;
+ const uniqueCount = uniqueRedirects.length;
return (
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
diff --git a/apps/builder/app/shared/project-settings/section-redirects.test.ts b/apps/builder/app/shared/project-settings/section-redirects.test.ts
index 584734959b..d835e117d7 100644
--- a/apps/builder/app/shared/project-settings/section-redirects.test.ts
+++ b/apps/builder/app/shared/project-settings/section-redirects.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, test } from "vitest";
import type { PageRedirect } from "@webstudio-is/sdk";
import { __testing__ } from "./section-redirects";
-const { validateFromPath, validateToPath } = __testing__;
+const { deleteRedirect, validateFromPath, validateToPath } = __testing__;
describe("validateFromPath", () => {
describe("format validation", () => {
@@ -20,29 +20,41 @@ describe("validateFromPath", () => {
test("returns error for path not starting with /", () => {
const result = validateFromPath("page", [], new Set());
- expect(result.errors).toContain(
- "Must start with a / or a full URL e.g. https://website.org"
- );
+ expect(result.errors).toContain("Must start with a /");
expect(result.warnings).toEqual([]);
});
- test("returns error for path ending with /", () => {
+ test("accepts path ending with /", () => {
const result = validateFromPath("/page/", [], new Set());
- expect(result.errors).toContain("Can't end with a /");
+ expect(result.errors).toEqual([]);
expect(result.warnings).toEqual([]);
});
- test("returns error for path with double slashes", () => {
+ test("accepts path with double slashes", () => {
const result = validateFromPath("/page//subpage", [], new Set());
- expect(result.errors).toContain("Can't contain repeating /");
+ expect(result.errors).toEqual([]);
expect(result.warnings).toEqual([]);
});
- test("returns error for path with invalid characters", () => {
+ test("accepts browser-encodable characters", () => {
const result = validateFromPath("/page name", [], new Set());
- expect(result.errors).toContain(
- "Path contains invalid characters (spaces or URL-unsafe characters are not allowed)"
+ expect(result.errors).toEqual([]);
+ expect(result.warnings).toEqual([]);
+ });
+
+ test("accepts query values containing unencoded urls", () => {
+ const result = validateFromPath(
+ "/path?url=https://example.com/a?b=c",
+ [],
+ new Set()
);
+ expect(result.errors).toEqual([]);
+ expect(result.warnings).toEqual([]);
+ });
+
+ test("returns error for path with backslash", () => {
+ const result = validateFromPath("/page\\name", [], new Set());
+ expect(result.errors).toContain("Must be a valid URL path");
expect(result.warnings).toEqual([]);
});
@@ -76,6 +88,14 @@ describe("validateFromPath", () => {
expect(result.warnings).toEqual([]);
});
+ test("warns that source fragments are ignored", () => {
+ const result = validateFromPath("/page#section", [], new Set());
+ expect(result.errors).toEqual([]);
+ expect(result.warnings).toContain(
+ "Source fragments are ignored because browsers do not send them"
+ );
+ });
+
test("accepts path with uppercase letters", () => {
const result = validateFromPath("/Path/SubPage", [], new Set());
expect(result.errors).toEqual([]);
@@ -110,9 +130,11 @@ describe("validateFromPath", () => {
expect(result.warnings).toEqual([]);
});
- test("accepts path with named splat", () => {
+ test("rejects path with named splat", () => {
const result = validateFromPath("/docs/:path*", [], new Set());
- expect(result.errors).toEqual([]);
+ expect(result.errors).toContain(
+ "Named splats are not supported; use * instead"
+ );
expect(result.warnings).toEqual([]);
});
@@ -122,25 +144,9 @@ describe("validateFromPath", () => {
expect(result.warnings).toEqual([]);
});
- test("skips duplicate/warning checks for paths not starting with /", () => {
- // External URLs or other formats that pass schema validation
- // but don't start with / should skip the duplicate redirect
- // and existing page checks (since those only apply to local paths)
- const existingRedirects: Array<PageRedirect> = [
- { old: "https://old.com/page", new: "/new", status: "301" },
- ];
- const existingPaths = new Set(["https://old.com/page"]);
-
- // Even though this path "exists" in redirects and pages,
- // no error/warning because it doesn't start with /
- // Note: This tests the current behavior - external URLs bypass checks
- const result = validateFromPath(
- "https://old.com/page",
- existingRedirects,
- existingPaths
- );
- // The schema may reject this, but if it passes, no duplicate check
- // If schema rejects, we get format errors instead
+ test("rejects external source URLs", () => {
+ const result = validateFromPath("https://old.com/page", [], new Set());
+ expect(result.errors).toContain("Must start with a /");
expect(result.warnings).toEqual([]);
});
});
@@ -163,6 +169,50 @@ describe("validateFromPath", () => {
expect(result.warnings).toEqual([]);
});
+ test("returns error when redirect already exists without source fragment", () => {
+ const result = validateFromPath(
+ "/old-page#section",
+ existingRedirects,
+ new Set()
+ );
+ expect(result.errors).toContain("This path is already being redirected");
+ expect(result.warnings).toContain(
+ "Source fragments are ignored because browsers do not send them"
+ );
+ });
+
+ test("returns error when fragment-only sources would match the same request", () => {
+ const result = validateFromPath(
+ "/old-page#two",
+ [{ old: "/old-page#one", new: "/new-page", status: "301" }],
+ new Set()
+ );
+ expect(result.errors).toContain("This path is already being redirected");
+ expect(result.warnings).toContain(
+ "Source fragments are ignored because browsers do not send them"
+ );
+ });
+
+ test("returns error when encoded and decoded sources would match the same request", () => {
+ const result = validateFromPath(
+ "/%C3%BCber",
+ [{ old: "/über", new: "/new-page", status: "301" }],
+ new Set()
+ );
+ expect(result.errors).toContain("This path is already being redirected");
+ expect(result.warnings).toEqual([]);
+ });
+
+ test("does not treat different exact query strings as duplicates", () => {
+ const result = validateFromPath(
+ "/old-page?x=2",
+ [{ old: "/old-page?x=1", new: "/new-page", status: "301" }],
+ new Set()
+ );
+ expect(result.errors).toEqual([]);
+ expect(result.warnings).toEqual([]);
+ });
+
test("returns error when wildcard redirect already exists", () => {
const result = validateFromPath("/blog/*", existingRedirects, new Set());
expect(result.errors).toContain("This path is already being redirected");
@@ -212,6 +262,49 @@ describe("validateFromPath", () => {
);
});
+ test("checks existing page warning without source fragment", () => {
+ const result = validateFromPath("/about#section", [], existingPaths);
+ expect(result.errors).toEqual([]);
+ expect(result.warnings).toEqual([
+ "Source fragments are ignored because browsers do not send them",
+ "This redirect will override an existing page",
+ ]);
+ });
+
+ test("checks existing page warning with encoded source path", () => {
+ const result = validateFromPath("/%C3%BCber", [], new Set(["/über"]));
+ expect(result.errors).toEqual([]);
+ expect(result.warnings).toContain(
+ "This redirect will override an existing page"
+ );
+ });
+
+ test("returns warning when concrete redirect source overrides dynamic page path", () => {
+ const result = validateFromPath("/blog/post", [], new Set(["/blog/:id"]));
+ expect(result.errors).toEqual([]);
+ expect(result.warnings).toContain(
+ "This redirect will override an existing page"
+ );
+ });
+
+ test("returns warning when redirect pattern overrides concrete page path", () => {
+ const result = validateFromPath(
+ "/blog/:slug",
+ [],
+ new Set(["/blog/post"])
+ );
+ expect(result.errors).toEqual([]);
+ expect(result.warnings).toContain(
+ "This redirect will override an existing page"
+ );
+ });
+
+ test("does not warn that query-specific source fully overrides an existing page", () => {
+ const result = validateFromPath("/about?x=1", [], existingPaths);
+ expect(result.errors).toEqual([]);
+ expect(result.warnings).toEqual([]);
+ });
+
test("returns warning for dynamic route path", () => {
const result = validateFromPath("/blog/:id", [], existingPaths);
expect(result.errors).toEqual([]);
@@ -276,6 +369,45 @@ describe("validateToPath", () => {
const errors = validateToPath("//example.com/page");
expect(errors).toEqual([]);
});
+
+ test("accepts target params provided by source pattern", () => {
+ expect(validateToPath("/posts/:slug", "/blog/:slug")).toEqual([]);
+ expect(validateToPath("/reference/*", "/docs/*")).toEqual([]);
+ });
+
+ test("rejects target params that source cannot provide", () => {
+ expect(validateToPath("/posts/:slug", "/old")).toContain(
+ "Target route params must match params from the source path"
+ );
+ expect(validateToPath("/posts/:slug", "/old?preview=1")).toContain(
+ "Target route params must match params from the source path"
+ );
+ expect(validateToPath("/reference/*", "/docs")).toContain(
+ "Target route params must match params from the source path"
+ );
+ });
+
+ test("rejects unsupported target param syntax", () => {
+ expect(validateToPath("/posts/:year-:slug", "/blog/:year/:slug")).toContain(
+ "Target route params must match params from the source path"
+ );
+ expect(validateToPath("/posts?slug=:slug", "/blog/:slug")).toContain(
+ "Target route params must match params from the source path"
+ );
+ });
+});
+
+describe("deleteRedirect", () => {
+ test("deletes the selected redirect object instead of relying on filtered index", () => {
+ const first = { old: "/first", new: "/one", status: "301" } as const;
+ const second = { old: "/second", new: "/two", status: "301" } as const;
+ const third = { old: "/third", new: "/three", status: "301" } as const;
+
+ expect(deleteRedirect([first, second, third], third)).toEqual([
+ first,
+ second,
+ ]);
+ });
});
describe("redirect patterns (integration tests)", () => {
@@ -296,11 +428,9 @@ describe("redirect patterns (integration tests)", () => {
expect(toErrors).toEqual([]);
});
- test("parameterized from path: /old/:slug → /new (param captured but not substituted)", () => {
- // Note: The :slug is captured by the router but cannot be substituted
- // into the "to" path - all matching URLs redirect to the same destination
+ test("parameterized redirect: /old/:slug → /new/:slug", () => {
const fromResult = validateFromPath("/old/:slug", [], new Set());
- const toErrors = validateToPath("/new");
+ const toErrors = validateToPath("/new/:slug", "/old/:slug");
expect(fromResult.errors).toEqual([]);
expect(toErrors).toEqual([]);
});
diff --git a/apps/builder/app/shared/project-settings/section-redirects.tsx b/apps/builder/app/shared/project-settings/section-redirects.tsx
index 1a1940954a..87bb05aef1 100644
--- a/apps/builder/app/shared/project-settings/section-redirects.tsx
+++ b/apps/builder/app/shared/project-settings/section-redirects.tsx
@@ -31,18 +31,28 @@ import {
UploadIcon,
} from "@webstudio-is/icons";
import { ImportRedirectsDialog } from "./import-redirects-dialog";
-import { OldPagePath, 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";
import { $pages } from "~/shared/sync/data-stores";
import { $publishedOrigin } from "~/shared/nano-states";
import { serverSyncStore } from "~/shared/sync/sync-stores";
-import { getExistingRoutePaths, sectionSpacing } from "./utils";
+import {
+ doesRedirectSourceOverridePagePath,
+ getExistingRoutePaths,
+ sectionSpacing,
+} from "./utils";
import {
LOOP_ERROR,
wouldCreateLoop,
} from "~/shared/redirects/redirect-loop-detection";
+import {
+ hasInvalidLocalTargetParams,
+ hasNamedSplat,
+ normalizeRedirectSource,
+ stripRedirectSourceFragment,
+} from "~/shared/redirects/redirect-source";
const statusCodeOptions = ["301", "302"] as const;
@@ -61,28 +71,48 @@ const validateFromPath = (
redirects: Array<PageRedirect>,
existingPaths: Set<string>
): ValidationResult => {
- const fromPathValidationResult = OldPagePath.safeParse(fromPath);
+ const fromPathValidationResult = RedirectSourcePath.safeParse(fromPath);
if (fromPathValidationResult.success) {
- if (fromPath.startsWith("/")) {
- // Check for duplicate redirect first (error takes precedence)
- if (redirects.some((redirect) => redirect.old === fromPath)) {
- return {
- errors: ["This path is already being redirected"],
- warnings: [],
- };
- }
+ if (hasNamedSplat(fromPath)) {
+ return {
+ errors: ["Named splats are not supported; use * instead"],
+ warnings: [],
+ };
+ }
- // Show warning if redirecting from an existing page path
- // The redirect will take precedence over the page when published
- if (existingPaths.has(fromPath)) {
- return {
- errors: [],
- warnings: ["This redirect will override an existing page"],
- };
- }
+ const sourceWithoutFragment = stripRedirectSourceFragment(fromPath);
+ const sourcePath = normalizeRedirectSource(fromPath);
+ const warnings =
+ sourceWithoutFragment === fromPath
+ ? []
+ : ["Source fragments are ignored because browsers do not send them"];
+
+ // Check for duplicate redirect first (error takes precedence)
+ if (
+ redirects.some(
+ (redirect) => normalizeRedirectSource(redirect.old) === sourcePath
+ )
+ ) {
+ return {
+ errors: ["This path is already being redirected"],
+ warnings,
+ };
+ }
+
+ // Show warning if redirecting from an existing page path.
+ // The redirect will take precedence over the page when published.
+ if (
+ Array.from(existingPaths).some((pagePath) =>
+ doesRedirectSourceOverridePagePath(sourcePath, pagePath)
+ )
+ ) {
+ return {
+ errors: [],
+ warnings: [...warnings, "This redirect will override an existing page"],
+ };
}
- return { errors: [], warnings: [] };
+ return { errors: [], warnings };
}
return {
@@ -91,16 +121,32 @@ const validateFromPath = (
};
};
-const validateToPath = (toPath: string): string[] => {
+const unsupportedTargetParamMessage =
+ "Target route params must match params from the source path";
+
+const validateToPath = (toPath: string, fromPath?: string): string[] => {
const toPathValidationResult = ProjectNewRedirectPath.safeParse(toPath);
- if (toPathValidationResult.success) {
- return [];
+ if (toPathValidationResult.success === false) {
+ return toPathValidationResult.error.format()._errors;
+ }
+
+ if (hasInvalidLocalTargetParams(toPath, fromPath)) {
+ return [unsupportedTargetParamMessage];
}
- return toPathValidationResult.error.format()._errors;
+
+ return [];
+};
+
+const deleteRedirect = (
+ redirects: Array<PageRedirect>,
+ redirectToDelete: PageRedirect
+) => {
+ return redirects.filter((redirect) => redirect !== redirectToDelete);
};
// Exported for testing
export const __testing__ = {
+ deleteRedirect,
validateFromPath,
validateToPath,
};
@@ -149,11 +195,14 @@ export const SectionRedirects = () => {
);
setFromPathErrors(errors);
setFromPathWarnings(warnings);
+ if (toPath !== "") {
+ setToPathErrors(validateToPath(toPath, value));
+ }
};
const handleToPathChange = (value: string) => {
setToPath(value);
- setToPathErrors(validateToPath(value));
+ setToPathErrors(validateToPath(value, fromPath));
};
const handleSave = (redirects: Array<PageRedirect>) => {
@@ -172,7 +221,7 @@ export const SectionRedirects = () => {
redirects,
existingPaths
);
- const toPathValidationErrors = validateToPath(toPath);
+ const toPathValidationErrors = validateToPath(toPath, fromPath);
const hasLoop = wouldCreateLoop(fromPath, toPath, redirects);
// Update error state so user sees what went wrong
@@ -207,10 +256,8 @@ export const SectionRedirects = () => {
fromPathRef.current?.focus();
};
- const handleDeleteRedirect = (index: number) => {
- const newRedirects = [...redirects];
- newRedirects.splice(index, 1);
- handleSave(newRedirects);
+ const handleDeleteRedirect = (redirect: PageRedirect) => {
+ handleSave(deleteRedirect(redirects, redirect));
};
const handleImportRedirects = (
@@ -400,7 +447,7 @@ export const SectionRedirects = () => {
<Grid css={sectionSpacing}>
<List asChild>
<Flex direction="column" gap="1" align="stretch">
- {filteredRedirects.map((redirect, index) => {
+ {filteredRedirects.map((redirect) => {
return (
<ListItem asChild key={redirect.old}>
<Grid
@@ -466,7 +513,7 @@ export const SectionRedirects = () => {
variant="destructive"
icon={<TrashIcon />}
aria-label={`Delete redirect from ${redirect.old}`}
- onClick={() => handleDeleteRedirect(index)}
+ onClick={() => handleDeleteRedirect(redirect)}
/>
</Grid>
</ListItem>
diff --git a/apps/builder/app/shared/project-settings/utils.test.ts b/apps/builder/app/shared/project-settings/utils.test.ts
index d0bc83c397..4b7e08e788 100644
--- a/apps/builder/app/shared/project-settings/utils.test.ts
+++ b/apps/builder/app/shared/project-settings/utils.test.ts
@@ -1,7 +1,11 @@
import { describe, expect, test } from "vitest";
import { createDefaultPages } from "@webstudio-is/project-build";
import type { PageRedirect } from "@webstudio-is/sdk";
-import { getExistingRoutePaths, findMatchingRedirect } from "./utils";
+import {
+ doesRedirectSourceOverridePagePath,
+ findMatchingRedirect,
+ getExistingRoutePaths,
+} from "./utils";
describe("getExistingRoutePaths", () => {
test("gets all the route paths that exists in the project", () => {
@@ -50,6 +54,24 @@ describe("findMatchingRedirect", () => {
expect(result?.old).toBe("/about");
});
+ test("finds redirect after removing source fragment", () => {
+ const redirects = [createRedirect("/about#section")];
+ const result = findMatchingRedirect("/about", redirects);
+ expect(result?.old).toBe("/about#section");
+ });
+
+ test("finds redirect with encoded source path for decoded page path", () => {
+ const redirects = [createRedirect("/%C3%BCber")];
+ const result = findMatchingRedirect("/über", redirects);
+ expect(result?.old).toBe("/%C3%BCber");
+ });
+
+ test("does not report query-specific redirect as fully overriding a page", () => {
+ const redirects = [createRedirect("/about?x=1")];
+ const result = findMatchingRedirect("/about", redirects);
+ expect(result).toBeUndefined();
+ });
+
test("returns undefined when no match found", () => {
const redirects = [createRedirect("/about")];
const result = findMatchingRedirect("/contact", redirects);
@@ -127,6 +149,12 @@ describe("findMatchingRedirect", () => {
const result = findMatchingRedirect("/blog", redirects);
expect(result?.old).toBe("/blog/:id?");
});
+
+ test("matches optional static segment", () => {
+ const redirects = [createRedirect("/en?/about")];
+ const result = findMatchingRedirect("/en/about", redirects);
+ expect(result?.old).toBe("/en?/about");
+ });
});
describe("priority and order", () => {
@@ -171,3 +199,39 @@ describe("findMatchingRedirect", () => {
});
});
});
+
+describe("doesRedirectSourceOverridePagePath", () => {
+ test("returns true when exact redirect source matches exact page path", () => {
+ expect(doesRedirectSourceOverridePagePath("/about", "/about")).toBe(true);
+ });
+
+ test("returns true when exact redirect source matches dynamic page path", () => {
+ expect(doesRedirectSourceOverridePagePath("/blog/post", "/blog/:id")).toBe(
+ true
+ );
+ });
+
+ test("returns true when redirect pattern matches exact page path", () => {
+ expect(
+ doesRedirectSourceOverridePagePath("/blog/:slug", "/blog/post")
+ ).toBe(true);
+ });
+
+ test("returns true when redirect splat overlaps page path", () => {
+ expect(doesRedirectSourceOverridePagePath("/docs/*", "/docs/:id")).toBe(
+ true
+ );
+ });
+
+ test("returns false for exact-query redirect source", () => {
+ expect(doesRedirectSourceOverridePagePath("/about?x=1", "/about")).toBe(
+ false
+ );
+ });
+
+ test("returns false when paths do not overlap", () => {
+ expect(doesRedirectSourceOverridePagePath("/about", "/contact")).toBe(
+ false
+ );
+ });
+});
diff --git a/apps/builder/app/shared/project-settings/utils.ts b/apps/builder/app/shared/project-settings/utils.ts
index 843aa29466..eca9b5cc7d 100644
--- a/apps/builder/app/shared/project-settings/utils.ts
+++ b/apps/builder/app/shared/project-settings/utils.ts
@@ -5,7 +5,12 @@ import {
type Pages,
type PageRedirect,
} from "@webstudio-is/sdk";
-import { matchPathnamePattern } from "~/builder/shared/url-pattern";
+import { matchPath } from "@remix-run/react";
+import {
+ getRedirectSourcePathname,
+ getRedirectSourceSearchIndex,
+ normalizeRedirectSource,
+} from "~/shared/redirects/redirect-source";
export const leftPanelWidth = rawTheme.spacing[26];
export const rightPanelWidth = rawTheme.spacing[35];
@@ -32,18 +37,52 @@ export const getExistingRoutePaths = (pages?: Pages): Set<string> => {
return paths;
};
+export const doesRedirectSourceOverridePagePath = (
+ redirectSource: string,
+ pagePath: string
+) => {
+ const source = normalizeRedirectSource(redirectSource);
+ if (getRedirectSourceSearchIndex(source) !== -1) {
+ return false;
+ }
+
+ const sourcePathname = getRedirectSourcePathname(source);
+ const normalizedPagePath = normalizeRedirectSource(pagePath);
+
+ if (sourcePathname === normalizedPagePath) {
+ return true;
+ }
+
+ return (
+ matchPath(
+ {
+ path: normalizedPagePath,
+ caseSensitive: true,
+ end: true,
+ },
+ sourcePathname
+ ) !== null ||
+ matchPath(
+ {
+ path: sourcePathname,
+ caseSensitive: true,
+ end: true,
+ },
+ normalizedPagePath
+ ) !== null
+ );
+};
+
/**
* Find a redirect that would match the given page path.
- * Uses URLPattern for proper pattern matching (wildcards, dynamic segments).
+ * Uses the same pattern matcher as published redirect runtime.
*/
export const findMatchingRedirect = (
pagePath: string,
redirects: Array<PageRedirect>
): PageRedirect | undefined => {
for (const redirect of redirects) {
- // matchPathnamePattern returns matched groups if pattern matches, undefined otherwise
- const match = matchPathnamePattern(redirect.old, pagePath);
- if (match !== undefined) {
+ if (doesRedirectSourceOverridePagePath(redirect.old, pagePath)) {
return redirect;
}
}
diff --git a/apps/builder/app/shared/redirects/README.md b/apps/builder/app/shared/redirects/README.md
index 0289da75ad..1e0fdc4731 100644
--- a/apps/builder/app/shared/redirects/README.md
+++ b/apps/builder/app/shared/redirects/README.md
@@ -8,7 +8,7 @@ Webstudio stores redirects with this schema:
```typescript
type PageRedirect = {
- old: string; // Source path (must start with /, cannot end with /)
+ old: string; // Source path, pattern, or exact path + query
new: string; // Target path or URL
status?: "301" | "302"; // Optional, defaults to 301
};
@@ -16,24 +16,21 @@ type PageRedirect = {
### Path Requirements
-| Requirement | Valid | Invalid |
-| ------------------- | ------------------ | ---------------------- |
-| Must start with `/` | `/about` | `about` |
-| Cannot end with `/` | `/about` | `/about/` |
-| No double slashes | `/a/b/c` | `/a//b` |
-| Allowed chars | `a-zA-Z0-9-_/:?.*` | `<>{}` |
-| Reserved paths | `/home` | `/s/...`, `/build/...` |
+| Requirement | Valid | Invalid |
+| -------------------------- | --------------------- | ---------------------- |
+| Must start with `/` | `/about` | `about` |
+| Root is not a source | `/about` | `/` |
+| Protocol-relative rejected | `/about` | `//example.com/path` |
+| Exact query allowed | `/old?x=1` | |
+| Simple splat allowed | `/docs/*` | `/docs/:path*` |
+| Browser URL chars allowed | `/über`, `/path name` | backslashes, controls |
+| Reserved paths | `/home` | `/s/...`, `/build/...` |
-### Slash Normalization
+### Path Exactness
-The parser **strips trailing slashes** from source paths to match Webstudio's requirements:
-
-```
-Input: /old-path/ → Output: /old-path
-Input: /old-path → Output: /old-path
-```
-
-Target paths preserve their original form (Webstudio allows trailing slashes in targets).
+The parser preserves source paths exactly after trimming surrounding whitespace.
+`/old` and `/old/` remain different redirects because the published runtime does
+not normalize trailing slashes.
---
@@ -231,20 +228,28 @@ REDIRECT 301 /uppercase /target
These patterns are **skipped with a warning** (not imported):
-### Dynamic Placeholders
+### Platform-Specific Dynamic Syntax
```
-/blog/:slug → /posts/:slug
+/docs/:path* → /documentation/*
/news/:year/:month/:slug → /archive/:year-:month-:slug
```
-### Splat Wildcards
+Webstudio supports simple route params like `/blog/:slug` and splats like
+`/docs/*`. Named splats and composite local target params are skipped because
+they do not expand with Webstudio's published redirect runtime.
+
+### Splat Target Syntax
```
/docs/* → /documentation/:splat
-/old/* → /new/*
```
+Netlify `:splat` targets are converted to Webstudio `*` targets during import.
+Only target pathnames are converted. Query or hash substitutions like
+`/files?name=:splat` are skipped because the published runtime does not expand
+params outside the target pathname. Other named splat styles are skipped.
+
### Conditions
```
@@ -307,13 +312,17 @@ Webstudio supports these path patterns in redirects:
| Segment | `/:slug` | `/anything` (single segment) |
| Optional | `/:id?` | `/` or `/123` |
-**Important:** Captured values (like `:slug`) cannot be inserted into the destination path. The destination is always a fixed path or URL.
+Captured values can be inserted into local destination paths with the same
+parameter names. External and protocol-relative targets are returned unchanged.
### What Gets Imported
✅ **Imported:**
- Simple path-to-path redirects (`/old` → `/new`)
+- Exact query redirects (`/old?x=1` → `/new`)
+- Simple dynamic redirects (`/blog/:slug` → `/posts/:slug`)
+- Splat redirects (`/old/*` → `/new/*`)
- Redirects to external URLs (`/github` → `https://github.com/...`)
- 301 (permanent) and 302 (temporary) status codes
- 307 and 308 status codes (converted to 302 and 301)
@@ -322,10 +331,12 @@ Webstudio supports these path patterns in redirects:
⚠️ **Skipped (with explanation):**
-- Dynamic placeholders like `/blog/:slug` → `/posts/:slug`
-- Wildcard substitutions like `/old/*` → `/new/*`
+- Named splats like `/docs/:path*`
+- Composite local target params like `/archive/:year-:slug`
+- Param-expanded targets for exact query sources like
+ `/old?x=1 → /posts/:slug`
- Conditional redirects (country, header, cookie-based)
-- Query parameter matching
+- Platform-specific query parameter matching
- Regex-based rules (Apache RewriteRule, RedirectMatch)
- Rewrites (status 200) and "not found" rules (status 404)
@@ -338,11 +349,11 @@ Webstudio redirects are designed for simplicity and performance. Some advanced f
| Simple redirects | ✅ | ✅ | ✅ | ✅ |
| External URLs | ✅ | ✅ | ✅ | ✅ |
| Wildcard source | ✅ | ✅ | ✅ | ✅ |
-| Wildcard substitution | ✅ | ✅ | ✅ | ❌ |
+| Wildcard substitution | ✅ | ✅ | ✅ | ✅ |
| Regex patterns | ❌ | ❌ | ✅ | ❌ |
| Header/cookie conditions | ✅ | ✅ | ✅ | ❌ |
| Geo/country conditions | ✅ | ✅ | ❌ | ❌ |
-| Query string matching | ✅ | ✅ | ✅ | ❌ |
+| Exact query redirects | ✅ | ✅ | ✅ | ✅ |
| Rewrites (proxy) | ✅ | ✅ | ✅ | ❌ |
### Status Codes Explained
@@ -430,8 +441,8 @@ After parsing, show a preview before importing:
│ │
│ Skipped: │
│ ┌─────────────────────────────────────────────────────┐ │
-│ │ Line 5: /docs/* → wildcard patterns not supported │ │
-│ │ Line 8: /:slug → placeholders not supported │ │
+│ │ Line 5: /store id=:id → query matching not supported│ │
+│ │ Line 8: RewriteRule → advanced rewrites unsupported│ │
│ │ Line 12: missing target path │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
@@ -530,5 +541,5 @@ From `@webstudio-is/design-system`:
6. **Skipped Feedback**: Show why lines were skipped with line numbers
7. **Merge Options**: Let user choose add vs replace
8. **Duplicate Handling**: Detect and handle conflicts with existing redirects
-9. **Validation**: Run Webstudio's `OldPagePath` validation on import
+9. **Validation**: Run Webstudio's `RedirectSourcePath` validation on import
10. **Toast Feedback**: Show success/error toast after import
diff --git a/apps/builder/app/shared/redirects/fixtures/netlify._redirects b/apps/builder/app/shared/redirects/fixtures/netlify._redirects
index 43407c7b5d..702074d70c 100644
--- a/apps/builder/app/shared/redirects/fixtures/netlify._redirects
+++ b/apps/builder/app/shared/redirects/fixtures/netlify._redirects
@@ -47,7 +47,7 @@
/perm-redirect /perm 308
# -----------------------------------------------------------------
-# PATH PATTERNS (skipped - unsupported)
+# PATH PATTERNS
# -----------------------------------------------------------------
# Splat wildcards
@@ -101,7 +101,7 @@
# TRAILING SLASH HANDLING
# -----------------------------------------------------------------
-# Will be normalized (trailing slash stripped from source)
+# Trailing slash is preserved in the source
/old-path/ /new-path 301
# -----------------------------------------------------------------
diff --git a/apps/builder/app/shared/redirects/redirect-loop-detection.test.ts b/apps/builder/app/shared/redirects/redirect-loop-detection.test.ts
index bfd01be7fc..9b050a7ef9 100644
--- a/apps/builder/app/shared/redirects/redirect-loop-detection.test.ts
+++ b/apps/builder/app/shared/redirects/redirect-loop-detection.test.ts
@@ -14,6 +14,51 @@ describe("wouldCreateLoop", () => {
];
expect(wouldCreateLoop("/about", "/about", existing)).toBe(true);
});
+
+ test("returns true for self-redirect with target fragment", () => {
+ expect(wouldCreateLoop("/about", "/about#section", [])).toBe(true);
+ });
+
+ test("returns true for self-redirect with source fragment", () => {
+ expect(wouldCreateLoop("/about#section", "/about", [])).toBe(true);
+ });
+
+ test("returns true when path-only source redirects to the same path with query", () => {
+ expect(wouldCreateLoop("/about", "/about?x=1", [])).toBe(true);
+ });
+
+ test("returns true when path-only source redirects to the same path with relative query", () => {
+ expect(wouldCreateLoop("/about", "?x=1", [])).toBe(true);
+ });
+
+ test("returns true when source redirects to itself through relative target", () => {
+ expect(wouldCreateLoop("/about", "about", [])).toBe(true);
+ });
+
+ test("returns true for encoded and decoded variants of the same path", () => {
+ expect(wouldCreateLoop("/%C3%BCber", "/über", [])).toBe(true);
+ expect(wouldCreateLoop("/über", "/%C3%BCber", [])).toBe(true);
+ });
+
+ test("returns true for matching exact query redirect", () => {
+ expect(wouldCreateLoop("/about?x=1", "/about?x=1", [])).toBe(true);
+ });
+
+ test("returns false for different exact query redirect", () => {
+ expect(wouldCreateLoop("/about?x=1", "/about?x=2", [])).toBe(false);
+ });
+
+ test("returns true when dynamic source matches the target path", () => {
+ expect(wouldCreateLoop("/blog/:slug", "/blog/post", [])).toBe(true);
+ });
+
+ test("returns true when wildcard source matches the target path", () => {
+ expect(wouldCreateLoop("/docs/*", "/docs/api/reference", [])).toBe(true);
+ });
+
+ test("returns true when optional static source matches the target path", () => {
+ expect(wouldCreateLoop("/en?/about", "/en/about", [])).toBe(true);
+ });
});
describe("direct loop detection (A → B → A)", () => {
@@ -30,6 +75,63 @@ describe("wouldCreateLoop", () => {
];
expect(wouldCreateLoop("/a", "/b", existing)).toBe(false);
});
+
+ test("returns true when target redirects back to source without fragments", () => {
+ const existing: PageRedirect[] = [
+ { old: "/b#section", new: "/a#target", status: "301" },
+ ];
+ expect(wouldCreateLoop("/a#source", "/b#target", existing)).toBe(true);
+ });
+
+ test("returns true when existing path-only redirect matches target query string", () => {
+ const existing: PageRedirect[] = [
+ { old: "/b", new: "/a", status: "301" },
+ ];
+ expect(wouldCreateLoop("/a", "/b?x=1", existing)).toBe(true);
+ });
+
+ test("returns true when existing redirect source is an encoded path variant", () => {
+ const existing: PageRedirect[] = [
+ { old: "/%C3%BCber", new: "/a", status: "301" },
+ ];
+ expect(wouldCreateLoop("/a", "/über", existing)).toBe(true);
+ });
+
+ test("returns true when existing dynamic redirect matches target path", () => {
+ const existing: PageRedirect[] = [
+ { old: "/blog/:slug", new: "/a", status: "301" },
+ ];
+ expect(wouldCreateLoop("/a", "/blog/post", existing)).toBe(true);
+ });
+
+ test("returns true when existing optional static redirect matches target path", () => {
+ const existing: PageRedirect[] = [
+ { old: "/en?/about", new: "/a", status: "301" },
+ ];
+ expect(wouldCreateLoop("/a", "/en/about", existing)).toBe(true);
+ });
+
+ test("returns true when relative target resolves to an existing redirect source", () => {
+ const existing: PageRedirect[] = [
+ { old: "/new", new: "/old", status: "301" },
+ ];
+ expect(wouldCreateLoop("/old", "new", existing)).toBe(true);
+ });
+
+ test("returns true when nested relative target resolves to an existing redirect source", () => {
+ const existing: PageRedirect[] = [
+ { old: "/old/new", new: "/old/", status: "301" },
+ ];
+ expect(wouldCreateLoop("/old/", "new", existing)).toBe(true);
+ });
+
+ test("follows the first matching existing redirect like the published runtime", () => {
+ const existing: PageRedirect[] = [
+ { old: "/b", new: "/c", status: "301" },
+ { old: "/b", new: "/a", status: "301" },
+ ];
+ expect(wouldCreateLoop("/a", "/b", existing)).toBe(false);
+ });
});
describe("chain loop detection (A → B → C → A)", () => {
@@ -82,6 +184,11 @@ describe("wouldCreateLoop", () => {
test("returns false for protocol-relative URL target", () => {
expect(wouldCreateLoop("/a", "//example.com/b", [])).toBe(false);
});
+
+ test("returns false for non-path URL targets handled externally by runtime", () => {
+ expect(wouldCreateLoop("/a", "mailto:[email protected]", [])).toBe(false);
+ expect(wouldCreateLoop("/a", "#section", [])).toBe(false);
+ });
});
describe("edge cases", () => {
diff --git a/apps/builder/app/shared/redirects/redirect-loop-detection.ts b/apps/builder/app/shared/redirects/redirect-loop-detection.ts
index 7992ddfbac..968229c203 100644
--- a/apps/builder/app/shared/redirects/redirect-loop-detection.ts
+++ b/apps/builder/app/shared/redirects/redirect-loop-detection.ts
@@ -1,7 +1,60 @@
import type { PageRedirect } from "@webstudio-is/sdk";
+import {
+ doesRedirectSourceMatchUrl,
+ getRedirectSourcePathname,
+ getRedirectSourceSearchIndex,
+ isRedirectSourcePattern,
+ normalizeRedirectSource,
+} from "./redirect-source";
+import { matchPath } from "@remix-run/react";
export const LOOP_ERROR = "This redirect would create a loop";
+const isExternalTarget = (path: string) => {
+ return /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(path) || path.startsWith("//");
+};
+
+const resolveLocalTarget = (source: string, target: string) => {
+ if (isExternalTarget(target) || target.startsWith("#")) {
+ return;
+ }
+
+ if (target.startsWith("/")) {
+ return normalizeRedirectSource(target);
+ }
+
+ try {
+ const resolved = new URL(
+ target,
+ `https://example.com${getRedirectSourcePathname(source)}`
+ );
+ return normalizeRedirectSource(`${resolved.pathname}${resolved.search}`);
+ } catch {
+ return;
+ }
+};
+
+const doesRedirectSourceMatchLocalUrl = (source: string, url: string) => {
+ const normalizedSource = normalizeRedirectSource(source);
+ const normalizedUrl = normalizeRedirectSource(url);
+ if (getRedirectSourceSearchIndex(normalizedSource) !== -1) {
+ return normalizedSource === normalizedUrl;
+ }
+ if (isRedirectSourcePattern(normalizedSource) === false) {
+ return doesRedirectSourceMatchUrl(normalizedSource, normalizedUrl);
+ }
+ return (
+ matchPath(
+ {
+ path: normalizedSource,
+ caseSensitive: true,
+ end: true,
+ },
+ getRedirectSourcePathname(normalizedUrl)
+ ) !== null
+ );
+};
+
/**
* Checks if adding a redirect from `fromPath` to `toPath` would create a loop
* given the existing redirects.
@@ -13,33 +66,36 @@ export const wouldCreateLoop = (
toPath: string,
existingRedirects: PageRedirect[]
): boolean => {
- // Self-redirect is always a loop
- if (fromPath === toPath) {
- return true;
- }
+ const source = normalizeRedirectSource(fromPath);
+ const target = resolveLocalTarget(source, toPath);
// External URLs can't create loops (they leave the site)
- if (
- toPath.startsWith("http://") ||
- toPath.startsWith("https://") ||
- toPath.startsWith("//")
- ) {
+ if (target === undefined) {
return false;
}
- // Build a map for O(1) lookup
- const redirectMap = new Map<string, string>();
- for (const redirect of existingRedirects) {
- redirectMap.set(redirect.old, redirect.new);
+ // Self-redirect is always a loop
+ if (doesRedirectSourceMatchLocalUrl(source, target)) {
+ return true;
}
+ // Keep normalized sources so exact-query and path-only matching can follow
+ // the same semantics as the published runtime.
+ const redirectEntries = existingRedirects.map((redirect) => {
+ const redirectSource = normalizeRedirectSource(redirect.old);
+ return {
+ source: redirectSource,
+ target: resolveLocalTarget(redirectSource, redirect.new),
+ };
+ });
+
// Follow the chain from toPath and check if we reach fromPath
- const visited = new Set<string>([fromPath]);
- let current = toPath;
+ const visited = new Set<string>([source]);
+ let current = target;
while (current) {
// Found a loop back to the source
- if (current === fromPath) {
+ if (doesRedirectSourceMatchLocalUrl(source, current)) {
return true;
}
@@ -51,21 +107,18 @@ export const wouldCreateLoop = (
visited.add(current);
// Get next hop
- const next = redirectMap.get(current);
+ let next: string | undefined;
+ for (const redirect of redirectEntries) {
+ if (doesRedirectSourceMatchLocalUrl(redirect.source, current)) {
+ next = redirect.target;
+ break;
+ }
+ }
if (!next) {
// Chain ends without looping back
return false;
}
- // External URL ends the chain
- if (
- next.startsWith("http://") ||
- next.startsWith("https://") ||
- next.startsWith("//")
- ) {
- return false;
- }
-
current = next;
}
diff --git a/apps/builder/app/shared/redirects/redirect-parsers.test.ts b/apps/builder/app/shared/redirects/redirect-parsers.test.ts
index 54deea31ea..35ba1fe92c 100644
--- a/apps/builder/app/shared/redirects/redirect-parsers.test.ts
+++ b/apps/builder/app/shared/redirects/redirect-parsers.test.ts
@@ -158,7 +158,7 @@ invalid-no-slash,/new,301
expect(result.skipped).toHaveLength(1);
expect(result.skipped[0]).toMatchObject({
line: 3,
- reason: expect.stringContaining("source"),
+ reason: expect.stringContaining("Must start with a /"),
});
});
@@ -329,18 +329,21 @@ invalid-no-slash,/new,301
expect(result.skipped[0].reason).toContain("condition");
});
- test("skips JSON redirects with placeholders in source (unsupported)", () => {
+ test("parses Webstudio dynamic route patterns", () => {
const input = `[
{ "source": "/simple", "target": "/target", "status": 301 },
{ "source": "/blog/:slug", "target": "/posts/:slug", "status": 301 },
- { "source": "/docs/:path*", "target": "/documentation/:path*", "status": 301 }
+ { "source": "/docs/*", "target": "/documentation/*", "status": 301 }
]`;
const result = parseRedirects(input);
- expect(result.redirects).toHaveLength(1);
- expect(result.skipped).toHaveLength(2);
- expect(result.skipped[0].reason).toContain("placeholder");
+ expect(result.redirects).toEqual([
+ { old: "/simple", new: "/target", status: 301 },
+ { old: "/blog/:slug", new: "/posts/:slug", status: 301 },
+ { old: "/docs/*", new: "/documentation/*", status: 301 },
+ ]);
+ expect(result.skipped).toEqual([]);
});
});
@@ -367,16 +370,70 @@ invalid-no-slash,/new,301
]);
});
- test("skips splat redirects (unsupported)", () => {
+ test("parses splat redirects", () => {
const input = `/simple /target 301
/blog/* /articles/:splat 301
/other /other-target`;
const result = parseRedirects(input);
- expect(result.redirects).toHaveLength(2);
+ expect(result.redirects).toEqual([
+ { old: "/simple", new: "/target", status: 301 },
+ { old: "/blog/*", new: "/articles/*", status: 301 },
+ { old: "/other", new: "/other-target", status: 301 },
+ ]);
+ expect(result.skipped).toEqual([]);
+ });
+
+ test("rewrites Netlify splat params only in local target pathnames", () => {
+ const input = `/blog/* /articles/:splat?from=:splat 301
+/docs/* /documentation/:splat#section-:splat 301
+/files/* /downloads/:splat 301`;
+
+ const result = parseRedirects(input);
+
+ expect(result.redirects).toEqual([
+ { old: "/files/*", new: "/downloads/*", status: 301 },
+ ]);
+ expect(result.skipped).toHaveLength(2);
+ expect(result.skipped[0].reason).toContain(
+ "unsupported target route parameter syntax"
+ );
+ expect(result.skipped[1].reason).toContain(
+ "unsupported target route parameter syntax"
+ );
+ });
+
+ test("does not rewrite splat params in external targets", () => {
+ const input = `/blog/* https://cdn.example.com/:splat 301
+/assets/* //cdn.example.com/:splat 301`;
+
+ const result = parseRedirects(input);
+
+ expect(result.redirects).toEqual([
+ {
+ old: "/blog/*",
+ new: "https://cdn.example.com/:splat",
+ status: 301,
+ },
+ { old: "/assets/*", new: "//cdn.example.com/:splat", status: 301 },
+ ]);
+ expect(result.skipped).toEqual([]);
+ });
+
+ test("skips named splat sources that do not match Webstudio syntax", () => {
+ const input = `/simple /target 301
+/docs/:path* /documentation/* 301
+/other /other-target`;
+
+ const result = parseRedirects(input);
+
+ expect(result.redirects).toEqual([
+ { old: "/simple", new: "/target", status: 301 },
+ { old: "/other", new: "/other-target", status: 301 },
+ ]);
expect(result.skipped).toHaveLength(1);
- expect(result.skipped[0].reason).toContain("wildcard");
+ expect(result.skipped[0].reason).toContain("named splat");
});
test("ignores comment lines", () => {
@@ -461,16 +518,119 @@ invalid-no-slash,/new,301
]);
});
- test("skips redirects with placeholders (unsupported)", () => {
+ test("parses dynamic segment redirects", () => {
+ const input = `/simple /target 301
+/blog/:year/:slug /posts/:year/:slug 301
+/other /other-target`;
+
+ const result = parseRedirects(input);
+
+ expect(result.redirects).toEqual([
+ { old: "/simple", new: "/target", status: 301 },
+ { old: "/blog/:year/:slug", new: "/posts/:year/:slug", status: 301 },
+ { old: "/other", new: "/other-target", status: 301 },
+ ]);
+ expect(result.skipped).toEqual([]);
+ });
+
+ test("skips local targets with unsupported composite route params", () => {
const input = `/simple /target 301
/blog/:year/:slug /posts/:year-:slug 301
/other /other-target`;
const result = parseRedirects(input);
- expect(result.redirects).toHaveLength(2);
+ expect(result.redirects).toEqual([
+ { old: "/simple", new: "/target", status: 301 },
+ { old: "/other", new: "/other-target", status: 301 },
+ ]);
+ expect(result.skipped).toHaveLength(1);
+ expect(result.skipped[0].reason).toContain(
+ "unsupported target route parameter syntax"
+ );
+ });
+
+ test("skips relative targets with unsupported composite route params", () => {
+ const input = `/blog/:year/:slug posts/:year-:slug 301`;
+
+ const result = parseRedirects(input);
+
+ expect(result.redirects).toEqual([]);
+ expect(result.skipped).toHaveLength(1);
+ expect(result.skipped[0].reason).toContain(
+ "unsupported target route parameter syntax"
+ );
+ });
+
+ test("skips target params embedded inside otherwise static segments", () => {
+ const input = `/blog/:slug /posts/post-:slug 301`;
+
+ const result = parseRedirects(input);
+
+ expect(result.redirects).toEqual([]);
expect(result.skipped).toHaveLength(1);
- expect(result.skipped[0].reason).toContain("placeholder");
+ expect(result.skipped[0].reason).toContain(
+ "unsupported target route parameter syntax"
+ );
+ });
+
+ test("skips target params in search strings because runtime does not expand them", () => {
+ const input = `/blog/:slug /posts?slug=:slug 301
+/query ?slug=:slug 301`;
+
+ const result = parseRedirects(input);
+
+ expect(result.redirects).toEqual([]);
+ expect(result.skipped).toHaveLength(2);
+ expect(result.skipped[0].reason).toContain(
+ "unsupported target route parameter syntax"
+ );
+ expect(result.skipped[1].reason).toContain(
+ "unsupported target route parameter syntax"
+ );
+ });
+
+ test("skips target params when source has an exact query string", () => {
+ const input = `/blog/:slug?preview=1 /posts/:slug 301
+/docs/*?preview=1 /reference/* 301`;
+
+ const result = parseRedirects(input);
+
+ expect(result.redirects).toEqual([]);
+ expect(result.skipped).toHaveLength(2);
+ expect(result.skipped[0].reason).toContain(
+ "unsupported target route parameter syntax"
+ );
+ expect(result.skipped[1].reason).toContain(
+ "unsupported target route parameter syntax"
+ );
+ });
+
+ test("skips target params not provided by source patterns", () => {
+ const input = `/old /posts/:slug 301
+/blog/:slug /posts/:missing 301
+/docs /reference/* 301`;
+
+ const result = parseRedirects(input);
+
+ expect(result.redirects).toEqual([]);
+ expect(result.skipped).toHaveLength(3);
+ for (const skipped of result.skipped) {
+ expect(skipped.reason).toContain(
+ "unsupported target route parameter syntax"
+ );
+ }
+ });
+
+ test("allows literal colon targets that are not route params", () => {
+ const input = `/old /time/12:30?at=12:30 301`;
+
+ const result = parseRedirects(input);
+
+ expect(result.redirects).toEqual([
+ { old: "/old", new: "/time/12:30?at=12:30", status: 301 },
+ ]);
+ expect(result.skipped).toEqual([]);
});
test("skips redirects with query parameter matching (unsupported)", () => {
@@ -787,19 +947,18 @@ REDIRECT 301 /about /about-us`;
]);
});
- test("handles root path redirect", () => {
+ test("skips root path redirect sources", () => {
const input = `source,target,status
/,/home,301`;
const result = parseRedirects(input);
- expect(result.redirects).toEqual([
- { old: "/", new: "/home", status: 301 },
- ]);
+ expect(result.redirects).toEqual([]);
+ expect(result.skipped).toHaveLength(1);
+ expect(result.skipped[0].reason).toContain("Can't be just a /");
});
- test("strips trailing slashes from source paths", () => {
- // Webstudio requires: paths cannot end with /
+ test("preserves trailing slashes in source paths", () => {
const input = `source,target,status
/old/,/new/,301
/about,/about-us/,301`;
@@ -807,7 +966,7 @@ REDIRECT 301 /about /about-us`;
const result = parseRedirects(input);
expect(result.redirects).toEqual([
- { old: "/old", new: "/new/", status: 301 },
+ { old: "/old/", new: "/new/", status: 301 },
{ old: "/about", new: "/about-us/", status: 301 },
]);
});
@@ -851,9 +1010,8 @@ REDIRECT 301 /about /about-us`;
const result = parseRedirects(content);
- // Should parse simple redirects and skip ones with placeholders/conditions
+ // Should parse supported redirects and skip conditional/advanced rules.
expect(result.redirects.length).toBeGreaterThan(0);
- // Some should be skipped due to placeholders and conditions
expect(result.skipped.length).toBeGreaterThan(0);
});
@@ -865,9 +1023,9 @@ REDIRECT 301 /about /about-us`;
const result = parseRedirects(content);
- // Should parse simple redirects
+ // Should parse supported redirects.
expect(result.redirects.length).toBeGreaterThan(0);
- // Many should be skipped: conditions, placeholders, rewrites
+ // Some rules are skipped: conditions, rewrites, and query matching.
expect(result.skipped.length).toBeGreaterThan(0);
});
@@ -1123,15 +1281,15 @@ Redirect 301 /old /new`;
});
// Path validation edge cases
- test("skips paths with double slashes", () => {
+ test("skips protocol-relative sources with double leading slashes", () => {
const input = `source,target,status
//double-slash,/new,301`;
const result = parseRedirects(input);
- // Double slash still starts with /, so it passes basic validation
- // Webstudio's OldPagePath schema will reject it later
- expect(result.redirects).toHaveLength(1);
+ expect(result.redirects).toHaveLength(0);
+ expect(result.skipped).toHaveLength(1);
+ expect(result.skipped[0].reason).toContain("Must start with a /");
});
test("handles http URLs as source (invalid)", () => {
@@ -1142,9 +1300,7 @@ https://example.com/old,/new,301`;
expect(result.redirects).toHaveLength(0);
expect(result.skipped).toHaveLength(1);
- expect(result.skipped[0].reason).toContain(
- "source path must start with /"
- );
+ expect(result.skipped[0].reason).toContain("Must start with a /");
});
test("handles protocol-relative URLs as target", () => {
@@ -1237,15 +1393,58 @@ ${longPath},/new,301`;
expect(result.redirects).toHaveLength(1);
});
- test("skips asterisk in path segment", () => {
+ test("allows literal asterisk in path segment", () => {
const input = `source,target,status
/files/*.txt,/all-files,301`;
const result = parseRedirects(input);
- expect(result.redirects).toHaveLength(0);
+ expect(result.redirects).toEqual([
+ { old: "/files/*.txt", new: "/all-files", status: 301 },
+ ]);
+ expect(result.skipped).toEqual([]);
+ });
+
+ test("skips sources reserved for system routes", () => {
+ const input = `source,target,status
+/s/image,/new,301
+/build/main.js,/new,301`;
+
+ const result = parseRedirects(input);
+
+ expect(result.redirects).toEqual([]);
+ expect(result.skipped).toHaveLength(2);
+ expect(result.skipped[0].reason).toContain(
+ "/s prefix is reserved for the system"
+ );
+ expect(result.skipped[1].reason).toContain(
+ "/build prefix is reserved for the system"
+ );
+ });
+
+ test("accepts relative targets allowed by ProjectNewRedirectPath", () => {
+ const input = `source,target,status
+/old,new,301
+/query,?preview=1,302`;
+
+ const result = parseRedirects(input);
+
+ expect(result.redirects).toEqual([
+ { old: "/old", new: "new", status: 301 },
+ { old: "/query", new: "?preview=1", status: 302 },
+ ]);
+ expect(result.skipped).toEqual([]);
+ });
+
+ test("skips invalid targets with ProjectNewRedirectPath validation", () => {
+ const input = `source,target,status
+/old,http://[invalid,301`;
+
+ const result = parseRedirects(input);
+
+ expect(result.redirects).toEqual([]);
expect(result.skipped).toHaveLength(1);
- expect(result.skipped[0].reason).toContain("wildcard");
+ expect(result.skipped[0].reason).toContain("Must be a valid URL");
});
});
});
diff --git a/apps/builder/app/shared/redirects/redirect-parsers.ts b/apps/builder/app/shared/redirects/redirect-parsers.ts
index 339fa2f1da..6d9543c474 100644
--- a/apps/builder/app/shared/redirects/redirect-parsers.ts
+++ b/apps/builder/app/shared/redirects/redirect-parsers.ts
@@ -1,4 +1,10 @@
import Papa from "papaparse";
+import { ProjectNewRedirectPath, RedirectSourcePath } from "@webstudio-is/sdk";
+import {
+ getRedirectSourceSearchIndex,
+ hasInvalidLocalTargetParams,
+ hasNamedSplat,
+} from "./redirect-source";
export type ParsedRedirect = {
old: string;
@@ -136,22 +142,33 @@ const detectFormat = (
return "csv"; // fallback
};
-/**
- * Check if a path contains unsupported patterns
- */
-const hasPlaceholder = (path: string): boolean => {
- // :param placeholders like /blog/:slug
- return /:[a-zA-Z_][a-zA-Z0-9_]*\*?/.test(path);
+const hasConditions = (record: RawRecord): boolean => {
+ return "has" in record || "missing" in record;
};
-const hasWildcard = (path: string): boolean => {
- // * wildcards but not in query string
- const pathPart = path.split("?")[0];
- return pathPart.includes("*");
+const normalizeNetlifyTarget = (from: string, to: string) => {
+ if (
+ getRedirectSourceSearchIndex(from) !== -1 ||
+ from.split("/").includes("*") === false ||
+ /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(to) ||
+ to.startsWith("//")
+ ) {
+ return to;
+ }
+
+ const searchOrHashIndex = to.search(/[?#]/);
+ if (searchOrHashIndex === -1) {
+ return to.replaceAll(":splat", "*");
+ }
+ const pathname = to.slice(0, searchOrHashIndex);
+ const searchAndHash = to.slice(searchOrHashIndex);
+ return `${pathname.replaceAll(":splat", "*")}${searchAndHash}`;
};
-const hasConditions = (record: RawRecord): boolean => {
- return "has" in record || "missing" in record;
+const formatSchemaError = (result: {
+ error: { issues: { message: string }[] };
+}) => {
+ return result.error.issues.map((issue) => issue.message).join(", ");
};
/**
@@ -230,16 +247,7 @@ const findValue = (record: RawRecord, keys: readonly string[]): unknown => {
return undefined;
};
-/**
- * Normalize a path - strip trailing slashes from source paths
- */
-const normalizePath = (path: string, isSource: boolean): string => {
- let normalized = path.trim();
- if (isSource && normalized.length > 1 && normalized.endsWith("/")) {
- normalized = normalized.slice(0, -1);
- }
- return normalized;
-};
+const normalizePath = (path: string): string => path.trim();
/**
* Validate and normalize a single record into a redirect
@@ -286,48 +294,49 @@ const normalizeRecord = (
}
const to = String(toValue);
- // Check for wildcards in source
- if (hasWildcard(from)) {
+ const normalizedFrom = normalizePath(from);
+ const normalizedTo = normalizePath(to);
+
+ // Validate source path
+ const sourceValidationResult = RedirectSourcePath.safeParse(normalizedFrom);
+ if (sourceValidationResult.success === false) {
return {
skipped: {
line: lineNumber,
content: originalContent,
- reason: "contains wildcard (*) - not supported",
+ reason: formatSchemaError(sourceValidationResult),
},
};
}
- // Check for placeholders in source or target
- if (hasPlaceholder(from) || hasPlaceholder(to)) {
+ if (hasNamedSplat(normalizedFrom)) {
return {
skipped: {
line: lineNumber,
content: originalContent,
- reason: "contains placeholder (:param) - not supported",
+ reason: "contains named splat (:name*) - use * instead",
},
};
}
- // Validate source path
- const normalizedFrom = normalizePath(from, true);
- if (!normalizedFrom.startsWith("/")) {
+ if (hasInvalidLocalTargetParams(normalizedTo, normalizedFrom)) {
return {
skipped: {
line: lineNumber,
content: originalContent,
- reason: "source path must start with /",
+ reason: "contains unsupported target route parameter syntax",
},
};
}
// Validate target path
- const normalizedTo = normalizePath(to, false);
- if (!normalizedTo.startsWith("/") && !normalizedTo.startsWith("http")) {
+ const targetValidationResult = ProjectNewRedirectPath.safeParse(normalizedTo);
+ if (targetValidationResult.success === false) {
return {
skipped: {
line: lineNumber,
content: originalContent,
- reason: "target path must start with / or http",
+ reason: formatSchemaError(targetValidationResult),
},
};
}
@@ -550,7 +559,7 @@ const parseNetlify = (content: string): ParseResult => {
}
const from = parts[0];
- const to = parts[1];
+ const to = normalizeNetlifyTarget(from, parts[1]);
const statusPart = parts[2];
const rest = parts.slice(3).join(" ");
@@ -564,8 +573,15 @@ const parseNetlify = (content: string): ParseResult => {
continue;
}
- // Check for query parameter matching (e.g., /store id=:id)
- if (to.includes("=") && !to.startsWith("http")) {
+ // Check for query parameter matching (e.g., /store id=:id /products/:id).
+ // A normal target may also contain "=" in its query string.
+ if (
+ to.includes("=") &&
+ to.startsWith("/") === false &&
+ to.startsWith("?") === false &&
+ /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(to) === false &&
+ to.startsWith("//") === false
+ ) {
// This might be query matching like "/store id=:id /products/:id"
// Re-parse: /source query=value /target
skipped.push({
diff --git a/apps/builder/app/shared/redirects/redirect-source.test.ts b/apps/builder/app/shared/redirects/redirect-source.test.ts
new file mode 100644
index 0000000000..ab23525b6b
--- /dev/null
+++ b/apps/builder/app/shared/redirects/redirect-source.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, test } from "vitest";
+import {
+ doesRedirectSourceMatchUrl,
+ getRedirectSourcePathname,
+ getRedirectSourceSearchIndex,
+ hasInvalidLocalTargetParams,
+ hasNamedSplat,
+ isRedirectSourcePattern,
+ normalizeRedirectSource,
+ stripRedirectSourceFragment,
+} from "./redirect-source";
+
+describe("redirect source helpers", () => {
+ test("strips source fragments", () => {
+ expect(stripRedirectSourceFragment("/old#section")).toBe("/old");
+ expect(stripRedirectSourceFragment("/old?x=1#section")).toBe("/old?x=1");
+ });
+
+ test("normalizes encoded pathname variants without changing search", () => {
+ expect(normalizeRedirectSource("/%C3%BCber?x=a%20b")).toBe("/über?x=a%20b");
+ expect(normalizeRedirectSource("/path%20with%20spaces?x=a+b")).toBe(
+ "/path with spaces?x=a+b"
+ );
+ });
+
+ test("does not decode encoded slashes into path separators", () => {
+ expect(normalizeRedirectSource("/file%2Fname")).toBe("/file%2Fname");
+ });
+
+ test("keeps malformed percent escapes unchanged", () => {
+ expect(normalizeRedirectSource("/%E0%A4%A")).toBe("/%E0%A4%A");
+ });
+
+ test("gets normalized pathname without search", () => {
+ expect(getRedirectSourcePathname("/%C3%BCber?x=1")).toBe("/über");
+ });
+
+ test("distinguishes optional path segments from query delimiters", () => {
+ expect(getRedirectSourceSearchIndex("/blog/:slug?")).toBe(-1);
+ expect(getRedirectSourceSearchIndex("/blog/:slug?/comments")).toBe(-1);
+ expect(getRedirectSourceSearchIndex("/en?/about")).toBe(-1);
+ expect(getRedirectSourceSearchIndex("/one?/:two?/three")).toBe(-1);
+ expect(getRedirectSourceSearchIndex("/blog/:slug?preview=1")).toBe(11);
+ expect(getRedirectSourceSearchIndex("/old?x=1")).toBe(4);
+ });
+
+ test("matches path-only sources against requests with query strings", () => {
+ expect(doesRedirectSourceMatchUrl("/old", "/old?x=1")).toBe(true);
+ });
+
+ test("matches query-specific sources exactly", () => {
+ expect(doesRedirectSourceMatchUrl("/old?x=1", "/old?x=1")).toBe(true);
+ expect(doesRedirectSourceMatchUrl("/old?x=1", "/old?x=2")).toBe(false);
+ expect(doesRedirectSourceMatchUrl("/old?x=1", "/old")).toBe(false);
+ });
+
+ test("matches encoded and decoded pathname spellings", () => {
+ expect(doesRedirectSourceMatchUrl("/über", "/%C3%BCber")).toBe(true);
+ expect(doesRedirectSourceMatchUrl("/%C3%BCber", "/über")).toBe(true);
+ });
+
+ test("detects redirect route patterns", () => {
+ expect(isRedirectSourcePattern("/blog/:slug")).toBe(true);
+ expect(isRedirectSourcePattern("/docs/*")).toBe(true);
+ expect(isRedirectSourcePattern("/en?/about")).toBe(true);
+ expect(isRedirectSourcePattern("/time/12:30")).toBe(false);
+ expect(isRedirectSourcePattern("/file*name")).toBe(false);
+ });
+
+ test("detects named splats that are not supported for new redirect inputs", () => {
+ expect(hasNamedSplat("/docs/:path*")).toBe(true);
+ expect(hasNamedSplat("/docs/:path*/edit")).toBe(true);
+ expect(hasNamedSplat("/docs/*")).toBe(false);
+ expect(hasNamedSplat("/blog/:slug")).toBe(false);
+ expect(hasNamedSplat("/file*name")).toBe(false);
+ });
+
+ test("detects unsupported local target param syntax", () => {
+ expect(hasInvalidLocalTargetParams("/posts/:slug")).toBe(false);
+ expect(hasInvalidLocalTargetParams("/posts/:year-:slug")).toBe(true);
+ expect(hasInvalidLocalTargetParams("/posts?slug=:slug")).toBe(true);
+ expect(hasInvalidLocalTargetParams("/time/12:30")).toBe(false);
+ expect(hasInvalidLocalTargetParams("https://example.com/:slug")).toBe(
+ false
+ );
+ });
+
+ test("detects target params not provided by source patterns", () => {
+ expect(hasInvalidLocalTargetParams("/posts/:slug", "/blog/:slug")).toBe(
+ false
+ );
+ expect(hasInvalidLocalTargetParams("/reference/*", "/docs/*")).toBe(false);
+ expect(hasInvalidLocalTargetParams("/posts/:slug", "/old")).toBe(true);
+ expect(hasInvalidLocalTargetParams("/posts/:slug", "/blog?x=1")).toBe(true);
+ expect(hasInvalidLocalTargetParams("/posts/:missing", "/blog/:slug")).toBe(
+ true
+ );
+ expect(
+ hasInvalidLocalTargetParams("https://example.com/:missing", "/blog/:slug")
+ ).toBe(false);
+ });
+});
diff --git a/apps/builder/app/shared/redirects/redirect-source.ts b/apps/builder/app/shared/redirects/redirect-source.ts
new file mode 100644
index 0000000000..440e6c03bc
--- /dev/null
+++ b/apps/builder/app/shared/redirects/redirect-source.ts
@@ -0,0 +1,151 @@
+const isOptionalSegmentMarker = (source: string, index: number) => {
+ const nextChar = source[index + 1];
+ if (nextChar !== undefined && nextChar !== "/") {
+ return false;
+ }
+
+ const segmentStart = source.lastIndexOf("/", index - 1);
+ const segment = source.slice(segmentStart + 1, index);
+ return segment !== "";
+};
+
+export const getRedirectSourceSearchIndex = (source: string) => {
+ for (let index = 0; index < source.length; index += 1) {
+ if (
+ source[index] === "?" &&
+ isOptionalSegmentMarker(source, index) === false
+ ) {
+ return index;
+ }
+ }
+ return -1;
+};
+
+const stripSearch = (path: string) => {
+ const searchIndex = getRedirectSourceSearchIndex(path);
+ return searchIndex === -1 ? path : path.slice(0, searchIndex);
+};
+
+const safeDecodePathname = (pathname: string) => {
+ try {
+ return decodeURI(pathname);
+ } catch {
+ return pathname;
+ }
+};
+
+export const stripRedirectSourceFragment = (source: string) => {
+ const hashIndex = source.indexOf("#");
+ return hashIndex === -1 ? source : source.slice(0, hashIndex);
+};
+
+export const normalizeRedirectSource = (source: string) => {
+ const sourceWithoutFragment = stripRedirectSourceFragment(source);
+ const searchIndex = getRedirectSourceSearchIndex(sourceWithoutFragment);
+ if (searchIndex === -1) {
+ return safeDecodePathname(sourceWithoutFragment);
+ }
+ const pathname = sourceWithoutFragment.slice(0, searchIndex);
+ const search = sourceWithoutFragment.slice(searchIndex);
+ return `${safeDecodePathname(pathname)}${search}`;
+};
+
+export const getRedirectSourcePathname = (source: string) => {
+ return stripSearch(normalizeRedirectSource(source));
+};
+
+export const isRedirectSourcePattern = (source: string) => {
+ return (
+ /(^|\/):[^/]+/.test(source) ||
+ /(^|\/)\*(?=\/|$)/.test(source) ||
+ /(^|\/)[^/]+\?(?=\/|$)/.test(source)
+ );
+};
+
+export const hasNamedSplat = (source: string) => {
+ return /(^|\/):[^/?#/*]+\*(?=\/|[?#]|$)/.test(source);
+};
+
+const isExternalOrNonPathTarget = (target: string) => {
+ return (
+ /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(target) ||
+ target.startsWith("//") ||
+ target.startsWith("#")
+ );
+};
+
+const getPathParamNames = (pathname: string) => {
+ const names = new Set<string>();
+ for (const segment of pathname.split("/")) {
+ if (segment === "*") {
+ names.add("*");
+ continue;
+ }
+ const match = segment.match(/^:([a-zA-Z_][a-zA-Z0-9_]*)\??$/);
+ if (match) {
+ names.add(match[1]);
+ }
+ }
+ return names;
+};
+
+const getRedirectSourcePathParamNames = (source: string) => {
+ const normalizedSource = normalizeRedirectSource(source);
+ if (getRedirectSourceSearchIndex(normalizedSource) !== -1) {
+ return new Set<string>();
+ }
+ return getPathParamNames(getRedirectSourcePathname(normalizedSource));
+};
+
+const paramLikePattern = /:[a-zA-Z_][a-zA-Z0-9_]*/;
+const pathParamPattern = /^:([a-zA-Z_][a-zA-Z0-9_]*)\??$/;
+
+export const hasInvalidLocalTargetParams = (
+ target: string,
+ source?: string
+) => {
+ if (isExternalOrNonPathTarget(target)) {
+ return false;
+ }
+
+ const searchOrHashIndex = target.search(/[?#]/);
+ if (
+ searchOrHashIndex !== -1 &&
+ paramLikePattern.test(target.slice(searchOrHashIndex))
+ ) {
+ return true;
+ }
+
+ const sourceParamNames =
+ source === undefined ? undefined : getRedirectSourcePathParamNames(source);
+ const pathname = target.split(/[?#]/, 1)[0];
+ return pathname.split("/").some((segment) => {
+ let targetParamName: string | undefined;
+ if (segment === "*") {
+ targetParamName = "*";
+ } else {
+ const match = segment.match(pathParamPattern);
+ if (match) {
+ targetParamName = match[1];
+ } else {
+ return paramLikePattern.test(segment);
+ }
+ }
+
+ return (
+ sourceParamNames !== undefined &&
+ sourceParamNames.has(targetParamName) === false
+ );
+ });
+};
+
+export const doesRedirectSourceMatchUrl = (source: string, url: string) => {
+ const normalizedSource = normalizeRedirectSource(source);
+ const normalizedUrl = normalizeRedirectSource(url);
+
+ if (getRedirectSourceSearchIndex(normalizedSource) !== -1) {
+ return normalizedSource === normalizedUrl;
+ }
+
+ return normalizedSource === stripSearch(normalizedUrl);
+};
diff --git a/fixtures/react-router-cloudflare/app/__generated__/$resources.redirects.ts b/fixtures/react-router-cloudflare/app/__generated__/$resources.redirects.ts
new file mode 100644
index 0000000000..a3ee44bd02
--- /dev/null
+++ b/fixtures/react-router-cloudflare/app/__generated__/$resources.redirects.ts
@@ -0,0 +1 @@
+export const redirects = [];
diff --git a/fixtures/react-router-cloudflare/app/redirect-url.ts b/fixtures/react-router-cloudflare/app/redirect-url.ts
index 1e717eaa73..0e9e45efde 100644
--- a/fixtures/react-router-cloudflare/app/redirect-url.ts
+++ b/fixtures/react-router-cloudflare/app/redirect-url.ts
@@ -1,4 +1,21 @@
-import { createPath, generatePath, parsePath } from "react-router";
+import {
+ createPath,
+ generatePath,
+ matchPath,
+ parsePath,
+ redirect,
+} from "react-router";
+
+type RedirectItem = {
+ old: string;
+ new: string;
+ status?: number | string;
+};
+
+type MatchedRedirect = {
+ url: string;
+ status: number;
+};
/**
* Expands route params in local redirect targets.
@@ -9,13 +26,142 @@ export const generateRedirectUrl = (
url: string,
params: Record<string, string | undefined>
) => {
- if (url.startsWith("/") === false || url.startsWith("//")) {
+ if (
+ /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(url) ||
+ url.startsWith("//") ||
+ url.startsWith("?") ||
+ url.startsWith("#")
+ ) {
return url;
}
+ const targetParams = Object.fromEntries(
+ Object.entries(params).map(([name, value]) => [
+ name,
+ name === "*" ? value : value?.replaceAll("/", "%2F"),
+ ])
+ );
const path = parsePath(url);
- return createPath({
- ...path,
- pathname: generatePath(path.pathname ?? "/", params),
- });
+ try {
+ return createPath({
+ ...path,
+ pathname: generatePath(path.pathname ?? "/", targetParams),
+ });
+ } catch {
+ return url;
+ }
+};
+
+const stripHash = (source: string) => {
+ const hashIndex = source.indexOf("#");
+ return hashIndex === -1 ? source : source.slice(0, hashIndex);
+};
+
+const getRedirectStatus = (status: RedirectItem["status"]) => {
+ return Number(status) === 302 ? 302 : 301;
+};
+
+const decodePathname = (pathname: string) => {
+ try {
+ return decodeURI(pathname);
+ } catch {
+ return pathname;
+ }
+};
+
+const getPathnameVariants = (pathname: string) => {
+ return Array.from(new Set([pathname, decodePathname(pathname)]));
+};
+
+const isOptionalSegmentMarker = (source: string, index: number) => {
+ const nextChar = source[index + 1];
+ if (nextChar !== undefined && nextChar !== "/") {
+ return false;
+ }
+
+ const segmentStart = source.lastIndexOf("/", index - 1);
+ const segment = source.slice(segmentStart + 1, index);
+ return segment !== "";
+};
+
+const getSourceSearchIndex = (source: string) => {
+ for (let index = 0; index < source.length; index += 1) {
+ if (
+ source[index] === "?" &&
+ isOptionalSegmentMarker(source, index) === false
+ ) {
+ return index;
+ }
+ }
+ return -1;
+};
+
+const isRedirectPattern = (source: string) => {
+ return (
+ /(^|\/):[^/]+/.test(source) ||
+ /(^|\/)\*(?=\/|$)/.test(source) ||
+ /(^|\/)[^/]+\?(?=\/|$)/.test(source)
+ );
+};
+
+export const matchRedirect = (
+ requestUrl: string,
+ redirects: RedirectItem[]
+): MatchedRedirect | undefined => {
+ const url = new URL(requestUrl);
+ const requestPathnames = getPathnameVariants(url.pathname);
+
+ for (const redirect of redirects) {
+ const source = stripHash(redirect.old);
+ if (getSourceSearchIndex(source) !== -1) {
+ const exactMatch = requestPathnames.some(
+ (requestPathname) => source === `${requestPathname}${url.search}`
+ );
+ if (exactMatch) {
+ return {
+ url: generateRedirectUrl(redirect.new, {}),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+ continue;
+ }
+
+ if (isRedirectPattern(source) === false) {
+ if (requestPathnames.includes(source)) {
+ return {
+ url: generateRedirectUrl(redirect.new, {}),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+ continue;
+ }
+
+ const match = requestPathnames
+ .map((requestPathname) =>
+ matchPath(
+ { path: source, caseSensitive: true, end: true },
+ requestPathname
+ )
+ )
+ .find((match) => match !== null);
+ if (match === undefined) {
+ continue;
+ }
+
+ return {
+ url: generateRedirectUrl(redirect.new, match.params),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+};
+
+export const redirectRequest = (
+ request: Request,
+ redirects: RedirectItem[]
+): Response | undefined => {
+ const matchedRedirect = matchRedirect(request.url, redirects);
+ if (matchedRedirect === undefined) {
+ return;
+ }
+ return redirect(matchedRedirect.url, matchedRedirect.status);
};
diff --git a/fixtures/react-router-cloudflare/app/root.tsx b/fixtures/react-router-cloudflare/app/root.tsx
index 85f70e95ed..ae64304577 100644
--- a/fixtures/react-router-cloudflare/app/root.tsx
+++ b/fixtures/react-router-cloudflare/app/root.tsx
@@ -2,14 +2,27 @@
import {
type HeadersFunction,
+ type LoaderFunctionArgs,
Links,
Meta,
Outlet,
useMatches,
} from "react-router";
+import { redirectRequest } from "./redirect-url";
// @todo think about how to make __generated__ typeable
// @ts-ignore
import { CustomCode, projectId, lastPublished } from "./__generated__/_index";
+// @ts-ignore
+import { redirects } from "./__generated__/$resources.redirects";
+
+export const loader = ({ request }: LoaderFunctionArgs) => {
+ const redirectResponse = redirectRequest(request, redirects);
+ if (redirectResponse !== undefined) {
+ return redirectResponse;
+ }
+
+ return null;
+};
export const headers: HeadersFunction = ({ errorHeaders }) => {
if (errorHeaders) {
diff --git a/fixtures/react-router-docker/app/__generated__/$resources.redirects.ts b/fixtures/react-router-docker/app/__generated__/$resources.redirects.ts
new file mode 100644
index 0000000000..a3ee44bd02
--- /dev/null
+++ b/fixtures/react-router-docker/app/__generated__/$resources.redirects.ts
@@ -0,0 +1 @@
+export const redirects = [];
diff --git a/fixtures/react-router-docker/app/redirect-url.ts b/fixtures/react-router-docker/app/redirect-url.ts
index 1e717eaa73..0e9e45efde 100644
--- a/fixtures/react-router-docker/app/redirect-url.ts
+++ b/fixtures/react-router-docker/app/redirect-url.ts
@@ -1,4 +1,21 @@
-import { createPath, generatePath, parsePath } from "react-router";
+import {
+ createPath,
+ generatePath,
+ matchPath,
+ parsePath,
+ redirect,
+} from "react-router";
+
+type RedirectItem = {
+ old: string;
+ new: string;
+ status?: number | string;
+};
+
+type MatchedRedirect = {
+ url: string;
+ status: number;
+};
/**
* Expands route params in local redirect targets.
@@ -9,13 +26,142 @@ export const generateRedirectUrl = (
url: string,
params: Record<string, string | undefined>
) => {
- if (url.startsWith("/") === false || url.startsWith("//")) {
+ if (
+ /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(url) ||
+ url.startsWith("//") ||
+ url.startsWith("?") ||
+ url.startsWith("#")
+ ) {
return url;
}
+ const targetParams = Object.fromEntries(
+ Object.entries(params).map(([name, value]) => [
+ name,
+ name === "*" ? value : value?.replaceAll("/", "%2F"),
+ ])
+ );
const path = parsePath(url);
- return createPath({
- ...path,
- pathname: generatePath(path.pathname ?? "/", params),
- });
+ try {
+ return createPath({
+ ...path,
+ pathname: generatePath(path.pathname ?? "/", targetParams),
+ });
+ } catch {
+ return url;
+ }
+};
+
+const stripHash = (source: string) => {
+ const hashIndex = source.indexOf("#");
+ return hashIndex === -1 ? source : source.slice(0, hashIndex);
+};
+
+const getRedirectStatus = (status: RedirectItem["status"]) => {
+ return Number(status) === 302 ? 302 : 301;
+};
+
+const decodePathname = (pathname: string) => {
+ try {
+ return decodeURI(pathname);
+ } catch {
+ return pathname;
+ }
+};
+
+const getPathnameVariants = (pathname: string) => {
+ return Array.from(new Set([pathname, decodePathname(pathname)]));
+};
+
+const isOptionalSegmentMarker = (source: string, index: number) => {
+ const nextChar = source[index + 1];
+ if (nextChar !== undefined && nextChar !== "/") {
+ return false;
+ }
+
+ const segmentStart = source.lastIndexOf("/", index - 1);
+ const segment = source.slice(segmentStart + 1, index);
+ return segment !== "";
+};
+
+const getSourceSearchIndex = (source: string) => {
+ for (let index = 0; index < source.length; index += 1) {
+ if (
+ source[index] === "?" &&
+ isOptionalSegmentMarker(source, index) === false
+ ) {
+ return index;
+ }
+ }
+ return -1;
+};
+
+const isRedirectPattern = (source: string) => {
+ return (
+ /(^|\/):[^/]+/.test(source) ||
+ /(^|\/)\*(?=\/|$)/.test(source) ||
+ /(^|\/)[^/]+\?(?=\/|$)/.test(source)
+ );
+};
+
+export const matchRedirect = (
+ requestUrl: string,
+ redirects: RedirectItem[]
+): MatchedRedirect | undefined => {
+ const url = new URL(requestUrl);
+ const requestPathnames = getPathnameVariants(url.pathname);
+
+ for (const redirect of redirects) {
+ const source = stripHash(redirect.old);
+ if (getSourceSearchIndex(source) !== -1) {
+ const exactMatch = requestPathnames.some(
+ (requestPathname) => source === `${requestPathname}${url.search}`
+ );
+ if (exactMatch) {
+ return {
+ url: generateRedirectUrl(redirect.new, {}),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+ continue;
+ }
+
+ if (isRedirectPattern(source) === false) {
+ if (requestPathnames.includes(source)) {
+ return {
+ url: generateRedirectUrl(redirect.new, {}),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+ continue;
+ }
+
+ const match = requestPathnames
+ .map((requestPathname) =>
+ matchPath(
+ { path: source, caseSensitive: true, end: true },
+ requestPathname
+ )
+ )
+ .find((match) => match !== null);
+ if (match === undefined) {
+ continue;
+ }
+
+ return {
+ url: generateRedirectUrl(redirect.new, match.params),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+};
+
+export const redirectRequest = (
+ request: Request,
+ redirects: RedirectItem[]
+): Response | undefined => {
+ const matchedRedirect = matchRedirect(request.url, redirects);
+ if (matchedRedirect === undefined) {
+ return;
+ }
+ return redirect(matchedRedirect.url, matchedRedirect.status);
};
diff --git a/fixtures/react-router-docker/app/root.tsx b/fixtures/react-router-docker/app/root.tsx
index 85f70e95ed..ae64304577 100644
--- a/fixtures/react-router-docker/app/root.tsx
+++ b/fixtures/react-router-docker/app/root.tsx
@@ -2,14 +2,27 @@
import {
type HeadersFunction,
+ type LoaderFunctionArgs,
Links,
Meta,
Outlet,
useMatches,
} from "react-router";
+import { redirectRequest } from "./redirect-url";
// @todo think about how to make __generated__ typeable
// @ts-ignore
import { CustomCode, projectId, lastPublished } from "./__generated__/_index";
+// @ts-ignore
+import { redirects } from "./__generated__/$resources.redirects";
+
+export const loader = ({ request }: LoaderFunctionArgs) => {
+ const redirectResponse = redirectRequest(request, redirects);
+ if (redirectResponse !== undefined) {
+ return redirectResponse;
+ }
+
+ return null;
+};
export const headers: HeadersFunction = ({ errorHeaders }) => {
if (errorHeaders) {
diff --git a/fixtures/react-router-netlify/app/__generated__/$resources.redirects.ts b/fixtures/react-router-netlify/app/__generated__/$resources.redirects.ts
new file mode 100644
index 0000000000..a3ee44bd02
--- /dev/null
+++ b/fixtures/react-router-netlify/app/__generated__/$resources.redirects.ts
@@ -0,0 +1 @@
+export const redirects = [];
diff --git a/fixtures/react-router-netlify/app/redirect-url.ts b/fixtures/react-router-netlify/app/redirect-url.ts
index 1e717eaa73..0e9e45efde 100644
--- a/fixtures/react-router-netlify/app/redirect-url.ts
+++ b/fixtures/react-router-netlify/app/redirect-url.ts
@@ -1,4 +1,21 @@
-import { createPath, generatePath, parsePath } from "react-router";
+import {
+ createPath,
+ generatePath,
+ matchPath,
+ parsePath,
+ redirect,
+} from "react-router";
+
+type RedirectItem = {
+ old: string;
+ new: string;
+ status?: number | string;
+};
+
+type MatchedRedirect = {
+ url: string;
+ status: number;
+};
/**
* Expands route params in local redirect targets.
@@ -9,13 +26,142 @@ export const generateRedirectUrl = (
url: string,
params: Record<string, string | undefined>
) => {
- if (url.startsWith("/") === false || url.startsWith("//")) {
+ if (
+ /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(url) ||
+ url.startsWith("//") ||
+ url.startsWith("?") ||
+ url.startsWith("#")
+ ) {
return url;
}
+ const targetParams = Object.fromEntries(
+ Object.entries(params).map(([name, value]) => [
+ name,
+ name === "*" ? value : value?.replaceAll("/", "%2F"),
+ ])
+ );
const path = parsePath(url);
- return createPath({
- ...path,
- pathname: generatePath(path.pathname ?? "/", params),
- });
+ try {
+ return createPath({
+ ...path,
+ pathname: generatePath(path.pathname ?? "/", targetParams),
+ });
+ } catch {
+ return url;
+ }
+};
+
+const stripHash = (source: string) => {
+ const hashIndex = source.indexOf("#");
+ return hashIndex === -1 ? source : source.slice(0, hashIndex);
+};
+
+const getRedirectStatus = (status: RedirectItem["status"]) => {
+ return Number(status) === 302 ? 302 : 301;
+};
+
+const decodePathname = (pathname: string) => {
+ try {
+ return decodeURI(pathname);
+ } catch {
+ return pathname;
+ }
+};
+
+const getPathnameVariants = (pathname: string) => {
+ return Array.from(new Set([pathname, decodePathname(pathname)]));
+};
+
+const isOptionalSegmentMarker = (source: string, index: number) => {
+ const nextChar = source[index + 1];
+ if (nextChar !== undefined && nextChar !== "/") {
+ return false;
+ }
+
+ const segmentStart = source.lastIndexOf("/", index - 1);
+ const segment = source.slice(segmentStart + 1, index);
+ return segment !== "";
+};
+
+const getSourceSearchIndex = (source: string) => {
+ for (let index = 0; index < source.length; index += 1) {
+ if (
+ source[index] === "?" &&
+ isOptionalSegmentMarker(source, index) === false
+ ) {
+ return index;
+ }
+ }
+ return -1;
+};
+
+const isRedirectPattern = (source: string) => {
+ return (
+ /(^|\/):[^/]+/.test(source) ||
+ /(^|\/)\*(?=\/|$)/.test(source) ||
+ /(^|\/)[^/]+\?(?=\/|$)/.test(source)
+ );
+};
+
+export const matchRedirect = (
+ requestUrl: string,
+ redirects: RedirectItem[]
+): MatchedRedirect | undefined => {
+ const url = new URL(requestUrl);
+ const requestPathnames = getPathnameVariants(url.pathname);
+
+ for (const redirect of redirects) {
+ const source = stripHash(redirect.old);
+ if (getSourceSearchIndex(source) !== -1) {
+ const exactMatch = requestPathnames.some(
+ (requestPathname) => source === `${requestPathname}${url.search}`
+ );
+ if (exactMatch) {
+ return {
+ url: generateRedirectUrl(redirect.new, {}),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+ continue;
+ }
+
+ if (isRedirectPattern(source) === false) {
+ if (requestPathnames.includes(source)) {
+ return {
+ url: generateRedirectUrl(redirect.new, {}),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+ continue;
+ }
+
+ const match = requestPathnames
+ .map((requestPathname) =>
+ matchPath(
+ { path: source, caseSensitive: true, end: true },
+ requestPathname
+ )
+ )
+ .find((match) => match !== null);
+ if (match === undefined) {
+ continue;
+ }
+
+ return {
+ url: generateRedirectUrl(redirect.new, match.params),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+};
+
+export const redirectRequest = (
+ request: Request,
+ redirects: RedirectItem[]
+): Response | undefined => {
+ const matchedRedirect = matchRedirect(request.url, redirects);
+ if (matchedRedirect === undefined) {
+ return;
+ }
+ return redirect(matchedRedirect.url, matchedRedirect.status);
};
diff --git a/fixtures/react-router-netlify/app/root.tsx b/fixtures/react-router-netlify/app/root.tsx
index 85f70e95ed..ae64304577 100644
--- a/fixtures/react-router-netlify/app/root.tsx
+++ b/fixtures/react-router-netlify/app/root.tsx
@@ -2,14 +2,27 @@
import {
type HeadersFunction,
+ type LoaderFunctionArgs,
Links,
Meta,
Outlet,
useMatches,
} from "react-router";
+import { redirectRequest } from "./redirect-url";
// @todo think about how to make __generated__ typeable
// @ts-ignore
import { CustomCode, projectId, lastPublished } from "./__generated__/_index";
+// @ts-ignore
+import { redirects } from "./__generated__/$resources.redirects";
+
+export const loader = ({ request }: LoaderFunctionArgs) => {
+ const redirectResponse = redirectRequest(request, redirects);
+ if (redirectResponse !== undefined) {
+ return redirectResponse;
+ }
+
+ return null;
+};
export const headers: HeadersFunction = ({ errorHeaders }) => {
if (errorHeaders) {
diff --git a/fixtures/react-router-vercel/app/__generated__/$resources.redirects.ts b/fixtures/react-router-vercel/app/__generated__/$resources.redirects.ts
new file mode 100644
index 0000000000..a3ee44bd02
--- /dev/null
+++ b/fixtures/react-router-vercel/app/__generated__/$resources.redirects.ts
@@ -0,0 +1 @@
+export const redirects = [];
diff --git a/fixtures/react-router-vercel/app/redirect-url.ts b/fixtures/react-router-vercel/app/redirect-url.ts
index 1e717eaa73..0e9e45efde 100644
--- a/fixtures/react-router-vercel/app/redirect-url.ts
+++ b/fixtures/react-router-vercel/app/redirect-url.ts
@@ -1,4 +1,21 @@
-import { createPath, generatePath, parsePath } from "react-router";
+import {
+ createPath,
+ generatePath,
+ matchPath,
+ parsePath,
+ redirect,
+} from "react-router";
+
+type RedirectItem = {
+ old: string;
+ new: string;
+ status?: number | string;
+};
+
+type MatchedRedirect = {
+ url: string;
+ status: number;
+};
/**
* Expands route params in local redirect targets.
@@ -9,13 +26,142 @@ export const generateRedirectUrl = (
url: string,
params: Record<string, string | undefined>
) => {
- if (url.startsWith("/") === false || url.startsWith("//")) {
+ if (
+ /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(url) ||
+ url.startsWith("//") ||
+ url.startsWith("?") ||
+ url.startsWith("#")
+ ) {
return url;
}
+ const targetParams = Object.fromEntries(
+ Object.entries(params).map(([name, value]) => [
+ name,
+ name === "*" ? value : value?.replaceAll("/", "%2F"),
+ ])
+ );
const path = parsePath(url);
- return createPath({
- ...path,
- pathname: generatePath(path.pathname ?? "/", params),
- });
+ try {
+ return createPath({
+ ...path,
+ pathname: generatePath(path.pathname ?? "/", targetParams),
+ });
+ } catch {
+ return url;
+ }
+};
+
+const stripHash = (source: string) => {
+ const hashIndex = source.indexOf("#");
+ return hashIndex === -1 ? source : source.slice(0, hashIndex);
+};
+
+const getRedirectStatus = (status: RedirectItem["status"]) => {
+ return Number(status) === 302 ? 302 : 301;
+};
+
+const decodePathname = (pathname: string) => {
+ try {
+ return decodeURI(pathname);
+ } catch {
+ return pathname;
+ }
+};
+
+const getPathnameVariants = (pathname: string) => {
+ return Array.from(new Set([pathname, decodePathname(pathname)]));
+};
+
+const isOptionalSegmentMarker = (source: string, index: number) => {
+ const nextChar = source[index + 1];
+ if (nextChar !== undefined && nextChar !== "/") {
+ return false;
+ }
+
+ const segmentStart = source.lastIndexOf("/", index - 1);
+ const segment = source.slice(segmentStart + 1, index);
+ return segment !== "";
+};
+
+const getSourceSearchIndex = (source: string) => {
+ for (let index = 0; index < source.length; index += 1) {
+ if (
+ source[index] === "?" &&
+ isOptionalSegmentMarker(source, index) === false
+ ) {
+ return index;
+ }
+ }
+ return -1;
+};
+
+const isRedirectPattern = (source: string) => {
+ return (
+ /(^|\/):[^/]+/.test(source) ||
+ /(^|\/)\*(?=\/|$)/.test(source) ||
+ /(^|\/)[^/]+\?(?=\/|$)/.test(source)
+ );
+};
+
+export const matchRedirect = (
+ requestUrl: string,
+ redirects: RedirectItem[]
+): MatchedRedirect | undefined => {
+ const url = new URL(requestUrl);
+ const requestPathnames = getPathnameVariants(url.pathname);
+
+ for (const redirect of redirects) {
+ const source = stripHash(redirect.old);
+ if (getSourceSearchIndex(source) !== -1) {
+ const exactMatch = requestPathnames.some(
+ (requestPathname) => source === `${requestPathname}${url.search}`
+ );
+ if (exactMatch) {
+ return {
+ url: generateRedirectUrl(redirect.new, {}),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+ continue;
+ }
+
+ if (isRedirectPattern(source) === false) {
+ if (requestPathnames.includes(source)) {
+ return {
+ url: generateRedirectUrl(redirect.new, {}),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+ continue;
+ }
+
+ const match = requestPathnames
+ .map((requestPathname) =>
+ matchPath(
+ { path: source, caseSensitive: true, end: true },
+ requestPathname
+ )
+ )
+ .find((match) => match !== null);
+ if (match === undefined) {
+ continue;
+ }
+
+ return {
+ url: generateRedirectUrl(redirect.new, match.params),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+};
+
+export const redirectRequest = (
+ request: Request,
+ redirects: RedirectItem[]
+): Response | undefined => {
+ const matchedRedirect = matchRedirect(request.url, redirects);
+ if (matchedRedirect === undefined) {
+ return;
+ }
+ return redirect(matchedRedirect.url, matchedRedirect.status);
};
diff --git a/fixtures/react-router-vercel/app/root.tsx b/fixtures/react-router-vercel/app/root.tsx
index 85f70e95ed..ae64304577 100644
--- a/fixtures/react-router-vercel/app/root.tsx
+++ b/fixtures/react-router-vercel/app/root.tsx
@@ -2,14 +2,27 @@
import {
type HeadersFunction,
+ type LoaderFunctionArgs,
Links,
Meta,
Outlet,
useMatches,
} from "react-router";
+import { redirectRequest } from "./redirect-url";
// @todo think about how to make __generated__ typeable
// @ts-ignore
import { CustomCode, projectId, lastPublished } from "./__generated__/_index";
+// @ts-ignore
+import { redirects } from "./__generated__/$resources.redirects";
+
+export const loader = ({ request }: LoaderFunctionArgs) => {
+ const redirectResponse = redirectRequest(request, redirects);
+ if (redirectResponse !== undefined) {
+ return redirectResponse;
+ }
+
+ return null;
+};
export const headers: HeadersFunction = ({ errorHeaders }) => {
if (errorHeaders) {
diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.redirects.ts b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.redirects.ts
new file mode 100644
index 0000000000..a3ee44bd02
--- /dev/null
+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.redirects.ts
@@ -0,0 +1 @@
+export const redirects = [];
diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.redirects.ts b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.redirects.ts
new file mode 100644
index 0000000000..a3ee44bd02
--- /dev/null
+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.redirects.ts
@@ -0,0 +1 @@
+export const redirects = [];
diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.redirects.ts b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.redirects.ts
new file mode 100644
index 0000000000..a3ee44bd02
--- /dev/null
+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.redirects.ts
@@ -0,0 +1 @@
+export const redirects = [];
diff --git a/fixtures/webstudio-cloudflare-template/app/redirect-url.ts b/fixtures/webstudio-cloudflare-template/app/redirect-url.ts
index 0e51b5c977..8e13c608e9 100644
--- a/fixtures/webstudio-cloudflare-template/app/redirect-url.ts
+++ b/fixtures/webstudio-cloudflare-template/app/redirect-url.ts
@@ -1,4 +1,21 @@
-import { createPath, generatePath, parsePath } from "@remix-run/react";
+import {
+ createPath,
+ generatePath,
+ matchPath,
+ parsePath,
+} from "@remix-run/react";
+import { redirect } from "@remix-run/server-runtime";
+
+type RedirectItem = {
+ old: string;
+ new: string;
+ status?: number | string;
+};
+
+type MatchedRedirect = {
+ url: string;
+ status: number;
+};
/**
* Expands route params in local redirect targets.
@@ -9,13 +26,142 @@ export const generateRedirectUrl = (
url: string,
params: Record<string, string | undefined>
) => {
- if (url.startsWith("/") === false || url.startsWith("//")) {
+ if (
+ /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(url) ||
+ url.startsWith("//") ||
+ url.startsWith("?") ||
+ url.startsWith("#")
+ ) {
return url;
}
+ const targetParams = Object.fromEntries(
+ Object.entries(params).map(([name, value]) => [
+ name,
+ name === "*" ? value : value?.replaceAll("/", "%2F"),
+ ])
+ );
const path = parsePath(url);
- return createPath({
- ...path,
- pathname: generatePath(path.pathname ?? "/", params),
- });
+ try {
+ return createPath({
+ ...path,
+ pathname: generatePath(path.pathname ?? "/", targetParams),
+ });
+ } catch {
+ return url;
+ }
+};
+
+const stripHash = (source: string) => {
+ const hashIndex = source.indexOf("#");
+ return hashIndex === -1 ? source : source.slice(0, hashIndex);
+};
+
+const getRedirectStatus = (status: RedirectItem["status"]) => {
+ return Number(status) === 302 ? 302 : 301;
+};
+
+const decodePathname = (pathname: string) => {
+ try {
+ return decodeURI(pathname);
+ } catch {
+ return pathname;
+ }
+};
+
+const getPathnameVariants = (pathname: string) => {
+ return Array.from(new Set([pathname, decodePathname(pathname)]));
+};
+
+const isOptionalSegmentMarker = (source: string, index: number) => {
+ const nextChar = source[index + 1];
+ if (nextChar !== undefined && nextChar !== "/") {
+ return false;
+ }
+
+ const segmentStart = source.lastIndexOf("/", index - 1);
+ const segment = source.slice(segmentStart + 1, index);
+ return segment !== "";
+};
+
+const getSourceSearchIndex = (source: string) => {
+ for (let index = 0; index < source.length; index += 1) {
+ if (
+ source[index] === "?" &&
+ isOptionalSegmentMarker(source, index) === false
+ ) {
+ return index;
+ }
+ }
+ return -1;
+};
+
+const isRedirectPattern = (source: string) => {
+ return (
+ /(^|\/):[^/]+/.test(source) ||
+ /(^|\/)\*(?=\/|$)/.test(source) ||
+ /(^|\/)[^/]+\?(?=\/|$)/.test(source)
+ );
+};
+
+export const matchRedirect = (
+ requestUrl: string,
+ redirects: RedirectItem[]
+): MatchedRedirect | undefined => {
+ const url = new URL(requestUrl);
+ const requestPathnames = getPathnameVariants(url.pathname);
+
+ for (const redirect of redirects) {
+ const source = stripHash(redirect.old);
+ if (getSourceSearchIndex(source) !== -1) {
+ const exactMatch = requestPathnames.some(
+ (requestPathname) => source === `${requestPathname}${url.search}`
+ );
+ if (exactMatch) {
+ return {
+ url: generateRedirectUrl(redirect.new, {}),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+ continue;
+ }
+
+ if (isRedirectPattern(source) === false) {
+ if (requestPathnames.includes(source)) {
+ return {
+ url: generateRedirectUrl(redirect.new, {}),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+ continue;
+ }
+
+ const match = requestPathnames
+ .map((requestPathname) =>
+ matchPath(
+ { path: source, caseSensitive: true, end: true },
+ requestPathname
+ )
+ )
+ .find((match) => match !== null);
+ if (match === undefined) {
+ continue;
+ }
+
+ return {
+ url: generateRedirectUrl(redirect.new, match.params),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+};
+
+export const redirectRequest = (
+ request: Request,
+ redirects: RedirectItem[]
+): Response | undefined => {
+ const matchedRedirect = matchRedirect(request.url, redirects);
+ if (matchedRedirect === undefined) {
+ return;
+ }
+ return redirect(matchedRedirect.url, matchedRedirect.status);
};
diff --git a/fixtures/webstudio-cloudflare-template/app/root.tsx b/fixtures/webstudio-cloudflare-template/app/root.tsx
index b79380efc1..0fde2045df 100644
--- a/fixtures/webstudio-cloudflare-template/app/root.tsx
+++ b/fixtures/webstudio-cloudflare-template/app/root.tsx
@@ -1,10 +1,25 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { Links, Meta, Outlet, useMatches } from "@remix-run/react";
-import type { HeadersFunction } from "@remix-run/server-runtime";
+import type {
+ HeadersFunction,
+ LoaderFunctionArgs,
+} from "@remix-run/server-runtime";
+import { redirectRequest } from "./redirect-url";
// @todo think about how to make __generated__ typeable
// @ts-ignore
import { CustomCode, projectId, lastPublished } from "./__generated__/_index";
+// @ts-ignore
+import { redirects } from "./__generated__/$resources.redirects";
+
+export const loader = ({ request }: LoaderFunctionArgs) => {
+ const redirectResponse = redirectRequest(request, redirects);
+ if (redirectResponse !== undefined) {
+ return redirectResponse;
+ }
+
+ return null;
+};
export const headers: HeadersFunction = ({ errorHeaders }) => {
if (errorHeaders) {
diff --git a/fixtures/webstudio-features/app/__generated__/$resources.redirects.ts b/fixtures/webstudio-features/app/__generated__/$resources.redirects.ts
new file mode 100644
index 0000000000..a3ee44bd02
--- /dev/null
+++ b/fixtures/webstudio-features/app/__generated__/$resources.redirects.ts
@@ -0,0 +1 @@
+export const redirects = [];
diff --git a/fixtures/webstudio-features/app/redirect-url.ts b/fixtures/webstudio-features/app/redirect-url.ts
index 1e717eaa73..0e9e45efde 100644
--- a/fixtures/webstudio-features/app/redirect-url.ts
+++ b/fixtures/webstudio-features/app/redirect-url.ts
@@ -1,4 +1,21 @@
-import { createPath, generatePath, parsePath } from "react-router";
+import {
+ createPath,
+ generatePath,
+ matchPath,
+ parsePath,
+ redirect,
+} from "react-router";
+
+type RedirectItem = {
+ old: string;
+ new: string;
+ status?: number | string;
+};
+
+type MatchedRedirect = {
+ url: string;
+ status: number;
+};
/**
* Expands route params in local redirect targets.
@@ -9,13 +26,142 @@ export const generateRedirectUrl = (
url: string,
params: Record<string, string | undefined>
) => {
- if (url.startsWith("/") === false || url.startsWith("//")) {
+ if (
+ /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(url) ||
+ url.startsWith("//") ||
+ url.startsWith("?") ||
+ url.startsWith("#")
+ ) {
return url;
}
+ const targetParams = Object.fromEntries(
+ Object.entries(params).map(([name, value]) => [
+ name,
+ name === "*" ? value : value?.replaceAll("/", "%2F"),
+ ])
+ );
const path = parsePath(url);
- return createPath({
- ...path,
- pathname: generatePath(path.pathname ?? "/", params),
- });
+ try {
+ return createPath({
+ ...path,
+ pathname: generatePath(path.pathname ?? "/", targetParams),
+ });
+ } catch {
+ return url;
+ }
+};
+
+const stripHash = (source: string) => {
+ const hashIndex = source.indexOf("#");
+ return hashIndex === -1 ? source : source.slice(0, hashIndex);
+};
+
+const getRedirectStatus = (status: RedirectItem["status"]) => {
+ return Number(status) === 302 ? 302 : 301;
+};
+
+const decodePathname = (pathname: string) => {
+ try {
+ return decodeURI(pathname);
+ } catch {
+ return pathname;
+ }
+};
+
+const getPathnameVariants = (pathname: string) => {
+ return Array.from(new Set([pathname, decodePathname(pathname)]));
+};
+
+const isOptionalSegmentMarker = (source: string, index: number) => {
+ const nextChar = source[index + 1];
+ if (nextChar !== undefined && nextChar !== "/") {
+ return false;
+ }
+
+ const segmentStart = source.lastIndexOf("/", index - 1);
+ const segment = source.slice(segmentStart + 1, index);
+ return segment !== "";
+};
+
+const getSourceSearchIndex = (source: string) => {
+ for (let index = 0; index < source.length; index += 1) {
+ if (
+ source[index] === "?" &&
+ isOptionalSegmentMarker(source, index) === false
+ ) {
+ return index;
+ }
+ }
+ return -1;
+};
+
+const isRedirectPattern = (source: string) => {
+ return (
+ /(^|\/):[^/]+/.test(source) ||
+ /(^|\/)\*(?=\/|$)/.test(source) ||
+ /(^|\/)[^/]+\?(?=\/|$)/.test(source)
+ );
+};
+
+export const matchRedirect = (
+ requestUrl: string,
+ redirects: RedirectItem[]
+): MatchedRedirect | undefined => {
+ const url = new URL(requestUrl);
+ const requestPathnames = getPathnameVariants(url.pathname);
+
+ for (const redirect of redirects) {
+ const source = stripHash(redirect.old);
+ if (getSourceSearchIndex(source) !== -1) {
+ const exactMatch = requestPathnames.some(
+ (requestPathname) => source === `${requestPathname}${url.search}`
+ );
+ if (exactMatch) {
+ return {
+ url: generateRedirectUrl(redirect.new, {}),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+ continue;
+ }
+
+ if (isRedirectPattern(source) === false) {
+ if (requestPathnames.includes(source)) {
+ return {
+ url: generateRedirectUrl(redirect.new, {}),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+ continue;
+ }
+
+ const match = requestPathnames
+ .map((requestPathname) =>
+ matchPath(
+ { path: source, caseSensitive: true, end: true },
+ requestPathname
+ )
+ )
+ .find((match) => match !== null);
+ if (match === undefined) {
+ continue;
+ }
+
+ return {
+ url: generateRedirectUrl(redirect.new, match.params),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+};
+
+export const redirectRequest = (
+ request: Request,
+ redirects: RedirectItem[]
+): Response | undefined => {
+ const matchedRedirect = matchRedirect(request.url, redirects);
+ if (matchedRedirect === undefined) {
+ return;
+ }
+ return redirect(matchedRedirect.url, matchedRedirect.status);
};
diff --git a/fixtures/webstudio-features/app/root.tsx b/fixtures/webstudio-features/app/root.tsx
index 85f70e95ed..ae64304577 100644
--- a/fixtures/webstudio-features/app/root.tsx
+++ b/fixtures/webstudio-features/app/root.tsx
@@ -2,14 +2,27 @@
import {
type HeadersFunction,
+ type LoaderFunctionArgs,
Links,
Meta,
Outlet,
useMatches,
} from "react-router";
+import { redirectRequest } from "./redirect-url";
// @todo think about how to make __generated__ typeable
// @ts-ignore
import { CustomCode, projectId, lastPublished } from "./__generated__/_index";
+// @ts-ignore
+import { redirects } from "./__generated__/$resources.redirects";
+
+export const loader = ({ request }: LoaderFunctionArgs) => {
+ const redirectResponse = redirectRequest(request, redirects);
+ if (redirectResponse !== undefined) {
+ return redirectResponse;
+ }
+
+ return null;
+};
export const headers: HeadersFunction = ({ errorHeaders }) => {
if (errorHeaders) {
diff --git a/packages/cli/src/framework-react-router.ts b/packages/cli/src/framework-react-router.ts
index cd5dbd23ef..a361856fe0 100644
--- a/packages/cli/src/framework-react-router.ts
+++ b/packages/cli/src/framework-react-router.ts
@@ -26,11 +26,6 @@ export const createFramework = async (): Promise<Framework> => {
join(routeTemplatesDir, "default-sitemap.tsx"),
"utf8"
);
- const redirectTemplate = await readFile(
- join(routeTemplatesDir, "redirect.tsx"),
- "utf8"
- );
-
// cleanup route templates after reading to not bloat generated code
await rm(routeTemplatesDir, { recursive: true, force: true });
@@ -85,12 +80,6 @@ export const createFramework = async (): Promise<Framework> => {
template: textTemplate,
},
],
- redirect: ({ pagePath }: { pagePath: string }) => [
- {
- file: join("app", "routes", `${generateRemixRoute(pagePath)}.ts`),
- template: redirectTemplate,
- },
- ],
defaultSitemap: () => [
{
file: join(
diff --git a/packages/cli/src/framework-remix.ts b/packages/cli/src/framework-remix.ts
index 19f6b2e5c0..b7dbc00717 100644
--- a/packages/cli/src/framework-remix.ts
+++ b/packages/cli/src/framework-remix.ts
@@ -26,11 +26,6 @@ export const createFramework = async (): Promise<Framework> => {
join(routeTemplatesDir, "default-sitemap.tsx"),
"utf8"
);
- const redirectTemplate = await readFile(
- join(routeTemplatesDir, "redirect.tsx"),
- "utf8"
- );
-
// cleanup route templates after reading to not bloat generated code
await rm(routeTemplatesDir, { recursive: true, force: true });
@@ -85,12 +80,6 @@ export const createFramework = async (): Promise<Framework> => {
template: textTemplate,
},
],
- redirect: ({ pagePath }: { pagePath: string }) => [
- {
- file: join("app", "routes", `${generateRemixRoute(pagePath)}.ts`),
- template: redirectTemplate,
- },
- ],
defaultSitemap: () => [
{
file: join(
diff --git a/packages/cli/src/framework-vike-ssg.ts b/packages/cli/src/framework-vike-ssg.ts
index b478af7fea..53c3a46b3a 100644
--- a/packages/cli/src/framework-vike-ssg.ts
+++ b/packages/cli/src/framework-vike-ssg.ts
@@ -81,7 +81,6 @@ export const createFramework = async (): Promise<Framework> => {
},
xml: () => [],
text: () => [],
- redirect: () => [],
defaultSitemap: () => [],
};
};
diff --git a/packages/cli/src/framework.ts b/packages/cli/src/framework.ts
index 3eb92c74c0..27f7c6bacf 100644
--- a/packages/cli/src/framework.ts
+++ b/packages/cli/src/framework.ts
@@ -15,6 +15,5 @@ export type Framework = {
html: (params: { pagePath: string }) => FrameworkTemplateEntry[];
xml: (params: { pagePath: string }) => FrameworkTemplateEntry[];
text: (params: { pagePath: string }) => FrameworkTemplateEntry[];
- redirect: (params: { pagePath: string }) => FrameworkTemplateEntry[];
defaultSitemap: () => FrameworkTemplateEntry[];
};
diff --git a/packages/cli/src/prebuild.test.ts b/packages/cli/src/prebuild.test.ts
new file mode 100644
index 0000000000..46d177d82d
--- /dev/null
+++ b/packages/cli/src/prebuild.test.ts
@@ -0,0 +1,644 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import {
+ mkdtemp,
+ mkdir,
+ readdir,
+ readFile,
+ rm,
+ writeFile,
+} from "node:fs/promises";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import { downloadAsset, generateRedirectsModule, prebuild } from "./prebuild";
+
+const originalCwd = process.cwd();
+const originalFetch = globalThis.fetch;
+let tempDir: string;
+let consoleInfo: ReturnType<typeof vi.spyOn>;
+const rootFolderId = "root";
+const elementComponent = "ws:element";
+type Redirects = Array<{ old: string; new: string; status?: "301" | "302" }>;
+
+const getFilePaths = async (dir: string): Promise<string[]> => {
+ const entries = await readdir(dir, { withFileTypes: true });
+ const paths = await Promise.all(
+ entries.map(async (entry) => {
+ const path = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ return getFilePaths(path);
+ }
+ return [path];
+ })
+ );
+ return paths.flat();
+};
+
+const createSiteData = (
+ overrides: {
+ pages?: Array<{
+ id: string;
+ name: string;
+ title: string;
+ path: string;
+ rootInstanceId: string;
+ meta: Record<string, unknown>;
+ }>;
+ instances?: Array<
+ [
+ string,
+ {
+ id: string;
+ component: string;
+ tag?: string;
+ children: Array<{ type: "id"; value: string }>;
+ },
+ ]
+ >;
+ pageMeta?: Record<string, unknown>;
+ redirects?: Redirects;
+ } = {}
+) => {
+ const pages = overrides.pages ?? [
+ {
+ id: "home",
+ name: "Home",
+ title: "Home",
+ path: "",
+ rootInstanceId: "root",
+ meta: {},
+ },
+ ];
+
+ return {
+ origin: "https://assets.example",
+ projectDomain: "example.com",
+ user: {
+ email: "[email protected]",
+ },
+ assets: [
+ {
+ id: "asset-image",
+ name: "image.png",
+ type: "image",
+ format: "png",
+ size: 1,
+ meta: {
+ width: 1,
+ height: 1,
+ },
+ description: "",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ },
+ ],
+ build: {
+ projectId: "project-id",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ updatedAt: "2024-01-02T00:00:00.000Z",
+ pages: {
+ meta: {
+ siteName: "Site",
+ contactEmail: "",
+ ...overrides.pageMeta,
+ },
+ compiler: {
+ atomicStyles: true,
+ },
+ redirects: overrides.redirects ?? [
+ {
+ old: "/dl.php?filename=file.pdf",
+ new: "/downloads/file.pdf",
+ },
+ {
+ old: "/über",
+ new: "/ueber",
+ status: "302",
+ },
+ ],
+ homePageId: pages[0].id,
+ rootFolderId,
+ pages,
+ folders: [
+ {
+ id: rootFolderId,
+ name: "Root",
+ slug: "",
+ children: pages.map((page) => page.id),
+ },
+ ],
+ },
+ props: [],
+ instances: overrides.instances ?? [
+ [
+ "root",
+ {
+ id: "root",
+ component: "Box",
+ children: [],
+ },
+ ],
+ ],
+ dataSources: [],
+ resources: [],
+ styleSourceSelections: [],
+ styles: [],
+ breakpoints: [],
+ },
+ };
+};
+
+const writeSiteData = async (
+ siteData: ReturnType<typeof createSiteData> = createSiteData()
+) => {
+ await writeFile(".webstudio/data.json", JSON.stringify(siteData), "utf8");
+};
+
+beforeEach(async () => {
+ tempDir = await mkdtemp(join(tmpdir(), "webstudio-prebuild-"));
+ process.chdir(tempDir);
+ consoleInfo = vi.spyOn(console, "info").mockImplementation(() => {});
+ await mkdir(".webstudio", { recursive: true });
+ await writeSiteData();
+});
+
+afterEach(async () => {
+ consoleInfo.mockRestore();
+ process.chdir(originalCwd);
+ globalThis.fetch = originalFetch;
+ await rm(tempDir, { recursive: true, force: true });
+ vi.restoreAllMocks();
+});
+
+describe("generateRedirectsModule", () => {
+ test("generates an empty redirects data module", () => {
+ expect(generateRedirectsModule(undefined)).toEqual(`
+ export const redirects = [];
+ `);
+ });
+
+ test("preserves redirect sources exactly as data", () => {
+ const redirects = [
+ {
+ old: "/dl.php?filename=file.pdf",
+ new: "/downloads/file.pdf",
+ },
+ {
+ old: "/path?url=https%3A%2F%2Fexample.com%2Fa%3Fb%3Dc",
+ new: "/target",
+ status: "302",
+ },
+ {
+ old: "/über",
+ new: "/ueber",
+ },
+ {
+ old: "/%E6%B8%AF%E8%81%9E",
+ new: "/news",
+ },
+ {
+ old: "/path%20with%20spaces",
+ new: "/spaces",
+ },
+ {
+ old: "/old#section",
+ new: "/new#target",
+ },
+ ] satisfies Redirects;
+
+ expect(generateRedirectsModule(redirects)).toEqual(`
+ export const redirects = [
+ {
+ "old": "/dl.php?filename=file.pdf",
+ "new": "/downloads/file.pdf",
+ "status": 301
+ },
+ {
+ "old": "/path?url=https%3A%2F%2Fexample.com%2Fa%3Fb%3Dc",
+ "new": "/target",
+ "status": "302"
+ },
+ {
+ "old": "/über",
+ "new": "/ueber",
+ "status": 301
+ },
+ {
+ "old": "/%E6%B8%AF%E8%81%9E",
+ "new": "/news",
+ "status": 301
+ },
+ {
+ "old": "/path%20with%20spaces",
+ "new": "/spaces",
+ "status": 301
+ },
+ {
+ "old": "/old#section",
+ "new": "/new#target",
+ "status": 301
+ }
+];
+ `);
+ });
+});
+
+describe("downloadAsset", () => {
+ test("does not fetch assets that already exist", async () => {
+ await mkdir("public/assets", { recursive: true });
+ await writeFile("public/assets/image.png", "existing", "utf8");
+ const fetch = vi.fn();
+ globalThis.fetch = fetch;
+
+ await downloadAsset(
+ "https://assets.example/image.png",
+ "image.png",
+ "assets"
+ );
+
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ test("logs fetch failures without throwing", async () => {
+ const fetch = vi.fn(async () => ({
+ ok: false,
+ statusText: "Not Found",
+ }));
+ globalThis.fetch = fetch as unknown as typeof globalThis.fetch;
+ const consoleError = vi
+ .spyOn(console, "error")
+ .mockImplementation(() => {});
+
+ await expect(
+ downloadAsset(
+ "https://assets.example/missing.png",
+ "missing.png",
+ "assets"
+ )
+ ).resolves.toBeUndefined();
+
+ expect(fetch).toHaveBeenCalledWith("https://assets.example/missing.png");
+ expect(consoleError).toHaveBeenCalledWith(
+ expect.stringContaining("Error in downloading file missing.png")
+ );
+ });
+});
+
+describe("prebuild", () => {
+ test("scaffolds generated files and stores redirects as data", async () => {
+ await mkdir("app/__generated__", { recursive: true });
+ await mkdir("app/routes", { recursive: true });
+ await writeFile("app/__generated__/stale.ts", "stale", "utf8");
+ await writeFile("app/routes/stale.tsx", "stale", "utf8");
+
+ await prebuild({
+ assets: false,
+ template: ["defaults"],
+ });
+
+ const redirectsModule = await readFile(
+ "app/__generated__/$resources.redirects.ts",
+ "utf8"
+ );
+ expect(redirectsModule).toEqual(
+ generateRedirectsModule([
+ {
+ old: "/dl.php?filename=file.pdf",
+ new: "/downloads/file.pdf",
+ },
+ {
+ old: "/über",
+ new: "/ueber",
+ status: "302",
+ },
+ ])
+ );
+
+ await expect(
+ readFile("app/__generated__/$resources.assets.ts", "utf8")
+ ).resolves.toContain("image.png");
+ await expect(
+ readFile("app/__generated__/$resources.sitemap.xml.ts", "utf8")
+ ).resolves.toContain('"path": "/"');
+ await expect(
+ readFile("app/__generated__/$resources.wsauth.server.ts", "utf8")
+ ).resolves.toContain("wsauth");
+ await expect(readFile(".webstudio/auth.json", "utf8")).resolves.toContain(
+ "{}"
+ );
+
+ const routeTemplate = await readFile("app/routes/_index.tsx", "utf8");
+ expect(routeTemplate).toContain("../__generated__/_index");
+ expect(routeTemplate).toContain("../__generated__/_index.server");
+ expect(routeTemplate).not.toContain("__CLIENT__");
+ expect(routeTemplate).not.toContain("__SERVER__");
+
+ await expect(
+ readFile("app/__generated__/stale.ts", "utf8")
+ ).rejects.toThrow("ENOENT");
+ await expect(readFile("app/routes/stale.tsx", "utf8")).rejects.toThrow(
+ "ENOENT"
+ );
+
+ const generatedPaths = await getFilePaths("app");
+ expect(generatedPaths).not.toEqual(
+ expect.arrayContaining([
+ expect.stringContaining("dl.php"),
+ expect.stringContaining("filename=file.pdf"),
+ expect.stringContaining("über"),
+ ])
+ );
+ });
+
+ test("selects react-router templates", async () => {
+ await prebuild({
+ assets: false,
+ template: ["react-router", "react-router-vercel"],
+ });
+
+ await expect(readFile("app/routes.ts", "utf8")).resolves.toContain(
+ "react-router"
+ );
+ await expect(readFile("app/root.tsx", "utf8")).resolves.toContain(
+ "react-router"
+ );
+ await expect(readFile("app/routes/_index.tsx", "utf8")).resolves.toContain(
+ 'from "react-router"'
+ );
+ await expect(
+ readFile("app/__generated__/$resources.redirects.ts", "utf8")
+ ).resolves.toContain("/dl.php?filename=file.pdf");
+ });
+
+ test("selects ssg templates and skips dynamic routes", async () => {
+ await writeSiteData(
+ createSiteData({
+ pages: [
+ {
+ id: "home",
+ name: "Home",
+ title: "Home",
+ path: "",
+ rootInstanceId: "root",
+ meta: {},
+ },
+ {
+ id: "post",
+ name: "Post",
+ title: "Post",
+ path: "/blog/:slug",
+ rootInstanceId: "root",
+ meta: {},
+ },
+ ],
+ })
+ );
+
+ await prebuild({
+ assets: false,
+ template: ["ssg"],
+ });
+
+ await expect(readFile("pages/index/+Page.tsx", "utf8")).resolves.toContain(
+ "../app/__generated__/_index"
+ );
+ await expect(readFile("pages/index/+data.ts", "utf8")).resolves.toContain(
+ "../app/__generated__/_index.server"
+ );
+ await expect(
+ readFile("pages/blog/:slug/+Page.tsx", "utf8")
+ ).rejects.toThrow("ENOENT");
+ await expect(
+ readFile("app/__generated__/[blog].$slug._index.tsx", "utf8")
+ ).resolves.toContain("export { Page }");
+ });
+
+ test("generates html, xml, and text document routes", async () => {
+ await writeSiteData(
+ createSiteData({
+ pages: [
+ {
+ id: "home",
+ name: "Home",
+ title: "Home",
+ path: "",
+ rootInstanceId: "root",
+ meta: {},
+ },
+ {
+ id: "feed",
+ name: "Feed",
+ title: "Feed",
+ path: "/feed.xml",
+ rootInstanceId: "xml-root",
+ meta: {
+ documentType: "xml",
+ },
+ },
+ {
+ id: "robots",
+ name: "Robots",
+ title: "Robots",
+ path: "/robots.txt",
+ rootInstanceId: "root",
+ meta: {
+ documentType: "text",
+ },
+ },
+ ],
+ instances: [
+ [
+ "root",
+ {
+ id: "root",
+ component: "Box",
+ children: [],
+ },
+ ],
+ [
+ "xml-root",
+ {
+ id: "xml-root",
+ component: "Box",
+ children: [{ type: "id", value: "xml-feed" }],
+ },
+ ],
+ [
+ "xml-feed",
+ {
+ id: "xml-feed",
+ component: elementComponent,
+ tag: "rss",
+ children: [],
+ },
+ ],
+ ],
+ })
+ );
+
+ await prebuild({
+ assets: false,
+ template: ["defaults"],
+ });
+
+ await expect(readFile("app/routes/_index.tsx", "utf8")).resolves.toContain(
+ "useLoaderData"
+ );
+ await expect(
+ readFile("app/routes/[feed.xml]._index.tsx", "utf8")
+ ).resolves.toContain("renderToString");
+ await expect(
+ readFile("app/routes/[robots.txt]._index.tsx", "utf8")
+ ).resolves.toContain("Content-Type");
+ });
+
+ test("generates custom code only for the home page", async () => {
+ await writeSiteData(
+ createSiteData({
+ pageMeta: {
+ code: '<script src="/custom.js"></script><style>.x{color:red}</style>',
+ },
+ pages: [
+ {
+ id: "home",
+ name: "Home",
+ title: "Home",
+ path: "",
+ rootInstanceId: "root",
+ meta: {},
+ },
+ {
+ id: "about",
+ name: "About",
+ title: "About",
+ path: "/about",
+ rootInstanceId: "root",
+ meta: {},
+ },
+ ],
+ })
+ );
+
+ await prebuild({
+ assets: false,
+ template: ["defaults"],
+ });
+
+ await expect(
+ readFile("app/__generated__/_index.tsx", "utf8")
+ ).resolves.toContain("CustomCode");
+ await expect(
+ readFile("app/__generated__/[about]._index.tsx", "utf8")
+ ).resolves.not.toContain("CustomCode");
+ });
+
+ test("downloads assets only when requested by prebuild", async () => {
+ const fetch = vi.fn(async () => ({
+ ok: false,
+ statusText: "Not Found",
+ }));
+ globalThis.fetch = fetch as unknown as typeof globalThis.fetch;
+ const consoleWarn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const consoleError = vi
+ .spyOn(console, "error")
+ .mockImplementation(() => {});
+
+ await prebuild({
+ assets: false,
+ template: ["defaults"],
+ });
+ expect(fetch).not.toHaveBeenCalled();
+
+ await prebuild({
+ assets: true,
+ template: ["defaults"],
+ });
+ expect(fetch).toHaveBeenCalledWith(
+ "https://assets.example/cgi/image/image.png?format=raw"
+ );
+ expect(consoleWarn).not.toHaveBeenCalled();
+ expect(consoleError).toHaveBeenCalledWith(
+ expect.stringContaining("Error in downloading file image.png")
+ );
+ });
+
+ test("merges package and tsconfig from every template", async () => {
+ const localTemplate = join(tempDir, "local-template");
+ await mkdir(localTemplate, { recursive: true });
+ await writeFile(
+ join(localTemplate, "package.json"),
+ JSON.stringify({
+ scripts: {
+ local: "echo local",
+ },
+ dependencies: {
+ "local-package": "1.0.0",
+ },
+ }),
+ "utf8"
+ );
+ await writeFile(
+ join(localTemplate, "tsconfig.json"),
+ JSON.stringify({
+ compilerOptions: {
+ strict: false,
+ paths: {
+ "~local/*": ["./local/*"],
+ },
+ },
+ }),
+ "utf8"
+ );
+ await writeFile(
+ "package.json",
+ JSON.stringify({
+ scripts: {
+ existing: "echo existing",
+ },
+ dependencies: {
+ existing: "1.0.0",
+ },
+ }),
+ "utf8"
+ );
+ await writeFile(
+ "tsconfig.json",
+ JSON.stringify({
+ compilerOptions: {
+ strict: true,
+ paths: {
+ "~existing/*": ["./existing/*"],
+ },
+ },
+ }),
+ "utf8"
+ );
+
+ await prebuild({
+ assets: false,
+ template: ["defaults", localTemplate],
+ });
+
+ const packageJson = JSON.parse(await readFile("package.json", "utf8"));
+ expect(packageJson.scripts.existing).toEqual("echo existing");
+ expect(packageJson.scripts.local).toEqual("echo local");
+ expect(packageJson.dependencies.existing).toEqual("1.0.0");
+ expect(packageJson.dependencies["local-package"]).toEqual("1.0.0");
+
+ const tsconfig = JSON.parse(await readFile("tsconfig.json", "utf8"));
+ expect(tsconfig.compilerOptions.strict).toEqual(false);
+ expect(tsconfig.compilerOptions.paths).toEqual({
+ "~existing/*": ["./existing/*"],
+ "~local/*": ["./local/*"],
+ });
+ });
+
+ test("throws when project data is missing", async () => {
+ await rm(".webstudio/data.json", { force: true });
+
+ await expect(
+ prebuild({
+ assets: false,
+ template: ["defaults"],
+ })
+ ).rejects.toThrow("Project data is missing");
+ });
+});
diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.ts
index 0b4052e939..5ae6310f3a 100644
--- a/packages/cli/src/prebuild.ts
+++ b/packages/cli/src/prebuild.ts
@@ -253,6 +253,19 @@ audit=false
fund=false
`;
+export const generateRedirectsModule = (pageRedirects: Pages["redirects"]) => {
+ const redirects =
+ pageRedirects?.map((redirect) => ({
+ old: redirect.old,
+ new: redirect.new,
+ status: redirect.status ?? 301,
+ })) ?? [];
+
+ return `
+ export const redirects = ${JSON.stringify(redirects, null, 2)};
+ `;
+};
+
export const prebuild = async (options: {
/**
* Do we need download assets
@@ -795,29 +808,10 @@ export const prebuild = async (options: {
`
);
- const redirects = pages.redirects;
- if (redirects !== undefined && redirects.length > 0) {
- for (const redirect of redirects) {
- const generatedBasename = generateRemixRoute(redirect.old);
- await createFileIfNotExists(
- join(generatedDir, `${generatedBasename}.ts`),
- `
- export const url = "${redirect.new}";
- export const status = ${redirect.status ?? 301};
- `
- );
-
- for (const { file, template } of framework.redirect({
- pagePath: redirect.old,
- })) {
- const content = template.replaceAll(
- "__REDIRECT__",
- importFrom(`./app/__generated__/${generatedBasename}`, file)
- );
- await createFileIfNotExists(file, content);
- }
- }
- }
+ await createFileIfNotExists(
+ join(generatedDir, "$resources.redirects.ts"),
+ generateRedirectsModule(pages.redirects)
+ );
if (assetsToDownload.length > 0) {
const downloading = spinner();
diff --git a/packages/cli/src/redirect-url.test.ts b/packages/cli/src/redirect-url.test.ts
index 7335419502..67757e6b15 100644
--- a/packages/cli/src/redirect-url.test.ts
+++ b/packages/cli/src/redirect-url.test.ts
@@ -1,60 +1,627 @@
-import { expect, test } from "vitest";
-import { matchPath as matchRemixPath } from "@remix-run/react";
-import { matchPath as matchReactRouterPath } from "react-router";
-import { generateRedirectUrl as generateRemixRedirectUrl } from "../templates/defaults/app/redirect-url";
-import { generateRedirectUrl as generateReactRouterRedirectUrl } from "../templates/react-router/app/redirect-url";
+import { describe, expect, test } from "vitest";
+import { readFile } from "node:fs/promises";
+import { join } from "node:path";
+import {
+ generateRedirectUrl as generateRemixRedirectUrl,
+ matchRedirect as matchRemixRedirect,
+ redirectRequest as redirectRemixRequest,
+} from "../templates/defaults/app/redirect-url";
+import {
+ generateRedirectUrl as generateReactRouterRedirectUrl,
+ matchRedirect as matchReactRouterRedirect,
+ redirectRequest as redirectReactRouterRequest,
+} from "../templates/react-router/app/redirect-url";
const implementations = [
{
name: "Remix",
generateRedirectUrl: generateRemixRedirectUrl,
- matchParams: (pattern: string, pathname: string) =>
- matchRemixPath(pattern, pathname)?.params ?? {},
+ matchRedirect: matchRemixRedirect,
+ redirectRequest: redirectRemixRequest,
},
{
name: "React Router",
generateRedirectUrl: generateReactRouterRedirectUrl,
- matchParams: (pattern: string, pathname: string) =>
- matchReactRouterPath(pattern, pathname)?.params ?? {},
+ matchRedirect: matchReactRouterRedirect,
+ redirectRequest: redirectReactRouterRequest,
},
] as const;
-for (const { name, generateRedirectUrl, matchParams } of implementations) {
- test(`${name}: generates redirect url for /privat/* to /*`, () => {
- const params = matchParams("/privat/*", "/privat/foo");
- expect(params).toEqual({ "*": "foo" });
+const defaultOrigin = "https://example.com";
- expect(generateRedirectUrl("/*", params)).toEqual("/foo");
+type Redirect = {
+ old: string;
+ new: string;
+ status?: number | string;
+};
+
+type MatchedRedirect = {
+ url: string;
+ status: number;
+};
+
+const url = (path: string) => `${defaultOrigin}${path}`;
+
+const cliRoot = process.cwd();
+const repoRoot = join(cliRoot, "../..");
+
+describe("redirect-url fixture copies", () => {
+ test.each([
+ "react-router-cloudflare",
+ "react-router-docker",
+ "react-router-netlify",
+ "react-router-vercel",
+ "webstudio-features",
+ ])(
+ "keeps %s redirect helper synced with react-router template",
+ async (fixture) => {
+ await expect(
+ readFile(
+ join(repoRoot, "fixtures", fixture, "app/redirect-url.ts"),
+ "utf8"
+ )
+ ).resolves.toEqual(
+ await readFile(
+ join(cliRoot, "templates/react-router/app/redirect-url.ts"),
+ "utf8"
+ )
+ );
+ }
+ );
+
+ test("keeps webstudio-cloudflare-template redirect helper synced with defaults template", async () => {
+ await expect(
+ readFile(
+ join(
+ repoRoot,
+ "fixtures/webstudio-cloudflare-template/app/redirect-url.ts"
+ ),
+ "utf8"
+ )
+ ).resolves.toEqual(
+ await readFile(
+ join(cliRoot, "templates/defaults/app/redirect-url.ts"),
+ "utf8"
+ )
+ );
});
+});
- test(`${name}: preserves nested splat params`, () => {
- const params = matchParams("/privat/*", "/privat/foo/bar");
- expect(params).toEqual({ "*": "foo/bar" });
+for (const {
+ name,
+ generateRedirectUrl,
+ matchRedirect,
+ redirectRequest,
+} of implementations) {
+ describe(`${name}: generateRedirectUrl`, () => {
+ const cases: Array<{
+ name: string;
+ target: string;
+ params: Record<string, string | undefined>;
+ expected: string;
+ }> = [
+ {
+ name: "expands splat params",
+ target: "/*",
+ params: { "*": "foo" },
+ expected: "/foo",
+ },
+ {
+ name: "preserves nested splat params",
+ target: "/*",
+ params: { "*": "foo/bar" },
+ expected: "/foo/bar",
+ },
+ {
+ name: "expands named params",
+ target: "/articles/:slug",
+ params: { slug: "post" },
+ expected: "/articles/post",
+ },
+ {
+ name: "expands named params in relative targets",
+ target: "articles/:slug",
+ params: { slug: "post" },
+ expected: "articles/post",
+ },
+ {
+ name: "preserves encoded slashes in named params",
+ target: "/articles/:slug",
+ params: { slug: "a/b" },
+ expected: "/articles/a%2Fb",
+ },
+ {
+ name: "preserves search and hash",
+ target: "/*?next=*#section",
+ params: { "*": "foo" },
+ expected: "/foo?next=*#section",
+ },
+ {
+ name: "preserves search on local targets",
+ target: "/target?x=1&y=2",
+ params: {},
+ expected: "/target?x=1&y=2",
+ },
+ {
+ name: "preserves hash on local targets",
+ target: "/target#section",
+ params: {},
+ expected: "/target#section",
+ },
+ {
+ name: "returns original local target when params cannot be expanded",
+ target: "/articles/:missing",
+ params: {},
+ expected: "/articles/:missing",
+ },
+ {
+ name: "preserves absolute urls",
+ target: "https://other.example/*",
+ params: { "*": "foo" },
+ expected: "https://other.example/*",
+ },
+ {
+ name: "preserves protocol-relative urls",
+ target: "//other.example/*",
+ params: { "*": "foo" },
+ expected: "//other.example/*",
+ },
+ {
+ name: "preserves non-path urls",
+ target: "mailto:[email protected]",
+ params: {},
+ expected: "mailto:[email protected]",
+ },
+ {
+ name: "preserves query-only targets",
+ target: "?preview=1",
+ params: { slug: "post" },
+ expected: "?preview=1",
+ },
+ {
+ name: "preserves hash-only targets",
+ target: "#section",
+ params: { slug: "post" },
+ expected: "#section",
+ },
+ ];
- expect(generateRedirectUrl("/*", params)).toEqual("/foo/bar");
+ test.each(cases)("$name", ({ target, params, expected }) => {
+ expect(generateRedirectUrl(target, params)).toEqual(expected);
+ });
});
- test(`${name}: generates redirect url from named params`, () => {
- const params = matchParams("/blog/:slug", "/blog/post");
- expect(params).toEqual({ slug: "post" });
+ describe(`${name}: matchRedirect`, () => {
+ const matchingCases: Array<{
+ name: string;
+ requestPath: string;
+ redirects: Redirect[];
+ expected: MatchedRedirect;
+ }> = [
+ {
+ name: "matches exact path",
+ requestPath: "/old",
+ redirects: [{ old: "/old", new: "/new" }],
+ expected: { url: "/new", status: 301 },
+ },
+ {
+ name: "path-only source ignores request query",
+ requestPath: "/old?x=1",
+ redirects: [{ old: "/old", new: "/new", status: 302 }],
+ expected: { url: "/new", status: 302 },
+ },
+ {
+ name: "matches exact path with trailing slash",
+ requestPath: "/old/",
+ redirects: [{ old: "/old/", new: "/new" }],
+ expected: { url: "/new", status: 301 },
+ },
+ {
+ name: "matches exact path with repeated slashes",
+ requestPath: "/a//b",
+ redirects: [{ old: "/a//b", new: "/new" }],
+ expected: { url: "/new", status: 301 },
+ },
+ {
+ name: "matches exact query string",
+ requestPath: "/old?x=1",
+ redirects: [{ old: "/old?x=1", new: "/new" }],
+ expected: { url: "/new", status: 301 },
+ },
+ {
+ name: "matches exact empty query value",
+ requestPath: "/old?x=",
+ redirects: [{ old: "/old?x=", new: "/new" }],
+ expected: { url: "/new", status: 301 },
+ },
+ {
+ name: "matches exact repeated query params",
+ requestPath: "/old?x=1&x=2",
+ redirects: [{ old: "/old?x=1&x=2", new: "/new" }],
+ expected: { url: "/new", status: 301 },
+ },
+ {
+ name: "matches exact encoded query values",
+ requestPath: "/old?q=a%20b%26c%3Dd",
+ redirects: [{ old: "/old?q=a%20b%26c%3Dd", new: "/new" }],
+ expected: { url: "/new", status: 301 },
+ },
+ {
+ name: "matches php-style source with query string",
+ requestPath: "/dl.php?filename=file.pdf",
+ redirects: [
+ { old: "/dl.php?filename=file.pdf", new: "/downloads/file.pdf" },
+ ],
+ expected: { url: "/downloads/file.pdf", status: 301 },
+ },
+ {
+ name: "matches query values containing encoded urls",
+ requestPath: "/path?url=https%3A%2F%2Fexample.com%2Fa%3Fb%3Dc",
+ redirects: [
+ {
+ old: "/path?url=https%3A%2F%2Fexample.com%2Fa%3Fb%3Dc",
+ new: "/target",
+ },
+ ],
+ expected: { url: "/target", status: 301 },
+ },
+ {
+ name: "matches query values containing unencoded urls",
+ requestPath: "/path?url=https://example.com/a?b=c",
+ redirects: [
+ {
+ old: "/path?url=https://example.com/a?b=c",
+ new: "/target",
+ },
+ ],
+ expected: { url: "/target", status: 301 },
+ },
+ {
+ name: "matches decoded query-specific source path against encoded request path",
+ requestPath: "/%C3%BCber?x=1",
+ redirects: [{ old: "/über?x=1", new: "/ueber" }],
+ expected: { url: "/ueber", status: 301 },
+ },
+ {
+ name: "matches encoded query-specific source path against decoded request path",
+ requestPath: "/über?x=1",
+ redirects: [{ old: "/%C3%BCber?x=1", new: "/ueber" }],
+ expected: { url: "/ueber", status: 301 },
+ },
+ {
+ name: "matches decoded spaces in query-specific source paths",
+ requestPath: "/path%20with%20spaces?x=1",
+ redirects: [{ old: "/path with spaces?x=1", new: "/spaces" }],
+ expected: { url: "/spaces", status: 301 },
+ },
+ {
+ name: "matches encoded source pathname",
+ requestPath: "/%E6%B8%AF%E8%81%9E",
+ redirects: [{ old: "/%E6%B8%AF%E8%81%9E", new: "/news" }],
+ expected: { url: "/news", status: 301 },
+ },
+ {
+ name: "matches decoded source against encoded request pathname",
+ requestPath: "/%C3%BCber",
+ redirects: [{ old: "/über", new: "/ueber" }],
+ expected: { url: "/ueber", status: 301 },
+ },
+ {
+ name: "matches encoded source against decoded request pathname",
+ requestPath: "/über",
+ redirects: [{ old: "/%C3%BCber", new: "/ueber" }],
+ expected: { url: "/ueber", status: 301 },
+ },
+ {
+ name: "matches encoded spaces",
+ requestPath: "/path%20with%20spaces",
+ redirects: [{ old: "/path%20with%20spaces", new: "/spaces" }],
+ expected: { url: "/spaces", status: 301 },
+ },
+ {
+ name: "matches decoded spaces against encoded request pathname",
+ requestPath: "/path%20with%20spaces",
+ redirects: [{ old: "/path with spaces", new: "/spaces" }],
+ expected: { url: "/spaces", status: 301 },
+ },
+ {
+ name: "matches browser-encoded angle brackets",
+ requestPath: "/path%3Cscript%3E",
+ redirects: [{ old: "/path<script>", new: "/encoded" }],
+ expected: { url: "/encoded", status: 301 },
+ },
+ {
+ name: "matches browser-encoded quotes",
+ requestPath: "/path%22quoted%22",
+ redirects: [{ old: '/path"quoted"', new: "/encoded" }],
+ expected: { url: "/encoded", status: 301 },
+ },
+ {
+ name: "matches url punctuation in exact paths",
+ requestPath: "/!$&'()+,;=@[]",
+ redirects: [{ old: "/!$&'()+,;=@[]", new: "/punctuation" }],
+ expected: { url: "/punctuation", status: 301 },
+ },
+ {
+ name: "matches literal colon in exact paths",
+ requestPath: "/time/12:30",
+ redirects: [{ old: "/time/12:30", new: "/time" }],
+ expected: { url: "/time", status: 301 },
+ },
+ {
+ name: "matches literal asterisk in exact paths",
+ requestPath: "/file*name",
+ redirects: [{ old: "/file*name", new: "/asterisk" }],
+ expected: { url: "/asterisk", status: 301 },
+ },
+ {
+ name: "matches malformed percent escapes as exact encoded paths",
+ requestPath: "/%E0%A4%A",
+ redirects: [{ old: "/%E0%A4%A", new: "/malformed-percent" }],
+ expected: { url: "/malformed-percent", status: 301 },
+ },
+ {
+ name: "does not decode encoded slash into path separator",
+ requestPath: "/file%2Fname",
+ redirects: [{ old: "/file%2Fname", new: "/encoded-slash" }],
+ expected: { url: "/encoded-slash", status: 301 },
+ },
+ {
+ name: "matches dynamic source and expands target params",
+ requestPath: "/blog/post",
+ redirects: [
+ { old: "/blog/:slug", new: "/articles/:slug", status: "302" },
+ ],
+ expected: { url: "/articles/post", status: 302 },
+ },
+ {
+ name: "matches dynamic source and expands relative target params",
+ requestPath: "/blog/post",
+ redirects: [{ old: "/blog/:slug", new: "articles/:slug" }],
+ expected: { url: "articles/post", status: 301 },
+ },
+ {
+ name: "matches optional dynamic source when param is present",
+ requestPath: "/blog/post",
+ redirects: [{ old: "/blog/:slug?", new: "/articles/:slug" }],
+ expected: { url: "/articles/post", status: 301 },
+ },
+ {
+ name: "matches optional dynamic source when param is absent",
+ requestPath: "/blog",
+ redirects: [{ old: "/blog/:slug?", new: "/articles" }],
+ expected: { url: "/articles", status: 301 },
+ },
+ {
+ name: "matches optional static source segment",
+ requestPath: "/en/about",
+ redirects: [{ old: "/en?/about", new: "/about" }],
+ expected: { url: "/about", status: 301 },
+ },
+ {
+ name: "matches mixed optional static and dynamic source",
+ requestPath: "/one/two/three/four/rest",
+ redirects: [
+ { old: "/one?/:two?/three/:four/*", new: "/target/:four/*" },
+ ],
+ expected: { url: "/target/four/rest", status: 301 },
+ },
+ {
+ name: "matches encoded dynamic params and keeps encoded target params",
+ requestPath: "/blog/%C3%BCber",
+ redirects: [{ old: "/blog/:slug", new: "/articles/:slug" }],
+ expected: { url: "/articles/%C3%BCber", status: 301 },
+ },
+ {
+ name: "does not throw when matched target has missing params",
+ requestPath: "/blog/post",
+ redirects: [{ old: "/blog/:slug", new: "/articles/:missing" }],
+ expected: { url: "/articles/:missing", status: 301 },
+ },
+ {
+ name: "matches encoded slashes in dynamic params without turning them into path separators",
+ requestPath: "/blog/a%2Fb",
+ redirects: [{ old: "/blog/:slug", new: "/articles/:slug" }],
+ expected: { url: "/articles/a%2Fb", status: 301 },
+ },
+ {
+ name: "matches splat source and expands target splat",
+ requestPath: "/docs/api/reference",
+ redirects: [{ old: "/docs/*", new: "/reference/*" }],
+ expected: { url: "/reference/api/reference", status: 301 },
+ },
+ {
+ name: "preserves absolute redirect targets",
+ requestPath: "/external",
+ redirects: [{ old: "/external", new: "https://other.example/path" }],
+ expected: { url: "https://other.example/path", status: 301 },
+ },
+ {
+ name: "preserves protocol-relative redirect targets",
+ requestPath: "/protocol-relative",
+ redirects: [{ old: "/protocol-relative", new: "//other.example/path" }],
+ expected: { url: "//other.example/path", status: 301 },
+ },
+ {
+ name: "ignores source fragments and preserves target fragments",
+ requestPath: "/old",
+ redirects: [{ old: "/old#section", new: "/new#target" }],
+ expected: { url: "/new#target", status: 301 },
+ },
+ {
+ name: "ignores source fragments after query strings",
+ requestPath: "/old?x=1",
+ redirects: [{ old: "/old?x=1#section", new: "/new" }],
+ expected: { url: "/new", status: 301 },
+ },
+ {
+ name: "falls back to 301 for unsupported status values",
+ requestPath: "/old",
+ redirects: [{ old: "/old", new: "/new", status: "307" }],
+ expected: { url: "/new", status: 301 },
+ },
+ {
+ name: "uses the first matching redirect",
+ requestPath: "/old",
+ redirects: [
+ { old: "/old", new: "/first", status: 302 },
+ { old: "/old", new: "/second", status: 301 },
+ ],
+ expected: { url: "/first", status: 302 },
+ },
+ {
+ name: "query-specific source wins when ordered before path-only source",
+ requestPath: "/old?x=1",
+ redirects: [
+ { old: "/old?x=1", new: "/query" },
+ { old: "/old", new: "/path" },
+ ],
+ expected: { url: "/query", status: 301 },
+ },
+ {
+ name: "path-only source wins when ordered before query-specific source",
+ requestPath: "/old?x=1",
+ redirects: [
+ { old: "/old", new: "/path" },
+ { old: "/old?x=1", new: "/query" },
+ ],
+ expected: { url: "/path", status: 301 },
+ },
+ ];
- expect(generateRedirectUrl("/articles/:slug", params)).toEqual(
- "/articles/post"
+ test.each(matchingCases)(
+ "$name",
+ ({ requestPath, redirects, expected }) => {
+ expect(matchRedirect(url(requestPath), redirects)).toEqual(expected);
+ }
);
- });
- test(`${name}: preserves search and hash`, () => {
- expect(generateRedirectUrl("/*?next=*#section", { "*": "foo" })).toEqual(
- "/foo?next=*#section"
+ test.each(matchingCases)(
+ "returns router redirect response: $name",
+ ({ requestPath, redirects, expected }) => {
+ const response = redirectRequest(
+ new Request(url(requestPath)),
+ redirects
+ );
+ expect(response).toBeInstanceOf(Response);
+ expect(response?.status).toEqual(expected.status);
+ expect(response?.headers.get("Location")).toEqual(expected.url);
+ }
);
- });
- test(`${name}: preserves non-local urls`, () => {
- expect(
- generateRedirectUrl("https://example.com/*", { "*": "foo" })
- ).toEqual("https://example.com/*");
- expect(generateRedirectUrl("//example.com/*", { "*": "foo" })).toEqual(
- "//example.com/*"
+ const nonMatchingCases: Array<{
+ name: string;
+ requestPath: string;
+ redirects: Redirect[];
+ }> = [
+ {
+ name: "returns undefined when there are no redirects",
+ requestPath: "/old",
+ redirects: [],
+ },
+ {
+ name: "does not match different paths",
+ requestPath: "/other",
+ redirects: [{ old: "/old", new: "/new" }],
+ },
+ {
+ name: "does not match nested paths for exact sources",
+ requestPath: "/old/nested",
+ redirects: [{ old: "/old", new: "/new" }],
+ },
+ {
+ name: "does not normalize trailing slash",
+ requestPath: "/old/",
+ redirects: [{ old: "/old", new: "/new" }],
+ },
+ {
+ name: "matches paths case-sensitively",
+ requestPath: "/path",
+ redirects: [{ old: "/Path", new: "/target" }],
+ },
+ {
+ name: "query-specific source does not match missing query",
+ requestPath: "/old",
+ redirects: [{ old: "/old?x=1", new: "/new" }],
+ },
+ {
+ name: "query-specific source does not match different query",
+ requestPath: "/old?x=2",
+ redirects: [{ old: "/old?x=1", new: "/new" }],
+ },
+ {
+ name: "query-specific source does not match extra query params",
+ requestPath: "/old?x=1&y=2",
+ redirects: [{ old: "/old?x=1", new: "/new" }],
+ },
+ {
+ name: "query-specific source does not normalize query param order",
+ requestPath: "/old?b=2&a=1",
+ redirects: [{ old: "/old?a=1&b=2", new: "/new" }],
+ },
+ {
+ name: "query-specific source does not decode query values",
+ requestPath: "/old?q=a+b",
+ redirects: [{ old: "/old?q=a%20b", new: "/new" }],
+ },
+ {
+ name: "query-specific source does not ignore empty query values",
+ requestPath: "/old?x",
+ redirects: [{ old: "/old?x=", new: "/new" }],
+ },
+ {
+ name: "literal colon does not behave like a route param",
+ requestPath: "/time/12:45",
+ redirects: [{ old: "/time/12:30", new: "/time" }],
+ },
+ {
+ name: "literal asterisk does not behave like a splat param",
+ requestPath: "/file-anything",
+ redirects: [{ old: "/file*name", new: "/asterisk" }],
+ },
+ {
+ name: "encoded slash does not match real slash",
+ requestPath: "/file/name",
+ redirects: [{ old: "/file%2Fname", new: "/encoded-slash" }],
+ },
+ {
+ name: "real slash does not match encoded slash",
+ requestPath: "/file%2Fname",
+ redirects: [{ old: "/file/name", new: "/real-slash" }],
+ },
+ {
+ name: "query-specific redirects do not extract route params",
+ requestPath: "/blog/post?preview=1",
+ redirects: [{ old: "/blog/:slug?preview=1", new: "/articles/:slug" }],
+ },
+ {
+ name: "optional dynamic sources do not match extra nested segments",
+ requestPath: "/blog/post/extra",
+ redirects: [{ old: "/blog/:slug?", new: "/articles/:slug" }],
+ },
+ {
+ name: "optional static source does not behave like a query-specific source",
+ requestPath: "/en?/about",
+ redirects: [{ old: "/en?/about", new: "/about" }],
+ },
+ {
+ name: "query-specific redirects do not decode query values",
+ requestPath: "/über?x=a+b",
+ redirects: [{ old: "/%C3%BCber?x=a%20b", new: "/new" }],
+ },
+ ];
+
+ test.each(nonMatchingCases)("$name", ({ requestPath, redirects }) => {
+ expect(matchRedirect(url(requestPath), redirects)).toBeUndefined();
+ });
+
+ test.each(nonMatchingCases)(
+ "does not return router redirect response: $name",
+ ({ requestPath, redirects }) => {
+ expect(
+ redirectRequest(new Request(url(requestPath)), redirects)
+ ).toBeUndefined();
+ }
);
});
}
diff --git a/packages/cli/templates/defaults/app/redirect-url.ts b/packages/cli/templates/defaults/app/redirect-url.ts
index 0e51b5c977..8e13c608e9 100644
--- a/packages/cli/templates/defaults/app/redirect-url.ts
+++ b/packages/cli/templates/defaults/app/redirect-url.ts
@@ -1,4 +1,21 @@
-import { createPath, generatePath, parsePath } from "@remix-run/react";
+import {
+ createPath,
+ generatePath,
+ matchPath,
+ parsePath,
+} from "@remix-run/react";
+import { redirect } from "@remix-run/server-runtime";
+
+type RedirectItem = {
+ old: string;
+ new: string;
+ status?: number | string;
+};
+
+type MatchedRedirect = {
+ url: string;
+ status: number;
+};
/**
* Expands route params in local redirect targets.
@@ -9,13 +26,142 @@ export const generateRedirectUrl = (
url: string,
params: Record<string, string | undefined>
) => {
- if (url.startsWith("/") === false || url.startsWith("//")) {
+ if (
+ /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(url) ||
+ url.startsWith("//") ||
+ url.startsWith("?") ||
+ url.startsWith("#")
+ ) {
return url;
}
+ const targetParams = Object.fromEntries(
+ Object.entries(params).map(([name, value]) => [
+ name,
+ name === "*" ? value : value?.replaceAll("/", "%2F"),
+ ])
+ );
const path = parsePath(url);
- return createPath({
- ...path,
- pathname: generatePath(path.pathname ?? "/", params),
- });
+ try {
+ return createPath({
+ ...path,
+ pathname: generatePath(path.pathname ?? "/", targetParams),
+ });
+ } catch {
+ return url;
+ }
+};
+
+const stripHash = (source: string) => {
+ const hashIndex = source.indexOf("#");
+ return hashIndex === -1 ? source : source.slice(0, hashIndex);
+};
+
+const getRedirectStatus = (status: RedirectItem["status"]) => {
+ return Number(status) === 302 ? 302 : 301;
+};
+
+const decodePathname = (pathname: string) => {
+ try {
+ return decodeURI(pathname);
+ } catch {
+ return pathname;
+ }
+};
+
+const getPathnameVariants = (pathname: string) => {
+ return Array.from(new Set([pathname, decodePathname(pathname)]));
+};
+
+const isOptionalSegmentMarker = (source: string, index: number) => {
+ const nextChar = source[index + 1];
+ if (nextChar !== undefined && nextChar !== "/") {
+ return false;
+ }
+
+ const segmentStart = source.lastIndexOf("/", index - 1);
+ const segment = source.slice(segmentStart + 1, index);
+ return segment !== "";
+};
+
+const getSourceSearchIndex = (source: string) => {
+ for (let index = 0; index < source.length; index += 1) {
+ if (
+ source[index] === "?" &&
+ isOptionalSegmentMarker(source, index) === false
+ ) {
+ return index;
+ }
+ }
+ return -1;
+};
+
+const isRedirectPattern = (source: string) => {
+ return (
+ /(^|\/):[^/]+/.test(source) ||
+ /(^|\/)\*(?=\/|$)/.test(source) ||
+ /(^|\/)[^/]+\?(?=\/|$)/.test(source)
+ );
+};
+
+export const matchRedirect = (
+ requestUrl: string,
+ redirects: RedirectItem[]
+): MatchedRedirect | undefined => {
+ const url = new URL(requestUrl);
+ const requestPathnames = getPathnameVariants(url.pathname);
+
+ for (const redirect of redirects) {
+ const source = stripHash(redirect.old);
+ if (getSourceSearchIndex(source) !== -1) {
+ const exactMatch = requestPathnames.some(
+ (requestPathname) => source === `${requestPathname}${url.search}`
+ );
+ if (exactMatch) {
+ return {
+ url: generateRedirectUrl(redirect.new, {}),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+ continue;
+ }
+
+ if (isRedirectPattern(source) === false) {
+ if (requestPathnames.includes(source)) {
+ return {
+ url: generateRedirectUrl(redirect.new, {}),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+ continue;
+ }
+
+ const match = requestPathnames
+ .map((requestPathname) =>
+ matchPath(
+ { path: source, caseSensitive: true, end: true },
+ requestPathname
+ )
+ )
+ .find((match) => match !== null);
+ if (match === undefined) {
+ continue;
+ }
+
+ return {
+ url: generateRedirectUrl(redirect.new, match.params),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+};
+
+export const redirectRequest = (
+ request: Request,
+ redirects: RedirectItem[]
+): Response | undefined => {
+ const matchedRedirect = matchRedirect(request.url, redirects);
+ if (matchedRedirect === undefined) {
+ return;
+ }
+ return redirect(matchedRedirect.url, matchedRedirect.status);
};
diff --git a/packages/cli/templates/defaults/app/root.tsx b/packages/cli/templates/defaults/app/root.tsx
index b79380efc1..0fde2045df 100644
--- a/packages/cli/templates/defaults/app/root.tsx
+++ b/packages/cli/templates/defaults/app/root.tsx
@@ -1,10 +1,25 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { Links, Meta, Outlet, useMatches } from "@remix-run/react";
-import type { HeadersFunction } from "@remix-run/server-runtime";
+import type {
+ HeadersFunction,
+ LoaderFunctionArgs,
+} from "@remix-run/server-runtime";
+import { redirectRequest } from "./redirect-url";
// @todo think about how to make __generated__ typeable
// @ts-ignore
import { CustomCode, projectId, lastPublished } from "./__generated__/_index";
+// @ts-ignore
+import { redirects } from "./__generated__/$resources.redirects";
+
+export const loader = ({ request }: LoaderFunctionArgs) => {
+ const redirectResponse = redirectRequest(request, redirects);
+ if (redirectResponse !== undefined) {
+ return redirectResponse;
+ }
+
+ return null;
+};
export const headers: HeadersFunction = ({ errorHeaders }) => {
if (errorHeaders) {
diff --git a/packages/cli/templates/defaults/app/route-templates/redirect.tsx b/packages/cli/templates/defaults/app/route-templates/redirect.tsx
deleted file mode 100644
index a65d706868..0000000000
--- a/packages/cli/templates/defaults/app/route-templates/redirect.tsx
+++ /dev/null
@@ -1,7 +0,0 @@
-import { type LoaderFunctionArgs, redirect } from "@remix-run/server-runtime";
-import { generateRedirectUrl } from "../redirect-url";
-import { url, status } from "__REDIRECT__";
-
-export const loader = (arg: LoaderFunctionArgs) => {
- return redirect(generateRedirectUrl(url, arg.params), status);
-};
diff --git a/packages/cli/templates/react-router/app/redirect-url.ts b/packages/cli/templates/react-router/app/redirect-url.ts
index 1e717eaa73..0e9e45efde 100644
--- a/packages/cli/templates/react-router/app/redirect-url.ts
+++ b/packages/cli/templates/react-router/app/redirect-url.ts
@@ -1,4 +1,21 @@
-import { createPath, generatePath, parsePath } from "react-router";
+import {
+ createPath,
+ generatePath,
+ matchPath,
+ parsePath,
+ redirect,
+} from "react-router";
+
+type RedirectItem = {
+ old: string;
+ new: string;
+ status?: number | string;
+};
+
+type MatchedRedirect = {
+ url: string;
+ status: number;
+};
/**
* Expands route params in local redirect targets.
@@ -9,13 +26,142 @@ export const generateRedirectUrl = (
url: string,
params: Record<string, string | undefined>
) => {
- if (url.startsWith("/") === false || url.startsWith("//")) {
+ if (
+ /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(url) ||
+ url.startsWith("//") ||
+ url.startsWith("?") ||
+ url.startsWith("#")
+ ) {
return url;
}
+ const targetParams = Object.fromEntries(
+ Object.entries(params).map(([name, value]) => [
+ name,
+ name === "*" ? value : value?.replaceAll("/", "%2F"),
+ ])
+ );
const path = parsePath(url);
- return createPath({
- ...path,
- pathname: generatePath(path.pathname ?? "/", params),
- });
+ try {
+ return createPath({
+ ...path,
+ pathname: generatePath(path.pathname ?? "/", targetParams),
+ });
+ } catch {
+ return url;
+ }
+};
+
+const stripHash = (source: string) => {
+ const hashIndex = source.indexOf("#");
+ return hashIndex === -1 ? source : source.slice(0, hashIndex);
+};
+
+const getRedirectStatus = (status: RedirectItem["status"]) => {
+ return Number(status) === 302 ? 302 : 301;
+};
+
+const decodePathname = (pathname: string) => {
+ try {
+ return decodeURI(pathname);
+ } catch {
+ return pathname;
+ }
+};
+
+const getPathnameVariants = (pathname: string) => {
+ return Array.from(new Set([pathname, decodePathname(pathname)]));
+};
+
+const isOptionalSegmentMarker = (source: string, index: number) => {
+ const nextChar = source[index + 1];
+ if (nextChar !== undefined && nextChar !== "/") {
+ return false;
+ }
+
+ const segmentStart = source.lastIndexOf("/", index - 1);
+ const segment = source.slice(segmentStart + 1, index);
+ return segment !== "";
+};
+
+const getSourceSearchIndex = (source: string) => {
+ for (let index = 0; index < source.length; index += 1) {
+ if (
+ source[index] === "?" &&
+ isOptionalSegmentMarker(source, index) === false
+ ) {
+ return index;
+ }
+ }
+ return -1;
+};
+
+const isRedirectPattern = (source: string) => {
+ return (
+ /(^|\/):[^/]+/.test(source) ||
+ /(^|\/)\*(?=\/|$)/.test(source) ||
+ /(^|\/)[^/]+\?(?=\/|$)/.test(source)
+ );
+};
+
+export const matchRedirect = (
+ requestUrl: string,
+ redirects: RedirectItem[]
+): MatchedRedirect | undefined => {
+ const url = new URL(requestUrl);
+ const requestPathnames = getPathnameVariants(url.pathname);
+
+ for (const redirect of redirects) {
+ const source = stripHash(redirect.old);
+ if (getSourceSearchIndex(source) !== -1) {
+ const exactMatch = requestPathnames.some(
+ (requestPathname) => source === `${requestPathname}${url.search}`
+ );
+ if (exactMatch) {
+ return {
+ url: generateRedirectUrl(redirect.new, {}),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+ continue;
+ }
+
+ if (isRedirectPattern(source) === false) {
+ if (requestPathnames.includes(source)) {
+ return {
+ url: generateRedirectUrl(redirect.new, {}),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+ continue;
+ }
+
+ const match = requestPathnames
+ .map((requestPathname) =>
+ matchPath(
+ { path: source, caseSensitive: true, end: true },
+ requestPathname
+ )
+ )
+ .find((match) => match !== null);
+ if (match === undefined) {
+ continue;
+ }
+
+ return {
+ url: generateRedirectUrl(redirect.new, match.params),
+ status: getRedirectStatus(redirect.status),
+ };
+ }
+};
+
+export const redirectRequest = (
+ request: Request,
+ redirects: RedirectItem[]
+): Response | undefined => {
+ const matchedRedirect = matchRedirect(request.url, redirects);
+ if (matchedRedirect === undefined) {
+ return;
+ }
+ return redirect(matchedRedirect.url, matchedRedirect.status);
};
diff --git a/packages/cli/templates/react-router/app/root.tsx b/packages/cli/templates/react-router/app/root.tsx
index 85f70e95ed..ae64304577 100644
--- a/packages/cli/templates/react-router/app/root.tsx
+++ b/packages/cli/templates/react-router/app/root.tsx
@@ -2,14 +2,27 @@
import {
type HeadersFunction,
+ type LoaderFunctionArgs,
Links,
Meta,
Outlet,
useMatches,
} from "react-router";
+import { redirectRequest } from "./redirect-url";
// @todo think about how to make __generated__ typeable
// @ts-ignore
import { CustomCode, projectId, lastPublished } from "./__generated__/_index";
+// @ts-ignore
+import { redirects } from "./__generated__/$resources.redirects";
+
+export const loader = ({ request }: LoaderFunctionArgs) => {
+ const redirectResponse = redirectRequest(request, redirects);
+ if (redirectResponse !== undefined) {
+ return redirectResponse;
+ }
+
+ return null;
+};
export const headers: HeadersFunction = ({ errorHeaders }) => {
if (errorHeaders) {
diff --git a/packages/cli/templates/react-router/app/route-templates/redirect.tsx b/packages/cli/templates/react-router/app/route-templates/redirect.tsx
deleted file mode 100644
index 5b10d776e0..0000000000
--- a/packages/cli/templates/react-router/app/route-templates/redirect.tsx
+++ /dev/null
@@ -1,7 +0,0 @@
-import { type LoaderFunctionArgs, redirect } from "react-router";
-import { generateRedirectUrl } from "../redirect-url";
-import { url, status } from "__REDIRECT__";
-
-export const loader = (arg: LoaderFunctionArgs) => {
- throw redirect(generateRedirectUrl(url, arg.params), status);
-};
diff --git a/packages/cli/vite.config.ts b/packages/cli/vite.config.ts
index 92d30ce6f2..6533ee61dc 100644
--- a/packages/cli/vite.config.ts
+++ b/packages/cli/vite.config.ts
@@ -1,4 +1,8 @@
-import { defineConfig } from "vite";
+import {
+ defaultClientConditions,
+ defaultServerConditions,
+ defineConfig,
+} from "vite";
import pkg from "./package.json";
const isExternal = (id: string, importer: string | undefined) => {
@@ -30,7 +34,15 @@ const isExternal = (id: string, importer: string | undefined) => {
};
export default defineConfig({
- // resolve only webstudio condition in tests
+ // resolve webstudio condition in tests
+ resolve: {
+ conditions: ["webstudio", ...defaultClientConditions],
+ },
+ ssr: {
+ resolve: {
+ conditions: ["webstudio", ...defaultServerConditions],
+ },
+ },
build: {
minify: false,
lib: {
diff --git a/packages/sdk/src/router-path-test-data.ts b/packages/sdk/src/router-path-test-data.ts
index 77899fc521..f2907fdad4 100644
--- a/packages/sdk/src/router-path-test-data.ts
+++ b/packages/sdk/src/router-path-test-data.ts
@@ -2,7 +2,7 @@
* Shared test data for router path validation.
*
* This file exports test cases that should be used consistently across:
- * 1. Path schema validation (SDK) - OldPagePath, page paths, etc.
+ * 1. Path schema validation (SDK) - page paths, redirect source paths, etc.
* 2. URLPattern matching (builder) - used for all page routing
* 3. Route generation for published sites (react-sdk)
*
@@ -141,7 +141,7 @@ export const INVALID_ROUTER_PATHS = {
// Empty or root only (for redirects, root is not a valid source)
empty: ["", "/"],
- // Spaces (must be URL-encoded)
+ // Spaces (must be URL-encoded for generic page/router paths)
spaces: ["/hello world", "/path with spaces"],
// URL-unsafe characters (RFC 3986)
@@ -175,6 +175,37 @@ export const INVALID_ROUTER_PATHS = {
export const ALL_VALID_PATHS = Object.values(VALID_ROUTER_PATHS).flat();
export const ALL_INVALID_PATHS = Object.values(INVALID_ROUTER_PATHS).flat();
+export const REDIRECT_SOURCE_EXTRA_VALID_PATHS = [
+ "/hello world",
+ "/path with spaces",
+ "/path<script>",
+ "/path>other",
+ '/path"quote',
+ "/path{test}",
+ "/path|other",
+ "/path[0]",
+ "/path`backtick",
+ "/about/",
+ "/about//page",
+ "/path?url=https://example.com/a?b=c",
+] as const;
+
+export const REDIRECT_SOURCE_VALID_PATHS = [
+ ...ALL_VALID_PATHS,
+ ...REDIRECT_SOURCE_EXTRA_VALID_PATHS,
+] as const;
+
+export const REDIRECT_SOURCE_INVALID_PATHS = [
+ ...INVALID_ROUTER_PATHS.empty,
+ "/path\\other",
+ "/line\nfeed",
+ "/tab\tfeed",
+ ...INVALID_ROUTER_PATHS.reserved,
+ "no-leading-slash",
+ "//leading-double",
+ ...INVALID_ROUTER_PATHS.controlChars,
+] as const;
+
// Paths that are specifically for testing URLPattern matching (no query/fragment)
// These are paths that work with URLPattern API
export const VALID_URLPATTERN_PATHS = [
diff --git a/packages/sdk/src/router-paths.test.ts b/packages/sdk/src/router-paths.test.ts
index b67510779b..da3fc9794d 100644
--- a/packages/sdk/src/router-paths.test.ts
+++ b/packages/sdk/src/router-paths.test.ts
@@ -2,7 +2,7 @@
* Shared test suite for router path handling consistency.
*
* This ensures that router paths are handled consistently across:
- * 1. Path schema validation (SDK) - OldPagePath, page paths
+ * 1. Path schema validation (SDK) - redirect source paths
* 2. URLPattern matching (builder) - used for all page routing
* 3. Route generation for published sites (react-sdk)
*
@@ -10,20 +10,23 @@
*/
import { describe, test, expect } from "vitest";
-import { OldPagePath, ProjectNewRedirectPath } from "./schema/pages";
-import { ALL_VALID_PATHS, ALL_INVALID_PATHS } from "./router-path-test-data";
+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("OldPagePath schema - valid paths", () => {
- test.each(ALL_VALID_PATHS)("accepts: %s", (path) => {
- const result = OldPagePath.safeParse(path);
+ describe("RedirectSourcePath schema - valid paths", () => {
+ test.each(REDIRECT_SOURCE_VALID_PATHS)("accepts: %s", (path) => {
+ const result = RedirectSourcePath.safeParse(path);
expect(result.success).toBe(true);
});
});
- describe("OldPagePath schema - invalid paths", () => {
- test.each(ALL_INVALID_PATHS)("rejects: %s", (path) => {
- const result = OldPagePath.safeParse(path);
+ describe("RedirectSourcePath schema - invalid paths", () => {
+ test.each(REDIRECT_SOURCE_INVALID_PATHS)("rejects: %s", (path) => {
+ const result = RedirectSourcePath.safeParse(path);
expect(result.success).toBe(false);
});
});
diff --git a/packages/sdk/src/schema/pages.test.ts b/packages/sdk/src/schema/pages.test.ts
index 3f62bd103f..6d28e8917b 100644
--- a/packages/sdk/src/schema/pages.test.ts
+++ b/packages/sdk/src/schema/pages.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, test } from "vitest";
import {
documentTypes,
- OldPagePath,
+ RedirectSourcePath,
PageAuth,
PagePath,
Pages,
@@ -333,181 +333,192 @@ test("validates folders do not contain cycles", () => {
);
});
-describe("OldPagePath", () => {
+describe("RedirectSourcePath", () => {
describe("basic validation", () => {
test("accepts valid path", () => {
- expect(OldPagePath.safeParse("/about").success).toBe(true);
- expect(OldPagePath.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 = OldPagePath.safeParse("");
+ const result = RedirectSourcePath.safeParse("");
expect(result.success).toBe(false);
});
test("rejects just a slash", () => {
- const result = OldPagePath.safeParse("/");
+ const result = RedirectSourcePath.safeParse("/");
expect(result.success).toBe(false);
});
test("must start with /", () => {
- const result = OldPagePath.safeParse("about");
+ const result = RedirectSourcePath.safeParse("about");
expect(result.success).toBe(false);
});
- test("cannot end with /", () => {
- const result = OldPagePath.safeParse("/about/");
- expect(result.success).toBe(false);
+ test("accepts trailing slash", () => {
+ const result = RedirectSourcePath.safeParse("/about/");
+ expect(result.success).toBe(true);
+ });
+
+ test("accepts repeated slashes inside the path", () => {
+ const result = RedirectSourcePath.safeParse("/about//page");
+ expect(result.success).toBe(true);
});
- test("cannot contain //", () => {
- const result = OldPagePath.safeParse("/about//page");
+ test("rejects protocol-relative paths", () => {
+ const result = RedirectSourcePath.safeParse("//example.com/path");
expect(result.success).toBe(false);
});
test("rejects /s prefix (reserved)", () => {
- expect(OldPagePath.safeParse("/s").success).toBe(false);
- expect(OldPagePath.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(OldPagePath.safeParse("/build").success).toBe(false);
- expect(OldPagePath.safeParse("/build/main.js").success).toBe(false);
+ expect(RedirectSourcePath.safeParse("/build").success).toBe(false);
+ expect(RedirectSourcePath.safeParse("/build/main.js").success).toBe(
+ false
+ );
});
});
describe("special characters", () => {
test("accepts wildcards", () => {
- expect(OldPagePath.safeParse("/blog/*").success).toBe(true);
+ expect(RedirectSourcePath.safeParse("/blog/*").success).toBe(true);
});
test("accepts dynamic segments", () => {
- expect(OldPagePath.safeParse("/:slug").success).toBe(true);
- expect(OldPagePath.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(OldPagePath.safeParse("/:id?").success).toBe(true);
+ expect(RedirectSourcePath.safeParse("/:id?").success).toBe(true);
});
test("accepts query strings", () => {
- expect(OldPagePath.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")
+ .success
+ ).toBe(true);
});
test("accepts URL-encoded characters", () => {
- expect(OldPagePath.safeParse("/hello%20world").success).toBe(true);
- expect(OldPagePath.safeParse("/%E6%B8%AF%E8%81%9E").success).toBe(true);
+ expect(RedirectSourcePath.safeParse("/hello%20world").success).toBe(true);
+ expect(RedirectSourcePath.safeParse("/%E6%B8%AF%E8%81%9E").success).toBe(
+ true
+ );
});
});
- describe("invalid characters", () => {
- test("rejects spaces", () => {
- const result = OldPagePath.safeParse("/hello world");
- expect(result.success).toBe(false);
- });
-
- test("rejects angle brackets", () => {
- expect(OldPagePath.safeParse("/path<script>").success).toBe(false);
- expect(OldPagePath.safeParse("/path>other").success).toBe(false);
- });
-
- test("rejects quotes", () => {
- expect(OldPagePath.safeParse('/path"quote').success).toBe(false);
- });
-
- test("rejects curly braces", () => {
- expect(OldPagePath.safeParse("/path{test}").success).toBe(false);
+ describe("browser-requestable characters", () => {
+ test("accepts spaces", () => {
+ expect(RedirectSourcePath.safeParse("/hello world").success).toBe(true);
+ expect(RedirectSourcePath.safeParse("/path with spaces").success).toBe(
+ true
+ );
});
- test("rejects pipe", () => {
- expect(OldPagePath.safeParse("/path|other").success).toBe(false);
+ 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);
});
- test("rejects backslash", () => {
- expect(OldPagePath.safeParse("/path\\other").success).toBe(false);
+ test("rejects backslash because URL parsers normalize it to slash", () => {
+ expect(RedirectSourcePath.safeParse("/path\\other").success).toBe(false);
});
- test("rejects square brackets", () => {
- expect(OldPagePath.safeParse("/path[0]").success).toBe(false);
+ test("rejects control characters", () => {
+ 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(OldPagePath.safeParse("/关于我们").success).toBe(true);
- expect(OldPagePath.safeParse("/产品/手机").success).toBe(true);
- expect(OldPagePath.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(OldPagePath.safeParse("/關於我們").success).toBe(true);
- expect(OldPagePath.safeParse("/港聞").success).toBe(true);
- expect(OldPagePath.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(OldPagePath.safeParse("/こんにちは").success).toBe(true);
- expect(OldPagePath.safeParse("/ブログ/記事").success).toBe(true);
+ expect(RedirectSourcePath.safeParse("/こんにちは").success).toBe(true);
+ expect(RedirectSourcePath.safeParse("/ブログ/記事").success).toBe(true);
});
test("accepts Japanese characters (Katakana)", () => {
- expect(OldPagePath.safeParse("/カテゴリ").success).toBe(true);
+ expect(RedirectSourcePath.safeParse("/カテゴリ").success).toBe(true);
});
test("accepts Japanese characters (Kanji)", () => {
- expect(OldPagePath.safeParse("/日本語").success).toBe(true);
- expect(OldPagePath.safeParse("/東京").success).toBe(true);
+ expect(RedirectSourcePath.safeParse("/日本語").success).toBe(true);
+ expect(RedirectSourcePath.safeParse("/東京").success).toBe(true);
});
test("accepts Korean characters (Hangul)", () => {
- expect(OldPagePath.safeParse("/한국어").success).toBe(true);
- expect(OldPagePath.safeParse("/블로그/포스트").success).toBe(true);
- expect(OldPagePath.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(OldPagePath.safeParse("/привет").success).toBe(true);
- expect(OldPagePath.safeParse("/о-нас").success).toBe(true);
- expect(OldPagePath.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(OldPagePath.safeParse("/مرحبا").success).toBe(true);
- expect(OldPagePath.safeParse("/عن-الشركة").success).toBe(true);
+ expect(RedirectSourcePath.safeParse("/مرحبا").success).toBe(true);
+ expect(RedirectSourcePath.safeParse("/عن-الشركة").success).toBe(true);
});
test("accepts Hebrew characters", () => {
- expect(OldPagePath.safeParse("/שלום").success).toBe(true);
- expect(OldPagePath.safeParse("/אודות").success).toBe(true);
+ expect(RedirectSourcePath.safeParse("/שלום").success).toBe(true);
+ expect(RedirectSourcePath.safeParse("/אודות").success).toBe(true);
});
test("accepts Thai characters", () => {
- expect(OldPagePath.safeParse("/สวัสดี").success).toBe(true);
- expect(OldPagePath.safeParse("/เกี่ยวกับเรา").success).toBe(true);
+ expect(RedirectSourcePath.safeParse("/สวัสดี").success).toBe(true);
+ expect(RedirectSourcePath.safeParse("/เกี่ยวกับเรา").success).toBe(true);
});
test("accepts Greek characters", () => {
- expect(OldPagePath.safeParse("/γεια").success).toBe(true);
- expect(OldPagePath.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(OldPagePath.safeParse("/blog/关于").success).toBe(true);
- expect(OldPagePath.safeParse("/news/港聞").success).toBe(true);
- expect(OldPagePath.safeParse("/category/日本語").success).toBe(true);
+ 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(OldPagePath.safeParse("/über-uns").success).toBe(true);
- expect(OldPagePath.safeParse("/café").success).toBe(true);
- expect(OldPagePath.safeParse("/niño").success).toBe(true);
- expect(OldPagePath.safeParse("/naïve").success).toBe(true);
- expect(OldPagePath.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(OldPagePath.safeParse("/🎉").success).toBe(true);
- expect(OldPagePath.safeParse("/hello-🌍").success).toBe(true);
+ expect(RedirectSourcePath.safeParse("/🎉").success).toBe(true);
+ expect(RedirectSourcePath.safeParse("/hello-🌍").success).toBe(true);
});
});
});
diff --git a/packages/sdk/src/schema/pages.ts b/packages/sdk/src/schema/pages.ts
index b0825f8b35..d04df06e47 100644
--- a/packages/sdk/src/schema/pages.ts
+++ b/packages/sdk/src/schema/pages.ts
@@ -156,28 +156,30 @@ const DefaultPagePage = z
)
.refine((path) => path.length <= 255, "Path can't exceed 255 characters");
-export const OldPagePath = z
+export const RedirectSourcePath = z
.string()
.refine((path) => path !== "", "Can't be empty")
.refine((path) => path !== "/", "Can't be just a /")
.refine(
- (path) => path === "" || path.startsWith("/"),
- "Must start with a / or a full URL e.g. https://website.org"
+ (path) => path.startsWith("/") && path.startsWith("//") === false,
+ "Must start with a /"
)
- .refine((path) => path.endsWith("/") === false, "Can't end with a /")
- .refine((path) => path.includes("//") === false, "Can't contain repeating /")
.refine((path) => {
- // Disallow specific problematic characters that should never appear in paths:
- // - Spaces and whitespace
- // - URL-unsafe characters: < > " { } | \ ^ ` [ ]
- // - Control characters
- // All other characters (including non-Latin Unicode like Chinese, Japanese,
- // Korean, Cyrillic, Arabic, etc.) are allowed as they are valid in modern URLs
- // when properly encoded by the browser
+ // Redirect sources may contain any browser-requestable URL characters.
+ // Backslashes and control characters are rejected because URL parsers
+ // normalize or strip them, making matching ambiguous.
// eslint-disable-next-line no-control-regex
- const disallowedChars = /[\s<>"{}|\\^`[\]\u0000-\u001f\u007f]/;
- return !disallowedChars.test(path);
- }, "Path contains invalid characters (spaces or URL-unsafe characters are not allowed)")
+ if (/[\\\u0000-\u001f\u007f]/.test(path)) {
+ return false;
+ }
+
+ try {
+ new URL(path, "https://example.com");
+ return true;
+ } catch {
+ return false;
+ }
+ }, "Must be a valid URL path")
.refine(
(path) => path !== "/s" && path.startsWith("/s/") === false,
"/s prefix is reserved for the system"
@@ -233,7 +235,7 @@ export const ProjectNewRedirectPath = z
}, "Must be a valid URL");
export const PageRedirect = z.object({
- old: OldPagePath,
+ old: RedirectSourcePath,
new: ProjectNewRedirectPath,
status: z.enum(["301", "302"]).optional(),
});