Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

rewrite.ts

93 lines2.7 KB

1import { joinPaths, trimPath } from './path'
2import type { LocationRewrite } from './router'
3​
4/** Compose multiple rewrite pairs into a single in/out rewrite. */
5/** Compose multiple rewrite pairs into a single in/out rewrite. */
6export function composeRewrites(rewrites: Array<LocationRewrite>) {
7 return {
8 input: ({ url }) => {
9 for (const rewrite of rewrites) {
10 url = executeRewriteInput(rewrite, url)
11 }
12 return url
13 },
14 output: ({ url }) => {
15 for (let i = rewrites.length - 1; i >= 0; i--) {
16 url = executeRewriteOutput(rewrites[i], url)
17 }
18 return url
19 },
20 } satisfies LocationRewrite
22​
23/** Create a rewrite pair that strips/adds a basepath on input/output. */
24/** Create a rewrite pair that strips/adds a basepath on input/output. */
25export function rewriteBasepath(opts: {
26 basepath: string
27 caseSensitive?: boolean
28}) {
29 const trimmedBasepath = trimPath(opts.basepath)
30 const normalizedBasepath = `/${trimmedBasepath}`
31 const normalizedBasepathWithSlash = `${normalizedBasepath}/`
32 const checkBasepath = opts.caseSensitive
33 ? normalizedBasepath
34 : normalizedBasepath.toLowerCase()
35 const checkBasepathWithSlash = opts.caseSensitive
36 ? normalizedBasepathWithSlash
37 : normalizedBasepathWithSlash.toLowerCase()
38​
39 return {
40 input: ({ url }) => {
41 const pathname = opts.caseSensitive
42 ? url.pathname
43 : url.pathname.toLowerCase()
44​
45 // Handle exact basepath match (e.g., /my-app -> /)
46 if (pathname === checkBasepath) {
47 url.pathname = '/'
48 } else if (pathname.startsWith(checkBasepathWithSlash)) {
49 // Handle basepath with trailing content (e.g., /my-app/users -> /users)
50 url.pathname = url.pathname.slice(normalizedBasepath.length)
51 }
52 return url
53 },
54 output: ({ url }) => {
55 url.pathname = joinPaths(['/', trimmedBasepath, url.pathname])
56 return url
57 },
58 } satisfies LocationRewrite
60​
61/** Execute a location input rewrite if provided. */
62/** Execute a location input rewrite if provided. */
63export function executeRewriteInput(
64 rewrite: LocationRewrite | undefined,
65 url: URL,
66): URL {
67 const res = rewrite?.input?.({ url })
68 if (res) {
69 if (typeof res === 'string') {
70 return new URL(res)
71 } else if (res instanceof URL) {
72 return res
73 }
74 }
75 return url
77​
78/** Execute a location output rewrite if provided. */
79/** Execute a location output rewrite if provided. */
80export function executeRewriteOutput(
81 rewrite: LocationRewrite | undefined,
82 url: URL,
83): URL {
84 const res = rewrite?.output?.({ url })
85 if (res) {
86 if (typeof res === 'string') {
87 return new URL(res)
88 } else if (res instanceof URL) {
89 return res
90 }
91 }
92 return url