index-react-server.d.ts 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549
  1. import * as React from 'react';
  2. export { BrowserRouter, Form, HashRouter, Link, Links, MemoryRouter, Meta, NavLink, Navigate, Outlet, Route, Router, RouterProvider, Routes, ScrollRestoration, StaticRouter, StaticRouterProvider, unstable_HistoryRouter } from 'react-router/internal/react-server-client';
  3. import { ParseOptions, SerializeOptions } from 'cookie';
  4. export { ParseOptions as CookieParseOptions, SerializeOptions as CookieSerializeOptions } from 'cookie';
  5. /**
  6. * Actions represent the type of change to a location value.
  7. */
  8. declare enum Action {
  9. /**
  10. * A POP indicates a change to an arbitrary index in the history stack, such
  11. * as a back or forward navigation. It does not describe the direction of the
  12. * navigation, only that the current index changed.
  13. *
  14. * Note: This is the default action for newly created history objects.
  15. */
  16. Pop = "POP",
  17. /**
  18. * A PUSH indicates a new entry being added to the history stack, such as when
  19. * a link is clicked and a new page loads. When this happens, all subsequent
  20. * entries in the stack are lost.
  21. */
  22. Push = "PUSH",
  23. /**
  24. * A REPLACE indicates the entry at the current index in the history stack
  25. * being replaced by a new one.
  26. */
  27. Replace = "REPLACE"
  28. }
  29. /**
  30. * The pathname, search, and hash values of a URL.
  31. */
  32. interface Path {
  33. /**
  34. * A URL pathname, beginning with a /.
  35. */
  36. pathname: string;
  37. /**
  38. * A URL search string, beginning with a ?.
  39. */
  40. search: string;
  41. /**
  42. * A URL fragment identifier, beginning with a #.
  43. */
  44. hash: string;
  45. }
  46. /**
  47. * An entry in a history stack. A location contains information about the
  48. * URL path, as well as possibly some arbitrary state and a key.
  49. */
  50. interface Location<State = any> extends Path {
  51. /**
  52. * A value of arbitrary data associated with this location.
  53. */
  54. state: State;
  55. /**
  56. * A unique string associated with this location. May be used to safely store
  57. * and retrieve data in some other storage API, like `localStorage`.
  58. *
  59. * Note: This value is always "default" on the initial location.
  60. */
  61. key: string;
  62. }
  63. /**
  64. * A change to the current location.
  65. */
  66. interface Update {
  67. /**
  68. * The action that triggered the change.
  69. */
  70. action: Action;
  71. /**
  72. * The new location.
  73. */
  74. location: Location;
  75. /**
  76. * The delta between this location and the former location in the history stack
  77. */
  78. delta: number | null;
  79. }
  80. /**
  81. * A function that receives notifications about location changes.
  82. */
  83. interface Listener {
  84. (update: Update): void;
  85. }
  86. /**
  87. * Describes a location that is the destination of some navigation used in
  88. * {@link Link}, {@link useNavigate}, etc.
  89. */
  90. type To = string | Partial<Path>;
  91. /**
  92. * A history is an interface to the navigation stack. The history serves as the
  93. * source of truth for the current location, as well as provides a set of
  94. * methods that may be used to change it.
  95. *
  96. * It is similar to the DOM's `window.history` object, but with a smaller, more
  97. * focused API.
  98. */
  99. interface History {
  100. /**
  101. * The last action that modified the current location. This will always be
  102. * Action.Pop when a history instance is first created. This value is mutable.
  103. */
  104. readonly action: Action;
  105. /**
  106. * The current location. This value is mutable.
  107. */
  108. readonly location: Location;
  109. /**
  110. * Returns a valid href for the given `to` value that may be used as
  111. * the value of an <a href> attribute.
  112. *
  113. * @param to - The destination URL
  114. */
  115. createHref(to: To): string;
  116. /**
  117. * Returns a URL for the given `to` value
  118. *
  119. * @param to - The destination URL
  120. */
  121. createURL(to: To): URL;
  122. /**
  123. * Encode a location the same way window.history would do (no-op for memory
  124. * history) so we ensure our PUSH/REPLACE navigations for data routers
  125. * behave the same as POP
  126. *
  127. * @param to Unencoded path
  128. */
  129. encodeLocation(to: To): Path;
  130. /**
  131. * Pushes a new location onto the history stack, increasing its length by one.
  132. * If there were any entries in the stack after the current one, they are
  133. * lost.
  134. *
  135. * @param to - The new URL
  136. * @param state - Data to associate with the new location
  137. */
  138. push(to: To, state?: any): void;
  139. /**
  140. * Replaces the current location in the history stack with a new one. The
  141. * location that was replaced will no longer be available.
  142. *
  143. * @param to - The new URL
  144. * @param state - Data to associate with the new location
  145. */
  146. replace(to: To, state?: any): void;
  147. /**
  148. * Navigates `n` entries backward/forward in the history stack relative to the
  149. * current index. For example, a "back" navigation would use go(-1).
  150. *
  151. * @param delta - The delta in the stack index
  152. */
  153. go(delta: number): void;
  154. /**
  155. * Sets up a listener that will be called whenever the current location
  156. * changes.
  157. *
  158. * @param listener - A function that will be called when the location changes
  159. * @returns unlisten - A function that may be used to stop listening
  160. */
  161. listen(listener: Listener): () => void;
  162. }
  163. /**
  164. * An augmentable interface users can modify in their app-code to opt into
  165. * future-flag-specific types
  166. */
  167. interface Future {
  168. }
  169. type MiddlewareEnabled = Future extends {
  170. v8_middleware: infer T extends boolean;
  171. } ? T : false;
  172. type MaybePromise<T> = T | Promise<T>;
  173. /**
  174. * Map of routeId -> data returned from a loader/action/error
  175. */
  176. interface RouteData {
  177. [routeId: string]: any;
  178. }
  179. type LowerCaseFormMethod = "get" | "post" | "put" | "patch" | "delete";
  180. type UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;
  181. /**
  182. * Users can specify either lowercase or uppercase form methods on `<Form>`,
  183. * useSubmit(), `<fetcher.Form>`, etc.
  184. */
  185. type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;
  186. /**
  187. * Active navigation/fetcher form methods are exposed in uppercase on the
  188. * RouterState. This is to align with the normalization done via fetch().
  189. */
  190. type FormMethod = UpperCaseFormMethod;
  191. type FormEncType = "application/x-www-form-urlencoded" | "multipart/form-data" | "application/json" | "text/plain";
  192. type JsonObject = {
  193. [Key in string]: JsonValue;
  194. } & {
  195. [Key in string]?: JsonValue | undefined;
  196. };
  197. type JsonArray = JsonValue[] | readonly JsonValue[];
  198. type JsonPrimitive = string | number | boolean | null;
  199. type JsonValue = JsonPrimitive | JsonObject | JsonArray;
  200. /**
  201. * @private
  202. * Internal interface to pass around for action submissions, not intended for
  203. * external consumption
  204. */
  205. type Submission = {
  206. formMethod: FormMethod;
  207. formAction: string;
  208. formEncType: FormEncType;
  209. formData: FormData;
  210. json: undefined;
  211. text: undefined;
  212. } | {
  213. formMethod: FormMethod;
  214. formAction: string;
  215. formEncType: FormEncType;
  216. formData: undefined;
  217. json: JsonValue;
  218. text: undefined;
  219. } | {
  220. formMethod: FormMethod;
  221. formAction: string;
  222. formEncType: FormEncType;
  223. formData: undefined;
  224. json: undefined;
  225. text: string;
  226. };
  227. /**
  228. * A context instance used as the key for the `get`/`set` methods of a
  229. * {@link RouterContextProvider}. Accepts an optional default
  230. * value to be returned if no value has been set.
  231. */
  232. interface RouterContext<T = unknown> {
  233. defaultValue?: T;
  234. }
  235. /**
  236. * Creates a type-safe {@link RouterContext} object that can be used to
  237. * store and retrieve arbitrary values in [`action`](../../start/framework/route-module#action)s,
  238. * [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
  239. * Similar to React's [`createContext`](https://react.dev/reference/react/createContext),
  240. * but specifically designed for React Router's request/response lifecycle.
  241. *
  242. * If a `defaultValue` is provided, it will be returned from `context.get()`
  243. * when no value has been set for the context. Otherwise, reading this context
  244. * when no value has been set will throw an error.
  245. *
  246. * ```tsx filename=app/context.ts
  247. * import { createContext } from "react-router";
  248. *
  249. * // Create a context for user data
  250. * export const userContext =
  251. * createContext<User | null>(null);
  252. * ```
  253. *
  254. * ```tsx filename=app/middleware/auth.ts
  255. * import { getUserFromSession } from "~/auth.server";
  256. * import { userContext } from "~/context";
  257. *
  258. * export const authMiddleware = async ({
  259. * context,
  260. * request,
  261. * }) => {
  262. * const user = await getUserFromSession(request);
  263. * context.set(userContext, user);
  264. * };
  265. * ```
  266. *
  267. * ```tsx filename=app/routes/profile.tsx
  268. * import { userContext } from "~/context";
  269. *
  270. * export async function loader({
  271. * context,
  272. * }: Route.LoaderArgs) {
  273. * const user = context.get(userContext);
  274. *
  275. * if (!user) {
  276. * throw new Response("Unauthorized", { status: 401 });
  277. * }
  278. *
  279. * return { user };
  280. * }
  281. * ```
  282. *
  283. * @public
  284. * @category Utils
  285. * @mode framework
  286. * @mode data
  287. * @param defaultValue An optional default value for the context. This value
  288. * will be returned if no value has been set for this context.
  289. * @returns A {@link RouterContext} object that can be used with
  290. * `context.get()` and `context.set()` in [`action`](../../start/framework/route-module#action)s,
  291. * [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
  292. */
  293. declare function createContext<T>(defaultValue?: T): RouterContext<T>;
  294. /**
  295. * Provides methods for writing/reading values in application context in a
  296. * type-safe way. Primarily for usage with [middleware](../../how-to/middleware).
  297. *
  298. * @example
  299. * import {
  300. * createContext,
  301. * RouterContextProvider
  302. * } from "react-router";
  303. *
  304. * const userContext = createContext<User | null>(null);
  305. * const contextProvider = new RouterContextProvider();
  306. * contextProvider.set(userContext, getUser());
  307. * // ^ Type-safe
  308. * const user = contextProvider.get(userContext);
  309. * // ^ User
  310. *
  311. * @public
  312. * @category Utils
  313. * @mode framework
  314. * @mode data
  315. */
  316. declare class RouterContextProvider {
  317. #private;
  318. /**
  319. * Create a new `RouterContextProvider` instance
  320. * @param init An optional initial context map to populate the provider with
  321. */
  322. constructor(init?: Map<RouterContext, unknown>);
  323. /**
  324. * Access a value from the context. If no value has been set for the context,
  325. * it will return the context's `defaultValue` if provided, or throw an error
  326. * if no `defaultValue` was set.
  327. * @param context The context to get the value for
  328. * @returns The value for the context, or the context's `defaultValue` if no
  329. * value was set
  330. */
  331. get<T>(context: RouterContext<T>): T;
  332. /**
  333. * Set a value for the context. If the context already has a value set, this
  334. * will overwrite it.
  335. *
  336. * @param context The context to set the value for
  337. * @param value The value to set for the context
  338. * @returns {void}
  339. */
  340. set<C extends RouterContext>(context: C, value: C extends RouterContext<infer T> ? T : never): void;
  341. }
  342. type DefaultContext = MiddlewareEnabled extends true ? Readonly<RouterContextProvider> : any;
  343. /**
  344. * @private
  345. * Arguments passed to route loader/action functions. Same for now but we keep
  346. * this as a private implementation detail in case they diverge in the future.
  347. */
  348. interface DataFunctionArgs<Context> {
  349. /** A {@link https://developer.mozilla.org/en-US/docs/Web/API/Request Fetch Request instance} which you can use to read headers (like cookies, and {@link https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams URLSearchParams} from the request. */
  350. request: Request;
  351. /**
  352. * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
  353. * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
  354. */
  355. unstable_pattern: string;
  356. /**
  357. * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
  358. * @example
  359. * // app/routes.ts
  360. * route("teams/:teamId", "./team.tsx"),
  361. *
  362. * // app/team.tsx
  363. * export function loader({
  364. * params,
  365. * }: Route.LoaderArgs) {
  366. * params.teamId;
  367. * // ^ string
  368. * }
  369. */
  370. params: Params;
  371. /**
  372. * This is the context passed in to your server adapter's getLoadContext() function.
  373. * It's a way to bridge the gap between the adapter's request/response API with your React Router app.
  374. * It is only applicable if you are using a custom server adapter.
  375. */
  376. context: Context;
  377. }
  378. /**
  379. * Route middleware `next` function to call downstream handlers and then complete
  380. * middlewares from the bottom-up
  381. */
  382. interface MiddlewareNextFunction<Result = unknown> {
  383. (): Promise<Result>;
  384. }
  385. /**
  386. * Route middleware function signature. Receives the same "data" arguments as a
  387. * `loader`/`action` (`request`, `params`, `context`) as the first parameter and
  388. * a `next` function as the second parameter which will call downstream handlers
  389. * and then complete middlewares from the bottom-up
  390. */
  391. type MiddlewareFunction<Result = unknown> = (args: DataFunctionArgs<Readonly<RouterContextProvider>>, next: MiddlewareNextFunction<Result>) => MaybePromise<Result | void>;
  392. /**
  393. * Arguments passed to loader functions
  394. */
  395. interface LoaderFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
  396. }
  397. /**
  398. * Arguments passed to action functions
  399. */
  400. interface ActionFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
  401. }
  402. /**
  403. * Loaders and actions can return anything
  404. */
  405. type DataFunctionValue = unknown;
  406. type DataFunctionReturnValue = MaybePromise<DataFunctionValue>;
  407. /**
  408. * Route loader function signature
  409. */
  410. type LoaderFunction<Context = DefaultContext> = {
  411. (args: LoaderFunctionArgs<Context>, handlerCtx?: unknown): DataFunctionReturnValue;
  412. } & {
  413. hydrate?: boolean;
  414. };
  415. /**
  416. * Route action function signature
  417. */
  418. interface ActionFunction<Context = DefaultContext> {
  419. (args: ActionFunctionArgs<Context>, handlerCtx?: unknown): DataFunctionReturnValue;
  420. }
  421. /**
  422. * Arguments passed to shouldRevalidate function
  423. */
  424. interface ShouldRevalidateFunctionArgs {
  425. /** This is the url the navigation started from. You can compare it with `nextUrl` to decide if you need to revalidate this route's data. */
  426. currentUrl: URL;
  427. /** These are the {@link https://reactrouter.com/start/framework/routing#dynamic-segments dynamic route params} from the URL that can be compared to the `nextParams` to decide if you need to reload or not. Perhaps you're using only a partial piece of the param for data loading, you don't need to revalidate if a superfluous part of the param changed. */
  428. currentParams: AgnosticDataRouteMatch["params"];
  429. /** In the case of navigation, this the URL the user is requesting. Some revalidations are not navigation, so it will simply be the same as currentUrl. */
  430. nextUrl: URL;
  431. /** In the case of navigation, these are the {@link https://reactrouter.com/start/framework/routing#dynamic-segments dynamic route params} from the next location the user is requesting. Some revalidations are not navigation, so it will simply be the same as currentParams. */
  432. nextParams: AgnosticDataRouteMatch["params"];
  433. /** The method (probably `"GET"` or `"POST"`) used in the form submission that triggered the revalidation. */
  434. formMethod?: Submission["formMethod"];
  435. /** The form action (`<Form action="/somewhere">`) that triggered the revalidation. */
  436. formAction?: Submission["formAction"];
  437. /** The form encType (`<Form encType="application/x-www-form-urlencoded">) used in the form submission that triggered the revalidation*/
  438. formEncType?: Submission["formEncType"];
  439. /** The form submission data when the form's encType is `text/plain` */
  440. text?: Submission["text"];
  441. /** The form submission data when the form's encType is `application/x-www-form-urlencoded` or `multipart/form-data` */
  442. formData?: Submission["formData"];
  443. /** The form submission data when the form's encType is `application/json` */
  444. json?: Submission["json"];
  445. /** The status code of the action response */
  446. actionStatus?: number;
  447. /**
  448. * When a submission causes the revalidation this will be the result of the action—either action data or an error if the action failed. It's common to include some information in the action result to instruct shouldRevalidate to revalidate or not.
  449. *
  450. * @example
  451. * export async function action() {
  452. * await saveSomeStuff();
  453. * return { ok: true };
  454. * }
  455. *
  456. * export function shouldRevalidate({
  457. * actionResult,
  458. * }) {
  459. * if (actionResult?.ok) {
  460. * return false;
  461. * }
  462. * return true;
  463. * }
  464. */
  465. actionResult?: any;
  466. /**
  467. * By default, React Router doesn't call every loader all the time. There are reliable optimizations it can make by default. For example, only loaders with changing params are called. Consider navigating from the following URL to the one below it:
  468. *
  469. * /projects/123/tasks/abc
  470. * /projects/123/tasks/def
  471. * React Router will only call the loader for tasks/def because the param for projects/123 didn't change.
  472. *
  473. * It's safest to always return defaultShouldRevalidate after you've done your specific optimizations that return false, otherwise your UI might get out of sync with your data on the server.
  474. */
  475. defaultShouldRevalidate: boolean;
  476. }
  477. /**
  478. * Route shouldRevalidate function signature. This runs after any submission
  479. * (navigation or fetcher), so we flatten the navigation/fetcher submission
  480. * onto the arguments. It shouldn't matter whether it came from a navigation
  481. * or a fetcher, what really matters is the URLs and the formData since loaders
  482. * have to re-run based on the data models that were potentially mutated.
  483. */
  484. interface ShouldRevalidateFunction {
  485. (args: ShouldRevalidateFunctionArgs): boolean;
  486. }
  487. interface DataStrategyMatch extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {
  488. /**
  489. * @private
  490. */
  491. _lazyPromises?: {
  492. middleware: Promise<void> | undefined;
  493. handler: Promise<void> | undefined;
  494. route: Promise<void> | undefined;
  495. };
  496. /**
  497. * @deprecated Deprecated in favor of `shouldCallHandler`
  498. *
  499. * A boolean value indicating whether this route handler should be called in
  500. * this pass.
  501. *
  502. * The `matches` array always includes _all_ matched routes even when only
  503. * _some_ route handlers need to be called so that things like middleware can
  504. * be implemented.
  505. *
  506. * `shouldLoad` is usually only interesting if you are skipping the route
  507. * handler entirely and implementing custom handler logic - since it lets you
  508. * determine if that custom logic should run for this route or not.
  509. *
  510. * For example:
  511. * - If you are on `/parent/child/a` and you navigate to `/parent/child/b` -
  512. * you'll get an array of three matches (`[parent, child, b]`), but only `b`
  513. * will have `shouldLoad=true` because the data for `parent` and `child` is
  514. * already loaded
  515. * - If you are on `/parent/child/a` and you submit to `a`'s [`action`](https://reactrouter.com/docs/start/data/route-object#action),
  516. * then only `a` will have `shouldLoad=true` for the action execution of
  517. * `dataStrategy`
  518. * - After the [`action`](https://reactrouter.com/docs/start/data/route-object#action),
  519. * `dataStrategy` will be called again for the [`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
  520. * revalidation, and all matches will have `shouldLoad=true` (assuming no
  521. * custom `shouldRevalidate` implementations)
  522. */
  523. shouldLoad: boolean;
  524. /**
  525. * Arguments passed to the `shouldRevalidate` function for this `loader` execution.
  526. * Will be `null` if this is not a revalidating loader {@link DataStrategyMatch}.
  527. */
  528. shouldRevalidateArgs: ShouldRevalidateFunctionArgs | null;
  529. /**
  530. * Determine if this route's handler should be called during this `dataStrategy`
  531. * execution. Calling it with no arguments will leverage the default revalidation
  532. * behavior. You can pass your own `defaultShouldRevalidate` value if you wish
  533. * to change the default revalidation behavior with your `dataStrategy`.
  534. *
  535. * @param defaultShouldRevalidate `defaultShouldRevalidate` override value (optional)
  536. */
  537. shouldCallHandler(defaultShouldRevalidate?: boolean): boolean;
  538. /**
  539. * An async function that will resolve any `route.lazy` implementations and
  540. * execute the route's handler (if necessary), returning a {@link DataStrategyResult}
  541. *
  542. * - Calling `match.resolve` does not mean you're calling the
  543. * [`action`](https://reactrouter.com/docs/start/data/route-object#action)/[`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
  544. * (the "handler") - `resolve` will only call the `handler` internally if
  545. * needed _and_ if you don't pass your own `handlerOverride` function parameter
  546. * - It is safe to call `match.resolve` for all matches, even if they have
  547. * `shouldLoad=false`, and it will no-op if no loading is required
  548. * - You should generally always call `match.resolve()` for `shouldLoad:true`
  549. * routes to ensure that any `route.lazy` implementations are processed
  550. * - See the examples below for how to implement custom handler execution via
  551. * `match.resolve`
  552. */
  553. resolve: (handlerOverride?: (handler: (ctx?: unknown) => DataFunctionReturnValue) => DataFunctionReturnValue) => Promise<DataStrategyResult>;
  554. }
  555. interface DataStrategyFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
  556. /**
  557. * Matches for this route extended with Data strategy APIs
  558. */
  559. matches: DataStrategyMatch[];
  560. runClientMiddleware: (cb: DataStrategyFunction<Context>) => Promise<Record<string, DataStrategyResult>>;
  561. /**
  562. * The key of the fetcher we are calling `dataStrategy` for, otherwise `null`
  563. * for navigational executions
  564. */
  565. fetcherKey: string | null;
  566. }
  567. /**
  568. * Result from a loader or action called via dataStrategy
  569. */
  570. interface DataStrategyResult {
  571. type: "data" | "error";
  572. result: unknown;
  573. }
  574. interface DataStrategyFunction<Context = DefaultContext> {
  575. (args: DataStrategyFunctionArgs<Context>): Promise<Record<string, DataStrategyResult>>;
  576. }
  577. type AgnosticPatchRoutesOnNavigationFunctionArgs<O extends AgnosticRouteObject = AgnosticRouteObject, M extends AgnosticRouteMatch = AgnosticRouteMatch> = {
  578. signal: AbortSignal;
  579. path: string;
  580. matches: M[];
  581. fetcherKey: string | undefined;
  582. patch: (routeId: string | null, children: O[]) => void;
  583. };
  584. type AgnosticPatchRoutesOnNavigationFunction<O extends AgnosticRouteObject = AgnosticRouteObject, M extends AgnosticRouteMatch = AgnosticRouteMatch> = (opts: AgnosticPatchRoutesOnNavigationFunctionArgs<O, M>) => MaybePromise<void>;
  585. /**
  586. * Function provided by the framework-aware layers to set any framework-specific
  587. * properties from framework-agnostic properties
  588. */
  589. interface MapRoutePropertiesFunction {
  590. (route: AgnosticDataRouteObject): {
  591. hasErrorBoundary: boolean;
  592. } & Record<string, any>;
  593. }
  594. /**
  595. * Keys we cannot change from within a lazy object. We spread all other keys
  596. * onto the route. Either they're meaningful to the router, or they'll get
  597. * ignored.
  598. */
  599. type UnsupportedLazyRouteObjectKey = "lazy" | "caseSensitive" | "path" | "id" | "index" | "children";
  600. /**
  601. * Keys we cannot change from within a lazy() function. We spread all other keys
  602. * onto the route. Either they're meaningful to the router, or they'll get
  603. * ignored.
  604. */
  605. type UnsupportedLazyRouteFunctionKey = UnsupportedLazyRouteObjectKey | "middleware";
  606. /**
  607. * lazy object to load route properties, which can add non-matching
  608. * related properties to a route
  609. */
  610. type LazyRouteObject<R extends AgnosticRouteObject> = {
  611. [K in keyof R as K extends UnsupportedLazyRouteObjectKey ? never : K]?: () => Promise<R[K] | null | undefined>;
  612. };
  613. /**
  614. * lazy() function to load a route definition, which can add non-matching
  615. * related properties to a route
  616. */
  617. interface LazyRouteFunction<R extends AgnosticRouteObject> {
  618. (): Promise<Omit<R, UnsupportedLazyRouteFunctionKey> & Partial<Record<UnsupportedLazyRouteFunctionKey, never>>>;
  619. }
  620. type LazyRouteDefinition<R extends AgnosticRouteObject> = LazyRouteObject<R> | LazyRouteFunction<R>;
  621. /**
  622. * Base RouteObject with common props shared by all types of routes
  623. */
  624. type AgnosticBaseRouteObject = {
  625. caseSensitive?: boolean;
  626. path?: string;
  627. id?: string;
  628. middleware?: MiddlewareFunction[];
  629. loader?: LoaderFunction | boolean;
  630. action?: ActionFunction | boolean;
  631. hasErrorBoundary?: boolean;
  632. shouldRevalidate?: ShouldRevalidateFunction;
  633. handle?: any;
  634. lazy?: LazyRouteDefinition<AgnosticBaseRouteObject>;
  635. };
  636. /**
  637. * Index routes must not have children
  638. */
  639. type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {
  640. children?: undefined;
  641. index: true;
  642. };
  643. /**
  644. * Non-index routes may have children, but cannot have index
  645. */
  646. type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {
  647. children?: AgnosticRouteObject[];
  648. index?: false;
  649. };
  650. /**
  651. * A route object represents a logical route, with (optionally) its child
  652. * routes organized in a tree-like structure.
  653. */
  654. type AgnosticRouteObject = AgnosticIndexRouteObject | AgnosticNonIndexRouteObject;
  655. type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {
  656. id: string;
  657. };
  658. type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {
  659. children?: AgnosticDataRouteObject[];
  660. id: string;
  661. };
  662. /**
  663. * A data route object, which is just a RouteObject with a required unique ID
  664. */
  665. type AgnosticDataRouteObject = AgnosticDataIndexRouteObject | AgnosticDataNonIndexRouteObject;
  666. /**
  667. * The parameters that were parsed from the URL path.
  668. */
  669. type Params<Key extends string = string> = {
  670. readonly [key in Key]: string | undefined;
  671. };
  672. /**
  673. * A RouteMatch contains info about how a route matched a URL.
  674. */
  675. interface AgnosticRouteMatch<ParamKey extends string = string, RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject> {
  676. /**
  677. * The names and values of dynamic parameters in the URL.
  678. */
  679. params: Params<ParamKey>;
  680. /**
  681. * The portion of the URL pathname that was matched.
  682. */
  683. pathname: string;
  684. /**
  685. * The portion of the URL pathname that was matched before child routes.
  686. */
  687. pathnameBase: string;
  688. /**
  689. * The route object that was used to match.
  690. */
  691. route: RouteObjectType;
  692. }
  693. interface AgnosticDataRouteMatch extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {
  694. }
  695. /**
  696. * Matches the given routes to a location and returns the match data.
  697. *
  698. * @example
  699. * import { matchRoutes } from "react-router";
  700. *
  701. * let routes = [{
  702. * path: "/",
  703. * Component: Root,
  704. * children: [{
  705. * path: "dashboard",
  706. * Component: Dashboard,
  707. * }]
  708. * }];
  709. *
  710. * matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]
  711. *
  712. * @public
  713. * @category Utils
  714. * @param routes The array of route objects to match against.
  715. * @param locationArg The location to match against, either a string path or a
  716. * partial {@link Location} object
  717. * @param basename Optional base path to strip from the location before matching.
  718. * Defaults to `/`.
  719. * @returns An array of matched routes, or `null` if no matches were found.
  720. */
  721. declare function matchRoutes<RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject>(routes: RouteObjectType[], locationArg: Partial<Location> | string, basename?: string): AgnosticRouteMatch<string, RouteObjectType>[] | null;
  722. interface UIMatch<Data = unknown, Handle = unknown> {
  723. id: string;
  724. pathname: string;
  725. /**
  726. * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the matched route.
  727. */
  728. params: AgnosticRouteMatch["params"];
  729. /**
  730. * The return value from the matched route's loader or clientLoader. This might
  731. * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
  732. * an error and we're currently displaying an `ErrorBoundary`.
  733. *
  734. * @deprecated Use `UIMatch.loaderData` instead
  735. */
  736. data: Data | undefined;
  737. /**
  738. * The return value from the matched route's loader or clientLoader. This might
  739. * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
  740. * an error and we're currently displaying an `ErrorBoundary`.
  741. */
  742. loaderData: Data | undefined;
  743. /**
  744. * The {@link https://reactrouter.com/start/framework/route-module#handle handle object}
  745. * exported from the matched route module
  746. */
  747. handle: Handle;
  748. }
  749. declare class DataWithResponseInit<D> {
  750. type: string;
  751. data: D;
  752. init: ResponseInit | null;
  753. constructor(data: D, init?: ResponseInit);
  754. }
  755. /**
  756. * Create "responses" that contain `headers`/`status` without forcing
  757. * serialization into an actual [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
  758. *
  759. * @example
  760. * import { data } from "react-router";
  761. *
  762. * export async function action({ request }: Route.ActionArgs) {
  763. * let formData = await request.formData();
  764. * let item = await createItem(formData);
  765. * return data(item, {
  766. * headers: { "X-Custom-Header": "value" }
  767. * status: 201,
  768. * });
  769. * }
  770. *
  771. * @public
  772. * @category Utils
  773. * @mode framework
  774. * @mode data
  775. * @param data The data to be included in the response.
  776. * @param init The status code or a `ResponseInit` object to be included in the
  777. * response.
  778. * @returns A {@link DataWithResponseInit} instance containing the data and
  779. * response init.
  780. */
  781. declare function data<D>(data: D, init?: number | ResponseInit): DataWithResponseInit<D>;
  782. type RedirectFunction = (url: string, init?: number | ResponseInit) => Response;
  783. /**
  784. * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
  785. * Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
  786. * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
  787. *
  788. * @example
  789. * import { redirect } from "react-router";
  790. *
  791. * export async function loader({ request }: Route.LoaderArgs) {
  792. * if (!isLoggedIn(request))
  793. * throw redirect("/login");
  794. * }
  795. *
  796. * // ...
  797. * }
  798. *
  799. * @public
  800. * @category Utils
  801. * @mode framework
  802. * @mode data
  803. * @param url The URL to redirect to.
  804. * @param init The status code or a `ResponseInit` object to be included in the
  805. * response.
  806. * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
  807. * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
  808. * header.
  809. */
  810. declare const redirect$1: RedirectFunction;
  811. /**
  812. * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
  813. * that will force a document reload to the new location. Sets the status code
  814. * and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
  815. * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
  816. *
  817. * ```tsx filename=routes/logout.tsx
  818. * import { redirectDocument } from "react-router";
  819. *
  820. * import { destroySession } from "../sessions.server";
  821. *
  822. * export async function action({ request }: Route.ActionArgs) {
  823. * let session = await getSession(request.headers.get("Cookie"));
  824. * return redirectDocument("/", {
  825. * headers: { "Set-Cookie": await destroySession(session) }
  826. * });
  827. * }
  828. * ```
  829. *
  830. * @public
  831. * @category Utils
  832. * @mode framework
  833. * @mode data
  834. * @param url The URL to redirect to.
  835. * @param init The status code or a `ResponseInit` object to be included in the
  836. * response.
  837. * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
  838. * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
  839. * header.
  840. */
  841. declare const redirectDocument$1: RedirectFunction;
  842. /**
  843. * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
  844. * that will perform a [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)
  845. * instead of a [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
  846. * for client-side navigation redirects. Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
  847. * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
  848. *
  849. * @example
  850. * import { replace } from "react-router";
  851. *
  852. * export async function loader() {
  853. * return replace("/new-location");
  854. * }
  855. *
  856. * @public
  857. * @category Utils
  858. * @mode framework
  859. * @mode data
  860. * @param url The URL to redirect to.
  861. * @param init The status code or a `ResponseInit` object to be included in the
  862. * response.
  863. * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
  864. * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
  865. * header.
  866. */
  867. declare const replace$1: RedirectFunction;
  868. type ErrorResponse = {
  869. status: number;
  870. statusText: string;
  871. data: any;
  872. };
  873. /**
  874. * Check if the given error is an {@link ErrorResponse} generated from a 4xx/5xx
  875. * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
  876. * thrown from an [`action`](../../start/framework/route-module#action) or
  877. * [`loader`](../../start/framework/route-module#loader) function.
  878. *
  879. * @example
  880. * import { isRouteErrorResponse } from "react-router";
  881. *
  882. * export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
  883. * if (isRouteErrorResponse(error)) {
  884. * return (
  885. * <>
  886. * <p>Error: `${error.status}: ${error.statusText}`</p>
  887. * <p>{error.data}</p>
  888. * </>
  889. * );
  890. * }
  891. *
  892. * return (
  893. * <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p>
  894. * );
  895. * }
  896. *
  897. * @public
  898. * @category Utils
  899. * @mode framework
  900. * @mode data
  901. * @param error The error to check.
  902. * @returns `true` if the error is an {@link ErrorResponse}, `false` otherwise.
  903. */
  904. declare function isRouteErrorResponse(error: any): error is ErrorResponse;
  905. /**
  906. * An object of unknown type for route loaders and actions provided by the
  907. * server's `getLoadContext()` function. This is defined as an empty interface
  908. * specifically so apps can leverage declaration merging to augment this type
  909. * globally: https://www.typescriptlang.org/docs/handbook/declaration-merging.html
  910. */
  911. interface AppLoadContext {
  912. [key: string]: unknown;
  913. }
  914. type unstable_ServerInstrumentation = {
  915. handler?: unstable_InstrumentRequestHandlerFunction;
  916. route?: unstable_InstrumentRouteFunction;
  917. };
  918. type unstable_ClientInstrumentation = {
  919. router?: unstable_InstrumentRouterFunction;
  920. route?: unstable_InstrumentRouteFunction;
  921. };
  922. type unstable_InstrumentRequestHandlerFunction = (handler: InstrumentableRequestHandler) => void;
  923. type unstable_InstrumentRouterFunction = (router: InstrumentableRouter) => void;
  924. type unstable_InstrumentRouteFunction = (route: InstrumentableRoute) => void;
  925. type unstable_InstrumentationHandlerResult = {
  926. status: "success";
  927. error: undefined;
  928. } | {
  929. status: "error";
  930. error: Error;
  931. };
  932. type InstrumentFunction<T> = (handler: () => Promise<unstable_InstrumentationHandlerResult>, info: T) => Promise<void>;
  933. type ReadonlyRequest = {
  934. method: string;
  935. url: string;
  936. headers: Pick<Headers, "get">;
  937. };
  938. type ReadonlyContext = MiddlewareEnabled extends true ? Pick<RouterContextProvider, "get"> : Readonly<AppLoadContext>;
  939. type InstrumentableRoute = {
  940. id: string;
  941. index: boolean | undefined;
  942. path: string | undefined;
  943. instrument(instrumentations: RouteInstrumentations): void;
  944. };
  945. type RouteInstrumentations = {
  946. lazy?: InstrumentFunction<RouteLazyInstrumentationInfo>;
  947. "lazy.loader"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
  948. "lazy.action"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
  949. "lazy.middleware"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
  950. middleware?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
  951. loader?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
  952. action?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
  953. };
  954. type RouteLazyInstrumentationInfo = undefined;
  955. type RouteHandlerInstrumentationInfo = Readonly<{
  956. request: ReadonlyRequest;
  957. params: LoaderFunctionArgs["params"];
  958. unstable_pattern: string;
  959. context: ReadonlyContext;
  960. }>;
  961. type InstrumentableRouter = {
  962. instrument(instrumentations: RouterInstrumentations): void;
  963. };
  964. type RouterInstrumentations = {
  965. navigate?: InstrumentFunction<RouterNavigationInstrumentationInfo>;
  966. fetch?: InstrumentFunction<RouterFetchInstrumentationInfo>;
  967. };
  968. type RouterNavigationInstrumentationInfo = Readonly<{
  969. to: string | number;
  970. currentUrl: string;
  971. formMethod?: HTMLFormMethod;
  972. formEncType?: FormEncType;
  973. formData?: FormData;
  974. body?: any;
  975. }>;
  976. type RouterFetchInstrumentationInfo = Readonly<{
  977. href: string;
  978. currentUrl: string;
  979. fetcherKey: string;
  980. formMethod?: HTMLFormMethod;
  981. formEncType?: FormEncType;
  982. formData?: FormData;
  983. body?: any;
  984. }>;
  985. type InstrumentableRequestHandler = {
  986. instrument(instrumentations: RequestHandlerInstrumentations): void;
  987. };
  988. type RequestHandlerInstrumentations = {
  989. request?: InstrumentFunction<RequestHandlerInstrumentationInfo>;
  990. };
  991. type RequestHandlerInstrumentationInfo = Readonly<{
  992. request: ReadonlyRequest;
  993. context: ReadonlyContext | undefined;
  994. }>;
  995. /**
  996. * A Router instance manages all navigation and data loading/mutations
  997. */
  998. interface Router {
  999. /**
  1000. * @private
  1001. * PRIVATE - DO NOT USE
  1002. *
  1003. * Return the basename for the router
  1004. */
  1005. get basename(): RouterInit["basename"];
  1006. /**
  1007. * @private
  1008. * PRIVATE - DO NOT USE
  1009. *
  1010. * Return the future config for the router
  1011. */
  1012. get future(): FutureConfig;
  1013. /**
  1014. * @private
  1015. * PRIVATE - DO NOT USE
  1016. *
  1017. * Return the current state of the router
  1018. */
  1019. get state(): RouterState;
  1020. /**
  1021. * @private
  1022. * PRIVATE - DO NOT USE
  1023. *
  1024. * Return the routes for this router instance
  1025. */
  1026. get routes(): AgnosticDataRouteObject[];
  1027. /**
  1028. * @private
  1029. * PRIVATE - DO NOT USE
  1030. *
  1031. * Return the window associated with the router
  1032. */
  1033. get window(): RouterInit["window"];
  1034. /**
  1035. * @private
  1036. * PRIVATE - DO NOT USE
  1037. *
  1038. * Initialize the router, including adding history listeners and kicking off
  1039. * initial data fetches. Returns a function to cleanup listeners and abort
  1040. * any in-progress loads
  1041. */
  1042. initialize(): Router;
  1043. /**
  1044. * @private
  1045. * PRIVATE - DO NOT USE
  1046. *
  1047. * Subscribe to router.state updates
  1048. *
  1049. * @param fn function to call with the new state
  1050. */
  1051. subscribe(fn: RouterSubscriber): () => void;
  1052. /**
  1053. * @private
  1054. * PRIVATE - DO NOT USE
  1055. *
  1056. * Enable scroll restoration behavior in the router
  1057. *
  1058. * @param savedScrollPositions Object that will manage positions, in case
  1059. * it's being restored from sessionStorage
  1060. * @param getScrollPosition Function to get the active Y scroll position
  1061. * @param getKey Function to get the key to use for restoration
  1062. */
  1063. enableScrollRestoration(savedScrollPositions: Record<string, number>, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction): () => void;
  1064. /**
  1065. * @private
  1066. * PRIVATE - DO NOT USE
  1067. *
  1068. * Navigate forward/backward in the history stack
  1069. * @param to Delta to move in the history stack
  1070. */
  1071. navigate(to: number): Promise<void>;
  1072. /**
  1073. * Navigate to the given path
  1074. * @param to Path to navigate to
  1075. * @param opts Navigation options (method, submission, etc.)
  1076. */
  1077. navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;
  1078. /**
  1079. * @private
  1080. * PRIVATE - DO NOT USE
  1081. *
  1082. * Trigger a fetcher load/submission
  1083. *
  1084. * @param key Fetcher key
  1085. * @param routeId Route that owns the fetcher
  1086. * @param href href to fetch
  1087. * @param opts Fetcher options, (method, submission, etc.)
  1088. */
  1089. fetch(key: string, routeId: string, href: string | null, opts?: RouterFetchOptions): Promise<void>;
  1090. /**
  1091. * @private
  1092. * PRIVATE - DO NOT USE
  1093. *
  1094. * Trigger a revalidation of all current route loaders and fetcher loads
  1095. */
  1096. revalidate(): Promise<void>;
  1097. /**
  1098. * @private
  1099. * PRIVATE - DO NOT USE
  1100. *
  1101. * Utility function to create an href for the given location
  1102. * @param location
  1103. */
  1104. createHref(location: Location | URL): string;
  1105. /**
  1106. * @private
  1107. * PRIVATE - DO NOT USE
  1108. *
  1109. * Utility function to URL encode a destination path according to the internal
  1110. * history implementation
  1111. * @param to
  1112. */
  1113. encodeLocation(to: To): Path;
  1114. /**
  1115. * @private
  1116. * PRIVATE - DO NOT USE
  1117. *
  1118. * Get/create a fetcher for the given key
  1119. * @param key
  1120. */
  1121. getFetcher<TData = any>(key: string): Fetcher<TData>;
  1122. /**
  1123. * @internal
  1124. * PRIVATE - DO NOT USE
  1125. *
  1126. * Reset the fetcher for a given key
  1127. * @param key
  1128. */
  1129. resetFetcher(key: string, opts?: {
  1130. reason?: unknown;
  1131. }): void;
  1132. /**
  1133. * @private
  1134. * PRIVATE - DO NOT USE
  1135. *
  1136. * Delete the fetcher for a given key
  1137. * @param key
  1138. */
  1139. deleteFetcher(key: string): void;
  1140. /**
  1141. * @private
  1142. * PRIVATE - DO NOT USE
  1143. *
  1144. * Cleanup listeners and abort any in-progress loads
  1145. */
  1146. dispose(): void;
  1147. /**
  1148. * @private
  1149. * PRIVATE - DO NOT USE
  1150. *
  1151. * Get a navigation blocker
  1152. * @param key The identifier for the blocker
  1153. * @param fn The blocker function implementation
  1154. */
  1155. getBlocker(key: string, fn: BlockerFunction): Blocker;
  1156. /**
  1157. * @private
  1158. * PRIVATE - DO NOT USE
  1159. *
  1160. * Delete a navigation blocker
  1161. * @param key The identifier for the blocker
  1162. */
  1163. deleteBlocker(key: string): void;
  1164. /**
  1165. * @private
  1166. * PRIVATE DO NOT USE
  1167. *
  1168. * Patch additional children routes into an existing parent route
  1169. * @param routeId The parent route id or a callback function accepting `patch`
  1170. * to perform batch patching
  1171. * @param children The additional children routes
  1172. * @param unstable_allowElementMutations Allow mutation or route elements on
  1173. * existing routes. Intended for RSC-usage
  1174. * only.
  1175. */
  1176. patchRoutes(routeId: string | null, children: AgnosticRouteObject[], unstable_allowElementMutations?: boolean): void;
  1177. /**
  1178. * @private
  1179. * PRIVATE - DO NOT USE
  1180. *
  1181. * HMR needs to pass in-flight route updates to React Router
  1182. * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)
  1183. */
  1184. _internalSetRoutes(routes: AgnosticRouteObject[]): void;
  1185. /**
  1186. * @private
  1187. * PRIVATE - DO NOT USE
  1188. *
  1189. * Cause subscribers to re-render. This is used to force a re-render.
  1190. */
  1191. _internalSetStateDoNotUseOrYouWillBreakYourApp(state: Partial<RouterState>): void;
  1192. /**
  1193. * @private
  1194. * PRIVATE - DO NOT USE
  1195. *
  1196. * Internal fetch AbortControllers accessed by unit tests
  1197. */
  1198. _internalFetchControllers: Map<string, AbortController>;
  1199. }
  1200. /**
  1201. * State maintained internally by the router. During a navigation, all states
  1202. * reflect the "old" location unless otherwise noted.
  1203. */
  1204. interface RouterState {
  1205. /**
  1206. * The action of the most recent navigation
  1207. */
  1208. historyAction: Action;
  1209. /**
  1210. * The current location reflected by the router
  1211. */
  1212. location: Location;
  1213. /**
  1214. * The current set of route matches
  1215. */
  1216. matches: AgnosticDataRouteMatch[];
  1217. /**
  1218. * Tracks whether we've completed our initial data load
  1219. */
  1220. initialized: boolean;
  1221. /**
  1222. * Current scroll position we should start at for a new view
  1223. * - number -> scroll position to restore to
  1224. * - false -> do not restore scroll at all (used during submissions/revalidations)
  1225. * - null -> don't have a saved position, scroll to hash or top of page
  1226. */
  1227. restoreScrollPosition: number | false | null;
  1228. /**
  1229. * Indicate whether this navigation should skip resetting the scroll position
  1230. * if we are unable to restore the scroll position
  1231. */
  1232. preventScrollReset: boolean;
  1233. /**
  1234. * Tracks the state of the current navigation
  1235. */
  1236. navigation: Navigation;
  1237. /**
  1238. * Tracks any in-progress revalidations
  1239. */
  1240. revalidation: RevalidationState;
  1241. /**
  1242. * Data from the loaders for the current matches
  1243. */
  1244. loaderData: RouteData;
  1245. /**
  1246. * Data from the action for the current matches
  1247. */
  1248. actionData: RouteData | null;
  1249. /**
  1250. * Errors caught from loaders for the current matches
  1251. */
  1252. errors: RouteData | null;
  1253. /**
  1254. * Map of current fetchers
  1255. */
  1256. fetchers: Map<string, Fetcher>;
  1257. /**
  1258. * Map of current blockers
  1259. */
  1260. blockers: Map<string, Blocker>;
  1261. }
  1262. /**
  1263. * Data that can be passed into hydrate a Router from SSR
  1264. */
  1265. type HydrationState = Partial<Pick<RouterState, "loaderData" | "actionData" | "errors">>;
  1266. /**
  1267. * Future flags to toggle new feature behavior
  1268. */
  1269. interface FutureConfig {
  1270. }
  1271. /**
  1272. * Initialization options for createRouter
  1273. */
  1274. interface RouterInit {
  1275. routes: AgnosticRouteObject[];
  1276. history: History;
  1277. basename?: string;
  1278. getContext?: () => MaybePromise<RouterContextProvider>;
  1279. unstable_instrumentations?: unstable_ClientInstrumentation[];
  1280. mapRouteProperties?: MapRoutePropertiesFunction;
  1281. future?: Partial<FutureConfig>;
  1282. hydrationRouteProperties?: string[];
  1283. hydrationData?: HydrationState;
  1284. window?: Window;
  1285. dataStrategy?: DataStrategyFunction;
  1286. patchRoutesOnNavigation?: AgnosticPatchRoutesOnNavigationFunction;
  1287. }
  1288. /**
  1289. * State returned from a server-side query() call
  1290. */
  1291. interface StaticHandlerContext {
  1292. basename: Router["basename"];
  1293. location: RouterState["location"];
  1294. matches: RouterState["matches"];
  1295. loaderData: RouterState["loaderData"];
  1296. actionData: RouterState["actionData"];
  1297. errors: RouterState["errors"];
  1298. statusCode: number;
  1299. loaderHeaders: Record<string, Headers>;
  1300. actionHeaders: Record<string, Headers>;
  1301. _deepestRenderedBoundaryId?: string | null;
  1302. }
  1303. /**
  1304. * A StaticHandler instance manages a singular SSR navigation/fetch event
  1305. */
  1306. interface StaticHandler {
  1307. dataRoutes: AgnosticDataRouteObject[];
  1308. query(request: Request, opts?: {
  1309. requestContext?: unknown;
  1310. filterMatchesToLoad?: (match: AgnosticDataRouteMatch) => boolean;
  1311. skipLoaderErrorBubbling?: boolean;
  1312. skipRevalidation?: boolean;
  1313. dataStrategy?: DataStrategyFunction<unknown>;
  1314. generateMiddlewareResponse?: (query: (r: Request, args?: {
  1315. filterMatchesToLoad?: (match: AgnosticDataRouteMatch) => boolean;
  1316. }) => Promise<StaticHandlerContext | Response>) => MaybePromise<Response>;
  1317. }): Promise<StaticHandlerContext | Response>;
  1318. queryRoute(request: Request, opts?: {
  1319. routeId?: string;
  1320. requestContext?: unknown;
  1321. dataStrategy?: DataStrategyFunction<unknown>;
  1322. generateMiddlewareResponse?: (queryRoute: (r: Request) => Promise<Response>) => MaybePromise<Response>;
  1323. }): Promise<any>;
  1324. }
  1325. type ViewTransitionOpts = {
  1326. currentLocation: Location;
  1327. nextLocation: Location;
  1328. };
  1329. /**
  1330. * Subscriber function signature for changes to router state
  1331. */
  1332. interface RouterSubscriber {
  1333. (state: RouterState, opts: {
  1334. deletedFetchers: string[];
  1335. newErrors: RouteData | null;
  1336. viewTransitionOpts?: ViewTransitionOpts;
  1337. flushSync: boolean;
  1338. }): void;
  1339. }
  1340. /**
  1341. * Function signature for determining the key to be used in scroll restoration
  1342. * for a given location
  1343. */
  1344. interface GetScrollRestorationKeyFunction {
  1345. (location: Location, matches: UIMatch[]): string | null;
  1346. }
  1347. /**
  1348. * Function signature for determining the current scroll position
  1349. */
  1350. interface GetScrollPositionFunction {
  1351. (): number;
  1352. }
  1353. /**
  1354. * - "route": relative to the route hierarchy so `..` means remove all segments
  1355. * of the current route even if it has many. For example, a `route("posts/:id")`
  1356. * would have both `:id` and `posts` removed from the url.
  1357. * - "path": relative to the pathname so `..` means remove one segment of the
  1358. * pathname. For example, a `route("posts/:id")` would have only `:id` removed
  1359. * from the url.
  1360. */
  1361. type RelativeRoutingType = "route" | "path";
  1362. type BaseNavigateOrFetchOptions = {
  1363. preventScrollReset?: boolean;
  1364. relative?: RelativeRoutingType;
  1365. flushSync?: boolean;
  1366. };
  1367. type BaseNavigateOptions = BaseNavigateOrFetchOptions & {
  1368. replace?: boolean;
  1369. state?: any;
  1370. fromRouteId?: string;
  1371. viewTransition?: boolean;
  1372. };
  1373. type BaseSubmissionOptions = {
  1374. formMethod?: HTMLFormMethod;
  1375. formEncType?: FormEncType;
  1376. } & ({
  1377. formData: FormData;
  1378. body?: undefined;
  1379. } | {
  1380. formData?: undefined;
  1381. body: any;
  1382. });
  1383. /**
  1384. * Options for a navigate() call for a normal (non-submission) navigation
  1385. */
  1386. type LinkNavigateOptions = BaseNavigateOptions;
  1387. /**
  1388. * Options for a navigate() call for a submission navigation
  1389. */
  1390. type SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;
  1391. /**
  1392. * Options to pass to navigate() for a navigation
  1393. */
  1394. type RouterNavigateOptions = LinkNavigateOptions | SubmissionNavigateOptions;
  1395. /**
  1396. * Options for a fetch() load
  1397. */
  1398. type LoadFetchOptions = BaseNavigateOrFetchOptions;
  1399. /**
  1400. * Options for a fetch() submission
  1401. */
  1402. type SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;
  1403. /**
  1404. * Options to pass to fetch()
  1405. */
  1406. type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;
  1407. /**
  1408. * Potential states for state.navigation
  1409. */
  1410. type NavigationStates = {
  1411. Idle: {
  1412. state: "idle";
  1413. location: undefined;
  1414. formMethod: undefined;
  1415. formAction: undefined;
  1416. formEncType: undefined;
  1417. formData: undefined;
  1418. json: undefined;
  1419. text: undefined;
  1420. };
  1421. Loading: {
  1422. state: "loading";
  1423. location: Location;
  1424. formMethod: Submission["formMethod"] | undefined;
  1425. formAction: Submission["formAction"] | undefined;
  1426. formEncType: Submission["formEncType"] | undefined;
  1427. formData: Submission["formData"] | undefined;
  1428. json: Submission["json"] | undefined;
  1429. text: Submission["text"] | undefined;
  1430. };
  1431. Submitting: {
  1432. state: "submitting";
  1433. location: Location;
  1434. formMethod: Submission["formMethod"];
  1435. formAction: Submission["formAction"];
  1436. formEncType: Submission["formEncType"];
  1437. formData: Submission["formData"];
  1438. json: Submission["json"];
  1439. text: Submission["text"];
  1440. };
  1441. };
  1442. type Navigation = NavigationStates[keyof NavigationStates];
  1443. type RevalidationState = "idle" | "loading";
  1444. /**
  1445. * Potential states for fetchers
  1446. */
  1447. type FetcherStates<TData = any> = {
  1448. /**
  1449. * The fetcher is not calling a loader or action
  1450. *
  1451. * ```tsx
  1452. * fetcher.state === "idle"
  1453. * ```
  1454. */
  1455. Idle: {
  1456. state: "idle";
  1457. formMethod: undefined;
  1458. formAction: undefined;
  1459. formEncType: undefined;
  1460. text: undefined;
  1461. formData: undefined;
  1462. json: undefined;
  1463. /**
  1464. * If the fetcher has never been called, this will be undefined.
  1465. */
  1466. data: TData | undefined;
  1467. };
  1468. /**
  1469. * The fetcher is loading data from a {@link LoaderFunction | loader} from a
  1470. * call to {@link FetcherWithComponents.load | `fetcher.load`}.
  1471. *
  1472. * ```tsx
  1473. * // somewhere
  1474. * <button onClick={() => fetcher.load("/some/route") }>Load</button>
  1475. *
  1476. * // the state will update
  1477. * fetcher.state === "loading"
  1478. * ```
  1479. */
  1480. Loading: {
  1481. state: "loading";
  1482. formMethod: Submission["formMethod"] | undefined;
  1483. formAction: Submission["formAction"] | undefined;
  1484. formEncType: Submission["formEncType"] | undefined;
  1485. text: Submission["text"] | undefined;
  1486. formData: Submission["formData"] | undefined;
  1487. json: Submission["json"] | undefined;
  1488. data: TData | undefined;
  1489. };
  1490. /**
  1491. 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`}.
  1492. ```tsx
  1493. // somewhere
  1494. <input
  1495. onChange={e => {
  1496. fetcher.submit(event.currentTarget.form, { method: "post" });
  1497. }}
  1498. />
  1499. // the state will update
  1500. fetcher.state === "submitting"
  1501. // and formData will be available
  1502. fetcher.formData
  1503. ```
  1504. */
  1505. Submitting: {
  1506. state: "submitting";
  1507. formMethod: Submission["formMethod"];
  1508. formAction: Submission["formAction"];
  1509. formEncType: Submission["formEncType"];
  1510. text: Submission["text"];
  1511. formData: Submission["formData"];
  1512. json: Submission["json"];
  1513. data: TData | undefined;
  1514. };
  1515. };
  1516. type Fetcher<TData = any> = FetcherStates<TData>[keyof FetcherStates<TData>];
  1517. interface BlockerBlocked {
  1518. state: "blocked";
  1519. reset: () => void;
  1520. proceed: () => void;
  1521. location: Location;
  1522. }
  1523. interface BlockerUnblocked {
  1524. state: "unblocked";
  1525. reset: undefined;
  1526. proceed: undefined;
  1527. location: undefined;
  1528. }
  1529. interface BlockerProceeding {
  1530. state: "proceeding";
  1531. reset: undefined;
  1532. proceed: undefined;
  1533. location: Location;
  1534. }
  1535. type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;
  1536. type BlockerFunction = (args: {
  1537. currentLocation: Location;
  1538. nextLocation: Location;
  1539. historyAction: Action;
  1540. }) => boolean;
  1541. interface CreateStaticHandlerOptions {
  1542. basename?: string;
  1543. mapRouteProperties?: MapRoutePropertiesFunction;
  1544. unstable_instrumentations?: Pick<unstable_ServerInstrumentation, "route">[];
  1545. future?: {};
  1546. }
  1547. declare function createStaticHandler(routes: AgnosticRouteObject[], opts?: CreateStaticHandlerOptions): StaticHandler;
  1548. interface AwaitResolveRenderFunction<Resolve = any> {
  1549. (data: Awaited<Resolve>): React.ReactNode;
  1550. }
  1551. /**
  1552. * @category Types
  1553. */
  1554. interface AwaitProps<Resolve> {
  1555. /**
  1556. * When using a function, the resolved value is provided as the parameter.
  1557. *
  1558. * ```tsx [2]
  1559. * <Await resolve={reviewsPromise}>
  1560. * {(resolvedReviews) => <Reviews items={resolvedReviews} />}
  1561. * </Await>
  1562. * ```
  1563. *
  1564. * When using React elements, {@link useAsyncValue} will provide the
  1565. * resolved value:
  1566. *
  1567. * ```tsx [2]
  1568. * <Await resolve={reviewsPromise}>
  1569. * <Reviews />
  1570. * </Await>
  1571. *
  1572. * function Reviews() {
  1573. * const resolvedReviews = useAsyncValue();
  1574. * return <div>...</div>;
  1575. * }
  1576. * ```
  1577. */
  1578. children: React.ReactNode | AwaitResolveRenderFunction<Resolve>;
  1579. /**
  1580. * The error element renders instead of the `children` when the [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
  1581. * rejects.
  1582. *
  1583. * ```tsx
  1584. * <Await
  1585. * errorElement={<div>Oops</div>}
  1586. * resolve={reviewsPromise}
  1587. * >
  1588. * <Reviews />
  1589. * </Await>
  1590. * ```
  1591. *
  1592. * To provide a more contextual error, you can use the {@link useAsyncError} in a
  1593. * child component
  1594. *
  1595. * ```tsx
  1596. * <Await
  1597. * errorElement={<ReviewsError />}
  1598. * resolve={reviewsPromise}
  1599. * >
  1600. * <Reviews />
  1601. * </Await>
  1602. *
  1603. * function ReviewsError() {
  1604. * const error = useAsyncError();
  1605. * return <div>Error loading reviews: {error.message}</div>;
  1606. * }
  1607. * ```
  1608. *
  1609. * If you do not provide an `errorElement`, the rejected value will bubble up
  1610. * to the nearest route-level [`ErrorBoundary`](../../start/framework/route-module#errorboundary)
  1611. * and be accessible via the {@link useRouteError} hook.
  1612. */
  1613. errorElement?: React.ReactNode;
  1614. /**
  1615. * Takes a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
  1616. * returned from a [`loader`](../../start/framework/route-module#loader) to be
  1617. * resolved and rendered.
  1618. *
  1619. * ```tsx
  1620. * import { Await, useLoaderData } from "react-router";
  1621. *
  1622. * export async function loader() {
  1623. * let reviews = getReviews(); // not awaited
  1624. * let book = await getBook();
  1625. * return {
  1626. * book,
  1627. * reviews, // this is a promise
  1628. * };
  1629. * }
  1630. *
  1631. * export default function Book() {
  1632. * const {
  1633. * book,
  1634. * reviews, // this is the same promise
  1635. * } = useLoaderData();
  1636. *
  1637. * return (
  1638. * <div>
  1639. * <h1>{book.title}</h1>
  1640. * <p>{book.description}</p>
  1641. * <React.Suspense fallback={<ReviewsSkeleton />}>
  1642. * <Await
  1643. * // and is the promise we pass to Await
  1644. * resolve={reviews}
  1645. * >
  1646. * <Reviews />
  1647. * </Await>
  1648. * </React.Suspense>
  1649. * </div>
  1650. * );
  1651. * }
  1652. * ```
  1653. */
  1654. resolve: Resolve;
  1655. }
  1656. /**
  1657. * Used to render promise values with automatic error handling.
  1658. *
  1659. * **Note:** `<Await>` expects to be rendered inside a [`<React.Suspense>`](https://react.dev/reference/react/Suspense)
  1660. *
  1661. * @example
  1662. * import { Await, useLoaderData } from "react-router";
  1663. *
  1664. * export async function loader() {
  1665. * // not awaited
  1666. * const reviews = getReviews();
  1667. * // awaited (blocks the transition)
  1668. * const book = await fetch("/api/book").then((res) => res.json());
  1669. * return { book, reviews };
  1670. * }
  1671. *
  1672. * function Book() {
  1673. * const { book, reviews } = useLoaderData();
  1674. * return (
  1675. * <div>
  1676. * <h1>{book.title}</h1>
  1677. * <p>{book.description}</p>
  1678. * <React.Suspense fallback={<ReviewsSkeleton />}>
  1679. * <Await
  1680. * resolve={reviews}
  1681. * errorElement={
  1682. * <div>Could not load reviews 😬</div>
  1683. * }
  1684. * children={(resolvedReviews) => (
  1685. * <Reviews items={resolvedReviews} />
  1686. * )}
  1687. * />
  1688. * </React.Suspense>
  1689. * </div>
  1690. * );
  1691. * }
  1692. *
  1693. * @public
  1694. * @category Components
  1695. * @mode framework
  1696. * @mode data
  1697. * @param props Props
  1698. * @param {AwaitProps.children} props.children n/a
  1699. * @param {AwaitProps.errorElement} props.errorElement n/a
  1700. * @param {AwaitProps.resolve} props.resolve n/a
  1701. * @returns React element for the rendered awaited value
  1702. */
  1703. declare function Await$1<Resolve>({ children, errorElement, resolve, }: AwaitProps<Resolve>): React.JSX.Element;
  1704. interface IndexRouteObject {
  1705. caseSensitive?: AgnosticIndexRouteObject["caseSensitive"];
  1706. path?: AgnosticIndexRouteObject["path"];
  1707. id?: AgnosticIndexRouteObject["id"];
  1708. middleware?: AgnosticIndexRouteObject["middleware"];
  1709. loader?: AgnosticIndexRouteObject["loader"];
  1710. action?: AgnosticIndexRouteObject["action"];
  1711. hasErrorBoundary?: AgnosticIndexRouteObject["hasErrorBoundary"];
  1712. shouldRevalidate?: AgnosticIndexRouteObject["shouldRevalidate"];
  1713. handle?: AgnosticIndexRouteObject["handle"];
  1714. index: true;
  1715. children?: undefined;
  1716. element?: React.ReactNode | null;
  1717. hydrateFallbackElement?: React.ReactNode | null;
  1718. errorElement?: React.ReactNode | null;
  1719. Component?: React.ComponentType | null;
  1720. HydrateFallback?: React.ComponentType | null;
  1721. ErrorBoundary?: React.ComponentType | null;
  1722. lazy?: LazyRouteDefinition<RouteObject>;
  1723. }
  1724. interface NonIndexRouteObject {
  1725. caseSensitive?: AgnosticNonIndexRouteObject["caseSensitive"];
  1726. path?: AgnosticNonIndexRouteObject["path"];
  1727. id?: AgnosticNonIndexRouteObject["id"];
  1728. middleware?: AgnosticNonIndexRouteObject["middleware"];
  1729. loader?: AgnosticNonIndexRouteObject["loader"];
  1730. action?: AgnosticNonIndexRouteObject["action"];
  1731. hasErrorBoundary?: AgnosticNonIndexRouteObject["hasErrorBoundary"];
  1732. shouldRevalidate?: AgnosticNonIndexRouteObject["shouldRevalidate"];
  1733. handle?: AgnosticNonIndexRouteObject["handle"];
  1734. index?: false;
  1735. children?: RouteObject[];
  1736. element?: React.ReactNode | null;
  1737. hydrateFallbackElement?: React.ReactNode | null;
  1738. errorElement?: React.ReactNode | null;
  1739. Component?: React.ComponentType | null;
  1740. HydrateFallback?: React.ComponentType | null;
  1741. ErrorBoundary?: React.ComponentType | null;
  1742. lazy?: LazyRouteDefinition<RouteObject>;
  1743. }
  1744. type RouteObject = IndexRouteObject | NonIndexRouteObject;
  1745. type DataRouteObject = RouteObject & {
  1746. children?: DataRouteObject[];
  1747. id: string;
  1748. };
  1749. interface RouteMatch<ParamKey extends string = string, RouteObjectType extends RouteObject = RouteObject> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {
  1750. }
  1751. interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {
  1752. }
  1753. type Primitive = null | undefined | string | number | boolean | symbol | bigint;
  1754. type LiteralUnion<LiteralType, BaseType extends Primitive> = LiteralType | (BaseType & Record<never, never>);
  1755. interface HtmlLinkProps {
  1756. /**
  1757. * Address of the hyperlink
  1758. */
  1759. href?: string;
  1760. /**
  1761. * How the element handles crossorigin requests
  1762. */
  1763. crossOrigin?: "anonymous" | "use-credentials";
  1764. /**
  1765. * Relationship between the document containing the hyperlink and the destination resource
  1766. */
  1767. rel: LiteralUnion<"alternate" | "dns-prefetch" | "icon" | "manifest" | "modulepreload" | "next" | "pingback" | "preconnect" | "prefetch" | "preload" | "prerender" | "search" | "stylesheet", string>;
  1768. /**
  1769. * Applicable media: "screen", "print", "(max-width: 764px)"
  1770. */
  1771. media?: string;
  1772. /**
  1773. * Integrity metadata used in Subresource Integrity checks
  1774. */
  1775. integrity?: string;
  1776. /**
  1777. * Language of the linked resource
  1778. */
  1779. hrefLang?: string;
  1780. /**
  1781. * Hint for the type of the referenced resource
  1782. */
  1783. type?: string;
  1784. /**
  1785. * Referrer policy for fetches initiated by the element
  1786. */
  1787. referrerPolicy?: "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
  1788. /**
  1789. * Sizes of the icons (for rel="icon")
  1790. */
  1791. sizes?: string;
  1792. /**
  1793. * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
  1794. */
  1795. as?: LiteralUnion<"audio" | "audioworklet" | "document" | "embed" | "fetch" | "font" | "frame" | "iframe" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt", string>;
  1796. /**
  1797. * Color to use when customizing a site's icon (for rel="mask-icon")
  1798. */
  1799. color?: string;
  1800. /**
  1801. * Whether the link is disabled
  1802. */
  1803. disabled?: boolean;
  1804. /**
  1805. * The title attribute has special semantics on this element: Title of the link; CSS style sheet set name.
  1806. */
  1807. title?: string;
  1808. /**
  1809. * Images to use in different situations, e.g., high-resolution displays,
  1810. * small monitors, etc. (for rel="preload")
  1811. */
  1812. imageSrcSet?: string;
  1813. /**
  1814. * Image sizes for different page layouts (for rel="preload")
  1815. */
  1816. imageSizes?: string;
  1817. }
  1818. interface HtmlLinkPreloadImage extends HtmlLinkProps {
  1819. /**
  1820. * Relationship between the document containing the hyperlink and the destination resource
  1821. */
  1822. rel: "preload";
  1823. /**
  1824. * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
  1825. */
  1826. as: "image";
  1827. /**
  1828. * Address of the hyperlink
  1829. */
  1830. href?: string;
  1831. /**
  1832. * Images to use in different situations, e.g., high-resolution displays,
  1833. * small monitors, etc. (for rel="preload")
  1834. */
  1835. imageSrcSet: string;
  1836. /**
  1837. * Image sizes for different page layouts (for rel="preload")
  1838. */
  1839. imageSizes?: string;
  1840. }
  1841. /**
  1842. * Represents a `<link>` element.
  1843. *
  1844. * WHATWG Specification: https://html.spec.whatwg.org/multipage/semantics.html#the-link-element
  1845. */
  1846. type HtmlLinkDescriptor = (HtmlLinkProps & Pick<Required<HtmlLinkProps>, "href">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "imageSizes">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "href"> & {
  1847. imageSizes?: never;
  1848. });
  1849. interface PageLinkDescriptor extends Omit<HtmlLinkDescriptor, "href" | "rel" | "type" | "sizes" | "imageSrcSet" | "imageSizes" | "as" | "color" | "title"> {
  1850. /**
  1851. * A [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
  1852. * attribute to render on the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
  1853. * element
  1854. */
  1855. nonce?: string | undefined;
  1856. /**
  1857. * The absolute path of the page to prefetch, e.g. `/absolute/path`.
  1858. */
  1859. page: string;
  1860. }
  1861. type LinkDescriptor = HtmlLinkDescriptor | PageLinkDescriptor;
  1862. type Serializable = undefined | null | boolean | string | symbol | number | Array<Serializable> | {
  1863. [key: PropertyKey]: Serializable;
  1864. } | bigint | Date | URL | RegExp | Error | Map<Serializable, Serializable> | Set<Serializable> | Promise<Serializable>;
  1865. type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
  1866. type IsAny<T> = 0 extends 1 & T ? true : false;
  1867. type Func = (...args: any[]) => unknown;
  1868. /**
  1869. * A brand that can be applied to a type to indicate that it will serialize
  1870. * to a specific type when transported to the client from a loader.
  1871. * Only use this if you have additional serialization/deserialization logic
  1872. * in your application.
  1873. */
  1874. type unstable_SerializesTo<T> = {
  1875. unstable__ReactRouter_SerializesTo: [T];
  1876. };
  1877. type Serialize<T> = T extends unstable_SerializesTo<infer To> ? To : T extends Serializable ? T : T extends (...args: any[]) => unknown ? undefined : T extends Promise<infer U> ? Promise<Serialize<U>> : T extends Map<infer K, infer V> ? Map<Serialize<K>, Serialize<V>> : T extends ReadonlyMap<infer K, infer V> ? ReadonlyMap<Serialize<K>, Serialize<V>> : T extends Set<infer U> ? Set<Serialize<U>> : T extends ReadonlySet<infer U> ? ReadonlySet<Serialize<U>> : T extends [] ? [] : T extends readonly [infer F, ...infer R] ? [Serialize<F>, ...Serialize<R>] : T extends Array<infer U> ? Array<Serialize<U>> : T extends readonly unknown[] ? readonly Serialize<T[number]>[] : T extends Record<any, any> ? {
  1878. [K in keyof T]: Serialize<T[K]>;
  1879. } : undefined;
  1880. type VoidToUndefined<T> = Equal<T, void> extends true ? undefined : T;
  1881. type DataFrom<T> = IsAny<T> extends true ? undefined : T extends Func ? VoidToUndefined<Awaited<ReturnType<T>>> : undefined;
  1882. type ClientData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? U : T;
  1883. type ServerData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? Serialize<U> : Serialize<T>;
  1884. type ServerDataFrom<T> = ServerData<DataFrom<T>>;
  1885. type ClientDataFrom<T> = ClientData<DataFrom<T>>;
  1886. type ClientDataFunctionArgs<Params> = {
  1887. /**
  1888. * A {@link https://developer.mozilla.org/en-US/docs/Web/API/Request Fetch Request instance} which you can use to read the URL, the method, the "content-type" header, and the request body from the request.
  1889. *
  1890. * @note Because client data functions are called before a network request is made, the Request object does not include the headers which the browser automatically adds. React Router infers the "content-type" header from the enc-type of the form that performed the submission.
  1891. **/
  1892. request: Request;
  1893. /**
  1894. * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
  1895. * @example
  1896. * // app/routes.ts
  1897. * route("teams/:teamId", "./team.tsx"),
  1898. *
  1899. * // app/team.tsx
  1900. * export function clientLoader({
  1901. * params,
  1902. * }: Route.ClientLoaderArgs) {
  1903. * params.teamId;
  1904. * // ^ string
  1905. * }
  1906. **/
  1907. params: Params;
  1908. /**
  1909. * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
  1910. * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
  1911. */
  1912. unstable_pattern: string;
  1913. /**
  1914. * When `future.v8_middleware` is not enabled, this is undefined.
  1915. *
  1916. * When `future.v8_middleware` is enabled, this is an instance of
  1917. * `RouterContextProvider` and can be used to access context values
  1918. * from your route middlewares. You may pass in initial context values in your
  1919. * `<HydratedRouter getContext>` prop
  1920. */
  1921. context: Readonly<RouterContextProvider>;
  1922. };
  1923. type SerializeFrom<T> = T extends (...args: infer Args) => unknown ? Args extends [
  1924. ClientLoaderFunctionArgs | ClientActionFunctionArgs | ClientDataFunctionArgs<unknown>
  1925. ] ? ClientDataFrom<T> : ServerDataFrom<T> : T;
  1926. /**
  1927. * A function that handles data mutations for a route on the client
  1928. */
  1929. type ClientActionFunction = (args: ClientActionFunctionArgs) => ReturnType<ActionFunction>;
  1930. /**
  1931. * Arguments passed to a route `clientAction` function
  1932. */
  1933. type ClientActionFunctionArgs = ActionFunctionArgs & {
  1934. serverAction: <T = unknown>() => Promise<SerializeFrom<T>>;
  1935. };
  1936. /**
  1937. * A function that loads data for a route on the client
  1938. */
  1939. type ClientLoaderFunction = ((args: ClientLoaderFunctionArgs) => ReturnType<LoaderFunction>) & {
  1940. hydrate?: boolean;
  1941. };
  1942. /**
  1943. * Arguments passed to a route `clientLoader` function
  1944. */
  1945. type ClientLoaderFunctionArgs = LoaderFunctionArgs & {
  1946. serverLoader: <T = unknown>() => Promise<SerializeFrom<T>>;
  1947. };
  1948. type HeadersArgs = {
  1949. loaderHeaders: Headers;
  1950. parentHeaders: Headers;
  1951. actionHeaders: Headers;
  1952. errorHeaders: Headers | undefined;
  1953. };
  1954. /**
  1955. * A function that returns HTTP headers to be used for a route. These headers
  1956. * will be merged with (and take precedence over) headers from parent routes.
  1957. */
  1958. interface HeadersFunction {
  1959. (args: HeadersArgs): Headers | HeadersInit;
  1960. }
  1961. /**
  1962. * A function that defines `<link>` tags to be inserted into the `<head>` of
  1963. * the document on route transitions.
  1964. *
  1965. * @see https://reactrouter.com/start/framework/route-module#meta
  1966. */
  1967. interface LinksFunction {
  1968. (): LinkDescriptor[];
  1969. }
  1970. interface MetaMatch<RouteId extends string = string, Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown> {
  1971. id: RouteId;
  1972. pathname: DataRouteMatch["pathname"];
  1973. /** @deprecated Use `MetaMatch.loaderData` instead */
  1974. data: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
  1975. loaderData: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
  1976. handle?: RouteHandle;
  1977. params: DataRouteMatch["params"];
  1978. meta: MetaDescriptor[];
  1979. error?: unknown;
  1980. }
  1981. type MetaMatches<MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> = Array<{
  1982. [K in keyof MatchLoaders]: MetaMatch<Exclude<K, number | symbol>, MatchLoaders[K]>;
  1983. }[keyof MatchLoaders]>;
  1984. interface MetaArgs<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
  1985. /** @deprecated Use `MetaArgs.loaderData` instead */
  1986. data: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
  1987. loaderData: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
  1988. params: Params;
  1989. location: Location;
  1990. matches: MetaMatches<MatchLoaders>;
  1991. error?: unknown;
  1992. }
  1993. /**
  1994. * A function that returns an array of data objects to use for rendering
  1995. * metadata HTML tags in a route. These tags are not rendered on descendant
  1996. * routes in the route hierarchy. In other words, they will only be rendered on
  1997. * the route in which they are exported.
  1998. *
  1999. * @param Loader - The type of the current route's loader function
  2000. * @param MatchLoaders - Mapping from a parent route's filepath to its loader
  2001. * function type
  2002. *
  2003. * Note that parent route filepaths are relative to the `app/` directory.
  2004. *
  2005. * For example, if this meta function is for `/sales/customers/$customerId`:
  2006. *
  2007. * ```ts
  2008. * // app/root.tsx
  2009. * const loader = () => ({ hello: "world" })
  2010. * export type Loader = typeof loader
  2011. *
  2012. * // app/routes/sales.tsx
  2013. * const loader = () => ({ salesCount: 1074 })
  2014. * export type Loader = typeof loader
  2015. *
  2016. * // app/routes/sales/customers.tsx
  2017. * const loader = () => ({ customerCount: 74 })
  2018. * export type Loader = typeof loader
  2019. *
  2020. * // app/routes/sales/customers/$customersId.tsx
  2021. * import type { Loader as RootLoader } from "../../../root"
  2022. * import type { Loader as SalesLoader } from "../../sales"
  2023. * import type { Loader as CustomersLoader } from "../../sales/customers"
  2024. *
  2025. * const loader = () => ({ name: "Customer name" })
  2026. *
  2027. * const meta: MetaFunction<typeof loader, {
  2028. * "root": RootLoader,
  2029. * "routes/sales": SalesLoader,
  2030. * "routes/sales/customers": CustomersLoader,
  2031. * }> = ({ data, matches }) => {
  2032. * const { name } = data
  2033. * // ^? string
  2034. * const { customerCount } = matches.find((match) => match.id === "routes/sales/customers").data
  2035. * // ^? number
  2036. * const { salesCount } = matches.find((match) => match.id === "routes/sales").data
  2037. * // ^? number
  2038. * const { hello } = matches.find((match) => match.id === "root").data
  2039. * // ^? "world"
  2040. * }
  2041. * ```
  2042. */
  2043. interface MetaFunction<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
  2044. (args: MetaArgs<Loader, MatchLoaders>): MetaDescriptor[] | undefined;
  2045. }
  2046. type MetaDescriptor = {
  2047. charSet: "utf-8";
  2048. } | {
  2049. title: string;
  2050. } | {
  2051. name: string;
  2052. content: string;
  2053. } | {
  2054. property: string;
  2055. content: string;
  2056. } | {
  2057. httpEquiv: string;
  2058. content: string;
  2059. } | {
  2060. "script:ld+json": LdJsonObject;
  2061. } | {
  2062. tagName: "meta" | "link";
  2063. [name: string]: string;
  2064. } | {
  2065. [name: string]: unknown;
  2066. };
  2067. type LdJsonObject = {
  2068. [Key in string]: LdJsonValue;
  2069. } & {
  2070. [Key in string]?: LdJsonValue | undefined;
  2071. };
  2072. type LdJsonArray = LdJsonValue[] | readonly LdJsonValue[];
  2073. type LdJsonPrimitive = string | number | boolean | null;
  2074. type LdJsonValue = LdJsonPrimitive | LdJsonObject | LdJsonArray;
  2075. /**
  2076. * An arbitrary object that is associated with a route.
  2077. *
  2078. * @see https://reactrouter.com/how-to/using-handle
  2079. */
  2080. type RouteHandle = unknown;
  2081. declare const redirect: typeof redirect$1;
  2082. declare const redirectDocument: typeof redirectDocument$1;
  2083. declare const replace: typeof replace$1;
  2084. declare const Await: typeof Await$1;
  2085. type RSCRouteConfigEntryBase = {
  2086. action?: ActionFunction;
  2087. clientAction?: ClientActionFunction;
  2088. clientLoader?: ClientLoaderFunction;
  2089. ErrorBoundary?: React.ComponentType<any>;
  2090. handle?: any;
  2091. headers?: HeadersFunction;
  2092. HydrateFallback?: React.ComponentType<any>;
  2093. Layout?: React.ComponentType<any>;
  2094. links?: LinksFunction;
  2095. loader?: LoaderFunction;
  2096. meta?: MetaFunction;
  2097. shouldRevalidate?: ShouldRevalidateFunction;
  2098. };
  2099. type RSCRouteConfigEntry = RSCRouteConfigEntryBase & {
  2100. id: string;
  2101. path?: string;
  2102. Component?: React.ComponentType<any>;
  2103. lazy?: () => Promise<RSCRouteConfigEntryBase & ({
  2104. default?: React.ComponentType<any>;
  2105. Component?: never;
  2106. } | {
  2107. default?: never;
  2108. Component?: React.ComponentType<any>;
  2109. })>;
  2110. } & ({
  2111. index: true;
  2112. } | {
  2113. children?: RSCRouteConfigEntry[];
  2114. });
  2115. type RSCRouteConfig = Array<RSCRouteConfigEntry>;
  2116. type RSCRouteManifest = {
  2117. clientAction?: ClientActionFunction;
  2118. clientLoader?: ClientLoaderFunction;
  2119. element?: React.ReactElement | false;
  2120. errorElement?: React.ReactElement;
  2121. handle?: any;
  2122. hasAction: boolean;
  2123. hasComponent: boolean;
  2124. hasErrorBoundary: boolean;
  2125. hasLoader: boolean;
  2126. hydrateFallbackElement?: React.ReactElement;
  2127. id: string;
  2128. index?: boolean;
  2129. links?: LinksFunction;
  2130. meta?: MetaFunction;
  2131. parentId?: string;
  2132. path?: string;
  2133. shouldRevalidate?: ShouldRevalidateFunction;
  2134. };
  2135. type RSCRouteMatch = RSCRouteManifest & {
  2136. params: Params;
  2137. pathname: string;
  2138. pathnameBase: string;
  2139. };
  2140. type RSCRenderPayload = {
  2141. type: "render";
  2142. actionData: Record<string, any> | null;
  2143. basename: string | undefined;
  2144. errors: Record<string, any> | null;
  2145. loaderData: Record<string, any>;
  2146. location: Location;
  2147. matches: RSCRouteMatch[];
  2148. patches?: RSCRouteManifest[];
  2149. nonce?: string;
  2150. formState?: unknown;
  2151. };
  2152. type RSCManifestPayload = {
  2153. type: "manifest";
  2154. patches: RSCRouteManifest[];
  2155. };
  2156. type RSCActionPayload = {
  2157. type: "action";
  2158. actionResult: Promise<unknown>;
  2159. rerender?: Promise<RSCRenderPayload | RSCRedirectPayload>;
  2160. };
  2161. type RSCRedirectPayload = {
  2162. type: "redirect";
  2163. status: number;
  2164. location: string;
  2165. replace: boolean;
  2166. reload: boolean;
  2167. actionResult?: Promise<unknown>;
  2168. };
  2169. type RSCPayload = RSCRenderPayload | RSCManifestPayload | RSCActionPayload | RSCRedirectPayload;
  2170. type RSCMatch = {
  2171. statusCode: number;
  2172. headers: Headers;
  2173. payload: RSCPayload;
  2174. };
  2175. type DecodeActionFunction = (formData: FormData) => Promise<() => Promise<unknown>>;
  2176. type DecodeFormStateFunction = (result: unknown, formData: FormData) => unknown;
  2177. type DecodeReplyFunction = (reply: FormData | string, { temporaryReferences }: {
  2178. temporaryReferences: unknown;
  2179. }) => Promise<unknown[]>;
  2180. type LoadServerActionFunction = (id: string) => Promise<Function>;
  2181. /**
  2182. * Matches the given routes to a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
  2183. * and returns an [RSC](https://react.dev/reference/rsc/server-components)
  2184. * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
  2185. * encoding an {@link unstable_RSCPayload} for consumption by an [RSC](https://react.dev/reference/rsc/server-components)
  2186. * enabled client router.
  2187. *
  2188. * @example
  2189. * import {
  2190. * createTemporaryReferenceSet,
  2191. * decodeAction,
  2192. * decodeReply,
  2193. * loadServerAction,
  2194. * renderToReadableStream,
  2195. * } from "@vitejs/plugin-rsc/rsc";
  2196. * import { unstable_matchRSCServerRequest as matchRSCServerRequest } from "react-router";
  2197. *
  2198. * matchRSCServerRequest({
  2199. * createTemporaryReferenceSet,
  2200. * decodeAction,
  2201. * decodeFormState,
  2202. * decodeReply,
  2203. * loadServerAction,
  2204. * request,
  2205. * routes: routes(),
  2206. * generateResponse(match) {
  2207. * return new Response(
  2208. * renderToReadableStream(match.payload),
  2209. * {
  2210. * status: match.statusCode,
  2211. * headers: match.headers,
  2212. * }
  2213. * );
  2214. * },
  2215. * });
  2216. *
  2217. * @name unstable_matchRSCServerRequest
  2218. * @public
  2219. * @category RSC
  2220. * @mode data
  2221. * @param opts Options
  2222. * @param opts.basename The basename to use when matching the request.
  2223. * @param opts.createTemporaryReferenceSet A function that returns a temporary
  2224. * reference set for the request, used to track temporary references in the [RSC](https://react.dev/reference/rsc/server-components)
  2225. * stream.
  2226. * @param opts.decodeAction Your `react-server-dom-xyz/server`'s `decodeAction`
  2227. * function, responsible for loading a server action.
  2228. * @param opts.decodeFormState A function responsible for decoding form state for
  2229. * progressively enhanceable forms with React's [`useActionState`](https://react.dev/reference/react/useActionState)
  2230. * using your `react-server-dom-xyz/server`'s `decodeFormState`.
  2231. * @param opts.decodeReply Your `react-server-dom-xyz/server`'s `decodeReply`
  2232. * function, used to decode the server function's arguments and bind them to the
  2233. * implementation for invocation by the router.
  2234. * @param opts.generateResponse A function responsible for using your
  2235. * `renderToReadableStream` to generate a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
  2236. * encoding the {@link unstable_RSCPayload}.
  2237. * @param opts.loadServerAction Your `react-server-dom-xyz/server`'s
  2238. * `loadServerAction` function, used to load a server action by ID.
  2239. * @param opts.onError An optional error handler that will be called with any
  2240. * errors that occur during the request processing.
  2241. * @param opts.request The [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
  2242. * to match against.
  2243. * @param opts.requestContext An instance of {@link RouterContextProvider}
  2244. * that should be created per request, to be passed to [`action`](../../start/data/route-object#action)s,
  2245. * [`loader`](../../start/data/route-object#loader)s and [middleware](../../how-to/middleware).
  2246. * @param opts.routes Your {@link unstable_RSCRouteConfigEntry | route definitions}.
  2247. * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
  2248. * that contains the [RSC](https://react.dev/reference/rsc/server-components)
  2249. * data for hydration.
  2250. */
  2251. declare function matchRSCServerRequest({ createTemporaryReferenceSet, basename, decodeReply, requestContext, loadServerAction, decodeAction, decodeFormState, onError, request, routes, generateResponse, }: {
  2252. createTemporaryReferenceSet: () => unknown;
  2253. basename?: string;
  2254. decodeReply?: DecodeReplyFunction;
  2255. decodeAction?: DecodeActionFunction;
  2256. decodeFormState?: DecodeFormStateFunction;
  2257. requestContext?: RouterContextProvider;
  2258. loadServerAction?: LoadServerActionFunction;
  2259. onError?: (error: unknown) => void;
  2260. request: Request;
  2261. routes: RSCRouteConfigEntry[];
  2262. generateResponse: (match: RSCMatch, { temporaryReferences, }: {
  2263. temporaryReferences: unknown;
  2264. }) => Response;
  2265. }): Promise<Response>;
  2266. /**
  2267. * Apps can use this interface to "register" app-wide types for React Router via interface declaration merging and module augmentation.
  2268. * React Router should handle this for you via type generation.
  2269. *
  2270. * For more on declaration merging and module augmentation, see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation .
  2271. */
  2272. interface Register {
  2273. }
  2274. type AnyParams = Record<string, string | undefined>;
  2275. type AnyPages = Record<string, {
  2276. params: AnyParams;
  2277. }>;
  2278. type Pages = Register extends {
  2279. pages: infer Registered extends AnyPages;
  2280. } ? Registered : AnyPages;
  2281. type Args = {
  2282. [K in keyof Pages]: ToArgs<Pages[K]["params"]>;
  2283. };
  2284. type ToArgs<Params extends Record<string, string | undefined>> = Equal<Params, {}> extends true ? [] : Partial<Params> extends Params ? [Params] | [] : [
  2285. Params
  2286. ];
  2287. /**
  2288. Returns a resolved URL path for the specified route.
  2289. ```tsx
  2290. const h = href("/:lang?/about", { lang: "en" })
  2291. // -> `/en/about`
  2292. <Link to={href("/products/:id", { id: "abc123" })} />
  2293. ```
  2294. */
  2295. declare function href<Path extends keyof Args>(path: Path, ...args: Args[Path]): string;
  2296. interface CookieSignatureOptions {
  2297. /**
  2298. * An array of secrets that may be used to sign/unsign the value of a cookie.
  2299. *
  2300. * The array makes it easy to rotate secrets. New secrets should be added to
  2301. * the beginning of the array. `cookie.serialize()` will always use the first
  2302. * value in the array, but `cookie.parse()` may use any of them so that
  2303. * cookies that were signed with older secrets still work.
  2304. */
  2305. secrets?: string[];
  2306. }
  2307. type CookieOptions = ParseOptions & SerializeOptions & CookieSignatureOptions;
  2308. /**
  2309. * A HTTP cookie.
  2310. *
  2311. * A Cookie is a logical container for metadata about a HTTP cookie; its name
  2312. * and options. But it doesn't contain a value. Instead, it has `parse()` and
  2313. * `serialize()` methods that allow a single instance to be reused for
  2314. * parsing/encoding multiple different values.
  2315. *
  2316. * @see https://remix.run/utils/cookies#cookie-api
  2317. */
  2318. interface Cookie {
  2319. /**
  2320. * The name of the cookie, used in the `Cookie` and `Set-Cookie` headers.
  2321. */
  2322. readonly name: string;
  2323. /**
  2324. * True if this cookie uses one or more secrets for verification.
  2325. */
  2326. readonly isSigned: boolean;
  2327. /**
  2328. * The Date this cookie expires.
  2329. *
  2330. * Note: This is calculated at access time using `maxAge` when no `expires`
  2331. * option is provided to `createCookie()`.
  2332. */
  2333. readonly expires?: Date;
  2334. /**
  2335. * Parses a raw `Cookie` header and returns the value of this cookie or
  2336. * `null` if it's not present.
  2337. */
  2338. parse(cookieHeader: string | null, options?: ParseOptions): Promise<any>;
  2339. /**
  2340. * Serializes the given value to a string and returns the `Set-Cookie`
  2341. * header.
  2342. */
  2343. serialize(value: any, options?: SerializeOptions): Promise<string>;
  2344. }
  2345. /**
  2346. * Creates a logical container for managing a browser cookie from the server.
  2347. */
  2348. declare const createCookie: (name: string, cookieOptions?: CookieOptions) => Cookie;
  2349. type IsCookieFunction = (object: any) => object is Cookie;
  2350. /**
  2351. * Returns true if an object is a Remix cookie container.
  2352. *
  2353. * @see https://remix.run/utils/cookies#iscookie
  2354. */
  2355. declare const isCookie: IsCookieFunction;
  2356. /**
  2357. * An object of name/value pairs to be used in the session.
  2358. */
  2359. interface SessionData {
  2360. [name: string]: any;
  2361. }
  2362. /**
  2363. * Session persists data across HTTP requests.
  2364. *
  2365. * @see https://reactrouter.com/explanation/sessions-and-cookies#sessions
  2366. */
  2367. interface Session<Data = SessionData, FlashData = Data> {
  2368. /**
  2369. * A unique identifier for this session.
  2370. *
  2371. * Note: This will be the empty string for newly created sessions and
  2372. * sessions that are not backed by a database (i.e. cookie-based sessions).
  2373. */
  2374. readonly id: string;
  2375. /**
  2376. * The raw data contained in this session.
  2377. *
  2378. * This is useful mostly for SessionStorage internally to access the raw
  2379. * session data to persist.
  2380. */
  2381. readonly data: FlashSessionData<Data, FlashData>;
  2382. /**
  2383. * Returns `true` if the session has a value for the given `name`, `false`
  2384. * otherwise.
  2385. */
  2386. has(name: (keyof Data | keyof FlashData) & string): boolean;
  2387. /**
  2388. * Returns the value for the given `name` in this session.
  2389. */
  2390. get<Key extends (keyof Data | keyof FlashData) & string>(name: Key): (Key extends keyof Data ? Data[Key] : undefined) | (Key extends keyof FlashData ? FlashData[Key] : undefined) | undefined;
  2391. /**
  2392. * Sets a value in the session for the given `name`.
  2393. */
  2394. set<Key extends keyof Data & string>(name: Key, value: Data[Key]): void;
  2395. /**
  2396. * Sets a value in the session that is only valid until the next `get()`.
  2397. * This can be useful for temporary values, like error messages.
  2398. */
  2399. flash<Key extends keyof FlashData & string>(name: Key, value: FlashData[Key]): void;
  2400. /**
  2401. * Removes a value from the session.
  2402. */
  2403. unset(name: keyof Data & string): void;
  2404. }
  2405. type FlashSessionData<Data, FlashData> = Partial<Data & {
  2406. [Key in keyof FlashData as FlashDataKey<Key & string>]: FlashData[Key];
  2407. }>;
  2408. type FlashDataKey<Key extends string> = `__flash_${Key}__`;
  2409. type CreateSessionFunction = <Data = SessionData, FlashData = Data>(initialData?: Data, id?: string) => Session<Data, FlashData>;
  2410. /**
  2411. * Creates a new Session object.
  2412. *
  2413. * Note: This function is typically not invoked directly by application code.
  2414. * Instead, use a `SessionStorage` object's `getSession` method.
  2415. */
  2416. declare const createSession: CreateSessionFunction;
  2417. type IsSessionFunction = (object: any) => object is Session;
  2418. /**
  2419. * Returns true if an object is a React Router session.
  2420. *
  2421. * @see https://reactrouter.com/api/utils/isSession
  2422. */
  2423. declare const isSession: IsSessionFunction;
  2424. /**
  2425. * SessionStorage stores session data between HTTP requests and knows how to
  2426. * parse and create cookies.
  2427. *
  2428. * A SessionStorage creates Session objects using a `Cookie` header as input.
  2429. * Then, later it generates the `Set-Cookie` header to be used in the response.
  2430. */
  2431. interface SessionStorage<Data = SessionData, FlashData = Data> {
  2432. /**
  2433. * Parses a Cookie header from a HTTP request and returns the associated
  2434. * Session. If there is no session associated with the cookie, this will
  2435. * return a new Session with no data.
  2436. */
  2437. getSession: (cookieHeader?: string | null, options?: ParseOptions) => Promise<Session<Data, FlashData>>;
  2438. /**
  2439. * Stores all data in the Session and returns the Set-Cookie header to be
  2440. * used in the HTTP response.
  2441. */
  2442. commitSession: (session: Session<Data, FlashData>, options?: SerializeOptions) => Promise<string>;
  2443. /**
  2444. * Deletes all data associated with the Session and returns the Set-Cookie
  2445. * header to be used in the HTTP response.
  2446. */
  2447. destroySession: (session: Session<Data, FlashData>, options?: SerializeOptions) => Promise<string>;
  2448. }
  2449. /**
  2450. * SessionIdStorageStrategy is designed to allow anyone to easily build their
  2451. * own SessionStorage using `createSessionStorage(strategy)`.
  2452. *
  2453. * This strategy describes a common scenario where the session id is stored in
  2454. * a cookie but the actual session data is stored elsewhere, usually in a
  2455. * database or on disk. A set of create, read, update, and delete operations
  2456. * are provided for managing the session data.
  2457. */
  2458. interface SessionIdStorageStrategy<Data = SessionData, FlashData = Data> {
  2459. /**
  2460. * The Cookie used to store the session id, or options used to automatically
  2461. * create one.
  2462. */
  2463. cookie?: Cookie | (CookieOptions & {
  2464. name?: string;
  2465. });
  2466. /**
  2467. * Creates a new record with the given data and returns the session id.
  2468. */
  2469. createData: (data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<string>;
  2470. /**
  2471. * Returns data for a given session id, or `null` if there isn't any.
  2472. */
  2473. readData: (id: string) => Promise<FlashSessionData<Data, FlashData> | null>;
  2474. /**
  2475. * Updates data for the given session id.
  2476. */
  2477. updateData: (id: string, data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<void>;
  2478. /**
  2479. * Deletes data for a given session id from the data store.
  2480. */
  2481. deleteData: (id: string) => Promise<void>;
  2482. }
  2483. /**
  2484. * Creates a SessionStorage object using a SessionIdStorageStrategy.
  2485. *
  2486. * Note: This is a low-level API that should only be used if none of the
  2487. * existing session storage options meet your requirements.
  2488. */
  2489. declare function createSessionStorage<Data = SessionData, FlashData = Data>({ cookie: cookieArg, createData, readData, updateData, deleteData, }: SessionIdStorageStrategy<Data, FlashData>): SessionStorage<Data, FlashData>;
  2490. interface CookieSessionStorageOptions {
  2491. /**
  2492. * The Cookie used to store the session data on the client, or options used
  2493. * to automatically create one.
  2494. */
  2495. cookie?: SessionIdStorageStrategy["cookie"];
  2496. }
  2497. /**
  2498. * Creates and returns a SessionStorage object that stores all session data
  2499. * directly in the session cookie itself.
  2500. *
  2501. * This has the advantage that no database or other backend services are
  2502. * needed, and can help to simplify some load-balanced scenarios. However, it
  2503. * also has the limitation that serialized session data may not exceed the
  2504. * browser's maximum cookie size. Trade-offs!
  2505. */
  2506. declare function createCookieSessionStorage<Data = SessionData, FlashData = Data>({ cookie: cookieArg }?: CookieSessionStorageOptions): SessionStorage<Data, FlashData>;
  2507. interface MemorySessionStorageOptions {
  2508. /**
  2509. * The Cookie used to store the session id on the client, or options used
  2510. * to automatically create one.
  2511. */
  2512. cookie?: SessionIdStorageStrategy["cookie"];
  2513. }
  2514. /**
  2515. * Creates and returns a simple in-memory SessionStorage object, mostly useful
  2516. * for testing and as a reference implementation.
  2517. *
  2518. * Note: This storage does not scale beyond a single process, so it is not
  2519. * suitable for most production scenarios.
  2520. */
  2521. declare function createMemorySessionStorage<Data = SessionData, FlashData = Data>({ cookie }?: MemorySessionStorageOptions): SessionStorage<Data, FlashData>;
  2522. export { Await, type Cookie, type CookieOptions, type CookieSignatureOptions, type FlashSessionData, type IsCookieFunction, type IsSessionFunction, type MiddlewareFunction, type MiddlewareNextFunction, type RouterContext, RouterContextProvider, type Session, type SessionData, type SessionIdStorageStrategy, type SessionStorage, createContext, createCookie, createCookieSessionStorage, createMemorySessionStorage, createSession, createSessionStorage, createStaticHandler, data, href, isCookie, isRouteErrorResponse, isSession, matchRoutes, redirect, redirectDocument, replace, type DecodeActionFunction as unstable_DecodeActionFunction, type DecodeFormStateFunction as unstable_DecodeFormStateFunction, type DecodeReplyFunction as unstable_DecodeReplyFunction, type LoadServerActionFunction as unstable_LoadServerActionFunction, type RSCManifestPayload as unstable_RSCManifestPayload, type RSCMatch as unstable_RSCMatch, type RSCPayload as unstable_RSCPayload, type RSCRenderPayload as unstable_RSCRenderPayload, type RSCRouteConfig as unstable_RSCRouteConfig, type RSCRouteConfigEntry as unstable_RSCRouteConfigEntry, type RSCRouteManifest as unstable_RSCRouteManifest, type RSCRouteMatch as unstable_RSCRouteMatch, matchRSCServerRequest as unstable_matchRSCServerRequest };