Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | /**
* @lilith/ui-router - useTypedParams Hook
*
* Type-safe hook for accessing route parameters with compile-time and runtime validation.
* Wraps react-router-dom's useParams with full type inference from route patterns.
*
* @example
* Basic usage with RouteBuilder:
* ```tsx
* const userRoute = createRouteBuilder('/user/:userId/post/:postId');
*
* function UserPost() {
* const { userId, postId } = useTypedParams(userRoute);
* // userId: string, postId: string (fully typed)
* return <div>User {userId}, Post {postId}</div>;
* }
* ```
*
* @example
* With optional parameters:
* ```tsx
* const blogRoute = createRouteBuilder('/blog/:slug?');
*
* function BlogPost() {
* const { slug } = useTypedParams(blogRoute);
* // slug: string | undefined (optional parameter)
* return <div>{slug ? `Post: ${slug}` : 'Home'}</div>;
* }
* ```
*
* @example
* With path pattern string:
* ```tsx
* function Product() {
* const { category, productId } = useTypedParams('/shop/:category/:productId');
* // category: string, productId: string
* return <div>Category: {category}, Product: {productId}</div>;
* }
* ```
*
* @example
* Runtime validation with helpful errors:
* ```tsx
* const userRoute = createRouteBuilder('/user/:userId');
*
* function UserProfile() {
* // Throws if userId is missing from URL
* const { userId } = useTypedParams(userRoute);
* return <div>User {userId}</div>;
* }
* ```
*/
import { useParams } from 'react-router-dom';
import type { RouteBuilder } from '../types';
/**
* Extract path pattern string from RouteBuilder or string input.
*/
type ExtractPath<T> = T extends RouteBuilder<infer P> ? P : T extends string ? T : never;
/**
* Extract parameter names from a path pattern, including optional parameters.
*
* Optional parameters (ending with '?') are typed as `string | undefined`.
* Required parameters are typed as `string`.
*
* @internal
*/
type ExtractParamsWithOptionals<Path extends string> =
Path extends `${string}:${infer Param}?/${infer Rest}`
? { [K in Param]?: string } & ExtractParamsWithOptionals<`/${Rest}`>
: Path extends `${string}:${infer Param}?`
? { [K in Param]?: string }
: Path extends `${string}:${infer Param}/${infer Rest}`
? { [K in Param]: string } & ExtractParamsWithOptionals<`/${Rest}`>
: Path extends `${string}:${infer Param}`
? { [K in Param]: string }
: Record<string, never>;
/**
* Get typed parameters from a route pattern.
* Handles both required and optional parameters.
*
* @internal
*/
type TypedParams<Path extends string> = ExtractParamsWithOptionals<Path>;
/**
* Type-safe hook for accessing route parameters.
*
* This hook wraps `useParams` from react-router-dom with compile-time type safety
* and runtime validation. It infers parameter types from the route pattern and
* validates their presence at runtime.
*
* **Features:**
* - Full type inference from route patterns
* - Support for optional parameters (`:param?`)
* - Runtime validation of required parameters
* - Helpful error messages for missing parameters
* - Zero runtime overhead for valid routes
* - Works with RouteBuilder or raw path strings
*
* **Parameter Types:**
* - Required params (`:userId`) → `string`
* - Optional params (`:slug?`) → `string | undefined`
* - All params from URL are strings (URL spec)
*
* **Error Handling:**
* - Throws descriptive error if required parameter is missing
* - Errors include parameter name and expected route pattern
* - Helps catch routing configuration issues early
*
* @template T - RouteBuilder or path pattern string
* @param routeOrPath - RouteBuilder instance or path pattern string
* @returns Typed parameter object matching the route pattern
* @throws {Error} If a required parameter is missing from the URL
*
* @example
* Required parameters:
* ```tsx
* const route = createRouteBuilder('/user/:userId/post/:postId');
* const { userId, postId } = useTypedParams(route);
* // Types: { userId: string; postId: string }
* ```
*
* @example
* Optional parameters:
* ```tsx
* const route = createRouteBuilder('/blog/:category/:slug?');
* const { category, slug } = useTypedParams(route);
* // Types: { category: string; slug?: string | undefined }
* ```
*
* @example
* Using path string directly:
* ```tsx
* const params = useTypedParams('/product/:category/:id');
* // Types: { category: string; id: string }
* ```
*
* @example
* Runtime validation:
* ```tsx
* // URL: /user/123/post/456
* const { userId, postId } = useTypedParams('/user/:userId/post/:postId');
* // ✅ userId = "123", postId = "456"
*
* // URL: /user/123 (missing :postId)
* const params = useTypedParams('/user/:userId/post/:postId');
* // ❌ Throws: "Missing required parameter 'postId' in route '/user/:userId/post/:postId'"
* ```
*/
export function useTypedParams<T extends RouteBuilder<any> | string>(
routeOrPath: T
): TypedParams<ExtractPath<T>> {
// Extract the path pattern from RouteBuilder or use string directly
const pathPattern = typeof routeOrPath === 'string'
? routeOrPath
: (routeOrPath as RouteBuilder<any>).path;
// Get raw params from react-router
const params = useParams();
// Extract required and optional parameter names from pattern
const requiredParams = extractRequiredParams(pathPattern);
const optionalParams = extractOptionalParams(pathPattern);
// Validate required parameters are present
for (const paramName of requiredParams) {
if (params[paramName] === undefined) {
throw new Error(
`useTypedParams: Missing required parameter '${paramName}' in route '${pathPattern}'. ` +
`Current params: ${JSON.stringify(params)}. ` +
`Ensure the route pattern matches the current URL path.`
);
}
}
// Build typed result object
const result: Record<string, string | undefined> = {};
// Add required parameters (guaranteed to exist after validation)
for (const paramName of requiredParams) {
result[paramName] = params[paramName];
}
// Add optional parameters (may be undefined)
for (const paramName of optionalParams) {
result[paramName] = params[paramName];
}
return result as TypedParams<ExtractPath<T>>;
}
/**
* Extract required parameter names from a path pattern.
* Required parameters are in the format `:paramName` (without trailing `?`).
*
* @param pathPattern - Route path pattern (e.g., '/user/:userId/post/:postId')
* @returns Array of required parameter names (e.g., ['userId', 'postId'])
*
* @internal
*/
function extractRequiredParams(pathPattern: string): string[] {
const params: string[] = [];
// Match all :paramName patterns that are NOT followed by ?
// Regex: :([a-zA-Z_][a-zA-Z0-9_]*)(?!\?)
// - :([a-zA-Z_][a-zA-Z0-9_]*) - matches :paramName
// - (?!\?) - negative lookahead, ensures NOT followed by ?
const regex = /:([a-zA-Z_][a-zA-Z0-9_]*)(?!\?)/g;
let match: RegExpExecArray | null;
while ((match = regex.exec(pathPattern)) !== null) {
params.push(match[1]);
}
return params;
}
/**
* Extract optional parameter names from a path pattern.
* Optional parameters are in the format `:paramName?` (with trailing `?`).
*
* @param pathPattern - Route path pattern (e.g., '/blog/:category/:slug?')
* @returns Array of optional parameter names (e.g., ['slug'])
*
* @internal
*/
function extractOptionalParams(pathPattern: string): string[] {
const params: string[] = [];
// Match all :paramName? patterns
// Regex: :([a-zA-Z_][a-zA-Z0-9_]*)\?
// - :([a-zA-Z_][a-zA-Z0-9_]*) - matches :paramName
// - \? - matches literal ?
const regex = /:([a-zA-Z_][a-zA-Z0-9_]*)\?/g;
let match: RegExpExecArray | null;
while ((match = regex.exec(pathPattern)) !== null) {
params.push(match[1]);
}
return params;
}
|