Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(matcher): avoid prefix overlap for wildcards #92

Merged
merged 2 commits into from Mar 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/matcher.ts
Expand Up @@ -101,7 +101,7 @@ function _matchRoutes(

// Wildcard
for (const [key, value] of _sortRoutesMap(table.wildcard)) {
if (path.startsWith(key)) {
if (path === key || path.startsWith(key + "/")) {
matches.push(value);
}
}
Expand Down Expand Up @@ -139,7 +139,9 @@ function _routerNodeToTable(
node.type === NODE_TYPES.NORMAL &&
!(path.includes("*") || path.includes(":"))
) {
table.static.set(path, node.data);
if (node.data) {
table.static.set(path, node.data);
}
} else if (node.type === NODE_TYPES.WILDCARD) {
table.wildcard.set(path.replace("/**", ""), node.data);
} else if (node.type === NODE_TYPES.PLACEHOLDER) {
Expand Down
30 changes: 30 additions & 0 deletions tests/matcher.test.ts
Expand Up @@ -53,6 +53,8 @@ describe("Route matcher", function () {
"/foo/*/sub",
"/without-trailing",
"/with-trailing/",
"/c/**",
"/cart",
]);

const router = createRouter({ routes });
Expand Down Expand Up @@ -96,6 +98,9 @@ describe("Route matcher", function () {
"/with-trailing" => {
"pattern": "/with-trailing/",
},
"/cart" => {
"pattern": "/cart",
},
},
"wildcard": Map {
"/foo" => {
Expand All @@ -104,6 +109,9 @@ describe("Route matcher", function () {
"/foo/baz" => {
"pattern": "/foo/baz/**",
},
"/c" => {
"pattern": "/c/**",
},
},
}
`);
Expand Down Expand Up @@ -170,6 +178,22 @@ describe("Route matcher", function () {
);
});

it("prefix overlap", () => {
expect(_match("/c/123")).to.toMatchInlineSnapshot(`
[
"/c/**",
]
`);
expect(_match("/c/123")).toMatchObject(_match("/c/123/"))
expect(_match("/c/123")).toMatchObject(_match("/c"))

expect(_match("/cart")).to.toMatchInlineSnapshot(`
[
"/cart",
]
`);
});

it("can be exported", () => {
const jsonData = exportMatcher(matcher);
expect(jsonData).toMatchInlineSnapshot(`
Expand All @@ -192,6 +216,9 @@ describe("Route matcher", function () {
"/": {
"pattern": "/",
},
"/cart": {
"pattern": "/cart",
},
"/foo": {
"pattern": "/foo",
},
Expand All @@ -209,6 +236,9 @@ describe("Route matcher", function () {
},
},
"wildcard": {
"/c": {
"pattern": "/c/**",
},
"/foo": {
"pattern": "/foo/**",
},
Expand Down