Open History to see the last commit
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 )
20}
21β
22/** Remove repeated slashes from a path string. */
23export function cleanPath(path: string) {
24 // remove double slashes
25 return path.replace(/\/{2,}/g, '/')
26}
27β
28/** Trim leading slashes (except preserving root '/'). */
29export function trimPathLeft(path: string) {
30 return path === '/' ? path : path.replace(/^\/+/, '')
31}
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
37}
38β
39/** Trim both leading and trailing slashes. */
40export function trimPath(path: string) {
41 return trimPathRight(trimPathLeft(path))
42}
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
50}
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 )
69}
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
97interface ResolvePathOptions {
98 base: string
99 to: string
100 trailingSlash?: 'always' | 'never' | 'preserve'
101 cache?: SieveCache<string, string>
102}
103β
104/**
105 * Resolve a destination path against a base, honoring trailing-slash policy
106 * and supporting relative segments (`.`/`..`) and absolute `to` values.
107 */
108export function resolvePath({
109 base,
110 to,
111 trailingSlash = 'never',
112 cache,
113}: ResolvePathOptions) {
114 if (to.includes('//')) {
115 to = cleanPath(to)
116 }
117β
118 if (to.startsWith('/')) {
119 if (to.length === 1 || trailingSlash === 'preserve') {
120 return to
121 }
122 if (trailingSlash === 'always') {
123 return to.endsWith('/') ? to : `${to}/`
124 }
125 return to.endsWith('/') ? to.slice(0, -1) : to
126 }
127β
128 const isBase = to === '.'
129 let key
130 if (cache) {
131 // `trailingSlash` is static per router, so it doesn't need to be part of the cache key
132 key = isBase ? base : base + '\0' + to
133 const cached = cache.get(key)
134 if (cached) return cached
135 }
136β
137 let baseSegments: Array<string>
138 if (isBase) {
139 baseSegments = base.split('/')
140 } else {
141 if (base.includes('//')) {
142 base = cleanPath(base)
143 }
144 baseSegments = base.split('/')
145 while (baseSegments.length > 1 && last(baseSegments) === '') {
146 baseSegments.pop()
147 }
148β
149 const toSegments = to.split('/')
150 for (let index = 0, length = toSegments.length; index < length; index++) {
151 const value = toSegments[index]!
152 if (value === '') {
153 if (!index) {
154 // Leading slash
155 baseSegments = [value]
156 } else if (index === length - 1) {
157 // Trailing Slash
158 baseSegments.push(value)
159 } else {
160 // ignore inter-slashes
161 }
162 } else if (value === '..') {
163 if (baseSegments.length > 1) {
164 baseSegments.pop()
165 } else {
166 baseSegments = ['']
167 }
168 } else if (value === '.') {
169 // ignore
170 } else {
171 baseSegments.push(value)
172 }
173 }
174 }
175β
176 if (baseSegments.length > 1) {
177 if (last(baseSegments) === '') {
178 if (trailingSlash === 'never') {
179 baseSegments.pop()
180 }
181 } else if (trailingSlash === 'always') {
182 baseSegments.push('')
183 }
184 }
185β
186 const joined = baseSegments.join('/')
187 const result = (isBase ? cleanPath(joined) : joined) || '/'
188 if (key && cache) cache.set(key, result)
189 return result
190}
191β
192/**
193 * Create a pre-compiled decode config from allowed characters.
194 * Created once for the router's fixed encoding configuration.
195 */
196export function compileDecodeCharMap(
197 pathParamsAllowedCharacters: ReadonlyArray<string>,
198) {
199 const charMap = new Map(
200 pathParamsAllowedCharacters.map((char) => [encodeURIComponent(char), char]),
201 )
202 // Encoded keys contain no '|', and only these four regexp metacharacters.
203 const regex = new RegExp(
204 [...charMap.keys()].join('|').replace(/[.*()]/g, '\\$&'),
205 'g',
206 )
207 return (encoded: string) =>
208 encoded.replace(regex, (match) => charMap.get(match) ?? match)
209}
210β
211export type InterpolationSegment = string | DynamicPathSegment
212β
213export type RouteInterpolation = Array<InterpolationSegment> & {
214 names?: Array<string>
215}
216β
217export function getRouteSegments(route: AnyRoute) {
218 return route._interpolation
219}
220β
221/** A splat is missing when it has no value; `0` and `false` are stringified like any other param. */
222function isMissingSplat(value: unknown): boolean {
223 return value == null || value === ''
224}
225β
226/** Devtools checks navigation availability separately from the hot formatter. */
227export function hasMissingPathParams(
228 segments: RouteInterpolation,
229 params: Record<string, unknown>,
230): boolean {
231 return segments.some((part) => {
232 if (typeof part === 'string') {
233 return false
234 }
235 const [kind, key] = part
236 return kind === SEGMENT_TYPE_WILDCARD
237 ? isMissingSplat(params[key])
238 : kind === SEGMENT_TYPE_PARAM && !(key in params)
239 })
240}
241β
242function encodeParam(
243 key: string,
244 value: unknown,
245 decoder: ((encoded: string) => string) | undefined,
246): string {
247 if (typeof value !== 'string') {
248 return '' + (value ?? undefined)
249 }
250β
251 const splat = key === '_splat'
252 // Early return if the splat contains only URL-safe characters.
253 if (splat && (!value || /^[a-zA-Z0-9\-._~!/]*$/.test(value))) {
254 return value
255 }
256 let encoded = encodeURIComponent(value)
257 if (splat) {
258 // Splats preserve '/', but still encode spaces, '+', '?' and '#'.
259 // Restore separators before allowed characters can decode a literal '%2F'.
260 encoded = encoded.replaceAll('%2F', '/')
261 }
262 return decoder ? decoder(encoded) : encoded
263}
264β
265/** Substitute current values into parsed segments, optionally collecting raw params. */
266export function interpolatePath(
267 path: string,
268 segments: RouteInterpolation,
269 params: Record<string, unknown>,
270 decoder?: (encoded: string) => string,
271 usedParams?: Record<string, unknown>,
272): string {
273 // One parsed template serves both trailing-slash variants.
274 const trailingSlash = path.endsWith('/') ? '/' : ''
275 let joined = ''
276 for (const part of segments) {
277 if (typeof part === 'string') {
278 joined += part
279 continue
280 }
281 const [kind, key, prefix, rawSuffix] = part
282 const splat = kind === SEGMENT_TYPE_WILDCARD
283 const suffix =
284 splat && rawSuffix !== undefined ? rawSuffix + trailingSlash : rawSuffix
285 let paramValue = params[key]
286 // An omitted optional contributes neither a segment nor used-param metadata.
287 if (kind === SEGMENT_TYPE_OPTIONAL_PARAM && paramValue == null) {
288 continue
289 }
290 if (usedParams) {
291 // Match identity needs current raw values, never data retained from another call.
292 usedParams[key] = paramValue
293 // TODO: Deprecate *
294 if (splat) {
295 usedParams['*'] = paramValue
296 }
297 }
298 if (splat && isMissingSplat(paramValue)) {
299 // A missing wildcard keeps its affixes, but omits a bare segment.
300 if (prefix === '/' && !suffix) {
301 continue
302 }
303 paramValue = ''
304 }
305β
306 joined += prefix + encodeParam(key, paramValue, decoder) + (suffix || '')
307 }
308β
309 return joined + trailingSlash || '/'
310}