Skip to content
Open
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
7 changes: 2 additions & 5 deletions src/cases.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,10 +389,7 @@ export const MATCH_TESTS: MatchTestSet[] = [
},
{ input: "/route", expected: false },
{ input: "/test", expected: false },
{
input: "/test//",
expected: { path: "/test//", params: {} },
},
{ input: "/test//", expected: false },
],
},
{
Expand Down Expand Up @@ -632,7 +629,7 @@ export const MATCH_TESTS: MatchTestSet[] = [
},
{
input: "/test//",
expected: { path: "/test//", params: {} },
expected: { path: "/test/", params: {} },
},
{
input: "/test/route",
Expand Down
11 changes: 8 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -464,21 +464,21 @@ export function pathToRegexp(
}

const data = typeof path === "object" ? path : parse(path, options);
const originalPath = data.originalPath;
flatten(data.tokens, 0, [], (tokens) => {
if (combinations >= 256) {
throw new PathError("Too many path combinations", data.originalPath);
throw new PathError("Too many path combinations", originalPath);
}

if (combinations > 0) source += "|";
source += toRegExpSource(tokens, delimiter, keys, data.originalPath);
source += toRegExpSource(tokens, delimiter, keys, originalPath, trailing);
combinations++;
});
}

process(path);

let pattern = `^(?:${source})`;
if (trailing) pattern += "(?:" + escape(delimiter) + "$)?";
pattern += end ? "$" : "(?=" + escape(delimiter) + "|$)";

return { regexp: new RegExp(pattern, sensitive ? "" : "i"), keys };
Expand Down Expand Up @@ -519,6 +519,7 @@ function toRegExpSource(
delimiter: string,
keys: Keys,
originalPath: string | undefined,
trailing: boolean,
): string {
let result = "";
let backtrack = "";
Expand Down Expand Up @@ -598,6 +599,10 @@ function toRegExpSource(
throw new TypeError(`Unknown token type: ${(token as any).type}`);
}

if (trailing && !backtrack.endsWith(delimiter)) {
result += "(?:" + escape(delimiter) + "$)?";
}

return result;
}

Expand Down