Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 49 additions & 3 deletions packages/blocks/src/sdk/redirects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ export function loadRedirects(blocks: Record<string, unknown>): RedirectMap {
const redirect: Redirect = {
from: normalizePath(entry.from),
to: entry.to,
status: entry.type === "permanent" ? 301 : 302,
status: normalizeStatus(entry.type),
};

if (redirect.from.includes("*")) {
Expand Down Expand Up @@ -140,7 +140,7 @@ export function parseRedirectsCsv(csv: string): Redirect[] {
const line = raw.trim();
if (!line || line.startsWith("#")) continue;

const parts = line.split(",").map((p) => p.trim());
const parts = splitCsvLine(line);
if (parts.length < 2) continue;

const [from, to, type] = parts;
Expand All @@ -152,7 +152,7 @@ export function parseRedirectsCsv(csv: string): Redirect[] {
redirects.push({
from: normalizePath(from),
to,
status: type === "permanent" || type === "301" ? 301 : 302,
status: normalizeStatus(type),
});
}

Expand Down Expand Up @@ -204,6 +204,52 @@ export function matchRedirect(pathname: string, map: RedirectMap): Redirect | nu
// Helpers
// -------------------------------------------------------------------------

/**
* Split one CSV line on commas that are not inside a quoted field.
*
* Bulk redirect exports routinely hold VTEX URLs whose query contains commas
* (`?map=category-1,category-2`). Those rows are quoted, and a plain
* `split(",")` shreds them into rules with a truncated source and a fragment of
* the query as the target.
*/
function splitCsvLine(line: string): string[] {
const parts: string[] = [];
let current = "";
let quoted = false;

for (let i = 0; i < line.length; i++) {
const char = line[i];
if (char === '"') {
// "" inside a quoted field is an escaped quote (RFC 4180).
if (quoted && line[i + 1] === '"') {
current += '"';
i++;
} else {
quoted = !quoted;
}
} else if (char === "," && !quoted) {
parts.push(current.trim());
current = "";
} else {
current += char;
}
}
parts.push(current.trim());
return parts;
}

/**
* Redirect type -> HTTP status, case-insensitively.
*
* Exports commonly write `PERMANENT`. Matching only the lowercase spelling
* downgraded those rows to 302, and a temporary redirect passes no ranking
* signal to the new URL.
*/
function normalizeStatus(type?: string): 301 | 302 {
const t = type?.trim().toLowerCase();
return t === "permanent" || t === "301" ? 301 : 302;
}

function normalizePath(path: string): string {
let p = path.trim();

Expand Down
71 changes: 71 additions & 0 deletions packages/blocks/src/sdk/redirectsCsvParsing.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/**
* CSV parsing details that bulk redirect exports depend on: quoted fields and
* the spelling of the redirect type.
*/
import { describe, expect, it } from "vitest";
import { loadRedirects, matchRedirect, parseRedirectsCsv } from "./redirects";

describe("quoted fields", () => {
it("does not split on a comma inside a quoted source", () => {
// Real VTEX export row: the query itself contains a comma.
const [redirect] = parseRedirectsCsv(
'from,to,type\n"https://www.example.com/relogios?map=category-1,category-2",/relogios,PERMANENT\n',
);

expect(redirect).toMatchObject({ to: "/relogios", status: 301 });
expect(redirect.from).toBe("/relogios");
});

it("does not split on a comma inside a quoted target", () => {
const [redirect] = parseRedirectsCsv('from,to\n/old,"/new?map=a,b"\n');
expect(redirect).toMatchObject({ from: "/old", to: "/new?map=a,b" });
});

it("unescapes a doubled quote inside a quoted field", () => {
const [redirect] = parseRedirectsCsv('from,to\n/old,"/new?q=""x"""\n');
expect(redirect.to).toBe('/new?q="x"');
});

it("still handles rows with no quoting at all", () => {
const map = loadRedirects({});
expect(parseRedirectsCsv("from,to,type\n/a,/b,permanent\n")).toEqual([
{ from: "/a", to: "/b", status: 301 },
]);
expect(map.exact.size).toBe(0);
});

it("cannot rescue an unquoted row whose query holds a comma", () => {
// Documents the boundary: quoting is what makes a comma literal. An export
// that omits the quotes is still shredded, and that is the export's bug.
const [redirect] = parseRedirectsCsv("from,to\n/x?map=a,b\n");
expect(redirect).toMatchObject({ from: "/x?map=a", to: "b" });
});
});

describe("redirect type spelling", () => {
const statusOf = (type: string) => parseRedirectsCsv(`from,to,type\n/a,/b,${type}\n`)[0].status;

it("reads the CSV type case-insensitively", () => {
expect(statusOf("PERMANENT")).toBe(301);
expect(statusOf("Permanent")).toBe(301);
expect(statusOf("permanent")).toBe(301);
expect(statusOf("301")).toBe(301);
});

it("still defaults to temporary", () => {
expect(statusOf("TEMPORARY")).toBe(302);
expect(statusOf("temporary")).toBe(302);
expect(statusOf("")).toBe(302);
expect(parseRedirectsCsv("from,to\n/a,/b\n")[0].status).toBe(302);
});

it("reads the CMS block type case-insensitively too", () => {
const map = loadRedirects({
r: {
__resolveType: "website/loaders/redirect.ts",
redirect: { from: "/a", to: "/b", type: "PERMANENT" },
},
});
expect(matchRedirect("/a", map)?.status).toBe(301);
});
});