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

path.ts

306 lines8.6 KB

1import { last } from './utils'
2import {
3 SEGMENT_TYPE_OPTIONAL_PARAM,
4 SEGMENT_TYPE_PARAM,
5 SEGMENT_TYPE_WILDCARD,
6} from './new-process-route-tree'
7import type { SieveCache } from './sieve-cache'
8import type { DynamicPathSegment } from './new-process-route-tree'
9import type { AnyRoute } from './route'
10​
11/** Join path segments, cleaning duplicate slashes between parts. */
12export function joinPaths(paths: Array<string | undefined>) {
13 return cleanPath(
14 paths
15 .filter((val) => {
16 return val !== undefined
17 })
18 .join('/'),
19 )
21​
22/** Remove repeated slashes from a path string. */
23export function cleanPath(path: string) {
24 // remove double slashes
25 return path.replace(/\/{2,}/g, '/')
27​
28/** Trim leading slashes (except preserving root '/'). */
29export function trimPathLeft(path: string) {
30 return path === '/' ? path : path.replace(/^\/+/, '')
32​
33/** Trim trailing slashes (except preserving root '/'). */
34export function trimPathRight(path: string) {
35 const len = path.length
36 return len > 1 && path[len - 1] === '/' ? path.replace(/\/+$/, '') : path
38​
39/** Trim both leading and trailing slashes. */
40export function trimPath(path: string) {
41 return trimPathRight(trimPathLeft(path))
43​
44/** Remove a trailing slash from value when appropriate for comparisons. */
45export function removeTrailingSlash(value: string, basepath: string): string {
46 if (value?.endsWith('/') && value !== '/' && value !== `${basepath}/`) {
47 return value.slice(0, -1)
48 }
49 return value
51​
52// intended to only compare path name
53// see the usage in the isActive under useLinkProps
54// /sample/path1 = /sample/path1/
55// /sample/path1/some <> /sample/path1
56/**
57 * Compare two pathnames for exact equality after normalizing trailing slashes
58 * relative to the provided `basepath`.
59 */
60export function exactPathTest(
61 pathName1: string,
62 pathName2: string,
63 basepath: string,
64): boolean {
65 return (
66 removeTrailingSlash(pathName1, basepath) ===
67 removeTrailingSlash(pathName2, basepath)
68 )
70​
71// When resolving relative paths, we treat all paths as if they are trailing slash
72// documents. All trailing slashes are removed after the path is resolved.
73// Here are a few examples:
74//
75// /a/b/c + ./d = /a/b/c/d
76// /a/b/c + ../d = /a/b/d
77// /a/b/c + ./d/ = /a/b/c/d
78// /a/b/c + ../d/ = /a/b/d
79// /a/b/c + ./ = /a/b/c
80//
81// Absolute paths that start with `/` short circuit the resolution process to the root
82// path.
83//
84// Here are some examples:
85//
86// /a/b/c + /d = /d
87// /a/b/c + /d/ = /d
88// /a/b/c + / = /
89//
90// Non-.-prefixed paths are still treated as relative paths, resolved like `./`
91//
92// Here are some examples:
93//
94// /a/b/c + d = /a/b/c/d
95// /a/b/c + d/ = /a/b/c/d
96// /a/b/c + d/e = /a/b/c/d/e
97/**
98 * Resolve a destination path against a base, honoring trailing-slash policy
99 * and supporting relative segments (`.`/`..`) and absolute `to` values.
100 *
101 * Internal: parameters are positional so the router's hot callers pass no
102 * options object.
103 */
104export function resolvePath(
105 base: string,
106 to: string,
107 trailingSlash: 'always' | 'never' | 'preserve' = 'never',
108 cache?: SieveCache<string, string>,
109) {
110 if (to.includes('//')) {
111 to = cleanPath(to)
112 }
113​
114 if (to.startsWith('/')) {
115 if (to.length === 1 || trailingSlash === 'preserve') {
116 return to
117 }
118 if (trailingSlash === 'always') {
119 return to.endsWith('/') ? to : `${to}/`
120 }
121 return to.endsWith('/') ? to.slice(0, -1) : to
122 }
123​
124 const isBase = to === '.'
125 let key
126 if (cache) {
127 // `trailingSlash` is static per router, so it doesn't need to be part of the cache key
128 key = isBase ? base : base + '\0' + to
129 const cached = cache.get(key)
130 if (cached) return cached
131 }
132​
133 let baseSegments: Array<string>
134 if (isBase) {
135 baseSegments = base.split('/')
136 } else {
137 if (base.includes('//')) {
138 base = cleanPath(base)
139 }
140 baseSegments = base.split('/')
141 while (baseSegments.length > 1 && last(baseSegments) === '') {
142 baseSegments.pop()
143 }
144​
145 const toSegments = to.split('/')
146 for (let index = 0, length = toSegments.length; index < length; index++) {
147 const value = toSegments[index]!
148 if (value === '') {
149 if (!index) {
150 // Leading slash
151 baseSegments = [value]
152 } else if (index === length - 1) {
153 // Trailing Slash
154 baseSegments.push(value)
155 } else {
156 // ignore inter-slashes
157 }
158 } else if (value === '..') {
159 if (baseSegments.length > 1) {
160 baseSegments.pop()
161 } else {
162 baseSegments = ['']
163 }
164 } else if (value === '.') {
165 // ignore
166 } else {
167 baseSegments.push(value)
168 }
169 }
170 }
171​
172 if (baseSegments.length > 1) {
173 if (last(baseSegments) === '') {
174 if (trailingSlash === 'never') {
175 baseSegments.pop()
176 }
177 } else if (trailingSlash === 'always') {
178 baseSegments.push('')
179 }
180 }
181​
182 const joined = baseSegments.join('/')
183 const result = (isBase ? cleanPath(joined) : joined) || '/'
184 if (key && cache) cache.set(key, result)
185 return result
187​
188/**
189 * Create a pre-compiled decode config from allowed characters.
190 * Created once for the router's fixed encoding configuration.
191 */
192export function compileDecodeCharMap(
193 pathParamsAllowedCharacters: ReadonlyArray<string>,
194) {
195 const charMap = new Map(
196 pathParamsAllowedCharacters.map((char) => [encodeURIComponent(char), char]),
197 )
198 // Encoded keys contain no '|', and only these four regexp metacharacters.
199 const regex = new RegExp(
200 [...charMap.keys()].join('|').replace(/[.*()]/g, '\\$&'),
201 'g',
202 )
203 return (encoded: string) =>
204 encoded.replace(regex, (match) => charMap.get(match) ?? match)
206​
207export type InterpolationSegment = string | DynamicPathSegment
208​
209export type RouteInterpolation = Array<InterpolationSegment> & {
210 names?: Array<string>
212​
213export function getRouteSegments(route: AnyRoute) {
214 return route._interpolation
216​
217/** A splat is missing when it has no value; `0` and `false` are stringified like any other param. */
218function isMissingSplat(value: unknown): boolean {
219 return value == null || value === ''
221​
222/** Devtools checks navigation availability separately from the hot formatter. */
223export function hasMissingPathParams(
224 segments: RouteInterpolation,
225 params: Record<string, unknown>,
226): boolean {
227 return segments.some((part) => {
228 if (typeof part === 'string') {
229 return false
230 }
231 const [kind, key] = part
232 return kind === SEGMENT_TYPE_WILDCARD
233 ? isMissingSplat(params[key])
234 : kind === SEGMENT_TYPE_PARAM && !(key in params)
235 })
237​
238function encodeParam(
239 key: string,
240 value: unknown,
241 decoder: ((encoded: string) => string) | undefined,
242): string {
243 if (typeof value !== 'string') {
244 return '' + (value ?? undefined)
245 }
246​
247 const splat = key === '_splat'
248 // Early return if the splat contains only URL-safe characters.
249 if (splat && (!value || /^[a-zA-Z0-9\-._~!/]*$/.test(value))) {
250 return value
251 }
252 let encoded = encodeURIComponent(value)
253 if (splat) {
254 // Splats preserve '/', but still encode spaces, '+', '?' and '#'.
255 // Restore separators before allowed characters can decode a literal '%2F'.
256 encoded = encoded.replaceAll('%2F', '/')
257 }
258 return decoder ? decoder(encoded) : encoded
260​
261/** Substitute current values into parsed segments, optionally collecting raw params. */
262export function interpolatePath(
263 path: string,
264 segments: RouteInterpolation,
265 params: Record<string, unknown>,
266 decoder?: (encoded: string) => string,
267 usedParams?: Record<string, unknown>,
268): string {
269 // One parsed template serves both trailing-slash variants.
270 const trailingSlash = path.endsWith('/') ? '/' : ''
271 let joined = ''
272 for (const part of segments) {
273 if (typeof part === 'string') {
274 joined += part
275 continue
276 }
277 const [kind, key, prefix, rawSuffix] = part
278 const splat = kind === SEGMENT_TYPE_WILDCARD
279 const suffix =
280 splat && rawSuffix !== undefined ? rawSuffix + trailingSlash : rawSuffix
281 let paramValue = params[key]
282 // An omitted optional contributes neither a segment nor used-param metadata.
283 if (kind === SEGMENT_TYPE_OPTIONAL_PARAM && paramValue == null) {
284 continue
285 }
286 if (usedParams) {
287 // Match identity needs current raw values, never data retained from another call.
288 usedParams[key] = paramValue
289 // TODO: Deprecate *
290 if (splat) {
291 usedParams['*'] = paramValue
292 }
293 }
294 if (splat && isMissingSplat(paramValue)) {
295 // A missing wildcard keeps its affixes, but omits a bare segment.
296 if (prefix === '/' && !suffix) {
297 continue
298 }
299 paramValue = ''
300 }
301​
302 joined += prefix + encodeParam(key, paramValue, decoder) + (suffix || '')
303 }
304​
305 return joined + trailingSlash || '/'