@remix-run/router 0.0.0-experimental-e960cf1a → 0.0.0-experimental-bc2c864b

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
@@ -11,7 +11,7 @@ import type {
11
11
  ActionFunction,
12
12
  AgnosticDataRouteMatch,
13
13
  AgnosticDataRouteObject,
14
- AgnosticDataStrategyMatch,
14
+ DataStrategyMatch,
15
15
  AgnosticRouteObject,
16
16
  DataResult,
17
17
  DataStrategyFunction,
@@ -23,8 +23,8 @@ import type {
23
23
  FormEncType,
24
24
  FormMethod,
25
25
  HTMLFormMethod,
26
+ HandlerResult,
26
27
  ImmutableRouteKey,
27
- LazyRoutePromise,
28
28
  LoaderFunction,
29
29
  MapRoutePropertiesFunction,
30
30
  MutationFormMethod,
@@ -665,16 +665,6 @@ interface RevalidatingFetcher extends FetchLoadMatch {
665
665
  controller: AbortController | null;
666
666
  }
667
667
 
668
- /**
669
- * Wrapper object to allow us to throw any response out from callLoaderOrAction
670
- * for queryRouter while preserving whether or not it was thrown or returned
671
- * from the loader/action
672
- */
673
- interface QueryRouteResponse {
674
- type: ResultType.data | ResultType.error;
675
- response: Response;
676
- }
677
-
678
668
  const validMutationMethodsArr: MutationFormMethod[] = [
679
669
  "post",
680
670
  "put",
@@ -757,9 +747,6 @@ export function createRouter(init: RouterInit): Router {
757
747
  "You must provide a non-empty routes array to createRouter"
758
748
  );
759
749
 
760
- const dataStrategy = init.unstable_dataStrategy || defaultDataStrategy;
761
- const callLoaderOrAction = createCallLoaderOrAction(dataStrategy);
762
-
763
750
  let mapRouteProperties: MapRoutePropertiesFunction;
764
751
  if (init.mapRouteProperties) {
765
752
  mapRouteProperties = init.mapRouteProperties;
@@ -784,6 +771,7 @@ export function createRouter(init: RouterInit): Router {
784
771
  );
785
772
  let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;
786
773
  let basename = init.basename || "/";
774
+ let dataStrategyImpl = init.unstable_dataStrategy || defaultDataStrategy;
787
775
  // Config driven behavior flags
788
776
  let future: FutureConfig = {
789
777
  v7_fetcherPersist: false,
@@ -825,19 +813,34 @@ export function createRouter(init: RouterInit): Router {
825
813
  initialErrors = { [route.id]: error };
826
814
  }
827
815
 
828
- // "Initialized" here really means "Can `RouterProvider` render my route tree?"
829
- // Prior to `route.HydrateFallback`, we only had a root `fallbackElement` so we used
830
- // `state.initialized` to render that instead of `<DataRoutes>`. Now that we
831
- // support route level fallbacks we can always render and we'll just render
832
- // as deep as we have data for and detect the nearest ancestor HydrateFallback
833
- let initialized =
834
- future.v7_partialHydration ||
816
+ let initialized: boolean;
817
+ let hasLazyRoutes = initialMatches.some((m) => m.route.lazy);
818
+ let hasLoaders = initialMatches.some((m) => m.route.loader);
819
+ if (hasLazyRoutes) {
835
820
  // All initialMatches need to be loaded before we're ready. If we have lazy
836
821
  // functions around still then we'll need to run them in initialize()
837
- (!initialMatches.some((m) => m.route.lazy) &&
838
- // And we have to either have no loaders or have been provided hydrationData
839
- (!initialMatches.some((m) => m.route.loader) ||
840
- init.hydrationData != null));
822
+ initialized = false;
823
+ } else if (!hasLoaders) {
824
+ // If we've got no loaders to run, then we're good to go
825
+ initialized = true;
826
+ } else if (future.v7_partialHydration) {
827
+ // If partial hydration is enabled, we're initialized so long as we were
828
+ // provided with hydrationData for every route with a loader, and no loaders
829
+ // were marked for explicit hydration
830
+ let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;
831
+ let errors = init.hydrationData ? init.hydrationData.errors : null;
832
+ initialized = initialMatches.every(
833
+ (m) =>
834
+ m.route.loader &&
835
+ m.route.loader.hydrate !== true &&
836
+ ((loaderData && loaderData[m.route.id] !== undefined) ||
837
+ (errors && errors[m.route.id] !== undefined))
838
+ );
839
+ } else {
840
+ // Without partial hydration - we're initialized if we were provided any
841
+ // hydrationData - which is expected to be complete
842
+ initialized = init.hydrationData != null;
843
+ }
841
844
 
842
845
  let router: Router;
843
846
  let state: RouterState = {
@@ -1018,11 +1021,7 @@ export function createRouter(init: RouterInit): Router {
1018
1021
  // in the normal navigation flow. For SSR it's expected that lazy modules are
1019
1022
  // resolved prior to router creation since we can't go into a fallbackElement
1020
1023
  // UI for SSR'd apps
1021
- if (
1022
- !state.initialized ||
1023
- (future.v7_partialHydration &&
1024
- state.matches.some((m) => isUnhydratedRoute(state, m.route)))
1025
- ) {
1024
+ if (!state.initialized) {
1026
1025
  startNavigation(HistoryAction.Pop, state.location, {
1027
1026
  initialHydration: true,
1028
1027
  });
@@ -1575,16 +1574,13 @@ export function createRouter(init: RouterInit): Router {
1575
1574
  }),
1576
1575
  };
1577
1576
  } else {
1578
- result = await callLoaderOrAction(
1577
+ let results = await callDataStrategy(
1579
1578
  "action",
1580
1579
  request,
1581
- actionMatch,
1582
- matches,
1583
- manifest,
1584
- mapRouteProperties,
1585
- basename,
1586
- future.v7_relativeSplatPath
1580
+ [actionMatch],
1581
+ matches
1587
1582
  );
1583
+ result = results[0];
1588
1584
 
1589
1585
  if (request.signal.aborted) {
1590
1586
  return { shortCircuited: true };
@@ -1600,9 +1596,13 @@ export function createRouter(init: RouterInit): Router {
1600
1596
  // we redirected to the exact same location we're currently at to avoid
1601
1597
  // double back-buttons
1602
1598
  replace =
1603
- result.location === state.location.pathname + state.location.search;
1599
+ result.response.headers.get("Location") ===
1600
+ state.location.pathname + state.location.search;
1604
1601
  }
1605
- await startRedirectNavigation(state, result, { submission, replace });
1602
+ await startRedirectNavigation(request, result, {
1603
+ submission,
1604
+ replace,
1605
+ });
1606
1606
  return { shortCircuited: true };
1607
1607
  }
1608
1608
 
@@ -1770,7 +1770,7 @@ export function createRouter(init: RouterInit): Router {
1770
1770
  }
1771
1771
 
1772
1772
  let { loaderResults, fetcherResults } =
1773
- await loadDataAndMaybeResolveDeferred(
1773
+ await callLoadersAndMaybeResolveData(
1774
1774
  state.matches,
1775
1775
  matches,
1776
1776
  matchesToLoad,
@@ -1804,7 +1804,9 @@ export function createRouter(init: RouterInit): Router {
1804
1804
  revalidatingFetchers[redirect.idx - matchesToLoad.length].key;
1805
1805
  fetchRedirectIds.add(fetcherKey);
1806
1806
  }
1807
- await startRedirectNavigation(state, redirect.result, { replace });
1807
+ await startRedirectNavigation(request, redirect.result, {
1808
+ replace,
1809
+ });
1808
1810
  return { shortCircuited: true };
1809
1811
  }
1810
1812
 
@@ -1969,16 +1971,13 @@ export function createRouter(init: RouterInit): Router {
1969
1971
  fetchControllers.set(key, abortController);
1970
1972
 
1971
1973
  let originatingLoadId = incrementingLoadId;
1972
- let actionResult = await callLoaderOrAction(
1974
+ let actionResults = await callDataStrategy(
1973
1975
  "action",
1974
1976
  fetchRequest,
1975
- match,
1976
- requestMatches,
1977
- manifest,
1978
- mapRouteProperties,
1979
- basename,
1980
- future.v7_relativeSplatPath
1977
+ [match],
1978
+ requestMatches
1981
1979
  );
1980
+ let actionResult = actionResults[0];
1982
1981
 
1983
1982
  if (fetchRequest.signal.aborted) {
1984
1983
  // We can delete this so long as we weren't aborted by our own fetcher
@@ -2011,7 +2010,7 @@ export function createRouter(init: RouterInit): Router {
2011
2010
  } else {
2012
2011
  fetchRedirectIds.add(key);
2013
2012
  updateFetcherState(key, getLoadingFetcher(submission));
2014
- return startRedirectNavigation(state, actionResult, {
2013
+ return startRedirectNavigation(fetchRequest, actionResult, {
2015
2014
  fetcherSubmission: submission,
2016
2015
  });
2017
2016
  }
@@ -2101,7 +2100,7 @@ export function createRouter(init: RouterInit): Router {
2101
2100
  );
2102
2101
 
2103
2102
  let { loaderResults, fetcherResults } =
2104
- await loadDataAndMaybeResolveDeferred(
2103
+ await callLoadersAndMaybeResolveData(
2105
2104
  state.matches,
2106
2105
  matches,
2107
2106
  matchesToLoad,
@@ -2132,7 +2131,7 @@ export function createRouter(init: RouterInit): Router {
2132
2131
  revalidatingFetchers[redirect.idx - matchesToLoad.length].key;
2133
2132
  fetchRedirectIds.add(fetcherKey);
2134
2133
  }
2135
- return startRedirectNavigation(state, redirect.result);
2134
+ return startRedirectNavigation(revalidationRequest, redirect.result);
2136
2135
  }
2137
2136
 
2138
2137
  // Process and commit output from loaders
@@ -2220,16 +2219,13 @@ export function createRouter(init: RouterInit): Router {
2220
2219
  fetchControllers.set(key, abortController);
2221
2220
 
2222
2221
  let originatingLoadId = incrementingLoadId;
2223
- let result: DataResult = await callLoaderOrAction(
2222
+ let results = await callDataStrategy(
2224
2223
  "loader",
2225
2224
  fetchRequest,
2226
- match,
2227
- matches,
2228
- manifest,
2229
- mapRouteProperties,
2230
- basename,
2231
- future.v7_relativeSplatPath
2225
+ [match],
2226
+ matches
2232
2227
  );
2228
+ let result = results[0];
2233
2229
 
2234
2230
  // Deferred isn't supported for fetcher loads, await everything and treat it
2235
2231
  // as a normal load. resolveDeferredData will return undefined if this
@@ -2267,7 +2263,7 @@ export function createRouter(init: RouterInit): Router {
2267
2263
  return;
2268
2264
  } else {
2269
2265
  fetchRedirectIds.add(key);
2270
- await startRedirectNavigation(state, result);
2266
+ await startRedirectNavigation(fetchRequest, result);
2271
2267
  return;
2272
2268
  }
2273
2269
  }
@@ -2304,7 +2300,7 @@ export function createRouter(init: RouterInit): Router {
2304
2300
  * the history action from the original navigation (PUSH or REPLACE).
2305
2301
  */
2306
2302
  async function startRedirectNavigation(
2307
- state: RouterState,
2303
+ request: Request,
2308
2304
  redirect: RedirectResult,
2309
2305
  {
2310
2306
  submission,
@@ -2316,26 +2312,40 @@ export function createRouter(init: RouterInit): Router {
2316
2312
  replace?: boolean;
2317
2313
  } = {}
2318
2314
  ) {
2319
- if (redirect.revalidate) {
2315
+ if (redirect.response.headers.has("X-Remix-Revalidate")) {
2320
2316
  isRevalidationRequired = true;
2321
2317
  }
2322
2318
 
2323
- let redirectLocation = createLocation(state.location, redirect.location, {
2319
+ let location = redirect.response.headers.get("Location");
2320
+ invariant(location, "Expected a Location header on the redirect Response");
2321
+ let redirectLocation = createLocation(state.location, location, {
2324
2322
  _isRedirect: true,
2325
2323
  });
2326
- invariant(
2327
- redirectLocation,
2328
- "Expected a location on the redirect navigation"
2329
- );
2324
+
2325
+ if (ABSOLUTE_URL_REGEX.test(location)) {
2326
+ // Strip off the protocol+origin for same-origin + same-basename absolute redirects
2327
+ let normalizedLocation = location;
2328
+ let currentUrl = new URL(request.url);
2329
+ let url = normalizedLocation.startsWith("//")
2330
+ ? new URL(currentUrl.protocol + normalizedLocation)
2331
+ : new URL(normalizedLocation);
2332
+ let isSameBasename = stripBasename(url.pathname, basename) != null;
2333
+ if (url.origin === currentUrl.origin && isSameBasename) {
2334
+ normalizedLocation = url.pathname + url.search + url.hash;
2335
+ redirectLocation = createLocation(state.location, normalizedLocation, {
2336
+ _isRedirect: true,
2337
+ });
2338
+ }
2339
+ }
2330
2340
 
2331
2341
  if (isBrowser) {
2332
2342
  let isDocumentReload = false;
2333
2343
 
2334
- if (redirect.reloadDocument) {
2344
+ if (redirect.response.headers.has("X-Remix-Reload-Document")) {
2335
2345
  // Hard reload if the response contained X-Remix-Reload-Document
2336
2346
  isDocumentReload = true;
2337
- } else if (ABSOLUTE_URL_REGEX.test(redirect.location)) {
2338
- const url = init.history.createURL(redirect.location);
2347
+ } else if (ABSOLUTE_URL_REGEX.test(location)) {
2348
+ const url = init.history.createURL(location);
2339
2349
  isDocumentReload =
2340
2350
  // Hard reload if it's an absolute URL to a new origin
2341
2351
  url.origin !== routerWindow.location.origin ||
@@ -2345,9 +2355,9 @@ export function createRouter(init: RouterInit): Router {
2345
2355
 
2346
2356
  if (isDocumentReload) {
2347
2357
  if (replace) {
2348
- routerWindow.location.replace(redirect.location);
2358
+ routerWindow.location.replace(location);
2349
2359
  } else {
2350
- routerWindow.location.assign(redirect.location);
2360
+ routerWindow.location.assign(location);
2351
2361
  }
2352
2362
  return;
2353
2363
  }
@@ -2378,14 +2388,14 @@ export function createRouter(init: RouterInit): Router {
2378
2388
  // redirected location
2379
2389
  let activeSubmission = submission || fetcherSubmission;
2380
2390
  if (
2381
- redirectPreserveMethodStatusCodes.has(redirect.status) &&
2391
+ redirectPreserveMethodStatusCodes.has(redirect.response.status) &&
2382
2392
  activeSubmission &&
2383
2393
  isMutationMethod(activeSubmission.formMethod)
2384
2394
  ) {
2385
2395
  await startNavigation(redirectHistoryAction, redirectLocation, {
2386
2396
  submission: {
2387
2397
  ...activeSubmission,
2388
- formAction: redirect.location,
2398
+ formAction: location,
2389
2399
  },
2390
2400
  // Preserve this flag across redirects
2391
2401
  preventScrollReset: pendingPreventScrollReset,
@@ -2407,7 +2417,55 @@ export function createRouter(init: RouterInit): Router {
2407
2417
  }
2408
2418
  }
2409
2419
 
2410
- async function loadDataAndMaybeResolveDeferred(
2420
+ // Utility wrapper for calling dataStrategy client-side without having to
2421
+ // pass around the manifest, mapRouteProperties, etc.
2422
+ async function callDataStrategy(
2423
+ type: "loader" | "action",
2424
+ request: Request,
2425
+ matchesToLoad: AgnosticDataRouteMatch[],
2426
+ matches: AgnosticDataRouteMatch[]
2427
+ ): Promise<DataResult[]> {
2428
+ try {
2429
+ let results = await callDataStrategyImpl(
2430
+ dataStrategyImpl,
2431
+ type,
2432
+ request,
2433
+ matchesToLoad,
2434
+ matches,
2435
+ manifest,
2436
+ mapRouteProperties
2437
+ );
2438
+
2439
+ return await Promise.all(
2440
+ results.map((result, i) => {
2441
+ if (isRedirectHandlerResult(result)) {
2442
+ return {
2443
+ type: ResultType.redirect,
2444
+ response: normalizeRelativeRoutingRedirectResponse(
2445
+ result.result,
2446
+ request,
2447
+ matchesToLoad[i].route.id,
2448
+ matches,
2449
+ basename,
2450
+ future.v7_relativeSplatPath
2451
+ ),
2452
+ };
2453
+ }
2454
+
2455
+ return convertHandlerResultToDataResult(result);
2456
+ })
2457
+ );
2458
+ } catch (e) {
2459
+ // If the outer dataStrategy method throws, just return the error for all
2460
+ // matches - and it'll naturally bubble to the root
2461
+ return matchesToLoad.map(() => ({
2462
+ type: ResultType.error,
2463
+ error: e,
2464
+ }));
2465
+ }
2466
+ }
2467
+
2468
+ async function callLoadersAndMaybeResolveData(
2411
2469
  currentMatches: AgnosticDataRouteMatch[],
2412
2470
  matches: AgnosticDataRouteMatch[],
2413
2471
  matchesToLoad: AgnosticDataRouteMatch[],
@@ -2416,30 +2474,22 @@ export function createRouter(init: RouterInit): Router {
2416
2474
  ) {
2417
2475
  let [loaderResults, ...fetcherResults] = await Promise.all([
2418
2476
  matchesToLoad.length
2419
- ? dataStrategy({
2420
- matches: matchesToLoad.map((m) =>
2421
- finesseToAgnosticDataStrategyMatch(
2422
- m,
2423
- mapRouteProperties,
2424
- manifest
2425
- )
2426
- ),
2427
- request,
2428
- type: "loader",
2429
- defaultStrategy(match) {
2430
- return callLoaderOrActionImplementation(
2431
- "loader",
2432
- request,
2433
- match,
2434
- matches,
2435
- basename,
2436
- future.v7_relativeSplatPath
2437
- );
2438
- },
2439
- })
2477
+ ? callDataStrategy("loader", request, matchesToLoad, matches)
2440
2478
  : [],
2441
2479
  ...fetchersToLoad.map((f) => {
2442
- if (!f.matches || !f.match || !f.controller) {
2480
+ if (f.matches && f.match && f.controller) {
2481
+ let fetcherRequest = createClientSideRequest(
2482
+ init.history,
2483
+ f.path,
2484
+ f.controller.signal
2485
+ );
2486
+ return callDataStrategy(
2487
+ "loader",
2488
+ fetcherRequest,
2489
+ [f.match],
2490
+ f.matches
2491
+ ).then((r) => r[0]);
2492
+ } else {
2443
2493
  return Promise.resolve<DataResult>({
2444
2494
  type: ResultType.error,
2445
2495
  error: getInternalRouterError(404, {
@@ -2447,41 +2497,6 @@ export function createRouter(init: RouterInit): Router {
2447
2497
  }),
2448
2498
  });
2449
2499
  }
2450
-
2451
- return dataStrategy({
2452
- matches: [
2453
- finesseToAgnosticDataStrategyMatch(
2454
- f.match!,
2455
- mapRouteProperties,
2456
- manifest
2457
- ),
2458
- ],
2459
- request,
2460
- type: "loader",
2461
- defaultStrategy(match) {
2462
- invariant(
2463
- f.controller,
2464
- "Expected controller for fetcher in defaultStrategy"
2465
- );
2466
- invariant(
2467
- f.matches,
2468
- "Expected matches for fetcher in defaultStrategy"
2469
- );
2470
-
2471
- return callLoaderOrActionImplementation(
2472
- "loader",
2473
- createClientSideRequest(
2474
- init.history,
2475
- f.path,
2476
- f.controller.signal
2477
- ),
2478
- match,
2479
- f.matches,
2480
- basename,
2481
- future.v7_relativeSplatPath
2482
- );
2483
- },
2484
- }).then((r) => r[0]);
2485
2500
  }),
2486
2501
  ]);
2487
2502
 
@@ -2865,6 +2880,7 @@ export const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred");
2865
2880
  */
2866
2881
  export interface StaticHandlerFutureConfig {
2867
2882
  v7_relativeSplatPath: boolean;
2883
+ v7_throwAbortReason: boolean;
2868
2884
  }
2869
2885
 
2870
2886
  export interface CreateStaticHandlerOptions {
@@ -2873,7 +2889,7 @@ export interface CreateStaticHandlerOptions {
2873
2889
  * @deprecated Use `mapRouteProperties` instead
2874
2890
  */
2875
2891
  detectErrorBoundary?: DetectErrorBoundaryFunction;
2876
- dataStrategy?: DataStrategyFunction;
2892
+ unstable_dataStrategy?: DataStrategyFunction;
2877
2893
  mapRouteProperties?: MapRoutePropertiesFunction;
2878
2894
  future?: Partial<StaticHandlerFutureConfig>;
2879
2895
  }
@@ -2887,11 +2903,9 @@ export function createStaticHandler(
2887
2903
  "You must provide a non-empty routes array to createStaticHandler"
2888
2904
  );
2889
2905
 
2890
- const dataStrategy = opts?.dataStrategy || defaultDataStrategy;
2891
- const callLoaderOrAction = createCallLoaderOrAction(dataStrategy);
2892
-
2893
2906
  let manifest: RouteManifest = {};
2894
2907
  let basename = (opts ? opts.basename : null) || "/";
2908
+ let dataStrategyImpl = opts?.unstable_dataStrategy || defaultDataStrategy;
2895
2909
  let mapRouteProperties: MapRoutePropertiesFunction;
2896
2910
  if (opts?.mapRouteProperties) {
2897
2911
  mapRouteProperties = opts.mapRouteProperties;
@@ -2907,6 +2921,7 @@ export function createStaticHandler(
2907
2921
  // Config driven behavior flags
2908
2922
  let future: StaticHandlerFutureConfig = {
2909
2923
  v7_relativeSplatPath: false,
2924
+ v7_throwAbortReason: false,
2910
2925
  ...(opts ? opts.future : null),
2911
2926
  };
2912
2927
 
@@ -3122,14 +3137,14 @@ export function createStaticHandler(
3122
3137
  actionHeaders: {},
3123
3138
  };
3124
3139
  } catch (e) {
3125
- // If the user threw/returned a Response in callLoaderOrAction, we throw
3126
- // it to bail out and then return or throw here based on whether the user
3127
- // returned or threw
3128
- if (isQueryRouteResponse(e)) {
3140
+ // If the user threw/returned a Response in callLoaderOrAction for a
3141
+ // `queryRoute` call, we throw the `HandlerResult` to bail out early
3142
+ // and then return or throw the raw Response here accordingly
3143
+ if (isHandlerResult(e) && isResponse(e.result)) {
3129
3144
  if (e.type === ResultType.error) {
3130
- throw e.response;
3145
+ throw e.result;
3131
3146
  }
3132
- return e.response;
3147
+ return e.result;
3133
3148
  }
3134
3149
  // Redirects are always returned since they don't propagate to catch
3135
3150
  // boundaries
@@ -3163,23 +3178,18 @@ export function createStaticHandler(
3163
3178
  error,
3164
3179
  };
3165
3180
  } else {
3166
- result = await callLoaderOrAction(
3181
+ let results = await callDataStrategy(
3167
3182
  "action",
3168
3183
  request,
3169
- actionMatch,
3184
+ [actionMatch],
3170
3185
  matches,
3171
- manifest,
3172
- mapRouteProperties,
3173
- basename,
3174
- future.v7_relativeSplatPath,
3175
- { isStaticRequest: true, isRouteRequest, requestContext }
3186
+ isRouteRequest,
3187
+ requestContext
3176
3188
  );
3189
+ result = results[0];
3177
3190
 
3178
3191
  if (request.signal.aborted) {
3179
- let method = isRouteRequest ? "queryRoute" : "query";
3180
- throw new Error(
3181
- `${method}() call aborted: ${request.method} ${request.url}`
3182
- );
3192
+ throwStaticHandlerAbortedError(request, isRouteRequest, future);
3183
3193
  }
3184
3194
  }
3185
3195
 
@@ -3189,9 +3199,9 @@ export function createStaticHandler(
3189
3199
  // can get back on the "throw all redirect responses" train here should
3190
3200
  // this ever happen :/
3191
3201
  throw new Response(null, {
3192
- status: result.status,
3202
+ status: result.response.status,
3193
3203
  headers: {
3194
- Location: result.location,
3204
+ Location: result.response.headers.get("Location")!,
3195
3205
  },
3196
3206
  });
3197
3207
  }
@@ -3250,7 +3260,9 @@ export function createStaticHandler(
3250
3260
  : 500,
3251
3261
  actionData: null,
3252
3262
  actionHeaders: {
3253
- ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),
3263
+ ...(result.response
3264
+ ? { [actionMatch.route.id]: result.response.headers }
3265
+ : {}),
3254
3266
  },
3255
3267
  };
3256
3268
  }
@@ -3265,14 +3277,20 @@ export function createStaticHandler(
3265
3277
 
3266
3278
  return {
3267
3279
  ...context,
3268
- // action status codes take precedence over loader status codes
3269
- ...(result.statusCode ? { statusCode: result.statusCode } : {}),
3270
3280
  actionData: {
3271
3281
  [actionMatch.route.id]: result.data,
3272
3282
  },
3273
- actionHeaders: {
3274
- ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),
3275
- },
3283
+ // action status codes take precedence over loader status codes
3284
+ ...(result.response
3285
+ ? {
3286
+ statusCode: result.response.status,
3287
+ actionHeaders: {
3288
+ [actionMatch.route.id]: result.response.headers,
3289
+ },
3290
+ }
3291
+ : {
3292
+ actionHeaders: {},
3293
+ }),
3276
3294
  };
3277
3295
  }
3278
3296
 
@@ -3330,30 +3348,17 @@ export function createStaticHandler(
3330
3348
  };
3331
3349
  }
3332
3350
 
3333
- let results = await dataStrategy({
3334
- matches: matchesToLoad.map((m) =>
3335
- finesseToAgnosticDataStrategyMatch(m, mapRouteProperties, manifest)
3336
- ),
3351
+ let results = await callDataStrategy(
3352
+ "loader",
3337
3353
  request,
3338
- type: "loader",
3339
- defaultStrategy(match) {
3340
- return callLoaderOrActionImplementation(
3341
- "loader",
3342
- request,
3343
- match,
3344
- matches,
3345
- basename,
3346
- future.v7_relativeSplatPath,
3347
- { isStaticRequest: true, isRouteRequest, requestContext }
3348
- );
3349
- },
3350
- });
3354
+ matchesToLoad,
3355
+ matches,
3356
+ isRouteRequest,
3357
+ requestContext
3358
+ );
3351
3359
 
3352
3360
  if (request.signal.aborted) {
3353
- let method = isRouteRequest ? "queryRoute" : "query";
3354
- throw new Error(
3355
- `${method}() call aborted: ${request.method} ${request.url}`
3356
- );
3361
+ throwStaticHandlerAbortedError(request, isRouteRequest, future);
3357
3362
  }
3358
3363
 
3359
3364
  // Process and commit output from loaders
@@ -3386,6 +3391,52 @@ export function createStaticHandler(
3386
3391
  };
3387
3392
  }
3388
3393
 
3394
+ // Utility wrapper for calling dataStrategy server-side without having to
3395
+ // pass around the manifest, mapRouteProperties, etc.
3396
+ async function callDataStrategy(
3397
+ type: "loader" | "action",
3398
+ request: Request,
3399
+ matchesToLoad: AgnosticDataRouteMatch[],
3400
+ matches: AgnosticDataRouteMatch[],
3401
+ isRouteRequest: boolean,
3402
+ requestContext: unknown
3403
+ ): Promise<DataResult[]> {
3404
+ let results = await callDataStrategyImpl(
3405
+ dataStrategyImpl,
3406
+ type,
3407
+ request,
3408
+ matchesToLoad,
3409
+ matches,
3410
+ manifest,
3411
+ mapRouteProperties,
3412
+ requestContext
3413
+ );
3414
+
3415
+ return await Promise.all(
3416
+ results.map((result, i) => {
3417
+ if (isRedirectHandlerResult(result)) {
3418
+ // Throw redirects and let the server handle them with an HTTP redirect
3419
+ throw normalizeRelativeRoutingRedirectResponse(
3420
+ result.result,
3421
+ request,
3422
+ matchesToLoad[i].route.id,
3423
+ matches,
3424
+ basename,
3425
+ future.v7_relativeSplatPath
3426
+ );
3427
+ }
3428
+ if (isResponse(result.result) && isRouteRequest) {
3429
+ // For SSR single-route requests, we want to hand Responses back directly
3430
+ // without unwrapping. We do this with the QueryRouteResponse wrapper
3431
+ // interface so we can know whether it was returned or thrown
3432
+ throw result;
3433
+ }
3434
+
3435
+ return convertHandlerResultToDataResult(result);
3436
+ })
3437
+ );
3438
+ }
3439
+
3389
3440
  return {
3390
3441
  dataRoutes,
3391
3442
  query,
@@ -3399,13 +3450,6 @@ export function createStaticHandler(
3399
3450
  //#region Helpers
3400
3451
  ////////////////////////////////////////////////////////////////////////////////
3401
3452
 
3402
- function defaultDataStrategy({
3403
- defaultStrategy,
3404
- matches,
3405
- }: DataStrategyFunctionArgs) {
3406
- return Promise.all(matches.map((match) => defaultStrategy(match)));
3407
- }
3408
-
3409
3453
  /**
3410
3454
  * Given an existing StaticHandlerContext and an error thrown at render time,
3411
3455
  * provide an updated StaticHandlerContext suitable for a second SSR render
@@ -3417,7 +3461,7 @@ export function getStaticContextFromError(
3417
3461
  ) {
3418
3462
  let newContext: StaticHandlerContext = {
3419
3463
  ...context,
3420
- statusCode: 500,
3464
+ statusCode: isRouteErrorResponse(error) ? error.status : 500,
3421
3465
  errors: {
3422
3466
  [context._deepestRenderedBoundaryId || routes[0].id]: error,
3423
3467
  },
@@ -3425,6 +3469,19 @@ export function getStaticContextFromError(
3425
3469
  return newContext;
3426
3470
  }
3427
3471
 
3472
+ function throwStaticHandlerAbortedError(
3473
+ request: Request,
3474
+ isRouteRequest: boolean,
3475
+ future: StaticHandlerFutureConfig
3476
+ ) {
3477
+ if (future.v7_throwAbortReason && request.signal.reason !== undefined) {
3478
+ throw request.signal.reason;
3479
+ }
3480
+
3481
+ let method = isRouteRequest ? "queryRoute" : "query";
3482
+ throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);
3483
+ }
3484
+
3428
3485
  function isSubmissionNavigation(
3429
3486
  opts: BaseNavigateOrFetchOptions
3430
3487
  ): opts is SubmissionNavigateOptions {
@@ -3700,21 +3757,27 @@ function getMatchesToLoad(
3700
3757
  let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);
3701
3758
 
3702
3759
  let navigationMatches = boundaryMatches.filter((match, index) => {
3703
- if (isInitialLoad) {
3704
- // On initial hydration we don't do any shouldRevalidate stuff - we just
3705
- // call the unhydrated loaders
3706
- return isUnhydratedRoute(state, match.route);
3707
- }
3708
-
3709
- if (match.route.lazy) {
3760
+ let { route } = match;
3761
+ if (route.lazy) {
3710
3762
  // We haven't loaded this route yet so we don't know if it's got a loader!
3711
3763
  return true;
3712
3764
  }
3713
3765
 
3714
- if (match.route.loader == null) {
3766
+ if (route.loader == null) {
3715
3767
  return false;
3716
3768
  }
3717
3769
 
3770
+ if (isInitialLoad) {
3771
+ if (route.loader.hydrate) {
3772
+ return true;
3773
+ }
3774
+ return (
3775
+ state.loaderData[route.id] === undefined &&
3776
+ // Don't re-run if the loader ran and threw an error
3777
+ (!state.errors || state.errors[route.id] === undefined)
3778
+ );
3779
+ }
3780
+
3718
3781
  // Always call the loader on new route instances and pending defer cancellations
3719
3782
  if (
3720
3783
  isNewLoader(state.loaderData, state.matches[index], match) ||
@@ -3834,23 +3897,6 @@ function getMatchesToLoad(
3834
3897
  return [navigationMatches, revalidatingFetchers];
3835
3898
  }
3836
3899
 
3837
- // Is this route unhydrated (when v7_partialHydration=true) such that we need
3838
- // to call it's loader on the initial router creation
3839
- function isUnhydratedRoute(state: RouterState, route: AgnosticDataRouteObject) {
3840
- if (!route.loader) {
3841
- return false;
3842
- }
3843
- if (route.loader.hydrate) {
3844
- return true;
3845
- }
3846
- return (
3847
- state.loaderData[route.id] === undefined &&
3848
- (!state.errors ||
3849
- // Loader ran but errored - don't re-run
3850
- state.errors[route.id] === undefined)
3851
- );
3852
- }
3853
-
3854
3900
  function isNewLoader(
3855
3901
  currentLoaderData: RouteData,
3856
3902
  currentMatch: AgnosticDataRouteMatch,
@@ -3980,93 +4026,98 @@ async function loadLazyRouteModule(
3980
4026
  return routeToUpdate;
3981
4027
  }
3982
4028
 
3983
- function createCallLoaderOrAction(dataStrategy: DataStrategyFunction) {
3984
- return async (
3985
- type: "loader" | "action",
3986
- request: Request,
3987
- match: AgnosticDataRouteMatch,
3988
- matches: AgnosticDataRouteMatch[],
3989
- manifest: RouteManifest,
3990
- mapRouteProperties: MapRoutePropertiesFunction,
3991
- basename: string,
3992
- v7_relativeSplatPath: boolean,
3993
- opts: {
3994
- isStaticRequest?: boolean;
3995
- isRouteRequest?: boolean;
3996
- requestContext?: unknown;
3997
- } = {}
3998
- ): Promise<DataResult> => {
3999
- let [result] = await dataStrategy({
4000
- matches: [
4001
- finesseToAgnosticDataStrategyMatch(match, mapRouteProperties, manifest),
4002
- ],
4003
- request,
4004
- type,
4005
- defaultStrategy(match) {
4006
- return callLoaderOrActionImplementation(
4007
- type,
4008
- request,
4009
- match,
4010
- matches,
4011
- basename,
4012
- v7_relativeSplatPath,
4013
- opts
4014
- );
4015
- },
4016
- });
4017
-
4018
- return result;
4019
- };
4029
+ // Default implementation of `dataStrategy` which fetches all loaders in parallel
4030
+ function defaultDataStrategy(
4031
+ opts: DataStrategyFunctionArgs
4032
+ ): ReturnType<DataStrategyFunction> {
4033
+ return Promise.all(opts.matches.map((m) => m.bikeshed_loadRoute()));
4020
4034
  }
4021
4035
 
4022
- function finesseToAgnosticDataStrategyMatch(
4023
- match: AgnosticDataRouteMatch,
4036
+ async function callDataStrategyImpl(
4037
+ dataStrategyImpl: DataStrategyFunction,
4038
+ type: "loader" | "action",
4039
+ request: Request,
4040
+ matchesToLoad: AgnosticDataRouteMatch[],
4041
+ matches: AgnosticDataRouteMatch[],
4042
+ manifest: RouteManifest,
4024
4043
  mapRouteProperties: MapRoutePropertiesFunction,
4025
- manifest: RouteManifest
4026
- ): AgnosticDataStrategyMatch {
4027
- let loadRoutePromise: Promise<AgnosticDataRouteObject> | undefined;
4028
-
4029
- if (match.route.lazy) {
4030
- try {
4031
- loadRoutePromise = loadLazyRouteModule(
4032
- match.route,
4033
- mapRouteProperties,
4034
- manifest
4035
- );
4036
- } catch (error) {
4037
- loadRoutePromise = Promise.reject(error);
4038
- }
4039
- }
4044
+ requestContext?: unknown
4045
+ ): Promise<HandlerResult[]> {
4046
+ let routeIdsToLoad = matchesToLoad.reduce(
4047
+ (acc, m) => acc.add(m.route.id),
4048
+ new Set<string>()
4049
+ );
4050
+ let loadedMatches = new Set<string>();
4051
+
4052
+ // Send all matches here to allow for a middleware-type implementation.
4053
+ // handler will be a no-op for unneeded routes and we filter those results
4054
+ // back out below.
4055
+ let results = await dataStrategyImpl({
4056
+ matches: matches.map((match) => {
4057
+ // `bikeshed_loadRoute` encapsulates the route.lazy, executing the
4058
+ // loader/action, and mapping return values/thrown errors to a
4059
+ // HandlerResult. Users can pass a callback to take fine-grained control
4060
+ // over the execution of the loader/action
4061
+ let bikeshed_loadRoute: DataStrategyMatch["bikeshed_loadRoute"] = (
4062
+ bikeshed_handlerOverride
4063
+ ) => {
4064
+ loadedMatches.add(match.route.id);
4065
+ return routeIdsToLoad.has(match.route.id)
4066
+ ? callLoaderOrAction(
4067
+ type,
4068
+ request,
4069
+ match,
4070
+ manifest,
4071
+ mapRouteProperties,
4072
+ bikeshed_handlerOverride,
4073
+ requestContext
4074
+ )
4075
+ : // TODO: What's the best thing to do here - return an empty "success" result?
4076
+ // Or return a success result with the current route loader/action data?
4077
+ // We strip these results out if the route didn't need to be revalidated in
4078
+ // `callDataStrategy` so it doesn't matter for us. It's more of a question
4079
+ // of whether exposing the current data to the user is useful?
4080
+ Promise.resolve({ type: ResultType.data, result: undefined });
4081
+ };
4040
4082
 
4041
- if (!loadRoutePromise) {
4042
- loadRoutePromise = Promise.resolve(match.route);
4043
- }
4083
+ return {
4084
+ ...match,
4085
+ bikeshed_loadRoute,
4086
+ };
4087
+ }),
4088
+ request,
4089
+ params: matches[0].params,
4090
+ });
4044
4091
 
4045
- loadRoutePromise.catch(() => {});
4092
+ // Throw if any loadRoute implementations not called since they are what
4093
+ // ensures a route is fully loaded
4094
+ // Throw if any loadRoute implementations not called since they are what
4095
+ // ensure a route is fully loaded
4096
+ matches.forEach((m) =>
4097
+ invariant(
4098
+ loadedMatches.has(m.route.id),
4099
+ `\`match.bikeshed_loadRoute()\` was not called for route id "${m.route.id}". ` +
4100
+ "You must call `match.bikeshed_loadRoute()` on every match passed to " +
4101
+ "`dataStrategy` to ensure all routes are properly loaded."
4102
+ )
4103
+ );
4046
4104
 
4047
- return {
4048
- ...match,
4049
- route: Object.assign(
4050
- loadRoutePromise,
4051
- match.route
4052
- ) as unknown as LazyRoutePromise,
4053
- };
4105
+ // Filter out any middleware-only matches for which we didn't need to run handlers
4106
+ return results.filter((_, i) => routeIdsToLoad.has(matches[i].route.id));
4054
4107
  }
4055
4108
 
4056
- async function callLoaderOrActionImplementation(
4109
+ // Default logic for calling a loader/action is the user has no specified a dataStrategy
4110
+ async function callLoaderOrAction(
4057
4111
  type: "loader" | "action",
4058
4112
  request: Request,
4059
- match: AgnosticDataStrategyMatch,
4060
- matches: AgnosticDataRouteMatch[],
4061
- basename: string,
4062
- v7_relativeSplatPath: boolean,
4063
- opts: {
4064
- isStaticRequest?: boolean;
4065
- isRouteRequest?: boolean;
4066
- requestContext?: unknown;
4067
- } = {}
4068
- ): Promise<DataResult> {
4069
- let resultType;
4113
+ match: AgnosticDataRouteMatch,
4114
+ manifest: RouteManifest,
4115
+ mapRouteProperties: MapRoutePropertiesFunction,
4116
+ bikeshed_handlerOverride: Parameters<
4117
+ DataStrategyMatch["bikeshed_loadRoute"]
4118
+ >[0],
4119
+ staticContext?: unknown
4120
+ ): Promise<HandlerResult> {
4070
4121
  let result;
4071
4122
  let onReject: (() => void) | undefined;
4072
4123
 
@@ -4076,14 +4127,19 @@ async function callLoaderOrActionImplementation(
4076
4127
  let abortPromise = new Promise((_, r) => (reject = r));
4077
4128
  onReject = () => reject();
4078
4129
  request.signal.addEventListener("abort", onReject);
4079
- return Promise.race([
4080
- handler({
4081
- request,
4082
- params: match.params,
4083
- context: opts.requestContext,
4084
- }),
4085
- abortPromise,
4086
- ]);
4130
+
4131
+ let handlerArg = {
4132
+ request,
4133
+ params: match.params,
4134
+ context: staticContext,
4135
+ };
4136
+ let handlerPromise = bikeshed_handlerOverride
4137
+ ? bikeshed_handlerOverride(async (ctx: unknown) =>
4138
+ ctx !== undefined ? handler(handlerArg, ctx) : handler(handlerArg)
4139
+ )
4140
+ : handler(handlerArg);
4141
+
4142
+ return Promise.race([handlerPromise, abortPromise]);
4087
4143
  };
4088
4144
 
4089
4145
  try {
@@ -4100,7 +4156,7 @@ async function callLoaderOrActionImplementation(
4100
4156
  runHandler(handler).catch((e) => {
4101
4157
  handlerError = e;
4102
4158
  }),
4103
- match.route,
4159
+ loadLazyRouteModule(match.route, mapRouteProperties, manifest),
4104
4160
  ]);
4105
4161
  if (handlerError) {
4106
4162
  throw handlerError;
@@ -4108,11 +4164,11 @@ async function callLoaderOrActionImplementation(
4108
4164
  result = values[0];
4109
4165
  } else {
4110
4166
  // Load lazy route module, then run any returned handler
4111
- let route = await match.route;
4167
+ await loadLazyRouteModule(match.route, mapRouteProperties, manifest);
4112
4168
 
4113
- handler = route[type];
4169
+ handler = match.route[type];
4114
4170
  if (handler) {
4115
- // Handler still run even if we got interrupted to maintain consistency
4171
+ // Handler still runs even if we got interrupted to maintain consistency
4116
4172
  // with un-abortable behavior of handler execution on non-lazy or
4117
4173
  // previously-lazy-loaded routes
4118
4174
  result = await runHandler(handler);
@@ -4127,7 +4183,7 @@ async function callLoaderOrActionImplementation(
4127
4183
  } else {
4128
4184
  // lazy() route has no loader to run. Short circuit here so we don't
4129
4185
  // hit the invariant below that errors on returning undefined.
4130
- return { type: ResultType.data, data: undefined };
4186
+ return { type: ResultType.data, result: undefined };
4131
4187
  }
4132
4188
  }
4133
4189
  } else if (!handler) {
@@ -4147,82 +4203,22 @@ async function callLoaderOrActionImplementation(
4147
4203
  `function. Please return a value or \`null\`.`
4148
4204
  );
4149
4205
  } catch (e) {
4150
- resultType = ResultType.error;
4151
- result = e;
4206
+ return { type: ResultType.error, result: e };
4152
4207
  } finally {
4153
4208
  if (onReject) {
4154
4209
  request.signal.removeEventListener("abort", onReject);
4155
4210
  }
4156
4211
  }
4157
4212
 
4158
- if (isResponse(result)) {
4159
- let status = result.status;
4160
-
4161
- // Process redirects
4162
- if (redirectStatusCodes.has(status)) {
4163
- let location = result.headers.get("Location");
4164
- invariant(
4165
- location,
4166
- "Redirects returned/thrown from loaders/actions must have a Location header"
4167
- );
4168
-
4169
- // Support relative routing in internal redirects
4170
- if (!ABSOLUTE_URL_REGEX.test(location)) {
4171
- location = normalizeTo(
4172
- new URL(request.url),
4173
- matches.slice(
4174
- 0,
4175
- matches.findIndex((m) => m.route.id === match.route.id) + 1
4176
- ),
4177
- basename,
4178
- true,
4179
- location,
4180
- v7_relativeSplatPath
4181
- );
4182
- } else if (!opts.isStaticRequest) {
4183
- // Strip off the protocol+origin for same-origin + same-basename absolute
4184
- // redirects. If this is a static request, we can let it go back to the
4185
- // browser as-is
4186
- let currentUrl = new URL(request.url);
4187
- let url = location.startsWith("//")
4188
- ? new URL(currentUrl.protocol + location)
4189
- : new URL(location);
4190
- let isSameBasename = stripBasename(url.pathname, basename) != null;
4191
- if (url.origin === currentUrl.origin && isSameBasename) {
4192
- location = url.pathname + url.search + url.hash;
4193
- }
4194
- }
4195
-
4196
- // Don't process redirects in the router during static requests requests.
4197
- // Instead, throw the Response and let the server handle it with an HTTP
4198
- // redirect. We also update the Location header in place in this flow so
4199
- // basename and relative routing is taken into account
4200
- if (opts.isStaticRequest) {
4201
- result.headers.set("Location", location);
4202
- throw result;
4203
- }
4204
-
4205
- return {
4206
- type: ResultType.redirect,
4207
- status,
4208
- location,
4209
- revalidate: result.headers.get("X-Remix-Revalidate") !== null,
4210
- reloadDocument: result.headers.get("X-Remix-Reload-Document") !== null,
4211
- };
4212
- }
4213
+ return { type: ResultType.data, result };
4214
+ }
4213
4215
 
4214
- // For SSR single-route requests, we want to hand Responses back directly
4215
- // without unwrapping. We do this with the QueryRouteResponse wrapper
4216
- // interface so we can know whether it was returned or thrown
4217
- if (opts.isRouteRequest) {
4218
- let queryRouteResponse: QueryRouteResponse = {
4219
- type:
4220
- resultType === ResultType.error ? ResultType.error : ResultType.data,
4221
- response: result,
4222
- };
4223
- throw queryRouteResponse;
4224
- }
4216
+ async function convertHandlerResultToDataResult(
4217
+ handlerResult: HandlerResult
4218
+ ): Promise<DataResult> {
4219
+ let { result, type } = handlerResult;
4225
4220
 
4221
+ if (isResponse(result)) {
4226
4222
  let data: any;
4227
4223
 
4228
4224
  try {
@@ -4230,7 +4226,11 @@ async function callLoaderOrActionImplementation(
4230
4226
  // Check between word boundaries instead of startsWith() due to the last
4231
4227
  // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type
4232
4228
  if (contentType && /\bapplication\/json\b/.test(contentType)) {
4233
- data = await result.json();
4229
+ if (result.body == null) {
4230
+ data = null;
4231
+ } else {
4232
+ data = await result.json();
4233
+ }
4234
4234
  } else {
4235
4235
  data = await result.text();
4236
4236
  }
@@ -4238,24 +4238,23 @@ async function callLoaderOrActionImplementation(
4238
4238
  return { type: ResultType.error, error: e };
4239
4239
  }
4240
4240
 
4241
- if (resultType === ResultType.error) {
4241
+ if (type === ResultType.error) {
4242
4242
  return {
4243
- type: resultType,
4244
- error: new ErrorResponseImpl(status, result.statusText, data),
4245
- headers: result.headers,
4243
+ type,
4244
+ error: new ErrorResponseImpl(result.status, result.statusText, data),
4245
+ response: result,
4246
4246
  };
4247
4247
  }
4248
4248
 
4249
4249
  return {
4250
4250
  type: ResultType.data,
4251
4251
  data,
4252
- statusCode: result.status,
4253
- headers: result.headers,
4252
+ response: result,
4254
4253
  };
4255
4254
  }
4256
4255
 
4257
- if (resultType === ResultType.error) {
4258
- return { type: resultType, error: result };
4256
+ if (type === ResultType.error) {
4257
+ return { type, error: result };
4259
4258
  }
4260
4259
 
4261
4260
  if (isDeferredData(result)) {
@@ -4270,6 +4269,40 @@ async function callLoaderOrActionImplementation(
4270
4269
  return { type: ResultType.data, data: result };
4271
4270
  }
4272
4271
 
4272
+ // Support relative routing in internal redirects
4273
+ function normalizeRelativeRoutingRedirectResponse(
4274
+ response: Response,
4275
+ request: Request,
4276
+ routeId: string,
4277
+ matches: AgnosticDataRouteMatch[],
4278
+ basename: string,
4279
+ v7_relativeSplatPath: boolean
4280
+ ) {
4281
+ let location = response.headers.get("Location");
4282
+ invariant(
4283
+ location,
4284
+ "Redirects returned/thrown from loaders/actions must have a Location header"
4285
+ );
4286
+
4287
+ if (!ABSOLUTE_URL_REGEX.test(location)) {
4288
+ let trimmedMatches = matches.slice(
4289
+ 0,
4290
+ matches.findIndex((m) => m.route.id === routeId) + 1
4291
+ );
4292
+ location = normalizeTo(
4293
+ new URL(request.url),
4294
+ trimmedMatches,
4295
+ basename,
4296
+ true,
4297
+ location,
4298
+ v7_relativeSplatPath
4299
+ );
4300
+ response.headers.set("Location", location);
4301
+ }
4302
+
4303
+ return response;
4304
+ }
4305
+
4273
4306
  // Utility method for creating the Request instances for loaders/actions during
4274
4307
  // client-side navigations and fetches. During SSR we will always have a
4275
4308
  // Request instance from the static handler (query/queryRoute)
@@ -4388,28 +4421,35 @@ function processRouteLoaderData(
4388
4421
  ? result.error.status
4389
4422
  : 500;
4390
4423
  }
4391
- if (result.headers) {
4392
- loaderHeaders[id] = result.headers;
4424
+ if (result.response) {
4425
+ loaderHeaders[id] = result.response.headers;
4393
4426
  }
4394
4427
  } else {
4395
4428
  if (isDeferredResult(result)) {
4396
4429
  activeDeferreds.set(id, result.deferredData);
4397
4430
  loaderData[id] = result.deferredData.data;
4431
+ // Error status codes always override success status codes, but if all
4432
+ // loaders are successful we take the deepest status code.
4433
+ if (
4434
+ result.statusCode != null &&
4435
+ result.statusCode !== 200 &&
4436
+ !foundError
4437
+ ) {
4438
+ statusCode = result.statusCode;
4439
+ }
4440
+ if (result.headers) {
4441
+ loaderHeaders[id] = result.headers;
4442
+ }
4398
4443
  } else {
4399
4444
  loaderData[id] = result.data;
4400
- }
4401
-
4402
- // Error status codes always override success status codes, but if all
4403
- // loaders are successful we take the deepest status code.
4404
- if (
4405
- result.statusCode != null &&
4406
- result.statusCode !== 200 &&
4407
- !foundError
4408
- ) {
4409
- statusCode = result.statusCode;
4410
- }
4411
- if (result.headers) {
4412
- loaderHeaders[id] = result.headers;
4445
+ // Error status codes always override success status codes, but if all
4446
+ // loaders are successful we take the deepest status code.
4447
+ if (result.response) {
4448
+ if (result.response.status !== 200 && !foundError) {
4449
+ statusCode = result.response.status;
4450
+ }
4451
+ loaderHeaders[id] = result.response.headers;
4452
+ }
4413
4453
  }
4414
4454
  }
4415
4455
  });
@@ -4655,6 +4695,22 @@ function isHashChangeOnly(a: Location, b: Location): boolean {
4655
4695
  return false;
4656
4696
  }
4657
4697
 
4698
+ function isHandlerResult(result: unknown): result is HandlerResult {
4699
+ return (
4700
+ result != null &&
4701
+ typeof result === "object" &&
4702
+ "type" in result &&
4703
+ "result" in result &&
4704
+ (result.type === ResultType.data || result.type === ResultType.error)
4705
+ );
4706
+ }
4707
+
4708
+ function isRedirectHandlerResult(result: HandlerResult) {
4709
+ return (
4710
+ isResponse(result.result) && redirectStatusCodes.has(result.result.status)
4711
+ );
4712
+ }
4713
+
4658
4714
  function isDeferredResult(result: DataResult): result is DeferredResult {
4659
4715
  return result.type === ResultType.deferred;
4660
4716
  }
@@ -4699,14 +4755,6 @@ function isRedirectResponse(result: any): result is Response {
4699
4755
  return status >= 300 && status <= 399 && location != null;
4700
4756
  }
4701
4757
 
4702
- function isQueryRouteResponse(obj: any): obj is QueryRouteResponse {
4703
- return (
4704
- obj &&
4705
- isResponse(obj.response) &&
4706
- (obj.type === ResultType.data || obj.type === ResultType.error)
4707
- );
4708
- }
4709
-
4710
4758
  function isValidMethod(method: string): method is FormMethod | V7_FormMethod {
4711
4759
  return validRequestMethods.has(method.toLowerCase() as FormMethod);
4712
4760
  }