@tanstack/solid-router 1.108.0

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.
Files changed (271) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +29 -0
  3. package/dist/cjs/Asset.cjs +59 -0
  4. package/dist/cjs/Asset.cjs.map +1 -0
  5. package/dist/cjs/Asset.d.cts +2 -0
  6. package/dist/cjs/CatchBoundary.cjs +92 -0
  7. package/dist/cjs/CatchBoundary.cjs.map +1 -0
  8. package/dist/cjs/CatchBoundary.d.cts +11 -0
  9. package/dist/cjs/HeadContent.cjs +129 -0
  10. package/dist/cjs/HeadContent.cjs.map +1 -0
  11. package/dist/cjs/HeadContent.d.cts +8 -0
  12. package/dist/cjs/Match.cjs +340 -0
  13. package/dist/cjs/Match.cjs.map +1 -0
  14. package/dist/cjs/Match.d.cts +8 -0
  15. package/dist/cjs/Matches.cjs +151 -0
  16. package/dist/cjs/Matches.cjs.map +1 -0
  17. package/dist/cjs/Matches.d.cts +69 -0
  18. package/dist/cjs/RouterProvider.cjs +45 -0
  19. package/dist/cjs/RouterProvider.cjs.map +1 -0
  20. package/dist/cjs/RouterProvider.d.cts +35 -0
  21. package/dist/cjs/SafeFragment.cjs +8 -0
  22. package/dist/cjs/SafeFragment.cjs.map +1 -0
  23. package/dist/cjs/SafeFragment.d.cts +1 -0
  24. package/dist/cjs/ScriptOnce.cjs +23 -0
  25. package/dist/cjs/ScriptOnce.cjs.map +1 -0
  26. package/dist/cjs/ScriptOnce.d.cts +5 -0
  27. package/dist/cjs/Scripts.cjs +48 -0
  28. package/dist/cjs/Scripts.cjs.map +1 -0
  29. package/dist/cjs/Scripts.d.cts +1 -0
  30. package/dist/cjs/ScrollRestoration.cjs +37 -0
  31. package/dist/cjs/ScrollRestoration.cjs.map +1 -0
  32. package/dist/cjs/ScrollRestoration.d.cts +15 -0
  33. package/dist/cjs/Transitioner.cjs +132 -0
  34. package/dist/cjs/Transitioner.cjs.map +1 -0
  35. package/dist/cjs/Transitioner.d.cts +1 -0
  36. package/dist/cjs/awaited.cjs +53 -0
  37. package/dist/cjs/awaited.cjs.map +1 -0
  38. package/dist/cjs/awaited.d.cts +11 -0
  39. package/dist/cjs/fileRoute.cjs +90 -0
  40. package/dist/cjs/fileRoute.cjs.map +1 -0
  41. package/dist/cjs/fileRoute.d.cts +58 -0
  42. package/dist/cjs/history.d.cts +8 -0
  43. package/dist/cjs/index.cjs +260 -0
  44. package/dist/cjs/index.cjs.map +1 -0
  45. package/dist/cjs/index.d.cts +53 -0
  46. package/dist/cjs/lazyRouteComponent.cjs +74 -0
  47. package/dist/cjs/lazyRouteComponent.cjs.map +1 -0
  48. package/dist/cjs/lazyRouteComponent.d.cts +7 -0
  49. package/dist/cjs/link.cjs +279 -0
  50. package/dist/cjs/link.cjs.map +1 -0
  51. package/dist/cjs/link.d.cts +113 -0
  52. package/dist/cjs/matchContext.cjs +25 -0
  53. package/dist/cjs/matchContext.cjs.map +1 -0
  54. package/dist/cjs/matchContext.d.cts +3 -0
  55. package/dist/cjs/not-found.cjs +51 -0
  56. package/dist/cjs/not-found.cjs.map +1 -0
  57. package/dist/cjs/not-found.d.cts +27 -0
  58. package/dist/cjs/redirects.cjs +29 -0
  59. package/dist/cjs/redirects.cjs.map +1 -0
  60. package/dist/cjs/redirects.d.cts +21 -0
  61. package/dist/cjs/renderRouteNotFound.cjs +23 -0
  62. package/dist/cjs/renderRouteNotFound.cjs.map +1 -0
  63. package/dist/cjs/renderRouteNotFound.d.cts +3 -0
  64. package/dist/cjs/route.cjs +233 -0
  65. package/dist/cjs/route.cjs.map +1 -0
  66. package/dist/cjs/route.d.cts +297 -0
  67. package/dist/cjs/routeInfo.d.cts +53 -0
  68. package/dist/cjs/router.cjs +1687 -0
  69. package/dist/cjs/router.cjs.map +1 -0
  70. package/dist/cjs/router.d.cts +555 -0
  71. package/dist/cjs/routerContext.cjs +33 -0
  72. package/dist/cjs/routerContext.cjs.map +1 -0
  73. package/dist/cjs/routerContext.d.cts +8 -0
  74. package/dist/cjs/scroll-restoration.cjs +183 -0
  75. package/dist/cjs/scroll-restoration.cjs.map +1 -0
  76. package/dist/cjs/scroll-restoration.d.cts +29 -0
  77. package/dist/cjs/typePrimitives.d.cts +66 -0
  78. package/dist/cjs/useBlocker.cjs +165 -0
  79. package/dist/cjs/useBlocker.cjs.map +1 -0
  80. package/dist/cjs/useBlocker.d.cts +68 -0
  81. package/dist/cjs/useCanGoBack.cjs +8 -0
  82. package/dist/cjs/useCanGoBack.cjs.map +1 -0
  83. package/dist/cjs/useCanGoBack.d.cts +1 -0
  84. package/dist/cjs/useLoaderData.cjs +14 -0
  85. package/dist/cjs/useLoaderData.cjs.map +1 -0
  86. package/dist/cjs/useLoaderData.d.cts +13 -0
  87. package/dist/cjs/useLoaderDeps.cjs +17 -0
  88. package/dist/cjs/useLoaderDeps.cjs.map +1 -0
  89. package/dist/cjs/useLoaderDeps.d.cts +12 -0
  90. package/dist/cjs/useLocation.cjs +10 -0
  91. package/dist/cjs/useLocation.cjs.map +1 -0
  92. package/dist/cjs/useLocation.d.cts +7 -0
  93. package/dist/cjs/useMatch.cjs +39 -0
  94. package/dist/cjs/useMatch.cjs.map +1 -0
  95. package/dist/cjs/useMatch.d.cts +14 -0
  96. package/dist/cjs/useNavigate.cjs +45 -0
  97. package/dist/cjs/useNavigate.cjs.map +1 -0
  98. package/dist/cjs/useNavigate.d.cts +7 -0
  99. package/dist/cjs/useParams.cjs +15 -0
  100. package/dist/cjs/useParams.cjs.map +1 -0
  101. package/dist/cjs/useParams.d.cts +15 -0
  102. package/dist/cjs/useRouteContext.cjs +11 -0
  103. package/dist/cjs/useRouteContext.cjs.map +1 -0
  104. package/dist/cjs/useRouteContext.d.cts +13 -0
  105. package/dist/cjs/useRouter.cjs +29 -0
  106. package/dist/cjs/useRouter.cjs.map +1 -0
  107. package/dist/cjs/useRouter.d.cts +4 -0
  108. package/dist/cjs/useRouterState.cjs +16 -0
  109. package/dist/cjs/useRouterState.cjs.map +1 -0
  110. package/dist/cjs/useRouterState.d.cts +8 -0
  111. package/dist/cjs/useSearch.cjs +15 -0
  112. package/dist/cjs/useSearch.cjs.map +1 -0
  113. package/dist/cjs/useSearch.d.cts +15 -0
  114. package/dist/cjs/utils.cjs +58 -0
  115. package/dist/cjs/utils.cjs.map +1 -0
  116. package/dist/cjs/utils.d.cts +44 -0
  117. package/dist/esm/Asset.d.ts +2 -0
  118. package/dist/esm/Asset.js +59 -0
  119. package/dist/esm/Asset.js.map +1 -0
  120. package/dist/esm/CatchBoundary.d.ts +11 -0
  121. package/dist/esm/CatchBoundary.js +75 -0
  122. package/dist/esm/CatchBoundary.js.map +1 -0
  123. package/dist/esm/HeadContent.d.ts +8 -0
  124. package/dist/esm/HeadContent.js +112 -0
  125. package/dist/esm/HeadContent.js.map +1 -0
  126. package/dist/esm/Match.d.ts +8 -0
  127. package/dist/esm/Match.js +323 -0
  128. package/dist/esm/Match.js.map +1 -0
  129. package/dist/esm/Matches.d.ts +69 -0
  130. package/dist/esm/Matches.js +134 -0
  131. package/dist/esm/Matches.js.map +1 -0
  132. package/dist/esm/RouterProvider.d.ts +35 -0
  133. package/dist/esm/RouterProvider.js +45 -0
  134. package/dist/esm/RouterProvider.js.map +1 -0
  135. package/dist/esm/SafeFragment.d.ts +1 -0
  136. package/dist/esm/SafeFragment.js +8 -0
  137. package/dist/esm/SafeFragment.js.map +1 -0
  138. package/dist/esm/ScriptOnce.d.ts +5 -0
  139. package/dist/esm/ScriptOnce.js +23 -0
  140. package/dist/esm/ScriptOnce.js.map +1 -0
  141. package/dist/esm/Scripts.d.ts +1 -0
  142. package/dist/esm/Scripts.js +48 -0
  143. package/dist/esm/Scripts.js.map +1 -0
  144. package/dist/esm/ScrollRestoration.d.ts +15 -0
  145. package/dist/esm/ScrollRestoration.js +37 -0
  146. package/dist/esm/ScrollRestoration.js.map +1 -0
  147. package/dist/esm/Transitioner.d.ts +1 -0
  148. package/dist/esm/Transitioner.js +115 -0
  149. package/dist/esm/Transitioner.js.map +1 -0
  150. package/dist/esm/awaited.d.ts +11 -0
  151. package/dist/esm/awaited.js +36 -0
  152. package/dist/esm/awaited.js.map +1 -0
  153. package/dist/esm/fileRoute.d.ts +58 -0
  154. package/dist/esm/fileRoute.js +90 -0
  155. package/dist/esm/fileRoute.js.map +1 -0
  156. package/dist/esm/history.d.ts +8 -0
  157. package/dist/esm/index.d.ts +53 -0
  158. package/dist/esm/index.js +149 -0
  159. package/dist/esm/index.js.map +1 -0
  160. package/dist/esm/lazyRouteComponent.d.ts +7 -0
  161. package/dist/esm/lazyRouteComponent.js +74 -0
  162. package/dist/esm/lazyRouteComponent.js.map +1 -0
  163. package/dist/esm/link.d.ts +113 -0
  164. package/dist/esm/link.js +262 -0
  165. package/dist/esm/link.js.map +1 -0
  166. package/dist/esm/matchContext.d.ts +3 -0
  167. package/dist/esm/matchContext.js +8 -0
  168. package/dist/esm/matchContext.js.map +1 -0
  169. package/dist/esm/not-found.d.ts +27 -0
  170. package/dist/esm/not-found.js +51 -0
  171. package/dist/esm/not-found.js.map +1 -0
  172. package/dist/esm/redirects.d.ts +21 -0
  173. package/dist/esm/redirects.js +29 -0
  174. package/dist/esm/redirects.js.map +1 -0
  175. package/dist/esm/renderRouteNotFound.d.ts +3 -0
  176. package/dist/esm/renderRouteNotFound.js +23 -0
  177. package/dist/esm/renderRouteNotFound.js.map +1 -0
  178. package/dist/esm/route.d.ts +297 -0
  179. package/dist/esm/route.js +233 -0
  180. package/dist/esm/route.js.map +1 -0
  181. package/dist/esm/routeInfo.d.ts +53 -0
  182. package/dist/esm/router.d.ts +555 -0
  183. package/dist/esm/router.js +1687 -0
  184. package/dist/esm/router.js.map +1 -0
  185. package/dist/esm/routerContext.d.ts +8 -0
  186. package/dist/esm/routerContext.js +16 -0
  187. package/dist/esm/routerContext.js.map +1 -0
  188. package/dist/esm/scroll-restoration.d.ts +29 -0
  189. package/dist/esm/scroll-restoration.js +183 -0
  190. package/dist/esm/scroll-restoration.js.map +1 -0
  191. package/dist/esm/typePrimitives.d.ts +66 -0
  192. package/dist/esm/useBlocker.d.ts +68 -0
  193. package/dist/esm/useBlocker.js +148 -0
  194. package/dist/esm/useBlocker.js.map +1 -0
  195. package/dist/esm/useCanGoBack.d.ts +1 -0
  196. package/dist/esm/useCanGoBack.js +8 -0
  197. package/dist/esm/useCanGoBack.js.map +1 -0
  198. package/dist/esm/useLoaderData.d.ts +13 -0
  199. package/dist/esm/useLoaderData.js +14 -0
  200. package/dist/esm/useLoaderData.js.map +1 -0
  201. package/dist/esm/useLoaderDeps.d.ts +12 -0
  202. package/dist/esm/useLoaderDeps.js +17 -0
  203. package/dist/esm/useLoaderDeps.js.map +1 -0
  204. package/dist/esm/useLocation.d.ts +7 -0
  205. package/dist/esm/useLocation.js +10 -0
  206. package/dist/esm/useLocation.js.map +1 -0
  207. package/dist/esm/useMatch.d.ts +14 -0
  208. package/dist/esm/useMatch.js +22 -0
  209. package/dist/esm/useMatch.js.map +1 -0
  210. package/dist/esm/useNavigate.d.ts +7 -0
  211. package/dist/esm/useNavigate.js +28 -0
  212. package/dist/esm/useNavigate.js.map +1 -0
  213. package/dist/esm/useParams.d.ts +15 -0
  214. package/dist/esm/useParams.js +15 -0
  215. package/dist/esm/useParams.js.map +1 -0
  216. package/dist/esm/useRouteContext.d.ts +13 -0
  217. package/dist/esm/useRouteContext.js +11 -0
  218. package/dist/esm/useRouteContext.js.map +1 -0
  219. package/dist/esm/useRouter.d.ts +4 -0
  220. package/dist/esm/useRouter.js +12 -0
  221. package/dist/esm/useRouter.js.map +1 -0
  222. package/dist/esm/useRouterState.d.ts +8 -0
  223. package/dist/esm/useRouterState.js +16 -0
  224. package/dist/esm/useRouterState.js.map +1 -0
  225. package/dist/esm/useSearch.d.ts +15 -0
  226. package/dist/esm/useSearch.js +15 -0
  227. package/dist/esm/useSearch.js.map +1 -0
  228. package/dist/esm/utils.d.ts +44 -0
  229. package/dist/esm/utils.js +41 -0
  230. package/dist/esm/utils.js.map +1 -0
  231. package/package.json +75 -0
  232. package/src/Asset.tsx +23 -0
  233. package/src/CatchBoundary.tsx +78 -0
  234. package/src/HeadContent.tsx +146 -0
  235. package/src/Match.tsx +356 -0
  236. package/src/Matches.tsx +348 -0
  237. package/src/RouterProvider.tsx +130 -0
  238. package/src/SafeFragment.tsx +3 -0
  239. package/src/ScriptOnce.tsx +30 -0
  240. package/src/Scripts.tsx +65 -0
  241. package/src/ScrollRestoration.tsx +65 -0
  242. package/src/Transitioner.tsx +152 -0
  243. package/src/awaited.tsx +49 -0
  244. package/src/fileRoute.ts +274 -0
  245. package/src/history.ts +9 -0
  246. package/src/index.tsx +359 -0
  247. package/src/lazyRouteComponent.tsx +114 -0
  248. package/src/link.tsx +1002 -0
  249. package/src/matchContext.tsx +10 -0
  250. package/src/not-found.tsx +69 -0
  251. package/src/redirects.ts +71 -0
  252. package/src/renderRouteNotFound.tsx +27 -0
  253. package/src/route.ts +1477 -0
  254. package/src/routeInfo.ts +239 -0
  255. package/src/router.ts +3066 -0
  256. package/src/routerContext.tsx +26 -0
  257. package/src/scroll-restoration.tsx +337 -0
  258. package/src/typePrimitives.ts +195 -0
  259. package/src/useBlocker.tsx +298 -0
  260. package/src/useCanGoBack.ts +5 -0
  261. package/src/useLoaderData.tsx +64 -0
  262. package/src/useLoaderDeps.tsx +52 -0
  263. package/src/useLocation.tsx +26 -0
  264. package/src/useMatch.tsx +96 -0
  265. package/src/useNavigate.tsx +61 -0
  266. package/src/useParams.tsx +83 -0
  267. package/src/useRouteContext.ts +62 -0
  268. package/src/useRouter.tsx +15 -0
  269. package/src/useRouterState.tsx +32 -0
  270. package/src/useSearch.tsx +84 -0
  271. package/src/utils.ts +96 -0
@@ -0,0 +1,1687 @@
1
+ import { createMemoryHistory, createBrowserHistory, parseHref } from "@tanstack/history";
2
+ import { Store, batch } from "@tanstack/solid-store";
3
+ import invariant from "tiny-invariant";
4
+ import { trimPath, trimPathLeft, parsePathname, resolvePath, cleanPath, trimPathRight, rootRouteId, pick, createControlledPromise, getLocationChangeInfo, matchPathname, deepEqual, defaultParseSearch, defaultStringifySearch, interpolatePath, replaceEqualDeep, joinPaths, last, functionalUpdate } from "@tanstack/router-core";
5
+ import { isResolvedRedirect, isRedirect } from "./redirects.js";
6
+ import { isNotFound } from "./not-found.js";
7
+ import { setupScrollRestoration } from "./scroll-restoration.js";
8
+ const componentTypes = [
9
+ "component",
10
+ "errorComponent",
11
+ "pendingComponent",
12
+ "notFoundComponent"
13
+ ];
14
+ function routeNeedsPreload(route) {
15
+ var _a;
16
+ for (const componentType of componentTypes) {
17
+ if ((_a = route.options[componentType]) == null ? void 0 : _a.preload) {
18
+ return true;
19
+ }
20
+ }
21
+ return false;
22
+ }
23
+ function validateSearch(validateSearch2, input) {
24
+ if (validateSearch2 == null) return {};
25
+ if ("~standard" in validateSearch2) {
26
+ const result = validateSearch2["~standard"].validate(input);
27
+ if (result instanceof Promise)
28
+ throw new SearchParamError("Async validation not supported");
29
+ if (result.issues)
30
+ throw new SearchParamError(JSON.stringify(result.issues, void 0, 2), {
31
+ cause: result
32
+ });
33
+ return result.value;
34
+ }
35
+ if ("parse" in validateSearch2) {
36
+ return validateSearch2.parse(input);
37
+ }
38
+ if (typeof validateSearch2 === "function") {
39
+ return validateSearch2(input);
40
+ }
41
+ return {};
42
+ }
43
+ function createRouter(options) {
44
+ return new Router(options);
45
+ }
46
+ class Router {
47
+ /**
48
+ * @deprecated Use the `createRouter` function instead
49
+ */
50
+ constructor(options) {
51
+ this.tempLocationKey = `${Math.round(
52
+ Math.random() * 1e7
53
+ )}`;
54
+ this.resetNextScroll = true;
55
+ this.shouldViewTransition = void 0;
56
+ this.isViewTransitionTypesSupported = void 0;
57
+ this.subscribers = /* @__PURE__ */ new Set();
58
+ this.isScrollRestoring = false;
59
+ this.isScrollRestorationSetup = false;
60
+ this.startSolidTransition = (fn) => fn();
61
+ this.update = (newOptions) => {
62
+ var _a;
63
+ if (newOptions.notFoundRoute) {
64
+ console.warn(
65
+ "The notFoundRoute API is deprecated and will be removed in the next major version. See https://tanstack.com/router/v1/docs/guide/not-found-errors#migrating-from-notfoundroute for more info."
66
+ );
67
+ }
68
+ const previousOptions = this.options;
69
+ this.options = {
70
+ ...this.options,
71
+ ...newOptions
72
+ };
73
+ this.isServer = this.options.isServer ?? typeof document === "undefined";
74
+ this.pathParamsDecodeCharMap = this.options.pathParamsAllowedCharacters ? new Map(
75
+ this.options.pathParamsAllowedCharacters.map((char) => [
76
+ encodeURIComponent(char),
77
+ char
78
+ ])
79
+ ) : void 0;
80
+ if (!this.basepath || newOptions.basepath && newOptions.basepath !== previousOptions.basepath) {
81
+ if (newOptions.basepath === void 0 || newOptions.basepath === "" || newOptions.basepath === "/") {
82
+ this.basepath = "/";
83
+ } else {
84
+ this.basepath = `/${trimPath(newOptions.basepath)}`;
85
+ }
86
+ }
87
+ if (!this.history || this.options.history && this.options.history !== this.history) {
88
+ this.history = this.options.history ?? (this.isServer ? createMemoryHistory({
89
+ initialEntries: [this.basepath || "/"]
90
+ }) : createBrowserHistory());
91
+ this.latestLocation = this.parseLocation();
92
+ }
93
+ if (this.options.routeTree !== this.routeTree) {
94
+ this.routeTree = this.options.routeTree;
95
+ this.buildRouteTree();
96
+ }
97
+ if (!this.__store) {
98
+ this.__store = new Store(getInitialRouterState(this.latestLocation), {
99
+ onUpdate: () => {
100
+ this.__store.state = {
101
+ ...this.state,
102
+ cachedMatches: this.state.cachedMatches.filter(
103
+ (d) => !["redirected"].includes(d.status)
104
+ )
105
+ };
106
+ }
107
+ });
108
+ setupScrollRestoration(this);
109
+ }
110
+ if (typeof window !== "undefined" && "CSS" in window && typeof ((_a = window.CSS) == null ? void 0 : _a.supports) === "function") {
111
+ this.isViewTransitionTypesSupported = window.CSS.supports(
112
+ "selector(:active-view-transition-type(a)"
113
+ );
114
+ }
115
+ };
116
+ this.buildRouteTree = () => {
117
+ this.routesById = {};
118
+ this.routesByPath = {};
119
+ const notFoundRoute = this.options.notFoundRoute;
120
+ if (notFoundRoute) {
121
+ notFoundRoute.init({
122
+ originalIndex: 99999999999,
123
+ defaultSsr: this.options.defaultSsr
124
+ });
125
+ this.routesById[notFoundRoute.id] = notFoundRoute;
126
+ }
127
+ const recurseRoutes = (childRoutes) => {
128
+ childRoutes.forEach((childRoute, i) => {
129
+ childRoute.init({
130
+ originalIndex: i,
131
+ defaultSsr: this.options.defaultSsr
132
+ });
133
+ const existingRoute = this.routesById[childRoute.id];
134
+ invariant(
135
+ !existingRoute,
136
+ `Duplicate routes found with id: ${String(childRoute.id)}`
137
+ );
138
+ this.routesById[childRoute.id] = childRoute;
139
+ if (!childRoute.isRoot && childRoute.path) {
140
+ const trimmedFullPath = trimPathRight(childRoute.fullPath);
141
+ if (!this.routesByPath[trimmedFullPath] || childRoute.fullPath.endsWith("/")) {
142
+ this.routesByPath[trimmedFullPath] = childRoute;
143
+ }
144
+ }
145
+ const children = childRoute.children;
146
+ if (children == null ? void 0 : children.length) {
147
+ recurseRoutes(children);
148
+ }
149
+ });
150
+ };
151
+ recurseRoutes([this.routeTree]);
152
+ const scoredRoutes = [];
153
+ const routes = Object.values(this.routesById);
154
+ routes.forEach((d, i) => {
155
+ var _a;
156
+ if (d.isRoot || !d.path) {
157
+ return;
158
+ }
159
+ const trimmed = trimPathLeft(d.fullPath);
160
+ const parsed = parsePathname(trimmed);
161
+ while (parsed.length > 1 && ((_a = parsed[0]) == null ? void 0 : _a.value) === "/") {
162
+ parsed.shift();
163
+ }
164
+ const scores = parsed.map((segment) => {
165
+ if (segment.value === "/") {
166
+ return 0.75;
167
+ }
168
+ if (segment.type === "param") {
169
+ return 0.5;
170
+ }
171
+ if (segment.type === "wildcard") {
172
+ return 0.25;
173
+ }
174
+ return 1;
175
+ });
176
+ scoredRoutes.push({ child: d, trimmed, parsed, index: i, scores });
177
+ });
178
+ this.flatRoutes = scoredRoutes.sort((a, b) => {
179
+ const minLength = Math.min(a.scores.length, b.scores.length);
180
+ for (let i = 0; i < minLength; i++) {
181
+ if (a.scores[i] !== b.scores[i]) {
182
+ return b.scores[i] - a.scores[i];
183
+ }
184
+ }
185
+ if (a.scores.length !== b.scores.length) {
186
+ return b.scores.length - a.scores.length;
187
+ }
188
+ for (let i = 0; i < minLength; i++) {
189
+ if (a.parsed[i].value !== b.parsed[i].value) {
190
+ return a.parsed[i].value > b.parsed[i].value ? 1 : -1;
191
+ }
192
+ }
193
+ return a.index - b.index;
194
+ }).map((d, i) => {
195
+ d.child.rank = i;
196
+ return d.child;
197
+ });
198
+ };
199
+ this.subscribe = (eventType, fn) => {
200
+ const listener = {
201
+ eventType,
202
+ fn
203
+ };
204
+ this.subscribers.add(listener);
205
+ return () => {
206
+ this.subscribers.delete(listener);
207
+ };
208
+ };
209
+ this.emit = (routerEvent) => {
210
+ this.subscribers.forEach((listener) => {
211
+ if (listener.eventType === routerEvent.type) {
212
+ listener.fn(routerEvent);
213
+ }
214
+ });
215
+ };
216
+ this.parseLocation = (previousLocation, locationToParse) => {
217
+ const parse = ({
218
+ pathname,
219
+ search,
220
+ hash,
221
+ state
222
+ }) => {
223
+ const parsedSearch = this.options.parseSearch(search);
224
+ const searchStr = this.options.stringifySearch(parsedSearch);
225
+ return {
226
+ pathname,
227
+ searchStr,
228
+ search: replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.search, parsedSearch),
229
+ hash: hash.split("#").reverse()[0] ?? "",
230
+ href: `${pathname}${searchStr}${hash}`,
231
+ state: replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.state, state)
232
+ };
233
+ };
234
+ const location = parse(locationToParse ?? this.history.location);
235
+ const { __tempLocation, __tempKey } = location.state;
236
+ if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {
237
+ const parsedTempLocation = parse(__tempLocation);
238
+ parsedTempLocation.state.key = location.state.key;
239
+ delete parsedTempLocation.state.__tempLocation;
240
+ return {
241
+ ...parsedTempLocation,
242
+ maskedLocation: location
243
+ };
244
+ }
245
+ return location;
246
+ };
247
+ this.resolvePathWithBase = (from, path) => {
248
+ const resolvedPath = resolvePath({
249
+ basepath: this.basepath,
250
+ base: from,
251
+ to: cleanPath(path),
252
+ trailingSlash: this.options.trailingSlash,
253
+ caseSensitive: this.options.caseSensitive
254
+ });
255
+ return resolvedPath;
256
+ };
257
+ this.getMatchedRoutes = (next, dest) => {
258
+ let routeParams = {};
259
+ const trimmedPath = trimPathRight(next.pathname);
260
+ const getMatchedParams = (route) => {
261
+ const result = matchPathname(this.basepath, trimmedPath, {
262
+ to: route.fullPath,
263
+ caseSensitive: route.options.caseSensitive ?? this.options.caseSensitive,
264
+ fuzzy: true
265
+ });
266
+ return result;
267
+ };
268
+ let foundRoute = (dest == null ? void 0 : dest.to) !== void 0 ? this.routesByPath[dest.to] : void 0;
269
+ if (foundRoute) {
270
+ routeParams = getMatchedParams(foundRoute);
271
+ } else {
272
+ foundRoute = this.flatRoutes.find((route) => {
273
+ const matchedParams = getMatchedParams(route);
274
+ if (matchedParams) {
275
+ routeParams = matchedParams;
276
+ return true;
277
+ }
278
+ return false;
279
+ });
280
+ }
281
+ let routeCursor = foundRoute || this.routesById[rootRouteId];
282
+ const matchedRoutes = [routeCursor];
283
+ while (routeCursor.parentRoute) {
284
+ routeCursor = routeCursor.parentRoute;
285
+ matchedRoutes.unshift(routeCursor);
286
+ }
287
+ return { matchedRoutes, routeParams, foundRoute };
288
+ };
289
+ this.cancelMatch = (id) => {
290
+ const match = this.getMatch(id);
291
+ if (!match) return;
292
+ match.abortController.abort();
293
+ clearTimeout(match.pendingTimeout);
294
+ };
295
+ this.cancelMatches = () => {
296
+ var _a;
297
+ (_a = this.state.pendingMatches) == null ? void 0 : _a.forEach((match) => {
298
+ this.cancelMatch(match.id);
299
+ });
300
+ };
301
+ this.buildLocation = (opts) => {
302
+ const build = (dest = {}, matchedRoutesResult) => {
303
+ var _a, _b, _c, _d, _e, _f;
304
+ const fromMatches = dest._fromLocation ? this.matchRoutes(dest._fromLocation, { _buildLocation: true }) : this.state.matches;
305
+ const fromMatch = dest.from != null ? fromMatches.find(
306
+ (d) => matchPathname(this.basepath, trimPathRight(d.pathname), {
307
+ to: dest.from,
308
+ caseSensitive: false,
309
+ fuzzy: false
310
+ })
311
+ ) : void 0;
312
+ const fromPath = (fromMatch == null ? void 0 : fromMatch.pathname) || this.latestLocation.pathname;
313
+ invariant(
314
+ dest.from == null || fromMatch != null,
315
+ "Could not find match for from: " + dest.from
316
+ );
317
+ const fromSearch = ((_a = this.state.pendingMatches) == null ? void 0 : _a.length) ? (_b = last(this.state.pendingMatches)) == null ? void 0 : _b.search : ((_c = last(fromMatches)) == null ? void 0 : _c.search) || this.latestLocation.search;
318
+ const stayingMatches = matchedRoutesResult == null ? void 0 : matchedRoutesResult.matchedRoutes.filter(
319
+ (d) => fromMatches.find((e) => e.routeId === d.id)
320
+ );
321
+ let pathname;
322
+ if (dest.to) {
323
+ const resolvePathTo = (fromMatch == null ? void 0 : fromMatch.fullPath) || this.latestLocation.pathname;
324
+ pathname = this.resolvePathWithBase(resolvePathTo, `${dest.to}`);
325
+ } else {
326
+ const fromRouteByFromPathRouteId = this.routesById[(_d = stayingMatches == null ? void 0 : stayingMatches.find((route) => {
327
+ const interpolatedPath = interpolatePath({
328
+ path: route.fullPath,
329
+ params: (matchedRoutesResult == null ? void 0 : matchedRoutesResult.routeParams) ?? {},
330
+ decodeCharMap: this.pathParamsDecodeCharMap
331
+ }).interpolatedPath;
332
+ const pathname2 = joinPaths([this.basepath, interpolatedPath]);
333
+ return pathname2 === fromPath;
334
+ })) == null ? void 0 : _d.id];
335
+ pathname = this.resolvePathWithBase(
336
+ fromPath,
337
+ (fromRouteByFromPathRouteId == null ? void 0 : fromRouteByFromPathRouteId.to) ?? fromPath
338
+ );
339
+ }
340
+ const prevParams = { ...(_e = last(fromMatches)) == null ? void 0 : _e.params };
341
+ let nextParams = (dest.params ?? true) === true ? prevParams : {
342
+ ...prevParams,
343
+ ...functionalUpdate(dest.params, prevParams)
344
+ };
345
+ if (Object.keys(nextParams).length > 0) {
346
+ matchedRoutesResult == null ? void 0 : matchedRoutesResult.matchedRoutes.map((route) => {
347
+ var _a2;
348
+ return ((_a2 = route.options.params) == null ? void 0 : _a2.stringify) ?? route.options.stringifyParams;
349
+ }).filter(Boolean).forEach((fn) => {
350
+ nextParams = { ...nextParams, ...fn(nextParams) };
351
+ });
352
+ }
353
+ pathname = interpolatePath({
354
+ path: pathname,
355
+ params: nextParams ?? {},
356
+ leaveWildcards: false,
357
+ leaveParams: opts.leaveParams,
358
+ decodeCharMap: this.pathParamsDecodeCharMap
359
+ }).interpolatedPath;
360
+ let search = fromSearch;
361
+ if (opts._includeValidateSearch && ((_f = this.options.search) == null ? void 0 : _f.strict)) {
362
+ let validatedSearch = {};
363
+ matchedRoutesResult == null ? void 0 : matchedRoutesResult.matchedRoutes.forEach((route) => {
364
+ try {
365
+ if (route.options.validateSearch) {
366
+ validatedSearch = {
367
+ ...validatedSearch,
368
+ ...validateSearch(route.options.validateSearch, {
369
+ ...validatedSearch,
370
+ ...search
371
+ }) ?? {}
372
+ };
373
+ }
374
+ } catch {
375
+ }
376
+ });
377
+ search = validatedSearch;
378
+ }
379
+ const applyMiddlewares = (search2) => {
380
+ const allMiddlewares = (matchedRoutesResult == null ? void 0 : matchedRoutesResult.matchedRoutes.reduce(
381
+ (acc, route) => {
382
+ var _a2;
383
+ const middlewares = [];
384
+ if ("search" in route.options) {
385
+ if ((_a2 = route.options.search) == null ? void 0 : _a2.middlewares) {
386
+ middlewares.push(...route.options.search.middlewares);
387
+ }
388
+ } else if (route.options.preSearchFilters || route.options.postSearchFilters) {
389
+ const legacyMiddleware = ({
390
+ search: search3,
391
+ next
392
+ }) => {
393
+ let nextSearch = search3;
394
+ if ("preSearchFilters" in route.options && route.options.preSearchFilters) {
395
+ nextSearch = route.options.preSearchFilters.reduce(
396
+ (prev, next2) => next2(prev),
397
+ search3
398
+ );
399
+ }
400
+ const result = next(nextSearch);
401
+ if ("postSearchFilters" in route.options && route.options.postSearchFilters) {
402
+ return route.options.postSearchFilters.reduce(
403
+ (prev, next2) => next2(prev),
404
+ result
405
+ );
406
+ }
407
+ return result;
408
+ };
409
+ middlewares.push(legacyMiddleware);
410
+ }
411
+ if (opts._includeValidateSearch && route.options.validateSearch) {
412
+ const validate = ({ search: search3, next }) => {
413
+ try {
414
+ const result = next(search3);
415
+ const validatedSearch = {
416
+ ...result,
417
+ ...validateSearch(
418
+ route.options.validateSearch,
419
+ result
420
+ ) ?? {}
421
+ };
422
+ return validatedSearch;
423
+ } catch {
424
+ }
425
+ };
426
+ middlewares.push(validate);
427
+ }
428
+ return acc.concat(middlewares);
429
+ },
430
+ []
431
+ )) ?? [];
432
+ const final = ({ search: search3 }) => {
433
+ if (!dest.search) {
434
+ return {};
435
+ }
436
+ if (dest.search === true) {
437
+ return search3;
438
+ }
439
+ return functionalUpdate(dest.search, search3);
440
+ };
441
+ allMiddlewares.push(final);
442
+ const applyNext = (index, currentSearch) => {
443
+ if (index >= allMiddlewares.length) {
444
+ return currentSearch;
445
+ }
446
+ const middleware = allMiddlewares[index];
447
+ const next = (newSearch) => {
448
+ return applyNext(index + 1, newSearch);
449
+ };
450
+ return middleware({ search: currentSearch, next });
451
+ };
452
+ return applyNext(0, search2);
453
+ };
454
+ search = applyMiddlewares(search);
455
+ search = replaceEqualDeep(fromSearch, search);
456
+ const searchStr = this.options.stringifySearch(search);
457
+ const hash = dest.hash === true ? this.latestLocation.hash : dest.hash ? functionalUpdate(dest.hash, this.latestLocation.hash) : void 0;
458
+ const hashStr = hash ? `#${hash}` : "";
459
+ let nextState = dest.state === true ? this.latestLocation.state : dest.state ? functionalUpdate(dest.state, this.latestLocation.state) : {};
460
+ nextState = replaceEqualDeep(this.latestLocation.state, nextState);
461
+ return {
462
+ pathname,
463
+ search,
464
+ searchStr,
465
+ state: nextState,
466
+ hash: hash ?? "",
467
+ href: `${pathname}${searchStr}${hashStr}`,
468
+ unmaskOnReload: dest.unmaskOnReload
469
+ };
470
+ };
471
+ const buildWithMatches = (dest = {}, maskedDest) => {
472
+ var _a;
473
+ const next = build(dest);
474
+ let maskedNext = maskedDest ? build(maskedDest) : void 0;
475
+ if (!maskedNext) {
476
+ let params = {};
477
+ const foundMask = (_a = this.options.routeMasks) == null ? void 0 : _a.find((d) => {
478
+ const match = matchPathname(this.basepath, next.pathname, {
479
+ to: d.from,
480
+ caseSensitive: false,
481
+ fuzzy: false
482
+ });
483
+ if (match) {
484
+ params = match;
485
+ return true;
486
+ }
487
+ return false;
488
+ });
489
+ if (foundMask) {
490
+ const { from: _from, ...maskProps } = foundMask;
491
+ maskedDest = {
492
+ ...pick(opts, ["from"]),
493
+ ...maskProps,
494
+ params
495
+ };
496
+ maskedNext = build(maskedDest);
497
+ }
498
+ }
499
+ const nextMatches = this.getMatchedRoutes(next, dest);
500
+ const final = build(dest, nextMatches);
501
+ if (maskedNext) {
502
+ const maskedMatches = this.getMatchedRoutes(maskedNext, maskedDest);
503
+ const maskedFinal = build(maskedDest, maskedMatches);
504
+ final.maskedLocation = maskedFinal;
505
+ }
506
+ return final;
507
+ };
508
+ if (opts.mask) {
509
+ return buildWithMatches(opts, {
510
+ ...pick(opts, ["from"]),
511
+ ...opts.mask
512
+ });
513
+ }
514
+ return buildWithMatches(opts);
515
+ };
516
+ this.commitLocation = ({
517
+ viewTransition,
518
+ ignoreBlocker,
519
+ ...next
520
+ }) => {
521
+ const isSameState = () => {
522
+ const ignoredProps = [
523
+ "key",
524
+ "__TSR_index",
525
+ "__hashScrollIntoViewOptions"
526
+ ];
527
+ ignoredProps.forEach((prop) => {
528
+ next.state[prop] = this.latestLocation.state[prop];
529
+ });
530
+ const isEqual = deepEqual(next.state, this.latestLocation.state);
531
+ ignoredProps.forEach((prop) => {
532
+ delete next.state[prop];
533
+ });
534
+ return isEqual;
535
+ };
536
+ const isSameUrl = this.latestLocation.href === next.href;
537
+ const previousCommitPromise = this.commitLocationPromise;
538
+ this.commitLocationPromise = createControlledPromise(() => {
539
+ previousCommitPromise == null ? void 0 : previousCommitPromise.resolve();
540
+ });
541
+ if (isSameUrl && isSameState()) {
542
+ this.load();
543
+ } else {
544
+ let { maskedLocation, hashScrollIntoView, ...nextHistory } = next;
545
+ if (maskedLocation) {
546
+ nextHistory = {
547
+ ...maskedLocation,
548
+ state: {
549
+ ...maskedLocation.state,
550
+ __tempKey: void 0,
551
+ __tempLocation: {
552
+ ...nextHistory,
553
+ search: nextHistory.searchStr,
554
+ state: {
555
+ ...nextHistory.state,
556
+ __tempKey: void 0,
557
+ __tempLocation: void 0,
558
+ key: void 0
559
+ }
560
+ }
561
+ }
562
+ };
563
+ if (nextHistory.unmaskOnReload ?? this.options.unmaskOnReload ?? false) {
564
+ nextHistory.state.__tempKey = this.tempLocationKey;
565
+ }
566
+ }
567
+ nextHistory.state.__hashScrollIntoViewOptions = hashScrollIntoView ?? this.options.defaultHashScrollIntoView ?? true;
568
+ this.shouldViewTransition = viewTransition;
569
+ this.history[next.replace ? "replace" : "push"](
570
+ nextHistory.href,
571
+ nextHistory.state,
572
+ { ignoreBlocker }
573
+ );
574
+ }
575
+ this.resetNextScroll = next.resetScroll ?? true;
576
+ if (!this.history.subscribers.size) {
577
+ this.load();
578
+ }
579
+ return this.commitLocationPromise;
580
+ };
581
+ this.buildAndCommitLocation = ({
582
+ replace,
583
+ resetScroll,
584
+ hashScrollIntoView,
585
+ viewTransition,
586
+ ignoreBlocker,
587
+ href,
588
+ ...rest
589
+ } = {}) => {
590
+ if (href) {
591
+ const currentIndex = this.history.location.state.__TSR_index;
592
+ const parsed = parseHref(href, {
593
+ __TSR_index: replace ? currentIndex : currentIndex + 1
594
+ });
595
+ rest.to = parsed.pathname;
596
+ rest.search = this.options.parseSearch(parsed.search);
597
+ rest.hash = parsed.hash.slice(1);
598
+ }
599
+ const location = this.buildLocation({
600
+ ...rest,
601
+ _includeValidateSearch: true
602
+ });
603
+ return this.commitLocation({
604
+ ...location,
605
+ viewTransition,
606
+ replace,
607
+ resetScroll,
608
+ hashScrollIntoView,
609
+ ignoreBlocker
610
+ });
611
+ };
612
+ this.navigate = ({ to, reloadDocument, href, ...rest }) => {
613
+ if (reloadDocument) {
614
+ if (!href) {
615
+ const location = this.buildLocation({ to, ...rest });
616
+ href = this.history.createHref(location.href);
617
+ }
618
+ if (rest.replace) {
619
+ window.location.replace(href);
620
+ } else {
621
+ window.location.href = href;
622
+ }
623
+ return;
624
+ }
625
+ return this.buildAndCommitLocation({
626
+ ...rest,
627
+ href,
628
+ to
629
+ });
630
+ };
631
+ this.load = async (opts) => {
632
+ this.latestLocation = this.parseLocation(this.latestLocation);
633
+ let redirect;
634
+ let notFound;
635
+ let loadPromise;
636
+ loadPromise = new Promise((resolve) => {
637
+ this.startSolidTransition(async () => {
638
+ var _a;
639
+ try {
640
+ const next = this.latestLocation;
641
+ const prevLocation = this.state.resolvedLocation;
642
+ this.cancelMatches();
643
+ let pendingMatches;
644
+ batch(() => {
645
+ pendingMatches = this.matchRoutes(next);
646
+ this.__store.setState((s) => ({
647
+ ...s,
648
+ status: "pending",
649
+ isLoading: true,
650
+ location: next,
651
+ pendingMatches,
652
+ // If a cached moved to pendingMatches, remove it from cachedMatches
653
+ cachedMatches: s.cachedMatches.filter((d) => {
654
+ return !pendingMatches.find((e) => e.id === d.id);
655
+ })
656
+ }));
657
+ });
658
+ if (!this.state.redirect) {
659
+ this.emit({
660
+ type: "onBeforeNavigate",
661
+ ...getLocationChangeInfo({
662
+ resolvedLocation: prevLocation,
663
+ location: next
664
+ })
665
+ });
666
+ }
667
+ this.emit({
668
+ type: "onBeforeLoad",
669
+ ...getLocationChangeInfo({
670
+ resolvedLocation: prevLocation,
671
+ location: next
672
+ })
673
+ });
674
+ await this.loadMatches({
675
+ sync: opts == null ? void 0 : opts.sync,
676
+ matches: pendingMatches,
677
+ location: next,
678
+ // eslint-disable-next-line @typescript-eslint/require-await
679
+ onReady: async () => {
680
+ this.startViewTransition(async () => {
681
+ let exitingMatches;
682
+ let enteringMatches;
683
+ let stayingMatches;
684
+ batch(() => {
685
+ this.__store.setState((s) => {
686
+ const previousMatches = s.matches;
687
+ const newMatches = s.pendingMatches || s.matches;
688
+ exitingMatches = previousMatches.filter(
689
+ (match) => !newMatches.find((d) => d.id === match.id)
690
+ );
691
+ enteringMatches = newMatches.filter(
692
+ (match) => !previousMatches.find((d) => d.id === match.id)
693
+ );
694
+ stayingMatches = previousMatches.filter(
695
+ (match) => newMatches.find((d) => d.id === match.id)
696
+ );
697
+ return {
698
+ ...s,
699
+ isLoading: false,
700
+ loadedAt: Date.now(),
701
+ matches: newMatches,
702
+ pendingMatches: void 0,
703
+ cachedMatches: [
704
+ ...s.cachedMatches,
705
+ ...exitingMatches.filter((d) => d.status !== "error")
706
+ ]
707
+ };
708
+ });
709
+ this.clearExpiredCache();
710
+ });
711
+ [
712
+ [exitingMatches, "onLeave"],
713
+ [enteringMatches, "onEnter"],
714
+ [stayingMatches, "onStay"]
715
+ ].forEach(([matches, hook]) => {
716
+ matches.forEach((match) => {
717
+ var _a2, _b;
718
+ (_b = (_a2 = this.looseRoutesById[match.routeId].options)[hook]) == null ? void 0 : _b.call(_a2, match);
719
+ });
720
+ });
721
+ });
722
+ }
723
+ });
724
+ } catch (err) {
725
+ if (isResolvedRedirect(err)) {
726
+ redirect = err;
727
+ if (!this.isServer) {
728
+ this.navigate({
729
+ ...redirect,
730
+ replace: true,
731
+ ignoreBlocker: true
732
+ });
733
+ }
734
+ } else if (isNotFound(err)) {
735
+ notFound = err;
736
+ }
737
+ this.__store.setState((s) => ({
738
+ ...s,
739
+ statusCode: redirect ? redirect.statusCode : notFound ? 404 : s.matches.some((d) => d.status === "error") ? 500 : 200,
740
+ redirect
741
+ }));
742
+ }
743
+ if (this.latestLoadPromise === loadPromise) {
744
+ (_a = this.commitLocationPromise) == null ? void 0 : _a.resolve();
745
+ this.latestLoadPromise = void 0;
746
+ this.commitLocationPromise = void 0;
747
+ }
748
+ resolve();
749
+ });
750
+ });
751
+ this.latestLoadPromise = loadPromise;
752
+ await loadPromise;
753
+ while (this.latestLoadPromise && loadPromise !== this.latestLoadPromise) {
754
+ await this.latestLoadPromise;
755
+ }
756
+ if (this.hasNotFoundMatch()) {
757
+ this.__store.setState((s) => ({
758
+ ...s,
759
+ statusCode: 404
760
+ }));
761
+ }
762
+ };
763
+ this.startViewTransition = (fn) => {
764
+ const shouldViewTransition = this.shouldViewTransition ?? this.options.defaultViewTransition;
765
+ delete this.shouldViewTransition;
766
+ if (shouldViewTransition && typeof document !== "undefined" && "startViewTransition" in document && typeof document.startViewTransition === "function") {
767
+ let startViewTransitionParams;
768
+ if (typeof shouldViewTransition === "object" && this.isViewTransitionTypesSupported) {
769
+ startViewTransitionParams = {
770
+ update: fn,
771
+ types: shouldViewTransition.types
772
+ };
773
+ } else {
774
+ startViewTransitionParams = fn;
775
+ }
776
+ document.startViewTransition(startViewTransitionParams);
777
+ } else {
778
+ fn();
779
+ }
780
+ };
781
+ this.updateMatch = (id, updater) => {
782
+ var _a;
783
+ let updated;
784
+ const isPending = (_a = this.state.pendingMatches) == null ? void 0 : _a.find((d) => d.id === id);
785
+ const isMatched = this.state.matches.find((d) => d.id === id);
786
+ const isCached = this.state.cachedMatches.find((d) => d.id === id);
787
+ const matchesKey = isPending ? "pendingMatches" : isMatched ? "matches" : isCached ? "cachedMatches" : "";
788
+ if (matchesKey) {
789
+ this.__store.setState((s) => {
790
+ var _a2;
791
+ return {
792
+ ...s,
793
+ [matchesKey]: (_a2 = s[matchesKey]) == null ? void 0 : _a2.map(
794
+ (d) => d.id === id ? updated = updater(d) : d
795
+ )
796
+ };
797
+ });
798
+ }
799
+ return updated;
800
+ };
801
+ this.getMatch = (matchId) => {
802
+ return [
803
+ ...this.state.cachedMatches,
804
+ ...this.state.pendingMatches ?? [],
805
+ ...this.state.matches
806
+ ].find((d) => d.id === matchId);
807
+ };
808
+ this.loadMatches = async ({
809
+ location,
810
+ matches,
811
+ preload: allPreload,
812
+ onReady,
813
+ updateMatch = this.updateMatch,
814
+ sync
815
+ }) => {
816
+ let firstBadMatchIndex;
817
+ let rendered = false;
818
+ const triggerOnReady = async () => {
819
+ if (!rendered) {
820
+ rendered = true;
821
+ await (onReady == null ? void 0 : onReady());
822
+ }
823
+ };
824
+ const resolvePreload = (matchId) => {
825
+ return !!(allPreload && !this.state.matches.find((d) => d.id === matchId));
826
+ };
827
+ if (!this.isServer && !this.state.matches.length) {
828
+ triggerOnReady();
829
+ }
830
+ const handleRedirectAndNotFound = (match, err) => {
831
+ var _a, _b, _c, _d;
832
+ if (isResolvedRedirect(err)) {
833
+ if (!err.reloadDocument) {
834
+ throw err;
835
+ }
836
+ }
837
+ if (isRedirect(err) || isNotFound(err)) {
838
+ updateMatch(match.id, (prev) => ({
839
+ ...prev,
840
+ status: isRedirect(err) ? "redirected" : isNotFound(err) ? "notFound" : "error",
841
+ isFetching: false,
842
+ error: err,
843
+ beforeLoadPromise: void 0,
844
+ loaderPromise: void 0
845
+ }));
846
+ if (!err.routeId) {
847
+ err.routeId = match.routeId;
848
+ }
849
+ (_a = match.beforeLoadPromise) == null ? void 0 : _a.resolve();
850
+ (_b = match.loaderPromise) == null ? void 0 : _b.resolve();
851
+ (_c = match.loadPromise) == null ? void 0 : _c.resolve();
852
+ if (isRedirect(err)) {
853
+ rendered = true;
854
+ err = this.resolveRedirect({ ...err, _fromLocation: location });
855
+ throw err;
856
+ } else if (isNotFound(err)) {
857
+ this._handleNotFound(matches, err, {
858
+ updateMatch
859
+ });
860
+ (_d = this.serverSsr) == null ? void 0 : _d.onMatchSettled({
861
+ router: this,
862
+ match: this.getMatch(match.id)
863
+ });
864
+ throw err;
865
+ }
866
+ }
867
+ };
868
+ try {
869
+ await new Promise((resolveAll, rejectAll) => {
870
+ ;
871
+ (async () => {
872
+ var _a, _b, _c;
873
+ try {
874
+ const handleSerialError = (index, err, routerCode) => {
875
+ var _a2, _b2;
876
+ const { id: matchId, routeId } = matches[index];
877
+ const route = this.looseRoutesById[routeId];
878
+ if (err instanceof Promise) {
879
+ throw err;
880
+ }
881
+ err.routerCode = routerCode;
882
+ firstBadMatchIndex = firstBadMatchIndex ?? index;
883
+ handleRedirectAndNotFound(this.getMatch(matchId), err);
884
+ try {
885
+ (_b2 = (_a2 = route.options).onError) == null ? void 0 : _b2.call(_a2, err);
886
+ } catch (errorHandlerErr) {
887
+ err = errorHandlerErr;
888
+ handleRedirectAndNotFound(this.getMatch(matchId), err);
889
+ }
890
+ updateMatch(matchId, (prev) => {
891
+ var _a3, _b3;
892
+ (_a3 = prev.beforeLoadPromise) == null ? void 0 : _a3.resolve();
893
+ (_b3 = prev.loadPromise) == null ? void 0 : _b3.resolve();
894
+ return {
895
+ ...prev,
896
+ error: err,
897
+ status: "error",
898
+ isFetching: false,
899
+ updatedAt: Date.now(),
900
+ abortController: new AbortController(),
901
+ beforeLoadPromise: void 0
902
+ };
903
+ });
904
+ };
905
+ for (const [index, { id: matchId, routeId }] of matches.entries()) {
906
+ const existingMatch = this.getMatch(matchId);
907
+ const parentMatchId = (_a = matches[index - 1]) == null ? void 0 : _a.id;
908
+ const route = this.looseRoutesById[routeId];
909
+ const pendingMs = route.options.pendingMs ?? this.options.defaultPendingMs;
910
+ const shouldPending = !!(onReady && !this.isServer && !resolvePreload(matchId) && (route.options.loader || route.options.beforeLoad) && typeof pendingMs === "number" && pendingMs !== Infinity && (route.options.pendingComponent ?? this.options.defaultPendingComponent));
911
+ let executeBeforeLoad = true;
912
+ if (
913
+ // If we are in the middle of a load, either of these will be present
914
+ // (not to be confused with `loadPromise`, which is always defined)
915
+ existingMatch.beforeLoadPromise || existingMatch.loaderPromise
916
+ ) {
917
+ if (shouldPending) {
918
+ setTimeout(() => {
919
+ try {
920
+ triggerOnReady();
921
+ } catch {
922
+ }
923
+ }, pendingMs);
924
+ }
925
+ await existingMatch.beforeLoadPromise;
926
+ executeBeforeLoad = this.getMatch(matchId).status !== "success";
927
+ }
928
+ if (executeBeforeLoad) {
929
+ try {
930
+ updateMatch(matchId, (prev) => ({
931
+ ...prev,
932
+ loadPromise: createControlledPromise(() => {
933
+ var _a2;
934
+ (_a2 = prev.loadPromise) == null ? void 0 : _a2.resolve();
935
+ }),
936
+ beforeLoadPromise: createControlledPromise()
937
+ }));
938
+ const abortController = new AbortController();
939
+ let pendingTimeout;
940
+ if (shouldPending) {
941
+ pendingTimeout = setTimeout(() => {
942
+ try {
943
+ triggerOnReady();
944
+ } catch {
945
+ }
946
+ }, pendingMs);
947
+ }
948
+ const { paramsError, searchError } = this.getMatch(matchId);
949
+ if (paramsError) {
950
+ handleSerialError(index, paramsError, "PARSE_PARAMS");
951
+ }
952
+ if (searchError) {
953
+ handleSerialError(index, searchError, "VALIDATE_SEARCH");
954
+ }
955
+ const getParentMatchContext = () => parentMatchId ? this.getMatch(parentMatchId).context : this.options.context ?? {};
956
+ updateMatch(matchId, (prev) => ({
957
+ ...prev,
958
+ isFetching: "beforeLoad",
959
+ fetchCount: prev.fetchCount + 1,
960
+ abortController,
961
+ pendingTimeout,
962
+ context: {
963
+ ...getParentMatchContext(),
964
+ ...prev.__routeContext
965
+ }
966
+ }));
967
+ const { search, params, context, cause } = this.getMatch(matchId);
968
+ const preload = resolvePreload(matchId);
969
+ const beforeLoadFnContext = {
970
+ search,
971
+ abortController,
972
+ params,
973
+ preload,
974
+ context,
975
+ location,
976
+ navigate: (opts) => this.navigate({ ...opts, _fromLocation: location }),
977
+ buildLocation: this.buildLocation,
978
+ cause: preload ? "preload" : cause,
979
+ matches
980
+ };
981
+ const beforeLoadContext = await ((_c = (_b = route.options).beforeLoad) == null ? void 0 : _c.call(_b, beforeLoadFnContext)) ?? {};
982
+ if (isRedirect(beforeLoadContext) || isNotFound(beforeLoadContext)) {
983
+ handleSerialError(index, beforeLoadContext, "BEFORE_LOAD");
984
+ }
985
+ updateMatch(matchId, (prev) => {
986
+ return {
987
+ ...prev,
988
+ __beforeLoadContext: beforeLoadContext,
989
+ context: {
990
+ ...getParentMatchContext(),
991
+ ...prev.__routeContext,
992
+ ...beforeLoadContext
993
+ },
994
+ abortController
995
+ };
996
+ });
997
+ } catch (err) {
998
+ handleSerialError(index, err, "BEFORE_LOAD");
999
+ }
1000
+ updateMatch(matchId, (prev) => {
1001
+ var _a2;
1002
+ (_a2 = prev.beforeLoadPromise) == null ? void 0 : _a2.resolve();
1003
+ return {
1004
+ ...prev,
1005
+ beforeLoadPromise: void 0,
1006
+ isFetching: false
1007
+ };
1008
+ });
1009
+ }
1010
+ }
1011
+ const validResolvedMatches = matches.slice(0, firstBadMatchIndex);
1012
+ const matchPromises = [];
1013
+ validResolvedMatches.forEach(({ id: matchId, routeId }, index) => {
1014
+ matchPromises.push(
1015
+ (async () => {
1016
+ const { loaderPromise: prevLoaderPromise } = this.getMatch(matchId);
1017
+ let loaderShouldRunAsync = false;
1018
+ let loaderIsRunningAsync = false;
1019
+ if (prevLoaderPromise) {
1020
+ await prevLoaderPromise;
1021
+ const match = this.getMatch(matchId);
1022
+ if (match.error) {
1023
+ handleRedirectAndNotFound(match, match.error);
1024
+ }
1025
+ } else {
1026
+ const parentMatchPromise = matchPromises[index - 1];
1027
+ const route = this.looseRoutesById[routeId];
1028
+ const getLoaderContext = () => {
1029
+ const {
1030
+ params,
1031
+ loaderDeps,
1032
+ abortController,
1033
+ context,
1034
+ cause
1035
+ } = this.getMatch(matchId);
1036
+ const preload2 = resolvePreload(matchId);
1037
+ return {
1038
+ params,
1039
+ deps: loaderDeps,
1040
+ preload: !!preload2,
1041
+ parentMatchPromise,
1042
+ abortController,
1043
+ context,
1044
+ location,
1045
+ navigate: (opts) => this.navigate({ ...opts, _fromLocation: location }),
1046
+ cause: preload2 ? "preload" : cause,
1047
+ route
1048
+ };
1049
+ };
1050
+ const age = Date.now() - this.getMatch(matchId).updatedAt;
1051
+ const preload = resolvePreload(matchId);
1052
+ const staleAge = preload ? route.options.preloadStaleTime ?? this.options.defaultPreloadStaleTime ?? 3e4 : route.options.staleTime ?? this.options.defaultStaleTime ?? 0;
1053
+ const shouldReloadOption = route.options.shouldReload;
1054
+ const shouldReload = typeof shouldReloadOption === "function" ? shouldReloadOption(getLoaderContext()) : shouldReloadOption;
1055
+ updateMatch(matchId, (prev) => ({
1056
+ ...prev,
1057
+ loaderPromise: createControlledPromise(),
1058
+ preload: !!preload && !this.state.matches.find((d) => d.id === matchId)
1059
+ }));
1060
+ const runLoader = async () => {
1061
+ var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i, _j, _k;
1062
+ try {
1063
+ const potentialPendingMinPromise = async () => {
1064
+ const latestMatch = this.getMatch(matchId);
1065
+ if (latestMatch.minPendingPromise) {
1066
+ await latestMatch.minPendingPromise;
1067
+ }
1068
+ };
1069
+ try {
1070
+ this.loadRouteChunk(route);
1071
+ updateMatch(matchId, (prev) => ({
1072
+ ...prev,
1073
+ isFetching: "loader"
1074
+ }));
1075
+ const loaderData = await ((_b2 = (_a2 = route.options).loader) == null ? void 0 : _b2.call(_a2, getLoaderContext()));
1076
+ handleRedirectAndNotFound(
1077
+ this.getMatch(matchId),
1078
+ loaderData
1079
+ );
1080
+ await route._lazyPromise;
1081
+ await potentialPendingMinPromise();
1082
+ const assetContext = {
1083
+ matches,
1084
+ match: this.getMatch(matchId),
1085
+ params: this.getMatch(matchId).params,
1086
+ loaderData
1087
+ };
1088
+ const headFnContent = (_d = (_c2 = route.options).head) == null ? void 0 : _d.call(_c2, assetContext);
1089
+ const meta = headFnContent == null ? void 0 : headFnContent.meta;
1090
+ const links = headFnContent == null ? void 0 : headFnContent.links;
1091
+ const headScripts = headFnContent == null ? void 0 : headFnContent.scripts;
1092
+ const scripts = (_f = (_e = route.options).scripts) == null ? void 0 : _f.call(_e, assetContext);
1093
+ const headers = (_h = (_g = route.options).headers) == null ? void 0 : _h.call(_g, {
1094
+ loaderData
1095
+ });
1096
+ updateMatch(matchId, (prev) => ({
1097
+ ...prev,
1098
+ error: void 0,
1099
+ status: "success",
1100
+ isFetching: false,
1101
+ updatedAt: Date.now(),
1102
+ loaderData,
1103
+ meta,
1104
+ links,
1105
+ headScripts,
1106
+ headers,
1107
+ scripts
1108
+ }));
1109
+ } catch (e) {
1110
+ let error = e;
1111
+ await potentialPendingMinPromise();
1112
+ handleRedirectAndNotFound(this.getMatch(matchId), e);
1113
+ try {
1114
+ (_j = (_i = route.options).onError) == null ? void 0 : _j.call(_i, e);
1115
+ } catch (onErrorError) {
1116
+ error = onErrorError;
1117
+ handleRedirectAndNotFound(
1118
+ this.getMatch(matchId),
1119
+ onErrorError
1120
+ );
1121
+ }
1122
+ updateMatch(matchId, (prev) => ({
1123
+ ...prev,
1124
+ error,
1125
+ status: "error",
1126
+ isFetching: false
1127
+ }));
1128
+ }
1129
+ (_k = this.serverSsr) == null ? void 0 : _k.onMatchSettled({
1130
+ router: this,
1131
+ match: this.getMatch(matchId)
1132
+ });
1133
+ await route._componentsPromise;
1134
+ } catch (err) {
1135
+ updateMatch(matchId, (prev) => ({
1136
+ ...prev,
1137
+ loaderPromise: void 0
1138
+ }));
1139
+ handleRedirectAndNotFound(this.getMatch(matchId), err);
1140
+ }
1141
+ };
1142
+ const { status, invalid } = this.getMatch(matchId);
1143
+ loaderShouldRunAsync = status === "success" && (invalid || (shouldReload ?? age > staleAge));
1144
+ if (preload && route.options.preload === false) {
1145
+ } else if (loaderShouldRunAsync && !sync) {
1146
+ loaderIsRunningAsync = true;
1147
+ (async () => {
1148
+ try {
1149
+ await runLoader();
1150
+ const { loaderPromise, loadPromise } = this.getMatch(matchId);
1151
+ loaderPromise == null ? void 0 : loaderPromise.resolve();
1152
+ loadPromise == null ? void 0 : loadPromise.resolve();
1153
+ updateMatch(matchId, (prev) => ({
1154
+ ...prev,
1155
+ loaderPromise: void 0
1156
+ }));
1157
+ } catch (err) {
1158
+ if (isResolvedRedirect(err)) {
1159
+ await this.navigate(err);
1160
+ }
1161
+ }
1162
+ })();
1163
+ } else if (status !== "success" || loaderShouldRunAsync && sync) {
1164
+ await runLoader();
1165
+ }
1166
+ }
1167
+ if (!loaderIsRunningAsync) {
1168
+ const { loaderPromise, loadPromise } = this.getMatch(matchId);
1169
+ loaderPromise == null ? void 0 : loaderPromise.resolve();
1170
+ loadPromise == null ? void 0 : loadPromise.resolve();
1171
+ }
1172
+ updateMatch(matchId, (prev) => ({
1173
+ ...prev,
1174
+ isFetching: loaderIsRunningAsync ? prev.isFetching : false,
1175
+ loaderPromise: loaderIsRunningAsync ? prev.loaderPromise : void 0,
1176
+ invalid: false
1177
+ }));
1178
+ return this.getMatch(matchId);
1179
+ })()
1180
+ );
1181
+ });
1182
+ await Promise.all(matchPromises);
1183
+ resolveAll();
1184
+ } catch (err) {
1185
+ rejectAll(err);
1186
+ }
1187
+ })();
1188
+ });
1189
+ await triggerOnReady();
1190
+ } catch (err) {
1191
+ if (isRedirect(err) || isNotFound(err)) {
1192
+ if (isNotFound(err) && !allPreload) {
1193
+ await triggerOnReady();
1194
+ }
1195
+ throw err;
1196
+ }
1197
+ }
1198
+ return matches;
1199
+ };
1200
+ this.invalidate = (opts) => {
1201
+ const invalidate = (d) => {
1202
+ var _a;
1203
+ if (((_a = opts == null ? void 0 : opts.filter) == null ? void 0 : _a.call(opts, d)) ?? true) {
1204
+ return {
1205
+ ...d,
1206
+ invalid: true,
1207
+ ...d.status === "error" ? { status: "pending", error: void 0 } : {}
1208
+ };
1209
+ }
1210
+ return d;
1211
+ };
1212
+ this.__store.setState((s) => {
1213
+ var _a;
1214
+ return {
1215
+ ...s,
1216
+ matches: s.matches.map(invalidate),
1217
+ cachedMatches: s.cachedMatches.map(invalidate),
1218
+ pendingMatches: (_a = s.pendingMatches) == null ? void 0 : _a.map(invalidate)
1219
+ };
1220
+ });
1221
+ return this.load({ sync: opts == null ? void 0 : opts.sync });
1222
+ };
1223
+ this.resolveRedirect = (err) => {
1224
+ const redirect = err;
1225
+ if (!redirect.href) {
1226
+ redirect.href = this.buildLocation(redirect).href;
1227
+ }
1228
+ return redirect;
1229
+ };
1230
+ this.clearCache = (opts) => {
1231
+ const filter = opts == null ? void 0 : opts.filter;
1232
+ if (filter !== void 0) {
1233
+ this.__store.setState((s) => {
1234
+ return {
1235
+ ...s,
1236
+ cachedMatches: s.cachedMatches.filter(
1237
+ (m) => !filter(m)
1238
+ )
1239
+ };
1240
+ });
1241
+ } else {
1242
+ this.__store.setState((s) => {
1243
+ return {
1244
+ ...s,
1245
+ cachedMatches: []
1246
+ };
1247
+ });
1248
+ }
1249
+ };
1250
+ this.clearExpiredCache = () => {
1251
+ const filter = (d) => {
1252
+ const route = this.looseRoutesById[d.routeId];
1253
+ if (!route.options.loader) {
1254
+ return true;
1255
+ }
1256
+ const gcTime = (d.preload ? route.options.preloadGcTime ?? this.options.defaultPreloadGcTime : route.options.gcTime ?? this.options.defaultGcTime) ?? 5 * 60 * 1e3;
1257
+ return !(d.status !== "error" && Date.now() - d.updatedAt < gcTime);
1258
+ };
1259
+ this.clearCache({ filter });
1260
+ };
1261
+ this.loadRouteChunk = (route) => {
1262
+ if (route._lazyPromise === void 0) {
1263
+ if (route.lazyFn) {
1264
+ route._lazyPromise = route.lazyFn().then((lazyRoute) => {
1265
+ const { id: _id, ...options2 } = lazyRoute.options;
1266
+ Object.assign(route.options, options2);
1267
+ });
1268
+ } else {
1269
+ route._lazyPromise = Promise.resolve();
1270
+ }
1271
+ }
1272
+ if (route._componentsPromise === void 0) {
1273
+ route._componentsPromise = route._lazyPromise.then(
1274
+ () => Promise.all(
1275
+ componentTypes.map(async (type) => {
1276
+ const component = route.options[type];
1277
+ if (component == null ? void 0 : component.preload) {
1278
+ await component.preload();
1279
+ }
1280
+ })
1281
+ )
1282
+ );
1283
+ }
1284
+ return route._componentsPromise;
1285
+ };
1286
+ this.preloadRoute = async (opts) => {
1287
+ const next = this.buildLocation(opts);
1288
+ let matches = this.matchRoutes(next, {
1289
+ throwOnError: true,
1290
+ preload: true,
1291
+ dest: opts
1292
+ });
1293
+ const activeMatchIds = new Set(
1294
+ [...this.state.matches, ...this.state.pendingMatches ?? []].map(
1295
+ (d) => d.id
1296
+ )
1297
+ );
1298
+ const loadedMatchIds = /* @__PURE__ */ new Set([
1299
+ ...activeMatchIds,
1300
+ ...this.state.cachedMatches.map((d) => d.id)
1301
+ ]);
1302
+ batch(() => {
1303
+ matches.forEach((match) => {
1304
+ if (!loadedMatchIds.has(match.id)) {
1305
+ this.__store.setState((s) => ({
1306
+ ...s,
1307
+ cachedMatches: [...s.cachedMatches, match]
1308
+ }));
1309
+ }
1310
+ });
1311
+ });
1312
+ try {
1313
+ matches = await this.loadMatches({
1314
+ matches,
1315
+ location: next,
1316
+ preload: true,
1317
+ updateMatch: (id, updater) => {
1318
+ if (activeMatchIds.has(id)) {
1319
+ matches = matches.map((d) => d.id === id ? updater(d) : d);
1320
+ } else {
1321
+ this.updateMatch(id, updater);
1322
+ }
1323
+ }
1324
+ });
1325
+ return matches;
1326
+ } catch (err) {
1327
+ if (isRedirect(err)) {
1328
+ if (err.reloadDocument) {
1329
+ return void 0;
1330
+ }
1331
+ return await this.preloadRoute({
1332
+ ...err,
1333
+ _fromLocation: next
1334
+ });
1335
+ }
1336
+ if (!isNotFound(err)) {
1337
+ console.error(err);
1338
+ }
1339
+ return void 0;
1340
+ }
1341
+ };
1342
+ this.matchRoute = (location, opts) => {
1343
+ const matchLocation = {
1344
+ ...location,
1345
+ to: location.to ? this.resolvePathWithBase(
1346
+ location.from || "",
1347
+ location.to
1348
+ ) : void 0,
1349
+ params: location.params || {},
1350
+ leaveParams: true
1351
+ };
1352
+ const next = this.buildLocation(matchLocation);
1353
+ if ((opts == null ? void 0 : opts.pending) && this.state.status !== "pending") {
1354
+ return false;
1355
+ }
1356
+ const pending = (opts == null ? void 0 : opts.pending) === void 0 ? !this.state.isLoading : opts.pending;
1357
+ const baseLocation = pending ? this.latestLocation : this.state.resolvedLocation || this.state.location;
1358
+ const match = matchPathname(this.basepath, baseLocation.pathname, {
1359
+ ...opts,
1360
+ to: next.pathname
1361
+ });
1362
+ if (!match) {
1363
+ return false;
1364
+ }
1365
+ if (location.params) {
1366
+ if (!deepEqual(match, location.params, { partial: true })) {
1367
+ return false;
1368
+ }
1369
+ }
1370
+ if (match && ((opts == null ? void 0 : opts.includeSearch) ?? true)) {
1371
+ return deepEqual(baseLocation.search, next.search, { partial: true }) ? match : false;
1372
+ }
1373
+ return match;
1374
+ };
1375
+ this._handleNotFound = (matches, err, {
1376
+ updateMatch = this.updateMatch
1377
+ } = {}) => {
1378
+ const matchesByRouteId = Object.fromEntries(
1379
+ matches.map((match2) => [match2.routeId, match2])
1380
+ );
1381
+ let routeCursor = (err.global ? this.looseRoutesById[rootRouteId] : this.looseRoutesById[err.routeId]) || this.looseRoutesById[rootRouteId];
1382
+ while (!routeCursor.options.notFoundComponent && !this.options.defaultNotFoundComponent && routeCursor.id !== rootRouteId) {
1383
+ routeCursor = routeCursor.parentRoute;
1384
+ invariant(
1385
+ routeCursor,
1386
+ "Found invalid route tree while trying to find not-found handler."
1387
+ );
1388
+ }
1389
+ const match = matchesByRouteId[routeCursor.id];
1390
+ invariant(match, "Could not find match for route: " + routeCursor.id);
1391
+ updateMatch(match.id, (prev) => ({
1392
+ ...prev,
1393
+ status: "notFound",
1394
+ error: err,
1395
+ isFetching: false
1396
+ }));
1397
+ if (err.routerCode === "BEFORE_LOAD" && routeCursor.parentRoute) {
1398
+ err.routeId = routeCursor.parentRoute.id;
1399
+ this._handleNotFound(matches, err, {
1400
+ updateMatch
1401
+ });
1402
+ }
1403
+ };
1404
+ this.hasNotFoundMatch = () => {
1405
+ return this.__store.state.matches.some(
1406
+ (d) => d.status === "notFound" || d.globalNotFound
1407
+ );
1408
+ };
1409
+ this.update({
1410
+ defaultPreloadDelay: 50,
1411
+ defaultPendingMs: 1e3,
1412
+ defaultPendingMinMs: 500,
1413
+ context: void 0,
1414
+ ...options,
1415
+ caseSensitive: options.caseSensitive ?? false,
1416
+ notFoundMode: options.notFoundMode ?? "fuzzy",
1417
+ stringifySearch: options.stringifySearch ?? defaultStringifySearch,
1418
+ parseSearch: options.parseSearch ?? defaultParseSearch
1419
+ });
1420
+ if (typeof document !== "undefined") {
1421
+ window.__TSR_ROUTER__ = this;
1422
+ }
1423
+ }
1424
+ get state() {
1425
+ return this.__store.state;
1426
+ }
1427
+ get looseRoutesById() {
1428
+ return this.routesById;
1429
+ }
1430
+ matchRoutes(pathnameOrNext, locationSearchOrOpts, opts) {
1431
+ if (typeof pathnameOrNext === "string") {
1432
+ return this.matchRoutesInternal(
1433
+ {
1434
+ pathname: pathnameOrNext,
1435
+ search: locationSearchOrOpts
1436
+ },
1437
+ opts
1438
+ );
1439
+ } else {
1440
+ return this.matchRoutesInternal(pathnameOrNext, locationSearchOrOpts);
1441
+ }
1442
+ }
1443
+ matchRoutesInternal(next, opts) {
1444
+ const { foundRoute, matchedRoutes, routeParams } = this.getMatchedRoutes(
1445
+ next,
1446
+ opts == null ? void 0 : opts.dest
1447
+ );
1448
+ let isGlobalNotFound = false;
1449
+ if (
1450
+ // If we found a route, and it's not an index route and we have left over path
1451
+ foundRoute ? foundRoute.path !== "/" && routeParams["**"] : (
1452
+ // Or if we didn't find a route and we have left over path
1453
+ trimPathRight(next.pathname)
1454
+ )
1455
+ ) {
1456
+ if (this.options.notFoundRoute) {
1457
+ matchedRoutes.push(this.options.notFoundRoute);
1458
+ } else {
1459
+ isGlobalNotFound = true;
1460
+ }
1461
+ }
1462
+ const globalNotFoundRouteId = (() => {
1463
+ if (!isGlobalNotFound) {
1464
+ return void 0;
1465
+ }
1466
+ if (this.options.notFoundMode !== "root") {
1467
+ for (let i = matchedRoutes.length - 1; i >= 0; i--) {
1468
+ const route = matchedRoutes[i];
1469
+ if (route.children) {
1470
+ return route.id;
1471
+ }
1472
+ }
1473
+ }
1474
+ return rootRouteId;
1475
+ })();
1476
+ const parseErrors = matchedRoutes.map((route) => {
1477
+ var _a;
1478
+ let parsedParamsError;
1479
+ const parseParams = ((_a = route.options.params) == null ? void 0 : _a.parse) ?? route.options.parseParams;
1480
+ if (parseParams) {
1481
+ try {
1482
+ const parsedParams = parseParams(routeParams);
1483
+ Object.assign(routeParams, parsedParams);
1484
+ } catch (err) {
1485
+ parsedParamsError = new PathParamError(err.message, {
1486
+ cause: err
1487
+ });
1488
+ if (opts == null ? void 0 : opts.throwOnError) {
1489
+ throw parsedParamsError;
1490
+ }
1491
+ return parsedParamsError;
1492
+ }
1493
+ }
1494
+ return;
1495
+ });
1496
+ const matches = [];
1497
+ const getParentContext = (parentMatch) => {
1498
+ const parentMatchId = parentMatch == null ? void 0 : parentMatch.id;
1499
+ const parentContext = !parentMatchId ? this.options.context ?? {} : parentMatch.context ?? this.options.context ?? {};
1500
+ return parentContext;
1501
+ };
1502
+ matchedRoutes.forEach((route, index) => {
1503
+ var _a, _b;
1504
+ const parentMatch = matches[index - 1];
1505
+ const [preMatchSearch, strictMatchSearch, searchError] = (() => {
1506
+ const parentSearch = (parentMatch == null ? void 0 : parentMatch.search) ?? next.search;
1507
+ const parentStrictSearch = (parentMatch == null ? void 0 : parentMatch._strictSearch) ?? {};
1508
+ try {
1509
+ const strictSearch = validateSearch(route.options.validateSearch, { ...parentSearch }) ?? {};
1510
+ return [
1511
+ {
1512
+ ...parentSearch,
1513
+ ...strictSearch
1514
+ },
1515
+ { ...parentStrictSearch, ...strictSearch },
1516
+ void 0
1517
+ ];
1518
+ } catch (err) {
1519
+ let searchParamError = err;
1520
+ if (!(err instanceof SearchParamError)) {
1521
+ searchParamError = new SearchParamError(err.message, {
1522
+ cause: err
1523
+ });
1524
+ }
1525
+ if (opts == null ? void 0 : opts.throwOnError) {
1526
+ throw searchParamError;
1527
+ }
1528
+ return [parentSearch, {}, searchParamError];
1529
+ }
1530
+ })();
1531
+ const loaderDeps = ((_b = (_a = route.options).loaderDeps) == null ? void 0 : _b.call(_a, {
1532
+ search: preMatchSearch
1533
+ })) ?? "";
1534
+ const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : "";
1535
+ const { usedParams, interpolatedPath } = interpolatePath({
1536
+ path: route.fullPath,
1537
+ params: routeParams,
1538
+ decodeCharMap: this.pathParamsDecodeCharMap
1539
+ });
1540
+ const matchId = interpolatePath({
1541
+ path: route.id,
1542
+ params: routeParams,
1543
+ leaveWildcards: true,
1544
+ decodeCharMap: this.pathParamsDecodeCharMap
1545
+ }).interpolatedPath + loaderDepsHash;
1546
+ const existingMatch = this.getMatch(matchId);
1547
+ const previousMatch = this.state.matches.find(
1548
+ (d) => d.routeId === route.id
1549
+ );
1550
+ const cause = previousMatch ? "stay" : "enter";
1551
+ let match;
1552
+ if (existingMatch) {
1553
+ match = {
1554
+ ...existingMatch,
1555
+ cause,
1556
+ params: previousMatch ? replaceEqualDeep(previousMatch.params, routeParams) : routeParams,
1557
+ _strictParams: usedParams,
1558
+ search: previousMatch ? replaceEqualDeep(previousMatch.search, preMatchSearch) : replaceEqualDeep(existingMatch.search, preMatchSearch),
1559
+ _strictSearch: strictMatchSearch
1560
+ };
1561
+ } else {
1562
+ const status = route.options.loader || route.options.beforeLoad || route.lazyFn || routeNeedsPreload(route) ? "pending" : "success";
1563
+ match = {
1564
+ id: matchId,
1565
+ index,
1566
+ routeId: route.id,
1567
+ params: previousMatch ? replaceEqualDeep(previousMatch.params, routeParams) : routeParams,
1568
+ _strictParams: usedParams,
1569
+ pathname: joinPaths([this.basepath, interpolatedPath]),
1570
+ updatedAt: Date.now(),
1571
+ search: previousMatch ? replaceEqualDeep(previousMatch.search, preMatchSearch) : preMatchSearch,
1572
+ _strictSearch: strictMatchSearch,
1573
+ searchError: void 0,
1574
+ status,
1575
+ isFetching: false,
1576
+ error: void 0,
1577
+ paramsError: parseErrors[index],
1578
+ __routeContext: {},
1579
+ __beforeLoadContext: {},
1580
+ context: {},
1581
+ abortController: new AbortController(),
1582
+ fetchCount: 0,
1583
+ cause,
1584
+ loaderDeps: previousMatch ? replaceEqualDeep(previousMatch.loaderDeps, loaderDeps) : loaderDeps,
1585
+ invalid: false,
1586
+ preload: false,
1587
+ links: void 0,
1588
+ scripts: void 0,
1589
+ headScripts: void 0,
1590
+ meta: void 0,
1591
+ staticData: route.options.staticData || {},
1592
+ loadPromise: createControlledPromise(),
1593
+ fullPath: route.fullPath
1594
+ };
1595
+ }
1596
+ if (!(opts == null ? void 0 : opts.preload)) {
1597
+ match.globalNotFound = globalNotFoundRouteId === route.id;
1598
+ }
1599
+ match.searchError = searchError;
1600
+ const parentContext = getParentContext(parentMatch);
1601
+ match.context = {
1602
+ ...parentContext,
1603
+ ...match.__routeContext,
1604
+ ...match.__beforeLoadContext
1605
+ };
1606
+ matches.push(match);
1607
+ });
1608
+ matches.forEach((match, index) => {
1609
+ var _a, _b, _c, _d, _e, _f, _g, _h;
1610
+ const route = this.looseRoutesById[match.routeId];
1611
+ const existingMatch = this.getMatch(match.id);
1612
+ if (!existingMatch && (opts == null ? void 0 : opts._buildLocation) !== true) {
1613
+ const parentMatch = matches[index - 1];
1614
+ const parentContext = getParentContext(parentMatch);
1615
+ const contextFnContext = {
1616
+ deps: match.loaderDeps,
1617
+ params: match.params,
1618
+ context: parentContext,
1619
+ location: next,
1620
+ navigate: (opts2) => this.navigate({ ...opts2, _fromLocation: next }),
1621
+ buildLocation: this.buildLocation,
1622
+ cause: match.cause,
1623
+ abortController: match.abortController,
1624
+ preload: !!match.preload,
1625
+ matches
1626
+ };
1627
+ match.__routeContext = ((_b = (_a = route.options).context) == null ? void 0 : _b.call(_a, contextFnContext)) ?? {};
1628
+ match.context = {
1629
+ ...parentContext,
1630
+ ...match.__routeContext,
1631
+ ...match.__beforeLoadContext
1632
+ };
1633
+ }
1634
+ if (match.status === "success") {
1635
+ match.headers = (_d = (_c = route.options).headers) == null ? void 0 : _d.call(_c, {
1636
+ loaderData: match.loaderData
1637
+ });
1638
+ const assetContext = {
1639
+ matches,
1640
+ match,
1641
+ params: match.params,
1642
+ loaderData: match.loaderData
1643
+ };
1644
+ const headFnContent = (_f = (_e = route.options).head) == null ? void 0 : _f.call(_e, assetContext);
1645
+ match.links = headFnContent == null ? void 0 : headFnContent.links;
1646
+ match.headScripts = headFnContent == null ? void 0 : headFnContent.scripts;
1647
+ match.meta = headFnContent == null ? void 0 : headFnContent.meta;
1648
+ match.scripts = (_h = (_g = route.options).scripts) == null ? void 0 : _h.call(_g, assetContext);
1649
+ }
1650
+ });
1651
+ return matches;
1652
+ }
1653
+ }
1654
+ function lazyFn(fn, key) {
1655
+ return async (...args) => {
1656
+ const imported = await fn();
1657
+ return imported[key || "default"](...args);
1658
+ };
1659
+ }
1660
+ class SearchParamError extends Error {
1661
+ }
1662
+ class PathParamError extends Error {
1663
+ }
1664
+ function getInitialRouterState(location) {
1665
+ return {
1666
+ loadedAt: 0,
1667
+ isLoading: false,
1668
+ isTransitioning: false,
1669
+ status: "idle",
1670
+ resolvedLocation: void 0,
1671
+ location,
1672
+ matches: [],
1673
+ pendingMatches: [],
1674
+ cachedMatches: [],
1675
+ statusCode: 200
1676
+ };
1677
+ }
1678
+ export {
1679
+ PathParamError,
1680
+ Router,
1681
+ SearchParamError,
1682
+ componentTypes,
1683
+ createRouter,
1684
+ getInitialRouterState,
1685
+ lazyFn
1686
+ };
1687
+ //# sourceMappingURL=router.js.map