INDIE UNPKG

23.7 kBTypeScriptView Raw
1import { e as RouteObject, f as History, g as MaybePromise, c as RouterContextProvider, h as MapRoutePropertiesFunction, i as Action, L as Location, D as DataRouteMatch, j as Submission, k as RouteData, l as DataStrategyFunction, m as PatchRoutesOnNavigationFunction, n as DataRouteObject, o as RouteBranch, p as RouteManifest, U as UIMatch, T as To, q as HTMLFormMethod, F as FormEncType, r as Path, s as LoaderFunctionArgs, t as MiddlewareEnabled, u as AppLoadContext } from './data-BqZ2x964.js';
2
3/**
4 * A Router instance manages all navigation and data loading/mutations
5 */
6interface Router {
7 /**
8 * @private
9 * PRIVATE - DO NOT USE
10 *
11 * Return the basename for the router
12 */
13 get basename(): RouterInit["basename"];
14 /**
15 * @private
16 * PRIVATE - DO NOT USE
17 *
18 * Return the future config for the router
19 */
20 get future(): FutureConfig;
21 /**
22 * @private
23 * PRIVATE - DO NOT USE
24 *
25 * Return the current state of the router
26 */
27 get state(): RouterState;
28 /**
29 * @private
30 * PRIVATE - DO NOT USE
31 *
32 * Return the routes for this router instance
33 */
34 get routes(): DataRouteObject[];
35 /**
36 * @private
37 * PRIVATE - DO NOT USE
38 *
39 * Return the route branches for this router instance
40 */
41 get branches(): RouteBranch<DataRouteObject>[] | undefined;
42 /**
43 * @private
44 * PRIVATE - DO NOT USE
45 *
46 * Return the manifest for this router instance
47 */
48 get manifest(): RouteManifest;
49 /**
50 * @private
51 * PRIVATE - DO NOT USE
52 *
53 * Return the window associated with the router
54 */
55 get window(): RouterInit["window"];
56 /**
57 * @private
58 * PRIVATE - DO NOT USE
59 *
60 * Initialize the router, including adding history listeners and kicking off
61 * initial data fetches. Returns a function to cleanup listeners and abort
62 * any in-progress loads
63 */
64 initialize(): Router;
65 /**
66 * @private
67 * PRIVATE - DO NOT USE
68 *
69 * Subscribe to router.state updates
70 *
71 * @param fn function to call with the new state
72 */
73 subscribe(fn: RouterSubscriber): () => void;
74 /**
75 * @private
76 * PRIVATE - DO NOT USE
77 *
78 * Enable scroll restoration behavior in the router
79 *
80 * @param savedScrollPositions Object that will manage positions, in case
81 * it's being restored from sessionStorage
82 * @param getScrollPosition Function to get the active Y scroll position
83 * @param getKey Function to get the key to use for restoration
84 */
85 enableScrollRestoration(savedScrollPositions: Record<string, number>, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction): () => void;
86 /**
87 * @private
88 * PRIVATE - DO NOT USE
89 *
90 * Navigate forward/backward in the history stack
91 * @param to Delta to move in the history stack
92 */
93 navigate(to: number): Promise<void>;
94 /**
95 * Navigate to the given path
96 * @param to Path to navigate to
97 * @param opts Navigation options (method, submission, etc.)
98 */
99 navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;
100 /**
101 * @private
102 * PRIVATE - DO NOT USE
103 *
104 * Trigger a fetcher load/submission
105 *
106 * @param key Fetcher key
107 * @param routeId Route that owns the fetcher
108 * @param href href to fetch
109 * @param opts Fetcher options, (method, submission, etc.)
110 */
111 fetch(key: string, routeId: string, href: string | null, opts?: RouterFetchOptions): Promise<void>;
112 /**
113 * @private
114 * PRIVATE - DO NOT USE
115 *
116 * Trigger a revalidation of all current route loaders and fetcher loads
117 */
118 revalidate(): Promise<void>;
119 /**
120 * @private
121 * PRIVATE - DO NOT USE
122 *
123 * Utility function to create an href for the given location
124 * @param location
125 */
126 createHref(location: Location | URL): string;
127 /**
128 * @private
129 * PRIVATE - DO NOT USE
130 *
131 * Utility function to URL encode a destination path according to the internal
132 * history implementation
133 * @param to
134 */
135 encodeLocation(to: To): Path;
136 /**
137 * @private
138 * PRIVATE - DO NOT USE
139 *
140 * Get/create a fetcher for the given key
141 * @param key
142 */
143 getFetcher<TData = any>(key: string): Fetcher<TData>;
144 /**
145 * @internal
146 * PRIVATE - DO NOT USE
147 *
148 * Reset the fetcher for a given key
149 * @param key
150 */
151 resetFetcher(key: string, opts?: {
152 reason?: unknown;
153 }): void;
154 /**
155 * @private
156 * PRIVATE - DO NOT USE
157 *
158 * Delete the fetcher for a given key
159 * @param key
160 */
161 deleteFetcher(key: string): void;
162 /**
163 * @private
164 * PRIVATE - DO NOT USE
165 *
166 * Cleanup listeners and abort any in-progress loads
167 */
168 dispose(): void;
169 /**
170 * @private
171 * PRIVATE - DO NOT USE
172 *
173 * Get a navigation blocker
174 * @param key The identifier for the blocker
175 * @param fn The blocker function implementation
176 */
177 getBlocker(key: string, fn: BlockerFunction): Blocker;
178 /**
179 * @private
180 * PRIVATE - DO NOT USE
181 *
182 * Delete a navigation blocker
183 * @param key The identifier for the blocker
184 */
185 deleteBlocker(key: string): void;
186 /**
187 * @private
188 * PRIVATE DO NOT USE
189 *
190 * Patch additional children routes into an existing parent route
191 * @param routeId The parent route id or a callback function accepting `patch`
192 * to perform batch patching
193 * @param children The additional children routes
194 * @param unstable_allowElementMutations Allow mutation or route elements on
195 * existing routes. Intended for RSC-usage
196 * only.
197 */
198 patchRoutes(routeId: string | null, children: RouteObject[], unstable_allowElementMutations?: boolean): void;
199 /**
200 * @private
201 * PRIVATE - DO NOT USE
202 *
203 * HMR needs to pass in-flight route updates to React Router
204 * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)
205 */
206 _internalSetRoutes(routes: RouteObject[]): void;
207 /**
208 * @private
209 * PRIVATE - DO NOT USE
210 *
211 * Cause subscribers to re-render. This is used to force a re-render.
212 */
213 _internalSetStateDoNotUseOrYouWillBreakYourApp(state: Partial<RouterState>): void;
214 /**
215 * @private
216 * PRIVATE - DO NOT USE
217 *
218 * Internal fetch AbortControllers accessed by unit tests
219 */
220 _internalFetchControllers: Map<string, AbortController>;
221}
222/**
223 * State maintained internally by the router. During a navigation, all states
224 * reflect the "old" location unless otherwise noted.
225 */
226interface RouterState {
227 /**
228 * The action of the most recent navigation
229 */
230 historyAction: Action;
231 /**
232 * The current location reflected by the router
233 */
234 location: Location;
235 /**
236 * The current set of route matches
237 */
238 matches: DataRouteMatch[];
239 /**
240 * Tracks whether we've completed our initial data load
241 */
242 initialized: boolean;
243 /**
244 * Tracks whether we should be rendering a HydrateFallback during hydration
245 */
246 renderFallback: boolean;
247 /**
248 * Current scroll position we should start at for a new view
249 * - number -> scroll position to restore to
250 * - false -> do not restore scroll at all (used during submissions/revalidations)
251 * - null -> don't have a saved position, scroll to hash or top of page
252 */
253 restoreScrollPosition: number | false | null;
254 /**
255 * Indicate whether this navigation should skip resetting the scroll position
256 * if we are unable to restore the scroll position
257 */
258 preventScrollReset: boolean;
259 /**
260 * Tracks the state of the current navigation
261 */
262 navigation: Navigation;
263 /**
264 * Tracks any in-progress revalidations
265 */
266 revalidation: RevalidationState;
267 /**
268 * Data from the loaders for the current matches
269 */
270 loaderData: RouteData;
271 /**
272 * Data from the action for the current matches
273 */
274 actionData: RouteData | null;
275 /**
276 * Errors caught from loaders for the current matches
277 */
278 errors: RouteData | null;
279 /**
280 * Map of current fetchers
281 */
282 fetchers: Map<string, Fetcher>;
283 /**
284 * Map of current blockers
285 */
286 blockers: Map<string, Blocker>;
287}
288/**
289 * Data that can be passed into hydrate a Router from SSR
290 */
291type HydrationState = Partial<Pick<RouterState, "loaderData" | "actionData" | "errors">>;
292/**
293 * Future flags to toggle new feature behavior
294 */
295interface FutureConfig {
296}
297/**
298 * Initialization options for createRouter
299 */
300interface RouterInit {
301 routes: RouteObject[];
302 history: History;
303 basename?: string;
304 getContext?: () => MaybePromise<RouterContextProvider>;
305 instrumentations?: ClientInstrumentation[];
306 mapRouteProperties?: MapRoutePropertiesFunction;
307 future?: Partial<FutureConfig>;
308 hydrationRouteProperties?: string[];
309 hydrationData?: HydrationState;
310 window?: Window;
311 dataStrategy?: DataStrategyFunction;
312 patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;
313}
314/**
315 * State returned from a server-side query() call
316 */
317interface StaticHandlerContext {
318 basename: Router["basename"];
319 location: RouterState["location"];
320 matches: RouterState["matches"];
321 loaderData: RouterState["loaderData"];
322 actionData: RouterState["actionData"];
323 errors: RouterState["errors"];
324 statusCode: number;
325 loaderHeaders: Record<string, Headers>;
326 actionHeaders: Record<string, Headers>;
327 _deepestRenderedBoundaryId?: string | null;
328}
329/**
330 * A StaticHandler instance manages a singular SSR navigation/fetch event
331 */
332interface StaticHandler {
333 /**
334 * The set of data routes managed by this handler
335 */
336 dataRoutes: DataRouteObject[];
337 /**
338 * @private
339 * PRIVATE - DO NOT USE
340 *
341 * The route branches derived from the data routes, used for internal route
342 * matching in Framework Mode
343 */
344 _internalRouteBranches: RouteBranch<DataRouteObject>[];
345 /**
346 * Perform a query for a given request - executing all matched route
347 * loaders/actions. Used for document requests.
348 *
349 * @param request The request to query
350 * @param opts Optional query options
351 * @param opts.dataStrategy Alternate dataStrategy implementation
352 * @param opts.filterMatchesToLoad Predicate function to filter which matches should be loaded
353 * @param opts.generateMiddlewareResponse To enable middleware, provide a function
354 * to generate a response to bubble back up the middleware chain
355 * @param opts.requestContext Context object to pass to loaders/actions
356 * @param opts.skipLoaderErrorBubbling Skip loader error bubbling
357 * @param opts.skipRevalidation Skip revalidation after action submission
358 * @param opts.normalizePath Normalize the request path
359 */
360 query(request: Request, opts?: {
361 requestContext?: unknown;
362 filterMatchesToLoad?: (match: DataRouteMatch) => boolean;
363 skipLoaderErrorBubbling?: boolean;
364 skipRevalidation?: boolean;
365 dataStrategy?: DataStrategyFunction<unknown>;
366 generateMiddlewareResponse?: (query: (r: Request, args?: {
367 filterMatchesToLoad?: (match: DataRouteMatch) => boolean;
368 }) => Promise<StaticHandlerContext | Response>) => MaybePromise<Response>;
369 normalizePath?: (request: Request) => Path;
370 }): Promise<StaticHandlerContext | Response>;
371 /**
372 * Perform a query for a specific route. Used for resource requests.
373 *
374 * @param request The request to query
375 * @param opts Optional queryRoute options
376 * @param opts.dataStrategy Alternate dataStrategy implementation
377 * @param opts.generateMiddlewareResponse To enable middleware, provide a function
378 * to generate a response to bubble back up the middleware chain
379 * @param opts.requestContext Context object to pass to loaders/actions
380 * @param opts.routeId The ID of the route to query
381 * @param opts.normalizePath Normalize the request path
382
383 */
384 queryRoute(request: Request, opts?: {
385 routeId?: string;
386 requestContext?: unknown;
387 dataStrategy?: DataStrategyFunction<unknown>;
388 generateMiddlewareResponse?: (queryRoute: (r: Request) => Promise<Response>) => MaybePromise<Response>;
389 normalizePath?: (request: Request) => Path;
390 }): Promise<any>;
391}
392type ViewTransitionOpts = {
393 currentLocation: Location;
394 nextLocation: Location;
395};
396/**
397 * Subscriber function signature for changes to router state
398 */
399interface RouterSubscriber {
400 (state: RouterState, opts: {
401 deletedFetchers: string[];
402 newErrors: RouteData | null;
403 viewTransitionOpts?: ViewTransitionOpts;
404 flushSync: boolean;
405 }): void;
406}
407/**
408 * Function signature for determining the key to be used in scroll restoration
409 * for a given location
410 */
411interface GetScrollRestorationKeyFunction {
412 (location: Location, matches: UIMatch[]): string | null;
413}
414/**
415 * Function signature for determining the current scroll position
416 */
417interface GetScrollPositionFunction {
418 (): number;
419}
420/**
421 * - "route": relative to the route hierarchy so `..` means remove all segments
422 * of the current route even if it has many. For example, a `route("posts/:id")`
423 * would have both `:id` and `posts` removed from the url.
424 * - "path": relative to the pathname so `..` means remove one segment of the
425 * pathname. For example, a `route("posts/:id")` would have only `:id` removed
426 * from the url.
427 */
428type RelativeRoutingType = "route" | "path";
429type BaseNavigateOrFetchOptions = {
430 preventScrollReset?: boolean;
431 relative?: RelativeRoutingType;
432 flushSync?: boolean;
433 defaultShouldRevalidate?: boolean;
434};
435type BaseNavigateOptions = BaseNavigateOrFetchOptions & {
436 replace?: boolean;
437 state?: any;
438 fromRouteId?: string;
439 viewTransition?: boolean;
440 mask?: To;
441};
442type BaseSubmissionOptions = {
443 formMethod?: HTMLFormMethod;
444 formEncType?: FormEncType;
445} & ({
446 formData: FormData;
447 body?: undefined;
448} | {
449 formData?: undefined;
450 body: any;
451});
452/**
453 * Options for a navigate() call for a normal (non-submission) navigation
454 */
455type LinkNavigateOptions = BaseNavigateOptions;
456/**
457 * Options for a navigate() call for a submission navigation
458 */
459type SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;
460/**
461 * Options to pass to navigate() for a navigation
462 */
463type RouterNavigateOptions = LinkNavigateOptions | SubmissionNavigateOptions;
464/**
465 * Options for a fetch() load
466 */
467type LoadFetchOptions = BaseNavigateOrFetchOptions;
468/**
469 * Options for a fetch() submission
470 */
471type SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;
472/**
473 * Options to pass to fetch()
474 */
475type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;
476/**
477 * Potential states for state.navigation
478 */
479type NavigationStates = {
480 Idle: {
481 state: "idle";
482 location: undefined;
483 matches: undefined;
484 historyAction: undefined;
485 formMethod: undefined;
486 formAction: undefined;
487 formEncType: undefined;
488 formData: undefined;
489 json: undefined;
490 text: undefined;
491 };
492 Loading: {
493 state: "loading";
494 location: Location;
495 matches: DataRouteMatch[];
496 historyAction: Action;
497 formMethod: Submission["formMethod"] | undefined;
498 formAction: Submission["formAction"] | undefined;
499 formEncType: Submission["formEncType"] | undefined;
500 formData: Submission["formData"] | undefined;
501 json: Submission["json"] | undefined;
502 text: Submission["text"] | undefined;
503 };
504 Submitting: {
505 state: "submitting";
506 location: Location;
507 matches: DataRouteMatch[];
508 historyAction: Action;
509 formMethod: Submission["formMethod"];
510 formAction: Submission["formAction"];
511 formEncType: Submission["formEncType"];
512 formData: Submission["formData"];
513 json: Submission["json"];
514 text: Submission["text"];
515 };
516};
517type Navigation = NavigationStates[keyof NavigationStates];
518type RevalidationState = "idle" | "loading";
519/**
520 * Potential states for fetchers
521 */
522type FetcherStates<TData = any> = {
523 /**
524 * The fetcher is not calling a loader or action
525 *
526 * ```tsx
527 * fetcher.state === "idle"
528 * ```
529 */
530 Idle: {
531 state: "idle";
532 formMethod: undefined;
533 formAction: undefined;
534 formEncType: undefined;
535 text: undefined;
536 formData: undefined;
537 json: undefined;
538 /**
539 * If the fetcher has never been called, this will be undefined.
540 */
541 data: TData | undefined;
542 };
543 /**
544 * The fetcher is loading data from a {@link LoaderFunction | loader} from a
545 * call to {@link FetcherWithComponents.load | `fetcher.load`}.
546 *
547 * ```tsx
548 * // somewhere
549 * <button onClick={() => fetcher.load("/some/route") }>Load</button>
550 *
551 * // the state will update
552 * fetcher.state === "loading"
553 * ```
554 */
555 Loading: {
556 state: "loading";
557 formMethod: Submission["formMethod"] | undefined;
558 formAction: Submission["formAction"] | undefined;
559 formEncType: Submission["formEncType"] | undefined;
560 text: Submission["text"] | undefined;
561 formData: Submission["formData"] | undefined;
562 json: Submission["json"] | undefined;
563 data: TData | undefined;
564 };
565 /**
566 The fetcher is submitting to a {@link LoaderFunction} (GET) or {@link ActionFunction} (POST) from a {@link FetcherWithComponents.Form | `fetcher.Form`} or {@link FetcherWithComponents.submit | `fetcher.submit`}.
567
568 ```tsx
569 // somewhere
570 <input
571 onChange={e => {
572 fetcher.submit(event.currentTarget.form, { method: "post" });
573 }}
574 />
575
576 // the state will update
577 fetcher.state === "submitting"
578
579 // and formData will be available
580 fetcher.formData
581 ```
582 */
583 Submitting: {
584 state: "submitting";
585 formMethod: Submission["formMethod"];
586 formAction: Submission["formAction"];
587 formEncType: Submission["formEncType"];
588 text: Submission["text"];
589 formData: Submission["formData"];
590 json: Submission["json"];
591 data: TData | undefined;
592 };
593};
594type Fetcher<TData = any> = FetcherStates<TData>[keyof FetcherStates<TData>];
595interface BlockerBlocked {
596 state: "blocked";
597 reset: () => void;
598 proceed: () => void;
599 location: Location;
600}
601interface BlockerUnblocked {
602 state: "unblocked";
603 reset: undefined;
604 proceed: undefined;
605 location: undefined;
606}
607interface BlockerProceeding {
608 state: "proceeding";
609 reset: undefined;
610 proceed: undefined;
611 location: Location;
612}
613type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;
614type BlockerFunction = (args: {
615 currentLocation: Location;
616 nextLocation: Location;
617 historyAction: Action;
618}) => boolean;
619declare const IDLE_NAVIGATION: NavigationStates["Idle"];
620declare const IDLE_FETCHER: FetcherStates["Idle"];
621declare const IDLE_BLOCKER: BlockerUnblocked;
622/**
623 * Create a router and listen to history POP navigations
624 */
625declare function createRouter(init: RouterInit): Router;
626interface CreateStaticHandlerOptions {
627 basename?: string;
628 mapRouteProperties?: MapRoutePropertiesFunction;
629 instrumentations?: Pick<ServerInstrumentation, "route">[];
630 future?: Partial<FutureConfig>;
631}
632
633type ServerInstrumentation = {
634 handler?: InstrumentRequestHandlerFunction;
635 route?: InstrumentRouteFunction;
636};
637type ClientInstrumentation = {
638 router?: InstrumentRouterFunction;
639 route?: InstrumentRouteFunction;
640};
641type InstrumentRequestHandlerFunction = (handler: InstrumentableRequestHandler) => void;
642type InstrumentRouterFunction = (router: InstrumentableRouter) => void;
643type InstrumentRouteFunction = (route: InstrumentableRoute) => void;
644type InstrumentationHandlerResult = {
645 status: "success";
646 error: undefined;
647} | {
648 status: "error";
649 error: Error;
650};
651type InstrumentFunction<T> = (handler: () => Promise<InstrumentationHandlerResult>, info: T) => Promise<void>;
652type ReadonlyRequest = {
653 method: string;
654 url: string;
655 headers: Pick<Headers, "get">;
656};
657type ReadonlyContext = MiddlewareEnabled extends true ? Pick<RouterContextProvider, "get"> : Readonly<AppLoadContext>;
658type InstrumentableRoute = {
659 id: string;
660 index: boolean | undefined;
661 path: string | undefined;
662 instrument(instrumentations: RouteInstrumentations): void;
663};
664type RouteInstrumentations = {
665 lazy?: InstrumentFunction<RouteLazyInstrumentationInfo>;
666 "lazy.loader"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
667 "lazy.action"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
668 "lazy.middleware"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
669 middleware?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
670 loader?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
671 action?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
672};
673type RouteLazyInstrumentationInfo = undefined;
674type RouteHandlerInstrumentationInfo = Readonly<{
675 request: ReadonlyRequest;
676 params: LoaderFunctionArgs["params"];
677 pattern: string;
678 context: ReadonlyContext;
679}>;
680type InstrumentableRouter = {
681 instrument(instrumentations: RouterInstrumentations): void;
682};
683type RouterInstrumentations = {
684 navigate?: InstrumentFunction<RouterNavigationInstrumentationInfo>;
685 fetch?: InstrumentFunction<RouterFetchInstrumentationInfo>;
686};
687type RouterNavigationInstrumentationInfo = Readonly<{
688 to: string | number;
689 currentUrl: string;
690 formMethod?: HTMLFormMethod;
691 formEncType?: FormEncType;
692 formData?: FormData;
693 body?: any;
694}>;
695type RouterFetchInstrumentationInfo = Readonly<{
696 href: string;
697 currentUrl: string;
698 fetcherKey: string;
699 formMethod?: HTMLFormMethod;
700 formEncType?: FormEncType;
701 formData?: FormData;
702 body?: any;
703}>;
704type InstrumentableRequestHandler = {
705 instrument(instrumentations: RequestHandlerInstrumentations): void;
706};
707type RequestHandlerInstrumentations = {
708 request?: InstrumentFunction<RequestHandlerInstrumentationInfo>;
709};
710type RequestHandlerInstrumentationInfo = Readonly<{
711 request: ReadonlyRequest;
712 context: ReadonlyContext | undefined;
713}>;
714
715export { type BlockerFunction as B, type ClientInstrumentation as C, type Fetcher as F, type GetScrollPositionFunction as G, type HydrationState as H, type InstrumentRequestHandlerFunction as I, type NavigationStates as N, type RouterInit as R, type StaticHandler as S, type Router as a, type Blocker as b, type RelativeRoutingType as c, type Navigation as d, type RouterState as e, type GetScrollRestorationKeyFunction as f, type StaticHandlerContext as g, type RouterSubscriber as h, type RouterNavigateOptions as i, type RouterFetchOptions as j, type RevalidationState as k, type ServerInstrumentation as l, type InstrumentRouterFunction as m, type InstrumentRouteFunction as n, type InstrumentationHandlerResult as o, IDLE_NAVIGATION as p, IDLE_FETCHER as q, IDLE_BLOCKER as r, createRouter as s, type FutureConfig as t, type CreateStaticHandlerOptions as u };