diff --git a/src/server/router.ts b/src/server/router.ts index d35ea44c..6239df71 100644 --- a/src/server/router.ts +++ b/src/server/router.ts @@ -1,5 +1,9 @@ import { PARTIAL_SEARCH_PARAM } from "$fresh/src/constants.ts"; import { BaseRoute, ErrorHandlerContext, ServeHandlerInfo } from "./types.ts"; +import { + isIdentifierChar, + isIdentifierStart, +} from "https://esm.sh/@babel/helper-validator-identifier@7.22.20"; type HandlerContext = T & ServeHandlerInfo & { isPartial: boolean; @@ -53,7 +57,7 @@ export type DestinationKind = "internal" | "static" | "route" | "notFound"; // deno-lint-ignore ban-types export type InternalRoute = { baseRoute: BaseRoute; - pattern: URLPattern | string; + pattern: RegExp | string; methods: { [K in KnownMethod]?: MatchHandler }; default?: MatchHandler; destination: DestinationKind; @@ -111,17 +115,121 @@ export function defaultUnknownMethodHandler( }); } +function skipRegex(input: string, idx: number): number { + let open = 0; + + for (let i = idx; i < input.length; i++) { + const char = input[i]; + if (char === "(" || char === "[") { + open++; + } else if (char === ")" || char === "]") { + if (open-- === 0) { + return i; + } + } else if (char === "\\") { + i++; + } + + idx = i; + } + + return idx; +} + +const enum Char { + "(" = 40, + ")" = 41, + "*" = 42, + "/" = 47, + ":" = 58, + "\\" = 92, + "{" = 123, + "}" = 125, +} + +// URLPattern is slow because it always parses the URL first and then matches +// the pattern. Converting it to a regex is faster, see: +// https://github.com/denoland/deno/issues/19861 +export function patternToRegExp(input: string): RegExp { + let tmpPattern = ""; + let pattern = "^"; + + let groupIdx = -1; + + for (let i = 0; i < input.length; i++) { + let ch = input.charCodeAt(i); + + if (groupIdx !== -1) { + if (ch === Char["{"]) { + throw new SyntaxError(`Unexpected token "{"`); + } + if (ch === Char["}"]) { + pattern = tmpPattern + "(?:" + pattern + ")"; + groupIdx = -1; + continue; + } + } + + if (ch === Char["/"]) { + if (pattern === "^") { + pattern += "\\/?"; + } else { + pattern += "\\/"; + } + } else if (ch === Char[":"]) { + const start = i + 1; + ch = input.charCodeAt(++i); + if (!isIdentifierStart(ch)) { + throw new SyntaxError(`Invalid URL pattern: ${input}`); + } + ch = input.charCodeAt(++i); + while (isIdentifierChar(ch)) { + ch = input.charCodeAt(++i); + } + + const name = input.slice(start, i); + + if (ch === Char["("]) { + const end = skipRegex(input, i); + pattern += `(?<${name}>${input.slice(i + 1, end)})`; + i = end; + continue; + } else if (ch === Char["*"]) { + pattern += `(?<${name}>.*?)`; + continue; + } else { + pattern += `(?<${name}>[^/]+)`; + i--; + } + } else if (ch === Char["*"]) { + pattern += ".*?"; + } else if (ch === Char["{"]) { + tmpPattern = pattern; + pattern = ""; + groupIdx = i; + } else { + pattern += input[i]; + } + } + + return new RegExp(pattern + "$", "u"); +} + +export const IS_PATTERN = /[*:{}+?()]/; + function processRoutes( processedRoutes: Array | null>, routes: Routes, destination: DestinationKind, ) { for (const [path, def] of Object.entries(routes)) { + const pattern = destination === "static" || !IS_PATTERN.test(path) + ? path + : patternToRegExp(path); + const entry: InternalRoute = { baseRoute: def.baseRoute, - pattern: destination === "static" - ? path - : new URLPattern({ pathname: path }), + pattern, methods: {}, default: undefined, destination, @@ -163,9 +271,12 @@ export function getParamsAndRoute( return (url: string) => { const urlObject = new URL(url); + const isPartial = urlObject.searchParams.has(PARTIAL_SEARCH_PARAM); const pathname = urlObject.pathname; + const cached = statics.get(pathname); if (cached !== undefined) { + cached.isPartial = isPartial; return cached; } @@ -179,7 +290,7 @@ export function getParamsAndRoute( if (typeof route.pattern === "string") { if (route.pattern === pathname) { processedRoutes[i] = null; - const res = { route: route, params: {}, isPartial: false }; + const res = { route: route, params: {}, isPartial }; statics.set(route.pattern, res); return res; } @@ -187,11 +298,11 @@ export function getParamsAndRoute( continue; } - const res = route.pattern.exec(url); + const res = route.pattern.exec(pathname); if (res !== null) { const groups: Record = {}; - const matched = res?.pathname.groups; + const matched = res?.groups; for (const key in matched) { const value = matched[key]; @@ -203,14 +314,14 @@ export function getParamsAndRoute( return { route: route, params: groups, - isPartial: urlObject.searchParams.has(PARTIAL_SEARCH_PARAM), + isPartial, }; } } return { route: undefined, params: {}, - isPartial: false, + isPartial, }; }; } diff --git a/src/server/router_test.ts b/src/server/router_test.ts new file mode 100644 index 00000000..11016394 --- /dev/null +++ b/src/server/router_test.ts @@ -0,0 +1,39 @@ +import { assertEquals } from "$std/testing/asserts.ts"; +import { IS_PATTERN, patternToRegExp } from "./router.ts"; + +function testPattern(input: string, test: string) { + const regex = patternToRegExp(input); + const match = test.match(regex); + return (match !== null) ? match.groups ?? {} : null; +} + +Deno.test("pathToRegexp", () => { + assertEquals(testPattern("/:path", "/foo"), { path: "foo" }); + assertEquals(testPattern("/:path", "/foo/bar"), null); + assertEquals(testPattern("/:path/bar", "/foo/bar"), { path: "foo" }); + assertEquals(testPattern("/foo/:path", "/foo/bar"), { path: "bar" }); + assertEquals(testPattern("/foo/:path", "/foo"), null); + assertEquals(testPattern("/foo/*", "/foo/asd/asdh/"), {}); + assertEquals(testPattern("/foo{/bar}?", "/foo"), {}); + assertEquals(testPattern("/foo/(\\d+)", "/foo"), null); + assertEquals(testPattern("/foo/(\\d+)", "/foo/1"), {}); + assertEquals(testPattern("/foo/(\\d+)", "/foo/11231"), {}); + assertEquals(testPattern("/foo/(bar)", "/foo/bar"), {}); + assertEquals(testPattern("/foo/:path*", "/foo/bar/asdf"), { + path: "bar/asdf", + }); + assertEquals(testPattern("/movies/:foo@:bar", "/movies/asdf@hehe"), { + foo: "asdf", + bar: "hehe", + }); +}); + +Deno.test("IS_PATTERN", () => { + assertEquals(IS_PATTERN.test("/foo"), false); + assertEquals(IS_PATTERN.test("/foo/bar/baz.jpg"), false); + assertEquals(IS_PATTERN.test("/foo/:path"), true); + assertEquals(IS_PATTERN.test("/foo/*"), true); + assertEquals(IS_PATTERN.test("/foo{/bar}?"), true); + assertEquals(IS_PATTERN.test("/foo/(\\d+)"), true); + assertEquals(IS_PATTERN.test("/foo/(a)"), true); +});