File size: 2,325 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import type {
  DynamicPrerenderManifestRoute,
  PrerenderManifest,
} from '../../../../build'
import type { DeepReadonly } from '../../../../shared/lib/deep-readonly'
import {
  getRouteMatcher,
  type RouteMatchFn,
} from '../../../../shared/lib/router/utils/route-matcher'
import { getRouteRegex } from '../../../../shared/lib/router/utils/route-regex'

/**
 * A matcher for a dynamic route.
 */
type Matcher = {
  /**
   * The matcher for the dynamic route. This is lazily created when the matcher
   * is first used.
   */
  matcher?: RouteMatchFn

  /**
   * The source of the dynamic route.
   */
  source: string

  /**
   * The route that matches the source.
   */
  route: DeepReadonly<DynamicPrerenderManifestRoute>
}

/**
 * A matcher for the prerender manifest.
 *
 * This class is used to match the pathname to the dynamic route.
 */
export class PrerenderManifestMatcher {
  private readonly matchers: Array<Matcher>
  constructor(
    pathname: string,
    prerenderManifest: DeepReadonly<PrerenderManifest>
  ) {
    this.matchers = Object.entries(prerenderManifest.dynamicRoutes)
      .filter(([source, route]) => {
        // If the pathname is a fallback source route, or the source route is
        // the same as the pathname, then we should include it in the matchers.
        return route.fallbackSourceRoute === pathname || source === pathname
      })
      .map(([source, route]) => ({ source, route }))
  }

  /**
   * Match the pathname to the dynamic route. If no match is found, an error is
   * thrown.
   *
   * @param pathname - The pathname to match.
   * @returns The dynamic route that matches the pathname.
   */
  public match(
    pathname: string
  ): DeepReadonly<DynamicPrerenderManifestRoute> | null {
    // Iterate over the matchers. They're already in the correct order of
    // specificity as they were inserted into the prerender manifest that way
    // and iterating over them with Object.entries guarantees that.
    for (const matcher of this.matchers) {
      // Lazily create the matcher, this is only done once per matcher.
      if (!matcher.matcher) {
        matcher.matcher = getRouteMatcher(getRouteRegex(matcher.source))
      }

      const match = matcher.matcher(pathname)
      if (match) {
        return matcher.route
      }
    }

    return null
  }
}