| import type { Key } from 'next/dist/compiled/path-to-regexp' |
| import { regexpToFunction } from 'next/dist/compiled/path-to-regexp' |
| import { pathToRegexp } from 'next/dist/compiled/path-to-regexp' |
|
|
| interface Options { |
| |
| |
| |
| |
| regexModifier?: (regex: string) => string |
| |
| |
| |
| |
| removeUnnamedParams?: boolean |
| |
| |
| |
| |
| strict?: boolean |
|
|
| |
| |
| |
| sensitive?: boolean |
| } |
|
|
| export type PatchMatcher = ( |
| pathname: string, |
| params?: Record<string, any> |
| ) => Record<string, any> | false |
|
|
| |
| |
| |
| |
| |
| export function getPathMatch(path: string, options?: Options): PatchMatcher { |
| const keys: Key[] = [] |
| const regexp = pathToRegexp(path, keys, { |
| delimiter: '/', |
| sensitive: |
| typeof options?.sensitive === 'boolean' ? options.sensitive : false, |
| strict: options?.strict, |
| }) |
|
|
| const matcher = regexpToFunction<Record<string, any>>( |
| options?.regexModifier |
| ? new RegExp(options.regexModifier(regexp.source), regexp.flags) |
| : regexp, |
| keys |
| ) |
|
|
| |
| |
| |
| |
| |
| |
| return (pathname, params) => { |
| |
| if (typeof pathname !== 'string') return false |
|
|
| const match = matcher(pathname) |
|
|
| |
| if (!match) return false |
|
|
| |
| |
| |
| |
| |
| if (options?.removeUnnamedParams) { |
| for (const key of keys) { |
| if (typeof key.name === 'number') { |
| delete match.params[key.name] |
| } |
| } |
| } |
|
|
| return { ...params, ...match.params } |
| } |
| } |
|
|