File size: 2,072 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { getSegmentParam } from '../../../server/app-render/get-segment-param'
import type { LoadComponentsReturnType } from '../../../server/load-components'
import type { AppPageModule } from '../../../server/route-modules/app-page/module'
import type AppPageRouteModule from '../../../server/route-modules/app-page/module'
import type { AppRouteModule } from '../../../server/route-modules/app-route/module'
import {
  isAppPageRouteModule,
  isAppRouteRouteModule,
} from '../../../server/route-modules/checks'
import { InvariantError } from '../../../shared/lib/invariant-error'

function collectAppPageRootParamKeys(
  routeModule: AppPageRouteModule
): readonly string[] {
  let rootParams: string[] = []

  let current = routeModule.userland.loaderTree
  while (current) {
    const [name, parallelRoutes, modules] = current

    // If this is a dynamic segment, then we collect the param.
    const param = getSegmentParam(name)?.param
    if (param) {
      rootParams.push(param)
    }

    // If this has a layout module, then we've found the root layout because
    // we return once we found the first layout.
    if (typeof modules.layout !== 'undefined') {
      return rootParams
    }

    // This didn't include a root layout, so we need to continue. We don't need
    // to collect from other parallel routes because we can't have a parallel
    // route above a root layout.
    current = parallelRoutes.children
  }

  // If we didn't find a root layout, then we don't have any params.
  return []
}

/**
 * Collects the segments for a given route module.
 *
 * @param components the loaded components
 * @returns the segments for the route module
 */
export function collectRootParamKeys({
  routeModule,
}: LoadComponentsReturnType<
  AppPageModule | AppRouteModule
>): readonly string[] {
  if (isAppRouteRouteModule(routeModule)) {
    return []
  }

  if (isAppPageRouteModule(routeModule)) {
    return collectAppPageRootParamKeys(routeModule)
  }

  throw new InvariantError(
    'Expected a route module to be one of app route or page'
  )
}