url.ts
This file
Path
src/utils/url.ts
319 lines · 8.8 KiB · TypeScript
Last changed by
fix(utils/url): specify the return type of `tryDecodeURI` (#4779)Yusuke Wadabefore adoption80a9837
History of this fileTake it
The walk stopped after 200 commits: lines older than 82bdc4d point at it.
4.9.0Yusuke Wadabefore adoption82bdc4d
lines 1–103why, one step back1/**2 * @module3 * URL utility.4 */56export type Pattern = readonly [string, string, RegExp | true] | '*'78export const splitPath = (path: string): string[] => {9 const paths = path.split('/')10 if (paths[0] === '') {11 paths.shift()12 }13 return paths14}1516export const splitRoutingPath = (routePath: string): string[] => {17 const { groups, path } = extractGroupsFromPath(routePath)1819 const paths = splitPath(path)20 return replaceGroupMarks(paths, groups)21}2223const extractGroupsFromPath = (path: string): { groups: [string, string][]; path: string } => {24 const groups: [string, string][] = []2526 path = path.replace(/\{[^}]+\}/g, (match, index) => {27 const mark = `@${index}`28 groups.push([mark, match])29 return mark30 })3132 return { groups, path }33}3435const replaceGroupMarks = (paths: string[], groups: [string, string][]): string[] => {36 for (let i = groups.length - 1; i >= 0; i--) {37 const [mark] = groups[i]3839 for (let j = paths.length - 1; j >= 0; j--) {40 if (paths[j].includes(mark)) {41 paths[j] = paths[j].replace(mark, groups[i][1])42 break43 }44 }45 }4647 return paths48}4950const patternCache: { [key: string]: Pattern } = {}51export const getPattern = (label: string, next?: string): Pattern | null => {52 // * => wildcard53 // :id{[0-9]+} => ([0-9]+)54 // :id => (.+)5556 if (label === '*') {57 return '*'58 }5960 const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/)61 if (match) {62 const cacheKey = `${label}#${next}`63 if (!patternCache[cacheKey]) {64 if (match[2]) {65 patternCache[cacheKey] =66 next && next[0] !== ':' && next[0] !== '*'67 ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)]68 : [label, match[1], new RegExp(`^${match[2]}$`)]69 } else {70 patternCache[cacheKey] = [label, match[1], true]71 }72 }7374 return patternCache[cacheKey]75 }7677 return null78}7980type Decoder = (str: string) => string81export const tryDecode = (str: string, decoder: Decoder): string => {82 try {83 return decoder(str)84 } catch {85 return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {86 try {87 return decoder(match)88 } catch {89 return match90 }91 })92 }93}9495/**96 * Try to apply decodeURI() to given string.97 * If it fails, skip invalid percent encoding or invalid UTF-8 sequences, and apply decodeURI() to the rest as much as possible.98 * @param str The string to decode.99 * @returns The decoded string that sometimes contains undecodable percent encoding.100 * @example101 * tryDecodeURI('Hello%20World') // 'Hello World'102 * tryDecodeURI('Hello%20World/%A4%A2') // 'Hello World/%A4%A2'103 */fix(utils/url): specify the return type of `tryDecodeURI` (#4779)Yusuke Wadabefore adoption80a9837
line 104why, one step back104export const tryDecodeURI = (str: string): string => tryDecode(str, decodeURI)4.9.0Yusuke Wadabefore adoption82bdc4d
lines 105–107why, one step back105106export const getPath = (request: Request): string => {107 const url = request.urlMerge commit from forkYusuke Wadabefore adoption1d79aed
line 108why, one step back108 const start = url.indexOf('/', url.indexOf(':') + 4)4.9.0Yusuke Wadabefore adoption82bdc4d
lines 109–113why, one step back109 let i = start110 for (; i < url.length; i++) {111 const charCode = url.charCodeAt(i)112 if (charCode === 37) {113 // '%'fix(url): ignore fragment identifiers in getPath() (#4627)Sano Sugurubefore adoption0c1d4c7
line 114why, one step back114 // If the path contains percent encoding, use `indexOf()` to find '?' or '#' and return the result immediately.4.9.0Yusuke Wadabefore adoption82bdc4d
lines 115–116why, one step back115 // Although this is a performance disadvantage, it is acceptable since we prefer cases that do not include percent encoding.116 const queryIndex = url.indexOf('?', i)fix(url): ignore fragment identifiers in getPath() (#4627)Sano Sugurubefore adoption0c1d4c7
lines 117–126why, one step back117 const hashIndex = url.indexOf('#', i)118 const end =119 queryIndex === -1120 ? hashIndex === -1121 ? undefined122 : hashIndex123 : hashIndex === -1124 ? queryIndex125 : Math.min(queryIndex, hashIndex)126 const path = url.slice(start, end)4.9.0Yusuke Wadabefore adoption82bdc4d
line 127why, one step back127 return tryDecodeURI(path.includes('%25') ? path.replace(/%25/g, '%2525') : path)fix(url): ignore fragment identifiers in getPath() (#4627)Sano Sugurubefore adoption0c1d4c7
lines 128–129why, one step back128 } else if (charCode === 63 || charCode === 35) {129 // '?' or '#'4.9.0Yusuke Wadabefore adoption82bdc4d
lines 130–228why, one step back130 break131 }132 }133 return url.slice(start, i)134}135136export const getQueryStrings = (url: string): string => {137 const queryIndex = url.indexOf('?', 8)138 return queryIndex === -1 ? '' : '?' + url.slice(queryIndex + 1)139}140141export const getPathNoStrict = (request: Request): string => {142 const result = getPath(request)143144 // if strict routing is false => `/hello/hey/` and `/hello/hey` are treated the same145 return result.length > 1 && result.at(-1) === '/' ? result.slice(0, -1) : result146}147148/**149 * Merge paths.150 * @param {string[]} ...paths - The paths to merge.151 * @returns {string} The merged path.152 * @example153 * mergePath('/api', '/users') // '/api/users'154 * mergePath('/api/', '/users') // '/api/users'155 * mergePath('/api', '/') // '/api'156 * mergePath('/api/', '/') // '/api/'157 */158export const mergePath: (...paths: string[]) => string = (159 base: string | undefined,160 sub: string | undefined,161 ...rest: string[]162): string => {163 if (rest.length) {164 sub = mergePath(sub as string, ...rest)165 }166 return `${base?.[0] === '/' ? '' : '/'}${base}${167 sub === '/' ? '' : `${base?.at(-1) === '/' ? '' : '/'}${sub?.[0] === '/' ? sub.slice(1) : sub}`168 }`169}170171export const checkOptionalParameter = (path: string): string[] | null => {172 /*173 If path is `/api/animals/:type?` it will return:174 [`/api/animals`, `/api/animals/:type`]175 in other cases it will return null176 */177178 if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(':')) {179 return null180 }181182 const segments = path.split('/')183 const results: string[] = []184 let basePath = ''185186 segments.forEach((segment) => {187 if (segment !== '' && !/\:/.test(segment)) {188 basePath += '/' + segment189 } else if (/\:/.test(segment)) {190 if (/\?/.test(segment)) {191 if (results.length === 0 && basePath === '') {192 results.push('/')193 } else {194 results.push(basePath)195 }196 const optionalSegment = segment.replace('?', '')197 basePath += '/' + optionalSegment198 results.push(basePath)199 } else {200 basePath += '/' + segment201 }202 }203 })204205 return results.filter((v, i, a) => a.indexOf(v) === i)206}207208// Optimized209const _decodeURI = (value: string) => {210 if (!/[%+]/.test(value)) {211 return value212 }213 if (value.indexOf('+') !== -1) {214 value = value.replace(/\+/g, ' ')215 }216 return value.indexOf('%') !== -1 ? tryDecode(value, decodeURIComponent_) : value217}218219const _getQueryParam = (220 url: string,221 key?: string,222 multiple?: boolean223): string | undefined | Record<string, string> | string[] | Record<string, string[]> => {224 let encoded225226 if (!multiple && key && !/[%+]/.test(key)) {227 // optimized for unencoded key228fix(utils/url): make _getQueryParam search behind question mark (#4507)tuzi3040before adoptionfa8eef7
line 229why, one step back229 let keyIndex = url.indexOf('?', 8)4.9.0Yusuke Wadabefore adoption82bdc4d
line 230why, one step back230 if (keyIndex === -1) {fix(utils/url): make _getQueryParam search behind question mark (#4507)tuzi3040before adoptionfa8eef7
lines 231–234why, one step back231 return undefined232 }233 if (!url.startsWith(key, keyIndex + 1)) {234 keyIndex = url.indexOf(`&${key}`, keyIndex + 1)4.9.0Yusuke Wadabefore adoption82bdc4d
lines 235–319why, one step back235 }236 while (keyIndex !== -1) {237 const trailingKeyCode = url.charCodeAt(keyIndex + key.length + 1)238 if (trailingKeyCode === 61) {239 const valueIndex = keyIndex + key.length + 2240 const endIndex = url.indexOf('&', valueIndex)241 return _decodeURI(url.slice(valueIndex, endIndex === -1 ? undefined : endIndex))242 } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {243 return ''244 }245 keyIndex = url.indexOf(`&${key}`, keyIndex + 1)246 }247248 encoded = /[%+]/.test(url)249 if (!encoded) {250 return undefined251 }252 // fallback to default routine253 }254255 const results: Record<string, string> | Record<string, string[]> = {}256 encoded ??= /[%+]/.test(url)257258 let keyIndex = url.indexOf('?', 8)259 while (keyIndex !== -1) {260 const nextKeyIndex = url.indexOf('&', keyIndex + 1)261 let valueIndex = url.indexOf('=', keyIndex)262 if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {263 valueIndex = -1264 }265 let name = url.slice(266 keyIndex + 1,267 valueIndex === -1 ? (nextKeyIndex === -1 ? undefined : nextKeyIndex) : valueIndex268 )269 if (encoded) {270 name = _decodeURI(name)271 }272273 keyIndex = nextKeyIndex274275 if (name === '') {276 continue277 }278279 let value280 if (valueIndex === -1) {281 value = ''282 } else {283 value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? undefined : nextKeyIndex)284 if (encoded) {285 value = _decodeURI(value)286 }287 }288289 if (multiple) {290 if (!(results[name] && Array.isArray(results[name]))) {291 results[name] = []292 }293 ;(results[name] as string[]).push(value)294 } else {295 results[name] ??= value296 }297 }298299 return key ? results[key] : results300}301302export const getQueryParam: (303 url: string,304 key?: string305) => string | undefined | Record<string, string> = _getQueryParam as (306 url: string,307 key?: string308) => string | undefined | Record<string, string>309310export const getQueryParams = (311 url: string,312 key?: string313): string[] | undefined | Record<string, string[]> => {314 return _getQueryParam(url, key, true) as string[] | undefined | Record<string, string[]>315}316317// `decodeURIComponent` is a long name.318// By making it a function, we can use it commonly when minified, reducing the amount of code.319export const decodeURIComponent_ = decodeURIComponent