From bed31d0c219029d44e170bef5c6d053edb2fe0b9 Mon Sep 17 00:00:00 2001 From: CHOYSEN Date: Wed, 8 Mar 2023 13:09:24 +0800 Subject: [PATCH] refactor: only compile rewrite rules once (#2018) --- src/node/plugins/rewritesPlugin.ts | 46 +++++++++++++++--------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/src/node/plugins/rewritesPlugin.ts b/src/node/plugins/rewritesPlugin.ts index d018e310..6cdbe37c 100644 --- a/src/node/plugins/rewritesPlugin.ts +++ b/src/node/plugins/rewritesPlugin.ts @@ -6,31 +6,31 @@ export function resolveRewrites( pages: string[], userRewrites: UserConfig['rewrites'] ) { - const rewriteEntries = Object.entries(userRewrites || {}) - const rewrites = rewriteEntries.length - ? Object.fromEntries( - pages - .map((src) => { - for (const [from, to] of rewriteEntries) { - const dest = rewrite(src, from, to) - if (dest) return [src, dest] - } - }) - .filter((e) => e != null) as [string, string][] - ) - : {} - return { - map: rewrites, - inv: Object.fromEntries(Object.entries(rewrites).map((a) => a.reverse())) + const rewriteRules = Object.entries(userRewrites || {}).map(([from, to]) => ({ + toPath: compile(to), + matchUrl: match(from) + })) + + const pageToRewrite: Record = {} + const rewriteToPage: Record = {} + if (rewriteRules.length) { + for (const page of pages) { + for (const { matchUrl, toPath } of rewriteRules) { + const res = matchUrl(page) + if (res) { + const dest = toPath(res.params) + pageToRewrite[page] = dest + rewriteToPage[dest] = page + break + } + } + } } -} -function rewrite(src: string, from: string, to: string) { - const urlMatch = match(from) - const res = urlMatch(src) - if (!res) return false - const toPath = compile(to) - return toPath(res.params) + return { + map: pageToRewrite, + inv: rewriteToPage + } } export const rewritesPlugin = (config: SiteConfig): Plugin => {