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 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 | 12x 12x 1x 1x 64x 4x 60x 4x 1x 56x 4x 52x 1x 64x 64x 4x 1x | /**
* @lilith/ui-router - Type System
*
* Comprehensive type-safe routing system for the Lilith Platform.
* Supports both simple static routes and complex parameterized routes
* with full type safety for path parameters, query parameters, and access control.
*
* Based on react-router-dom v7 types and analysis of 6+ routing patterns:
* - Constants-as-types (landing feature)
* - Lookup tables (marketplace RouterLookupTable)
* - Path parameter extraction
* - Query parameter handling
* - Route metadata and access control
*/
import * as React from 'react';
import type { Params, To } from 'react-router-dom';
import type { ComponentType, ReactNode, ReactElement } from 'react';
// ============================================================================
// Path Parameter Utilities
// ============================================================================
/**
* Extract path parameter names from a route pattern.
*
* @example
* ```typescript
* type ProfileParams = ExtractPathParams<'/profile/:userId/:section'>;
* // Result: { userId: string; section: string }
*
* type ProductParams = ExtractPathParams<'/shop/:category/:productId'>;
* // Result: { category: string; productId: string }
* ```
*/
export type ExtractPathParams<Path extends string> =
Path extends `${infer _Start}:${infer Param}/${infer Rest}`
? { [K in Param | keyof ExtractPathParams<`/${Rest}`>]: string }
: Path extends `${infer _Start}:${infer Param}`
? { [K in Param]: string }
: Record<string, never>;
/**
* Check if a route pattern has path parameters.
*
* @example
* ```typescript
* type HasParams1 = HasPathParams<'/profile/:userId'>; // true
* type HasParams2 = HasPathParams<'/about'>; // false
* ```
*/
export type HasPathParams<Path extends string> = Path extends `${string}:${string}`
? true
: false;
/**
* Type-safe path parameters extracted from a route pattern.
* Compatible with react-router-dom's Params type.
*
* @example
* ```typescript
* const params: PathParams<'/user/:id/post/:postId'> = {
* id: '123',
* postId: 'abc',
* };
* ```
*/
export type PathParams<Path extends string> = HasPathParams<Path> extends true
? ExtractPathParams<Path>
: Record<string, never>;
// ============================================================================
// Query Parameter Types
// ============================================================================
/**
* Base query parameter value types.
* Supports strings, numbers, booleans, and arrays.
*/
export type QueryParamValue = string | number | boolean | null | undefined;
/**
* Query parameter object with typed values.
* Use this for defining expected query parameters for a route.
*
* @example
* ```typescript
* type SearchQuery = QueryParams<{
* q: string;
* page: number;
* filter: string[];
* sort: 'asc' | 'desc';
* }>;
* ```
*/
export type QueryParams<T extends Record<string, QueryParamValue | QueryParamValue[]>> = {
[K in keyof T]?: T[K];
};
/**
* Helper to create URLSearchParams from typed query object.
*
* @example
* ```typescript
* const query: QueryParams<{ page: number; sort: string }> = {
* page: 2,
* sort: 'desc',
* };
* const searchParams = toSearchParams(query);
* // URLSearchParams: ?page=2&sort=desc
* ```
*/
export function toSearchParams<T extends Record<string, QueryParamValue | QueryParamValue[]>>(
params: QueryParams<T>
): URLSearchParams {
const searchParams = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value === null || value === undefined) continue;
if (Array.isArray(value)) {
value.forEach((v) => {
if (v !== null && v !== undefined) {
searchParams.append(key, String(v));
}
});
} else {
searchParams.set(key, String(value));
}
}
return searchParams;
}
/**
* Helper to parse URLSearchParams into typed query object.
*
* @example
* ```typescript
* const searchParams = new URLSearchParams('?page=2&sort=desc');
* const query = fromSearchParams<{ page: string; sort: string }>(searchParams);
* // Result: { page: '2', sort: 'desc' }
* ```
*/
export function fromSearchParams<T extends Record<string, QueryParamValue | QueryParamValue[]>>(
searchParams: URLSearchParams
): Partial<T> {
const result: Record<string, QueryParamValue | QueryParamValue[]> = {};
searchParams.forEach((value, key) => {
const existing = result[key];
if (existing === undefined) {
result[key] = value;
} else if (Array.isArray(existing)) {
existing.push(value);
} else {
result[key] = [existing as string, value];
}
});
return result as Partial<T>;
}
// ============================================================================
// Access Control Types
// ============================================================================
/**
* Access level categories for route-based access control.
* Defines who can access a route based on authentication and role.
*
* @example
* ```typescript
* const route: RouteDefinition<'/admin', never, 'admin'> = {
* path: '/admin',
* accessLevel: 'admin',
* meta: { title: 'Admin Dashboard' },
* };
* ```
*/
export type AccessLevel = 'public' | 'guest' | 'authenticated' | 'user' | 'admin';
/**
* Profile-based access control keys.
* Used in features like marketplace for profile-specific routing.
*
* @example
* ```typescript
* const route: RouteDefinition<'/dashboard', never, 'user', 'escort_worker'> = {
* path: '/dashboard',
* accessLevel: 'user',
* profileKey: 'escort_worker',
* meta: { title: 'Worker Dashboard' },
* };
* ```
*/
export type ProfileKey = string | null;
/**
* Access gate configuration for route-level access control.
* Defines conditions that must be met to access a route.
*
* @example
* ```typescript
* const accessGate: AccessGate = {
* level: 'authenticated',
* profiles: ['escort_worker', 'escort_client'],
* permissions: ['marketplace.view'],
* redirect: '/login',
* };
* ```
*/
export interface AccessGate<
TAccessLevel extends AccessLevel = AccessLevel,
TProfileKey extends ProfileKey = ProfileKey,
> {
/**
* Required access level to view this route.
*/
level: TAccessLevel;
/**
* Optional profile keys that can access this route.
* If undefined, all profiles with the required access level can access.
*/
profiles?: TProfileKey[];
/**
* Optional permission strings required to access this route.
* Uses dot notation: 'feature.action' (e.g., 'marketplace.create_listing')
*/
permissions?: string[];
/**
* Where to redirect if access is denied.
* Can be a static path or a function that returns a path based on context.
*/
redirect?: string | ((context: AccessGateContext) => string);
/**
* Optional custom validation function.
* Return true to grant access, false to deny.
*/
validate?: (context: AccessGateContext) => boolean | Promise<boolean>;
}
/**
* Context provided to access gate validation functions.
*/
export interface AccessGateContext {
/**
* Current user's access level.
*/
accessLevel: AccessLevel;
/**
* Current user's profile key.
*/
profileKey: ProfileKey;
/**
* Current user's permissions.
*/
permissions: string[];
/**
* Current route path being accessed.
*/
path: string;
/**
* Path parameters from the route.
*/
params: Params;
/**
* Query parameters from the URL.
*/
query: URLSearchParams;
}
// ============================================================================
// Route Metadata Types
// ============================================================================
/**
* Common metadata attached to route definitions.
* Extends this interface in your feature for custom metadata.
*
* @example
* ```typescript
* interface MyRouteMeta extends RouteMeta {
* analytics: {
* category: string;
* action: string;
* };
* breadcrumb: string;
* }
* ```
*/
export interface RouteMeta {
/**
* Human-readable title for the route.
* Used for <title> tags, breadcrumbs, navigation labels.
*/
title?: string;
/**
* Description of the route.
* Used for meta tags, tooltips, documentation.
*/
description?: string;
/**
* Icon identifier for the route.
* Can be icon name, emoji, or component key.
*/
icon?: string;
/**
* Tags for categorizing routes.
* Useful for filtering, searching, or grouping routes.
*/
tags?: string[];
/**
* Whether this route should be hidden from navigation menus.
*/
hidden?: boolean;
/**
* Display order for navigation menus (lower = earlier).
*/
order?: number;
/**
* Custom metadata - extend as needed.
*/
[key: string]: unknown;
}
// ============================================================================
// Route Definition Types
// ============================================================================
/**
* Complete route definition with path, parameters, access control, and metadata.
*
* @template TPath - Route path pattern (e.g., '/user/:id')
* @template TQuery - Query parameter schema
* @template TAccessLevel - Required access level
* @template TProfileKey - Required profile key
* @template TMeta - Route metadata schema
*
* @example
* ```typescript
* const userRoute: RouteDefinition<
* '/user/:userId',
* { tab?: string },
* 'authenticated',
* never,
* { breadcrumb: string }
* > = {
* path: '/user/:userId',
* accessGate: {
* level: 'authenticated',
* redirect: '/login',
* },
* meta: {
* title: 'User Profile',
* breadcrumb: 'Profile',
* },
* };
* ```
*/
export interface RouteDefinition<
TPath extends string = string,
TQuery extends Record<string, QueryParamValue | QueryParamValue[]> = Record<
string,
QueryParamValue
>,
TAccessLevel extends AccessLevel = AccessLevel,
TProfileKey extends ProfileKey = ProfileKey,
TMeta extends RouteMeta = RouteMeta,
> {
/**
* Route path pattern.
* Supports react-router path syntax: '/path/:param/*splat'
*/
path: TPath;
/**
* Access gate configuration for this route.
* If undefined, route is public.
*/
accessGate?: AccessGate<TAccessLevel, TProfileKey>;
/**
* Route metadata.
*/
meta?: TMeta;
/**
* Expected query parameter schema.
* Used for type-safe query parameter handling.
*/
querySchema?: TQuery;
/**
* Parent route path (for nested routes).
*/
parent?: string;
/**
* Child route definitions (for nested routes).
* Uses simplified type to avoid circular reference.
*/
children?: Array<{
path: string;
meta?: RouteMeta;
accessGate?: AccessGate;
}>;
}
// ============================================================================
// Route Builder Types
// ============================================================================
/**
* Type-safe route builder for constructing paths with parameters.
*
* @template TPath - Route path pattern
* @template TQuery - Query parameter schema
*
* @example
* ```typescript
* const userRoute: RouteBuilder<'/user/:userId', { tab?: string }> = {
* path: '/user/:userId',
* build: (params, query) => {
* // params is typed: { userId: string }
* // query is typed: { tab?: string }
* return `/user/${params.userId}?tab=${query?.tab || 'profile'}`;
* },
* };
* ```
*/
export interface RouteBuilder<
TPath extends string = string,
TQuery extends Record<string, QueryParamValue | QueryParamValue[]> = Record<
string,
QueryParamValue
>,
> {
/**
* Route path pattern.
*/
path: TPath;
/**
* Build a complete URL from path and query parameters.
*/
build: (
params: PathParams<TPath>,
query?: QueryParams<TQuery>
) => string;
/**
* Parse a URL into path and query parameters.
*/
parse?: (url: string) => {
params: PathParams<TPath>;
query: QueryParams<TQuery>;
};
}
/**
* Helper function to create a type-safe route builder.
*
* @example
* ```typescript
* const profileRoute = createRouteBuilder('/profile/:userId/:section', {
* querySchema: { tab: 'string' as const },
* });
*
* // Type-safe path building
* const url = profileRoute.build(
* { userId: '123', section: 'posts' },
* { tab: 'recent' }
* );
* // Result: '/profile/123/posts?tab=recent'
* ```
*/
export function createRouteBuilder<
TPath extends string,
TQuery extends Record<string, QueryParamValue | QueryParamValue[]> = Record<
string,
QueryParamValue
>,
>(
path: TPath,
_options?: {
querySchema?: TQuery;
}
): RouteBuilder<TPath, TQuery> {
return {
path,
build: (params, query) => {
// Replace path parameters
let builtPath = path as string;
for (const [key, value] of Object.entries(params)) {
builtPath = builtPath.replace(`:${key}`, encodeURIComponent(String(value)));
}
// Append query parameters
if (query && Object.keys(query).length > 0) {
const searchParams = toSearchParams(query);
const queryString = searchParams.toString();
if (queryString) {
builtPath += `?${queryString}`;
}
}
return builtPath;
},
parse: (url: string) => {
const urlObj = new URL(url, 'http://localhost'); // Base URL for parsing
const pathname = urlObj.pathname;
// Extract path parameters by matching pattern
const pathPattern = path.replace(/:([^/]+)/g, '([^/]+)');
const regex = new RegExp(`^${pathPattern}$`);
const match = pathname.match(regex);
const params: Record<string, string> = {};
if (match) {
const paramNames = (path.match(/:([^/]+)/g) || []).map((p) => p.slice(1));
paramNames.forEach((name, index) => {
params[name] = decodeURIComponent(match[index + 1]);
});
}
// Extract query parameters
const query = fromSearchParams<TQuery>(urlObj.searchParams);
return {
params: params as PathParams<TPath>,
query,
};
},
};
}
// ============================================================================
// Route Registry Types
// ============================================================================
/**
* Route registry entry for storing and looking up routes.
*
* @example
* ```typescript
* const registryEntry: RouteRegistryEntry = {
* key: 'user.profile',
* definition: {
* path: '/user/:userId',
* accessGate: { level: 'authenticated' },
* meta: { title: 'User Profile' },
* },
* builder: createRouteBuilder('/user/:userId'),
* };
* ```
*/
export interface RouteRegistryEntry<
TPath extends string = string,
TQuery extends Record<string, QueryParamValue | QueryParamValue[]> = Record<
string,
QueryParamValue
>,
TAccessLevel extends AccessLevel = AccessLevel,
TProfileKey extends ProfileKey = ProfileKey,
TMeta extends RouteMeta = RouteMeta,
> {
/**
* Unique key for this route (dot notation: 'feature.route')
*/
key: string;
/**
* Route definition
*/
definition: RouteDefinition<TPath, TQuery, TAccessLevel, TProfileKey, TMeta>;
/**
* Route builder for type-safe path construction
*/
builder: RouteBuilder<TPath, TQuery>;
/**
* Optional component reference (for lazy loading)
*/
component?: ComponentType | (() => Promise<{ default: ComponentType }>);
}
/**
* Route registry for storing and looking up routes by key.
* Supports both flat and nested route structures.
*
* @example
* ```typescript
* const registry = new RouteRegistry();
*
* // Register routes
* registry.register('home', {
* definition: { path: '/', meta: { title: 'Home' } },
* builder: createRouteBuilder('/'),
* });
*
* registry.register('user.profile', {
* definition: { path: '/user/:userId', meta: { title: 'Profile' } },
* builder: createRouteBuilder('/user/:userId'),
* });
*
* // Lookup routes
* const homeRoute = registry.get('home');
* const profileRoute = registry.get('user.profile');
*
* // Build paths
* const profileUrl = profileRoute.builder.build({ userId: '123' });
* ```
*/
export class RouteRegistry {
private routes = new Map<string, RouteRegistryEntry>();
/**
* Register a route in the registry.
*/
register<
TPath extends string,
TQuery extends Record<string, QueryParamValue | QueryParamValue[]>,
TAccessLevel extends AccessLevel,
TProfileKey extends ProfileKey,
TMeta extends RouteMeta,
>(
key: string,
entry: Omit<
RouteRegistryEntry<TPath, TQuery, TAccessLevel, TProfileKey, TMeta>,
'key'
>
): void {
this.routes.set(key, { key, ...entry } as unknown as RouteRegistryEntry);
}
/**
* Get a route by key.
*/
get(key: string): RouteRegistryEntry | undefined {
return this.routes.get(key);
}
/**
* Check if a route exists.
*/
has(key: string): boolean {
return this.routes.has(key);
}
/**
* Get all registered routes.
*/
all(): RouteRegistryEntry[] {
return Array.from(this.routes.values());
}
/**
* Get routes matching a filter.
*/
filter(predicate: (entry: RouteRegistryEntry) => boolean): RouteRegistryEntry[] {
return this.all().filter(predicate);
}
/**
* Get routes by access level.
*/
byAccessLevel(level: AccessLevel): RouteRegistryEntry[] {
return this.filter((entry) => {
const gateLevel = entry.definition.accessGate?.level;
return gateLevel !== undefined && gateLevel === level;
});
}
/**
* Get routes by tag.
*/
byTag(tag: string): RouteRegistryEntry[] {
return this.filter((entry) => {
const tags = entry.definition.meta?.tags;
return tags !== undefined && tags.includes(tag);
});
}
/**
* Clear all routes.
*/
clear(): void {
this.routes.clear();
}
}
// ============================================================================
// Router Lookup Table Types (for marketplace-style routing)
// ============================================================================
/**
* Router lookup table for mapping access level × profile combinations to route trees.
* Used in features like marketplace for profile-based routing.
*
* @template TAccessLevels - Union of access level keys
* @template TProfiles - Union of profile keys (including null)
* @template TComponent - Router component type
*
* @example
* ```typescript
* type AccessLevelKey = 'guest' | 'user' | 'admin';
* type ProfileKey = null | 'escort_worker' | 'escort_client';
*
* const routers: RouterLookupTable<AccessLevelKey, ProfileKey> = {
* guest: {
* null: GuestRoutes,
* escort_worker: GuestRoutes,
* escort_client: GuestRoutes,
* },
* user: {
* null: OnboardingRoutes,
* escort_worker: WorkerRoutes,
* escort_client: ClientRoutes,
* },
* admin: {
* null: AdminRoutes,
* escort_worker: AdminRoutes,
* escort_client: AdminRoutes,
* },
* };
* ```
*/
export type RouterLookupTable<
TAccessLevels extends string,
TProfiles extends string | null,
TComponent = React.ComponentType,
> = {
[K in TAccessLevels]: {
[P in TProfiles extends null ? 'null' : TProfiles]: TComponent;
};
};
/**
* Helper to get router from lookup table with type safety.
*
* @example
* ```typescript
* const router = getRouterFromTable(routers, 'user', 'escort_worker');
* // Returns: WorkerRoutes (with full type safety)
* ```
*/
export function getRouterFromTable<
TAccessLevels extends string,
TProfiles extends string | null,
TComponent = React.ComponentType,
>(
table: RouterLookupTable<TAccessLevels, TProfiles, TComponent>,
accessLevel: TAccessLevels,
profile: TProfiles
): TComponent {
const profileKey = (profile === null ? 'null' : profile) as keyof RouterLookupTable<
TAccessLevels,
TProfiles,
TComponent
>[TAccessLevels];
return table[accessLevel][profileKey];
}
// ============================================================================
// React Router Integration Types
// ============================================================================
/**
* Convert RouteDefinition to react-router RouteObject.
* Helper for integrating type-safe routes with react-router.
*
* @example
* ```typescript
* const routeDefinition: RouteDefinition<'/user/:id'> = {
* path: '/user/:id',
* meta: { title: 'User Profile' },
* };
*
* const routeObject = toRouteObject(routeDefinition, UserProfile);
* // Use with react-router's createBrowserRouter
* ```
*/
export function toRouteObject<TPath extends string>(
definition: RouteDefinition<TPath>,
component?: ComponentType
): {
path: string;
element?: ReactElement;
children?: Array<{
path: string;
element?: ReactElement;
}>;
} {
return {
path: definition.path,
element: component ? React.createElement(component) : undefined,
children: definition.children?.map((child) => ({
path: child.path,
element: undefined,
})),
};
}
/**
* Type-safe navigation helper compatible with react-router's navigate.
*
* @example
* ```typescript
* const navigate = useNavigate();
* const profileRoute = createRouteBuilder('/profile/:userId');
*
* // Type-safe navigation
* navigateTo(navigate, profileRoute, { userId: '123' }, { tab: 'posts' });
* ```
*/
export function navigateTo<
TPath extends string,
TQuery extends Record<string, QueryParamValue | QueryParamValue[]>,
>(
navigate: (to: To, options?: { replace?: boolean; state?: unknown }) => void,
builder: RouteBuilder<TPath, TQuery>,
params: PathParams<TPath>,
query?: QueryParams<TQuery>,
options?: { replace?: boolean; state?: unknown }
): void {
const url = builder.build(params, query);
navigate(url, options);
}
// ============================================================================
// Protected Route Types (Authentication & Authorization)
// ============================================================================
/**
* Authentication state provided by the consuming application's auth hook.
* Decouples ProtectedRoute from specific auth implementations.
*
* @example
* ```tsx
* const authState = useAuth(); // From your auth context
* <ProtectedRoute authState={authState}>
* <Dashboard />
* </ProtectedRoute>
* ```
*/
export interface AuthState {
/**
* Whether the user is currently authenticated.
* If false, triggers redirect or fallback behavior.
*/
isAuthenticated: boolean;
/**
* Whether authentication state is still being determined.
* If true, shows loading UI instead of redirecting.
* This prevents flash of unauthenticated content on initial page load.
*
* @default false
*/
isLoading?: boolean;
/**
* Current user's roles/permissions (optional).
* Used for role-based access control.
*
* @example ['admin', 'moderator']
*/
roles?: string[];
/**
* Additional user metadata (optional).
* Can be used by custom authorization logic.
*/
user?: unknown;
}
/**
* Function to determine if user is authorized based on auth state.
* Enables custom authorization logic beyond simple authentication checks.
*
* @param authState - Current authentication state
* @returns true if user is authorized, false otherwise
*
* @example
* ```tsx
* // Role-based authorization
* const requireAdmin = (auth: AuthState) =>
* auth.isAuthenticated && auth.roles?.includes('admin');
*
* <ProtectedRoute
* authState={authState}
* authorize={requireAdmin}
* unauthorizedRedirect="/access-denied"
* >
* <AdminPanel />
* </ProtectedRoute>
* ```
*/
export type AuthorizationFunction = (authState: AuthState) => boolean;
/**
* Props for the unified ProtectedRoute component.
* Addresses inconsistencies found in Wave 1 Analysis (8 duplicate implementations).
*
* @example
* Basic usage (authentication only):
* ```tsx
* <ProtectedRoute
* authState={useAuth()}
* unauthenticatedRedirect="/login"
* >
* <PrivateContent />
* </ProtectedRoute>
* ```
*
* @example
* With loading state (prevents flash):
* ```tsx
* <ProtectedRoute
* authState={useAuth()}
* unauthenticatedRedirect="/login"
* loadingFallback={<Spinner />}
* >
* <PrivateContent />
* </ProtectedRoute>
* ```
*
* @example
* Role-based access control:
* ```tsx
* <ProtectedRoute
* authState={useAuth()}
* requiredRoles={['admin', 'moderator']}
* unauthenticatedRedirect="/login"
* unauthorizedRedirect="/access-denied"
* >
* <AdminPanel />
* </ProtectedRoute>
* ```
*
* @example
* Custom authorization logic:
* ```tsx
* const requirePremium = (auth: AuthState) =>
* auth.isAuthenticated && auth.user?.isPremium === true;
*
* <ProtectedRoute
* authState={useAuth()}
* authorize={requirePremium}
* unauthorizedFallback={<UpgradePrompt />}
* >
* <PremiumFeature />
* </ProtectedRoute>
* ```
*
* @example
* Inline fallback instead of redirect:
* ```tsx
* <ProtectedRoute
* authState={useAuth()}
* unauthenticatedFallback={<LoginPrompt />}
* >
* <PrivateContent />
* </ProtectedRoute>
* ```
*/
export interface ProtectedRouteProps {
/**
* Current authentication state from your auth hook/context.
* Required to determine if user should access the route.
*
* @example
* ```tsx
* const authState = useAuth();
* <ProtectedRoute authState={authState}>...</ProtectedRoute>
* ```
*/
authState: AuthState;
/**
* Content to render when user is authenticated and authorized.
*/
children: ReactNode;
// --- Authentication Redirects ---
/**
* Path to redirect to when user is not authenticated.
* Mutually exclusive with `unauthenticatedFallback`.
*
* @example "/login"
* @example "/admin/login"
*/
unauthenticatedRedirect?: string;
/**
* Component to render when user is not authenticated.
* Use this for inline login forms instead of redirecting to separate page.
* Mutually exclusive with `unauthenticatedRedirect`.
*
* @example <LoginPrompt />
* @example <div>Please log in to continue</div>
*/
unauthenticatedFallback?: ReactNode;
// --- Authorization (Role-Based Access Control) ---
/**
* Required roles for accessing this route.
* User must have at least one of these roles to be authorized.
* If provided, `authState.roles` must also be provided.
*
* @example ['admin']
* @example ['admin', 'moderator'] // User needs admin OR moderator
*/
requiredRoles?: string[];
/**
* Custom authorization function for complex access control logic.
* Takes precedence over `requiredRoles` if both are provided.
*
* @param authState - Current authentication state
* @returns true if user is authorized, false otherwise
*
* @example
* ```tsx
* authorize={(auth) => auth.user?.isPremium === true}
* ```
*/
authorize?: AuthorizationFunction;
/**
* Path to redirect to when user is authenticated but not authorized.
* Only applies when using `requiredRoles` or `authorize`.
* Mutually exclusive with `unauthorizedFallback`.
*
* @example "/access-denied"
* @example "/upgrade-required"
*/
unauthorizedRedirect?: string;
/**
* Component to render when user is authenticated but not authorized.
* Only applies when using `requiredRoles` or `authorize`.
* Mutually exclusive with `unauthorizedRedirect`.
*
* @example <AccessDenied />
* @example <div>You don't have permission to view this page</div>
*/
unauthorizedFallback?: ReactNode;
// --- Loading State ---
/**
* Component to render while authentication state is loading.
* Prevents flash of unauthenticated content during initial auth check.
* Only shown when `authState.isLoading === true`.
*
* @default null (renders nothing while loading)
*
* @example <Spinner />
* @example <div>Loading...</div>
*/
loadingFallback?: ReactNode;
// --- Advanced Options ---
/**
* Whether to use `replace` navigation mode when redirecting.
* If true, replaces current history entry instead of pushing new one.
* Prevents users from navigating back to protected page after redirect.
*
* @default true
*/
replace?: boolean;
/**
* Additional state to pass to the redirect destination.
* Useful for passing the original location to login page for post-login redirect.
*
* @example { from: location.pathname }
*/
redirectState?: unknown;
/**
* Custom redirect path builder function.
* Allows dynamic redirect paths based on auth state or current location.
* Takes precedence over `unauthenticatedRedirect` if both provided.
*
* @param authState - Current authentication state
* @param isAuthorized - Whether user passed authorization check
* @returns Path to redirect to
*
* @example
* ```tsx
* buildRedirectPath={(auth, authorized) =>
* authorized ? '/login' : '/access-denied'
* }
* ```
*/
buildRedirectPath?: (authState: AuthState, isAuthorized: boolean) => string;
}
/**
* Validation errors that can occur during ProtectedRoute configuration.
*/
export class ProtectedRouteError extends Error {
constructor(message: string) {
super(`ProtectedRoute: ${message}`);
this.name = 'ProtectedRouteError';
}
}
/**
* Type guard utilities for ProtectedRoute validation.
*/
export namespace ProtectedRouteValidation {
/**
* Validates that redirect and fallback props are not both provided.
* @throws {ProtectedRouteError} If mutually exclusive props are both provided
*/
export function validateMutualExclusivity(props: ProtectedRouteProps): void {
if (props.unauthenticatedRedirect && props.unauthenticatedFallback) {
throw new ProtectedRouteError(
'Cannot provide both unauthenticatedRedirect and unauthenticatedFallback'
);
}
if (props.unauthorizedRedirect && props.unauthorizedFallback) {
throw new ProtectedRouteError(
'Cannot provide both unauthorizedRedirect and unauthorizedFallback'
);
}
}
/**
* Validates that required roles is used correctly.
* Returns whether role-based access is properly configured.
*/
export function validateRoleBasedAccess(props: ProtectedRouteProps): boolean {
if (props.requiredRoles && !props.authState.roles) {
return false;
}
return true;
}
/**
* Validates all ProtectedRoute props.
* @throws {ProtectedRouteError} If validation fails
*/
export function validateProps(props: ProtectedRouteProps): void {
validateMutualExclusivity(props);
if (!validateRoleBasedAccess(props)) {
throw new ProtectedRouteError(
'requiredRoles provided but authState.roles is undefined. Role check will always fail.'
);
}
}
}
/**
* Default values for ProtectedRoute optional props.
*/
export const PROTECTED_ROUTE_DEFAULTS = {
replace: true,
loadingFallback: null,
} as const;
|