@funstack/router 0.0.1-alpha.2 → 0.0.2-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 uhyo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.d.mts CHANGED
@@ -2,6 +2,16 @@ import { ComponentType, ReactNode } from "react";
2
2
 
3
3
  //#region src/route.d.ts
4
4
  declare const routeDefinitionSymbol: unique symbol;
5
+ /**
6
+ * Extracts parameter names from a path pattern.
7
+ * E.g., "/users/:id/posts/:postId" -> "id" | "postId"
8
+ */
9
+ type ExtractParams<T extends string> = T extends `${string}:${infer Param}/${infer Rest}` ? Param | ExtractParams<`/${Rest}`> : T extends `${string}:${infer Param}` ? Param : never;
10
+ /**
11
+ * Creates a params object type from a path pattern.
12
+ * E.g., "/users/:id" -> { id: string }
13
+ */
14
+ type PathParams<T extends string> = [ExtractParams<T>] extends [never] ? Record<string, never> : { [K in ExtractParams<T>]: string };
5
15
  /**
6
16
  * Arguments passed to loader functions.
7
17
  */
@@ -13,6 +23,32 @@ type LoaderArgs = {
13
23
  /** AbortSignal for cancellation on navigation */
14
24
  signal: AbortSignal;
15
25
  };
26
+ /**
27
+ * Props for route components without loader.
28
+ * Includes navigation state management props.
29
+ */
30
+ type RouteComponentProps<TParams extends Record<string, string>, TState = undefined> = {
31
+ /** Extracted path parameters */
32
+ params: TParams;
33
+ /** Current navigation state for this route (undefined on first visit) */
34
+ state: TState | undefined;
35
+ /** Update navigation state for this route asynchronously via replace navigation */
36
+ setState: (state: TState | ((prev: TState | undefined) => TState)) => Promise<void>;
37
+ /** Update navigation state for this route synchronously via updateCurrentEntry */
38
+ setStateSync: (state: TState | ((prev: TState | undefined) => TState)) => void;
39
+ /** Reset navigation state to undefined */
40
+ resetState: () => void;
41
+ /** Ephemeral navigation info (only available during navigation, not persisted) */
42
+ info: unknown;
43
+ };
44
+ /**
45
+ * Props for route components with loader.
46
+ * Includes data from loader and navigation state management props.
47
+ */
48
+ type RouteComponentPropsWithData<TParams extends Record<string, string>, TData, TState = undefined> = RouteComponentProps<TParams, TState> & {
49
+ /** Data returned from the loader */
50
+ data: TData;
51
+ };
16
52
  /**
17
53
  * Route definition created by the `route` helper function.
18
54
  */
@@ -26,33 +62,38 @@ interface OpaqueRouteDefinition {
26
62
  */
27
63
  type RouteDefinition = OpaqueRouteDefinition | {
28
64
  path: string;
29
- component?: ComponentType<{}>;
65
+ component?: ComponentType<object>;
30
66
  children?: RouteDefinition[];
31
67
  };
32
68
  /**
33
69
  * Route definition with loader - infers TData from loader return type.
70
+ * TPath is used to infer params type from the path pattern.
71
+ * TState is the type of navigation state for this route.
34
72
  */
35
- type RouteWithLoader<TData> = {
36
- path: string;
73
+ type RouteWithLoader<TPath extends string, TData, TState> = {
74
+ path: TPath;
37
75
  loader: (args: LoaderArgs) => TData;
38
- component: ComponentType<{
39
- data: TData;
40
- }>;
76
+ component: ComponentType<RouteComponentPropsWithData<PathParams<TPath>, TData, TState>>;
41
77
  children?: RouteDefinition[];
42
78
  };
43
79
  /**
44
80
  * Route definition without loader.
81
+ * TPath is used to infer params type from the path pattern.
82
+ * TState is the type of navigation state for this route.
45
83
  */
46
- type RouteWithoutLoader = {
47
- path: string;
48
- component?: ComponentType;
84
+ type RouteWithoutLoader<TPath extends string, TState> = {
85
+ path: TPath;
86
+ component?: ComponentType<RouteComponentProps<PathParams<TPath>, TState>>;
49
87
  children?: RouteDefinition[];
50
88
  };
51
89
  /**
52
90
  * Helper function for creating type-safe route definitions.
53
91
  *
54
92
  * When a loader is provided, TypeScript infers the return type and ensures
55
- * the component accepts a `data` prop of that type.
93
+ * the component accepts a `data` prop of that type. Components always receive
94
+ * a `params` prop with types inferred from the path pattern.
95
+ *
96
+ * For routes with navigation state, use `routeState<TState>()({ ... })` instead.
56
97
  *
57
98
  * @example
58
99
  * ```typescript
@@ -63,36 +104,54 @@ type RouteWithoutLoader = {
63
104
  * const res = await fetch(`/api/users/${params.userId}`, { signal });
64
105
  * return res.json() as Promise<User>;
65
106
  * },
66
- * component: UserDetail, // Must accept { data: Promise<User> }
107
+ * component: UserDetail, // Must accept { data: Promise<User>, params: { userId: string }, state, setState, resetState }
67
108
  * });
68
109
  *
69
110
  * // Route without loader
70
111
  * route({
71
112
  * path: "about",
72
- * component: AboutPage, // No data prop required
113
+ * component: AboutPage, // Must accept { params: {}, state, setState, resetState }
73
114
  * });
74
115
  * ```
75
116
  */
76
- declare function route<TData>(definition: RouteWithLoader<TData>): OpaqueRouteDefinition;
77
- declare function route(definition: RouteWithoutLoader): OpaqueRouteDefinition;
78
- //#endregion
79
- //#region src/Router.d.ts
80
- type RouterProps = {
81
- routes: RouteDefinition[];
82
- };
83
- declare function Router({
84
- routes: inputRoutes
85
- }: RouterProps): ReactNode;
86
- //#endregion
87
- //#region src/Outlet.d.ts
117
+ declare function route<TPath extends string, TData>(definition: RouteWithLoader<TPath, TData, undefined>): OpaqueRouteDefinition;
118
+ declare function route<TPath extends string>(definition: RouteWithoutLoader<TPath, undefined>): OpaqueRouteDefinition;
88
119
  /**
89
- * Renders the matched child route.
90
- * Used in layout components to specify where child routes should render.
120
+ * Helper function for creating type-safe route definitions with navigation state.
121
+ *
122
+ * Use this curried function when your route component needs to manage navigation state.
123
+ * The state is tied to the navigation history entry and persists across back/forward navigation.
124
+ *
125
+ * @example
126
+ * ```typescript
127
+ * // Route with navigation state
128
+ * type MyState = { scrollPosition: number };
129
+ * routeState<MyState>()({
130
+ * path: "users/:userId",
131
+ * component: UserPage, // Receives { params, state, setState, resetState }
132
+ * });
133
+ *
134
+ * // Route with both loader and navigation state
135
+ * type FilterState = { filter: string };
136
+ * routeState<FilterState>()({
137
+ * path: "products",
138
+ * loader: async () => fetchProducts(),
139
+ * component: ProductList, // Receives { data, params, state, setState, resetState }
140
+ * });
141
+ * ```
91
142
  */
92
- declare function Outlet(): ReactNode;
143
+ declare function routeState<TState>(): {
144
+ <TPath extends string, TData>(definition: RouteWithLoader<TPath, TData, TState>): OpaqueRouteDefinition;
145
+ <TPath extends string>(definition: RouteWithoutLoader<TPath, TState>): OpaqueRouteDefinition;
146
+ };
93
147
  //#endregion
94
148
  //#region src/types.d.ts
95
149
  declare const InternalRouteDefinitionSymbol: unique symbol;
150
+ /**
151
+ * Internal structure for storing per-route state in NavigationHistoryEntry.
152
+ * Each route in the matched stack gets its own state slot indexed by match position.
153
+ */
154
+
96
155
  /**
97
156
  * Route definition for the router.
98
157
  * When a loader is defined, the component receives the loader result as a `data` prop.
@@ -108,6 +167,12 @@ type InternalRouteDefinition = {
108
167
  /** Component to render when this route matches */
109
168
  component?: ComponentType<{
110
169
  data?: unknown;
170
+ params?: Record<string, string>;
171
+ state?: unknown;
172
+ setState?: (state: unknown | ((prev: unknown) => unknown)) => Promise<void>;
173
+ setStateSync?: (state: unknown | ((prev: unknown) => unknown)) => void;
174
+ resetState?: () => void;
175
+ info?: unknown;
111
176
  }>;
112
177
  };
113
178
  /**
@@ -136,6 +201,8 @@ type NavigateOptions = {
136
201
  replace?: boolean;
137
202
  /** State to associate with the navigation */
138
203
  state?: unknown;
204
+ /** Ephemeral info for this navigation only (not persisted in history) */
205
+ info?: unknown;
139
206
  };
140
207
  /**
141
208
  * Location object representing current URL state.
@@ -145,6 +212,53 @@ type Location = {
145
212
  search: string;
146
213
  hash: string;
147
214
  };
215
+ /**
216
+ * Callback invoked before navigation is intercepted.
217
+ * Call `event.preventDefault()` to prevent the router from handling this navigation.
218
+ *
219
+ * @param event - The NavigateEvent from the Navigation API
220
+ * @param matched - Array of matched routes, or null if no routes matched
221
+ */
222
+ type OnNavigateCallback = (event: NavigateEvent, matched: readonly MatchedRoute[] | null) => void;
223
+ /**
224
+ * Fallback mode when Navigation API is unavailable.
225
+ *
226
+ * - `"none"` (default): Render nothing when Navigation API is unavailable
227
+ * - `"static"`: Render matched routes without navigation capabilities (MPA behavior)
228
+ */
229
+ type FallbackMode = "none" | "static";
230
+ //#endregion
231
+ //#region src/Router.d.ts
232
+ type RouterProps = {
233
+ routes: RouteDefinition[];
234
+ /**
235
+ * Callback invoked before navigation is intercepted.
236
+ * Call `event.preventDefault()` to prevent the router from handling this navigation.
237
+ *
238
+ * @param event - The NavigateEvent from the Navigation API
239
+ * @param matched - Array of matched routes, or null if no routes matched
240
+ */
241
+ onNavigate?: OnNavigateCallback;
242
+ /**
243
+ * Fallback mode when Navigation API is unavailable.
244
+ *
245
+ * - `"none"` (default): Render nothing when Navigation API is unavailable
246
+ * - `"static"`: Render matched routes without navigation capabilities (MPA behavior)
247
+ */
248
+ fallback?: FallbackMode;
249
+ };
250
+ declare function Router({
251
+ routes: inputRoutes,
252
+ onNavigate,
253
+ fallback
254
+ }: RouterProps): ReactNode;
255
+ //#endregion
256
+ //#region src/Outlet.d.ts
257
+ /**
258
+ * Renders the matched child route.
259
+ * Used in layout components to specify where child routes should render.
260
+ */
261
+ declare function Outlet(): ReactNode;
148
262
  //#endregion
149
263
  //#region src/hooks/useNavigate.d.ts
150
264
  /**
@@ -158,12 +272,6 @@ declare function useNavigate(): (to: string, options?: NavigateOptions) => void;
158
272
  */
159
273
  declare function useLocation(): Location;
160
274
  //#endregion
161
- //#region src/hooks/useParams.d.ts
162
- /**
163
- * Returns route parameters from the matched path.
164
- */
165
- declare function useParams<T extends Record<string, string> = Record<string, string>>(): T;
166
- //#endregion
167
275
  //#region src/hooks/useSearchParams.d.ts
168
276
  type SetSearchParams = (params: URLSearchParams | Record<string, string> | ((prev: URLSearchParams) => URLSearchParams | Record<string, string>)) => void;
169
277
  /**
@@ -171,5 +279,58 @@ type SetSearchParams = (params: URLSearchParams | Record<string, string> | ((pre
171
279
  */
172
280
  declare function useSearchParams(): [URLSearchParams, SetSearchParams];
173
281
  //#endregion
174
- export { type LoaderArgs, type Location, type MatchedRoute, type MatchedRouteWithData, type NavigateOptions, Outlet, type RouteDefinition, Router, type RouterProps, route, useLocation, useNavigate, useParams, useSearchParams };
282
+ //#region src/hooks/useBlocker.d.ts
283
+ type UseBlockerOptions = {
284
+ /**
285
+ * Function that returns true if navigation should be blocked.
286
+ * Can call `confirm()` inside to show a confirmation dialog.
287
+ */
288
+ shouldBlock: () => boolean;
289
+ };
290
+ /**
291
+ * Hook to block navigation away from the current route.
292
+ *
293
+ * This is useful for scenarios like unsaved form data, ongoing file uploads,
294
+ * or any state that would be lost on navigation.
295
+ *
296
+ * @example
297
+ * ```tsx
298
+ * function EditForm() {
299
+ * const [isDirty, setIsDirty] = useState(false);
300
+ *
301
+ * useBlocker({
302
+ * shouldBlock: () => {
303
+ * if (isDirty) {
304
+ * return !confirm("You have unsaved changes. Leave anyway?");
305
+ * }
306
+ * return false;
307
+ * },
308
+ * });
309
+ *
310
+ * return <form>...</form>;
311
+ * }
312
+ * ```
313
+ *
314
+ * Note: This hook only handles SPA navigations (links, programmatic navigation).
315
+ * For hard navigations (tab close, refresh), handle `beforeunload` separately.
316
+ */
317
+ declare function useBlocker(options: UseBlockerOptions): void;
318
+ //#endregion
319
+ //#region src/core/RouterAdapter.d.ts
320
+ /**
321
+ * Represents the current location state.
322
+ * Abstracts NavigationHistoryEntry for static mode compatibility.
323
+ */
324
+ type LocationEntry = {
325
+ /** The current URL */
326
+ url: URL;
327
+ /** Unique key for this entry (used for loader caching) */
328
+ key: string;
329
+ /** State associated with this entry */
330
+ state: unknown;
331
+ /** Ephemeral info from current navigation (undefined if not from navigation event) */
332
+ info: unknown;
333
+ };
334
+ //#endregion
335
+ export { type FallbackMode, type LoaderArgs, type Location, type LocationEntry, type MatchedRoute, type MatchedRouteWithData, type NavigateOptions, type OnNavigateCallback, Outlet, type PathParams, type RouteComponentProps, type RouteComponentPropsWithData, type RouteDefinition, Router, type RouterProps, type UseBlockerOptions, route, routeState, useBlocker, useLocation, useNavigate, useSearchParams };
175
336
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/route.ts","../src/Router.tsx","../src/Outlet.tsx","../src/types.ts","../src/hooks/useNavigate.ts","../src/hooks/useLocation.ts","../src/hooks/useParams.ts","../src/hooks/useSearchParams.ts"],"sourcesContent":[],"mappings":";;;cAEM;;AAFqC;AAO3C;AAEU,KAFE,UAAA,GAEF;EAEC;EAED,MAAA,EAJA,MAIA,CAAA,MAAA,EAAA,MAAA,CAAA;EAAW;EAMJ,OAAA,EARN,OAQM;EASL;EACR,MAAA,EAhBM,WAgBN;CAGc;;;AAEZ;AAOW,UAtBA,qBAAA,CAsBA;EAAe,CArB7B,qBAAA,CAqB6B,EAAA,KAAA;EACG,IAAA,EAAA,MAAA;EAAtB,QAAA,CAAA,EApBA,eAoBA,EAAA;;;AAEe;AAsC5B;AAC8B,KAvDlB,eAAA,GACR,qBAsD0B,GAAA;EAAhB,IAAA,EAAA,MAAA;EACX,SAAA,CAAA,EApDe,aAoDf,CAAA,CAAA,CAAA,CAAA;EAAqB,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GAAuB;;;AApD2B,CAAA;AAQ9D;;;AAWkB,KAyCN,eAAA,GAzCM;EAEJ;EAAa,OAAA,CAAA,EAAA,OAAA;EAmBf;EAYA,KAAA,CAAA,EAAA,OAAA;AAQZ,CAAA;AAUA;;;KAAY,QAAA;EChEI,QAAA,EAAA,MAAW;;;;;;;;AJPgB;AAO/B,iBIAI,WAAA,CAAA,CJAM,EAAA,CAAA,EAAA,EAAA,MAAA,EAAA,OAAA,CAAA,EIAgC,eJAhC,EAAA,GAAA,IAAA;;;;;AAPqB;AAO/B,iBKAI,WAAA,CAAA,CLAM,EKAS,QLAT;;;;;;AALhB,iBMIU,SNJsB,CAAA,UMK1B,MNL0B,CAAA,MAAA,EAAA,MAAA,CAAA,GMKD,MNLC,CAAA,MAAA,EAAA,MAAA,CAAA,CAAA,CAAA,CAAA,EMMjC,CNNiC;;;KOCjC,eAAA,YAEC,kBACA,iCACQ,oBAAoB,kBAAkB;;;APPT;AAO/B,iBOMI,eAAA,CAAA,CPNM,EAAA,COMc,ePNd,EOM+B,ePN/B,CAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/route.ts","../src/types.ts","../src/Router.tsx","../src/Outlet.tsx","../src/hooks/useNavigate.ts","../src/hooks/useLocation.ts","../src/hooks/useSearchParams.ts","../src/hooks/useBlocker.ts","../src/core/RouterAdapter.ts"],"sourcesContent":[],"mappings":";;;cAEM;;AAFqC;AAEL;;KAMjC,aAEC,CAAA,UAAA,MAAA,CAAA,GADJ,CACI,SAAA,GAAA,MAAA,IAAA,KAAA,MAAA,IAAA,KAAA,KAAA,EAAA,GAAA,KAAA,GAAQ,aAAR,CAAA,IAA0B,IAA1B,EAAA,CAAA,GACA,CADA,SAAA,GAAA,MAAA,IAAA,KAAA,MAAA,EAAA,GAAA,KAAA,GAAA,KAAA;;;;;AASM,KAAA,UAAU,CAAA,UAAA,MAAA,CAAA,GAAA,CAAsB,aAAtB,CAAoC,CAApC,CAAA,CAAA,SAAA,CAAA,KA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AAA,EAAA,GAAA,GAAA,OAAA;CACI;;;;;AASN;;;;;;;AAOA;;;;;AAaA;;;;;;;;;;;AAcyD,iBOfzC,UAAA,CPeyC,OAAA,EOfrB,iBPeqB,CAAA,EAAA,IAAA;;;;;AArDd;AAEL;AAOpC,KQCU,aAAA,GRDV;EACI;EAA0B,GAAA,EQEzB,GRFyB;EAAlB;EACR,GAAA,EAAA,MAAA;EAAC;EAQK,KAAA,EAAA,OAAU;EAAoC;EAAd,IAAA,EAAA,OAAA;CACxC"}
package/dist/index.mjs CHANGED
@@ -1,4 +1,6 @@
1
- import { createContext, useCallback, useContext, useEffect, useMemo, useSyncExternalStore } from "react";
1
+ "use client";
2
+
3
+ import { createContext, useCallback, useContext, useEffect, useId, useMemo, useState, useSyncExternalStore } from "react";
2
4
  import { jsx } from "react/jsx-runtime";
3
5
 
4
6
  //#region src/context/RouterContext.ts
@@ -8,6 +10,29 @@ const RouterContext = createContext(null);
8
10
  //#region src/context/RouteContext.ts
9
11
  const RouteContext = createContext(null);
10
12
 
13
+ //#endregion
14
+ //#region src/context/BlockerContext.ts
15
+ /**
16
+ * Create a new blocker registry.
17
+ * The registry manages registered blockers and provides a way to check if any blocker is active.
18
+ */
19
+ function createBlockerRegistry() {
20
+ const blockers = /* @__PURE__ */ new Map();
21
+ return {
22
+ register(id, shouldBlock) {
23
+ blockers.set(id, shouldBlock);
24
+ return () => {
25
+ blockers.delete(id);
26
+ };
27
+ },
28
+ checkAll() {
29
+ for (const shouldBlock of blockers.values()) if (shouldBlock()) return true;
30
+ return false;
31
+ }
32
+ };
33
+ }
34
+ const BlockerContext = createContext(null);
35
+
11
36
  //#endregion
12
37
  //#region src/types.ts
13
38
  /**
@@ -100,16 +125,16 @@ function matchPath(pattern, pathname, exact) {
100
125
  //#region src/core/loaderCache.ts
101
126
  /**
102
127
  * Cache for loader results.
103
- * Key format: `${entryId}:${routePath}`
128
+ * Key format: `${entryId}:${matchIndex}`
104
129
  */
105
130
  const loaderCache = /* @__PURE__ */ new Map();
106
131
  /**
107
132
  * Get or create a loader result from cache.
108
133
  * If the result is not cached, executes the loader and caches the result.
109
134
  */
110
- function getOrCreateLoaderResult(entryId, route$1, args) {
135
+ function getOrCreateLoaderResult(entryId, matchIndex, route$1, args) {
111
136
  if (!route$1.loader) return;
112
- const cacheKey = `${entryId}:${route$1.path}`;
137
+ const cacheKey = `${entryId}:${matchIndex}`;
113
138
  if (!loaderCache.has(cacheKey)) loaderCache.set(cacheKey, route$1.loader(args));
114
139
  return loaderCache.get(cacheKey);
115
140
  }
@@ -124,9 +149,9 @@ function createLoaderRequest(url) {
124
149
  * Results are cached by navigation entry id to prevent duplicate execution.
125
150
  */
126
151
  function executeLoaders(matchedRoutes, entryId, request, signal) {
127
- return matchedRoutes.map((match) => {
152
+ return matchedRoutes.map((match, index) => {
128
153
  const { route: route$1, params } = match;
129
- const data = getOrCreateLoaderResult(entryId, route$1, {
154
+ const data = getOrCreateLoaderResult(entryId, index, route$1, {
130
155
  params,
131
156
  request,
132
157
  signal
@@ -137,9 +162,17 @@ function executeLoaders(matchedRoutes, entryId, request, signal) {
137
162
  };
138
163
  });
139
164
  }
165
+ /**
166
+ * Clear loader cache entries for a specific navigation entry.
167
+ * Called when a NavigationHistoryEntry is disposed (removed from history stack).
168
+ */
169
+ function clearLoaderCacheForEntry(entryId) {
170
+ const prefix = `${entryId}:`;
171
+ for (const key of loaderCache.keys()) if (key.startsWith(prefix)) loaderCache.delete(key);
172
+ }
140
173
 
141
174
  //#endregion
142
- //#region src/core/navigation.ts
175
+ //#region src/core/NavigationAPIAdapter.ts
143
176
  /**
144
177
  * Fallback AbortController for data loading initialized outside of a navigation event.
145
178
  * Aborted when the next navigation occurs.
@@ -148,53 +181,90 @@ function executeLoaders(matchedRoutes, entryId, request, signal) {
148
181
  */
149
182
  let idleController = null;
150
183
  /**
151
- * Get the current abort signal for loader cancellation.
152
- */
153
- function getIdleAbortSignal() {
154
- idleController ??= new AbortController();
155
- return idleController.signal;
156
- }
157
- /**
158
- * Check if Navigation API is available.
159
- */
160
- function hasNavigation() {
161
- return typeof navigation !== "undefined";
162
- }
163
- /**
164
- * Subscribe to Navigation API's currententrychange event.
165
- * Returns a cleanup function.
166
- */
167
- function subscribeToNavigation(callback) {
168
- if (!hasNavigation()) return () => {};
169
- navigation.addEventListener("currententrychange", callback);
170
- return () => {
171
- if (hasNavigation()) navigation.removeEventListener("currententrychange", callback);
172
- };
173
- }
174
- /**
175
- * Get current navigation entry snapshot.
184
+ * Adapter that uses the Navigation API for full SPA functionality.
176
185
  */
177
- function getNavigationSnapshot() {
178
- if (!hasNavigation()) return null;
179
- return navigation.currentEntry;
180
- }
181
- /**
182
- * Server snapshot - Navigation API not available on server.
183
- */
184
- function getServerSnapshot() {
185
- return null;
186
- }
187
- /**
188
- * Set up navigation interception for client-side routing.
189
- * Returns a cleanup function.
190
- */
191
- function setupNavigationInterception(routes) {
192
- if (!hasNavigation()) return () => {};
193
- const handleNavigate = (event) => {
194
- if (!event.canIntercept || event.hashChange) return;
195
- const url = new URL(event.destination.url);
196
- const matched = matchRoutes(routes, url.pathname);
197
- if (matched) {
186
+ var NavigationAPIAdapter = class {
187
+ #cachedSnapshot = null;
188
+ #cachedEntryId = null;
189
+ #currentNavigationInfo = void 0;
190
+ getSnapshot() {
191
+ const entry = navigation.currentEntry;
192
+ if (!entry?.url) return null;
193
+ if (this.#cachedEntryId === entry.id && this.#cachedSnapshot) return this.#cachedSnapshot;
194
+ this.#cachedEntryId = entry.id;
195
+ this.#cachedSnapshot = {
196
+ url: new URL(entry.url),
197
+ key: entry.id,
198
+ state: entry.getState(),
199
+ info: this.#currentNavigationInfo
200
+ };
201
+ return this.#cachedSnapshot;
202
+ }
203
+ getServerSnapshot() {
204
+ return null;
205
+ }
206
+ subscribe(callback) {
207
+ const controller = new AbortController();
208
+ navigation.addEventListener("currententrychange", callback, { signal: controller.signal });
209
+ this.#subscribeToDisposeEvents(controller.signal);
210
+ navigation.addEventListener("currententrychange", () => this.#subscribeToDisposeEvents(controller.signal), { signal: controller.signal });
211
+ return () => {
212
+ controller.abort();
213
+ };
214
+ }
215
+ /**
216
+ * Track which entries we've subscribed to dispose events for.
217
+ */
218
+ #subscribedEntryIds = /* @__PURE__ */ new Set();
219
+ /**
220
+ * Subscribe to dispose events on all navigation entries.
221
+ * When an entry is disposed, its cached loader results are cleared.
222
+ */
223
+ #subscribeToDisposeEvents(signal) {
224
+ for (const entry of navigation.entries()) {
225
+ if (this.#subscribedEntryIds.has(entry.id)) continue;
226
+ this.#subscribedEntryIds.add(entry.id);
227
+ const entryId = entry.id;
228
+ entry.addEventListener("dispose", () => {
229
+ clearLoaderCacheForEntry(entryId);
230
+ this.#subscribedEntryIds.delete(entryId);
231
+ }, { signal });
232
+ }
233
+ }
234
+ navigate(to, options) {
235
+ navigation.navigate(to, {
236
+ history: options?.replace ? "replace" : "push",
237
+ state: options?.state,
238
+ info: options?.info
239
+ });
240
+ }
241
+ async navigateAsync(to, options) {
242
+ await navigation.navigate(to, {
243
+ history: options?.replace ? "replace" : "push",
244
+ state: options?.state,
245
+ info: options?.info
246
+ }).finished;
247
+ }
248
+ setupInterception(routes, onNavigate, checkBlockers) {
249
+ const handleNavigate = (event) => {
250
+ this.#currentNavigationInfo = event.info;
251
+ this.#cachedSnapshot = null;
252
+ if (checkBlockers?.()) {
253
+ event.preventDefault();
254
+ return;
255
+ }
256
+ if (!event.canIntercept) {
257
+ onNavigate?.(event, []);
258
+ return;
259
+ }
260
+ const url = new URL(event.destination.url);
261
+ const matched = matchRoutes(routes, url.pathname);
262
+ if (onNavigate) {
263
+ onNavigate(event, matched);
264
+ if (event.defaultPrevented) return;
265
+ }
266
+ if (event.hashChange || event.downloadRequest !== null) return;
267
+ if (!matched) return;
198
268
  if (idleController) {
199
269
  idleController.abort();
200
270
  idleController = null;
@@ -206,60 +276,173 @@ function setupNavigationInterception(routes) {
206
276
  const results = executeLoaders(matched, currentEntry.id, request, event.signal);
207
277
  await Promise.all(results.map((r) => r.data));
208
278
  } });
209
- }
210
- };
211
- navigation.addEventListener("navigate", handleNavigate);
212
- return () => {
213
- if (hasNavigation()) navigation.removeEventListener("navigate", handleNavigate);
214
- };
279
+ };
280
+ const controller = new AbortController();
281
+ navigation.addEventListener("navigate", handleNavigate, { signal: controller.signal });
282
+ return () => {
283
+ controller.abort();
284
+ };
285
+ }
286
+ getIdleAbortSignal() {
287
+ idleController ??= new AbortController();
288
+ return idleController.signal;
289
+ }
290
+ updateCurrentEntryState(state) {
291
+ this.#cachedSnapshot = null;
292
+ navigation.updateCurrentEntry({ state });
293
+ }
294
+ };
295
+
296
+ //#endregion
297
+ //#region src/core/StaticAdapter.ts
298
+ /**
299
+ * Static adapter for fallback mode when Navigation API is unavailable.
300
+ * Provides read-only location access with no SPA navigation capabilities.
301
+ * Links will cause full page loads (MPA behavior).
302
+ */
303
+ var StaticAdapter = class {
304
+ #cachedSnapshot = null;
305
+ #idleController = null;
306
+ getSnapshot() {
307
+ if (typeof window === "undefined") return null;
308
+ if (!this.#cachedSnapshot) this.#cachedSnapshot = {
309
+ url: new URL(window.location.href),
310
+ key: "__static__",
311
+ state: void 0,
312
+ info: void 0
313
+ };
314
+ return this.#cachedSnapshot;
315
+ }
316
+ getServerSnapshot() {
317
+ return null;
318
+ }
319
+ subscribe(_callback) {
320
+ return () => {};
321
+ }
322
+ navigate(to, _options) {
323
+ console.warn("FUNSTACK Router: navigate() called in static fallback mode. Navigation API is not available in this browser. Links will cause full page loads.");
324
+ }
325
+ async navigateAsync(to, options) {
326
+ this.navigate(to, options);
327
+ }
328
+ setupInterception(_routes, _onNavigate, _checkBlockers) {}
329
+ getIdleAbortSignal() {
330
+ this.#idleController ??= new AbortController();
331
+ return this.#idleController.signal;
332
+ }
333
+ updateCurrentEntryState(_state) {}
334
+ };
335
+
336
+ //#endregion
337
+ //#region src/core/NullAdapter.ts
338
+ /**
339
+ * Null adapter for when Navigation API is unavailable and no fallback is configured.
340
+ * All methods are no-ops that return safe default values.
341
+ */
342
+ var NullAdapter = class {
343
+ #idleController = null;
344
+ getSnapshot() {
345
+ return null;
346
+ }
347
+ getServerSnapshot() {
348
+ return null;
349
+ }
350
+ subscribe(_callback) {
351
+ return () => {};
352
+ }
353
+ navigate(_to, _options) {
354
+ console.warn("FUNSTACK Router: navigate() called but no adapter is available. Navigation API is not available in this browser and no fallback mode is configured.");
355
+ }
356
+ async navigateAsync(to, options) {
357
+ this.navigate(to, options);
358
+ }
359
+ setupInterception(_routes, _onNavigate, _checkBlockers) {}
360
+ getIdleAbortSignal() {
361
+ this.#idleController ??= new AbortController();
362
+ return this.#idleController.signal;
363
+ }
364
+ updateCurrentEntryState(_state) {}
365
+ };
366
+
367
+ //#endregion
368
+ //#region src/core/createAdapter.ts
369
+ /**
370
+ * Check if Navigation API is available.
371
+ */
372
+ function hasNavigation() {
373
+ return typeof window !== "undefined" && "navigation" in window;
215
374
  }
216
375
  /**
217
- * Navigate to a new URL programmatically.
376
+ * Create the appropriate router adapter based on browser capabilities
377
+ * and the specified fallback mode.
378
+ *
379
+ * @param fallback - The fallback mode to use when Navigation API is unavailable
380
+ * @returns A RouterAdapter instance
218
381
  */
219
- function performNavigation(to, options) {
220
- if (!hasNavigation()) return;
221
- navigation.navigate(to, {
222
- history: options?.replace ? "replace" : "push",
223
- state: options?.state
224
- });
382
+ function createAdapter(fallback) {
383
+ if (hasNavigation()) return new NavigationAPIAdapter();
384
+ if (fallback === "static") return new StaticAdapter();
385
+ return new NullAdapter();
225
386
  }
226
387
 
227
388
  //#endregion
228
389
  //#region src/Router.tsx
229
- function Router({ routes: inputRoutes }) {
390
+ function Router({ routes: inputRoutes, onNavigate, fallback = "none" }) {
230
391
  const routes = internalRoutes(inputRoutes);
231
- const currentEntry = useSyncExternalStore(subscribeToNavigation, getNavigationSnapshot, getServerSnapshot);
392
+ const adapter = useMemo(() => createAdapter(fallback), [fallback]);
393
+ const [blockerRegistry] = useState(() => createBlockerRegistry());
394
+ const locationEntry = useSyncExternalStore(useCallback((callback) => adapter.subscribe(callback), [adapter]), () => adapter.getSnapshot(), () => adapter.getServerSnapshot());
232
395
  useEffect(() => {
233
- return setupNavigationInterception(routes);
234
- }, [routes]);
235
- const navigate = useCallback((to, options) => performNavigation(to, options), []);
396
+ return adapter.setupInterception(routes, onNavigate, blockerRegistry.checkAll);
397
+ }, [
398
+ adapter,
399
+ routes,
400
+ onNavigate,
401
+ blockerRegistry
402
+ ]);
403
+ const navigate = useCallback((to, options) => {
404
+ adapter.navigate(to, options);
405
+ }, [adapter]);
406
+ const navigateAsync = useCallback((to, options) => {
407
+ return adapter.navigateAsync(to, options);
408
+ }, [adapter]);
409
+ const updateCurrentEntryState = useCallback((state) => {
410
+ adapter.updateCurrentEntryState(state);
411
+ }, [adapter]);
236
412
  return useMemo(() => {
237
- if (currentEntry === null) return null;
238
- const currentUrl = currentEntry.url;
239
- if (currentUrl === null) return null;
240
- const url = new URL(currentUrl);
241
- const currentEntryId = currentEntry.id;
413
+ if (locationEntry === null) return null;
414
+ const { url, key } = locationEntry;
242
415
  const matchedRoutesWithData = (() => {
243
416
  const matched = matchRoutes(routes, url.pathname);
244
417
  if (!matched) return null;
245
- return executeLoaders(matched, currentEntryId, createLoaderRequest(url), getIdleAbortSignal());
418
+ return executeLoaders(matched, key, createLoaderRequest(url), adapter.getIdleAbortSignal());
246
419
  })();
247
420
  const routerContextValue = {
248
- currentEntry,
421
+ locationEntry,
249
422
  url,
250
- navigate
423
+ navigate,
424
+ navigateAsync,
425
+ updateCurrentEntryState
251
426
  };
252
- return /* @__PURE__ */ jsx(RouterContext.Provider, {
253
- value: routerContextValue,
254
- children: matchedRoutesWithData ? /* @__PURE__ */ jsx(RouteRenderer, {
255
- matchedRoutes: matchedRoutesWithData,
256
- index: 0
257
- }) : null
427
+ const blockerContextValue = { registry: blockerRegistry };
428
+ return /* @__PURE__ */ jsx(BlockerContext.Provider, {
429
+ value: blockerContextValue,
430
+ children: /* @__PURE__ */ jsx(RouterContext.Provider, {
431
+ value: routerContextValue,
432
+ children: matchedRoutesWithData ? /* @__PURE__ */ jsx(RouteRenderer, {
433
+ matchedRoutes: matchedRoutesWithData,
434
+ index: 0
435
+ }) : null
436
+ })
258
437
  });
259
438
  }, [
260
439
  navigate,
261
- currentEntry,
262
- routes
440
+ navigateAsync,
441
+ updateCurrentEntryState,
442
+ locationEntry,
443
+ routes,
444
+ adapter,
445
+ blockerRegistry
263
446
  ]);
264
447
  }
265
448
  /**
@@ -270,6 +453,47 @@ function RouteRenderer({ matchedRoutes, index }) {
270
453
  if (!match) return null;
271
454
  const { route: route$1, params, pathname, data } = match;
272
455
  const Component = route$1.component;
456
+ const routerContext = useContext(RouterContext);
457
+ if (!routerContext) throw new Error("RouteRenderer must be used within RouterContext");
458
+ const { locationEntry, url, navigateAsync, updateCurrentEntryState } = routerContext;
459
+ const routeState$1 = locationEntry.state?.__routeStates?.[index];
460
+ const setStateSync = useCallback((stateOrUpdater) => {
461
+ const currentStates = locationEntry.state?.__routeStates ?? [];
462
+ const currentRouteState = currentStates[index];
463
+ const newState = typeof stateOrUpdater === "function" ? stateOrUpdater(currentRouteState) : stateOrUpdater;
464
+ const newStates = [...currentStates];
465
+ newStates[index] = newState;
466
+ updateCurrentEntryState({ __routeStates: newStates });
467
+ }, [
468
+ locationEntry.state,
469
+ index,
470
+ updateCurrentEntryState
471
+ ]);
472
+ const setState = useCallback(async (stateOrUpdater) => {
473
+ const currentStates = locationEntry.state?.__routeStates ?? [];
474
+ const currentRouteState = currentStates[index];
475
+ const newState = typeof stateOrUpdater === "function" ? stateOrUpdater(currentRouteState) : stateOrUpdater;
476
+ const newStates = [...currentStates];
477
+ newStates[index] = newState;
478
+ await navigateAsync(url.href, {
479
+ replace: true,
480
+ state: { __routeStates: newStates }
481
+ });
482
+ }, [
483
+ locationEntry.state,
484
+ index,
485
+ url,
486
+ navigateAsync
487
+ ]);
488
+ const resetState = useCallback(() => {
489
+ const newStates = [...locationEntry.state?.__routeStates ?? []];
490
+ newStates[index] = void 0;
491
+ updateCurrentEntryState({ __routeStates: newStates });
492
+ }, [
493
+ locationEntry.state,
494
+ index,
495
+ updateCurrentEntryState
496
+ ]);
273
497
  const outlet = index < matchedRoutes.length - 1 ? /* @__PURE__ */ jsx(RouteRenderer, {
274
498
  matchedRoutes,
275
499
  index: index + 1
@@ -285,8 +509,24 @@ function RouteRenderer({ matchedRoutes, index }) {
285
509
  ]);
286
510
  const renderComponent = () => {
287
511
  if (!Component) return outlet;
288
- if (route$1.loader) return /* @__PURE__ */ jsx(Component, { data });
289
- return /* @__PURE__ */ jsx(Component, {});
512
+ const stateProps = {
513
+ state: routeState$1,
514
+ setState,
515
+ setStateSync,
516
+ resetState
517
+ };
518
+ const { info } = locationEntry;
519
+ if (route$1.loader) return /* @__PURE__ */ jsx(Component, {
520
+ data,
521
+ params,
522
+ ...stateProps,
523
+ info
524
+ });
525
+ return /* @__PURE__ */ jsx(Component, {
526
+ params,
527
+ ...stateProps,
528
+ info
529
+ });
290
530
  };
291
531
  return /* @__PURE__ */ jsx(RouteContext.Provider, {
292
532
  value: routeContextValue,
@@ -335,17 +575,6 @@ function useLocation() {
335
575
  }, [url]);
336
576
  }
337
577
 
338
- //#endregion
339
- //#region src/hooks/useParams.ts
340
- /**
341
- * Returns route parameters from the matched path.
342
- */
343
- function useParams() {
344
- const context = useContext(RouteContext);
345
- if (!context) throw new Error("useParams must be used within a Router");
346
- return context.params;
347
- }
348
-
349
578
  //#endregion
350
579
  //#region src/hooks/useSearchParams.ts
351
580
  /**
@@ -367,12 +596,85 @@ function useSearchParams() {
367
596
  }, [context])];
368
597
  }
369
598
 
599
+ //#endregion
600
+ //#region src/hooks/useBlocker.ts
601
+ /**
602
+ * Hook to block navigation away from the current route.
603
+ *
604
+ * This is useful for scenarios like unsaved form data, ongoing file uploads,
605
+ * or any state that would be lost on navigation.
606
+ *
607
+ * @example
608
+ * ```tsx
609
+ * function EditForm() {
610
+ * const [isDirty, setIsDirty] = useState(false);
611
+ *
612
+ * useBlocker({
613
+ * shouldBlock: () => {
614
+ * if (isDirty) {
615
+ * return !confirm("You have unsaved changes. Leave anyway?");
616
+ * }
617
+ * return false;
618
+ * },
619
+ * });
620
+ *
621
+ * return <form>...</form>;
622
+ * }
623
+ * ```
624
+ *
625
+ * Note: This hook only handles SPA navigations (links, programmatic navigation).
626
+ * For hard navigations (tab close, refresh), handle `beforeunload` separately.
627
+ */
628
+ function useBlocker(options) {
629
+ const context = useContext(BlockerContext);
630
+ if (!context) throw new Error("useBlocker must be used within a Router");
631
+ const { shouldBlock } = options;
632
+ const blockerId = useId();
633
+ const { registry } = context;
634
+ useEffect(() => {
635
+ return registry.register(blockerId, shouldBlock);
636
+ }, [
637
+ blockerId,
638
+ shouldBlock,
639
+ registry
640
+ ]);
641
+ }
642
+
370
643
  //#endregion
371
644
  //#region src/route.ts
372
645
  function route(definition) {
373
646
  return definition;
374
647
  }
648
+ /**
649
+ * Helper function for creating type-safe route definitions with navigation state.
650
+ *
651
+ * Use this curried function when your route component needs to manage navigation state.
652
+ * The state is tied to the navigation history entry and persists across back/forward navigation.
653
+ *
654
+ * @example
655
+ * ```typescript
656
+ * // Route with navigation state
657
+ * type MyState = { scrollPosition: number };
658
+ * routeState<MyState>()({
659
+ * path: "users/:userId",
660
+ * component: UserPage, // Receives { params, state, setState, resetState }
661
+ * });
662
+ *
663
+ * // Route with both loader and navigation state
664
+ * type FilterState = { filter: string };
665
+ * routeState<FilterState>()({
666
+ * path: "products",
667
+ * loader: async () => fetchProducts(),
668
+ * component: ProductList, // Receives { data, params, state, setState, resetState }
669
+ * });
670
+ * ```
671
+ */
672
+ function routeState() {
673
+ return function(definition) {
674
+ return definition;
675
+ };
676
+ }
375
677
 
376
678
  //#endregion
377
- export { Outlet, Router, route, useLocation, useNavigate, useParams, useSearchParams };
679
+ export { Outlet, Router, route, routeState, useBlocker, useLocation, useNavigate, useSearchParams };
378
680
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["route","result: MatchedRoute","urlPatternPath: string","params: Record<string, string>","consumedPathname: string","route","idleController: AbortController | null","route","newParams: URLSearchParams"],"sources":["../src/context/RouterContext.ts","../src/context/RouteContext.ts","../src/types.ts","../src/core/matchRoutes.ts","../src/core/loaderCache.ts","../src/core/navigation.ts","../src/Router.tsx","../src/Outlet.tsx","../src/hooks/useNavigate.ts","../src/hooks/useLocation.ts","../src/hooks/useParams.ts","../src/hooks/useSearchParams.ts","../src/route.ts"],"sourcesContent":["import { createContext } from \"react\";\nimport type { NavigateOptions } from \"../types.js\";\n\nexport type RouterContextValue = {\n /** Current navigation entry */\n currentEntry: NavigationHistoryEntry;\n /** Current URL */\n url: URL;\n /** Navigate to a new URL */\n navigate: (to: string, options?: NavigateOptions) => void;\n};\n\nexport const RouterContext = createContext<RouterContextValue | null>(null);\n","import { createContext, type ReactNode } from \"react\";\n\nexport type RouteContextValue = {\n /** Matched route parameters */\n params: Record<string, string>;\n /** The matched path pattern */\n matchedPath: string;\n /** Child route element to render via Outlet */\n outlet: ReactNode;\n};\n\nexport const RouteContext = createContext<RouteContextValue | null>(null);\n","import type { ComponentType } from \"react\";\nimport type { LoaderArgs, RouteDefinition } from \"./route.js\";\n\nconst InternalRouteDefinitionSymbol = Symbol();\n\n/**\n * Route definition for the router.\n * When a loader is defined, the component receives the loader result as a `data` prop.\n */\nexport type InternalRouteDefinition = {\n [InternalRouteDefinitionSymbol]: never;\n /** Path pattern to match (e.g., \"users/:id\") */\n path: string;\n /** Child routes for nested routing */\n children?: InternalRouteDefinition[];\n\n // Note: `loader` and `component` may both exist or both not exist.\n // Also, `unknown`s may actually be more specific types. They are guaranteed\n // to be the same type by the `route` helper function.\n /** Data loader function for this route */\n loader?: (args: LoaderArgs) => unknown;\n /** Component to render when this route matches */\n component?: ComponentType<{ data?: unknown }>;\n};\n\n/**\n * Converts user-defined routes to internal route definitions.\n * This function is used internally by the Router.\n *\n * Actually, this function just performs a type assertion since\n * both RouteDefinition and InternalRouteDefinition have the same runtime shape.\n */\nexport function internalRoutes(\n routes: RouteDefinition[],\n): InternalRouteDefinition[] {\n return routes as InternalRouteDefinition[];\n}\n\n/**\n * A matched route with its parameters.\n */\nexport type MatchedRoute = {\n /** The original route definition */\n route: InternalRouteDefinition;\n /** Extracted path parameters */\n params: Record<string, string>;\n /** The matched pathname segment */\n pathname: string;\n};\n\n/**\n * A matched route with loader data.\n */\nexport type MatchedRouteWithData = MatchedRoute & {\n /** Data returned from the loader (undefined if no loader) */\n data: unknown | undefined;\n};\n\n/**\n * Options for navigation.\n */\nexport type NavigateOptions = {\n /** Replace current history entry instead of pushing */\n replace?: boolean;\n /** State to associate with the navigation */\n state?: unknown;\n};\n\n/**\n * Location object representing current URL state.\n */\nexport type Location = {\n pathname: string;\n search: string;\n hash: string;\n};\n","import type { InternalRouteDefinition, MatchedRoute } from \"../types.js\";\n\n/**\n * Match a pathname against a route tree, returning the matched route stack.\n * Returns null if no match is found.\n */\nexport function matchRoutes(\n routes: InternalRouteDefinition[],\n pathname: string,\n): MatchedRoute[] | null {\n for (const route of routes) {\n const matched = matchRoute(route, pathname);\n if (matched) {\n return matched;\n }\n }\n return null;\n}\n\n/**\n * Match a single route and its children recursively.\n */\nfunction matchRoute(\n route: InternalRouteDefinition,\n pathname: string,\n): MatchedRoute[] | null {\n const hasChildren = Boolean(route.children?.length);\n\n // For parent routes (with children), we need to match as a prefix\n // For leaf routes (no children), we need an exact match\n const { matched, params, consumedPathname } = matchPath(\n route.path,\n pathname,\n !hasChildren,\n );\n\n if (!matched) {\n return null;\n }\n\n const result: MatchedRoute = {\n route,\n params,\n pathname: consumedPathname,\n };\n\n // If this route has children, try to match them\n if (hasChildren) {\n // Calculate remaining pathname, ensuring it starts with /\n let remainingPathname = pathname.slice(consumedPathname.length);\n if (!remainingPathname.startsWith(\"/\")) {\n remainingPathname = \"/\" + remainingPathname;\n }\n if (remainingPathname === \"\") {\n remainingPathname = \"/\";\n }\n\n for (const child of route.children!) {\n const childMatch = matchRoute(child, remainingPathname);\n if (childMatch) {\n // Merge params from parent into children\n return [\n result,\n ...childMatch.map((m) => ({\n ...m,\n params: { ...params, ...m.params },\n })),\n ];\n }\n }\n\n // If no children matched but this route has a component, it's still a valid match\n if (route.component) {\n return [result];\n }\n\n return null;\n }\n\n return [result];\n}\n\n/**\n * Match a path pattern against a pathname.\n */\nfunction matchPath(\n pattern: string,\n pathname: string,\n exact: boolean,\n): {\n matched: boolean;\n params: Record<string, string>;\n consumedPathname: string;\n} {\n // Normalize pattern\n const normalizedPattern = pattern.startsWith(\"/\") ? pattern : `/${pattern}`;\n\n // Build URLPattern\n let urlPatternPath: string;\n if (exact) {\n urlPatternPath = normalizedPattern;\n } else if (normalizedPattern === \"/\") {\n // Special case: root path as prefix matches anything\n urlPatternPath = \"/*\";\n } else {\n // For other prefix matches, add optional wildcard suffix\n urlPatternPath = `${normalizedPattern}{/*}?`;\n }\n\n const urlPattern = new URLPattern({ pathname: urlPatternPath });\n\n const match = urlPattern.exec({ pathname });\n if (!match) {\n return { matched: false, params: {}, consumedPathname: \"\" };\n }\n\n // Extract params (excluding the wildcard group \"0\")\n const params: Record<string, string> = {};\n for (const [key, value] of Object.entries(match.pathname.groups)) {\n if (value !== undefined && key !== \"0\") {\n params[key] = value;\n }\n }\n\n // Calculate consumed pathname\n let consumedPathname: string;\n if (exact) {\n consumedPathname = pathname;\n } else if (normalizedPattern === \"/\") {\n // Root pattern consumes just \"/\"\n consumedPathname = \"/\";\n } else {\n // For prefix matches, calculate based on pattern segments\n const patternSegments = normalizedPattern.split(\"/\").filter(Boolean);\n const pathnameSegments = pathname.split(\"/\").filter(Boolean);\n consumedPathname =\n \"/\" + pathnameSegments.slice(0, patternSegments.length).join(\"/\");\n }\n\n return { matched: true, params, consumedPathname };\n}\n","import type { LoaderArgs } from \"../route.js\";\nimport type {\n MatchedRoute,\n MatchedRouteWithData,\n InternalRouteDefinition,\n} from \"../types.js\";\n\n/**\n * Cache for loader results.\n * Key format: `${entryId}:${routePath}`\n */\nconst loaderCache = new Map<string, unknown>();\n\n/**\n * Get or create a loader result from cache.\n * If the result is not cached, executes the loader and caches the result.\n */\nfunction getOrCreateLoaderResult(\n entryId: string,\n route: InternalRouteDefinition,\n args: LoaderArgs,\n): unknown | undefined {\n if (!route.loader) {\n return undefined;\n }\n\n const cacheKey = `${entryId}:${route.path}`;\n\n if (!loaderCache.has(cacheKey)) {\n loaderCache.set(cacheKey, route.loader(args));\n }\n\n return loaderCache.get(cacheKey);\n}\n\n/**\n * Create a Request object for loader args.\n */\nexport function createLoaderRequest(url: URL): Request {\n return new Request(url.href, {\n method: \"GET\",\n });\n}\n\n/**\n * Execute loaders for matched routes and return routes with data.\n * Results are cached by navigation entry id to prevent duplicate execution.\n */\nexport function executeLoaders(\n matchedRoutes: MatchedRoute[],\n entryId: string,\n request: Request,\n signal: AbortSignal,\n): MatchedRouteWithData[] {\n return matchedRoutes.map((match) => {\n const { route, params } = match;\n const args: LoaderArgs = { params, request, signal };\n const data = getOrCreateLoaderResult(entryId, route, args);\n\n return { ...match, data };\n });\n}\n\n/**\n * Clear the loader cache.\n * Mainly used for testing.\n */\nexport function clearLoaderCache(): void {\n loaderCache.clear();\n}\n","import type { InternalRouteDefinition, NavigateOptions } from \"../types.js\";\nimport { matchRoutes } from \"./matchRoutes.js\";\nimport { executeLoaders, createLoaderRequest } from \"./loaderCache.js\";\n\n/**\n * Fallback AbortController for data loading initialized outside of a navigation event.\n * Aborted when the next navigation occurs.\n *\n * To save resources, this controller is created only when needed.\n */\nlet idleController: AbortController | null = null;\n\n/**\n * Get the current abort signal for loader cancellation.\n */\nexport function getIdleAbortSignal(): AbortSignal {\n idleController ??= new AbortController();\n return idleController.signal;\n}\n\n/**\n * Reset navigation state. Used for testing.\n */\nexport function resetNavigationState(): void {\n idleController?.abort();\n idleController = null;\n}\n\n/**\n * Check if Navigation API is available.\n */\nexport function hasNavigation(): boolean {\n return typeof navigation !== \"undefined\";\n}\n\n/**\n * Subscribe to Navigation API's currententrychange event.\n * Returns a cleanup function.\n */\nexport function subscribeToNavigation(callback: () => void): () => void {\n if (!hasNavigation()) {\n return () => {};\n }\n navigation.addEventListener(\"currententrychange\", callback);\n return () => {\n if (hasNavigation()) {\n navigation.removeEventListener(\"currententrychange\", callback);\n }\n };\n}\n\n/**\n * Get current navigation entry snapshot.\n */\nexport function getNavigationSnapshot(): NavigationHistoryEntry | null {\n if (!hasNavigation()) {\n return null;\n }\n return navigation.currentEntry;\n}\n\n/**\n * Server snapshot - Navigation API not available on server.\n */\nexport function getServerSnapshot(): null {\n return null;\n}\n\n/**\n * Set up navigation interception for client-side routing.\n * Returns a cleanup function.\n */\nexport function setupNavigationInterception(\n routes: InternalRouteDefinition[],\n): () => void {\n if (!hasNavigation()) {\n return () => {};\n }\n\n const handleNavigate = (event: NavigateEvent) => {\n // Only intercept same-origin navigations\n if (!event.canIntercept || event.hashChange) {\n return;\n }\n\n // Check if the URL matches any of our routes\n const url = new URL(event.destination.url);\n const matched = matchRoutes(routes, url.pathname);\n\n if (matched) {\n // Abort initial load's loaders if this is the first navigation\n if (idleController) {\n idleController.abort();\n idleController = null;\n }\n\n event.intercept({\n handler: async () => {\n const request = createLoaderRequest(url);\n\n // Note: in response to `currententrychange` event, <Router> should already\n // have dispatched data loaders and the results should be cached.\n // Here we run executeLoader to retrieve cached results.\n const currentEntry = navigation.currentEntry;\n if (!currentEntry) {\n throw new Error(\n \"Navigation currentEntry is null during navigation interception\",\n );\n }\n\n const results = executeLoaders(\n matched,\n currentEntry.id,\n request,\n event.signal,\n );\n\n // Delay navigation until async loaders complete\n await Promise.all(results.map((r) => r.data));\n },\n });\n }\n };\n\n navigation.addEventListener(\"navigate\", handleNavigate);\n return () => {\n if (hasNavigation()) {\n navigation.removeEventListener(\"navigate\", handleNavigate);\n }\n };\n}\n\n/**\n * Navigate to a new URL programmatically.\n */\nexport function performNavigation(to: string, options?: NavigateOptions): void {\n if (!hasNavigation()) {\n return;\n }\n navigation.navigate(to, {\n history: options?.replace ? \"replace\" : \"push\",\n state: options?.state,\n });\n}\n","import {\n type ReactNode,\n useCallback,\n useEffect,\n useMemo,\n useSyncExternalStore,\n} from \"react\";\nimport { RouterContext } from \"./context/RouterContext.js\";\nimport { RouteContext } from \"./context/RouteContext.js\";\nimport {\n type NavigateOptions,\n type MatchedRouteWithData,\n internalRoutes,\n} from \"./types.js\";\nimport { matchRoutes } from \"./core/matchRoutes.js\";\nimport {\n subscribeToNavigation,\n getNavigationSnapshot,\n getServerSnapshot,\n setupNavigationInterception,\n performNavigation,\n getIdleAbortSignal,\n} from \"./core/navigation.js\";\nimport { executeLoaders, createLoaderRequest } from \"./core/loaderCache.js\";\nimport type { RouteDefinition } from \"./route.js\";\n\nexport type RouterProps = {\n routes: RouteDefinition[];\n};\n\nexport function Router({ routes: inputRoutes }: RouterProps): ReactNode {\n const routes = internalRoutes(inputRoutes);\n\n const currentEntry = useSyncExternalStore(\n subscribeToNavigation,\n getNavigationSnapshot,\n getServerSnapshot,\n );\n\n // Set up navigation interception\n useEffect(() => {\n return setupNavigationInterception(routes);\n }, [routes]);\n\n // Navigate function for programmatic navigation\n const navigate = useCallback(\n (to: string, options?: NavigateOptions) => performNavigation(to, options),\n [],\n );\n\n return useMemo(() => {\n if (currentEntry === null) {\n // This happens either when Navigation API is unavailable,\n // or the current document is not fully active.\n return null;\n }\n const currentUrl = currentEntry.url;\n if (currentUrl === null) {\n // This means currentEntry is not in this document, which is impossible\n return null;\n }\n\n const url = new URL(currentUrl);\n const currentEntryId = currentEntry.id;\n // Match current URL against routes and execute loaders\n const matchedRoutesWithData = (() => {\n const matched = matchRoutes(routes, url.pathname);\n if (!matched) return null;\n\n // Execute loaders (results are cached by navigation entry id)\n const request = createLoaderRequest(url);\n const signal = getIdleAbortSignal();\n return executeLoaders(matched, currentEntryId, request, signal);\n })();\n\n const routerContextValue = { currentEntry, url, navigate };\n\n return (\n <RouterContext.Provider value={routerContextValue}>\n {matchedRoutesWithData ? (\n <RouteRenderer matchedRoutes={matchedRoutesWithData} index={0} />\n ) : null}\n </RouterContext.Provider>\n );\n }, [navigate, currentEntry, routes]);\n}\n\ntype RouteRendererProps = {\n matchedRoutes: MatchedRouteWithData[];\n index: number;\n};\n\n/**\n * Recursively render matched routes with proper context.\n */\nfunction RouteRenderer({\n matchedRoutes,\n index,\n}: RouteRendererProps): ReactNode {\n const match = matchedRoutes[index];\n if (!match) return null;\n\n const { route, params, pathname, data } = match;\n const Component = route.component;\n\n // Create outlet for child routes\n const outlet =\n index < matchedRoutes.length - 1 ? (\n <RouteRenderer matchedRoutes={matchedRoutes} index={index + 1} />\n ) : null;\n\n const routeContextValue = useMemo(\n () => ({ params, matchedPath: pathname, outlet }),\n [params, pathname, outlet],\n );\n\n // Render component with or without data prop based on loader presence\n const renderComponent = () => {\n if (!Component) return outlet;\n\n // When loader exists, data is defined and component expects data prop\n // When loader doesn't exist, data is undefined and component doesn't expect data prop\n // TypeScript can't narrow this union, so we use runtime check with type assertion\n if (route.loader) {\n const ComponentWithData = Component as React.ComponentType<{\n data: unknown;\n }>;\n return <ComponentWithData data={data} />;\n }\n const ComponentWithoutData = Component as React.ComponentType;\n return <ComponentWithoutData />;\n };\n\n return (\n <RouteContext.Provider value={routeContextValue}>\n {renderComponent()}\n </RouteContext.Provider>\n );\n}\n","import { type ReactNode, useContext } from \"react\";\nimport { RouteContext } from \"./context/RouteContext.js\";\n\n/**\n * Renders the matched child route.\n * Used in layout components to specify where child routes should render.\n */\nexport function Outlet(): ReactNode {\n const routeContext = useContext(RouteContext);\n\n if (!routeContext) {\n return null;\n }\n\n return routeContext.outlet;\n}\n","import { useContext } from \"react\";\nimport { RouterContext } from \"../context/RouterContext.js\";\nimport type { NavigateOptions } from \"../types.js\";\n\n/**\n * Returns a function for programmatic navigation.\n */\nexport function useNavigate(): (to: string, options?: NavigateOptions) => void {\n const context = useContext(RouterContext);\n\n if (!context) {\n throw new Error(\"useNavigate must be used within a Router\");\n }\n\n return context.navigate;\n}\n","import { useContext, useMemo } from \"react\";\nimport { RouterContext } from \"../context/RouterContext.js\";\nimport type { Location } from \"../types.js\";\n\n/**\n * Returns the current location object.\n */\nexport function useLocation(): Location {\n const context = useContext(RouterContext);\n\n if (!context) {\n throw new Error(\"useLocation must be used within a Router\");\n }\n\n const { url } = context;\n\n return useMemo(() => {\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n }, [url]);\n}\n","import { useContext } from \"react\";\nimport { RouteContext } from \"../context/RouteContext.js\";\n\n/**\n * Returns route parameters from the matched path.\n */\nexport function useParams<\n T extends Record<string, string> = Record<string, string>,\n>(): T {\n const context = useContext(RouteContext);\n\n if (!context) {\n throw new Error(\"useParams must be used within a Router\");\n }\n\n return context.params as T;\n}\n","import { useCallback, useContext, useMemo } from \"react\";\nimport { RouterContext } from \"../context/RouterContext.js\";\n\ntype SetSearchParams = (\n params:\n | URLSearchParams\n | Record<string, string>\n | ((prev: URLSearchParams) => URLSearchParams | Record<string, string>),\n) => void;\n\n/**\n * Returns and allows manipulation of URL search parameters.\n */\nexport function useSearchParams(): [URLSearchParams, SetSearchParams] {\n const context = useContext(RouterContext);\n\n if (!context) {\n throw new Error(\"useSearchParams must be used within a Router\");\n }\n\n const searchParams = context.url.searchParams;\n\n const setSearchParams = useCallback<SetSearchParams>(\n (params) => {\n const url = new URL(context.url);\n\n let newParams: URLSearchParams;\n if (typeof params === \"function\") {\n const result = params(new URLSearchParams(url.search));\n newParams =\n result instanceof URLSearchParams\n ? result\n : new URLSearchParams(result);\n } else if (params instanceof URLSearchParams) {\n newParams = params;\n } else {\n newParams = new URLSearchParams(params);\n }\n\n url.search = newParams.toString();\n context.navigate(url.pathname + url.search + url.hash, { replace: true });\n },\n [context],\n );\n\n return [searchParams, setSearchParams];\n}\n","import type { ComponentType } from \"react\";\n\nconst routeDefinitionSymbol = Symbol();\n\n/**\n * Arguments passed to loader functions.\n */\nexport type LoaderArgs = {\n /** Extracted path parameters */\n params: Record<string, string>;\n /** Request object with URL and headers */\n request: Request;\n /** AbortSignal for cancellation on navigation */\n signal: AbortSignal;\n};\n\n/**\n * Route definition created by the `route` helper function.\n */\nexport interface OpaqueRouteDefinition {\n [routeDefinitionSymbol]: never;\n path: string;\n children?: RouteDefinition[];\n}\n\n/**\n * Any route definition defined by user.\n */\nexport type RouteDefinition =\n | OpaqueRouteDefinition\n | {\n path: string;\n component?: ComponentType<{}>;\n children?: RouteDefinition[];\n };\n\n/**\n * Route definition with loader - infers TData from loader return type.\n */\ntype RouteWithLoader<TData> = {\n path: string;\n loader: (args: LoaderArgs) => TData;\n component: ComponentType<{ data: TData }>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n children?: RouteDefinition[];\n};\n\n/**\n * Route definition without loader.\n */\ntype RouteWithoutLoader = {\n path: string;\n component?: ComponentType;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n children?: RouteDefinition[];\n};\n\n/**\n * Helper function for creating type-safe route definitions.\n *\n * When a loader is provided, TypeScript infers the return type and ensures\n * the component accepts a `data` prop of that type.\n *\n * @example\n * ```typescript\n * // Route with async loader\n * route({\n * path: \"users/:userId\",\n * loader: async ({ params, signal }) => {\n * const res = await fetch(`/api/users/${params.userId}`, { signal });\n * return res.json() as Promise<User>;\n * },\n * component: UserDetail, // Must accept { data: Promise<User> }\n * });\n *\n * // Route without loader\n * route({\n * path: \"about\",\n * component: AboutPage, // No data prop required\n * });\n * ```\n */\nexport function route<TData>(\n definition: RouteWithLoader<TData>,\n): OpaqueRouteDefinition;\nexport function route(definition: RouteWithoutLoader): OpaqueRouteDefinition;\nexport function route<TData>(\n definition: RouteWithLoader<TData> | RouteWithoutLoader,\n): OpaqueRouteDefinition {\n return definition as OpaqueRouteDefinition;\n}\n"],"mappings":";;;;AAYA,MAAa,gBAAgB,cAAyC,KAAK;;;;ACD3E,MAAa,eAAe,cAAwC,KAAK;;;;;;;;;;;ACqBzE,SAAgB,eACd,QAC2B;AAC3B,QAAO;;;;;;;;;AC7BT,SAAgB,YACd,QACA,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;;ACPtB,SAAgB,cAA+D;CAC7E,MAAM,UAAU,WAAW,cAAc;AAEzC,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,2CAA2C;AAG7D,QAAO,QAAQ;;;;;;;;ACPjB,SAAgB,cAAwB;CACtC,MAAM,UAAU,WAAW,cAAc;AAEzC,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,2CAA2C;CAG7D,MAAM,EAAE,QAAQ;AAEhB,QAAO,cAAc;AACnB,SAAO;GACL,UAAU,IAAI;GACd,QAAQ,IAAI;GACZ,MAAM,IAAI;GACX;IACA,CAAC,IAAI,CAAC;;;;;;;;AChBX,SAAgB,YAET;CACL,MAAM,UAAU,WAAW,aAAa;AAExC,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,yCAAyC;AAG3D,QAAO,QAAQ;;;;;;;;ACFjB,SAAgB,kBAAsD;CACpE,MAAM,UAAU,WAAW,cAAc;AAEzC,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,+CAA+C;AA4BjE,QAAO,CAzBc,QAAQ,IAAI,cAET,aACrB,WAAW;EACV,MAAM,MAAM,IAAI,IAAI,QAAQ,IAAI;EAEhC,IAAIC;AACJ,MAAI,OAAO,WAAW,YAAY;GAChC,MAAM,SAAS,OAAO,IAAI,gBAAgB,IAAI,OAAO,CAAC;AACtD,eACE,kBAAkB,kBACd,SACA,IAAI,gBAAgB,OAAO;aACxB,kBAAkB,gBAC3B,aAAY;MAEZ,aAAY,IAAI,gBAAgB,OAAO;AAGzC,MAAI,SAAS,UAAU,UAAU;AACjC,UAAQ,SAAS,IAAI,WAAW,IAAI,SAAS,IAAI,MAAM,EAAE,SAAS,MAAM,CAAC;IAE3E,CAAC,QAAQ,CACV,CAEqC;;;;;ACyCxC,SAAgB,MACd,YACuB;AACvB,QAAO"}
1
+ {"version":3,"file":"index.mjs","names":["route","result: MatchedRoute","urlPatternPath: string","params: Record<string, string>","consumedPathname: string","route","idleController: AbortController | null","#cachedEntryId","#cachedSnapshot","#currentNavigationInfo","#subscribeToDisposeEvents","#subscribedEntryIds","#cachedSnapshot","#idleController","#idleController","route","routeState","newParams: URLSearchParams"],"sources":["../src/context/RouterContext.ts","../src/context/RouteContext.ts","../src/context/BlockerContext.ts","../src/types.ts","../src/core/matchRoutes.ts","../src/core/loaderCache.ts","../src/core/NavigationAPIAdapter.ts","../src/core/StaticAdapter.ts","../src/core/NullAdapter.ts","../src/core/createAdapter.ts","../src/Router.tsx","../src/Outlet.tsx","../src/hooks/useNavigate.ts","../src/hooks/useLocation.ts","../src/hooks/useSearchParams.ts","../src/hooks/useBlocker.ts","../src/route.ts"],"sourcesContent":["import { createContext } from \"react\";\nimport type { NavigateOptions } from \"../types.js\";\nimport type { LocationEntry } from \"../core/RouterAdapter.js\";\n\nexport type RouterContextValue = {\n /** Current location entry */\n locationEntry: LocationEntry;\n /** Current URL */\n url: URL;\n /** Navigate to a new URL */\n navigate: (to: string, options?: NavigateOptions) => void;\n /** Navigate to a new URL and wait for completion */\n navigateAsync: (to: string, options?: NavigateOptions) => Promise<void>;\n /** Update current entry's state without navigation */\n updateCurrentEntryState: (state: unknown) => void;\n};\n\nexport const RouterContext = createContext<RouterContextValue | null>(null);\n","import { createContext, type ReactNode } from \"react\";\n\nexport type RouteContextValue = {\n /** Matched route parameters */\n params: Record<string, string>;\n /** The matched path pattern */\n matchedPath: string;\n /** Child route element to render via Outlet */\n outlet: ReactNode;\n};\n\nexport const RouteContext = createContext<RouteContextValue | null>(null);\n","import { createContext } from \"react\";\n\nexport type BlockerId = string;\n\nexport type BlockerRegistry = {\n /** Register a blocker, returns unregister function */\n register: (id: BlockerId, shouldBlock: () => boolean) => () => void;\n /** Check all blockers - returns true if any blocks */\n checkAll: () => boolean;\n};\n\nexport type BlockerContextValue = {\n registry: BlockerRegistry;\n};\n\n/**\n * Create a new blocker registry.\n * The registry manages registered blockers and provides a way to check if any blocker is active.\n */\nexport function createBlockerRegistry(): BlockerRegistry {\n const blockers = new Map<BlockerId, () => boolean>();\n\n return {\n register(id: BlockerId, shouldBlock: () => boolean): () => void {\n blockers.set(id, shouldBlock);\n return () => {\n blockers.delete(id);\n };\n },\n\n checkAll(): boolean {\n for (const shouldBlock of blockers.values()) {\n if (shouldBlock()) {\n return true;\n }\n }\n return false;\n },\n };\n}\n\nexport const BlockerContext = createContext<BlockerContextValue | null>(null);\n","import type { ComponentType } from \"react\";\nimport type { LoaderArgs, RouteDefinition } from \"./route.js\";\n\nconst InternalRouteDefinitionSymbol = Symbol();\n\n/**\n * Internal structure for storing per-route state in NavigationHistoryEntry.\n * Each route in the matched stack gets its own state slot indexed by match position.\n */\nexport type InternalRouteState = {\n __routeStates: (unknown | undefined)[];\n};\n\n/**\n * Route definition for the router.\n * When a loader is defined, the component receives the loader result as a `data` prop.\n */\nexport type InternalRouteDefinition = {\n [InternalRouteDefinitionSymbol]: never;\n /** Path pattern to match (e.g., \"users/:id\") */\n path: string;\n /** Child routes for nested routing */\n children?: InternalRouteDefinition[];\n\n // Note: `loader` and `component` may both exist or both not exist.\n // Also, `unknown`s may actually be more specific types. They are guaranteed\n // to be the same type by the `route` helper function.\n /** Data loader function for this route */\n loader?: (args: LoaderArgs) => unknown;\n /** Component to render when this route matches */\n component?: ComponentType<{\n data?: unknown;\n params?: Record<string, string>;\n state?: unknown;\n setState?: (state: unknown | ((prev: unknown) => unknown)) => Promise<void>;\n setStateSync?: (state: unknown | ((prev: unknown) => unknown)) => void;\n resetState?: () => void;\n info?: unknown;\n }>;\n};\n\n/**\n * Converts user-defined routes to internal route definitions.\n * This function is used internally by the Router.\n *\n * Actually, this function just performs a type assertion since\n * both RouteDefinition and InternalRouteDefinition have the same runtime shape.\n */\nexport function internalRoutes(\n routes: RouteDefinition[],\n): InternalRouteDefinition[] {\n return routes as InternalRouteDefinition[];\n}\n\n/**\n * A matched route with its parameters.\n */\nexport type MatchedRoute = {\n /** The original route definition */\n route: InternalRouteDefinition;\n /** Extracted path parameters */\n params: Record<string, string>;\n /** The matched pathname segment */\n pathname: string;\n};\n\n/**\n * A matched route with loader data.\n */\nexport type MatchedRouteWithData = MatchedRoute & {\n /** Data returned from the loader (undefined if no loader) */\n data: unknown | undefined;\n};\n\n/**\n * Options for navigation.\n */\nexport type NavigateOptions = {\n /** Replace current history entry instead of pushing */\n replace?: boolean;\n /** State to associate with the navigation */\n state?: unknown;\n /** Ephemeral info for this navigation only (not persisted in history) */\n info?: unknown;\n};\n\n/**\n * Location object representing current URL state.\n */\nexport type Location = {\n pathname: string;\n search: string;\n hash: string;\n};\n\n/**\n * Callback invoked before navigation is intercepted.\n * Call `event.preventDefault()` to prevent the router from handling this navigation.\n *\n * @param event - The NavigateEvent from the Navigation API\n * @param matched - Array of matched routes, or null if no routes matched\n */\nexport type OnNavigateCallback = (\n event: NavigateEvent,\n matched: readonly MatchedRoute[] | null,\n) => void;\n\n/**\n * Fallback mode when Navigation API is unavailable.\n *\n * - `\"none\"` (default): Render nothing when Navigation API is unavailable\n * - `\"static\"`: Render matched routes without navigation capabilities (MPA behavior)\n */\nexport type FallbackMode =\n | \"none\" // Default: render nothing when Navigation API unavailable\n | \"static\"; // Render matched routes without navigation capabilities\n","import type { InternalRouteDefinition, MatchedRoute } from \"../types.js\";\n\n/**\n * Match a pathname against a route tree, returning the matched route stack.\n * Returns null if no match is found.\n */\nexport function matchRoutes(\n routes: InternalRouteDefinition[],\n pathname: string,\n): MatchedRoute[] | null {\n for (const route of routes) {\n const matched = matchRoute(route, pathname);\n if (matched) {\n return matched;\n }\n }\n return null;\n}\n\n/**\n * Match a single route and its children recursively.\n */\nfunction matchRoute(\n route: InternalRouteDefinition,\n pathname: string,\n): MatchedRoute[] | null {\n const hasChildren = Boolean(route.children?.length);\n\n // For parent routes (with children), we need to match as a prefix\n // For leaf routes (no children), we need an exact match\n const { matched, params, consumedPathname } = matchPath(\n route.path,\n pathname,\n !hasChildren,\n );\n\n if (!matched) {\n return null;\n }\n\n const result: MatchedRoute = {\n route,\n params,\n pathname: consumedPathname,\n };\n\n // If this route has children, try to match them\n if (hasChildren) {\n // Calculate remaining pathname, ensuring it starts with /\n let remainingPathname = pathname.slice(consumedPathname.length);\n if (!remainingPathname.startsWith(\"/\")) {\n remainingPathname = \"/\" + remainingPathname;\n }\n if (remainingPathname === \"\") {\n remainingPathname = \"/\";\n }\n\n for (const child of route.children!) {\n const childMatch = matchRoute(child, remainingPathname);\n if (childMatch) {\n // Merge params from parent into children\n return [\n result,\n ...childMatch.map((m) => ({\n ...m,\n params: { ...params, ...m.params },\n })),\n ];\n }\n }\n\n // If no children matched but this route has a component, it's still a valid match\n if (route.component) {\n return [result];\n }\n\n return null;\n }\n\n return [result];\n}\n\n/**\n * Match a path pattern against a pathname.\n */\nfunction matchPath(\n pattern: string,\n pathname: string,\n exact: boolean,\n): {\n matched: boolean;\n params: Record<string, string>;\n consumedPathname: string;\n} {\n // Normalize pattern\n const normalizedPattern = pattern.startsWith(\"/\") ? pattern : `/${pattern}`;\n\n // Build URLPattern\n let urlPatternPath: string;\n if (exact) {\n urlPatternPath = normalizedPattern;\n } else if (normalizedPattern === \"/\") {\n // Special case: root path as prefix matches anything\n urlPatternPath = \"/*\";\n } else {\n // For other prefix matches, add optional wildcard suffix\n urlPatternPath = `${normalizedPattern}{/*}?`;\n }\n\n const urlPattern = new URLPattern({ pathname: urlPatternPath });\n\n const match = urlPattern.exec({ pathname });\n if (!match) {\n return { matched: false, params: {}, consumedPathname: \"\" };\n }\n\n // Extract params (excluding the wildcard group \"0\")\n const params: Record<string, string> = {};\n for (const [key, value] of Object.entries(match.pathname.groups)) {\n if (value !== undefined && key !== \"0\") {\n params[key] = value;\n }\n }\n\n // Calculate consumed pathname\n let consumedPathname: string;\n if (exact) {\n consumedPathname = pathname;\n } else if (normalizedPattern === \"/\") {\n // Root pattern consumes just \"/\"\n consumedPathname = \"/\";\n } else {\n // For prefix matches, calculate based on pattern segments\n const patternSegments = normalizedPattern.split(\"/\").filter(Boolean);\n const pathnameSegments = pathname.split(\"/\").filter(Boolean);\n consumedPathname =\n \"/\" + pathnameSegments.slice(0, patternSegments.length).join(\"/\");\n }\n\n return { matched: true, params, consumedPathname };\n}\n","import type { LoaderArgs } from \"../route.js\";\nimport type {\n MatchedRoute,\n MatchedRouteWithData,\n InternalRouteDefinition,\n} from \"../types.js\";\n\n/**\n * Cache for loader results.\n * Key format: `${entryId}:${matchIndex}`\n */\nconst loaderCache = new Map<string, unknown>();\n\n/**\n * Get or create a loader result from cache.\n * If the result is not cached, executes the loader and caches the result.\n */\nfunction getOrCreateLoaderResult(\n entryId: string,\n matchIndex: number,\n route: InternalRouteDefinition,\n args: LoaderArgs,\n): unknown | undefined {\n if (!route.loader) {\n return undefined;\n }\n\n const cacheKey = `${entryId}:${matchIndex}`;\n\n if (!loaderCache.has(cacheKey)) {\n loaderCache.set(cacheKey, route.loader(args));\n }\n\n return loaderCache.get(cacheKey);\n}\n\n/**\n * Create a Request object for loader args.\n */\nexport function createLoaderRequest(url: URL): Request {\n return new Request(url.href, {\n method: \"GET\",\n });\n}\n\n/**\n * Execute loaders for matched routes and return routes with data.\n * Results are cached by navigation entry id to prevent duplicate execution.\n */\nexport function executeLoaders(\n matchedRoutes: MatchedRoute[],\n entryId: string,\n request: Request,\n signal: AbortSignal,\n): MatchedRouteWithData[] {\n return matchedRoutes.map((match, index) => {\n const { route, params } = match;\n const args: LoaderArgs = { params, request, signal };\n const data = getOrCreateLoaderResult(entryId, index, route, args);\n\n return { ...match, data };\n });\n}\n\n/**\n * Clear the loader cache.\n * Mainly used for testing.\n */\nexport function clearLoaderCache(): void {\n loaderCache.clear();\n}\n\n/**\n * Clear loader cache entries for a specific navigation entry.\n * Called when a NavigationHistoryEntry is disposed (removed from history stack).\n */\nexport function clearLoaderCacheForEntry(entryId: string): void {\n const prefix = `${entryId}:`;\n for (const key of loaderCache.keys()) {\n if (key.startsWith(prefix)) {\n loaderCache.delete(key);\n }\n }\n}\n","import type { RouterAdapter, LocationEntry } from \"./RouterAdapter.js\";\nimport type {\n InternalRouteDefinition,\n NavigateOptions,\n OnNavigateCallback,\n} from \"../types.js\";\nimport { matchRoutes } from \"./matchRoutes.js\";\nimport {\n executeLoaders,\n createLoaderRequest,\n clearLoaderCacheForEntry,\n} from \"./loaderCache.js\";\n\n/**\n * Fallback AbortController for data loading initialized outside of a navigation event.\n * Aborted when the next navigation occurs.\n *\n * To save resources, this controller is created only when needed.\n */\nlet idleController: AbortController | null = null;\n\n/**\n * Reset navigation state. Used for testing.\n */\nexport function resetNavigationState(): void {\n idleController?.abort();\n idleController = null;\n}\n\n/**\n * Adapter that uses the Navigation API for full SPA functionality.\n */\nexport class NavigationAPIAdapter implements RouterAdapter {\n // Cache the snapshot to ensure referential stability for useSyncExternalStore\n #cachedSnapshot: LocationEntry | null = null;\n #cachedEntryId: string | null = null;\n // Ephemeral info from the current navigation event (not persisted in history)\n #currentNavigationInfo: unknown = undefined;\n\n getSnapshot(): LocationEntry | null {\n const entry = navigation.currentEntry;\n if (!entry?.url) {\n return null;\n }\n\n // Return cached snapshot if entry hasn't changed\n if (this.#cachedEntryId === entry.id && this.#cachedSnapshot) {\n return this.#cachedSnapshot;\n }\n\n // Create new snapshot and cache it\n this.#cachedEntryId = entry.id;\n this.#cachedSnapshot = {\n url: new URL(entry.url),\n key: entry.id,\n state: entry.getState(),\n info: this.#currentNavigationInfo,\n };\n return this.#cachedSnapshot;\n }\n\n getServerSnapshot(): LocationEntry | null {\n return null;\n }\n\n subscribe(callback: () => void): () => void {\n const controller = new AbortController();\n navigation.addEventListener(\"currententrychange\", callback, {\n signal: controller.signal,\n });\n\n // Subscribe to dispose events on all existing entries\n this.#subscribeToDisposeEvents(controller.signal);\n\n // When current entry changes, subscribe to any new entries' dispose events\n navigation.addEventListener(\n \"currententrychange\",\n () => this.#subscribeToDisposeEvents(controller.signal),\n { signal: controller.signal },\n );\n\n return () => {\n controller.abort();\n };\n }\n\n /**\n * Track which entries we've subscribed to dispose events for.\n */\n #subscribedEntryIds = new Set<string>();\n\n /**\n * Subscribe to dispose events on all navigation entries.\n * When an entry is disposed, its cached loader results are cleared.\n */\n #subscribeToDisposeEvents(signal: AbortSignal): void {\n for (const entry of navigation.entries()) {\n if (this.#subscribedEntryIds.has(entry.id)) {\n continue;\n }\n this.#subscribedEntryIds.add(entry.id);\n\n const entryId = entry.id;\n entry.addEventListener(\n \"dispose\",\n () => {\n clearLoaderCacheForEntry(entryId);\n this.#subscribedEntryIds.delete(entryId);\n },\n { signal },\n );\n }\n }\n\n navigate(to: string, options?: NavigateOptions): void {\n navigation.navigate(to, {\n history: options?.replace ? \"replace\" : \"push\",\n state: options?.state,\n info: options?.info,\n });\n }\n\n async navigateAsync(to: string, options?: NavigateOptions): Promise<void> {\n const result = navigation.navigate(to, {\n history: options?.replace ? \"replace\" : \"push\",\n state: options?.state,\n info: options?.info,\n });\n await result.finished;\n }\n\n setupInterception(\n routes: InternalRouteDefinition[],\n onNavigate?: OnNavigateCallback,\n checkBlockers?: () => boolean,\n ): (() => void) | undefined {\n const handleNavigate = (event: NavigateEvent) => {\n // Capture ephemeral info from the navigate event\n // This info is only available during this navigation and resets on the next one\n this.#currentNavigationInfo = event.info;\n // Invalidate cached snapshot to pick up new info\n this.#cachedSnapshot = null;\n\n // Check blockers first - if any blocker returns true, prevent navigation\n if (checkBlockers?.()) {\n event.preventDefault();\n return;\n }\n\n // Only intercept same-origin navigations\n if (!event.canIntercept) {\n onNavigate?.(event, []);\n return;\n }\n\n // Check if the URL matches any of our routes\n const url = new URL(event.destination.url);\n const matched = matchRoutes(routes, url.pathname);\n\n // Call onNavigate callback if provided (regardless of route match)\n if (onNavigate) {\n onNavigate(event, matched);\n if (event.defaultPrevented) {\n return; // Do not intercept, allow browser default\n }\n }\n\n // hash change navigations are not intercepted.\n // Also do not intercept if it is a download request.\n if (event.hashChange || event.downloadRequest !== null) {\n return;\n }\n\n if (!matched) {\n return;\n }\n\n // Route match, so intercept\n\n // Abort initial load's loaders if this is the first navigation\n if (idleController) {\n idleController.abort();\n idleController = null;\n }\n\n event.intercept({\n handler: async () => {\n const request = createLoaderRequest(url);\n\n // Note: in response to `currententrychange` event, <Router> should already\n // have dispatched data loaders and the results should be cached.\n // Here we run executeLoader to retrieve cached results.\n const currentEntry = navigation.currentEntry;\n if (!currentEntry) {\n throw new Error(\n \"Navigation currentEntry is null during navigation interception\",\n );\n }\n\n const results = executeLoaders(\n matched,\n currentEntry.id,\n request,\n event.signal,\n );\n\n // Delay navigation until async loaders complete\n await Promise.all(results.map((r) => r.data));\n },\n });\n };\n\n const controller = new AbortController();\n navigation.addEventListener(\"navigate\", handleNavigate, {\n signal: controller.signal,\n });\n return () => {\n controller.abort();\n };\n }\n\n getIdleAbortSignal(): AbortSignal {\n idleController ??= new AbortController();\n return idleController.signal;\n }\n\n updateCurrentEntryState(state: unknown): void {\n // Invalidate cached snapshot BEFORE updating, so the subscriber gets fresh state\n this.#cachedSnapshot = null;\n navigation.updateCurrentEntry({ state });\n // Note: updateCurrentEntry fires currententrychange, so subscribers are notified automatically\n }\n}\n","import type { RouterAdapter, LocationEntry } from \"./RouterAdapter.js\";\nimport type {\n InternalRouteDefinition,\n NavigateOptions,\n OnNavigateCallback,\n} from \"../types.js\";\n\n/**\n * Static adapter for fallback mode when Navigation API is unavailable.\n * Provides read-only location access with no SPA navigation capabilities.\n * Links will cause full page loads (MPA behavior).\n */\nexport class StaticAdapter implements RouterAdapter {\n #cachedSnapshot: LocationEntry | null = null;\n #idleController: AbortController | null = null;\n\n getSnapshot(): LocationEntry | null {\n if (typeof window === \"undefined\") {\n return null;\n }\n\n // Cache the snapshot - it never changes in static mode\n if (!this.#cachedSnapshot) {\n this.#cachedSnapshot = {\n url: new URL(window.location.href),\n key: \"__static__\",\n state: undefined,\n info: undefined,\n };\n }\n return this.#cachedSnapshot;\n }\n\n getServerSnapshot(): LocationEntry | null {\n return null;\n }\n\n subscribe(_callback: () => void): () => void {\n // Static mode never fires location change events\n return () => {};\n }\n\n navigate(to: string, _options?: NavigateOptions): void {\n console.warn(\n \"FUNSTACK Router: navigate() called in static fallback mode. \" +\n \"Navigation API is not available in this browser. \" +\n \"Links will cause full page loads.\",\n );\n // Note: We intentionally do NOT do window.location.href = to\n // as that would mask bugs where developers expect SPA behavior.\n // If needed in the future, we could add a \"static-reload\" mode.\n }\n\n async navigateAsync(to: string, options?: NavigateOptions): Promise<void> {\n this.navigate(to, options);\n }\n\n setupInterception(\n _routes: InternalRouteDefinition[],\n _onNavigate?: OnNavigateCallback,\n _checkBlockers?: () => boolean,\n ): (() => void) | undefined {\n // No interception in static mode - links cause full page loads\n return undefined;\n }\n\n getIdleAbortSignal(): AbortSignal {\n this.#idleController ??= new AbortController();\n return this.#idleController.signal;\n }\n\n updateCurrentEntryState(_state: unknown): void {\n // No-op in static mode - state updates require Navigation API\n }\n}\n","import type { RouterAdapter, LocationEntry } from \"./RouterAdapter.js\";\nimport type {\n InternalRouteDefinition,\n NavigateOptions,\n OnNavigateCallback,\n} from \"../types.js\";\n\n/**\n * Null adapter for when Navigation API is unavailable and no fallback is configured.\n * All methods are no-ops that return safe default values.\n */\nexport class NullAdapter implements RouterAdapter {\n #idleController: AbortController | null = null;\n\n getSnapshot(): LocationEntry | null {\n return null;\n }\n\n getServerSnapshot(): LocationEntry | null {\n return null;\n }\n\n subscribe(_callback: () => void): () => void {\n return () => {};\n }\n\n navigate(_to: string, _options?: NavigateOptions): void {\n console.warn(\n \"FUNSTACK Router: navigate() called but no adapter is available. \" +\n \"Navigation API is not available in this browser and no fallback mode is configured.\",\n );\n }\n\n async navigateAsync(to: string, options?: NavigateOptions): Promise<void> {\n this.navigate(to, options);\n }\n\n setupInterception(\n _routes: InternalRouteDefinition[],\n _onNavigate?: OnNavigateCallback,\n _checkBlockers?: () => boolean,\n ): (() => void) | undefined {\n return undefined;\n }\n\n getIdleAbortSignal(): AbortSignal {\n this.#idleController ??= new AbortController();\n return this.#idleController.signal;\n }\n\n updateCurrentEntryState(_state: unknown): void {\n // No-op: NullAdapter doesn't support state updates\n }\n}\n","import type { RouterAdapter } from \"./RouterAdapter.js\";\nimport { NavigationAPIAdapter } from \"./NavigationAPIAdapter.js\";\nimport { StaticAdapter } from \"./StaticAdapter.js\";\nimport { NullAdapter } from \"./NullAdapter.js\";\nimport type { FallbackMode } from \"../types.js\";\n\n/**\n * Check if Navigation API is available.\n */\nfunction hasNavigation(): boolean {\n return typeof window !== \"undefined\" && \"navigation\" in window;\n}\n\n/**\n * Create the appropriate router adapter based on browser capabilities\n * and the specified fallback mode.\n *\n * @param fallback - The fallback mode to use when Navigation API is unavailable\n * @returns A RouterAdapter instance\n */\nexport function createAdapter(fallback: FallbackMode): RouterAdapter {\n // Try Navigation API first\n if (hasNavigation()) {\n return new NavigationAPIAdapter();\n }\n\n // Fall back to static mode if enabled\n if (fallback === \"static\") {\n return new StaticAdapter();\n }\n\n // No adapter available (fallback=\"none\" or default)\n return new NullAdapter();\n}\n","import {\n type ReactNode,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { RouterContext } from \"./context/RouterContext.js\";\nimport { RouteContext } from \"./context/RouteContext.js\";\nimport {\n BlockerContext,\n createBlockerRegistry,\n} from \"./context/BlockerContext.js\";\nimport {\n type NavigateOptions,\n type MatchedRouteWithData,\n type OnNavigateCallback,\n type FallbackMode,\n type InternalRouteState,\n internalRoutes,\n} from \"./types.js\";\nimport { matchRoutes } from \"./core/matchRoutes.js\";\nimport { createAdapter } from \"./core/createAdapter.js\";\nimport { executeLoaders, createLoaderRequest } from \"./core/loaderCache.js\";\nimport type { RouteDefinition } from \"./route.js\";\n\nexport type RouterProps = {\n routes: RouteDefinition[];\n /**\n * Callback invoked before navigation is intercepted.\n * Call `event.preventDefault()` to prevent the router from handling this navigation.\n *\n * @param event - The NavigateEvent from the Navigation API\n * @param matched - Array of matched routes, or null if no routes matched\n */\n onNavigate?: OnNavigateCallback;\n /**\n * Fallback mode when Navigation API is unavailable.\n *\n * - `\"none\"` (default): Render nothing when Navigation API is unavailable\n * - `\"static\"`: Render matched routes without navigation capabilities (MPA behavior)\n */\n fallback?: FallbackMode;\n};\n\nexport function Router({\n routes: inputRoutes,\n onNavigate,\n fallback = \"none\",\n}: RouterProps): ReactNode {\n const routes = internalRoutes(inputRoutes);\n\n // Create adapter once based on browser capabilities and fallback setting\n const adapter = useMemo(() => createAdapter(fallback), [fallback]);\n\n // Create blocker registry once\n const [blockerRegistry] = useState(() => createBlockerRegistry());\n\n // Subscribe to location changes via adapter\n const locationEntry = useSyncExternalStore(\n useCallback((callback) => adapter.subscribe(callback), [adapter]),\n () => adapter.getSnapshot(),\n () => adapter.getServerSnapshot(),\n );\n\n // Set up navigation interception via adapter\n useEffect(() => {\n return adapter.setupInterception(\n routes,\n onNavigate,\n blockerRegistry.checkAll,\n );\n }, [adapter, routes, onNavigate, blockerRegistry]);\n\n // Navigate function from adapter\n const navigate = useCallback(\n (to: string, options?: NavigateOptions) => {\n adapter.navigate(to, options);\n },\n [adapter],\n );\n\n // Navigate function that returns a Promise\n const navigateAsync = useCallback(\n (to: string, options?: NavigateOptions) => {\n return adapter.navigateAsync(to, options);\n },\n [adapter],\n );\n\n // Update current entry's state without navigation\n const updateCurrentEntryState = useCallback(\n (state: unknown) => {\n adapter.updateCurrentEntryState(state);\n },\n [adapter],\n );\n\n return useMemo(() => {\n if (locationEntry === null) {\n // This happens either when Navigation API is unavailable (and no fallback),\n // or the current document is not fully active.\n return null;\n }\n\n const { url, key } = locationEntry;\n\n // Match current URL against routes and execute loaders\n const matchedRoutesWithData = (() => {\n const matched = matchRoutes(routes, url.pathname);\n if (!matched) return null;\n\n // Execute loaders (results are cached by location entry key)\n const request = createLoaderRequest(url);\n const signal = adapter.getIdleAbortSignal();\n return executeLoaders(matched, key, request, signal);\n })();\n\n const routerContextValue = {\n locationEntry,\n url,\n navigate,\n navigateAsync,\n updateCurrentEntryState,\n };\n\n const blockerContextValue = { registry: blockerRegistry };\n\n return (\n <BlockerContext.Provider value={blockerContextValue}>\n <RouterContext.Provider value={routerContextValue}>\n {matchedRoutesWithData ? (\n <RouteRenderer matchedRoutes={matchedRoutesWithData} index={0} />\n ) : null}\n </RouterContext.Provider>\n </BlockerContext.Provider>\n );\n }, [\n navigate,\n navigateAsync,\n updateCurrentEntryState,\n locationEntry,\n routes,\n adapter,\n blockerRegistry,\n ]);\n}\n\ntype RouteRendererProps = {\n matchedRoutes: MatchedRouteWithData[];\n index: number;\n};\n\n/**\n * Recursively render matched routes with proper context.\n */\nfunction RouteRenderer({\n matchedRoutes,\n index,\n}: RouteRendererProps): ReactNode {\n const match = matchedRoutes[index];\n if (!match) return null;\n\n const { route, params, pathname, data } = match;\n const Component = route.component;\n\n const routerContext = useContext(RouterContext);\n if (!routerContext) {\n throw new Error(\"RouteRenderer must be used within RouterContext\");\n }\n const { locationEntry, url, navigateAsync, updateCurrentEntryState } =\n routerContext;\n\n // Extract this route's state from internal structure\n const internalState = locationEntry.state as InternalRouteState | undefined;\n const routeState = internalState?.__routeStates?.[index];\n\n // Create stable setStateSync callback for this route's slice (synchronous via updateCurrentEntry)\n const setStateSync = useCallback(\n (stateOrUpdater: unknown | ((prev: unknown) => unknown)) => {\n const currentStates =\n (locationEntry.state as InternalRouteState | undefined)\n ?.__routeStates ?? [];\n const currentRouteState = currentStates[index];\n\n const newState =\n typeof stateOrUpdater === \"function\"\n ? (stateOrUpdater as (prev: unknown) => unknown)(currentRouteState)\n : stateOrUpdater;\n\n const newStates = [...currentStates];\n newStates[index] = newState;\n updateCurrentEntryState({ __routeStates: newStates });\n },\n [locationEntry.state, index, updateCurrentEntryState],\n );\n\n // Create stable setState callback for this route's slice (async via replace navigation)\n const setState = useCallback(\n async (\n stateOrUpdater: unknown | ((prev: unknown) => unknown),\n ): Promise<void> => {\n const currentStates =\n (locationEntry.state as InternalRouteState | undefined)\n ?.__routeStates ?? [];\n const currentRouteState = currentStates[index];\n\n const newState =\n typeof stateOrUpdater === \"function\"\n ? (stateOrUpdater as (prev: unknown) => unknown)(currentRouteState)\n : stateOrUpdater;\n\n const newStates = [...currentStates];\n newStates[index] = newState;\n\n await navigateAsync(url.href, {\n replace: true,\n state: { __routeStates: newStates },\n });\n },\n [locationEntry.state, index, url, navigateAsync],\n );\n\n // Create stable resetState callback\n const resetState = useCallback(() => {\n const currentStates =\n (locationEntry.state as InternalRouteState | undefined)?.__routeStates ??\n [];\n const newStates = [...currentStates];\n newStates[index] = undefined;\n updateCurrentEntryState({ __routeStates: newStates });\n }, [locationEntry.state, index, updateCurrentEntryState]);\n\n // Create outlet for child routes\n const outlet =\n index < matchedRoutes.length - 1 ? (\n <RouteRenderer matchedRoutes={matchedRoutes} index={index + 1} />\n ) : null;\n\n const routeContextValue = useMemo(\n () => ({ params, matchedPath: pathname, outlet }),\n [params, pathname, outlet],\n );\n\n // Render component with or without data prop based on loader presence\n // Always pass params, state, setState, resetState, and info props to components\n const renderComponent = () => {\n if (!Component) return outlet;\n\n const stateProps = {\n state: routeState,\n setState,\n setStateSync,\n resetState,\n };\n\n // Ephemeral info from the current navigation\n const { info } = locationEntry;\n\n // When loader exists, data is defined and component expects data prop\n // When loader doesn't exist, data is undefined and component doesn't expect data prop\n // TypeScript can't narrow this union, so we use runtime check with type assertion\n if (route.loader) {\n const ComponentWithData = Component as React.ComponentType<{\n data: unknown;\n params: Record<string, string>;\n state: unknown;\n setState: (s: unknown | ((prev: unknown) => unknown)) => Promise<void>;\n setStateSync: (s: unknown | ((prev: unknown) => unknown)) => void;\n resetState: () => void;\n info: unknown;\n }>;\n return (\n <ComponentWithData\n data={data}\n params={params}\n {...stateProps}\n info={info}\n />\n );\n }\n const ComponentWithoutData = Component as React.ComponentType<{\n params: Record<string, string>;\n state: unknown;\n setState: (s: unknown | ((prev: unknown) => unknown)) => Promise<void>;\n setStateSync: (s: unknown | ((prev: unknown) => unknown)) => void;\n resetState: () => void;\n info: unknown;\n }>;\n return <ComponentWithoutData params={params} {...stateProps} info={info} />;\n };\n\n return (\n <RouteContext.Provider value={routeContextValue}>\n {renderComponent()}\n </RouteContext.Provider>\n );\n}\n","import { type ReactNode, useContext } from \"react\";\nimport { RouteContext } from \"./context/RouteContext.js\";\n\n/**\n * Renders the matched child route.\n * Used in layout components to specify where child routes should render.\n */\nexport function Outlet(): ReactNode {\n const routeContext = useContext(RouteContext);\n\n if (!routeContext) {\n return null;\n }\n\n return routeContext.outlet;\n}\n","import { useContext } from \"react\";\nimport { RouterContext } from \"../context/RouterContext.js\";\nimport type { NavigateOptions } from \"../types.js\";\n\n/**\n * Returns a function for programmatic navigation.\n */\nexport function useNavigate(): (to: string, options?: NavigateOptions) => void {\n const context = useContext(RouterContext);\n\n if (!context) {\n throw new Error(\"useNavigate must be used within a Router\");\n }\n\n return context.navigate;\n}\n","import { useContext, useMemo } from \"react\";\nimport { RouterContext } from \"../context/RouterContext.js\";\nimport type { Location } from \"../types.js\";\n\n/**\n * Returns the current location object.\n */\nexport function useLocation(): Location {\n const context = useContext(RouterContext);\n\n if (!context) {\n throw new Error(\"useLocation must be used within a Router\");\n }\n\n const { url } = context;\n\n return useMemo(() => {\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n }, [url]);\n}\n","import { useCallback, useContext, useMemo } from \"react\";\nimport { RouterContext } from \"../context/RouterContext.js\";\n\ntype SetSearchParams = (\n params:\n | URLSearchParams\n | Record<string, string>\n | ((prev: URLSearchParams) => URLSearchParams | Record<string, string>),\n) => void;\n\n/**\n * Returns and allows manipulation of URL search parameters.\n */\nexport function useSearchParams(): [URLSearchParams, SetSearchParams] {\n const context = useContext(RouterContext);\n\n if (!context) {\n throw new Error(\"useSearchParams must be used within a Router\");\n }\n\n const searchParams = context.url.searchParams;\n\n const setSearchParams = useCallback<SetSearchParams>(\n (params) => {\n const url = new URL(context.url);\n\n let newParams: URLSearchParams;\n if (typeof params === \"function\") {\n const result = params(new URLSearchParams(url.search));\n newParams =\n result instanceof URLSearchParams\n ? result\n : new URLSearchParams(result);\n } else if (params instanceof URLSearchParams) {\n newParams = params;\n } else {\n newParams = new URLSearchParams(params);\n }\n\n url.search = newParams.toString();\n context.navigate(url.pathname + url.search + url.hash, { replace: true });\n },\n [context],\n );\n\n return [searchParams, setSearchParams];\n}\n","import { useContext, useEffect, useId } from \"react\";\nimport { BlockerContext } from \"../context/BlockerContext.js\";\n\nexport type UseBlockerOptions = {\n /**\n * Function that returns true if navigation should be blocked.\n * Can call `confirm()` inside to show a confirmation dialog.\n */\n shouldBlock: () => boolean;\n};\n\n/**\n * Hook to block navigation away from the current route.\n *\n * This is useful for scenarios like unsaved form data, ongoing file uploads,\n * or any state that would be lost on navigation.\n *\n * @example\n * ```tsx\n * function EditForm() {\n * const [isDirty, setIsDirty] = useState(false);\n *\n * useBlocker({\n * shouldBlock: () => {\n * if (isDirty) {\n * return !confirm(\"You have unsaved changes. Leave anyway?\");\n * }\n * return false;\n * },\n * });\n *\n * return <form>...</form>;\n * }\n * ```\n *\n * Note: This hook only handles SPA navigations (links, programmatic navigation).\n * For hard navigations (tab close, refresh), handle `beforeunload` separately.\n */\nexport function useBlocker(options: UseBlockerOptions): void {\n const context = useContext(BlockerContext);\n\n if (!context) {\n throw new Error(\"useBlocker must be used within a Router\");\n }\n\n const { shouldBlock } = options;\n const blockerId = useId();\n const { registry } = context;\n\n // Register blocker on mount, unregister on unmount\n // Re-registers when shouldBlock function changes\n useEffect(() => {\n return registry.register(blockerId, shouldBlock);\n }, [blockerId, shouldBlock, registry]);\n}\n","import type { ComponentType } from \"react\";\n\nconst routeDefinitionSymbol = Symbol();\n\n/**\n * Extracts parameter names from a path pattern.\n * E.g., \"/users/:id/posts/:postId\" -> \"id\" | \"postId\"\n */\ntype ExtractParams<T extends string> =\n T extends `${string}:${infer Param}/${infer Rest}`\n ? Param | ExtractParams<`/${Rest}`>\n : T extends `${string}:${infer Param}`\n ? Param\n : never;\n\n/**\n * Creates a params object type from a path pattern.\n * E.g., \"/users/:id\" -> { id: string }\n */\nexport type PathParams<T extends string> = [ExtractParams<T>] extends [never]\n ? Record<string, never>\n : { [K in ExtractParams<T>]: string };\n\n/**\n * Arguments passed to loader functions.\n */\nexport type LoaderArgs = {\n /** Extracted path parameters */\n params: Record<string, string>;\n /** Request object with URL and headers */\n request: Request;\n /** AbortSignal for cancellation on navigation */\n signal: AbortSignal;\n};\n\n/**\n * Props for route components without loader.\n * Includes navigation state management props.\n */\nexport type RouteComponentProps<\n TParams extends Record<string, string>,\n TState = undefined,\n> = {\n /** Extracted path parameters */\n params: TParams;\n /** Current navigation state for this route (undefined on first visit) */\n state: TState | undefined;\n /** Update navigation state for this route asynchronously via replace navigation */\n setState: (\n state: TState | ((prev: TState | undefined) => TState),\n ) => Promise<void>;\n /** Update navigation state for this route synchronously via updateCurrentEntry */\n setStateSync: (\n state: TState | ((prev: TState | undefined) => TState),\n ) => void;\n /** Reset navigation state to undefined */\n resetState: () => void;\n /** Ephemeral navigation info (only available during navigation, not persisted) */\n info: unknown;\n};\n\n/**\n * Props for route components with loader.\n * Includes data from loader and navigation state management props.\n */\nexport type RouteComponentPropsWithData<\n TParams extends Record<string, string>,\n TData,\n TState = undefined,\n> = RouteComponentProps<TParams, TState> & {\n /** Data returned from the loader */\n data: TData;\n};\n\n/**\n * Route definition created by the `route` helper function.\n */\nexport interface OpaqueRouteDefinition {\n [routeDefinitionSymbol]: never;\n path: string;\n children?: RouteDefinition[];\n}\n\n/**\n * Any route definition defined by user.\n */\nexport type RouteDefinition =\n | OpaqueRouteDefinition\n | {\n path: string;\n component?: ComponentType<object>;\n children?: RouteDefinition[];\n };\n\n/**\n * Route definition with loader - infers TData from loader return type.\n * TPath is used to infer params type from the path pattern.\n * TState is the type of navigation state for this route.\n */\ntype RouteWithLoader<TPath extends string, TData, TState> = {\n path: TPath;\n loader: (args: LoaderArgs) => TData;\n component: ComponentType<\n RouteComponentPropsWithData<PathParams<TPath>, TData, TState>\n >;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n children?: RouteDefinition[];\n};\n\n/**\n * Route definition without loader.\n * TPath is used to infer params type from the path pattern.\n * TState is the type of navigation state for this route.\n */\ntype RouteWithoutLoader<TPath extends string, TState> = {\n path: TPath;\n component?: ComponentType<RouteComponentProps<PathParams<TPath>, TState>>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n children?: RouteDefinition[];\n};\n\n/**\n * Helper function for creating type-safe route definitions.\n *\n * When a loader is provided, TypeScript infers the return type and ensures\n * the component accepts a `data` prop of that type. Components always receive\n * a `params` prop with types inferred from the path pattern.\n *\n * For routes with navigation state, use `routeState<TState>()({ ... })` instead.\n *\n * @example\n * ```typescript\n * // Route with async loader\n * route({\n * path: \"users/:userId\",\n * loader: async ({ params, signal }) => {\n * const res = await fetch(`/api/users/${params.userId}`, { signal });\n * return res.json() as Promise<User>;\n * },\n * component: UserDetail, // Must accept { data: Promise<User>, params: { userId: string }, state, setState, resetState }\n * });\n *\n * // Route without loader\n * route({\n * path: \"about\",\n * component: AboutPage, // Must accept { params: {}, state, setState, resetState }\n * });\n * ```\n */\n// Overload with loader\nexport function route<TPath extends string, TData>(\n definition: RouteWithLoader<TPath, TData, undefined>,\n): OpaqueRouteDefinition;\n// Overload without loader\nexport function route<TPath extends string>(\n definition: RouteWithoutLoader<TPath, undefined>,\n): OpaqueRouteDefinition;\n// Implementation\nexport function route<TPath extends string, TData>(\n definition:\n | RouteWithLoader<TPath, TData, undefined>\n | RouteWithoutLoader<TPath, undefined>,\n): OpaqueRouteDefinition {\n return definition as unknown as OpaqueRouteDefinition;\n}\n\n/**\n * Helper function for creating type-safe route definitions with navigation state.\n *\n * Use this curried function when your route component needs to manage navigation state.\n * The state is tied to the navigation history entry and persists across back/forward navigation.\n *\n * @example\n * ```typescript\n * // Route with navigation state\n * type MyState = { scrollPosition: number };\n * routeState<MyState>()({\n * path: \"users/:userId\",\n * component: UserPage, // Receives { params, state, setState, resetState }\n * });\n *\n * // Route with both loader and navigation state\n * type FilterState = { filter: string };\n * routeState<FilterState>()({\n * path: \"products\",\n * loader: async () => fetchProducts(),\n * component: ProductList, // Receives { data, params, state, setState, resetState }\n * });\n * ```\n */\nexport function routeState<TState>(): {\n <TPath extends string, TData>(\n definition: RouteWithLoader<TPath, TData, TState>,\n ): OpaqueRouteDefinition;\n <TPath extends string>(\n definition: RouteWithoutLoader<TPath, TState>,\n ): OpaqueRouteDefinition;\n} {\n return function <TPath extends string, TData>(\n definition:\n | RouteWithLoader<TPath, TData, TState>\n | RouteWithoutLoader<TPath, TState>,\n ): OpaqueRouteDefinition {\n return definition as unknown as OpaqueRouteDefinition;\n };\n}\n"],"mappings":";;;;;;AAiBA,MAAa,gBAAgB,cAAyC,KAAK;;;;ACN3E,MAAa,eAAe,cAAwC,KAAK;;;;;;;;ACQzE,SAAgB,wBAAyC;CACvD,MAAM,2BAAW,IAAI,KAA+B;AAEpD,QAAO;EACL,SAAS,IAAe,aAAwC;AAC9D,YAAS,IAAI,IAAI,YAAY;AAC7B,gBAAa;AACX,aAAS,OAAO,GAAG;;;EAIvB,WAAoB;AAClB,QAAK,MAAM,eAAe,SAAS,QAAQ,CACzC,KAAI,aAAa,CACf,QAAO;AAGX,UAAO;;EAEV;;AAGH,MAAa,iBAAiB,cAA0C,KAAK;;;;;;;;;;;ACO7E,SAAgB,eACd,QAC2B;AAC3B,QAAO;;;;;;;;;AC7CT,SAAgB,YACd,QACA,UACuB;AACvB,MAAK,MAAMA,WAAS,QAAQ;EAC1B,MAAM,UAAU,WAAWA,SAAO,SAAS;AAC3C,MAAI,QACF,QAAO;;AAGX,QAAO;;;;;AAMT,SAAS,WACP,SACA,UACuB;CACvB,MAAM,cAAc,QAAQA,QAAM,UAAU,OAAO;CAInD,MAAM,EAAE,SAAS,QAAQ,qBAAqB,UAC5CA,QAAM,MACN,UACA,CAAC,YACF;AAED,KAAI,CAAC,QACH,QAAO;CAGT,MAAMC,SAAuB;EAC3B;EACA;EACA,UAAU;EACX;AAGD,KAAI,aAAa;EAEf,IAAI,oBAAoB,SAAS,MAAM,iBAAiB,OAAO;AAC/D,MAAI,CAAC,kBAAkB,WAAW,IAAI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O;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BT,SAAgB,aAOd;AACA,QAAO,SACL,YAGuB;AACvB,SAAO"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@funstack/router",
3
- "version": "0.0.1-alpha.2",
3
+ "version": "0.0.2-alpha.0",
4
4
  "description": "A modern React router based on the Navigation API",
5
5
  "repository": {
6
6
  "type": "git",
@@ -29,14 +29,14 @@
29
29
  },
30
30
  "devDependencies": {
31
31
  "@testing-library/jest-dom": "^6.9.1",
32
- "@testing-library/react": "^16.3.0",
32
+ "@testing-library/react": "^16.3.1",
33
33
  "@types/react": "^19.0.0",
34
- "jsdom": "^27.3.0",
34
+ "jsdom": "^27.4.0",
35
35
  "react": "^19.0.0",
36
- "tsdown": "^0.17.2",
36
+ "tsdown": "^0.18.2",
37
37
  "typescript": "^5.7.0",
38
38
  "urlpattern-polyfill": "^10.1.0",
39
- "vitest": "^4.0.15"
39
+ "vitest": "^4.0.16"
40
40
  },
41
41
  "scripts": {
42
42
  "build": "tsdown",