@tanstack/react-router 1.20.1 → 1.20.3-alpha.1

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 (320) hide show
  1. package/README.md +31 -0
  2. package/dist/cjs/Asset.cjs +41 -0
  3. package/dist/cjs/Asset.cjs.map +1 -0
  4. package/dist/cjs/Asset.d.cts +2 -0
  5. package/dist/cjs/CatchBoundary.cjs +16 -12
  6. package/dist/cjs/CatchBoundary.cjs.map +1 -1
  7. package/dist/cjs/CatchBoundary.d.cts +8 -32
  8. package/dist/cjs/ClientOnly.cjs +20 -0
  9. package/dist/cjs/ClientOnly.cjs.map +1 -0
  10. package/dist/cjs/ClientOnly.d.cts +29 -0
  11. package/dist/cjs/HeadContent.cjs +155 -0
  12. package/dist/cjs/HeadContent.cjs.map +1 -0
  13. package/dist/cjs/HeadContent.d.cts +7 -0
  14. package/dist/cjs/Match.cjs +252 -0
  15. package/dist/cjs/Match.cjs.map +1 -0
  16. package/dist/cjs/Match.d.cts +8 -0
  17. package/dist/cjs/Matches.cjs +39 -287
  18. package/dist/cjs/Matches.cjs.map +1 -1
  19. package/dist/cjs/Matches.d.cts +23 -83
  20. package/dist/cjs/RouterProvider.cjs +17 -140
  21. package/dist/cjs/RouterProvider.cjs.map +1 -1
  22. package/dist/cjs/RouterProvider.d.cts +8 -27
  23. package/dist/cjs/SafeFragment.cjs +8 -0
  24. package/dist/cjs/SafeFragment.cjs.map +1 -0
  25. package/dist/cjs/SafeFragment.d.cts +1 -0
  26. package/dist/cjs/ScriptOnce.cjs +28 -0
  27. package/dist/cjs/ScriptOnce.cjs.map +1 -0
  28. package/dist/cjs/ScriptOnce.d.cts +5 -0
  29. package/dist/cjs/Scripts.cjs +51 -0
  30. package/dist/cjs/Scripts.cjs.map +1 -0
  31. package/dist/cjs/Scripts.d.cts +1 -0
  32. package/dist/cjs/ScrollRestoration.cjs +39 -0
  33. package/dist/cjs/ScrollRestoration.cjs.map +1 -0
  34. package/dist/cjs/ScrollRestoration.d.cts +14 -0
  35. package/dist/cjs/Transitioner.cjs +115 -0
  36. package/dist/cjs/Transitioner.cjs.map +1 -0
  37. package/dist/cjs/Transitioner.d.cts +1 -0
  38. package/dist/cjs/awaited.cjs +12 -65
  39. package/dist/cjs/awaited.cjs.map +1 -1
  40. package/dist/cjs/awaited.d.cts +4 -4
  41. package/dist/cjs/fileRoute.cjs +41 -15
  42. package/dist/cjs/fileRoute.cjs.map +1 -1
  43. package/dist/cjs/fileRoute.d.cts +33 -108
  44. package/dist/cjs/history.d.cts +1 -0
  45. package/dist/cjs/index.cjs +216 -73
  46. package/dist/cjs/index.cjs.map +1 -1
  47. package/dist/cjs/index.d.cts +52 -29
  48. package/dist/cjs/lazyRouteComponent.cjs +40 -29
  49. package/dist/cjs/lazyRouteComponent.cjs.map +1 -1
  50. package/dist/cjs/lazyRouteComponent.d.cts +1 -1
  51. package/dist/cjs/link.cjs +212 -106
  52. package/dist/cjs/link.cjs.map +1 -1
  53. package/dist/cjs/link.d.cts +41 -86
  54. package/dist/cjs/matchContext.cjs +27 -0
  55. package/dist/cjs/matchContext.cjs.map +1 -0
  56. package/dist/cjs/matchContext.d.cts +3 -0
  57. package/dist/cjs/not-found.cjs +9 -15
  58. package/dist/cjs/not-found.cjs.map +1 -1
  59. package/dist/cjs/not-found.d.cts +5 -22
  60. package/dist/cjs/renderRouteNotFound.cjs +22 -0
  61. package/dist/cjs/renderRouteNotFound.cjs.map +1 -0
  62. package/dist/cjs/renderRouteNotFound.d.cts +2 -0
  63. package/dist/cjs/route.cjs +110 -79
  64. package/dist/cjs/route.cjs.map +1 -1
  65. package/dist/cjs/route.d.cts +64 -361
  66. package/dist/cjs/router.cjs +12 -1237
  67. package/dist/cjs/router.cjs.map +1 -1
  68. package/dist/cjs/router.d.cts +69 -237
  69. package/dist/cjs/routerContext.cjs +1 -1
  70. package/dist/cjs/routerContext.cjs.map +1 -1
  71. package/dist/cjs/routerContext.d.cts +7 -2
  72. package/dist/cjs/scroll-restoration.cjs +16 -177
  73. package/dist/cjs/scroll-restoration.cjs.map +1 -1
  74. package/dist/cjs/scroll-restoration.d.cts +1 -18
  75. package/dist/cjs/serializer.d.cts +6 -0
  76. package/dist/cjs/structuralSharing.d.cts +8 -0
  77. package/dist/cjs/typePrimitives.d.cts +16 -0
  78. package/dist/cjs/useBlocker.cjs +138 -9
  79. package/dist/cjs/useBlocker.cjs.map +1 -1
  80. package/dist/cjs/useBlocker.d.cts +64 -7
  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 +15 -0
  85. package/dist/cjs/useLoaderData.cjs.map +1 -0
  86. package/dist/cjs/useLoaderData.d.cts +8 -0
  87. package/dist/cjs/useLoaderDeps.cjs +14 -0
  88. package/dist/cjs/useLoaderDeps.cjs.map +1 -0
  89. package/dist/cjs/useLoaderDeps.d.cts +8 -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 +47 -0
  94. package/dist/cjs/useMatch.cjs.map +1 -0
  95. package/dist/cjs/useMatch.d.cts +10 -0
  96. package/dist/cjs/useNavigate.cjs +18 -19
  97. package/dist/cjs/useNavigate.cjs.map +1 -1
  98. package/dist/cjs/useNavigate.d.cts +4 -8
  99. package/dist/cjs/useParams.cjs +8 -8
  100. package/dist/cjs/useParams.cjs.map +1 -1
  101. package/dist/cjs/useParams.d.cts +9 -8
  102. package/dist/cjs/useRouteContext.cjs +3 -3
  103. package/dist/cjs/useRouteContext.cjs.map +1 -1
  104. package/dist/cjs/useRouteContext.d.cts +3 -7
  105. package/dist/cjs/useRouter.cjs.map +1 -1
  106. package/dist/cjs/useRouter.d.cts +3 -4
  107. package/dist/cjs/useRouterState.cjs +18 -1
  108. package/dist/cjs/useRouterState.cjs.map +1 -1
  109. package/dist/cjs/useRouterState.d.cts +8 -6
  110. package/dist/cjs/useSearch.cjs +7 -4
  111. package/dist/cjs/useSearch.cjs.map +1 -1
  112. package/dist/cjs/useSearch.d.cts +9 -7
  113. package/dist/cjs/utils.cjs +40 -122
  114. package/dist/cjs/utils.cjs.map +1 -1
  115. package/dist/cjs/utils.d.cts +46 -50
  116. package/dist/esm/Asset.d.ts +2 -0
  117. package/dist/esm/Asset.js +41 -0
  118. package/dist/esm/Asset.js.map +1 -0
  119. package/dist/esm/CatchBoundary.d.ts +8 -32
  120. package/dist/esm/CatchBoundary.js +16 -12
  121. package/dist/esm/CatchBoundary.js.map +1 -1
  122. package/dist/esm/ClientOnly.d.ts +29 -0
  123. package/dist/esm/ClientOnly.js +20 -0
  124. package/dist/esm/ClientOnly.js.map +1 -0
  125. package/dist/esm/HeadContent.d.ts +7 -0
  126. package/dist/esm/HeadContent.js +139 -0
  127. package/dist/esm/HeadContent.js.map +1 -0
  128. package/dist/esm/Match.d.ts +8 -0
  129. package/dist/esm/Match.js +235 -0
  130. package/dist/esm/Match.js.map +1 -0
  131. package/dist/esm/Matches.d.ts +23 -83
  132. package/dist/esm/Matches.js +36 -284
  133. package/dist/esm/Matches.js.map +1 -1
  134. package/dist/esm/RouterProvider.d.ts +8 -27
  135. package/dist/esm/RouterProvider.js +20 -126
  136. package/dist/esm/RouterProvider.js.map +1 -1
  137. package/dist/esm/SafeFragment.d.ts +1 -0
  138. package/dist/esm/SafeFragment.js +8 -0
  139. package/dist/esm/SafeFragment.js.map +1 -0
  140. package/dist/esm/ScriptOnce.d.ts +5 -0
  141. package/dist/esm/ScriptOnce.js +28 -0
  142. package/dist/esm/ScriptOnce.js.map +1 -0
  143. package/dist/esm/Scripts.d.ts +1 -0
  144. package/dist/esm/Scripts.js +51 -0
  145. package/dist/esm/Scripts.js.map +1 -0
  146. package/dist/esm/ScrollRestoration.d.ts +14 -0
  147. package/dist/esm/ScrollRestoration.js +39 -0
  148. package/dist/esm/ScrollRestoration.js.map +1 -0
  149. package/dist/esm/Transitioner.d.ts +1 -0
  150. package/dist/esm/Transitioner.js +98 -0
  151. package/dist/esm/Transitioner.js.map +1 -0
  152. package/dist/esm/awaited.d.ts +4 -4
  153. package/dist/esm/awaited.js +12 -65
  154. package/dist/esm/awaited.js.map +1 -1
  155. package/dist/esm/fileRoute.d.ts +33 -108
  156. package/dist/esm/fileRoute.js +38 -12
  157. package/dist/esm/fileRoute.js.map +1 -1
  158. package/dist/esm/history.d.ts +1 -0
  159. package/dist/esm/index.d.ts +52 -29
  160. package/dist/esm/index.js +41 -29
  161. package/dist/esm/index.js.map +1 -1
  162. package/dist/esm/lazyRouteComponent.d.ts +1 -1
  163. package/dist/esm/lazyRouteComponent.js +40 -29
  164. package/dist/esm/lazyRouteComponent.js.map +1 -1
  165. package/dist/esm/link.d.ts +41 -86
  166. package/dist/esm/link.js +212 -106
  167. package/dist/esm/link.js.map +1 -1
  168. package/dist/esm/matchContext.d.ts +3 -0
  169. package/dist/esm/matchContext.js +10 -0
  170. package/dist/esm/matchContext.js.map +1 -0
  171. package/dist/esm/not-found.d.ts +5 -22
  172. package/dist/esm/not-found.js +9 -15
  173. package/dist/esm/not-found.js.map +1 -1
  174. package/dist/esm/renderRouteNotFound.d.ts +2 -0
  175. package/dist/esm/renderRouteNotFound.js +22 -0
  176. package/dist/esm/renderRouteNotFound.js.map +1 -0
  177. package/dist/esm/route.d.ts +64 -361
  178. package/dist/esm/route.js +103 -72
  179. package/dist/esm/route.js.map +1 -1
  180. package/dist/esm/router.d.ts +69 -237
  181. package/dist/esm/router.js +13 -1238
  182. package/dist/esm/router.js.map +1 -1
  183. package/dist/esm/routerContext.d.ts +7 -2
  184. package/dist/esm/routerContext.js +1 -1
  185. package/dist/esm/routerContext.js.map +1 -1
  186. package/dist/esm/scroll-restoration.d.ts +1 -18
  187. package/dist/esm/scroll-restoration.js +17 -161
  188. package/dist/esm/scroll-restoration.js.map +1 -1
  189. package/dist/esm/serializer.d.ts +6 -0
  190. package/dist/esm/structuralSharing.d.ts +8 -0
  191. package/dist/esm/typePrimitives.d.ts +16 -0
  192. package/dist/esm/useBlocker.d.ts +64 -7
  193. package/dist/esm/useBlocker.js +138 -9
  194. package/dist/esm/useBlocker.js.map +1 -1
  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 +8 -0
  199. package/dist/esm/useLoaderData.js +15 -0
  200. package/dist/esm/useLoaderData.js.map +1 -0
  201. package/dist/esm/useLoaderDeps.d.ts +8 -0
  202. package/dist/esm/useLoaderDeps.js +14 -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 +10 -0
  208. package/dist/esm/useMatch.js +30 -0
  209. package/dist/esm/useMatch.js.map +1 -0
  210. package/dist/esm/useNavigate.d.ts +4 -8
  211. package/dist/esm/useNavigate.js +18 -19
  212. package/dist/esm/useNavigate.js.map +1 -1
  213. package/dist/esm/useParams.d.ts +9 -8
  214. package/dist/esm/useParams.js +8 -8
  215. package/dist/esm/useParams.js.map +1 -1
  216. package/dist/esm/useRouteContext.d.ts +3 -7
  217. package/dist/esm/useRouteContext.js +2 -2
  218. package/dist/esm/useRouteContext.js.map +1 -1
  219. package/dist/esm/useRouter.d.ts +3 -4
  220. package/dist/esm/useRouter.js.map +1 -1
  221. package/dist/esm/useRouterState.d.ts +8 -6
  222. package/dist/esm/useRouterState.js +18 -1
  223. package/dist/esm/useRouterState.js.map +1 -1
  224. package/dist/esm/useSearch.d.ts +9 -7
  225. package/dist/esm/useSearch.js +6 -3
  226. package/dist/esm/useSearch.js.map +1 -1
  227. package/dist/esm/utils.d.ts +46 -50
  228. package/dist/esm/utils.js +41 -123
  229. package/dist/esm/utils.js.map +1 -1
  230. package/package.json +30 -31
  231. package/src/Asset.tsx +40 -0
  232. package/src/CatchBoundary.tsx +35 -19
  233. package/src/ClientOnly.tsx +68 -0
  234. package/src/HeadContent.tsx +174 -0
  235. package/src/Match.tsx +330 -0
  236. package/src/Matches.tsx +149 -558
  237. package/src/RouterProvider.tsx +58 -212
  238. package/src/SafeFragment.tsx +5 -0
  239. package/src/ScriptOnce.tsx +32 -0
  240. package/src/Scripts.tsx +65 -0
  241. package/src/ScrollRestoration.tsx +69 -0
  242. package/src/Transitioner.tsx +130 -0
  243. package/src/awaited.tsx +16 -87
  244. package/src/fileRoute.ts +145 -248
  245. package/src/history.ts +2 -1
  246. package/src/index.tsx +368 -30
  247. package/src/lazyRouteComponent.tsx +68 -54
  248. package/src/link.tsx +397 -522
  249. package/src/matchContext.tsx +8 -0
  250. package/src/not-found.tsx +13 -34
  251. package/src/renderRouteNotFound.tsx +27 -0
  252. package/src/route.tsx +572 -0
  253. package/src/router.ts +99 -2067
  254. package/src/routerContext.tsx +8 -2
  255. package/src/scroll-restoration.tsx +23 -224
  256. package/src/serializer.ts +7 -0
  257. package/src/structuralSharing.ts +47 -0
  258. package/src/typePrimitives.ts +84 -0
  259. package/src/useBlocker.tsx +297 -15
  260. package/src/useCanGoBack.ts +5 -0
  261. package/src/useLoaderData.tsx +80 -0
  262. package/src/useLoaderDeps.tsx +58 -0
  263. package/src/useLocation.tsx +41 -0
  264. package/src/useMatch.tsx +119 -0
  265. package/src/useNavigate.tsx +41 -61
  266. package/src/useParams.tsx +88 -23
  267. package/src/useRouteContext.ts +24 -18
  268. package/src/useRouter.tsx +4 -5
  269. package/src/useRouterState.tsx +52 -10
  270. package/src/useSearch.tsx +87 -24
  271. package/src/utils.ts +97 -312
  272. package/dist/cjs/createServerFn.cjs +0 -40
  273. package/dist/cjs/createServerFn.cjs.map +0 -1
  274. package/dist/cjs/createServerFn.d.cts +0 -44
  275. package/dist/cjs/defer.cjs +0 -30
  276. package/dist/cjs/defer.cjs.map +0 -1
  277. package/dist/cjs/defer.d.cts +0 -25
  278. package/dist/cjs/location.d.cts +0 -12
  279. package/dist/cjs/path.cjs +0 -213
  280. package/dist/cjs/path.cjs.map +0 -1
  281. package/dist/cjs/path.d.cts +0 -24
  282. package/dist/cjs/qss.cjs +0 -45
  283. package/dist/cjs/qss.cjs.map +0 -1
  284. package/dist/cjs/qss.d.cts +0 -2
  285. package/dist/cjs/redirects.cjs +0 -16
  286. package/dist/cjs/redirects.cjs.map +0 -1
  287. package/dist/cjs/redirects.d.cts +0 -18
  288. package/dist/cjs/routeInfo.d.cts +0 -31
  289. package/dist/cjs/searchParams.cjs +0 -63
  290. package/dist/cjs/searchParams.cjs.map +0 -1
  291. package/dist/cjs/searchParams.d.cts +0 -7
  292. package/dist/esm/createServerFn.d.ts +0 -44
  293. package/dist/esm/createServerFn.js +0 -40
  294. package/dist/esm/createServerFn.js.map +0 -1
  295. package/dist/esm/defer.d.ts +0 -25
  296. package/dist/esm/defer.js +0 -30
  297. package/dist/esm/defer.js.map +0 -1
  298. package/dist/esm/location.d.ts +0 -12
  299. package/dist/esm/path.d.ts +0 -24
  300. package/dist/esm/path.js +0 -213
  301. package/dist/esm/path.js.map +0 -1
  302. package/dist/esm/qss.d.ts +0 -2
  303. package/dist/esm/qss.js +0 -45
  304. package/dist/esm/qss.js.map +0 -1
  305. package/dist/esm/redirects.d.ts +0 -18
  306. package/dist/esm/redirects.js +0 -16
  307. package/dist/esm/redirects.js.map +0 -1
  308. package/dist/esm/routeInfo.d.ts +0 -31
  309. package/dist/esm/searchParams.d.ts +0 -7
  310. package/dist/esm/searchParams.js +0 -63
  311. package/dist/esm/searchParams.js.map +0 -1
  312. package/src/createServerFn.ts +0 -107
  313. package/src/defer.ts +0 -70
  314. package/src/location.ts +0 -13
  315. package/src/path.ts +0 -280
  316. package/src/qss.ts +0 -53
  317. package/src/redirects.ts +0 -56
  318. package/src/route.ts +0 -1356
  319. package/src/routeInfo.ts +0 -63
  320. package/src/searchParams.ts +0 -79
@@ -1,1247 +1,22 @@
1
- import { createBrowserHistory, createMemoryHistory } from "@tanstack/history";
2
- import { Store } from "@tanstack/react-store";
3
- import { rootRouteId } from "./route.js";
4
- import { defaultStringifySearch, defaultParseSearch } from "./searchParams.js";
5
- import { replaceEqualDeep, pick, isServer, deepEqual, escapeJSON, last, functionalUpdate } from "./utils.js";
6
- import { getRouteMatch } from "./RouterProvider.js";
7
- import { trimPath, trimPathLeft, parsePathname, resolvePath, cleanPath, matchPathname, trimPathRight, interpolatePath, joinPaths } from "./path.js";
8
- import invariant from "tiny-invariant";
9
- import { isRedirect } from "./redirects.js";
10
- import { isNotFound } from "./not-found.js";
11
- import warning from "tiny-warning";
12
- const componentTypes = [
13
- "component",
14
- "errorComponent",
15
- "pendingComponent",
16
- "notFoundComponent"
17
- ];
18
- function createRouter(options) {
1
+ import { RouterCore } from "@tanstack/router-core";
2
+ import { createFileRoute, createLazyFileRoute } from "./fileRoute.js";
3
+ const createRouter = (options) => {
19
4
  return new Router(options);
20
- }
21
- class Router {
22
- /**
23
- * @deprecated Use the `createRouter` function instead
24
- */
5
+ };
6
+ class Router extends RouterCore {
25
7
  constructor(options) {
26
- this.tempLocationKey = `${Math.round(
27
- Math.random() * 1e7
28
- )}`;
29
- this.resetNextScroll = true;
30
- this.navigateTimeout = null;
31
- this.latestLoadPromise = Promise.resolve();
32
- this.subscribers = /* @__PURE__ */ new Set();
33
- this.injectedHtml = [];
34
- this.startReactTransition = (fn) => fn();
35
- this.update = (newOptions) => {
36
- if (newOptions.notFoundRoute) {
37
- console.warn(
38
- "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."
39
- );
40
- }
41
- const previousOptions = this.options;
42
- this.options = {
43
- ...this.options,
44
- ...newOptions
45
- };
46
- if (!this.basepath || newOptions.basepath && newOptions.basepath !== previousOptions.basepath) {
47
- if (newOptions.basepath === void 0 || newOptions.basepath === "" || newOptions.basepath === "/") {
48
- this.basepath = "/";
49
- } else {
50
- this.basepath = `/${trimPath(newOptions.basepath)}`;
51
- }
52
- }
53
- if (!this.history || this.options.history && this.options.history !== this.history) {
54
- this.history = this.options.history ?? (typeof document !== "undefined" ? createBrowserHistory() : createMemoryHistory({
55
- initialEntries: [this.options.basepath || "/"]
56
- }));
57
- this.latestLocation = this.parseLocation();
58
- }
59
- if (this.options.routeTree !== this.routeTree) {
60
- this.routeTree = this.options.routeTree;
61
- this.buildRouteTree();
62
- }
63
- if (!this.__store) {
64
- this.__store = new Store(getInitialRouterState(this.latestLocation), {
65
- onUpdate: () => {
66
- this.__store.state = {
67
- ...this.state,
68
- status: this.state.isTransitioning || this.state.isLoading ? "pending" : "idle",
69
- cachedMatches: this.state.cachedMatches.filter(
70
- (d) => !["redirected"].includes(d.status)
71
- )
72
- };
73
- }
74
- });
75
- }
76
- };
77
- this.buildRouteTree = () => {
78
- this.routesById = {};
79
- this.routesByPath = {};
80
- const notFoundRoute = this.options.notFoundRoute;
81
- if (notFoundRoute) {
82
- notFoundRoute.init({ originalIndex: 99999999999 });
83
- this.routesById[notFoundRoute.id] = notFoundRoute;
84
- }
85
- const recurseRoutes = (childRoutes) => {
86
- childRoutes.forEach((childRoute, i) => {
87
- childRoute.init({ originalIndex: i });
88
- const existingRoute = this.routesById[childRoute.id];
89
- invariant(
90
- !existingRoute,
91
- `Duplicate routes found with id: ${String(childRoute.id)}`
92
- );
93
- this.routesById[childRoute.id] = childRoute;
94
- if (!childRoute.isRoot && childRoute.path) {
95
- const trimmedFullPath = trimPathRight(childRoute.fullPath);
96
- if (!this.routesByPath[trimmedFullPath] || childRoute.fullPath.endsWith("/")) {
97
- this.routesByPath[trimmedFullPath] = childRoute;
98
- }
99
- }
100
- const children = childRoute.children;
101
- if (children == null ? void 0 : children.length) {
102
- recurseRoutes(children);
103
- }
104
- });
105
- };
106
- recurseRoutes([this.routeTree]);
107
- const scoredRoutes = [];
108
- Object.values(this.routesById).forEach((d, i) => {
109
- var _a;
110
- if (d.isRoot || !d.path) {
111
- return;
112
- }
113
- const trimmed = trimPathLeft(d.fullPath);
114
- const parsed = parsePathname(trimmed);
115
- while (parsed.length > 1 && ((_a = parsed[0]) == null ? void 0 : _a.value) === "/") {
116
- parsed.shift();
117
- }
118
- const scores = parsed.map((d2) => {
119
- if (d2.value === "/") {
120
- return 0.75;
121
- }
122
- if (d2.type === "param") {
123
- return 0.5;
124
- }
125
- if (d2.type === "wildcard") {
126
- return 0.25;
127
- }
128
- return 1;
129
- });
130
- scoredRoutes.push({ child: d, trimmed, parsed, index: i, scores });
131
- });
132
- this.flatRoutes = scoredRoutes.sort((a, b) => {
133
- const minLength = Math.min(a.scores.length, b.scores.length);
134
- for (let i = 0; i < minLength; i++) {
135
- if (a.scores[i] !== b.scores[i]) {
136
- return b.scores[i] - a.scores[i];
137
- }
138
- }
139
- if (a.scores.length !== b.scores.length) {
140
- return b.scores.length - a.scores.length;
141
- }
142
- for (let i = 0; i < minLength; i++) {
143
- if (a.parsed[i].value !== b.parsed[i].value) {
144
- return a.parsed[i].value > b.parsed[i].value ? 1 : -1;
145
- }
146
- }
147
- return a.index - b.index;
148
- }).map((d, i) => {
149
- d.child.rank = i;
150
- return d.child;
151
- });
152
- };
153
- this.subscribe = (eventType, fn) => {
154
- const listener = {
155
- eventType,
156
- fn
157
- };
158
- this.subscribers.add(listener);
159
- return () => {
160
- this.subscribers.delete(listener);
161
- };
162
- };
163
- this.emit = (routerEvent) => {
164
- this.subscribers.forEach((listener) => {
165
- if (listener.eventType === routerEvent.type) {
166
- listener.fn(routerEvent);
167
- }
168
- });
169
- };
170
- this.checkLatest = (promise) => {
171
- return this.latestLoadPromise !== promise ? this.latestLoadPromise : void 0;
172
- };
173
- this.parseLocation = (previousLocation) => {
174
- const parse = ({
175
- pathname,
176
- search,
177
- hash,
178
- state
179
- }) => {
180
- const parsedSearch = this.options.parseSearch(search);
181
- const searchStr = this.options.stringifySearch(parsedSearch);
182
- return {
183
- pathname,
184
- searchStr,
185
- search: replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.search, parsedSearch),
186
- hash: hash.split("#").reverse()[0] ?? "",
187
- href: `${pathname}${searchStr}${hash}`,
188
- state: replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.state, state)
189
- };
190
- };
191
- const location = parse(this.history.location);
192
- let { __tempLocation, __tempKey } = location.state;
193
- if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {
194
- const parsedTempLocation = parse(__tempLocation);
195
- parsedTempLocation.state.key = location.state.key;
196
- delete parsedTempLocation.state.__tempLocation;
197
- return {
198
- ...parsedTempLocation,
199
- maskedLocation: location
200
- };
201
- }
202
- return location;
203
- };
204
- this.resolvePathWithBase = (from, path) => {
205
- return resolvePath(this.basepath, from, cleanPath(path));
206
- };
207
- this.matchRoutes = (pathname, locationSearch, opts) => {
208
- let routeParams = {};
209
- let foundRoute = this.flatRoutes.find((route) => {
210
- const matchedParams = matchPathname(
211
- this.basepath,
212
- trimPathRight(pathname),
213
- {
214
- to: route.fullPath,
215
- caseSensitive: route.options.caseSensitive ?? this.options.caseSensitive,
216
- fuzzy: true
217
- }
218
- );
219
- if (matchedParams) {
220
- routeParams = matchedParams;
221
- return true;
222
- }
223
- return false;
224
- });
225
- let routeCursor = foundRoute || this.routesById[rootRouteId];
226
- let matchedRoutes = [routeCursor];
227
- let isGlobalNotFound = false;
228
- if (
229
- // If we found a route, and it's not an index route and we have left over path
230
- foundRoute ? foundRoute.path !== "/" && routeParams["**"] : (
231
- // Or if we didn't find a route and we have left over path
232
- trimPathRight(pathname)
233
- )
234
- ) {
235
- if (this.options.notFoundRoute) {
236
- matchedRoutes.push(this.options.notFoundRoute);
237
- } else {
238
- isGlobalNotFound = true;
239
- }
240
- }
241
- while (routeCursor == null ? void 0 : routeCursor.parentRoute) {
242
- routeCursor = routeCursor.parentRoute;
243
- if (routeCursor)
244
- matchedRoutes.unshift(routeCursor);
245
- }
246
- const globalNotFoundRouteId = (() => {
247
- if (!isGlobalNotFound) {
248
- return void 0;
249
- }
250
- if (this.options.notFoundMode !== "root") {
251
- for (let i = matchedRoutes.length - 1; i >= 0; i--) {
252
- const route = matchedRoutes[i];
253
- if (route.children) {
254
- return route.id;
255
- }
256
- }
257
- }
258
- return rootRouteId;
259
- })();
260
- const parseErrors = matchedRoutes.map((route) => {
261
- let parsedParamsError;
262
- if (route.options.parseParams) {
263
- try {
264
- const parsedParams = route.options.parseParams(routeParams);
265
- Object.assign(routeParams, parsedParams);
266
- } catch (err) {
267
- parsedParamsError = new PathParamError(err.message, {
268
- cause: err
269
- });
270
- if (opts == null ? void 0 : opts.throwOnError) {
271
- throw parsedParamsError;
272
- }
273
- return parsedParamsError;
274
- }
275
- }
276
- return;
277
- });
278
- const matches = [];
279
- matchedRoutes.forEach((route, index) => {
280
- var _a, _b, _c, _d, _e, _f;
281
- const parentMatch = matches[index - 1];
282
- const [preMatchSearch, searchError] = (() => {
283
- const parentSearch = (parentMatch == null ? void 0 : parentMatch.search) ?? locationSearch;
284
- try {
285
- const validator = typeof route.options.validateSearch === "object" ? route.options.validateSearch.parse : route.options.validateSearch;
286
- let search = (validator == null ? void 0 : validator(parentSearch)) ?? {};
287
- return [
288
- {
289
- ...parentSearch,
290
- ...search
291
- },
292
- void 0
293
- ];
294
- } catch (err) {
295
- const searchError2 = new SearchParamError(err.message, {
296
- cause: err
297
- });
298
- if (opts == null ? void 0 : opts.throwOnError) {
299
- throw searchError2;
300
- }
301
- return [parentSearch, searchError2];
302
- }
303
- })();
304
- const loaderDeps = ((_b = (_a = route.options).loaderDeps) == null ? void 0 : _b.call(_a, {
305
- search: preMatchSearch
306
- })) ?? "";
307
- const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : "";
308
- const interpolatedPath = interpolatePath({
309
- path: route.fullPath,
310
- params: routeParams
311
- });
312
- const matchId = interpolatePath({
313
- path: route.id,
314
- params: routeParams,
315
- leaveWildcards: true
316
- }) + loaderDepsHash;
317
- let existingMatch = getRouteMatch(this.state, matchId);
318
- const cause = this.state.matches.find((d) => d.id === matchId) ? "stay" : "enter";
319
- const match = existingMatch ? {
320
- ...existingMatch,
321
- cause,
322
- params: routeParams
323
- } : {
324
- id: matchId,
325
- routeId: route.id,
326
- params: routeParams,
327
- pathname: joinPaths([this.basepath, interpolatedPath]),
328
- updatedAt: Date.now(),
329
- search: {},
330
- searchError: void 0,
331
- status: "pending",
332
- showPending: false,
333
- isFetching: false,
334
- error: void 0,
335
- paramsError: parseErrors[index],
336
- loadPromise: Promise.resolve(),
337
- routeContext: void 0,
338
- context: void 0,
339
- abortController: new AbortController(),
340
- fetchCount: 0,
341
- cause,
342
- loaderDeps,
343
- invalid: false,
344
- preload: false,
345
- links: (_d = (_c = route.options).links) == null ? void 0 : _d.call(_c),
346
- scripts: (_f = (_e = route.options).scripts) == null ? void 0 : _f.call(_e),
347
- staticData: route.options.staticData || {}
348
- };
349
- if (!(opts == null ? void 0 : opts.preload)) {
350
- match.globalNotFound = globalNotFoundRouteId === route.id;
351
- }
352
- match.search = replaceEqualDeep(match.search, preMatchSearch);
353
- match.searchError = searchError;
354
- matches.push(match);
355
- });
356
- return matches;
357
- };
358
- this.cancelMatch = (id) => {
359
- };
360
- this.cancelMatches = () => {
361
- var _a;
362
- (_a = this.state.pendingMatches) == null ? void 0 : _a.forEach((match) => {
363
- this.cancelMatch(match.id);
364
- });
365
- };
366
- this.buildLocation = (opts) => {
367
- const build = (dest = {}, matches) => {
368
- var _a, _b, _c;
369
- const relevantMatches = this.state.pendingMatches || this.state.matches;
370
- const fromSearch = ((_a = relevantMatches[relevantMatches.length - 1]) == null ? void 0 : _a.search) || this.latestLocation.search;
371
- const fromMatches = this.matchRoutes(
372
- this.latestLocation.pathname,
373
- fromSearch
374
- );
375
- const stayingMatches = matches == null ? void 0 : matches.filter(
376
- (d) => fromMatches == null ? void 0 : fromMatches.find((e) => e.routeId === d.routeId)
377
- );
378
- const fromRoute = this.looseRoutesById[(_b = last(fromMatches)) == null ? void 0 : _b.routeId];
379
- let pathname = dest.to ? this.resolvePathWithBase(
380
- dest.from ?? this.latestLocation.pathname,
381
- `${dest.to}`
382
- ) : this.resolvePathWithBase(fromRoute == null ? void 0 : fromRoute.fullPath, fromRoute == null ? void 0 : fromRoute.fullPath);
383
- const prevParams = { ...(_c = last(fromMatches)) == null ? void 0 : _c.params };
384
- let nextParams = (dest.params ?? true) === true ? prevParams : { ...prevParams, ...functionalUpdate(dest.params, prevParams) };
385
- if (Object.keys(nextParams).length > 0) {
386
- matches == null ? void 0 : matches.map((d) => this.looseRoutesById[d.routeId].options.stringifyParams).filter(Boolean).forEach((fn) => {
387
- nextParams = { ...nextParams, ...fn(nextParams) };
388
- });
389
- }
390
- pathname = interpolatePath({
391
- path: pathname,
392
- params: nextParams ?? {},
393
- leaveWildcards: false,
394
- leaveParams: opts.leaveParams
395
- });
396
- const preSearchFilters = (stayingMatches == null ? void 0 : stayingMatches.map(
397
- (match) => this.looseRoutesById[match.routeId].options.preSearchFilters ?? []
398
- ).flat().filter(Boolean)) ?? [];
399
- const postSearchFilters = (stayingMatches == null ? void 0 : stayingMatches.map(
400
- (match) => this.looseRoutesById[match.routeId].options.postSearchFilters ?? []
401
- ).flat().filter(Boolean)) ?? [];
402
- const preFilteredSearch = (preSearchFilters == null ? void 0 : preSearchFilters.length) ? preSearchFilters == null ? void 0 : preSearchFilters.reduce(
403
- (prev, next) => next(prev),
404
- fromSearch
405
- ) : fromSearch;
406
- const destSearch = dest.search === true ? preFilteredSearch : dest.search ? functionalUpdate(dest.search, preFilteredSearch) ?? {} : (preSearchFilters == null ? void 0 : preSearchFilters.length) ? preFilteredSearch : {};
407
- const postFilteredSearch = (postSearchFilters == null ? void 0 : postSearchFilters.length) ? postSearchFilters.reduce((prev, next) => next(prev), destSearch) : destSearch;
408
- const search = replaceEqualDeep(fromSearch, postFilteredSearch);
409
- const searchStr = this.options.stringifySearch(search);
410
- const hash = dest.hash === true ? this.latestLocation.hash : dest.hash ? functionalUpdate(dest.hash, this.latestLocation.hash) : void 0;
411
- const hashStr = hash ? `#${hash}` : "";
412
- let nextState = dest.state === true ? this.latestLocation.state : dest.state ? functionalUpdate(dest.state, this.latestLocation.state) : {};
413
- nextState = replaceEqualDeep(this.latestLocation.state, nextState);
414
- return {
415
- pathname,
416
- search,
417
- searchStr,
418
- state: nextState,
419
- hash: hash ?? "",
420
- href: `${pathname}${searchStr}${hashStr}`,
421
- unmaskOnReload: dest.unmaskOnReload
422
- };
423
- };
424
- const buildWithMatches = (dest = {}, maskedDest) => {
425
- var _a;
426
- let next = build(dest);
427
- let maskedNext = maskedDest ? build(maskedDest) : void 0;
428
- if (!maskedNext) {
429
- let params = {};
430
- let foundMask = (_a = this.options.routeMasks) == null ? void 0 : _a.find((d) => {
431
- const match = matchPathname(this.basepath, next.pathname, {
432
- to: d.from,
433
- caseSensitive: false,
434
- fuzzy: false
435
- });
436
- if (match) {
437
- params = match;
438
- return true;
439
- }
440
- return false;
441
- });
442
- if (foundMask) {
443
- maskedDest = {
444
- ...pick(opts, ["from"]),
445
- ...foundMask,
446
- params
447
- };
448
- maskedNext = build(maskedDest);
449
- }
450
- }
451
- const nextMatches = this.matchRoutes(next.pathname, next.search);
452
- const maskedMatches = maskedNext ? this.matchRoutes(maskedNext.pathname, maskedNext.search) : void 0;
453
- const maskedFinal = maskedNext ? build(maskedDest, maskedMatches) : void 0;
454
- const final = build(dest, nextMatches);
455
- if (maskedFinal) {
456
- final.maskedLocation = maskedFinal;
457
- }
458
- return final;
459
- };
460
- if (opts.mask) {
461
- return buildWithMatches(opts, {
462
- ...pick(opts, ["from"]),
463
- ...opts.mask
464
- });
465
- }
466
- return buildWithMatches(opts);
467
- };
468
- this.commitLocation = async ({
469
- startTransition,
470
- ...next
471
- }) => {
472
- if (this.navigateTimeout)
473
- clearTimeout(this.navigateTimeout);
474
- const isSameUrl = this.latestLocation.href === next.href;
475
- if (!isSameUrl) {
476
- let { maskedLocation, ...nextHistory } = next;
477
- if (maskedLocation) {
478
- nextHistory = {
479
- ...maskedLocation,
480
- state: {
481
- ...maskedLocation.state,
482
- __tempKey: void 0,
483
- __tempLocation: {
484
- ...nextHistory,
485
- search: nextHistory.searchStr,
486
- state: {
487
- ...nextHistory.state,
488
- __tempKey: void 0,
489
- __tempLocation: void 0,
490
- key: void 0
491
- }
492
- }
493
- }
494
- };
495
- if (nextHistory.unmaskOnReload ?? this.options.unmaskOnReload ?? false) {
496
- nextHistory.state.__tempKey = this.tempLocationKey;
497
- }
498
- }
499
- const apply = () => {
500
- this.history[next.replace ? "replace" : "push"](
501
- nextHistory.href,
502
- nextHistory.state
503
- );
504
- };
505
- if (startTransition ?? true) {
506
- this.startReactTransition(apply);
507
- } else {
508
- apply();
509
- }
510
- }
511
- this.resetNextScroll = next.resetScroll ?? true;
512
- return this.latestLoadPromise;
513
- };
514
- this.buildAndCommitLocation = ({
515
- replace,
516
- resetScroll,
517
- startTransition,
518
- ...rest
519
- } = {}) => {
520
- const location = this.buildLocation(rest);
521
- return this.commitLocation({
522
- ...location,
523
- startTransition,
524
- replace,
525
- resetScroll
526
- });
527
- };
528
- this.navigate = ({ from, to, ...rest }) => {
529
- const toString = String(to);
530
- let isExternal;
531
- try {
532
- new URL(`${toString}`);
533
- isExternal = true;
534
- } catch (e) {
535
- }
536
- invariant(
537
- !isExternal,
538
- "Attempting to navigate to external url with this.navigate!"
539
- );
540
- return this.buildAndCommitLocation({
541
- ...rest,
542
- from,
543
- to
544
- // to: toString,
545
- });
546
- };
547
- this.loadMatches = async ({
548
- checkLatest,
549
- location,
550
- matches,
551
- preload
552
- }) => {
553
- var _a, _b;
554
- let latestPromise;
555
- let firstBadMatchIndex;
556
- const updateMatch = (match, opts) => {
557
- var _a2;
558
- const isPending = (_a2 = this.state.pendingMatches) == null ? void 0 : _a2.find(
559
- (d) => d.id === match.id
560
- );
561
- const isMatched = this.state.matches.find((d) => d.id === match.id);
562
- const matchesKey = isPending ? "pendingMatches" : isMatched ? "matches" : "cachedMatches";
563
- this.__store.setState((s) => {
564
- var _a3, _b2;
565
- return {
566
- ...s,
567
- [matchesKey]: (opts == null ? void 0 : opts.remove) ? (_a3 = s[matchesKey]) == null ? void 0 : _a3.filter((d) => d.id !== match.id) : (_b2 = s[matchesKey]) == null ? void 0 : _b2.map((d) => d.id === match.id ? match : d)
568
- };
569
- });
570
- };
571
- const handleMatchSpecialError = (match, err) => {
572
- match = {
573
- ...match,
574
- status: isRedirect(err) ? "redirected" : isNotFound(err) ? "notFound" : "error",
575
- isFetching: false,
576
- error: err
577
- };
578
- updateMatch(match);
579
- if (!err.routeId) {
580
- err.routeId = match.routeId;
581
- }
582
- throw err;
583
- };
584
- for (let [index, match] of matches.entries()) {
585
- const parentMatch = matches[index - 1];
586
- const route = this.looseRoutesById[match.routeId];
587
- const abortController = new AbortController();
588
- const handleSerialError = (err, code) => {
589
- var _a2, _b2;
590
- err.routerCode = code;
591
- firstBadMatchIndex = firstBadMatchIndex ?? index;
592
- if (isRedirect(err) || isNotFound(err)) {
593
- handleMatchSpecialError(match, err);
594
- }
595
- try {
596
- (_b2 = (_a2 = route.options).onError) == null ? void 0 : _b2.call(_a2, err);
597
- } catch (errorHandlerErr) {
598
- err = errorHandlerErr;
599
- if (isRedirect(err) || isNotFound(err)) {
600
- handleMatchSpecialError(match, errorHandlerErr);
601
- }
602
- }
603
- matches[index] = match = {
604
- ...match,
605
- error: err,
606
- status: "error",
607
- updatedAt: Date.now(),
608
- abortController: new AbortController()
609
- };
610
- };
611
- if (match.paramsError) {
612
- handleSerialError(match.paramsError, "PARSE_PARAMS");
613
- }
614
- if (match.searchError) {
615
- handleSerialError(match.searchError, "VALIDATE_SEARCH");
616
- }
617
- try {
618
- const parentContext = (parentMatch == null ? void 0 : parentMatch.context) ?? this.options.context ?? {};
619
- const pendingMs = route.options.pendingMs ?? this.options.defaultPendingMs;
620
- const pendingPromise = typeof pendingMs === "number" && pendingMs <= 0 ? Promise.resolve() : new Promise((r) => setTimeout(r, pendingMs));
621
- const beforeLoadContext = await ((_b = (_a = route.options).beforeLoad) == null ? void 0 : _b.call(_a, {
622
- search: match.search,
623
- abortController,
624
- params: match.params,
625
- preload: !!preload,
626
- context: parentContext,
627
- location,
628
- navigate: (opts) => this.navigate({ ...opts, from: match.pathname }),
629
- buildLocation: this.buildLocation,
630
- cause: preload ? "preload" : match.cause
631
- })) ?? {};
632
- if (isRedirect(beforeLoadContext) || isNotFound(beforeLoadContext)) {
633
- handleSerialError(beforeLoadContext, "BEFORE_LOAD");
634
- }
635
- const context = {
636
- ...parentContext,
637
- ...beforeLoadContext
638
- };
639
- matches[index] = match = {
640
- ...match,
641
- routeContext: replaceEqualDeep(match.routeContext, beforeLoadContext),
642
- context: replaceEqualDeep(match.context, context),
643
- abortController,
644
- pendingPromise
645
- };
646
- } catch (err) {
647
- handleSerialError(err, "BEFORE_LOAD");
648
- break;
649
- }
650
- }
651
- const validResolvedMatches = matches.slice(0, firstBadMatchIndex);
652
- const matchPromises = [];
653
- validResolvedMatches.forEach((match, index) => {
654
- matchPromises.push(
655
- new Promise(async (resolve, reject) => {
656
- var _a2;
657
- const parentMatchPromise = matchPromises[index - 1];
658
- const route = this.looseRoutesById[match.routeId];
659
- const handleError = (err) => {
660
- if (isRedirect(err) || isNotFound(err)) {
661
- handleMatchSpecialError(match, err);
662
- }
663
- };
664
- let loadPromise;
665
- matches[index] = match = {
666
- ...match,
667
- showPending: false
668
- };
669
- let didShowPending = false;
670
- const pendingMs = route.options.pendingMs ?? this.options.defaultPendingMs;
671
- const pendingMinMs = route.options.pendingMinMs ?? this.options.defaultPendingMinMs;
672
- const loaderContext = {
673
- params: match.params,
674
- deps: match.loaderDeps,
675
- preload: !!preload,
676
- parentMatchPromise,
677
- abortController: match.abortController,
678
- context: match.context,
679
- location,
680
- navigate: (opts) => this.navigate({ ...opts, from: match.pathname }),
681
- cause: preload ? "preload" : match.cause,
682
- route
683
- };
684
- const fetch = async () => {
685
- var _a3, _b2, _c, _d, _e, _f, _g, _h, _i, _j;
686
- try {
687
- if (match.isFetching) {
688
- loadPromise = (_a3 = getRouteMatch(this.state, match.id)) == null ? void 0 : _a3.loadPromise;
689
- } else {
690
- matches[index] = match = {
691
- ...match,
692
- isFetching: true,
693
- fetchCount: match.fetchCount + 1
694
- };
695
- const lazyPromise = ((_b2 = route.lazyFn) == null ? void 0 : _b2.call(route).then((lazyRoute) => {
696
- Object.assign(route.options, lazyRoute.options);
697
- })) || Promise.resolve();
698
- const componentsPromise = lazyPromise.then(
699
- () => Promise.all(
700
- componentTypes.map(async (type) => {
701
- const component = route.options[type];
702
- if (component == null ? void 0 : component.preload) {
703
- await component.preload();
704
- }
705
- })
706
- )
707
- );
708
- const loaderPromise = (_d = (_c = route.options).loader) == null ? void 0 : _d.call(_c, loaderContext);
709
- loadPromise = Promise.all([
710
- componentsPromise,
711
- loaderPromise,
712
- lazyPromise
713
- ]).then((d) => d[1]);
714
- }
715
- matches[index] = match = {
716
- ...match,
717
- loadPromise
718
- };
719
- updateMatch(match);
720
- const loaderData = await loadPromise;
721
- if (latestPromise = checkLatest())
722
- return await latestPromise;
723
- handleError(loaderData);
724
- if (didShowPending && pendingMinMs) {
725
- await new Promise((r) => setTimeout(r, pendingMinMs));
726
- }
727
- if (latestPromise = checkLatest())
728
- return await latestPromise;
729
- const [meta, headers] = await Promise.all([
730
- (_f = (_e = route.options).meta) == null ? void 0 : _f.call(_e, {
731
- params: match.params,
732
- loaderData
733
- }),
734
- (_h = (_g = route.options).headers) == null ? void 0 : _h.call(_g, {
735
- loaderData
736
- })
737
- ]);
738
- matches[index] = match = {
739
- ...match,
740
- error: void 0,
741
- status: "success",
742
- isFetching: false,
743
- updatedAt: Date.now(),
744
- loaderData,
745
- loadPromise: void 0,
746
- meta,
747
- headers
748
- };
749
- } catch (error) {
750
- if (latestPromise = checkLatest())
751
- return await latestPromise;
752
- handleError(error);
753
- try {
754
- (_j = (_i = route.options).onError) == null ? void 0 : _j.call(_i, error);
755
- } catch (onErrorError) {
756
- error = onErrorError;
757
- handleError(onErrorError);
758
- }
759
- matches[index] = match = {
760
- ...match,
761
- error,
762
- status: "error",
763
- isFetching: false
764
- };
765
- }
766
- updateMatch(match);
767
- };
768
- const age = Date.now() - match.updatedAt;
769
- let staleAge = preload ? route.options.preloadStaleTime ?? this.options.defaultPreloadStaleTime ?? 3e4 : route.options.staleTime ?? this.options.defaultStaleTime ?? 0;
770
- let shouldReload;
771
- const shouldReloadOption = route.options.shouldReload;
772
- shouldReload = typeof shouldReloadOption === "function" ? shouldReloadOption(loaderContext) : shouldReloadOption;
773
- matches[index] = match = {
774
- ...match,
775
- preload: !!preload && !this.state.matches.find((d) => d.id === match.id)
776
- };
777
- if (match.status === "success" && (match.invalid || (shouldReload ?? age > staleAge))) {
778
- (async () => {
779
- try {
780
- await fetch();
781
- } catch (err) {
782
- console.info("Background Fetching Error", err);
783
- if (isRedirect(err)) {
784
- (this.state.pendingMatches || this.state.matches).find((d) => d.id === match.id);
785
- handleError(err);
786
- invariant(
787
- false,
788
- "You need to redirect from a background fetch? This is not supported yet. File an issue."
789
- );
790
- }
791
- }
792
- })();
793
- return resolve();
794
- }
795
- const shouldPending = !preload && typeof pendingMs === "number" && (route.options.pendingComponent ?? this.options.defaultPendingComponent);
796
- if (match.status !== "success") {
797
- try {
798
- if (shouldPending) {
799
- (_a2 = match.pendingPromise) == null ? void 0 : _a2.then(async () => {
800
- if (latestPromise = checkLatest())
801
- return latestPromise;
802
- didShowPending = true;
803
- matches[index] = match = {
804
- ...match,
805
- showPending: true
806
- };
807
- updateMatch(match);
808
- resolve();
809
- });
810
- }
811
- await fetch();
812
- } catch (err) {
813
- reject(err);
814
- }
815
- }
816
- resolve();
817
- })
818
- );
819
- });
820
- await Promise.all(matchPromises);
821
- return matches;
822
- };
823
- this.invalidate = () => {
824
- const invalidate = (d) => ({
825
- ...d,
826
- invalid: true
827
- });
828
- this.__store.setState((s) => {
829
- var _a;
830
- return {
831
- ...s,
832
- matches: s.matches.map(invalidate),
833
- cachedMatches: s.cachedMatches.map(invalidate),
834
- pendingMatches: (_a = s.pendingMatches) == null ? void 0 : _a.map(invalidate)
835
- };
836
- });
837
- this.load();
838
- };
839
- this.load = async () => {
840
- const promise = new Promise(async (resolve, reject) => {
841
- const next = this.latestLocation;
842
- const prevLocation = this.state.resolvedLocation;
843
- const pathDidChange = prevLocation.href !== next.href;
844
- let latestPromise;
845
- this.cancelMatches();
846
- this.emit({
847
- type: "onBeforeLoad",
848
- fromLocation: prevLocation,
849
- toLocation: next,
850
- pathChanged: pathDidChange
851
- });
852
- let pendingMatches;
853
- const previousMatches = this.state.matches;
854
- this.__store.batch(() => {
855
- this.cleanCache();
856
- pendingMatches = this.matchRoutes(next.pathname, next.search, {
857
- debug: true
858
- });
859
- this.__store.setState((s) => ({
860
- ...s,
861
- isLoading: true,
862
- location: next,
863
- pendingMatches,
864
- cachedMatches: s.cachedMatches.filter((d) => {
865
- return !pendingMatches.find((e) => e.id === d.id);
866
- })
867
- }));
868
- });
869
- try {
870
- let redirect;
871
- let notFound;
872
- try {
873
- await this.loadMatches({
874
- matches: pendingMatches,
875
- location: next,
876
- checkLatest: () => this.checkLatest(promise)
877
- });
878
- } catch (err) {
879
- if (isRedirect(err)) {
880
- redirect = this.resolveRedirect(err);
881
- if (!isServer) {
882
- this.navigate({ ...redirect, replace: true });
883
- }
884
- } else if (isNotFound(err)) {
885
- notFound = err;
886
- this.handleNotFound(pendingMatches, err);
887
- }
888
- }
889
- if (latestPromise = this.checkLatest(promise)) {
890
- return latestPromise;
891
- }
892
- const exitingMatches = previousMatches.filter(
893
- (match) => !pendingMatches.find((d) => d.id === match.id)
894
- );
895
- const enteringMatches = pendingMatches.filter(
896
- (match) => !previousMatches.find((d) => d.id === match.id)
897
- );
898
- const stayingMatches = previousMatches.filter(
899
- (match) => pendingMatches.find((d) => d.id === match.id)
900
- );
901
- this.__store.batch(() => {
902
- this.__store.setState((s) => ({
903
- ...s,
904
- isLoading: false,
905
- matches: s.pendingMatches,
906
- pendingMatches: void 0,
907
- cachedMatches: [
908
- ...s.cachedMatches,
909
- ...exitingMatches.filter((d) => d.status !== "error")
910
- ],
911
- statusCode: (redirect == null ? void 0 : redirect.statusCode) || notFound ? 404 : s.matches.some((d) => d.status === "error") ? 500 : 200,
912
- redirect
913
- }));
914
- this.cleanCache();
915
- });
916
- [
917
- [exitingMatches, "onLeave"],
918
- [enteringMatches, "onEnter"],
919
- [stayingMatches, "onStay"]
920
- ].forEach(([matches, hook]) => {
921
- matches.forEach((match) => {
922
- var _a, _b;
923
- (_b = (_a = this.looseRoutesById[match.routeId].options)[hook]) == null ? void 0 : _b.call(_a, match);
924
- });
925
- });
926
- this.emit({
927
- type: "onLoad",
928
- fromLocation: prevLocation,
929
- toLocation: next,
930
- pathChanged: pathDidChange
931
- });
932
- resolve();
933
- } catch (err) {
934
- if (latestPromise = this.checkLatest(promise)) {
935
- return latestPromise;
936
- }
937
- console.log("Load Error", err);
938
- reject(err);
939
- }
940
- });
941
- this.latestLoadPromise = promise;
942
- return this.latestLoadPromise;
943
- };
944
- this.resolveRedirect = (err) => {
945
- let redirect = err;
946
- if (!redirect.href) {
947
- redirect.href = this.buildLocation(redirect).href;
948
- }
949
- return redirect;
950
- };
951
- this.cleanCache = () => {
952
- this.__store.setState((s) => {
953
- return {
954
- ...s,
955
- cachedMatches: s.cachedMatches.filter((d) => {
956
- const route = this.looseRoutesById[d.routeId];
957
- if (!route.options.loader) {
958
- return false;
959
- }
960
- const gcTime = (d.preload ? route.options.preloadGcTime ?? this.options.defaultPreloadGcTime : route.options.gcTime ?? this.options.defaultGcTime) ?? 5 * 60 * 1e3;
961
- return d.status !== "error" && Date.now() - d.updatedAt < gcTime;
962
- })
963
- };
964
- });
965
- };
966
- this.preloadRoute = async (opts) => {
967
- var _a;
968
- let next = this.buildLocation(opts);
969
- let matches = this.matchRoutes(next.pathname, next.search, {
970
- throwOnError: true,
971
- preload: true
972
- });
973
- const loadedMatchIds = Object.fromEntries(
974
- (_a = [
975
- ...this.state.matches,
976
- ...this.state.pendingMatches ?? [],
977
- ...this.state.cachedMatches
978
- ]) == null ? void 0 : _a.map((d) => [d.id, true])
979
- );
980
- this.__store.batch(() => {
981
- matches.forEach((match) => {
982
- if (!loadedMatchIds[match.id]) {
983
- this.__store.setState((s) => ({
984
- ...s,
985
- cachedMatches: [...s.cachedMatches, match]
986
- }));
987
- }
988
- });
989
- });
990
- try {
991
- matches = await this.loadMatches({
992
- matches,
993
- location: next,
994
- preload: true,
995
- checkLatest: () => void 0
996
- });
997
- return matches;
998
- } catch (err) {
999
- if (isRedirect(err)) {
1000
- return await this.preloadRoute(err);
1001
- }
1002
- console.error(err);
1003
- return void 0;
1004
- }
1005
- };
1006
- this.matchRoute = (location, opts) => {
1007
- const matchLocation = {
1008
- ...location,
1009
- to: location.to ? this.resolvePathWithBase(location.from || "", location.to) : void 0,
1010
- params: location.params || {},
1011
- leaveParams: true
1012
- };
1013
- const next = this.buildLocation(matchLocation);
1014
- if ((opts == null ? void 0 : opts.pending) && this.state.status !== "pending") {
1015
- return false;
1016
- }
1017
- const baseLocation = (opts == null ? void 0 : opts.pending) ? this.latestLocation : this.state.resolvedLocation;
1018
- if (!baseLocation) {
1019
- return false;
1020
- }
1021
- const match = matchPathname(this.basepath, baseLocation.pathname, {
1022
- ...opts,
1023
- to: next.pathname
1024
- });
1025
- if (!match) {
1026
- return false;
1027
- }
1028
- if (location.params) {
1029
- if (!deepEqual(match, location.params, true)) {
1030
- return false;
1031
- }
1032
- }
1033
- if (match && ((opts == null ? void 0 : opts.includeSearch) ?? true)) {
1034
- return deepEqual(baseLocation.search, next.search, true) ? match : false;
1035
- }
1036
- return match;
1037
- };
1038
- this.injectHtml = async (html) => {
1039
- this.injectedHtml.push(html);
1040
- };
1041
- this.registeredDeferredsIds = /* @__PURE__ */ new Map();
1042
- this.registeredDeferreds = /* @__PURE__ */ new WeakMap();
1043
- this.getDeferred = (uid) => {
1044
- const token = this.registeredDeferredsIds.get(uid);
1045
- if (!token) {
1046
- return void 0;
1047
- }
1048
- return this.registeredDeferreds.get(token);
1049
- };
1050
- this.dehydrateData = (key, getData) => {
1051
- warning(
1052
- false,
1053
- `The dehydrateData method is deprecated. Please use the injectHtml method to inject your own data.`
1054
- );
1055
- if (typeof document === "undefined") {
1056
- const strKey = typeof key === "string" ? key : JSON.stringify(key);
1057
- this.injectHtml(async () => {
1058
- const id = `__TSR_DEHYDRATED__${strKey}`;
1059
- const data = typeof getData === "function" ? await getData() : getData;
1060
- return `<script id='${id}' suppressHydrationWarning>
1061
- window["__TSR_DEHYDRATED__${escapeJSON(
1062
- strKey
1063
- )}"] = ${JSON.stringify(this.options.transformer.stringify(data))}
1064
- <\/script>`;
1065
- });
1066
- return () => this.hydrateData(key);
1067
- }
1068
- return () => void 0;
1069
- };
1070
- this.hydrateData = (key) => {
1071
- warning(
1072
- false,
1073
- `The hydrateData method is deprecated. Please use the extractHtml method to extract your own data.`
1074
- );
1075
- if (typeof document !== "undefined") {
1076
- const strKey = typeof key === "string" ? key : JSON.stringify(key);
1077
- return this.options.transformer.parse(
1078
- window[`__TSR_DEHYDRATED__${strKey}`]
1079
- );
1080
- }
1081
- return void 0;
1082
- };
1083
- this.dehydrate = () => {
1084
- var _a;
1085
- const pickError = ((_a = this.options.errorSerializer) == null ? void 0 : _a.serialize) ?? defaultSerializeError;
1086
- return {
1087
- state: {
1088
- dehydratedMatches: this.state.matches.map((d) => ({
1089
- ...pick(d, ["id", "status", "updatedAt", "loaderData"]),
1090
- // If an error occurs server-side during SSRing,
1091
- // send a small subset of the error to the client
1092
- error: d.error ? {
1093
- data: pickError(d.error),
1094
- __isServerError: true
1095
- } : void 0
1096
- }))
1097
- }
1098
- };
1099
- };
1100
- this.hydrate = async (__do_not_use_server_ctx) => {
1101
- var _a, _b, _c;
1102
- let _ctx = __do_not_use_server_ctx;
1103
- if (typeof document !== "undefined") {
1104
- _ctx = (_a = window.__TSR_DEHYDRATED__) == null ? void 0 : _a.data;
1105
- }
1106
- invariant(
1107
- _ctx,
1108
- "Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?"
1109
- );
1110
- const ctx = this.options.transformer.parse(_ctx);
1111
- this.dehydratedData = ctx.payload;
1112
- (_c = (_b = this.options).hydrate) == null ? void 0 : _c.call(_b, ctx.payload);
1113
- const dehydratedState = ctx.router.state;
1114
- let matches = this.matchRoutes(
1115
- this.state.location.pathname,
1116
- this.state.location.search
1117
- ).map((match) => {
1118
- var _a2, _b2, _c2, _d, _e, _f;
1119
- const dehydratedMatch = dehydratedState.dehydratedMatches.find(
1120
- (d) => d.id === match.id
1121
- );
1122
- invariant(
1123
- dehydratedMatch,
1124
- `Could not find a client-side match for dehydrated match with id: ${match.id}!`
1125
- );
1126
- if (dehydratedMatch) {
1127
- const route = this.looseRoutesById[match.routeId];
1128
- const assets = dehydratedMatch.status === "notFound" || dehydratedMatch.status === "redirected" ? {} : {
1129
- meta: (_b2 = (_a2 = route.options).meta) == null ? void 0 : _b2.call(_a2, {
1130
- params: match.params,
1131
- loaderData: dehydratedMatch.loaderData
1132
- }),
1133
- links: (_d = (_c2 = route.options).links) == null ? void 0 : _d.call(_c2),
1134
- scripts: (_f = (_e = route.options).scripts) == null ? void 0 : _f.call(_e)
1135
- };
1136
- return {
1137
- ...match,
1138
- ...dehydratedMatch,
1139
- ...assets
1140
- };
1141
- }
1142
- return match;
1143
- });
1144
- this.__store.setState((s) => {
1145
- return {
1146
- ...s,
1147
- matches,
1148
- lastUpdated: Date.now()
1149
- };
1150
- });
1151
- };
1152
- this.handleNotFound = (matches, err) => {
1153
- const matchesByRouteId = Object.fromEntries(
1154
- matches.map((match2) => [match2.routeId, match2])
1155
- );
1156
- let routeCursor = (err.global ? this.looseRoutesById[rootRouteId] : this.looseRoutesById[err.routeId]) || this.looseRoutesById[rootRouteId];
1157
- while (!routeCursor.options.notFoundComponent && !this.options.defaultNotFoundComponent && routeCursor.id !== rootRouteId) {
1158
- routeCursor = routeCursor == null ? void 0 : routeCursor.parentRoute;
1159
- invariant(
1160
- routeCursor,
1161
- "Found invalid route tree while trying to find not-found handler."
1162
- );
1163
- }
1164
- let match = matchesByRouteId[routeCursor.id];
1165
- invariant(match, "Could not find match for route: " + routeCursor.id);
1166
- Object.assign(match, {
1167
- status: "notFound",
1168
- error: err,
1169
- isFetching: false
1170
- });
1171
- };
1172
- this.hasNotFoundMatch = () => {
1173
- return this.__store.state.matches.some(
1174
- (d) => d.status === "notFound" || d.globalNotFound
1175
- );
1176
- };
1177
- this.update({
1178
- defaultPreloadDelay: 50,
1179
- defaultPendingMs: 1e3,
1180
- defaultPendingMinMs: 500,
1181
- context: void 0,
1182
- ...options,
1183
- stringifySearch: (options == null ? void 0 : options.stringifySearch) ?? defaultStringifySearch,
1184
- parseSearch: (options == null ? void 0 : options.parseSearch) ?? defaultParseSearch,
1185
- transformer: (options == null ? void 0 : options.transformer) ?? JSON
1186
- });
1187
- if (typeof document !== "undefined") {
1188
- window.__TSR__ROUTER__ = this;
1189
- }
1190
- }
1191
- get state() {
1192
- return this.__store.state;
1193
- }
1194
- get looseRoutesById() {
1195
- return this.routesById;
8
+ super(options);
1196
9
  }
1197
- // resolveMatchPromise = (matchId: string, key: string, value: any) => {
1198
- // state.matches
1199
- // .find((d) => d.id === matchId)
1200
- // ?.__promisesByKey[key]?.resolve(value)
1201
- // }
1202
- }
1203
- function lazyFn(fn, key) {
1204
- return async (...args) => {
1205
- const imported = await fn();
1206
- return imported[key || "default"](...args);
1207
- };
1208
- }
1209
- class SearchParamError extends Error {
1210
- }
1211
- class PathParamError extends Error {
1212
- }
1213
- function getInitialRouterState(location) {
1214
- return {
1215
- isLoading: false,
1216
- isTransitioning: false,
1217
- status: "idle",
1218
- resolvedLocation: { ...location },
1219
- location,
1220
- matches: [],
1221
- pendingMatches: [],
1222
- cachedMatches: [],
1223
- lastUpdated: 0,
1224
- statusCode: 200
1225
- };
1226
10
  }
1227
- function defaultSerializeError(err) {
1228
- if (err instanceof Error)
1229
- return {
1230
- name: err.name,
1231
- message: err.message
1232
- };
1233
- return {
1234
- data: err
1235
- };
11
+ if (typeof globalThis !== "undefined") {
12
+ globalThis.createFileRoute = createFileRoute;
13
+ globalThis.createLazyFileRoute = createLazyFileRoute;
14
+ } else if (typeof window !== "undefined") {
15
+ window.createFileRoute = createFileRoute;
16
+ window.createFileRoute = createLazyFileRoute;
1236
17
  }
1237
18
  export {
1238
- PathParamError,
1239
19
  Router,
1240
- SearchParamError,
1241
- componentTypes,
1242
- createRouter,
1243
- defaultSerializeError,
1244
- getInitialRouterState,
1245
- lazyFn
20
+ createRouter
1246
21
  };
1247
22
  //# sourceMappingURL=router.js.map