@remix-run/router 0.0.0-experimental-bcda00aaf → 0.0.0-experimental-1116190f7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/router.ts CHANGED
@@ -829,6 +829,7 @@ export function createRouter(init: RouterInit): Router {
829
829
  let initialScrollRestored = init.hydrationData != null;
830
830
 
831
831
  let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);
832
+ let initialMatchesIsFOW = false;
832
833
  let initialErrors: RouteData | null = null;
833
834
 
834
835
  if (initialMatches == null && !patchRoutesOnNavigationImpl) {
@@ -874,6 +875,7 @@ export function createRouter(init: RouterInit): Router {
874
875
  init.history.location.pathname
875
876
  );
876
877
  if (fogOfWar.active && fogOfWar.matches) {
878
+ initialMatchesIsFOW = true;
877
879
  initialMatches = fogOfWar.matches;
878
880
  }
879
881
  }
@@ -890,33 +892,18 @@ export function createRouter(init: RouterInit): Router {
890
892
  // were marked for explicit hydration
891
893
  let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;
892
894
  let errors = init.hydrationData ? init.hydrationData.errors : null;
893
- let isRouteInitialized = (m: AgnosticDataRouteMatch) => {
894
- // No loader, nothing to initialize
895
- if (!m.route.loader) {
896
- return true;
897
- }
898
- // Explicitly opting-in to running on hydration
899
- if (
900
- typeof m.route.loader === "function" &&
901
- m.route.loader.hydrate === true
902
- ) {
903
- return false;
904
- }
905
- // Otherwise, initialized if hydrated with data or an error
906
- return (
907
- (loaderData && loaderData[m.route.id] !== undefined) ||
908
- (errors && errors[m.route.id] !== undefined)
909
- );
910
- };
911
-
912
895
  // If errors exist, don't consider routes below the boundary
913
896
  if (errors) {
914
897
  let idx = initialMatches.findIndex(
915
898
  (m) => errors![m.route.id] !== undefined
916
899
  );
917
- initialized = initialMatches.slice(0, idx + 1).every(isRouteInitialized);
900
+ initialized = initialMatches
901
+ .slice(0, idx + 1)
902
+ .every((m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors));
918
903
  } else {
919
- initialized = initialMatches.every(isRouteInitialized);
904
+ initialized = initialMatches.every(
905
+ (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors)
906
+ );
920
907
  }
921
908
  } else {
922
909
  // Without partial hydration - we're initialized if we were provided any
@@ -1526,8 +1513,12 @@ export function createRouter(init: RouterInit): Router {
1526
1513
  let routesToUse = inFlightDataRoutes || dataRoutes;
1527
1514
  let loadingNavigation = opts && opts.overrideNavigation;
1528
1515
  let matches =
1529
- isUninterruptedRevalidation && inFlightDataRoutes == null
1530
- ? state.matches
1516
+ opts?.initialHydration &&
1517
+ state.matches &&
1518
+ state.matches.length > 0 &&
1519
+ !initialMatchesIsFOW
1520
+ ? // `matchRoutes()` has already been called if we're in here via `router.initialize()`
1521
+ state.matches
1531
1522
  : matchRoutes(routesToUse, location, basename);
1532
1523
  let flushSync = (opts && opts.flushSync) === true;
1533
1524
 
@@ -1558,7 +1549,7 @@ export function createRouter(init: RouterInit): Router {
1558
1549
  // Short circuit if it's only a hash change and not a revalidation or
1559
1550
  // mutation submission.
1560
1551
  //
1561
- // Ignore on initial page loads because since the initial load will always
1552
+ // Ignore on initial page loads because since the initial hydration will always
1562
1553
  // be "same hash". For example, on /page#hash and submit a <Form method="post">
1563
1554
  // which will default to a navigation to /page
1564
1555
  if (
@@ -1708,17 +1699,15 @@ export function createRouter(init: RouterInit): Router {
1708
1699
  if (discoverResult.type === "aborted") {
1709
1700
  return { shortCircuited: true };
1710
1701
  } else if (discoverResult.type === "error") {
1711
- let { boundaryId, error } = handleDiscoverRouteError(
1712
- location.pathname,
1713
- discoverResult
1714
- );
1702
+ let boundaryId = findNearestBoundary(discoverResult.partialMatches)
1703
+ .route.id;
1715
1704
  return {
1716
1705
  matches: discoverResult.partialMatches,
1717
1706
  pendingActionResult: [
1718
1707
  boundaryId,
1719
1708
  {
1720
1709
  type: ResultType.error,
1721
- error,
1710
+ error: discoverResult.error,
1722
1711
  },
1723
1712
  ],
1724
1713
  };
@@ -1886,15 +1875,13 @@ export function createRouter(init: RouterInit): Router {
1886
1875
  if (discoverResult.type === "aborted") {
1887
1876
  return { shortCircuited: true };
1888
1877
  } else if (discoverResult.type === "error") {
1889
- let { boundaryId, error } = handleDiscoverRouteError(
1890
- location.pathname,
1891
- discoverResult
1892
- );
1878
+ let boundaryId = findNearestBoundary(discoverResult.partialMatches)
1879
+ .route.id;
1893
1880
  return {
1894
1881
  matches: discoverResult.partialMatches,
1895
1882
  loaderData: {},
1896
1883
  errors: {
1897
- [boundaryId]: error,
1884
+ [boundaryId]: discoverResult.error,
1898
1885
  },
1899
1886
  };
1900
1887
  } else if (!discoverResult.matches) {
@@ -1982,9 +1969,7 @@ export function createRouter(init: RouterInit): Router {
1982
1969
  }
1983
1970
 
1984
1971
  revalidatingFetchers.forEach((rf) => {
1985
- if (fetchControllers.has(rf.key)) {
1986
- abortFetcher(rf.key);
1987
- }
1972
+ abortFetcher(rf.key);
1988
1973
  if (rf.controller) {
1989
1974
  // Fetchers use an independent AbortController so that aborting a fetcher
1990
1975
  // (via deleteFetcher) does not abort the triggering navigation that
@@ -2025,6 +2010,7 @@ export function createRouter(init: RouterInit): Router {
2025
2010
  abortPendingFetchRevalidations
2026
2011
  );
2027
2012
  }
2013
+
2028
2014
  revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));
2029
2015
 
2030
2016
  // If any loaders returned a redirect Response, start a new REPLACE navigation
@@ -2052,7 +2038,6 @@ export function createRouter(init: RouterInit): Router {
2052
2038
  let { loaderData, errors } = processLoaderData(
2053
2039
  state,
2054
2040
  matches,
2055
- matchesToLoad,
2056
2041
  loaderResults,
2057
2042
  pendingActionResult,
2058
2043
  revalidatingFetchers,
@@ -2072,13 +2057,9 @@ export function createRouter(init: RouterInit): Router {
2072
2057
  });
2073
2058
  });
2074
2059
 
2075
- // During partial hydration, preserve SSR errors for routes that don't re-run
2060
+ // Preserve SSR errors during partial hydration
2076
2061
  if (future.v7_partialHydration && initialHydration && state.errors) {
2077
- Object.entries(state.errors)
2078
- .filter(([id]) => !matchesToLoad.some((m) => m.route.id === id))
2079
- .forEach(([routeId, error]) => {
2080
- errors = Object.assign(errors || {}, { [routeId]: error });
2081
- });
2062
+ errors = { ...state.errors, ...errors };
2082
2063
  }
2083
2064
 
2084
2065
  let updatedFetchers = markFetchRedirectsDone();
@@ -2142,7 +2123,8 @@ export function createRouter(init: RouterInit): Router {
2142
2123
  );
2143
2124
  }
2144
2125
 
2145
- if (fetchControllers.has(key)) abortFetcher(key);
2126
+ abortFetcher(key);
2127
+
2146
2128
  let flushSync = (opts && opts.flushSync) === true;
2147
2129
 
2148
2130
  let routesToUse = inFlightDataRoutes || dataRoutes;
@@ -2187,7 +2169,7 @@ export function createRouter(init: RouterInit): Router {
2187
2169
 
2188
2170
  let match = getTargetMatch(matches, path);
2189
2171
 
2190
- pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
2172
+ let preventScrollReset = (opts && opts.preventScrollReset) === true;
2191
2173
 
2192
2174
  if (submission && isMutationMethod(submission.formMethod)) {
2193
2175
  handleFetcherAction(
@@ -2198,6 +2180,7 @@ export function createRouter(init: RouterInit): Router {
2198
2180
  matches,
2199
2181
  fogOfWar.active,
2200
2182
  flushSync,
2183
+ preventScrollReset,
2201
2184
  submission
2202
2185
  );
2203
2186
  return;
@@ -2214,6 +2197,7 @@ export function createRouter(init: RouterInit): Router {
2214
2197
  matches,
2215
2198
  fogOfWar.active,
2216
2199
  flushSync,
2200
+ preventScrollReset,
2217
2201
  submission
2218
2202
  );
2219
2203
  }
@@ -2228,6 +2212,7 @@ export function createRouter(init: RouterInit): Router {
2228
2212
  requestMatches: AgnosticDataRouteMatch[],
2229
2213
  isFogOfWar: boolean,
2230
2214
  flushSync: boolean,
2215
+ preventScrollReset: boolean,
2231
2216
  submission: Submission
2232
2217
  ) {
2233
2218
  interruptActiveLoads();
@@ -2274,8 +2259,7 @@ export function createRouter(init: RouterInit): Router {
2274
2259
  if (discoverResult.type === "aborted") {
2275
2260
  return;
2276
2261
  } else if (discoverResult.type === "error") {
2277
- let { error } = handleDiscoverRouteError(path, discoverResult);
2278
- setFetcherError(key, routeId, error, { flushSync });
2262
+ setFetcherError(key, routeId, discoverResult.error, { flushSync });
2279
2263
  return;
2280
2264
  } else if (!discoverResult.matches) {
2281
2265
  setFetcherError(
@@ -2342,6 +2326,7 @@ export function createRouter(init: RouterInit): Router {
2342
2326
  updateFetcherState(key, getLoadingFetcher(submission));
2343
2327
  return startRedirectNavigation(fetchRequest, actionResult, false, {
2344
2328
  fetcherSubmission: submission,
2329
+ preventScrollReset,
2345
2330
  });
2346
2331
  }
2347
2332
  }
@@ -2411,9 +2396,7 @@ export function createRouter(init: RouterInit): Router {
2411
2396
  existingFetcher ? existingFetcher.data : undefined
2412
2397
  );
2413
2398
  state.fetchers.set(staleKey, revalidatingFetcher);
2414
- if (fetchControllers.has(staleKey)) {
2415
- abortFetcher(staleKey);
2416
- }
2399
+ abortFetcher(staleKey);
2417
2400
  if (rf.controller) {
2418
2401
  fetchControllers.set(staleKey, rf.controller);
2419
2402
  }
@@ -2456,7 +2439,8 @@ export function createRouter(init: RouterInit): Router {
2456
2439
  return startRedirectNavigation(
2457
2440
  revalidationRequest,
2458
2441
  redirect.result,
2459
- false
2442
+ false,
2443
+ { preventScrollReset }
2460
2444
  );
2461
2445
  }
2462
2446
 
@@ -2469,7 +2453,8 @@ export function createRouter(init: RouterInit): Router {
2469
2453
  return startRedirectNavigation(
2470
2454
  revalidationRequest,
2471
2455
  redirect.result,
2472
- false
2456
+ false,
2457
+ { preventScrollReset }
2473
2458
  );
2474
2459
  }
2475
2460
 
@@ -2477,7 +2462,6 @@ export function createRouter(init: RouterInit): Router {
2477
2462
  let { loaderData, errors } = processLoaderData(
2478
2463
  state,
2479
2464
  matches,
2480
- matchesToLoad,
2481
2465
  loaderResults,
2482
2466
  undefined,
2483
2467
  revalidatingFetchers,
@@ -2537,6 +2521,7 @@ export function createRouter(init: RouterInit): Router {
2537
2521
  matches: AgnosticDataRouteMatch[],
2538
2522
  isFogOfWar: boolean,
2539
2523
  flushSync: boolean,
2524
+ preventScrollReset: boolean,
2540
2525
  submission?: Submission
2541
2526
  ) {
2542
2527
  let existingFetcher = state.fetchers.get(key);
@@ -2566,8 +2551,7 @@ export function createRouter(init: RouterInit): Router {
2566
2551
  if (discoverResult.type === "aborted") {
2567
2552
  return;
2568
2553
  } else if (discoverResult.type === "error") {
2569
- let { error } = handleDiscoverRouteError(path, discoverResult);
2570
- setFetcherError(key, routeId, error, { flushSync });
2554
+ setFetcherError(key, routeId, discoverResult.error, { flushSync });
2571
2555
  return;
2572
2556
  } else if (!discoverResult.matches) {
2573
2557
  setFetcherError(
@@ -2633,7 +2617,9 @@ export function createRouter(init: RouterInit): Router {
2633
2617
  return;
2634
2618
  } else {
2635
2619
  fetchRedirectIds.add(key);
2636
- await startRedirectNavigation(fetchRequest, result, false);
2620
+ await startRedirectNavigation(fetchRequest, result, false, {
2621
+ preventScrollReset,
2622
+ });
2637
2623
  return;
2638
2624
  }
2639
2625
  }
@@ -2676,10 +2662,12 @@ export function createRouter(init: RouterInit): Router {
2676
2662
  {
2677
2663
  submission,
2678
2664
  fetcherSubmission,
2665
+ preventScrollReset,
2679
2666
  replace,
2680
2667
  }: {
2681
2668
  submission?: Submission;
2682
2669
  fetcherSubmission?: Submission;
2670
+ preventScrollReset?: boolean;
2683
2671
  replace?: boolean;
2684
2672
  } = {}
2685
2673
  ) {
@@ -2760,7 +2748,7 @@ export function createRouter(init: RouterInit): Router {
2760
2748
  formAction: location,
2761
2749
  },
2762
2750
  // Preserve these flags across redirects
2763
- preventScrollReset: pendingPreventScrollReset,
2751
+ preventScrollReset: preventScrollReset || pendingPreventScrollReset,
2764
2752
  enableViewTransition: isNavigation
2765
2753
  ? pendingViewTransitionEnabled
2766
2754
  : undefined,
@@ -2777,7 +2765,7 @@ export function createRouter(init: RouterInit): Router {
2777
2765
  // Send fetcher submissions through for shouldRevalidate
2778
2766
  fetcherSubmission,
2779
2767
  // Preserve these flags across redirects
2780
- preventScrollReset: pendingPreventScrollReset,
2768
+ preventScrollReset: preventScrollReset || pendingPreventScrollReset,
2781
2769
  enableViewTransition: isNavigation
2782
2770
  ? pendingViewTransitionEnabled
2783
2771
  : undefined,
@@ -2926,8 +2914,8 @@ export function createRouter(init: RouterInit): Router {
2926
2914
  fetchLoadMatches.forEach((_, key) => {
2927
2915
  if (fetchControllers.has(key)) {
2928
2916
  cancelledFetcherLoads.add(key);
2929
- abortFetcher(key);
2930
2917
  }
2918
+ abortFetcher(key);
2931
2919
  });
2932
2920
  }
2933
2921
 
@@ -3010,9 +2998,10 @@ export function createRouter(init: RouterInit): Router {
3010
2998
 
3011
2999
  function abortFetcher(key: string) {
3012
3000
  let controller = fetchControllers.get(key);
3013
- invariant(controller, `Expected fetch controller: ${key}`);
3014
- controller.abort();
3015
- fetchControllers.delete(key);
3001
+ if (controller) {
3002
+ controller.abort();
3003
+ fetchControllers.delete(key);
3004
+ }
3016
3005
  }
3017
3006
 
3018
3007
  function markFetchersDone(keys: string[]) {
@@ -3138,23 +3127,6 @@ export function createRouter(init: RouterInit): Router {
3138
3127
  return { notFoundMatches: matches, route, error };
3139
3128
  }
3140
3129
 
3141
- function handleDiscoverRouteError(
3142
- pathname: string,
3143
- discoverResult: DiscoverRoutesErrorResult
3144
- ) {
3145
- return {
3146
- boundaryId: findNearestBoundary(discoverResult.partialMatches).route.id,
3147
- error: getInternalRouterError(400, {
3148
- type: "route-discovery",
3149
- pathname,
3150
- message:
3151
- discoverResult.error != null && "message" in discoverResult.error
3152
- ? discoverResult.error
3153
- : String(discoverResult.error),
3154
- }),
3155
- };
3156
- }
3157
-
3158
3130
  function cancelActiveDeferreds(
3159
3131
  predicate?: (routeId: string) => boolean
3160
3132
  ): string[] {
@@ -3290,21 +3262,30 @@ export function createRouter(init: RouterInit): Router {
3290
3262
  pathname: string,
3291
3263
  signal: AbortSignal
3292
3264
  ): Promise<DiscoverRoutesResult> {
3265
+ if (!patchRoutesOnNavigationImpl) {
3266
+ return { type: "success", matches };
3267
+ }
3268
+
3293
3269
  let partialMatches: AgnosticDataRouteMatch[] | null = matches;
3294
3270
  while (true) {
3295
3271
  let isNonHMR = inFlightDataRoutes == null;
3296
3272
  let routesToUse = inFlightDataRoutes || dataRoutes;
3273
+ let localManifest = manifest;
3297
3274
  try {
3298
- await loadLazyRouteChildren(
3299
- patchRoutesOnNavigationImpl!,
3300
- pathname,
3301
- partialMatches,
3302
- routesToUse,
3303
- manifest,
3304
- mapRouteProperties,
3305
- pendingPatchRoutes,
3306
- signal
3307
- );
3275
+ await patchRoutesOnNavigationImpl({
3276
+ path: pathname,
3277
+ matches: partialMatches,
3278
+ patch: (routeId, children) => {
3279
+ if (signal.aborted) return;
3280
+ patchRoutesImpl(
3281
+ routeId,
3282
+ children,
3283
+ routesToUse,
3284
+ localManifest,
3285
+ mapRouteProperties
3286
+ );
3287
+ },
3288
+ });
3308
3289
  } catch (e) {
3309
3290
  return { type: "error", error: e, partialMatches };
3310
3291
  } finally {
@@ -3314,7 +3295,7 @@ export function createRouter(init: RouterInit): Router {
3314
3295
  // trigger a re-run of memoized `router.routes` dependencies.
3315
3296
  // HMR will already update the identity and reflow when it lands
3316
3297
  // `inFlightDataRoutes` in `completeNavigation`
3317
- if (isNonHMR) {
3298
+ if (isNonHMR && !signal.aborted) {
3318
3299
  dataRoutes = [...dataRoutes];
3319
3300
  }
3320
3301
  }
@@ -4161,16 +4142,23 @@ function normalizeTo(
4161
4142
  path.hash = location.hash;
4162
4143
  }
4163
4144
 
4164
- // Add an ?index param for matched index routes if we don't already have one
4165
- if (
4166
- (to == null || to === "" || to === ".") &&
4167
- activeRouteMatch &&
4168
- activeRouteMatch.route.index &&
4169
- !hasNakedIndexQuery(path.search)
4170
- ) {
4171
- path.search = path.search
4172
- ? path.search.replace(/^\?/, "?index&")
4173
- : "?index";
4145
+ // Account for `?index` params when routing to the current location
4146
+ if ((to == null || to === "" || to === ".") && activeRouteMatch) {
4147
+ let nakedIndex = hasNakedIndexQuery(path.search);
4148
+ if (activeRouteMatch.route.index && !nakedIndex) {
4149
+ // Add one when we're targeting an index route
4150
+ path.search = path.search
4151
+ ? path.search.replace(/^\?/, "?index&")
4152
+ : "?index";
4153
+ } else if (!activeRouteMatch.route.index && nakedIndex) {
4154
+ // Remove existing ones when we're not
4155
+ let params = new URLSearchParams(path.search);
4156
+ let indexValues = params.getAll("index");
4157
+ params.delete("index");
4158
+ indexValues.filter((v) => v).forEach((v) => params.append("index", v));
4159
+ let qs = params.toString();
4160
+ path.search = qs ? `?${qs}` : "";
4161
+ }
4174
4162
  }
4175
4163
 
4176
4164
  // If we're operating within a basename, prepend it to the pathname. If
@@ -4334,20 +4322,18 @@ function normalizeNavigateOptions(
4334
4322
  return { path: createPath(parsedPath), submission };
4335
4323
  }
4336
4324
 
4337
- // Filter out all routes below any caught error as they aren't going to
4325
+ // Filter out all routes at/below any caught error as they aren't going to
4338
4326
  // render so we don't need to load them
4339
4327
  function getLoaderMatchesUntilBoundary(
4340
4328
  matches: AgnosticDataRouteMatch[],
4341
- boundaryId: string
4329
+ boundaryId: string,
4330
+ includeBoundary = false
4342
4331
  ) {
4343
- let boundaryMatches = matches;
4344
- if (boundaryId) {
4345
- let index = matches.findIndex((m) => m.route.id === boundaryId);
4346
- if (index >= 0) {
4347
- boundaryMatches = matches.slice(0, index);
4348
- }
4332
+ let index = matches.findIndex((m) => m.route.id === boundaryId);
4333
+ if (index >= 0) {
4334
+ return matches.slice(0, includeBoundary ? index + 1 : index);
4349
4335
  }
4350
- return boundaryMatches;
4336
+ return matches;
4351
4337
  }
4352
4338
 
4353
4339
  function getMatchesToLoad(
@@ -4356,7 +4342,7 @@ function getMatchesToLoad(
4356
4342
  matches: AgnosticDataRouteMatch[],
4357
4343
  submission: Submission | undefined,
4358
4344
  location: Location,
4359
- isInitialLoad: boolean,
4345
+ initialHydration: boolean,
4360
4346
  skipActionErrorRevalidation: boolean,
4361
4347
  isRevalidationRequired: boolean,
4362
4348
  cancelledDeferredRoutes: string[],
@@ -4377,13 +4363,26 @@ function getMatchesToLoad(
4377
4363
  let nextUrl = history.createURL(location);
4378
4364
 
4379
4365
  // Pick navigation matches that are net-new or qualify for revalidation
4380
- let boundaryId =
4381
- pendingActionResult && isErrorResult(pendingActionResult[1])
4382
- ? pendingActionResult[0]
4383
- : undefined;
4384
- let boundaryMatches = boundaryId
4385
- ? getLoaderMatchesUntilBoundary(matches, boundaryId)
4386
- : matches;
4366
+ let boundaryMatches = matches;
4367
+ if (initialHydration && state.errors) {
4368
+ // On initial hydration, only consider matches up to _and including_ the boundary.
4369
+ // This is inclusive to handle cases where a server loader ran successfully,
4370
+ // a child server loader bubbled up to this route, but this route has
4371
+ // `clientLoader.hydrate` so we want to still run the `clientLoader` so that
4372
+ // we have a complete version of `loaderData`
4373
+ boundaryMatches = getLoaderMatchesUntilBoundary(
4374
+ matches,
4375
+ Object.keys(state.errors)[0],
4376
+ true
4377
+ );
4378
+ } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {
4379
+ // If an action threw an error, we call loaders up to, but not including the
4380
+ // boundary
4381
+ boundaryMatches = getLoaderMatchesUntilBoundary(
4382
+ matches,
4383
+ pendingActionResult[0]
4384
+ );
4385
+ }
4387
4386
 
4388
4387
  // Don't revalidate loaders by default after action 4xx/5xx responses
4389
4388
  // when the flag is enabled. They can still opt-into revalidation via
@@ -4405,15 +4404,8 @@ function getMatchesToLoad(
4405
4404
  return false;
4406
4405
  }
4407
4406
 
4408
- if (isInitialLoad) {
4409
- if (typeof route.loader !== "function" || route.loader.hydrate) {
4410
- return true;
4411
- }
4412
- return (
4413
- state.loaderData[route.id] === undefined &&
4414
- // Don't re-run if the loader ran and threw an error
4415
- (!state.errors || state.errors[route.id] === undefined)
4416
- );
4407
+ if (initialHydration) {
4408
+ return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);
4417
4409
  }
4418
4410
 
4419
4411
  // Always call the loader on new route instances and pending defer cancellations
@@ -4455,12 +4447,12 @@ function getMatchesToLoad(
4455
4447
  let revalidatingFetchers: RevalidatingFetcher[] = [];
4456
4448
  fetchLoadMatches.forEach((f, key) => {
4457
4449
  // Don't revalidate:
4458
- // - on initial load (shouldn't be any fetchers then anyway)
4450
+ // - on initial hydration (shouldn't be any fetchers then anyway)
4459
4451
  // - if fetcher won't be present in the subsequent render
4460
4452
  // - no longer matches the URL (v7_fetcherPersist=false)
4461
4453
  // - was unmounted but persisted due to v7_fetcherPersist=true
4462
4454
  if (
4463
- isInitialLoad ||
4455
+ initialHydration ||
4464
4456
  !matches.some((m) => m.route.id === f.routeId) ||
4465
4457
  deletedFetchers.has(key)
4466
4458
  ) {
@@ -4540,6 +4532,38 @@ function getMatchesToLoad(
4540
4532
  return [navigationMatches, revalidatingFetchers];
4541
4533
  }
4542
4534
 
4535
+ function shouldLoadRouteOnHydration(
4536
+ route: AgnosticDataRouteObject,
4537
+ loaderData: RouteData | null | undefined,
4538
+ errors: RouteData | null | undefined
4539
+ ) {
4540
+ // We dunno if we have a loader - gotta find out!
4541
+ if (route.lazy) {
4542
+ return true;
4543
+ }
4544
+
4545
+ // No loader, nothing to initialize
4546
+ if (!route.loader) {
4547
+ return false;
4548
+ }
4549
+
4550
+ let hasData = loaderData != null && loaderData[route.id] !== undefined;
4551
+ let hasError = errors != null && errors[route.id] !== undefined;
4552
+
4553
+ // Don't run if we error'd during SSR
4554
+ if (!hasData && hasError) {
4555
+ return false;
4556
+ }
4557
+
4558
+ // Explicitly opting-in to running on hydration
4559
+ if (typeof route.loader === "function" && route.loader.hydrate === true) {
4560
+ return true;
4561
+ }
4562
+
4563
+ // Otherwise, run if we're not yet initialized with anything
4564
+ return !hasData && !hasError;
4565
+ }
4566
+
4543
4567
  function isNewLoader(
4544
4568
  currentLoaderData: RouteData,
4545
4569
  currentMatch: AgnosticDataRouteMatch,
@@ -4589,53 +4613,6 @@ function shouldRevalidateLoader(
4589
4613
  return arg.defaultShouldRevalidate;
4590
4614
  }
4591
4615
 
4592
- /**
4593
- * Idempotent utility to execute patchRoutesOnNavigation() to lazily load route
4594
- * definitions and update the routes/routeManifest
4595
- */
4596
- async function loadLazyRouteChildren(
4597
- patchRoutesOnNavigationImpl: AgnosticPatchRoutesOnNavigationFunction,
4598
- path: string,
4599
- matches: AgnosticDataRouteMatch[],
4600
- routes: AgnosticDataRouteObject[],
4601
- manifest: RouteManifest,
4602
- mapRouteProperties: MapRoutePropertiesFunction,
4603
- pendingRouteChildren: Map<
4604
- string,
4605
- ReturnType<typeof patchRoutesOnNavigationImpl>
4606
- >,
4607
- signal: AbortSignal
4608
- ) {
4609
- let key = [path, ...matches.map((m) => m.route.id)].join("-");
4610
- try {
4611
- let pending = pendingRouteChildren.get(key);
4612
- if (!pending) {
4613
- pending = patchRoutesOnNavigationImpl({
4614
- path,
4615
- matches,
4616
- patch: (routeId, children) => {
4617
- if (!signal.aborted) {
4618
- patchRoutesImpl(
4619
- routeId,
4620
- children,
4621
- routes,
4622
- manifest,
4623
- mapRouteProperties
4624
- );
4625
- }
4626
- },
4627
- });
4628
- pendingRouteChildren.set(key, pending);
4629
- }
4630
-
4631
- if (pending && isPromise<AgnosticRouteObject[]>(pending)) {
4632
- await pending;
4633
- }
4634
- } finally {
4635
- pendingRouteChildren.delete(key);
4636
- }
4637
- }
4638
-
4639
4616
  function patchRoutesImpl(
4640
4617
  routeId: string | null,
4641
4618
  children: AgnosticRouteObject[],
@@ -4662,12 +4639,9 @@ function patchRoutesImpl(
4662
4639
  // to simplify user-land code. This is useful because we re-call the
4663
4640
  // `patchRoutesOnNavigation` function for matched routes with params.
4664
4641
  let uniqueChildren = children.filter(
4665
- (a) =>
4666
- !childrenToPatch.some(
4667
- (b) =>
4668
- a.index === b.index &&
4669
- a.path === b.path &&
4670
- a.caseSensitive === b.caseSensitive
4642
+ (newRoute) =>
4643
+ !childrenToPatch.some((existingRoute) =>
4644
+ isSameRoute(newRoute, existingRoute)
4671
4645
  )
4672
4646
  );
4673
4647
 
@@ -4681,6 +4655,46 @@ function patchRoutesImpl(
4681
4655
  childrenToPatch.push(...newRoutes);
4682
4656
  }
4683
4657
 
4658
+ function isSameRoute(
4659
+ newRoute: AgnosticRouteObject,
4660
+ existingRoute: AgnosticRouteObject
4661
+ ): boolean {
4662
+ // Most optimal check is by id
4663
+ if (
4664
+ "id" in newRoute &&
4665
+ "id" in existingRoute &&
4666
+ newRoute.id === existingRoute.id
4667
+ ) {
4668
+ return true;
4669
+ }
4670
+
4671
+ // Second is by pathing differences
4672
+ if (
4673
+ !(
4674
+ newRoute.index === existingRoute.index &&
4675
+ newRoute.path === existingRoute.path &&
4676
+ newRoute.caseSensitive === existingRoute.caseSensitive
4677
+ )
4678
+ ) {
4679
+ return false;
4680
+ }
4681
+
4682
+ // Pathless layout routes are trickier since we need to check children.
4683
+ // If they have no children then they're the same as far as we can tell
4684
+ if (
4685
+ (!newRoute.children || newRoute.children.length === 0) &&
4686
+ (!existingRoute.children || existingRoute.children.length === 0)
4687
+ ) {
4688
+ return true;
4689
+ }
4690
+
4691
+ // Otherwise, we look to see if every child in the new route is already
4692
+ // represented in the existing route's children
4693
+ return newRoute.children!.every((aChild, i) =>
4694
+ existingRoute.children?.some((bChild) => isSameRoute(aChild, bChild))
4695
+ );
4696
+ }
4697
+
4684
4698
  /**
4685
4699
  * Execute route.lazy() methods to lazily load route modules (loader, action,
4686
4700
  * shouldRevalidate) and update the routeManifest in place which shares objects
@@ -5302,7 +5316,6 @@ function processRouteLoaderData(
5302
5316
  function processLoaderData(
5303
5317
  state: RouterState,
5304
5318
  matches: AgnosticDataRouteMatch[],
5305
- matchesToLoad: AgnosticDataRouteMatch[],
5306
5319
  results: Record<string, DataResult>,
5307
5320
  pendingActionResult: PendingActionResult | undefined,
5308
5321
  revalidatingFetchers: RevalidatingFetcher[],
@@ -5458,7 +5471,7 @@ function getInternalRouterError(
5458
5471
  pathname?: string;
5459
5472
  routeId?: string;
5460
5473
  method?: string;
5461
- type?: "defer-action" | "invalid-body" | "route-discovery";
5474
+ type?: "defer-action" | "invalid-body";
5462
5475
  message?: string;
5463
5476
  } = {}
5464
5477
  ) {
@@ -5467,11 +5480,7 @@ function getInternalRouterError(
5467
5480
 
5468
5481
  if (status === 400) {
5469
5482
  statusText = "Bad Request";
5470
- if (type === "route-discovery") {
5471
- errorMessage =
5472
- `Unable to match URL "${pathname}" - the \`patchRoutesOnNavigation()\` ` +
5473
- `function threw the following error:\n${message}`;
5474
- } else if (method && pathname && routeId) {
5483
+ if (method && pathname && routeId) {
5475
5484
  errorMessage =
5476
5485
  `You made a ${method} request to "${pathname}" but ` +
5477
5486
  `did not provide a \`loader\` for route "${routeId}", ` +