|
2 | 2 | /** @import { ResolveArgs } from './types.js' */ |
3 | 3 | import { base, assets, hash_routing } from './internal/client.js'; |
4 | 4 | import { resolve_route } from '../../../utils/routing.js'; |
| 5 | +import { decode_params } from '../../../utils/url.js'; |
| 6 | +import { get_routes } from '../../client/client.js'; |
5 | 7 |
|
6 | 8 | /** |
7 | 9 | * Resolve the URL of an asset in your `static` directory, by prefixing it with [`config.kit.paths.assets`](https://svelte.dev/docs/kit/configuration#paths) if configured, or otherwise by prefixing it with the base path. |
@@ -58,4 +60,40 @@ export function resolve(...args) { |
58 | 60 | ); |
59 | 61 | } |
60 | 62 |
|
| 63 | +/** |
| 64 | + * Match a pathname to a route ID and extracts any parameters. |
| 65 | + * |
| 66 | + * @example |
| 67 | + * ```js |
| 68 | + * import { match } from '$app/paths'; |
| 69 | + * |
| 70 | + * const result = await match('/blog/hello-world'); |
| 71 | + * // → { id: '/blog/[slug]', params: { slug: 'hello-world' } } |
| 72 | + * |
| 73 | + * |
| 74 | + * @param {Pathname} pathname |
| 75 | + * @returns {Promise<{ id: RouteId, params: Record<string, string> } | null>} |
| 76 | + */ |
| 77 | +export async function match(pathname) { |
| 78 | + let path = pathname; |
| 79 | + |
| 80 | + if (base && path.startsWith(base)) { |
| 81 | + path = path.slice(base.length) || '/'; |
| 82 | + } |
| 83 | + |
| 84 | + if (hash_routing && path.startsWith('#')) { |
| 85 | + path = path.slice(1) || '/'; |
| 86 | + } |
| 87 | + |
| 88 | + const routes = get_routes(); |
| 89 | + for (const route of routes) { |
| 90 | + const params = route.exec(path); |
| 91 | + if (params) { |
| 92 | + return { id: /** @type {RouteId} */ (route.id), params: decode_params(params) }; |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + return null; |
| 97 | +} |
| 98 | + |
61 | 99 | export { base, assets, resolve as resolveRoute }; |
0 commit comments